Limit API request body size (#4757)
Bound the size of HTTP request bodies on the main API listener so large messages cannot exhaust memory. Configurable via limit.max_api_request_body_size (defaults to 10 MiB, 0 disables). Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
cc6551d617
commit
f72254ba6b
+36
-2
@@ -44,8 +44,9 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrGzipReadFailed = errors.New("cannot read decompressed data")
|
||||
ErrGzipTooLarge = errors.New("decompressed data too large")
|
||||
ErrGzipReadFailed = errors.New("cannot read decompressed data")
|
||||
ErrGzipTooLarge = errors.New("decompressed data too large")
|
||||
ErrRequestBodyTooLarge = errors.New("request body too large")
|
||||
)
|
||||
|
||||
var gzipReaderPool = sync.Pool{
|
||||
@@ -106,6 +107,39 @@ func RemoveDoubleSlashes(w http.ResponseWriter, r *http.Request, next http.Handl
|
||||
next(w, r)
|
||||
}
|
||||
|
||||
// RequestBodyLimiter bounds the size of an incoming HTTP request body so that
|
||||
// large messages cannot exhaust memory. The Twirp handlers decode the whole
|
||||
// body before any grant check runs, so the limit is applied here, up front.
|
||||
//
|
||||
// It does not decode the body itself: a request whose Content-Length exceeds
|
||||
// the limit is rejected with 413, and the body is wrapped with
|
||||
// http.MaxBytesReader so a missing or dishonest Content-Length is still caught
|
||||
// by the downstream decoder.
|
||||
type RequestBodyLimiter struct {
|
||||
maxBytes int64
|
||||
}
|
||||
|
||||
func NewRequestBodyLimiter(maxBytes int64) *RequestBodyLimiter {
|
||||
return &RequestBodyLimiter{maxBytes: maxBytes}
|
||||
}
|
||||
|
||||
func (l *RequestBodyLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
if l.maxBytes <= 0 || r.Body == nil {
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// reject early when the declared size already exceeds the limit
|
||||
if r.ContentLength > l.maxBytes {
|
||||
HandleError(w, r, http.StatusRequestEntityTooLarge, ErrRequestBodyTooLarge)
|
||||
return
|
||||
}
|
||||
|
||||
// bound the read in case Content-Length is missing or wrong
|
||||
r.Body = http.MaxBytesReader(w, r.Body, l.maxBytes)
|
||||
next(w, r)
|
||||
}
|
||||
|
||||
func IsValidDomain(domain string) bool {
|
||||
domainRegexp := regexp.MustCompile(`^(?i)[a-z0-9-]+(\.[a-z0-9-]+)+\.?$`)
|
||||
return domainRegexp.MatchString(domain)
|
||||
|
||||
Reference in New Issue
Block a user