From 1ba97c3624e18883cf199b8f8559d32480362740 Mon Sep 17 00:00:00 2001 From: dezren39 Date: Tue, 17 Nov 2026 14:09:44 -0600 Subject: [PATCH 1/3] hosted-worker: refuse oversized kv PUT before buffering the body (#11332) --- pkgs/id/hosted-worker/src/user-do.ts | 54 +++++++++++++++++++++++- pkgs/id/hosted-worker/test/usage.test.ts | 29 +++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/pkgs/id/hosted-worker/src/user-do.ts b/pkgs/id/hosted-worker/src/user-do.ts index 69cb858c56..0dbdb225ca 100644 --- a/pkgs/id/hosted-worker/src/user-do.ts +++ b/pkgs/id/hosted-worker/src/user-do.ts @@ -60,6 +60,41 @@ function json(body: unknown, status = 200): Response { }); } +function ceilingExceeded(headroom: number): FailClosed { + return new FailClosed( + 413, + "ceiling_exceeded", + `storage ceiling exceeded: value is larger than the ${headroom} bytes of headroom; reads and export remain available`, + ); +} + +/** 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 ""; + const reader = req.body.getReader(); + const decoder = new TextDecoder(); + 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 decoder.decode(bytes); +} + export class UserDO { private state: DOState; private ready: Promise; @@ -145,6 +180,14 @@ export class UserDO { } } + /** The largest value (bytes) a KV PUT may store over `priorBytes` + * of existing data without exceeding the ceiling; null = no ceiling. */ + private kvHeadroom(priorBytes: number): number | null { + const ceiling = this.ceilingBytes(); + if (ceiling === null) return null; + return ceiling - this.usage().storage_bytes + priorBytes; + } + private meta(key: string): string | null { const rows = this.state.storage.sql.exec("SELECT value FROM meta WHERE key = ?", key).toArray(); return rows.length === 0 ? null : String(rows[0].value); @@ -287,11 +330,20 @@ export class UserDO { } const kvMatch = url.pathname.match(/^\/v1\/kv\/([A-Za-z0-9._-]{1,128})$/); if (kvMatch && req.method === "PUT") { - const value = await req.text(); const prior = this.state.storage.sql .exec("SELECT LENGTH(value) AS n FROM kv WHERE key = ?", kvMatch[1]) .toArray(); const priorBytes = prior.length === 0 ? 0 : Number(prior[0].n); + const headroom = this.kvHeadroom(priorBytes); + let value: string | null; + if (headroom === null) { + value = await req.text(); + } else { + const declared = req.headers.get("content-length"); + if (declared !== null && Number(declared) > headroom) throw ceilingExceeded(headroom); + value = await readTextUpTo(req, headroom); + if (value === null) throw ceilingExceeded(headroom); + } this.assertWritable(new TextEncoder().encode(value).byteLength - priorBytes); this.state.storage.sql.exec( "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", diff --git a/pkgs/id/hosted-worker/test/usage.test.ts b/pkgs/id/hosted-worker/test/usage.test.ts index f18f21991c..e1a32f9c9c 100644 --- a/pkgs/id/hosted-worker/test/usage.test.ts +++ b/pkgs/id/hosted-worker/test/usage.test.ts @@ -141,6 +141,35 @@ test("at cap: writes fail closed, reads and export succeed, delete recovers head assert.equal(put3.status, 200, "headroom recovered after delete"); }); +test("kv PUT over headroom is refused early on declared length, and by a capped read when chunked", async () => { + const { doA } = makeDO({ USER_CEILING_BYTES: "10" }); + const declared = await doA.fetch(routed("/v1/kv/big", { method: "PUT", body: "12345678901" })); + assert.equal(declared.status, 413); + assert.equal(((await declared.json()) as { error: string }).error, "ceiling_exceeded"); + + const chunkedBody = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode("12345")); + c.enqueue(new TextEncoder().encode("678901")); + c.close(); + }, + }); + const chunked = await doA.fetch( + routed("/v1/kv/big", { method: "PUT", body: chunkedBody, duplex: "half" } as RequestInit), + ); + assert.equal(chunked.status, 413); + assert.equal(((await chunked.json()) as { error: string }).error, "ceiling_exceeded"); + assert.equal((await getUsage(doA)).storage_bytes, 0, "no refused write is stored"); +}); + +test("kv overwrite headroom counts the prior value", async () => { + const { doA } = makeDO({ USER_CEILING_BYTES: "10" }); + assert.equal((await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "123456" }))).status, 200); + assert.equal((await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "1234567890" }))).status, 200); + assert.equal((await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "12345678901" }))).status, 413); + assert.equal((await getUsage(doA)).storage_bytes, 10); +}); + test("a deduped re-PUT of the same blob does not double-charge", async () => { const { doA } = makeDO({ USER_CEILING_BYTES: "10" }); const blob = new TextEncoder().encode("0123456789"); From cab8f684d188587ecad6235199160ede495880db Mon Sep 17 00:00:00 2001 From: dezren39 Date: Tue, 17 Nov 2026 14:10:42 -0600 Subject: [PATCH 2/3] hosted-worker: kv shrink not refused when usage is over ceiling (#11332) --- pkgs/id/hosted-worker/src/user-do.ts | 9 ++++++--- pkgs/id/hosted-worker/test/usage.test.ts | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/pkgs/id/hosted-worker/src/user-do.ts b/pkgs/id/hosted-worker/src/user-do.ts index 0dbdb225ca..26a2e94d57 100644 --- a/pkgs/id/hosted-worker/src/user-do.ts +++ b/pkgs/id/hosted-worker/src/user-do.ts @@ -180,12 +180,15 @@ export class UserDO { } } - /** The largest value (bytes) a KV PUT may store over `priorBytes` - * of existing data without exceeding the ceiling; null = no ceiling. */ + /** The largest value (bytes) a KV PUT can carry over `priorBytes` + * of existing data without being refused: a value that fits the + * ceiling, or one no larger than what it replaces (shrinking never + * grows storage, even when usage is already over the ceiling). + * null = no ceiling. */ private kvHeadroom(priorBytes: number): number | null { const ceiling = this.ceilingBytes(); if (ceiling === null) return null; - return ceiling - this.usage().storage_bytes + priorBytes; + return Math.max(ceiling - this.usage().storage_bytes + priorBytes, priorBytes); } private meta(key: string): string | null { diff --git a/pkgs/id/hosted-worker/test/usage.test.ts b/pkgs/id/hosted-worker/test/usage.test.ts index e1a32f9c9c..74b7f197bf 100644 --- a/pkgs/id/hosted-worker/test/usage.test.ts +++ b/pkgs/id/hosted-worker/test/usage.test.ts @@ -170,6 +170,20 @@ test("kv overwrite headroom counts the prior value", async () => { assert.equal((await getUsage(doA)).storage_bytes, 10); }); +test("kv shrink is allowed even when usage is already over the ceiling", async () => { + const state = { + id: { name: A }, + storage: { sql: fakeSql() }, + blockConcurrencyWhile: async (fn: () => Promise): Promise => fn(), + }; + const uncapped = new UserDO(state as never, { BLOBS: fakeBucket() } as never); + assert.equal((await uncapped.fetch(routed("/v1/kv/k1", { method: "PUT", body: "1234567890" }))).status, 200); + assert.equal((await uncapped.fetch(routed("/v1/kv/k2", { method: "PUT", body: "1234567890" }))).status, 200); + const capped = new UserDO(state as never, { BLOBS: fakeBucket(), USER_CEILING_BYTES: "5" } as never); + assert.equal((await capped.fetch(routed("/v1/kv/k1", { method: "PUT", body: "123" }))).status, 200, "shrink allowed"); + assert.equal((await capped.fetch(routed("/v1/kv/k1", { method: "PUT", body: "12345678" }))).status, 413, "growth refused"); +}); + test("a deduped re-PUT of the same blob does not double-charge", async () => { const { doA } = makeDO({ USER_CEILING_BYTES: "10" }); const blob = new TextEncoder().encode("0123456789"); From 48878de0142b654c988983b6d6615511818f2497 Mon Sep 17 00:00:00 2001 From: dezren39 Date: Tue, 17 Nov 2026 14:11:00 -0600 Subject: [PATCH 3/3] hosted-worker: revert max() headroom; shrink over cap is refused by assertWritable as before (#11332) --- pkgs/id/hosted-worker/src/user-do.ts | 9 +++------ pkgs/id/hosted-worker/test/usage.test.ts | 14 -------------- 2 files changed, 3 insertions(+), 20 deletions(-) diff --git a/pkgs/id/hosted-worker/src/user-do.ts b/pkgs/id/hosted-worker/src/user-do.ts index 26a2e94d57..bfab8219ab 100644 --- a/pkgs/id/hosted-worker/src/user-do.ts +++ b/pkgs/id/hosted-worker/src/user-do.ts @@ -180,15 +180,12 @@ export class UserDO { } } - /** The largest value (bytes) a KV PUT can carry over `priorBytes` - * of existing data without being refused: a value that fits the - * ceiling, or one no larger than what it replaces (shrinking never - * grows storage, even when usage is already over the ceiling). - * null = no ceiling. */ + /** The largest value (bytes) a KV PUT over `priorBytes` of existing + * data can carry and still pass assertWritable; null = no ceiling. */ private kvHeadroom(priorBytes: number): number | null { const ceiling = this.ceilingBytes(); if (ceiling === null) return null; - return Math.max(ceiling - this.usage().storage_bytes + priorBytes, priorBytes); + return ceiling - this.usage().storage_bytes + priorBytes; } private meta(key: string): string | null { diff --git a/pkgs/id/hosted-worker/test/usage.test.ts b/pkgs/id/hosted-worker/test/usage.test.ts index 74b7f197bf..e1a32f9c9c 100644 --- a/pkgs/id/hosted-worker/test/usage.test.ts +++ b/pkgs/id/hosted-worker/test/usage.test.ts @@ -170,20 +170,6 @@ test("kv overwrite headroom counts the prior value", async () => { assert.equal((await getUsage(doA)).storage_bytes, 10); }); -test("kv shrink is allowed even when usage is already over the ceiling", async () => { - const state = { - id: { name: A }, - storage: { sql: fakeSql() }, - blockConcurrencyWhile: async (fn: () => Promise): Promise => fn(), - }; - const uncapped = new UserDO(state as never, { BLOBS: fakeBucket() } as never); - assert.equal((await uncapped.fetch(routed("/v1/kv/k1", { method: "PUT", body: "1234567890" }))).status, 200); - assert.equal((await uncapped.fetch(routed("/v1/kv/k2", { method: "PUT", body: "1234567890" }))).status, 200); - const capped = new UserDO(state as never, { BLOBS: fakeBucket(), USER_CEILING_BYTES: "5" } as never); - assert.equal((await capped.fetch(routed("/v1/kv/k1", { method: "PUT", body: "123" }))).status, 200, "shrink allowed"); - assert.equal((await capped.fetch(routed("/v1/kv/k1", { method: "PUT", body: "12345678" }))).status, 413, "growth refused"); -}); - test("a deduped re-PUT of the same blob does not double-charge", async () => { const { doA } = makeDO({ USER_CEILING_BYTES: "10" }); const blob = new TextEncoder().encode("0123456789");