diff --git a/.github/test-suite-registry.json b/.github/test-suite-registry.json index eb71fbef47..596cdf5b66 100644 --- a/.github/test-suite-registry.json +++ b/.github/test-suite-registry.json @@ -250,7 +250,8 @@ "paths": [ "pkgs/id/hosted-worker/test/routing.test.ts", "pkgs/id/hosted-worker/test/blobs.test.ts", - "pkgs/id/hosted-worker/test/usage.test.ts" + "pkgs/id/hosted-worker/test/usage.test.ts", + "pkgs/id/hosted-worker/test/front-door.test.ts" ], "invocation": "cd pkgs/id/hosted-worker && npm test (node --test test/routing.test.ts)", "venue": { diff --git a/pkgs/id/hosted-worker/package.json b/pkgs/id/hosted-worker/package.json index 8aaa9e7a26..f08b06f270 100644 --- a/pkgs/id/hosted-worker/package.json +++ b/pkgs/id/hosted-worker/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "wrangler dev", "typecheck": "tsc --noEmit", - "test": "node --test test/routing.test.ts test/blobs.test.ts test/usage.test.ts test/currency.test.ts", + "test": "node --test test/routing.test.ts test/blobs.test.ts test/usage.test.ts test/currency.test.ts test/front-door.test.ts", "smoke": "node smoke/smoke.mjs" }, "devDependencies": { diff --git a/pkgs/id/hosted-worker/src/user-do.ts b/pkgs/id/hosted-worker/src/user-do.ts index 373010439f..8a8b4d73c9 100644 --- a/pkgs/id/hosted-worker/src/user-do.ts +++ b/pkgs/id/hosted-worker/src/user-do.ts @@ -68,12 +68,33 @@ function ceilingExceeded(headroom: number): FailClosed { ); } -/** Reads a request body as text, giving up as soon as it exceeds - * `limit` bytes so an oversized body is never buffered whole. */ -async function readTextUpTo(req: Request, limit: number): Promise { - if (!req.body) return ""; +/** Hard per-request body bound for every mutating route (#11337), + * matching the platform's default request size. It only bounds + * memory; the storage ceiling stays the authority on what fits. */ +export const MAX_BODY_BYTES = 100 * 1024 * 1024; + +/** The most body bytes any mutating route will read for this + * deployment: the storage ceiling when one is configured (no single + * write can exceed the whole ceiling), capped at MAX_BODY_BYTES. + * Shared by the front door and the DO so the two cannot drift. A + * malformed ceiling falls back to MAX_BODY_BYTES here; the DO's own + * ceiling check still fails those writes closed. */ +export function requestBodyLimit(rawCeiling: string | undefined): number { + if (rawCeiling === undefined || rawCeiling === "") return MAX_BODY_BYTES; + const n = Number(rawCeiling); + if (!Number.isInteger(n) || n < 0) return MAX_BODY_BYTES; + return Math.min(n, MAX_BODY_BYTES); +} + +export function bodyTooLarge(limit: number): FailClosed { + return new FailClosed(413, "body_too_large", `request body is larger than the ${limit}-byte limit`); +} + +/** Reads a request body, giving up as soon as it exceeds `limit` + * bytes so an oversized body is never buffered whole. */ +async function readBytesUpTo(req: Request, limit: number): Promise | null> { + if (!req.body) return new Uint8Array(0); const reader = req.body.getReader(); - const decoder = new TextDecoder(); const chunks: Uint8Array[] = []; let total = 0; for (;;) { @@ -92,7 +113,12 @@ async function readTextUpTo(req: Request, limit: number): Promise bytes.set(chunk, offset); offset += chunk.byteLength; } - return decoder.decode(bytes); + return bytes; +} + +async function readTextUpTo(req: Request, limit: number): Promise { + const bytes = await readBytesUpTo(req, limit); + return bytes === null ? null : new TextDecoder().decode(bytes); } export class UserDO { @@ -282,7 +308,14 @@ export class UserDO { } const blobHashMatch = url.pathname.match(/^\/v1\/blobs\/([0-9a-f]{64})$/); if (url.pathname === "/v1/blobs" && req.method === "PUT") { - const bytes = new Uint8Array(await req.arrayBuffer()); + // Bounded read (#11337): a blob larger than the whole + // ceiling can never fit, so the ceiling bounds the read too. + const limit = requestBodyLimit(this.env.USER_CEILING_BYTES); + const tooLarge = () => (this.ceilingBytes() === null ? bodyTooLarge(limit) : ceilingExceeded(limit)); + const declared = req.headers.get("content-length"); + if (declared !== null && Number(declared) > limit) throw tooLarge(); + const bytes = await readBytesUpTo(req, limit); + if (bytes === null) throw tooLarge(); const digest = await crypto.subtle.digest("SHA-256", bytes); const hash = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); const bucket = blobsBindingFor(this.env, jurisdiction as Jurisdiction); @@ -341,7 +374,11 @@ export class UserDO { const headroom = this.kvHeadroom(priorBytes); let value: string | null; if (headroom === null) { - value = await req.text(); + const limit = requestBodyLimit(this.env.USER_CEILING_BYTES); + const declared = req.headers.get("content-length"); + if (declared !== null && Number(declared) > limit) throw bodyTooLarge(limit); + value = await readTextUpTo(req, limit); + if (value === null) throw bodyTooLarge(limit); } else { const declared = req.headers.get("content-length"); if (declared !== null && Number(declared) > headroom) throw ceilingExceeded(headroom); diff --git a/pkgs/id/hosted-worker/src/worker.ts b/pkgs/id/hosted-worker/src/worker.ts index d991e71043..7dd2d91bba 100644 --- a/pkgs/id/hosted-worker/src/worker.ts +++ b/pkgs/id/hosted-worker/src/worker.ts @@ -12,12 +12,13 @@ // No Iroh QUIC runs inside the Worker (issue excludes). import { FailClosed, parseBindingId, parseJurisdiction, userStub, type ObjectNamespaceLike } from "./routing.ts"; -import { HDR_BINDING, HDR_JURISDICTION, HDR_ROUTED } from "./user-do.ts"; +import { HDR_BINDING, HDR_JURISDICTION, HDR_ROUTED, bodyTooLarge, requestBodyLimit } from "./user-do.ts"; export { UserDO } from "./user-do.ts"; interface Env { USERS: ObjectNamespaceLike; + USER_CEILING_BYTES?: string; } function json(body: unknown, status = 200): Response { @@ -32,6 +33,16 @@ export default { try { const bindingId = parseBindingId(req.headers.get("x-binding-id")); const jurisdiction = parseJurisdiction(req.headers.get("x-jurisdiction")); + const hasBody = req.method !== "GET" && req.method !== "HEAD"; + if (hasBody) { + // Front-door memory bound (#11337): refuse a declared + // oversized body before anything reads it. The body is then + // streamed, never buffered here, so the DO's capped reads + // bound memory for chunked bodies too. + const limit = requestBodyLimit(env.USER_CEILING_BYTES); + const declared = req.headers.get("content-length"); + if (declared !== null && Number(declared) > limit) throw bodyTooLarge(limit); + } const stub = userStub(env.USERS, bindingId, jurisdiction); const headers = new Headers(req.headers); headers.delete("x-binding-id"); @@ -42,8 +53,9 @@ export default { const forwarded = new Request(req.url, { method: req.method, headers, - body: req.method === "GET" || req.method === "HEAD" ? undefined : await req.arrayBuffer(), - }); + body: hasBody ? (req.body ?? undefined) : undefined, + duplex: "half", + } as RequestInit); return await stub.fetch(forwarded); } catch (e) { if (e instanceof FailClosed) return json({ error: e.code, message: e.message }, e.status); diff --git a/pkgs/id/hosted-worker/test/front-door.test.ts b/pkgs/id/hosted-worker/test/front-door.test.ts new file mode 100644 index 0000000000..bc3ad98dde --- /dev/null +++ b/pkgs/id/hosted-worker/test/front-door.test.ts @@ -0,0 +1,150 @@ +// #11337: the front door (worker.ts default export) must bound body +// memory before the DO's ceiling check can run. These tests go +// through the default export, not UserDO alone, with a namespace fake +// that routes to the real UserDO over in-memory SQLite and R2. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DatabaseSync } from "node:sqlite"; +import worker from "../src/worker.ts"; +import { UserDO } from "../src/user-do.ts"; + +const A = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + +function fakeSql() { + const db = new DatabaseSync(":memory:"); + return { + exec(query: string, ...params: unknown[]) { + const stmt = db.prepare(query); + if (/^\s*select/i.test(query)) { + const rows = stmt.all(...(params as never[])) as Record[]; + return { toArray: () => rows }; + } + stmt.run(...(params as never[])); + return { toArray: () => [] as Record[] }; + }, + }; +} + +function fakeBucket() { + const objects = new Map(); + return { + async head(key: string) { + const v = objects.get(key); + return v ? { size: v.byteLength } : null; + }, + async get(key: string) { + const v = objects.get(key); + return v ? { size: v.byteLength, body: new Blob([v]).stream() } : null; + }, + async put(key: string, value: Uint8Array) { + objects.set(key, value); + }, + async delete(key: string) { + objects.delete(key); + }, + }; +} + +function makeEnv(vars: Record = {}) { + const calls = { stub: 0 }; + const userDO = new UserDO( + { + id: { name: A }, + storage: { sql: fakeSql() }, + blockConcurrencyWhile: async (fn: () => Promise): Promise => fn(), + } as never, + { BLOBS: fakeBucket(), ...vars } as never, + ); + const ns = { + jurisdiction() { + return ns; + }, + idFromName(name: string) { + return { name }; + }, + get() { + return { + fetch: (r: Request) => { + calls.stub++; + return userDO.fetch(r); + }, + }; + }, + }; + return { env: { USERS: ns, ...vars } as never, calls }; +} + +function front(path: string, init: RequestInit = {}): Request { + const headers = new Headers(init.headers); + headers.set("x-binding-id", A); + headers.set("x-jurisdiction", "us"); + return new Request("https://hosted.example" + path, { ...init, headers, duplex: "half" } as RequestInit); +} + +/** A body stream that records how many bytes were pulled from it. */ +function countingBody(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 }; +} + +test("a declared oversized body is refused at the front door without being read", async () => { + const { env, calls } = makeEnv({ USER_CEILING_BYTES: "10" }); + const { body, seen } = countingBody([new Uint8Array(64)]); + const r = await worker.fetch( + front("/v1/blobs", { method: "PUT", body, headers: { "content-length": "64" } }), + env, + ); + assert.equal(r.status, 413); + assert.equal(((await r.json()) as { error: string }).error, "body_too_large"); + assert.equal(seen.bytes, 0, "the body was never read"); + assert.equal(calls.stub, 0, "the DO was never reached"); +}); + +test("a chunked oversized body stops being read at the limit plus one chunk", async () => { + const { env } = makeEnv({ USER_CEILING_BYTES: "10" }); + const chunk = new Uint8Array(4); + const { body, seen } = countingBody(Array.from({ length: 1000 }, () => chunk)); + const r = await worker.fetch(front("/v1/blobs", { method: "PUT", body }), env); + assert.equal(r.status, 413); + assert.ok(seen.bytes <= 10 + 2 * chunk.byteLength, `read ${seen.bytes} bytes of 4000`); + + const kv = countingBody(Array.from({ length: 1000 }, () => chunk)); + const r2 = await worker.fetch(front("/v1/kv/big", { method: "PUT", body: kv.body }), env); + assert.equal(r2.status, 413); + assert.ok(kv.seen.bytes <= 10 + 2 * chunk.byteLength, `read ${kv.seen.bytes} bytes of 4000`); +}); + +test("normal kv and blob PUTs still succeed end to end through the front door", async () => { + const { env } = makeEnv({ USER_CEILING_BYTES: "100" }); + const kv = await worker.fetch(front("/v1/kv/note", { method: "PUT", body: "hello" }), env); + assert.equal(kv.status, 200); + const read = await worker.fetch(front("/v1/kv/note"), env); + assert.equal(((await read.json()) as { value: string }).value, "hello"); + const blob = await worker.fetch( + front("/v1/blobs", { method: "PUT", body: new TextEncoder().encode("blobbytes!") }), + env, + ); + assert.equal(blob.status, 200); + const usage = (await (await worker.fetch(front("/v1/usage"), env)).json()) as { storage_bytes: number }; + assert.equal(usage.storage_bytes, 15); +}); + +test("with no ceiling, normal writes pass and the hard body bound still applies to declared length", async () => { + const { env, calls } = makeEnv(); + assert.equal((await worker.fetch(front("/v1/kv/k", { method: "PUT", body: "x" }), env)).status, 200); + const r = await worker.fetch( + front("/v1/kv/k", { method: "PUT", body: "x", headers: { "content-length": String(200 * 1024 * 1024) } }), + env, + ); + assert.equal(r.status, 413); + assert.equal(calls.stub, 1, "only the normal write reached the DO"); +});