diff --git a/caddytest/integration/handler_test.go b/caddytest/integration/handler_test.go index fa4981707..7a2610d80 100644 --- a/caddytest/integration/handler_test.go +++ b/caddytest/integration/handler_test.go @@ -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") } diff --git a/modules/caddyhttp/requestbody/requestbody.go b/modules/caddyhttp/requestbody/requestbody.go index 36805f936..adcb84b16 100644 --- a/modules/caddyhttp/requestbody/requestbody.go +++ b/modules/caddyhttp/requestbody/requestbody.go @@ -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) } diff --git a/modules/caddyhttp/requestbody/requestbody_test.go b/modules/caddyhttp/requestbody/requestbody_test.go index 71b7ca38b..0f0921edf 100644 --- a/modules/caddyhttp/requestbody/requestbody_test.go +++ b/modules/caddyhttp/requestbody/requestbody_test.go @@ -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) + } + }) + } +}