Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkgs/id/hosted-worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
26 changes: 25 additions & 1 deletion pkgs/id/hosted-worker/smoke/smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -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); }
}

Expand Down
26 changes: 26 additions & 0 deletions pkgs/id/hosted-worker/src/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown>;
delete(key: string): Promise<void>;
}

/** 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;
Expand Down
81 changes: 76 additions & 5 deletions pkgs/id/hosted-worker/src/user-do.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -38,7 +38,9 @@ interface DOState {
storage: { sql: SqlStorage };
blockConcurrencyWhile<T>(fn: () => Promise<T>): Promise<T>;
}
interface Env {}
interface Env {
BLOBS?: R2BucketLike;
}

function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
Expand All @@ -51,14 +53,29 @@ export class UserDO {
private state: DOState;
private ready: Promise<void>;

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),
);
});
}

Expand Down Expand Up @@ -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();
Expand Down
145 changes: 145 additions & 0 deletions pkgs/id/hosted-worker/test/blobs.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>[];
return { toArray: () => rows };
}
stmt.run(...(params as never[]));
return { toArray: () => [] as Record<string, unknown>[] };
},
};
}

function fakeBucket() {
const objects = new Map<string, Uint8Array>();
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<typeof fakeBucket>) {
const state = {
id: { name },
storage: { sql: fakeSql() },
blockConcurrencyWhile: async <T,>(fn: () => Promise<T>): Promise<T> => 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<string> {
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);
});
7 changes: 7 additions & 0 deletions pkgs/id/hosted-worker/wrangler.test.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
7 changes: 7 additions & 0 deletions pkgs/id/hosted-worker/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"