requestbody: enforce max_size early using Content-Length (#8337)

* requestbody: reject oversized Content-Length before the next handler

When max_size is set and the request declares a Content-Length above it, respond 413 right away instead of letting the next handler start and fail mid-read. Bodies of unknown length are still limited by MaxBytesReader. Both paths return the same error, so handle_errors sees no difference.

* caddytest: send unknown-length bodies in max_size placeholder tests

request_body now answers 413 for a declared Content-Length over max_size before the placeholder reads the body, so these tests no longer covered the read path and the direct respond one failed.

* requestbody: keep the body limited for error routes

Error routes get the same request, so wrap the body before the early 413 to stop them from reading past max_size.
This commit is contained in:
Kévin Dunglas 2026-11-03 09:18:40 +01:00 • committed by GitHub
parent fc2236fe43
commit 6cdffe9502
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 122 additions and 11 deletions

View file

@ -77,11 +77,7 @@ func TestRequestBodyPlaceholderRespectsMaxSizeInTemplate(t *testing.T) {
}
`, "caddyfile")
req, err := http.NewRequest(http.MethodPost, "http://localhost:9080/", bytes.NewBufferString("abcdefghijklm"))
if err != nil {
t.Fatalf("creating request: %v", err)
}
res := tester.AssertResponseCode(req, http.StatusRequestEntityTooLarge)
res := tester.AssertResponseCode(newUnknownLengthPost(t, "abcdefghijklm"), http.StatusRequestEntityTooLarge)
res.Body.Close()
}
@ -109,11 +105,7 @@ func TestRequestBodyPlaceholderRespectsMaxSizeInVarsRegexp(t *testing.T) {
}
`, "caddyfile")
req, err := http.NewRequest(http.MethodPost, "http://localhost:9080/", bytes.NewBufferString("abcdefghijklmnopqrstuvwxyz"))
if err != nil {
t.Fatalf("creating request: %v", err)
}
res := tester.AssertResponseCode(req, http.StatusRequestEntityTooLarge)
res := tester.AssertResponseCode(newUnknownLengthPost(t, "abcdefghijklmnopqrstuvwxyz"), http.StatusRequestEntityTooLarge)
res.Body.Close()
}
@ -138,5 +130,43 @@ func TestRequestBodyPlaceholderDirectRespondExpansion(t *testing.T) {
// direct placeholder consumers expand the sanitized request-body limit
// marker to its text instead of failing the request with 413; only the
// templates and vars matchers propagate the 413 status
tester.AssertPostResponseBody("http://localhost:9080/", nil, bytes.NewBufferString("abcdefghijklm"), http.StatusOK, "request body: http: request body too large")
tester.AssertResponse(newUnknownLengthPost(t, "abcdefghijklm"), http.StatusOK, "request body: http: request body too large")
}
// newUnknownLengthPost sends no Content-Length, so the body gets past
// request_body's early check and max_size trips while handlers read it.
func newUnknownLengthPost(t *testing.T, body string) *http.Request {
t.Helper()
req, err := http.NewRequest(http.MethodPost, "http://localhost:9080/", bytes.NewBufferString(body))
if err != nil {
t.Fatalf("creating request: %v", err)
}
req.ContentLength = -1
return req
}
func TestRequestBodyMaxSizeLimitsErrorRoute(t *testing.T) {
tester := caddytest.NewTester(t)
tester.InitServer(`
{
skip_install_trust
admin localhost:2999
http_port 9080
https_port 9443
grace_period 1ns
}
http://localhost:9080 {
request_body {
max_size 10
}
respond "next handler reached"
handle_errors {
respond "{http.request.body}" {err.status_code}
}
}
`, "caddyfile")
// the declared length is rejected before respond runs, and the error
// route reading the body must still be held to max_size
tester.AssertPostResponseBody("http://localhost:9080/", nil, bytes.NewBufferString("abcdefghijklm"), http.StatusRequestEntityTooLarge, "request body: http: request body too large")
}

View file

@ -32,6 +32,8 @@ func init() {
type RequestBody struct {
// The maximum number of bytes to allow reading from the body by a later handler.
// If more bytes are read, an error with HTTP status 413 is returned.
// Requests declaring a larger Content-Length get the same error
// before any later handler runs.
MaxSize int64 `json:"max_size,omitempty"`
// This field permit to replace body on the fly
@ -67,7 +69,11 @@ func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next cad
return next.ServeHTTP(w, r)
}
if rb.MaxSize > 0 {
// wrap before rejecting: error routes get this request and may read the body
r.Body = errorWrapper{http.MaxBytesReader(w, r.Body, rb.MaxSize)}
if r.ContentLength > rb.MaxSize {
return caddyhttp.Error(http.StatusRequestEntityTooLarge, &http.MaxBytesError{Limit: rb.MaxSize})
}
}
return next.ServeHTTP(w, r)
}

View file

@ -16,9 +16,11 @@ package requestbody
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/caddyserver/caddy/v2"
@ -150,3 +152,76 @@ func TestRequestBodySetHeaderPlaceholders(t *testing.T) {
})
}
}
// TestRequestBodyMaxSize verifies that a declared Content-Length over the limit
// is rejected before the next handler runs, while bodies of unknown length still
// fail on read, both with the same 413 error.
func TestRequestBodyMaxSize(t *testing.T) {
const maxSize = 8
for _, tc := range []struct {
name string
body string
contentLength int64
wantNext bool
wantErr bool
}{
{
name: "declared length over the limit",
body: "0123456789",
contentLength: 10,
wantErr: true,
},
{
name: "declared length within the limit",
body: "01234567",
contentLength: 8,
wantNext: true,
},
{
name: "unknown length over the limit",
body: "0123456789",
contentLength: -1,
wantNext: true,
wantErr: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
rb := RequestBody{MaxSize: maxSize}
req := httptest.NewRequest(http.MethodPost, "https://example.com/upload", strings.NewReader(tc.body))
req.ContentLength = tc.contentLength
if tc.contentLength < 0 {
req.TransferEncoding = []string{"chunked"}
}
var nextCalled bool
next := caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
nextCalled = true
_, err := io.ReadAll(r.Body)
return err
})
err := rb.ServeHTTP(httptest.NewRecorder(), req, next)
if nextCalled != tc.wantNext {
t.Errorf("next handler called = %t, want %t", nextCalled, tc.wantNext)
}
if !tc.wantErr {
if err != nil {
t.Fatalf("did not expect an error, but got: %v", err)
}
return
}
he, ok := errors.AsType[caddyhttp.HandlerError](err)
if !ok || he.StatusCode != http.StatusRequestEntityTooLarge {
t.Fatalf("want a %d handler error, got: %v", http.StatusRequestEntityTooLarge, err)
}
if mbe, ok := errors.AsType[*http.MaxBytesError](err); !ok || mbe.Limit != maxSize {
t.Errorf("want a *http.MaxBytesError with limit %d, got: %v", maxSize, err)
}
})
}
}