From 7f25162068ca3666c87fe9c67947f9eaac64c19b Mon Sep 17 00:00:00 2001 From: fleet lane code-b Date: Sat, 14 Nov 2026 10:40:51 -0600 Subject: [PATCH] feat(id): hosted Worker slice A - R2 blobs with DO reference indirection (#9954) Blob bytes live only in R2, content-addressed by sha256; the per-user DOs new SQLite blobs table (hash, size, owner, created_at) is the sole access path, so a hash with no reference row is invisible to that user even when the bytes exist for someone else. PUT dedups identical bytes across users (each uploader gets their own reference); DELETE removes only the callers reference - shared byte reclamation is GC work, never a delete side effect. Bucket binding is chosen through routing.ts blobsBindingFor (the #2283 seam), failing closed when unconfigured. Local emulation only; the #2285/#3403 account gates are untouched. Unit tests (real SQLite) + workerd smoke both prove round-trip and isolation. --- pkgs/id/hosted-worker/package.json | 2 +- pkgs/id/hosted-worker/smoke/smoke.mjs | 26 +++- pkgs/id/hosted-worker/src/routing.ts | 26 ++++ pkgs/id/hosted-worker/src/user-do.ts | 81 ++++++++++++- pkgs/id/hosted-worker/test/blobs.test.ts | 145 +++++++++++++++++++++++ pkgs/id/hosted-worker/wrangler.test.toml | 7 ++ pkgs/id/hosted-worker/wrangler.toml | 7 ++ 7 files changed, 287 insertions(+), 7 deletions(-) create mode 100644 pkgs/id/hosted-worker/test/blobs.test.ts diff --git a/pkgs/id/hosted-worker/package.json b/pkgs/id/hosted-worker/package.json index ae2e7cf2bd..1e5c639db9 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": "node --test test/routing.test.ts test/blobs.test.ts", "smoke": "node smoke/smoke.mjs" }, "devDependencies": { diff --git a/pkgs/id/hosted-worker/smoke/smoke.mjs b/pkgs/id/hosted-worker/smoke/smoke.mjs index 0b230e49ed..333c11a473 100644 --- a/pkgs/id/hosted-worker/smoke/smoke.mjs +++ b/pkgs/id/hosted-worker/smoke/smoke.mjs @@ -79,7 +79,7 @@ async function waitUp(port, tries) { check("harness + DO start, lazy create", up); let r = await fetch(base + q(A, A, "us")); let body = await r.json(); - check("state reports binding, jurisdiction, schema v1", body.binding_id === A && body.jurisdiction === "us" && body.schema_version === 1, JSON.stringify(body)); + check("state reports binding, jurisdiction, schema v2", body.binding_id === A && body.jurisdiction === "us" && body.schema_version === 2, JSON.stringify(body)); const many = await Promise.all(Array.from({ length: 8 }, () => fetch(base + q("cccccccccccccccccccccccccccccccc", "cccccccccccccccccccccccccccccccc", "eu")))); check("concurrent first requests all 200 (idempotent bootstrap)", many.every((x) => x.status === 200)); @@ -97,6 +97,30 @@ async function waitUp(port, tries) { check("mismatched jurisdiction on bound object -> 409", r.status === 409); r = await fetch(base + q(A, A, "us", "&routed=no")); check("unrouted request -> 403", r.status === 403); + + // Slice A (#9954): blob round-trip via reference indirection, + // user isolation by hash, dedup, reference-only delete. + const blob = (name, binding, j, hash) => "/v1/blobs" + (hash ? "/" + hash : "") + "?name=" + name + "&binding=" + binding + "&jurisdiction=" + j; + const bytes = "hosted blob bytes"; + r = await fetch(base + blob(A, A, "us"), { method: "PUT", body: bytes }); + const putBody = await r.json(); + check("PUT blob on A", r.status === 200 && putBody.size === bytes.length && /^[0-9a-f]{64}$/.test(putBody.hash), JSON.stringify(putBody)); + const hash = putBody.hash; + r = await fetch(base + blob(A, A, "us", hash)); + check("GET blob on A round-trips", r.status === 200 && (await r.text()) === bytes); + r = await fetch(base + blob(B, B, "us", hash)); + check("B cannot read A's blob by hash (isolation)", r.status === 404); + r = await fetch(base + blob(B, B, "us"), { method: "PUT", body: bytes }); + const putB = await r.json(); + check("PUT same bytes on B dedups to the same hash", r.status === 200 && putB.hash === hash && putB.deduped === true, JSON.stringify(putB)); + r = await fetch(base + blob(B, B, "us", hash)); + check("GET blob on B via its own reference", r.status === 200 && (await r.text()) === bytes); + r = await fetch(base + blob(A, A, "us", hash), { method: "DELETE" }); + check("DELETE blob reference on A", r.status === 200); + r = await fetch(base + blob(A, A, "us", hash)); + check("A can no longer read after delete", r.status === 404); + r = await fetch(base + blob(B, B, "us", hash)); + check("B still reads after A's delete (shared bytes kept)", r.status === 200); } finally { await stopDev(dev); } } diff --git a/pkgs/id/hosted-worker/src/routing.ts b/pkgs/id/hosted-worker/src/routing.ts index dab3612384..a43a4a413d 100644 --- a/pkgs/id/hosted-worker/src/routing.ts +++ b/pkgs/id/hosted-worker/src/routing.ts @@ -46,6 +46,32 @@ export function parseJurisdiction(raw: string | null): Jurisdiction { return raw as Jurisdiction; } +/** Minimal structural shape of an R2 bucket binding (the package + * carries no workers-types dependency; workerd satisfies this). */ +export interface R2BucketLike { + head(key: string): Promise<{ size: number } | null>; + get(key: string): Promise<{ body: ReadableStream; size: number } | null>; + put(key: string, value: ArrayBuffer | Uint8Array): Promise; + delete(key: string): Promise; +} + +/** The #2283 jurisdiction seam for blob storage: the bucket binding + * is chosen per jurisdiction HERE, in the routing module, never + * inline at a call site. Today every supported jurisdiction resolves + * to the package's single local binding (BLOBS); per-jurisdiction + * production buckets plug in at this one point when the #3403 + * provisioning gate lands. A missing binding fails closed. */ +export function blobsBindingFor( + env: { BLOBS?: R2BucketLike }, + jurisdiction: Jurisdiction, +): R2BucketLike { + void jurisdiction; + if (!env.BLOBS) { + throw new FailClosed(503, "blobs_unavailable", "no blob bucket binding is configured; failing closed"); + } + return env.BLOBS; +} + export interface ObjectNamespaceLike { jurisdiction(j: string): ObjectNamespaceLike; idFromName(name: string): unknown; diff --git a/pkgs/id/hosted-worker/src/user-do.ts b/pkgs/id/hosted-worker/src/user-do.ts index fab36fa3d2..3e63cad628 100644 --- a/pkgs/id/hosted-worker/src/user-do.ts +++ b/pkgs/id/hosted-worker/src/user-do.ts @@ -22,9 +22,9 @@ // equals the routed identity — a mismatch fails closed. // Any guard failure returns before side effects. -import { FailClosed, parseBindingId, parseJurisdiction } from "./routing.ts"; +import { FailClosed, blobsBindingFor, parseBindingId, parseJurisdiction, type Jurisdiction, type R2BucketLike } from "./routing.ts"; -export const SCHEMA_VERSION = 1; +export const SCHEMA_VERSION = 2; export const HDR_BINDING = "x-hosted-binding-id"; export const HDR_JURISDICTION = "x-hosted-jurisdiction"; @@ -38,7 +38,9 @@ interface DOState { storage: { sql: SqlStorage }; blockConcurrencyWhile(fn: () => Promise): Promise; } -interface Env {} +interface Env { + BLOBS?: R2BucketLike; +} function json(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { @@ -51,14 +53,29 @@ export class UserDO { private state: DOState; private ready: Promise; - constructor(state: DOState, _env: Env) { + private env: Env; + + constructor(state: DOState, env: Env) { this.state = state; + this.env = env; // Versioned, idempotent schema bootstrap before serving. this.ready = state.blockConcurrencyWhile(async () => { const sql = this.state.storage.sql; sql.exec("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); sql.exec("CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); - sql.exec("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)", "schema_version", String(SCHEMA_VERSION)); + // Slice A (#9954): blob references. Blob BYTES live only in + // R2, content-addressed by sha256; this table is the sole + // access path — a hash with no row here is invisible to this + // user, even if the bytes exist in the bucket for someone + // else. + sql.exec( + "CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, size INTEGER NOT NULL, owner TEXT NOT NULL, created_at TEXT NOT NULL)", + ); + sql.exec( + "INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + "schema_version", + String(SCHEMA_VERSION), + ); }); } @@ -117,6 +134,60 @@ export class UserDO { object_name: this.state.id.name ?? null, }); } + 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()); + 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); + // Content-addressed dedup: identical bytes are stored + // once, whoever uploads them; the reference row below is + // what grants THIS user access. + const existing = await bucket.head(hash); + if (!existing) await bucket.put(hash, bytes); + this.state.storage.sql.exec( + "INSERT INTO blobs (hash, size, owner, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING", + hash, + bytes.byteLength, + bindingId, + new Date().toISOString(), + ); + return json({ hash, size: bytes.byteLength, stored: true, deduped: !!existing }); + } + if (blobHashMatch && req.method === "GET") { + const hash = blobHashMatch[1]; + const rows = this.state.storage.sql + .exec("SELECT size FROM blobs WHERE hash = ?", hash) + .toArray(); + if (rows.length === 0) return json({ error: "not_found" }, 404); + const bucket = blobsBindingFor(this.env, jurisdiction as Jurisdiction); + const obj = await bucket.get(hash); + if (!obj) return json({ error: "not_found" }, 404); + return new Response(obj.body, { + status: 200, + headers: { + "content-type": "application/octet-stream", + "x-blob-hash": hash, + "x-blob-size": String(rows[0].size), + }, + }); + } + if (blobHashMatch && req.method === "DELETE") { + const hash = blobHashMatch[1]; + const rows = this.state.storage.sql + .exec("SELECT hash FROM blobs WHERE hash = ?", hash) + .toArray(); + if (rows.length === 0) return json({ error: "not_found" }, 404); + this.state.storage.sql.exec("DELETE FROM blobs WHERE hash = ?", hash); + // The reference is gone, so this user can no longer reach + // the bytes. The R2 object itself is deliberately NOT + // deleted here: identical content may be referenced by + // other users' objects, whose references this DO cannot + // see, and deleting shared bytes would break their reads. + // Byte reclamation is the GC work (#9935 family), never a + // side effect of one user's delete. + return json({ hash, deleted: true }); + } const kvMatch = url.pathname.match(/^\/v1\/kv\/([A-Za-z0-9._-]{1,128})$/); if (kvMatch && req.method === "PUT") { const value = await req.text(); diff --git a/pkgs/id/hosted-worker/test/blobs.test.ts b/pkgs/id/hosted-worker/test/blobs.test.ts new file mode 100644 index 0000000000..6b87854693 --- /dev/null +++ b/pkgs/id/hosted-worker/test/blobs.test.ts @@ -0,0 +1,145 @@ +// Slice A of #3811 (#9954): blob round-trip via reference +// indirection and user isolation, proven against the real UserDO +// class with an in-memory SQLite (node:sqlite) behind its SQL +// interface and an in-memory bucket behind the R2 interface. The +// workerd-level proof (real R2 emulation) lives in smoke/smoke.mjs. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DatabaseSync } from "node:sqlite"; +import { UserDO, HDR_BINDING, HDR_JURISDICTION, HDR_ROUTED } from "../src/user-do.ts"; + +const A = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const B = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + +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 { + objects, + async head(key: string) { + const v = objects.get(key); + return v ? { size: v.byteLength } : null; + }, + async get(key: string) { + const v = objects.get(key); + if (!v) return null; + return { + size: v.byteLength, + body: new ReadableStream({ + start(c) { + c.enqueue(v); + c.close(); + }, + }), + }; + }, + async put(key: string, value: ArrayBuffer | Uint8Array) { + objects.set(key, value instanceof Uint8Array ? value : new Uint8Array(value)); + }, + async delete(key: string) { + objects.delete(key); + }, + }; +} + +function makeDO(name: string, bucket: ReturnType) { + const state = { + id: { name }, + storage: { sql: fakeSql() }, + blockConcurrencyWhile: async (fn: () => Promise): Promise => fn(), + }; + return new UserDO(state as never, { BLOBS: bucket } as never); +} + +function routed(path: string, binding: string, init: RequestInit = {}): Request { + const headers = new Headers(init.headers); + headers.set(HDR_BINDING, binding); + headers.set(HDR_JURISDICTION, "us"); + headers.set(HDR_ROUTED, "restricted"); + return new Request("https://do" + path, { ...init, headers }); +} + +async function sha256Hex(bytes: Uint8Array): Promise { + const d = await crypto.subtle.digest("SHA-256", bytes as BufferSource); + return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +test("blob round-trip via reference indirection", async () => { + const bucket = fakeBucket(); + const doA = makeDO(A, bucket); + const bytes = new TextEncoder().encode("hello hosted world"); + const put = await doA.fetch(routed("/v1/blobs", A, { method: "PUT", body: bytes })); + assert.equal(put.status, 200); + const putBody = (await put.json()) as { hash: string; size: number; deduped: boolean }; + assert.equal(putBody.hash, await sha256Hex(bytes)); + assert.equal(putBody.size, bytes.byteLength); + assert.equal(putBody.deduped, false); + assert.equal(bucket.objects.size, 1); + + const get = await doA.fetch(routed("/v1/blobs/" + putBody.hash, A)); + assert.equal(get.status, 200); + assert.equal(get.headers.get("x-blob-size"), String(bytes.byteLength)); + assert.deepEqual(new Uint8Array(await get.arrayBuffer()), bytes); +}); + +test("user B cannot read user A's blob by hash; dedup grants B its own reference", async () => { + const bucket = fakeBucket(); + const doA = makeDO(A, bucket); + const doB = makeDO(B, bucket); + const bytes = new TextEncoder().encode("shared content"); + const put = await doA.fetch(routed("/v1/blobs", A, { method: "PUT", body: bytes })); + const { hash } = (await put.json()) as { hash: string }; + + const stolen = await doB.fetch(routed("/v1/blobs/" + hash, B)); + assert.equal(stolen.status, 404, "B has no reference row, so A's blob is invisible by hash"); + + const putB = await doB.fetch(routed("/v1/blobs", B, { method: "PUT", body: bytes })); + const putBBody = (await putB.json()) as { hash: string; deduped: boolean }; + assert.equal(putBBody.hash, hash); + assert.equal(putBBody.deduped, true, "identical bytes are stored once"); + assert.equal(bucket.objects.size, 1); + const getB = await doB.fetch(routed("/v1/blobs/" + hash, B)); + assert.equal(getB.status, 200, "B's own reference makes the blob readable for B"); +}); + +test("delete removes only the caller's reference; shared bytes survive", async () => { + const bucket = fakeBucket(); + const doA = makeDO(A, bucket); + const doB = makeDO(B, bucket); + const bytes = new TextEncoder().encode("delete me not"); + const { hash } = (await (await doA.fetch(routed("/v1/blobs", A, { method: "PUT", body: bytes }))).json()) as { hash: string }; + await doB.fetch(routed("/v1/blobs", B, { method: "PUT", body: bytes })); + + const del = await doA.fetch(routed("/v1/blobs/" + hash, A, { method: "DELETE" })); + assert.equal(del.status, 200); + assert.equal((await doA.fetch(routed("/v1/blobs/" + hash, A))).status, 404); + assert.equal((await doB.fetch(routed("/v1/blobs/" + hash, B))).status, 200, "B's read is unaffected by A's delete"); + assert.equal(bucket.objects.size, 1, "byte reclamation is GC's job, not delete's"); + assert.equal((await doA.fetch(routed("/v1/blobs/" + hash, A, { method: "DELETE" }))).status, 404); +}); + +test("blob routes stay behind the identity guard; schema is v2", async () => { + const bucket = fakeBucket(); + const doA = makeDO(A, bucket); + const unrouted = new Request("https://do/v1/blobs", { method: "PUT", body: "x" }); + assert.equal((await doA.fetch(unrouted)).status, 403); + const state = await doA.fetch(routed("/v1/state", A)); + const body = (await state.json()) as { schema_version: number }; + assert.equal(body.schema_version, 2); + const badHash = await doA.fetch(routed("/v1/blobs/not-a-hash", A)); + assert.equal(badHash.status, 404); +}); diff --git a/pkgs/id/hosted-worker/wrangler.test.toml b/pkgs/id/hosted-worker/wrangler.test.toml index d8d4897a7e..76b9aefd62 100644 --- a/pkgs/id/hosted-worker/wrangler.test.toml +++ b/pkgs/id/hosted-worker/wrangler.test.toml @@ -16,3 +16,10 @@ class_name = "UserDO" [[migrations]] tag = "v1" new_sqlite_classes = ["UserDO"] + +# Slice A of #3811 (#9954): content-addressed blob bytes. Local +# emulation only — no production bucket is provisioned by this +# config (account gates #2285 / #3403 stay untouched). +[[r2_buckets]] +binding = "BLOBS" +bucket_name = "id-hosted-blobs-test" diff --git a/pkgs/id/hosted-worker/wrangler.toml b/pkgs/id/hosted-worker/wrangler.toml index d31244f128..28697fd892 100644 --- a/pkgs/id/hosted-worker/wrangler.toml +++ b/pkgs/id/hosted-worker/wrangler.toml @@ -13,3 +13,10 @@ class_name = "UserDO" [[migrations]] tag = "v1" new_sqlite_classes = ["UserDO"] + +# Slice A of #3811 (#9954): content-addressed blob bytes. Local +# emulation only — no production bucket is provisioned by this +# config (account gates #2285 / #3403 stay untouched). +[[r2_buckets]] +binding = "BLOBS" +bucket_name = "id-hosted-blobs"