Public: anyone can read this; the crew can change it.

The CSP report endpoint takes at most 8 KB a report and 30 reports a minute from one address, refusing the rest with 429 #16063

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16042-the-csp-report-endpoint-takes-at-most-8 → main 0 commits fork

  • Merged. scout/16042-the-csp-report-endpoint-takes-at-most-8 was merged into main as d99f089.

Review

Sign in to review this change.
3 files changed +103 −10
src/http/csp_report.ts +22 −10
@@ -14,14 +14,16 @@
1414 * rows a day the rest fold into one per directive and hour, at most
1515 * `24 × (DIRECTIVES.size + 1)` more (#14962), and
1616 * days past `KEEP_DAYS` are dropped as new ones arrive. Anonymous callers are
17 * limited per client and per forge like the page-view beacon. Always 204.
17 * limited per client (30 a minute) and per forge like the page-view beacon,
18 * both rows of `RATE_CAPS` in `limits.ts`; a 413 or 429 says its limit in
19 * words (#16042). Otherwise 204.
1820 */
1921
2022 import type { Database } from "bun:sqlite";
2123 import type { App } from "../app.ts";
2224 import { RateLimiter } from "../core/ratelimit.ts";
2325 import type { Ctx } from "./context.ts";
24 import { BODY_CAPS, readBounded } from "./limits.ts";
26 import { BODY_CAPS, RATE_CAPS, readBounded } from "./limits.ts";
2527 import { clientBucket } from "./peer.ts";
2628
2729 export const CSP_REPORT_PATH = "/csp-report";
@@ -54,8 +56,9 @@ export const DIRECTIVES: ReadonlySet<string> = new Set([
5456 ]);
5557 /** A known directive name as is; any other folds to `other`. */
5658 export const knownDirective = (name: string): string => (DIRECTIVES.has(name) ? name : OTHER_DIRECTIVE);
57 const PER_CLIENT = 30;
58 const PER_FORGE = 600;
59 /** Reports a minute from one address, and from everyone (`RATE_CAPS.cspReport`). */
60 export const CSP_REPORT_PER_CLIENT = RATE_CAPS.cspReport.perClient;
61 const PER_FORGE = RATE_CAPS.cspReport.perForge;
5962
6063 export interface Violation {
6164 readonly directive: string;
@@ -66,8 +69,11 @@ export interface Violation {
6669 const limiter = (perMinute: number) => new RateLimiter({ perMinute, adminPerMinute: perMinute, enabled: true });
6770 const limits = new WeakMap<App, { client: RateLimiter; forge: RateLimiter }>();
6871
69 const answer = (status: number, headers?: Record<string, string>): Response =>
70 new Response(null, { status, headers: { "cache-control": "no-store", ...headers } });
72 const answer = (status: number, headers?: Record<string, string>, body: string | null = null): Response =>
73 new Response(body, {
74 status,
75 headers: { "cache-control": "no-store", ...(body === null ? {} : { "content-type": "text/plain; charset=utf-8" }), ...headers },
76 });
7177
7278 const text = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
7379
@@ -211,15 +217,21 @@ export async function cspReportSubmit(ctx: Ctx): Promise<Response> {
211217
212218 let pair = limits.get(app);
213219 if (pair === undefined) {
214 pair = { client: limiter(PER_CLIENT), forge: limiter(PER_FORGE) };
220 pair = { client: limiter(CSP_REPORT_PER_CLIENT), forge: limiter(PER_FORGE) };
215221 limits.set(app, pair);
216222 }
217 for (const verdict of [pair.client.take(clientBucket(request), "ro"), pair.forge.take("forge", "ro")]) {
218 if (!verdict.allowed) return answer(429, { "retry-after": String(Math.max(1, verdict.retryAfter)) });
223 const verdicts = [
224 { verdict: pair.client.take(clientBucket(request), "ro"), of: `${CSP_REPORT_PER_CLIENT} reports a minute from one address` },
225 { verdict: pair.forge.take("forge", "ro"), of: `${PER_FORGE} reports a minute in all` },
226 ];
227 for (const { verdict, of } of verdicts) {
228 if (!verdict.allowed) {
229 return answer(429, { "retry-after": String(Math.max(1, verdict.retryAfter)) }, `too many reports: at most ${of}\n`);
230 }
219231 }
220232
221233 const bytes = await readBounded(request, CSP_REPORT_MAX);
222 if (bytes === "too_large") return answer(413);
234 if (bytes === "too_large") return answer(413, undefined, `report too large: at most ${CSP_REPORT_MAX / 1024} KB (${CSP_REPORT_MAX} bytes)\n`);
223235 const found = parseCspReport(new TextDecoder().decode(bytes));
224236 if (found === "malformed") return answer(400);
225237 for (const v of found) recordViolation(app.db, v);
src/http/limits.ts +12
@@ -37,6 +37,18 @@ export const FETCH_MAX = BODY_CAPS.fetch.bytes;
3737 export const DRAIN_MAX = BODY_CAPS.drain.bytes;
3838 export const GZIP_MAX = BODY_CAPS.gzip.bytes;
3939
40 /**
41 * How many requests a minute an anonymous endpoint takes, beside the body
42 * caps, so a route names its row here and never a number of its own.
43 */
44 export const RATE_CAPS = {
45 cspReport: {
46 perClient: 30,
47 perForge: 600,
48 reason: "a page reports what its policy blocked, a handful a load; more from one address is a flood",
49 },
50 } as const satisfies Record<string, { perClient: number; perForge: number; reason: string }>;
51
4052 const closing = new WeakSet<Request>();
4153 const signedIn = new WeakSet<Request>();
4254
test/csp-report-limits.test.ts added +69
@@ -0,0 +1,69 @@
1 // The CSP report endpoint's limits (#16042): 8 KB a report, 30 a minute from one address, each
2 // refusal naming its limit, both read from `RATE_CAPS`/`BODY_CAPS` in limits.ts.
3 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { CSP_REPORT_MAX, CSP_REPORT_PER_CLIENT } from "../src/http/csp_report.ts";
9 import { BODY_CAPS, RATE_CAPS } from "../src/http/limits.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11
12 let dir: string;
13 let app: App;
14 let servers: Servers;
15 let base: string;
16
17 // Each test gets its own forge: the limiter is per app, and every request here comes from one
18 // loopback address (an unproxied X-Forwarded-For is not believed).
19 beforeEach(async () => {
20 dir = await mkdtemp(join(tmpdir(), "csp-limits-"));
21 app = createApp({ dataDir: dir, port: 0 });
22 servers = await serve(app);
23 base = `http://127.0.0.1:${servers.port}`;
24 });
25 afterEach(async () => {
26 await servers.stop();
27 await rm(dir, { recursive: true, force: true });
28 });
29
30 const report = (blocked: string) =>
31 JSON.stringify({ "csp-report": { "document-uri": `${base}/explore`, "violated-directive": "img-src", "blocked-uri": blocked } });
32 const send = (body: string) =>
33 fetch(`${base}/csp-report`, { method: "POST", headers: { "content-type": "application/csp-report" }, body });
34 const count = (blocked: string) =>
35 (app.db.query("SELECT SUM(n) AS n FROM csp_violation WHERE blocked = ?1").get(blocked) as { n: number | null }).n ?? 0;
36
37 describe("the CSP report endpoint's limits", () => {
38 test("the limits are rows of limits.ts: 8 KB a report, 30 a minute an address", () => {
39 expect(CSP_REPORT_MAX).toBe(BODY_CAPS.cspReport.bytes);
40 expect(CSP_REPORT_MAX).toBe(8 * 1024);
41 expect(CSP_REPORT_PER_CLIENT).toBe(RATE_CAPS.cspReport.perClient);
42 expect(CSP_REPORT_PER_CLIENT).toBe(30);
43 });
44
45 test("a well-formed report is stored", async () => {
46 const res = await send(report("https://ok.example/a.png"));
47 expect(res.status).toBe(204);
48 expect(count("ok.example")).toBe(1);
49 });
50
51 test("a body over 8 KB is a 413 naming the limit, and stores nothing", async () => {
52 const res = await send(report("https://big.example/" + "a".repeat(CSP_REPORT_MAX)));
53 expect(res.status).toBe(413);
54 const said = await res.text();
55 expect(said).toContain("8 KB");
56 expect(said).toContain(String(CSP_REPORT_MAX));
57 expect(count("big.example")).toBe(0);
58 });
59
60 test("the 31st report in a minute from one address is a 429 with Retry-After, and is not stored", async () => {
61 const body = report("https://flood.example/x.png");
62 for (let i = 0; i < 30; i++) expect((await send(body)).status).toBe(204);
63 const refused = await send(body);
64 expect(refused.status).toBe(429);
65 expect(Number(refused.headers.get("retry-after"))).toBeGreaterThanOrEqual(1);
66 expect(await refused.text()).toContain("30 reports a minute from one address");
67 expect(count("flood.example")).toBe(30);
68 });
69 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs