Skip to content

Commit f83b48e

Browse files
intel352claude
andcommitted
fix: replace MaxBytesReader(nil) with io.LimitReader to avoid nil ResponseWriter panic
http.MaxBytesReader panics when the ResponseWriter is nil and the body exceeds the limit. Switched to io.LimitReader (reads maxBytes+1 to detect overflow) and io.ReadAll, eliminating the nil-writer dependency entirely. Replaced the string-comparison EOF check with errors.Is(err, io.EOF). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent c92c9cb commit f83b48e

1 file changed

Lines changed: 11 additions & 20 deletions

File tree

internal/module_webhook.go

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ import (
66
"crypto/sha256"
77
"encoding/hex"
88
"encoding/json"
9+
"errors"
910
"fmt"
11+
"io"
1012
"net/http"
1113
"strings"
1214
"time"
@@ -306,27 +308,16 @@ func normalizeGenericEvent(event *GitEvent, payload map[string]any) {
306308
}
307309

308310
// readLimitedBody reads up to maxBytes from the request body.
311+
// It uses io.LimitReader to cap reads safely without requiring a ResponseWriter.
312+
// If the body is exactly maxBytes, an extra byte is attempted to detect overflow.
309313
func readLimitedBody(r *http.Request, maxBytes int64) ([]byte, error) {
310-
r.Body = http.MaxBytesReader(nil, r.Body, maxBytes)
311-
buf := make([]byte, 0, 4096)
312-
tmp := make([]byte, 4096)
313-
var total int64
314-
for {
315-
n, err := r.Body.Read(tmp)
316-
if n > 0 {
317-
total += int64(n)
318-
if total > maxBytes {
319-
return nil, fmt.Errorf("request body exceeds %d bytes", maxBytes)
320-
}
321-
buf = append(buf, tmp[:n]...)
322-
}
323-
if err != nil {
324-
if err.Error() == "EOF" || err.Error() == "http: request body too large" {
325-
break
326-
}
327-
// io.EOF is expected at end of body
328-
break
329-
}
314+
lr := io.LimitReader(r.Body, maxBytes+1)
315+
buf, err := io.ReadAll(lr)
316+
if err != nil && !errors.Is(err, io.EOF) {
317+
return nil, fmt.Errorf("failed to read request body: %w", err)
318+
}
319+
if int64(len(buf)) > maxBytes {
320+
return nil, fmt.Errorf("request body exceeds %d bytes", maxBytes)
330321
}
331322
return buf, nil
332323
}

0 commit comments

Comments
 (0)