diff --git a/pkgs/id/hosted-worker/package.json b/pkgs/id/hosted-worker/package.json index fc17b2d4f..e08e733b8 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 --experimental-transform-types --test test/routing.test.ts test/admission-gate.test.ts test/provisioning.test.ts test/blobs.test.ts test/canonical-cbor.test.ts test/usage.test.ts test/currency.test.ts test/front-door.test.ts test/id-uri-vectors.test.ts test/bridge-blake3.test.ts test/bridge-event.test.ts test/bridge-range.test.ts test/bridge-store.test.ts test/bridge-session.test.ts test/bridge-do.test.ts", + "test": "node --experimental-transform-types --test test/routing.test.ts test/admission-gate.test.ts test/provisioning.test.ts test/provisioning-surface.test.ts test/blobs.test.ts test/canonical-cbor.test.ts test/usage.test.ts test/currency.test.ts test/front-door.test.ts test/id-uri-vectors.test.ts test/bridge-blake3.test.ts test/bridge-event.test.ts test/bridge-range.test.ts test/bridge-store.test.ts test/bridge-session.test.ts test/bridge-do.test.ts", "smoke": "node smoke/smoke.mjs" }, "devDependencies": { diff --git a/pkgs/id/hosted-worker/src/provisioning-surface.ts b/pkgs/id/hosted-worker/src/provisioning-surface.ts new file mode 100644 index 000000000..3f1d48a1f --- /dev/null +++ b/pkgs/id/hosted-worker/src/provisioning-surface.ts @@ -0,0 +1,243 @@ +// Provisioning surface for hosted production enablement (#3403): the +// evidence-producing half of the provisioning gate in +// ./provisioning.ts. The gate is a pure validator — it consumes +// deployed-account evidence and never probes an account itself. This +// module is the prober it presupposes: +// +// - R2 buckets are provisioned through the Cloudflare API route +// with the `cf-r2-jurisdiction` request header — never through +// wrangler, whose `--jurisdiction` flag the #2285 canary showed +// can be silently ignored (it created a default bucket with no +// warning), and never without the header. +// - A bucket's jurisdiction is taken only from the API read-back. +// A jurisdiction-less read sees only default-jurisdiction +// buckets (the canary's jurisdiction-less GET of an eu bucket +// returned "does not exist"), so the read-back probes each +// supported jurisdiction with its header before concluding a +// bucket is unverified. +// - The #2285 canary's results are captured into the gate's +// evidence shape verbatim: only what the canary actually proved +// is recorded, and it is the gate — not this surface — that +// judges it. +// +// Nothing here enables production by itself: `provisionAndValidate` +// returns the gate's validated plan or the gate's refusal, and the +// gate authorizes no deployment. This surface makes no residency +// claim; it records what the account's own API reports. + +import { SUPPORTED_JURISDICTIONS, type Jurisdiction } from "./routing.ts"; +import { + validateEnablement, + type AccountEvidence, + type BucketEvidence, + type EnablementConfig, + type EnablementPlan, + type JurisdictionEvidence, + type SupportState, +} from "./provisioning.ts"; + +/** An operational failure of the provisioning surface itself (the + * API route refused or could not be reached). Distinct from the + * gate's FailClosed refusals: no evidence judgement was reached. */ +export class ProvisioningError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +/** The slice of the Cloudflare API this surface needs. Structural, + * so tests can model the account's observed behaviour (#2285) + * without network access. */ +export interface CloudflareApiClient { + /** Create a bucket through the API route, scoped by the + * jurisdiction header. Resolves with the HTTP status: 2xx created, + * 409 already exists, anything else a failure. */ + createR2Bucket(bucketName: string, jurisdiction: Jurisdiction): Promise<{ status: number }>; + /** Read one bucket back. Without a jurisdiction the read sees + * only default-jurisdiction buckets; with one it sees only that + * jurisdiction's buckets. `jurisdiction` in the result is the + * bucket's API-reported jurisdiction, or null when the response + * carries none. */ + getR2Bucket( + bucketName: string, + jurisdiction?: Jurisdiction, + ): Promise<{ status: number; jurisdiction: string | null }>; +} + +/** Minimal structural fetch shape (the package carries no + * workers-types dependency; the global fetch satisfies this). */ +export type FetchFn = ( + url: string, + init?: { method?: string; headers?: Record; body?: string }, +) => Promise<{ status: number; json(): Promise }>; + +export function createCloudflareApiClient(options: { + accountId: string; + apiToken: string; + fetchFn?: FetchFn; +}): CloudflareApiClient { + const fetchFn: FetchFn = options.fetchFn ?? ((url, init) => fetch(url, init)); + const base = `https://api.cloudflare.com/client/v4/accounts/${options.accountId}/r2/buckets`; + const auth = { authorization: `Bearer ${options.apiToken}` }; + return { + async createR2Bucket(bucketName, jurisdiction) { + const res = await fetchFn(base, { + method: "POST", + headers: { + ...auth, + "content-type": "application/json", + // The verified API route (#2285 mechanic 5): the header is + // what places the bucket; there is no other creation path. + "cf-r2-jurisdiction": jurisdiction, + }, + body: JSON.stringify({ name: bucketName }), + }); + return { status: res.status }; + }, + async getR2Bucket(bucketName, jurisdiction) { + const headers = jurisdiction ? { ...auth, "cf-r2-jurisdiction": jurisdiction } : { ...auth }; + const res = await fetchFn(`${base}/${encodeURIComponent(bucketName)}`, { method: "GET", headers }); + if (res.status !== 200) return { status: res.status, jurisdiction: null }; + const body = (await res.json()) as { result?: { jurisdiction?: unknown } } | null; + const reported = body?.result?.jurisdiction; + return { status: 200, jurisdiction: typeof reported === "string" ? reported : null }; + }, + }; +} + +async function tryGet( + client: CloudflareApiClient, + bucketName: string, + jurisdiction?: Jurisdiction, +): Promise<{ status: number; jurisdiction: string | null } | null> { + try { + return await client.getR2Bucket(bucketName, jurisdiction); + } catch { + // A failed read is not evidence either way; the caller records + // the bucket as unverified and the gate fails closed on it. + return null; + } +} + +/** Read one bucket's actual jurisdiction back from the R2 API. + * Returns the gate's BucketEvidence: `actualJurisdiction` is what + * the API reports ("default" for a bucket outside every supported + * jurisdiction), or null when no read could verify the bucket. */ +export async function readBucketEvidence( + client: CloudflareApiClient, + bucketName: string, +): Promise { + // A jurisdiction-less read sees default-jurisdiction buckets only. + const plain = await tryGet(client, bucketName); + if (plain?.status === 200) { + return { bucketName, actualJurisdiction: plain.jurisdiction ?? "default" }; + } + // Jurisdiction-scoped reads: the header is what makes a bucket in + // that jurisdiction visible at all (#2285), so a 200 here is the + // API attesting the bucket resides in the probed jurisdiction even + // when the response omits the field. + for (const jurisdiction of SUPPORTED_JURISDICTIONS) { + const scoped = await tryGet(client, bucketName, jurisdiction); + if (scoped?.status === 200) { + return { bucketName, actualJurisdiction: scoped.jurisdiction ?? jurisdiction }; + } + } + return { bucketName, actualJurisdiction: null }; +} + +/** Provision one bucket through the verified API route, then read + * it back. Idempotent: a bucket that already exists (409) is read + * back like any other — where it actually resides is the read-back's + * to say, and the gate refuses a mismatch. */ +export async function provisionBucket( + client: CloudflareApiClient, + bucketName: string, + jurisdiction: Jurisdiction, +): Promise { + let status: number; + try { + status = (await client.createR2Bucket(bucketName, jurisdiction)).status; + } catch (e) { + throw new ProvisioningError( + "bucket_provision_failed", + `creating bucket "${bucketName}" through the R2 API route failed: ${e instanceof Error ? e.message : String(e)}`, + ); + } + if ((status < 200 || status >= 300) && status !== 409) { + throw new ProvisioningError( + "bucket_provision_failed", + `creating bucket "${bucketName}" through the R2 API route returned HTTP ${status}; not proceeding`, + ); + } + return readBucketEvidence(client, bucketName); +} + +/** One jurisdiction's outcome from the deployed-account canary + * (#2285 mechanics 1–4 for Durable Objects, plus the deployed + * runtime/generated-types support check). Fields the canary did not + * determine stay absent here and are captured as "unverified". */ +export interface CanaryJurisdictionResult { + jurisdiction: string; + durableObjects?: SupportState; + runtimeTypes?: SupportState; +} + +/** Capture canary results into the gate's evidence shape, verbatim: + * only supported jurisdictions are recorded, and only the states + * the canary actually reported — this surface never upgrades a + * result. */ +export function captureCanaryEvidence( + results: readonly CanaryJurisdictionResult[], +): Partial> { + const captured: Partial> = {}; + for (const result of results) { + if (!(SUPPORTED_JURISDICTIONS as readonly string[]).includes(result.jurisdiction)) continue; + const jurisdiction = result.jurisdiction as Jurisdiction; + captured[jurisdiction] = { + durableObjects: result.durableObjects ?? "unverified", + runtimeTypes: result.runtimeTypes ?? "unverified", + }; + } + return captured; +} + +/** Gather the full deployed-account evidence the gate consumes: + * canary results for the jurisdictions, API read-backs for the + * buckets. */ +export async function gatherAccountEvidence( + client: CloudflareApiClient, + input: { buckets: readonly string[]; canary: readonly CanaryJurisdictionResult[] }, +): Promise { + const buckets: BucketEvidence[] = []; + for (const bucketName of input.buckets) { + buckets.push(await readBucketEvidence(client, bucketName)); + } + return { jurisdictions: captureCanaryEvidence(input.canary), buckets }; +} + +/** The surface end to end: provision the configured bucket through + * the API route, gather the evidence, and invoke the gate before + * any production signup/migration enablement. Returns the gate's + * validated plan; the gate's FailClosed refusal propagates + * unchanged. When the configured jurisdiction is not a supported + * one, no bucket is created — the gate refuses that configuration + * on its own, and provisioning under an invalid jurisdiction would + * be exactly the silent misplacement this gate exists to prevent. */ +export async function provisionAndValidate( + client: CloudflareApiClient, + config: EnablementConfig, + canary: readonly CanaryJurisdictionResult[], +): Promise { + const buckets: BucketEvidence[] = []; + if (config.bucket) { + const configured = config.jurisdiction; + if (configured !== undefined && (SUPPORTED_JURISDICTIONS as readonly string[]).includes(configured)) { + buckets.push(await provisionBucket(client, config.bucket.bucketName, configured as Jurisdiction)); + } else { + buckets.push(await readBucketEvidence(client, config.bucket.bucketName)); + } + } + return validateEnablement(config, { jurisdictions: captureCanaryEvidence(canary), buckets }); +} diff --git a/pkgs/id/hosted-worker/test/provisioning-surface.test.ts b/pkgs/id/hosted-worker/test/provisioning-surface.test.ts new file mode 100644 index 000000000..aa55b140f --- /dev/null +++ b/pkgs/id/hosted-worker/test/provisioning-surface.test.ts @@ -0,0 +1,220 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { FailClosed, type Jurisdiction } from "../src/routing.ts"; +import type { EnablementConfig } from "../src/provisioning.ts"; +import { + captureCanaryEvidence, + createCloudflareApiClient, + gatherAccountEvidence, + provisionAndValidate, + provisionBucket, + readBucketEvidence, + ProvisioningError, + type CloudflareApiClient, +} from "../src/provisioning-surface.ts"; + +// Tests for the #3403 provisioning surface — the evidence-producing +// half of the gate. The fake client models the account behaviour the +// #2285 canary actually observed: a jurisdiction-less GET of a +// jurisdiction-scoped bucket returns 404, a header-scoped GET sees +// only its own jurisdiction's buckets, and bucket creation without +// the API header route is not a thing this surface does. + +interface RecordedCall { + method: "create" | "get"; + bucketName: string; + jurisdiction?: Jurisdiction; +} + +class FakeCloudflare implements CloudflareApiClient { + calls: RecordedCall[] = []; + /** bucket name -> actual jurisdiction; null = default jurisdiction. */ + buckets = new Map(); + createStatus: number | null = null; + failGets = false; + + async createR2Bucket(bucketName: string, jurisdiction: Jurisdiction) { + this.calls.push({ method: "create", bucketName, jurisdiction }); + if (this.createStatus !== null) return { status: this.createStatus }; + if (this.buckets.has(bucketName)) return { status: 409 }; + this.buckets.set(bucketName, jurisdiction); + return { status: 200 }; + } + + async getR2Bucket(bucketName: string, jurisdiction?: Jurisdiction) { + this.calls.push({ method: "get", bucketName, jurisdiction }); + if (this.failGets) throw new Error("network unreachable"); + if (!this.buckets.has(bucketName)) return { status: 404, jurisdiction: null }; + const actual = this.buckets.get(bucketName) ?? null; + if (jurisdiction === undefined) { + // Jurisdiction-less reads see default-jurisdiction buckets only. + if (actual !== null) return { status: 404, jurisdiction: null }; + return { status: 200, jurisdiction: null }; + } + if (actual !== jurisdiction) return { status: 404, jurisdiction: null }; + return { status: 200, jurisdiction: actual }; + } +} + +const EU_CONFIG: EnablementConfig = { + jurisdiction: "eu", + restrictedNamespace: true, + durableObjectBinding: "USERS", + bucket: { binding: "BLOBS_EU", bucketName: "user-blobs-eu", declaredJurisdiction: "eu" }, +}; + +const US_CONFIG: EnablementConfig = { + jurisdiction: "us", + restrictedNamespace: true, + durableObjectBinding: "USERS", + bucket: { binding: "BLOBS_US", bucketName: "user-blobs-us", declaredJurisdiction: "us" }, +}; + +const EU_CANARY = [{ jurisdiction: "eu", durableObjects: "supported", runtimeTypes: "supported" }] as const; + +function refusalCode(fn: () => Promise): Promise { + return fn().then( + () => { + throw new Error("expected a FailClosed refusal, but validation passed"); + }, + (e: unknown) => { + if (e instanceof FailClosed) return e.code; + throw e; + }, + ); +} + +test("provisionBucket creates through the API route with the jurisdiction and returns the read-back", async () => { + const fake = new FakeCloudflare(); + const evidence = await provisionBucket(fake, "user-blobs-eu", "eu"); + assert.deepEqual(evidence, { bucketName: "user-blobs-eu", actualJurisdiction: "eu" }); + assert.deepEqual(fake.calls[0], { method: "create", bucketName: "user-blobs-eu", jurisdiction: "eu" }); +}); + +test("provisionBucket is idempotent: an existing bucket is read back, not recreated or trusted", async () => { + const fake = new FakeCloudflare(); + fake.buckets.set("user-blobs-eu", "eu"); + const evidence = await provisionBucket(fake, "user-blobs-eu", "eu"); + assert.deepEqual(evidence, { bucketName: "user-blobs-eu", actualJurisdiction: "eu" }); +}); + +test("provisionBucket surfaces a hard create failure instead of proceeding", async () => { + const fake = new FakeCloudflare(); + fake.createStatus = 500; + await assert.rejects(provisionBucket(fake, "user-blobs-eu", "eu"), (e: unknown) => { + assert.ok(e instanceof ProvisioningError); + assert.equal(e.code, "bucket_provision_failed"); + return true; + }); + // No read-back was attempted after the failed create. + assert.equal(fake.calls.filter((c) => c.method === "get").length, 0); +}); + +test("readBucketEvidence records a default-jurisdiction bucket as default, never as the claim", async () => { + const fake = new FakeCloudflare(); + fake.buckets.set("user-blobs-eu", null); // exists, but in no jurisdiction + const evidence = await readBucketEvidence(fake, "user-blobs-eu"); + assert.deepEqual(evidence, { bucketName: "user-blobs-eu", actualJurisdiction: "default" }); +}); + +test("readBucketEvidence finds a jurisdiction bucket only through its header-scoped probe (#2285)", async () => { + const fake = new FakeCloudflare(); + fake.buckets.set("user-blobs-eu", "eu"); + const evidence = await readBucketEvidence(fake, "user-blobs-eu"); + assert.equal(evidence.actualJurisdiction, "eu"); + // The jurisdiction-less read came first and missed; an eu-scoped + // read is what found it. + assert.equal(fake.calls[0]?.jurisdiction, undefined); + assert.ok(fake.calls.some((c) => c.method === "get" && c.jurisdiction === "eu")); +}); + +test("readBucketEvidence records an unverifiable bucket as null (missing or unreadable)", async () => { + const missing = new FakeCloudflare(); + assert.equal((await readBucketEvidence(missing, "nope")).actualJurisdiction, null); + const down = new FakeCloudflare(); + down.buckets.set("user-blobs-eu", "eu"); + down.failGets = true; + assert.equal((await readBucketEvidence(down, "user-blobs-eu")).actualJurisdiction, null); +}); + +test("captureCanaryEvidence passes results through verbatim and defaults the undetermined to unverified", () => { + const captured = captureCanaryEvidence([ + { jurisdiction: "eu", durableObjects: "supported", runtimeTypes: "supported" }, + { jurisdiction: "us", durableObjects: "unavailable" }, + { jurisdiction: "apac", durableObjects: "supported", runtimeTypes: "supported" }, + ]); + assert.deepEqual(captured, { + eu: { durableObjects: "supported", runtimeTypes: "supported" }, + us: { durableObjects: "unavailable", runtimeTypes: "unverified" }, + }); +}); + +test("gatherAccountEvidence combines canary capture with bucket read-backs", async () => { + const fake = new FakeCloudflare(); + fake.buckets.set("user-blobs-eu", "eu"); + const evidence = await gatherAccountEvidence(fake, { buckets: ["user-blobs-eu"], canary: EU_CANARY }); + assert.deepEqual(evidence, { + jurisdictions: { eu: { durableObjects: "supported", runtimeTypes: "supported" } }, + buckets: [{ bucketName: "user-blobs-eu", actualJurisdiction: "eu" }], + }); +}); + +test("provisionAndValidate returns the gate's plan on the full verified path", async () => { + const fake = new FakeCloudflare(); + const plan = await provisionAndValidate(fake, EU_CONFIG, EU_CANARY); + assert.deepEqual(plan, { + jurisdiction: "eu", + durableObjectBinding: "USERS", + bucket: { binding: "BLOBS_EU", bucketName: "user-blobs-eu", jurisdiction: "eu" }, + }); + // The bucket was provisioned through the API route on the way. + assert.ok(fake.calls.some((c) => c.method === "create" && c.jurisdiction === "eu")); +}); + +test("provisionAndValidate refuses when the bucket actually resides elsewhere, however it was created", async () => { + const fake = new FakeCloudflare(); + // The bucket already exists in "us"; the eu create 409s, and the + // read-back — not the create or the declared field — decides. + fake.buckets.set("user-blobs-eu", "us"); + assert.equal(await refusalCode(() => provisionAndValidate(fake, EU_CONFIG, EU_CANARY)), "bucket_jurisdiction_mismatch"); +}); + +test("provisionAndValidate refuses on the canary's unavailable jurisdiction (explicit US diagnostic)", async () => { + const fake = new FakeCloudflare(); + const canary = [{ jurisdiction: "us", durableObjects: "unavailable", runtimeTypes: "supported" }] as const; + assert.equal(await refusalCode(() => provisionAndValidate(fake, US_CONFIG, canary)), "jurisdiction_unavailable"); +}); + +test("provisionAndValidate creates nothing under an unsupported jurisdiction", async () => { + const fake = new FakeCloudflare(); + const config: EnablementConfig = { ...EU_CONFIG, jurisdiction: "apac" }; + assert.equal(await refusalCode(() => provisionAndValidate(fake, config, EU_CANARY)), "unsupported_jurisdiction"); + assert.equal(fake.calls.filter((c) => c.method === "create").length, 0); +}); + +test("the API client sends the jurisdiction header on create and reads jurisdiction from the response", async () => { + const seen: { url: string; headers?: Record }[] = []; + const client = createCloudflareApiClient({ + accountId: "acct-1", + apiToken: "token-1", + fetchFn: async (url, init) => { + seen.push({ url, headers: init?.headers }); + return { status: 200, json: async () => ({ success: true, result: { name: "b", jurisdiction: "eu" } }) }; + }, + }); + await client.createR2Bucket("b", "eu"); + assert.equal(seen[0]?.headers?.["cf-r2-jurisdiction"], "eu"); + assert.match(seen[0]?.url ?? "", /\/accounts\/acct-1\/r2\/buckets$/); + const read = await client.getR2Bucket("b", "eu"); + assert.deepEqual(read, { status: 200, jurisdiction: "eu" }); + assert.equal(seen[1]?.headers?.["cf-r2-jurisdiction"], "eu"); +}); + +test("the API client reports a response without a jurisdiction field as null, not as a claim", async () => { + const client = createCloudflareApiClient({ + accountId: "acct-1", + apiToken: "token-1", + fetchFn: async () => ({ status: 200, json: async () => ({ success: true, result: { name: "b" } }) }), + }); + assert.deepEqual(await client.getR2Bucket("b"), { status: 200, jurisdiction: null }); +});