Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions server/plugin/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"crypto/sha1" //nolint:gosec // GitHub webhooks are signed using sha1 https://developer.github.com/webhooks/.
"encoding/hex"
"encoding/json"
"errors"
"html"
"io"
"net/http"
Expand Down Expand Up @@ -199,11 +200,20 @@ func (wb *WebhookBroker) Close() {
}
}

const maxWebhookPayloadSize = 25 * 1024 * 1024 // 25 MB, matching GitHub's documented maximum

func (p *Plugin) handleWebhook(w http.ResponseWriter, r *http.Request) {
p.client.Log.Info("Webhook event received")
config := p.getConfiguration()

r.Body = http.MaxBytesReader(w, r.Body, maxWebhookPayloadSize)
body, err := io.ReadAll(r.Body)
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
http.Error(w, "Request body too large", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "Bad request body", http.StatusBadRequest)
return
}
Expand Down
46 changes: 46 additions & 0 deletions server/plugin/webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,52 @@ const (
gitHubOrginization = "test-org"
)

func TestHandleWebhookBodySizeLimit(t *testing.T) {
t.Run("rejects oversized request body", func(t *testing.T) {
_, mockAPI, _, _, _ := GetTestSetup(t)
p := NewPlugin()
p.initializeAPI()
p.SetAPI(mockAPI)
p.client = pluginapi.NewClient(mockAPI, p.Driver)
p.setConfiguration(&Configuration{
WebhookSecret: webhookSecret,
})

mockAPI.On("LogInfo", "Webhook event received")

oversizedBody := strings.NewReader(strings.Repeat("x", 26*1024*1024))
req := httptest.NewRequest(http.MethodPost, "/webhook", oversizedBody)
req.Header.Set("X-Hub-Signature", "sha1=invalid")
w := httptest.NewRecorder()

p.handleWebhook(w, req)

assert.Equal(t, http.StatusRequestEntityTooLarge, w.Code)
})

t.Run("accepts normal sized request body", func(t *testing.T) {
_, mockAPI, _, _, _ := GetTestSetup(t)
p := NewPlugin()
p.initializeAPI()
p.SetAPI(mockAPI)
p.client = pluginapi.NewClient(mockAPI, p.Driver)
p.setConfiguration(&Configuration{
WebhookSecret: webhookSecret,
})

mockAPI.On("LogInfo", "Webhook event received")

body := `{"zen": "test"}`
req := httptest.NewRequest(http.MethodPost, "/webhook", strings.NewReader(body))
req.Header.Set("X-Hub-Signature", "sha1=invalid")
w := httptest.NewRecorder()

p.handleWebhook(w, req)

assert.Equal(t, http.StatusUnauthorized, w.Code)
})
}

func TestPostPushEvent(t *testing.T) {
tests := []struct {
name string
Expand Down
Loading