diff --git a/nixos/services/id-mail/worker/runtime.test.mjs b/nixos/services/id-mail/worker/runtime.test.mjs index 82118e7f1a..51eff81200 100644 --- a/nixos/services/id-mail/worker/runtime.test.mjs +++ b/nixos/services/id-mail/worker/runtime.test.mjs @@ -229,3 +229,83 @@ test("template mode with no templates configured refuses instead of throwing (#6 assert.equal(response.status, 400); assert.deepEqual(fx.sent, []); }); + +function countingBody(chunk, count) { + const seen = { bytes: 0 }; + let i = 0; + const body = new ReadableStream( + { + pull(c) { + if (i++ >= count) return c.close(); + seen.bytes += chunk.byteLength; + c.enqueue(chunk); + }, + }, + { highWaterMark: 0 }, + ); + return { body, seen }; +} + +test("an oversized declared body is refused with 413 without being read (#11331)", async () => { + const harness = makeEnv(); + const env = harness.build(); + const { body, seen } = countingBody(new Uint8Array(64), 1); + const response = await worker.fetch( + new Request("https://mail.example/", { + method: "POST", + headers: { + authorization: `Bearer ${TOKEN}`, + "content-type": "application/json", + "content-length": String(65 * 1024), + }, + body, + duplex: "half", + }), + env, + ); + assert.equal(response.status, 413); + assert.deepEqual(await response.json(), { error: "body is too large" }); + assert.equal(seen.bytes, 0); + assert.deepEqual(harness.sent, []); +}); + +test("a drip-fed oversized body stops being read at the cap (#11331)", async () => { + const harness = makeEnv(); + const env = harness.build(); + const chunk = new Uint8Array(4096).fill(0x20); + const { body, seen } = countingBody(chunk, 1000); + const response = await worker.fetch( + new Request("https://mail.example/", { + method: "POST", + headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/json" }, + body, + duplex: "half", + }), + env, + ); + assert.equal(response.status, 413); + assert.ok(seen.bytes <= 64 * 1024 + 2 * chunk.byteLength, `read ${seen.bytes} bytes`); + assert.deepEqual(harness.sent, []); +}); + +test("bad JSON and non-object bodies keep their 400 envelopes after the bounded read (#11331)", async () => { + const harness = makeEnv(); + const env = harness.build(); + const post = (body) => + worker.fetch( + new Request("https://mail.example/", { + method: "POST", + headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/json" }, + body, + }), + env, + ); + const bad = await post("{nope"); + assert.equal(bad.status, 400); + assert.deepEqual(await bad.json(), { error: "body is not JSON" }); + const nul = await post("null"); + assert.equal(nul.status, 400); + assert.deepEqual(await nul.json(), { error: "body must be a JSON object" }); + const ok = await worker.fetch(mailRequest("bob@example.com"), env); + assert.equal(ok.status, 200); +}); diff --git a/nixos/services/id-mail/worker/src/index.js b/nixos/services/id-mail/worker/src/index.js index fe7b35cf20..ba1019c098 100644 --- a/nixos/services/id-mail/worker/src/index.js +++ b/nixos/services/id-mail/worker/src/index.js @@ -22,9 +22,16 @@ export default { return json({ error: "unauthorized" }, 401); } + // #11331: bounded read. A mail request is a few addresses, a + // subject and at most MAX_TEXT characters, so anything over + // MAX_BODY_BYTES is refused before it is buffered or parsed. + const raw = await readTextUpTo(request, MAX_BODY_BYTES); + if (raw === null) { + return json({ error: "body is too large" }, 413); + } let body; try { - body = await request.json(); + body = JSON.parse(raw); } catch { return json({ error: "body is not JSON" }, 400); } @@ -197,6 +204,36 @@ function sameText(a, b) { return diff === 0; } +const MAX_BODY_BYTES = 64 * 1024; + +/** The body as text, or null when it declares or streams more than + * `limit` bytes; an oversized body is never buffered whole. */ +async function readTextUpTo(request, limit) { + const declared = request.headers.get("content-length"); + if (declared !== null && Number(declared) > limit) return null; + if (!request.body) return ""; + const reader = request.body.getReader(); + const chunks = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > limit) { + await reader.cancel(); + return null; + } + chunks.push(value); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return new TextDecoder().decode(bytes); +} + function json(value, status = 200) { return new Response(JSON.stringify(value), { status, diff --git a/pkgs/atlas-search/worker/src/body.ts b/pkgs/atlas-search/worker/src/body.ts new file mode 100644 index 0000000000..4cc4c35ce6 --- /dev/null +++ b/pkgs/atlas-search/worker/src/body.ts @@ -0,0 +1,36 @@ +// Bounded request body read (#11331). /v1/search only needs +// { query, k }, so a body over MAX_SEARCH_BODY_BYTES is refused before +// it is buffered or parsed: a declared Content-Length over the cap is +// refused without reading, and an undeclared body stops at the cap. + +export const MAX_SEARCH_BODY_BYTES = 64 * 1024; + +/** The body as text, or null when it is larger than `limit` bytes. */ +export async function readTextUpTo( + req: Pick, + limit: number = MAX_SEARCH_BODY_BYTES, +): Promise { + const declared = req.headers.get("content-length"); + if (declared !== null && Number(declared) > limit) return null; + if (!req.body) return ""; + const reader = req.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > limit) { + await reader.cancel(); + return null; + } + chunks.push(value); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return new TextDecoder().decode(bytes); +} diff --git a/pkgs/atlas-search/worker/src/index.ts b/pkgs/atlas-search/worker/src/index.ts index 3956173663..03f66b63db 100644 --- a/pkgs/atlas-search/worker/src/index.ts +++ b/pkgs/atlas-search/worker/src/index.ts @@ -15,6 +15,7 @@ * POST /v1/search {query, k?} (gated) -> miss or hit envelope * GET /v1/cache/inspect?query=&k= (gated) -> DO metadata readback */ +import { readTextUpTo } from "./body"; import { QueryCache } from "./cache_do"; import { normalizeQuery, queryKey } from "./key"; @@ -70,9 +71,14 @@ export default { if (!(await gateOk(env, req))) { return errorJson(401, "unauthorized", "missing or invalid gate token"); } + // #11331: bounded read; the route only needs { query, k }. + const raw = await readTextUpTo(req); + if (raw === null) { + return errorJson(413, "payload_too_large", "body is larger than the 64 KiB limit"); + } let body: { query?: unknown; k?: unknown }; try { - body = (await req.json()) as typeof body; + body = JSON.parse(raw) as typeof body; } catch { return errorJson(400, "bad_request", "body must be JSON"); } diff --git a/pkgs/atlas-search/worker/test/body.test.ts b/pkgs/atlas-search/worker/test/body.test.ts new file mode 100644 index 0000000000..48357a519d --- /dev/null +++ b/pkgs/atlas-search/worker/test/body.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; +import { MAX_SEARCH_BODY_BYTES, readTextUpTo } from "../src/body"; + +function counting(chunks: Uint8Array[]) { + const seen = { bytes: 0 }; + let i = 0; + const body = new ReadableStream( + { + pull(c) { + if (i >= chunks.length) return c.close(); + const chunk = chunks[i++]; + seen.bytes += chunk.byteLength; + c.enqueue(chunk); + }, + }, + { highWaterMark: 0 }, + ); + return { body, seen }; +} + +describe("readTextUpTo (#11331)", () => { + it("caps at 64 KiB by default", () => { + expect(MAX_SEARCH_BODY_BYTES).toBe(64 * 1024); + }); + + it("refuses a declared oversized body without reading it", async () => { + const { body, seen } = counting([new Uint8Array(64)]); + const out = await readTextUpTo({ headers: new Headers({ "content-length": "64" }), body }, 10); + expect(out).toBeNull(); + expect(seen.bytes).toBe(0); + }); + + it("stops reading an undeclared oversized body at the cap plus one chunk", async () => { + const chunk = new Uint8Array(4); + const { body, seen } = counting(Array.from({ length: 1000 }, () => chunk)); + const out = await readTextUpTo({ headers: new Headers(), body }, 10); + expect(out).toBeNull(); + expect(seen.bytes).toBeLessThanOrEqual(10 + 2 * chunk.byteLength); + }); + + it("returns a body at or under the cap unchanged, multibyte included", async () => { + const text = '{"a":"é😀"}'; + const bytes = new TextEncoder().encode(text); + const { body } = counting([bytes.slice(0, 7), bytes.slice(7)]); + const out = await readTextUpTo({ headers: new Headers({ "content-length": String(bytes.byteLength) }), body }, bytes.byteLength); + expect(out).toBe(text); + }); + + it("treats a missing body as empty", async () => { + expect(await readTextUpTo({ headers: new Headers(), body: null })).toBe(""); + }); +}); diff --git a/pkgs/atlas-search/worker/test/worker.test.ts b/pkgs/atlas-search/worker/test/worker.test.ts index 48415a3d4f..3e5ef40f8a 100644 --- a/pkgs/atlas-search/worker/test/worker.test.ts +++ b/pkgs/atlas-search/worker/test/worker.test.ts @@ -178,6 +178,21 @@ describe("atlas-search worker", () => { expect(counts.search).toBe(s0); }); + it("refuses an oversized body with the 413 envelope before parsing it (#11331)", async () => { + const e0 = counts.embed; + const s0 = counts.search; + const resp = await SELF.fetch("https://worker.test/v1/search", { + method: "POST", + headers: { ...GATE, "Content-Type": "application/json" }, + body: JSON.stringify({ query: "x".repeat(70 * 1024) }), + }); + expect(resp.status).toBe(413); + const body = (await resp.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe("payload_too_large"); + expect(counts.embed).toBe(e0); + expect(counts.search).toBe(s0); + }); + it("reports a null search-service response as a 502, not a raw TypeError (#6982)", async () => { const resp = await search({ query: "nullsearch query" }); expect(resp.status).toBe(502);