From 67cabfbddaf502980696285fd1cd00355fc86d4d Mon Sep 17 00:00:00 2001 From: Bobby Ho Date: Tue, 14 Jul 2026 12:29:38 -0700 Subject: [PATCH] fix: enforce max body size on CSP violation report endpoint (#27243) The `/api/v2/csp/reports` endpoint is unauthenticated and CSRF-exempt, since it's the browser's `report-uri` target, and decoded request bodies with no size limit. This let an attacker post arbitrarily large JSON bodies to force unbounded heap allocation and OOM the server (Cure53 CDM-02-007). Wraps the request body in `http.MaxBytesReader` before decoding and returns 413 when the limit is exceeded, matching the existing convention used by `files.go`, `aitasks.go`, and `exp_chats.go`. Fixes: https://github.com/coder/security-disclosures/issues/171 (cherry picked from commit 0207a9824f3d760800549982f2c66fefb2a32193) --- coderd/apidoc/docs.go | 6 +++ coderd/apidoc/swagger.json | 6 +++ coderd/csp.go | 17 +++++++++ coderd/csp_test.go | 69 +++++++++++++++++++++++++++++++++++ docs/reference/api/general.md | 12 ++++-- 5 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 coderd/csp_test.go diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index a280e5e7c42ad..0ada08025d7ce 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -2225,6 +2225,12 @@ const docTemplate = `{ "responses": { "200": { "description": "OK" + }, + "413": { + "description": "Request Entity Too Large", + "schema": { + "$ref": "#/definitions/codersdk.Response" + } } }, "security": [ diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index 5eaa93a980359..5572ec0cb6f0c 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -1964,6 +1964,12 @@ "responses": { "200": { "description": "OK" + }, + "413": { + "description": "Request Entity Too Large", + "schema": { + "$ref": "#/definitions/codersdk.Response" + } } }, "security": [ diff --git a/coderd/csp.go b/coderd/csp.go index bba4980743dfd..2e817e0d0e9b7 100644 --- a/coderd/csp.go +++ b/coderd/csp.go @@ -2,6 +2,8 @@ package coderd import ( "encoding/json" + "errors" + "fmt" "net/http" "cdr.dev/slog/v3" @@ -9,6 +11,12 @@ import ( "github.com/coder/coder/v2/codersdk" ) +// cspReportMaxBytes bounds the size of a single CSP violation report. This +// endpoint is unauthenticated and CSRF-exempt (it's the browser's +// `report-uri` target), so it must not allow unbounded body sizes to reach +// json.Decode. Real CSP reports are small JSON objects; 64KB is generous. +const cspReportMaxBytes = 64 * 1024 + type cspViolation struct { Report map[string]interface{} `json:"csp-report"` } @@ -22,14 +30,23 @@ type cspViolation struct { // @Tags General // @Param request body cspViolation true "Violation report" // @Success 200 +// @Failure 413 {object} codersdk.Response // @Router /api/v2/csp/reports [post] func (api *API) logReportCSPViolations(rw http.ResponseWriter, r *http.Request) { ctx := r.Context() var v cspViolation + r.Body = http.MaxBytesReader(rw, r.Body, cspReportMaxBytes) dec := json.NewDecoder(r.Body) err := dec.Decode(&v) if err != nil { + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + httpapi.Write(ctx, rw, http.StatusRequestEntityTooLarge, codersdk.Response{ + Message: "Request body too large.", + Detail: fmt.Sprintf("Maximum CSP report size is %d bytes.", cspReportMaxBytes), + }) + return + } api.Logger.Warn(ctx, "CSP violation reported", slog.Error(err)) httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ Message: "Failed to read body, invalid json.", diff --git a/coderd/csp_test.go b/coderd/csp_test.go new file mode 100644 index 0000000000000..bf7f0f80e2791 --- /dev/null +++ b/coderd/csp_test.go @@ -0,0 +1,69 @@ +package coderd_test + +import ( + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/coder/coder/v2/coderd/coderdtest" + "github.com/coder/coder/v2/codersdk" + "github.com/coder/coder/v2/testutil" +) + +func TestPostCSPViolations(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, nil) + + // oversizedReportBody builds a JSON body well over the 64KB limit + // enforced by coderd.cspReportMaxBytes, mirroring the Cure53 PoC of + // posting oversized bodies to force unbounded heap allocation. + oversizedReportBody := func() []byte { + padding := strings.Repeat("a", 128*1024) + return []byte(`{"csp-report":{"padding":"` + padding + `"}}`) + } + + tests := []struct { + name string + body any + expectedStatus int + }{ + { + name: "OK", + body: map[string]any{ + "csp-report": map[string]any{ + "document-uri": "https://example.com", + "violated-directive": "script-src", + }, + }, + expectedStatus: http.StatusOK, + }, + { + name: "OversizedBody", + body: oversizedReportBody(), + expectedStatus: http.StatusRequestEntityTooLarge, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitShort) + res, err := client.Request(ctx, http.MethodPost, "/api/v2/csp/reports", tt.body) + require.NoError(t, err) + defer res.Body.Close() + + if tt.expectedStatus != http.StatusOK { + apiErr := codersdk.ReadBodyAsError(res) + var sdkErr *codersdk.Error + require.ErrorAs(t, apiErr, &sdkErr) + require.Equal(t, tt.expectedStatus, sdkErr.StatusCode()) + return + } + require.Equal(t, tt.expectedStatus, res.StatusCode) + }) + } +} diff --git a/docs/reference/api/general.md b/docs/reference/api/general.md index fa3c245d8093f..c81a9758598de 100644 --- a/docs/reference/api/general.md +++ b/docs/reference/api/general.md @@ -80,6 +80,7 @@ curl -X GET http://coder-server:8080/api/v2/buildinfo \ # Example request using curl curl -X POST http://coder-server:8080/api/v2/csp/reports \ -H 'Content-Type: application/json' \ + -H 'Accept: */*' \ -H 'Coder-Session-Token: API_KEY' ``` @@ -99,11 +100,16 @@ curl -X POST http://coder-server:8080/api/v2/csp/reports \ |--------|------|------------------------------------------------------|----------|------------------| | `body` | body | [coderd.cspViolation](schemas.md#coderdcspviolation) | true | Violation report | +### Example responses + +> 413 Response + ### Responses -| Status | Meaning | Description | Schema | -|--------|---------------------------------------------------------|-------------|--------| -| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | OK | | +| Status | Meaning | Description | Schema | +|--------|-------------------------------------------------------------------------|--------------------------|--------------------------------------------------| +| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | OK | | +| 413 | [Payload Too Large](https://tools.ietf.org/html/rfc7231#section-6.5.11) | Request Entity Too Large | [codersdk.Response](schemas.md#codersdkresponse) | To perform this operation, you must be authenticated. [Learn more](authentication.md).