Skip to content

Commit 9dd19e6

Browse files
authored
github hardening (#383)
* github hardening * x * x
1 parent 220836c commit 9dd19e6

4 files changed

Lines changed: 119 additions & 36 deletions

File tree

‎githubbot/githubbot/handler.go‎

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,33 @@ type Handler struct {
3030

3131
var _ base.Handler = (*Handler)(nil)
3232

33+
const (
34+
subscribeFailedMsg = "I couldn't subscribe to updates on `%s`! Make sure the repository exists, you have access to it, and the Keybase integration is installed on it.\n\ngithub.com/apps/%s/installations/new"
35+
)
36+
37+
// checkUserRepoAccess asks GitHub, with the user's own token, whether the user
38+
// can see repo. A missing repo and a forbidden one both return false.
39+
func checkUserRepoAccess(ctx context.Context, userClient *github.Client, repo string) (bool, error) {
40+
parsedRepo := strings.Split(repo, "/")
41+
if len(parsedRepo) != 2 {
42+
return false, fmt.Errorf("invalid repo: %s", repo)
43+
}
44+
got, res, err := userClient.Repositories.Get(ctx, parsedRepo[0], parsedRepo[1])
45+
if err != nil {
46+
if res != nil && (res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusForbidden) {
47+
return false, nil
48+
}
49+
return false, err
50+
}
51+
return repoFullNameMatches(got, repo), nil
52+
}
53+
54+
// repoFullNameMatches reports whether r is the repo named by repo, ignoring case.
55+
func repoFullNameMatches(r *github.Repository, repo string) bool {
56+
full := r.GetFullName()
57+
return full != "" && strings.EqualFold(full, repo)
58+
}
59+
3360
func NewHandler(stats *base.StatsRegistry, kbc *kbchat.API, debugConfig *base.ChatDebugOutputConfig, db *DB, oauthConfig *oauth2.Config, atr *ghinstallation.AppsTransport, httpPrefix, appName string) *Handler {
3461
return &Handler{
3562
DebugOutput: base.NewDebugOutput("Handler", debugConfig),
@@ -240,16 +267,6 @@ func (h *Handler) handleNewSubscription(ctx context.Context, repo string, msg ch
240267
h.ChatEcho(msg.ConvID, "`%s` doesn't look like a repository to me! Try sending `!github subscribe <owner/repo>`", repo)
241268
return false, nil
242269
}
243-
repoInstallation, res, err := client.Apps.GetRepositoryInstallation(context.TODO(), parsedRepo[0], parsedRepo[1])
244-
if err != nil {
245-
switch res.StatusCode {
246-
case http.StatusNotFound:
247-
h.ChatEcho(msg.ConvID, "I couldn't subscribe to updates on `%s`! Make sure the Keybase integration is installed on your repository, and that the repository exists.\n\ngithub.com/apps/%s/installations/new", repo, h.appName)
248-
return false, nil
249-
default:
250-
return false, fmt.Errorf("error getting installation: %s", err)
251-
}
252-
}
253270

254271
// check that user has authorization
255272
tc, err := base.GetOAuthClient(ctx, msg.Sender.Username, msg, h.kbc, h.oauthConfig, h.db,
@@ -263,23 +280,26 @@ func (h *Handler) handleNewSubscription(ctx context.Context, repo string, msg ch
263280
if err != nil {
264281
return false, fmt.Errorf("error creating github client: %s", err)
265282
}
266-
installations, _, err := userClient.Apps.ListUserInstallations(context.TODO(), nil)
283+
284+
// Check the user's access before touching the app's credentials. A repo that
285+
// doesn't exist and one the user can't see get the same reply, so this
286+
// doesn't reveal which repos exist.
287+
hasAccess, err := checkUserRepoAccess(ctx, userClient, repo)
267288
if err != nil {
268-
return false, fmt.Errorf("Error getting installations for current user: %s", err)
289+
return false, fmt.Errorf("error checking repository access: %s", err)
269290
}
270-
271-
// search through all user installations to see if they have permission to access the repo's installation
272-
hasPermission := false
273-
for _, i := range installations {
274-
if i.GetID() == repoInstallation.GetID() {
275-
hasPermission = true
276-
break
277-
}
291+
if !hasAccess {
292+
h.ChatEcho(msg.ConvID, subscribeFailedMsg, repo, h.appName)
293+
return false, nil
278294
}
279295

280-
if !hasPermission {
281-
h.ChatEcho(msg.ConvID, "You don't have permission to subscribe to `%s`.", repo)
282-
return false, fmt.Errorf("unauthorized for subscription")
296+
repoInstallation, res, err := client.Apps.GetRepositoryInstallation(ctx, parsedRepo[0], parsedRepo[1])
297+
if err != nil {
298+
if res != nil && res.StatusCode == http.StatusNotFound {
299+
h.ChatEcho(msg.ConvID, subscribeFailedMsg, repo, h.appName)
300+
return false, nil
301+
}
302+
return false, fmt.Errorf("error getting installation: %s", err)
283303
}
284304

285305
// auth checked, now we create the subscription

‎githubbot/githubbot/http.go‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package githubbot
22

33
import (
44
"context"
5+
"errors"
56
"fmt"
67
"net/http"
78
"strings"
@@ -49,9 +50,26 @@ func (h *HTTPSrv) handleHealthCheck(w http.ResponseWriter, _ *http.Request) {
4950
}
5051
}
5152

52-
func (h *HTTPSrv) handleWebhook(_ http.ResponseWriter, r *http.Request) {
53-
payload, err := github.ValidatePayload(r, []byte(h.secret))
53+
// maxWebhookBodyBytes is GitHub's own maximum webhook payload size.
54+
const maxWebhookBodyBytes = 25 * 1024 * 1024
55+
56+
// validateWebhook reads and authenticates a webhook body. The read is capped
57+
// so an oversized body fails with *http.MaxBytesError instead of being buffered.
58+
func validateWebhook(w http.ResponseWriter, r *http.Request, secret string) ([]byte, error) {
59+
base.LimitRequestBody(w, r, maxWebhookBodyBytes)
60+
return github.ValidatePayload(r, []byte(secret))
61+
}
62+
63+
func (h *HTTPSrv) handleWebhook(w http.ResponseWriter, r *http.Request) {
64+
payload, err := validateWebhook(w, r, h.secret)
5465
if err != nil {
66+
var tooLarge *http.MaxBytesError
67+
if errors.As(err, &tooLarge) {
68+
h.Debug("webhook payload too large (%s)", r.Header.Get("X-GitHub-Delivery"))
69+
h.Stats.Count("webhook - payload too large")
70+
w.WriteHeader(http.StatusRequestEntityTooLarge)
71+
return
72+
}
5573
h.Debug("Error validating payload (%s): %v\n", r.Header.Get("X-GitHub-Delivery"), err)
5674
h.Stats.Count("webhook - invalid payload")
5775
return
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package githubbot
2+
3+
import (
4+
"bytes"
5+
"crypto/hmac"
6+
"crypto/sha256"
7+
"encoding/hex"
8+
"net/http"
9+
"net/http/httptest"
10+
"testing"
11+
12+
"github.com/google/go-github/v89/github"
13+
"github.com/stretchr/testify/require"
14+
)
15+
16+
func TestRepoFullNameMatches(t *testing.T) {
17+
repo := &github.Repository{FullName: github.Ptr("Keybase/Managed-Bots")}
18+
require.Equal(t, true, repoFullNameMatches(repo, "keybase/managed-bots"), "expected case-insensitive match")
19+
require.Equal(t, false, repoFullNameMatches(repo, "keybase/other"), "expected mismatch for a different repo")
20+
require.Equal(t, false, repoFullNameMatches(&github.Repository{}, ""), "empty full name must not match an empty repo")
21+
require.Equal(t, false, repoFullNameMatches(nil, "keybase/managed-bots"), "nil repository must not match")
22+
}
23+
24+
func TestValidateWebhookLimitsBody(t *testing.T) {
25+
const secret = "s3cret"
26+
body := []byte(`{"zen":"ok"}`)
27+
mac := hmac.New(sha256.New, []byte(secret))
28+
mac.Write(body)
29+
sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))
30+
31+
newReq := func(body []byte) *http.Request {
32+
req := httptest.NewRequest(http.MethodPost, "/githubbot/webhook", bytes.NewReader(body))
33+
req.Header.Set("Content-Type", "application/json")
34+
req.Header.Set("X-Hub-Signature-256", sig)
35+
return req
36+
}
37+
38+
payload, err := validateWebhook(httptest.NewRecorder(), newReq(body), secret)
39+
require.NoError(t, err, "valid small payload rejected")
40+
require.Equal(t, body, payload)
41+
42+
big := make([]byte, maxWebhookBodyBytes+1)
43+
_, err = validateWebhook(httptest.NewRecorder(), newReq(big), secret)
44+
var tooLarge *http.MaxBytesError
45+
require.ErrorAs(t, err, &tooLarge, "expected MaxBytesError for oversized body")
46+
}

‎triviabot/triviabot/handler_test.go‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66

77
"github.com/keybase/go-keybase-chat-bot/kbchat/types/chat1"
88
"github.com/keybase/managed-bots/base"
9+
"github.com/stretchr/testify/require"
910
)
1011

1112
func newTestHandler() *Handler {
@@ -31,14 +32,14 @@ func TestHandleAnswerNeverBlocks(t *testing.T) {
3132
"user")
3233
}
3334
}()
35+
finished := false
3436
select {
3537
case <-done:
38+
finished = true
3639
case <-time.After(5 * time.Second):
37-
t.Fatal("handleAnswer blocked on a full answer queue")
38-
}
39-
if len(s.answerCh) != cap(s.answerCh) {
40-
t.Fatalf("expected queue to fill to %d, got %d", cap(s.answerCh), len(s.answerCh))
4140
}
41+
require.Equal(t, true, finished, "handleAnswer blocked on a full answer queue")
42+
require.Equal(t, cap(s.answerCh), len(s.answerCh), "expected queue to fill to capacity")
4243
}
4344

4445
func TestRemoveSessionOnlyRemovesSameSession(t *testing.T) {
@@ -48,16 +49,14 @@ func TestRemoveSessionOnlyRemovesSameSession(t *testing.T) {
4849
h.sessions[convID] = old
4950

5051
// A newer session replaced the old one; removing the old one must not
51-
// touch it.
52+
// touch it. Require Same rather than Equal: the two sessions are built
53+
// identically, so they could compare deeply equal.
5254
current := newSession(nil, nil, nil, convID)
5355
h.sessions[convID] = current
5456
h.removeSession(convID, old)
55-
if h.sessions[convID] != current {
56-
t.Fatal("removeSession dropped a session it did not own")
57-
}
57+
require.Same(t, current, h.sessions[convID], "removeSession dropped a session it did not own")
5858

5959
h.removeSession(convID, current)
60-
if _, ok := h.sessions[convID]; ok {
61-
t.Fatal("removeSession did not remove the finished session")
62-
}
60+
_, ok := h.sessions[convID]
61+
require.Equal(t, false, ok, "removeSession did not remove the finished session")
6362
}

0 commit comments

Comments
 (0)