Enforce the body size limit before CSRF parses the form (closes #90)
All checks were successful
check / check (push) Successful in 3m6s
All checks were successful
check / check (push) Successful in 3m6s
chi runs Use middleware in registration order, and every form route
group registered CSRF() before MaxBodySize(). gorilla/csrf calls
r.PostFormValue, so the form was parsed under net/http's 10 MB default
and the intended 1 MB cap never applied to form fields. The
/user/{username} group, which carries POST /password, had no
MaxBodySize registration at all.
- Register MaxBodySize ahead of CSRF in /pages, /sources, and
/source/{sourceID}, and add it to /user/{username}.
- Reject a declared-oversize body up front with 413. Reordering alone
cannot produce one: http.MaxBytesReader surfaces its error on Read,
so the form parse fails and gorilla/csrf answers 403 "no token" for
what is really an oversized body. MaxBytesReader is still installed
afterwards so chunked or length-lying clients stay hard-capped.
- Drop the handler-local MaxBytesReader calls in auth.go, profile.go,
and source_management.go now that the middleware is the single
enforcement point. maxBodyShift stays; webhook.go still uses it.
The /webhook/{uuid} receiver is untouched: it bounds itself with
io.LimitReader in readWebhookBody and is neither CSRF-protected nor
form-parsed.
Tests cover the middleware in isolation (declared oversize is rejected
without reaching a sentinel handler; at-limit and under-limit bodies
pass through intact; GET is unaffected; an undeclared oversize body is
truncated at the cap) and the real router built by SetupRoutes, so the
registration order itself is guarded: an oversized POST to
/pages/login returns 413 with no gorilla/csrf cookie issued, an
oversized POST /password with a valid session and CSRF token returns
413 and leaves the stored hash unchanged, and under-limit requests
still complete through the normal CSRF path.
This commit is contained in:
@@ -3,10 +3,12 @@ package middleware_test
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
@@ -426,6 +428,153 @@ func TestNoCache_SetsHeaders(t *testing.T) {
|
||||
)
|
||||
}
|
||||
|
||||
// --- MaxBodySize Middleware Tests ---
|
||||
|
||||
const testBodyLimit int64 = 64
|
||||
|
||||
// maxBodySizeHandler wraps a sentinel handler in MaxBodySize with
|
||||
// testBodyLimit. The sentinel records whether it ran and how much of
|
||||
// the body it managed to read, so tests can distinguish "never
|
||||
// reached" from "reached but truncated".
|
||||
type maxBodySizeResult struct {
|
||||
called bool
|
||||
read int
|
||||
readErr error
|
||||
response *httptest.ResponseRecorder
|
||||
}
|
||||
|
||||
func runMaxBodySize(
|
||||
t *testing.T,
|
||||
req *http.Request,
|
||||
) *maxBodySizeResult {
|
||||
t.Helper()
|
||||
|
||||
m, _ := testMiddleware(t, config.EnvironmentDev)
|
||||
res := &maxBodySizeResult{response: httptest.NewRecorder()}
|
||||
|
||||
handler := m.MaxBodySize(testBodyLimit)(http.HandlerFunc(
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
res.called = true
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
res.read = len(body)
|
||||
res.readErr = err
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
},
|
||||
))
|
||||
|
||||
handler.ServeHTTP(res.response, req)
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// postWithBody builds a POST request whose Content-Length is
|
||||
// accurate for the given payload size.
|
||||
func postWithBody(size int) *http.Request {
|
||||
req := httptest.NewRequestWithContext(
|
||||
context.Background(),
|
||||
http.MethodPost, "/pages/login",
|
||||
strings.NewReader(strings.Repeat("a", size)),
|
||||
)
|
||||
req.Header.Set(
|
||||
"Content-Type", "application/x-www-form-urlencoded",
|
||||
)
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
func TestMaxBodySize_DeclaredOversize_413AndHandlerNotReached(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
res := runMaxBodySize(t, postWithBody(int(testBodyLimit)+1))
|
||||
|
||||
assert.False(
|
||||
t, res.called,
|
||||
"handler must not be reached for an oversized body",
|
||||
)
|
||||
assert.Equal(
|
||||
t, http.StatusRequestEntityTooLarge, res.response.Code,
|
||||
)
|
||||
}
|
||||
|
||||
func TestMaxBodySize_AtLimit_PassesThrough(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
res := runMaxBodySize(t, postWithBody(int(testBodyLimit)))
|
||||
|
||||
assert.True(
|
||||
t, res.called,
|
||||
"handler should be reached for a body at the limit",
|
||||
)
|
||||
require.NoError(t, res.readErr)
|
||||
assert.Equal(t, int(testBodyLimit), res.read)
|
||||
assert.Equal(t, http.StatusOK, res.response.Code)
|
||||
}
|
||||
|
||||
func TestMaxBodySize_UnderLimit_PassesThrough(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
res := runMaxBodySize(t, postWithBody(1))
|
||||
|
||||
assert.True(t, res.called)
|
||||
require.NoError(t, res.readErr)
|
||||
assert.Equal(t, 1, res.read)
|
||||
assert.Equal(t, http.StatusOK, res.response.Code)
|
||||
}
|
||||
|
||||
func TestMaxBodySize_GetWithOversizeBody_NotCapped(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
req := httptest.NewRequestWithContext(
|
||||
context.Background(),
|
||||
http.MethodGet, "/pages/login",
|
||||
strings.NewReader(
|
||||
strings.Repeat("a", int(testBodyLimit)+1),
|
||||
),
|
||||
)
|
||||
|
||||
res := runMaxBodySize(t, req)
|
||||
|
||||
assert.True(
|
||||
t, res.called,
|
||||
"GET requests are not subject to the POST body cap",
|
||||
)
|
||||
require.NoError(t, res.readErr)
|
||||
assert.Equal(t, int(testBodyLimit)+1, res.read)
|
||||
}
|
||||
|
||||
// TestMaxBodySize_UndeclaredOversize_TruncatedAtCap covers the
|
||||
// chunked / lying-Content-Length case: there is nothing to check up
|
||||
// front, so the request reaches the handler but MaxBytesReader
|
||||
// hard-caps the body and the read fails at the limit.
|
||||
func TestMaxBodySize_UndeclaredOversize_TruncatedAtCap(
|
||||
t *testing.T,
|
||||
) {
|
||||
t.Parallel()
|
||||
|
||||
req := postWithBody(int(testBodyLimit) + 1)
|
||||
// Simulate a chunked request: no declared length.
|
||||
req.ContentLength = -1
|
||||
|
||||
res := runMaxBodySize(t, req)
|
||||
|
||||
assert.True(
|
||||
t, res.called,
|
||||
"an undeclared oversize body cannot be rejected up front",
|
||||
)
|
||||
require.Error(
|
||||
t, res.readErr,
|
||||
"reading past the cap must fail",
|
||||
)
|
||||
assert.Equal(
|
||||
t, int(testBodyLimit), res.read,
|
||||
"the handler must not see more than the cap",
|
||||
)
|
||||
}
|
||||
|
||||
// --- Helper Tests ---
|
||||
|
||||
func TestIpFromHostPort(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user