From 972ae2e46c0ad9c43c172570d7389a7722b85d9b Mon Sep 17 00:00:00 2001 From: felix Date: Tue, 24 Nov 2026 13:08:20 +0000 Subject: [PATCH 1/2] feat(id): TenantOpsDO provisioning state machine (E2 of #9083, #12797) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements design §4 on the E1 baseline: one TenantOpsDO per tenant keyed by binding_id, driving the tenant_db row through requested → db_creating → db_ready → active, with suspension, export-only and two-phase deletion (revoke credentials, cooling-off window, drop, tombstone). Creation is intent-first: the deterministic request id is a pure function of the tenant id, the row records the intent before the provider call, and retries adopt the database the intent already made — concurrent sign-ups create exactly one database (test proves it against the real E1 schema). Every transition checks the §4 actor (owner = the bound binding, operator, platform, abuse/ceiling triggers) on internal headers and fails closed. The Turso management API is a provider seam (idempotent create / find / drop); no provider configured fails closed. Credential issuance stays E4; this slice only revokes on deletion, as §4 step 10 requires. --- pkgs/id/hosted-worker/package.json | 2 +- pkgs/id/hosted-worker/src/tenant-ops.ts | 756 ++++++++++++++++++ pkgs/id/hosted-worker/src/worker.ts | 5 + pkgs/id/hosted-worker/test/tenant-ops.test.ts | 538 +++++++++++++ pkgs/id/hosted-worker/wrangler.toml | 11 + 5 files changed, 1311 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/hosted-worker/src/tenant-ops.ts create mode 100644 pkgs/id/hosted-worker/test/tenant-ops.test.ts diff --git a/pkgs/id/hosted-worker/package.json b/pkgs/id/hosted-worker/package.json index cfb3f90f83..21a8c562a9 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/provisioning-surface.test.ts test/enablement.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/tenancy-schema.test.ts test/export.test.ts test/routing-boundary.test.ts test/migration-control.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/enablement.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/tenancy-schema.test.ts test/tenant-ops.test.ts test/export.test.ts test/routing-boundary.test.ts test/migration-control.test.ts", "smoke": "node smoke/smoke.mjs" }, "devDependencies": { diff --git a/pkgs/id/hosted-worker/src/tenant-ops.ts b/pkgs/id/hosted-worker/src/tenant-ops.ts new file mode 100644 index 0000000000..518a234c77 --- /dev/null +++ b/pkgs/id/hosted-worker/src/tenant-ops.ts @@ -0,0 +1,756 @@ +// TenantOpsDO — the provisioning state machine for one tenant +// (component E2 of #9083, issue #12797). +// +// Design record: doc/2026-11-17T16-55-00Z_design_hosted-tenancy-architecture +// section 3 (the DO inventory: one TenantOpsDO per tenant, keyed by +// binding_id, created lazily; "the provisioning state machine (§4): +// serialised transitions, idempotent external effects, +// retry/compensation") and section 4 (the provisioning lifecycle this +// module implements, step for step). The registry row it drives is +// the E1 baseline (tenancy/migrations/0001_tenancy_baseline.sql, +// #12796): `tenant_db`, one row per tenant, tenant_id = binding_id. +// +// requested ──► db_creating ──► db_ready ──► active +// │ │ │ │ +// │ └──► failed ◄───┘ ├──► suspended ──► active +// └──► failed (validation) ├──► export_only ──► deleting +// └──► deleting ──► deleted +// +// (failed is also reachable from db_creating on a permanent provider +// failure; the diagram's failed edges are drawn from requested and +// db_ready's predecessor states — §4 step 4: creation is "retried +// with the same request id until the row is db_ready or failed".) +// +// The rules that make it defensible, and where they live below: +// +// - The row is the record; the object is the lock. Every route runs +// inside a per-object serialisation gate, so two concurrent +// sign-ups for one binding cannot interleave a transition, and +// the provider seam below is only ever called from inside the +// gate. +// - Creation is intent-first. The deterministic request id +// (provisioningRequestId) is a pure function of the tenant id, +// and the intent (request id, jurisdiction, tenant_id) is +// persisted on the row (state db_creating) BEFORE the provider +// call, so a retry after a crash adopts the existing database +// instead of creating a second one. +// - Only the actors §4 names may perform each step. The actor +// arrives on internal headers set by the tenancy Worker after +// authentication — the same trust posture as the front door's +// routing context (never trusted from a client) — and every +// transition checks the role (and, for owner, that the actor IS +// this object's binding) before it touches the row. +// - Deletion is two-phase (§4 step 10): credential revocation +// first (at deleting), then — after the cooling-off window — +// the drop, then the tombstone. A half-deleted tenant whose +// token still works is the failure this ordering prevents; a +// tenant stuck in deleting has no working credentials, which is +// the safe half-state. +// - Suspension must not look like loss: the state route answers +// in every state, including suspended and export_only. +// +// Seams, stated plainly: +// - The tenancy SQL handle is the object's SQLite storage with +// the tenancy migrations applied (the scaffold's local model of +// the central tenancy DB). The E6 store adapter (#12799's line) +// is where a Turso-over-HTTP handle plugs in; the machine does +// not care which side of the seam it is on. +// - The Turso management API is the TenantDatabaseProvider +// interface. The platform credential that a production provider +// would hold never leaves the Worker and is referenced by name +// only; with no provider configured, provisioning and database +// drops fail closed rather than pretending. +// - Credential ISSUANCE (§4 step 6) is E4, not this slice. This +// slice revokes credential metadata on deletion because §4 +// step 10 names revocation as deletion's first phase; it mints +// nothing. + +import { FailClosed, parseBindingId, parseJurisdiction, type Jurisdiction } from "./routing.ts"; + +export const TENANT_STATES = [ + "requested", + "db_creating", + "db_ready", + "active", + "suspended", + "export_only", + "deleting", + "deleted", + "failed", +] as const; +export type TenantState = (typeof TENANT_STATES)[number]; + +export const PARTICIPANT_KINDS = ["user_hosted", "user_native", "self_hosted_node", "public"] as const; +export type ParticipantKind = (typeof PARTICIPANT_KINDS)[number]; + +/** Internal headers, set by the tenancy Worker after it has + * authenticated the caller — the ops analogue of user-do.ts's + * routing context. Never trusted from a client. */ +export const HDR_ACTOR_ROLE = "x-tenancy-actor-role"; +export const HDR_ACTOR_ID = "x-tenancy-actor-id"; +export const HDR_TRIGGER = "x-tenancy-trigger"; + +/** §4's actors. owner = the bound binding (the account holder); + * operator = the operator role; platform = TenantOpsDO itself, + * holding the platform management credential; trigger = an + * automated trigger §4 names (abuse / ceiling). */ +export type ActorRole = "owner" | "operator" | "platform" | "trigger"; +export interface OpsActor { + role: ActorRole; + /** owner: the binding_id. operator: the operator's id. + * platform: "tenant-ops". trigger: the trigger name. */ + id: string; +} + +export interface TenantDatabaseHandle { + dbId: string; + dbUrl: string; +} + +/** A provider failure. `retryable` distinguishes a transient + * provider fault (retry with the same request id) from a permanent + * refusal (the tenant fails, with compensation). Errors that are + * not ProviderErrors are treated as retryable: an unknown fault + * must not fail a tenant permanently on a guess. */ +export class ProviderError extends Error { + readonly retryable: boolean; + constructor(message: string, retryable: boolean) { + super(message); + this.name = "ProviderError"; + this.retryable = retryable; + } +} + +/** The platform's database provider (the Turso management API in + * production). Every operation is idempotent, because the state + * machine retries: createDatabase under a request id that already + * has a database returns THAT database; dropDatabase of a missing + * database is a no-op success. */ +export interface TenantDatabaseProvider { + createDatabase(intent: { + requestId: string; + tenantId: string; + jurisdiction: Jurisdiction; + }): Promise; + /** The database created under an intent, if one exists. This is + * the adoption lookup: after a crash or a lost response, the + * machine finds the database its intent already made. */ + findDatabase(requestId: string): Promise; + dropDatabase(dbId: string): Promise; +} + +/** The deterministic provisioning request id for a tenant. Pure in + * the tenant id, so the intent needs no storage of its own: any + * retry, in any process, recomputes the same id and the provider + * call under it adopts rather than duplicates (§4: "retried with + * the same request id"). */ +export function provisioningRequestId(tenantId: string): string { + return `tenant-db:${tenantId}`; +} + +/** Bounded in-call create attempts. A retryable failure that + * outlasts them leaves the row db_creating — never failed on a + * transient fault — and the next provision call continues with the + * same request id. */ +export const MAX_CREATE_ATTEMPTS = 3; + +/** Default cooling-off window before a deletion completes (§4 + * step 10 names the window, not its length; the deployment may + * override it with TENANT_DELETION_COOLING_OFF_MS). */ +export const DEFAULT_COOLING_OFF_MS = 24 * 60 * 60 * 1000; + +interface SqlStorage { + exec(query: string, ...params: unknown[]): { toArray(): Record[] }; +} +interface DOState { + id: { name?: string; jurisdiction?: string }; + storage: { sql: SqlStorage }; + blockConcurrencyWhile(fn: () => Promise): Promise; +} +interface Env { + TENANT_DB_PROVIDER?: TenantDatabaseProvider; + TENANT_DELETION_COOLING_OFF_MS?: string; +} + +interface TenantRow { + tenant_id: string; + participant_kind: string; + turso_db_id: string | null; + turso_db_url: string | null; + jurisdiction: string; + backend: string; + state: TenantState; + schema_version: number; + created_at: string; + deleted_at: string | null; +} + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +} + +function rowView(row: TenantRow): Record { + return { + tenant_id: row.tenant_id, + state: row.state, + participant_kind: row.participant_kind, + jurisdiction: row.jurisdiction, + backend: row.backend, + turso_db_id: row.turso_db_id, + turso_db_url: row.turso_db_url, + schema_version: row.schema_version, + created_at: row.created_at, + deleted_at: row.deleted_at, + }; +} + +export class TenantOpsDO { + private state: DOState; + private env: Env; + private ready: Promise; + private gate: Promise = Promise.resolve(); + /** The tenant this object serves: its name is the binding_id + * (§3: keyed by binding_id). Null when the name is not a minted + * binding id — every route then fails closed. */ + private tenantId: string | null; + private schemaPresent = false; + + constructor(state: DOState, env: Env) { + this.state = state; + this.env = env; + try { + this.tenantId = parseBindingId(state.id.name ?? null); + } catch { + this.tenantId = null; + } + // The object's own journal. The tenancy tables are NOT created + // here: they belong to the tenancy migrations, applied to this + // storage by the migration runner (in tests, by the harness), + // and a missing tenancy schema fails closed below rather than + // being silently improvised. + this.ready = state.blockConcurrencyWhile(async () => { + const sql = this.state.storage.sql; + sql.exec( + "CREATE TABLE IF NOT EXISTS ops_meta (name TEXT PRIMARY KEY, value TEXT NOT NULL)", + ); + sql.exec( + "CREATE TABLE IF NOT EXISTS ops_journal (seq INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, event TEXT NOT NULL, from_state TEXT, to_state TEXT, actor_role TEXT NOT NULL, actor_id TEXT NOT NULL, detail TEXT)", + ); + const found = sql + .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tenant_db'") + .toArray(); + this.schemaPresent = found.length > 0; + }); + } + + // -- plumbing ---------------------------------------------------- + + private sql(): SqlStorage { + return this.state.storage.sql; + } + + /** The serialisation gate (§3/§4: "the object is the lock"). + * Every route runs inside it, so transitions for one tenant can + * never interleave — including across the provider call, which is + * exactly where a second sign-up would otherwise slip in. */ + private async serialized(fn: () => Promise): Promise { + let release!: () => void; + const next = new Promise((resolve) => { + release = resolve; + }); + const prev = this.gate; + this.gate = next; + await prev; + try { + return await fn(); + } finally { + release(); + } + } + + private meta(name: string): string | null { + const rows = this.sql().exec("SELECT value FROM ops_meta WHERE name = ?", name).toArray(); + return rows.length > 0 ? String(rows[0].value) : null; + } + + private setMeta(name: string, value: string): void { + this.sql().exec( + "INSERT INTO ops_meta (name, value) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET value = excluded.value", + name, + value, + ); + } + + private journal( + at: string, + event: string, + from: TenantState | null, + to: TenantState | null, + actor: OpsActor, + detail?: Record, + ): void { + this.sql().exec( + "INSERT INTO ops_journal (at, event, from_state, to_state, actor_role, actor_id, detail) VALUES (?, ?, ?, ?, ?, ?, ?)", + at, + event, + from, + to, + actor.role, + actor.id, + detail === undefined ? null : JSON.stringify(detail), + ); + } + + private row(): TenantRow | null { + const rows = this.sql() + .exec("SELECT * FROM tenant_db WHERE tenant_id = ?", this.tenantId) + .toArray(); + return rows.length > 0 ? (rows[0] as unknown as TenantRow) : null; + } + + private setState(row: TenantRow, to: TenantState, extra: Record = {}): TenantRow { + const sets = ["state = ?"]; + const params: unknown[] = [to]; + for (const [column, value] of Object.entries(extra)) { + sets.push(`${column} = ?`); + params.push(value); + } + params.push(row.tenant_id); + this.sql().exec(`UPDATE tenant_db SET ${sets.join(", ")} WHERE tenant_id = ?`, ...params); + return { ...row, ...extra, state: to }; + } + + private actor(req: Request): OpsActor { + const role = req.headers.get(HDR_ACTOR_ROLE); + const id = req.headers.get(HDR_ACTOR_ID); + if (role === null || id === null || id === "") { + throw new FailClosed(401, "missing_actor", "no authenticated actor on this request; failing closed"); + } + if (role === "owner" || role === "operator" || role === "platform") { + return { role, id }; + } + if (role === "trigger") { + const trigger = req.headers.get(HDR_TRIGGER); + if (trigger !== "abuse" && trigger !== "ceiling") { + throw new FailClosed(401, "invalid_actor", "a trigger actor must name a trigger §4 names (abuse | ceiling)"); + } + return { role, id: trigger }; + } + throw new FailClosed(401, "invalid_actor", `unknown actor role ${JSON.stringify(role)}; failing closed`); + } + + /** The §4 role check. `owner` must be THIS tenant's binding — + * an owner of some other binding is not an actor here at all. */ + private requireActor(actor: OpsActor, allowed: ActorRole[], step: string): void { + if (!allowed.includes(actor.role)) { + throw new FailClosed( + 403, + "actor_not_permitted", + `${step}: §4 does not name the ${actor.role} actor for this step; failing closed`, + ); + } + if (actor.role === "owner" && actor.id !== this.tenantId) { + throw new FailClosed( + 403, + "actor_not_permitted", + `${step}: the owner actor is not this tenant's binding; failing closed`, + ); + } + } + + private requireRow(step: string): TenantRow { + const row = this.row(); + if (row === null) { + throw new FailClosed(404, "tenant_not_requested", `${step}: no tenant row exists for this binding`); + } + return row; + } + + private requireState(row: TenantRow, states: TenantState[], step: string): void { + if (!states.includes(row.state)) { + throw new FailClosed( + 409, + "invalid_transition", + `${step}: tenant is ${row.state}; §4 allows this step only from ${states.join(" | ")}`, + ); + } + } + + private provider(step: string): TenantDatabaseProvider { + const provider = this.env.TENANT_DB_PROVIDER; + if (!provider) { + throw new FailClosed( + 503, + "provider_unavailable", + `${step}: no database provider is configured; the platform credential never leaves the Worker and none is bound here — failing closed`, + ); + } + return provider; + } + + private coolingOffMs(): number { + const raw = this.env.TENANT_DELETION_COOLING_OFF_MS; + if (raw === undefined || raw === "") return DEFAULT_COOLING_OFF_MS; + const n = Number(raw); + if (!Number.isInteger(n) || n < 0) { + throw new FailClosed( + 500, + "cooling_off_misconfigured", + "TENANT_DELETION_COOLING_OFF_MS is not a non-negative integer; deletion fails closed", + ); + } + return n; + } + + private async body(req: Request): Promise> { + const text = await req.text(); + if (text === "") return {}; + try { + const parsed: unknown = JSON.parse(text); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new FailClosed(400, "invalid_body", "request body must be a JSON object"); + } + return parsed as Record; + } catch (e) { + if (e instanceof FailClosed) throw e; + throw new FailClosed(400, "invalid_body", "request body is not valid JSON"); + } + } + + /** Caller-supplied internal clock (the tenancy Worker's), so + * time-bearing steps are deterministic under test; defaults to + * the object's own clock. */ + private at(body: Record): string { + const raw = body.at; + if (raw === undefined) return new Date().toISOString(); + if (typeof raw !== "string" || Number.isNaN(Date.parse(raw))) { + throw new FailClosed(400, "invalid_body", "at must be an ISO-8601 timestamp string"); + } + return raw; + } + + // -- §4 steps ------------------------------------------------------ + + /** Steps 1–3 (signup + binding ceremony are upstream; this is + * the tenant request they enable): record the row `requested` + * with its intent, then validate. A tenant whose binding is + * missing or not active fails validation ON the row (§4's + * requested ──► failed edge) — and no database is ever created + * before a binding exists. Idempotent: a repeat request returns + * the existing row, whatever state it has reached. */ + private async request(req: Request): Promise { + const actor = this.actor(req); + this.requireActor(actor, ["owner"], "tenant request"); + const body = await this.body(req); + const at = this.at(body); + const existing = this.row(); + if (existing !== null) return json(rowView(existing)); + + const jurisdiction = parseJurisdiction( + typeof body.jurisdiction === "string" ? body.jurisdiction : null, + ); + const participantKind = body.participantKind ?? "user_hosted"; + if (!(PARTICIPANT_KINDS as readonly unknown[]).includes(participantKind)) { + throw new FailClosed(400, "invalid_body", `participantKind must be one of ${PARTICIPANT_KINDS.join(" | ")}`); + } + const backend = body.backend ?? "turso"; + if (backend !== "turso" && backend !== "redb" && backend !== "k8s_tiered") { + throw new FailClosed(400, "invalid_body", "backend must be one of turso | redb | k8s_tiered"); + } + // Intent first: the row, carrying the deterministic request + // id's inputs (tenant, jurisdiction), exists before any + // provider call can happen. + this.sql().exec( + "INSERT INTO tenant_db (tenant_id, participant_kind, turso_db_id, turso_db_url, jurisdiction, backend, state, schema_version, created_at, deleted_at) VALUES (?, ?, NULL, NULL, ?, ?, 'requested', 0, ?, NULL)", + this.tenantId, + participantKind, + jurisdiction, + backend, + at, + ); + let row = this.requireRow("tenant request"); + this.journal(at, "requested", null, "requested", actor, { + request_id: provisioningRequestId(row.tenant_id), + jurisdiction, + }); + const binding = this.sql() + .exec("SELECT status FROM binding WHERE binding_id = ?", this.tenantId) + .toArray(); + if (binding.length === 0 || binding[0].status !== "active") { + const reason = binding.length === 0 ? "binding_missing" : "binding_not_active"; + row = this.setState(row, "failed"); + this.journal(at, "failed", "requested", "failed", actor, { reason }); + } + return json(rowView(row)); + } + + /** Step 4: database creation. TenantOpsDO only, holding the + * platform credential (via the provider seam). Intent-first and + * idempotent: adopt before creating, retry retryable failures + * with the same request id, and on a permanent failure check + * once more for a database the intent already made before + * failing the tenant — adoption is the compensation that leaves + * no orphan and no duplicate. */ + private async provision(req: Request): Promise { + const actor = this.actor(req); + this.requireActor(actor, ["platform"], "database creation"); + const at = this.at(await this.body(req)); + let row = this.requireRow("database creation"); + if (row.state === "db_ready" || row.state === "active" || row.state === "suspended" || row.state === "export_only") { + return json(rowView(row)); // already provisioned: idempotent no-op + } + this.requireState(row, ["requested", "db_creating"], "database creation"); + const provider = this.provider("database creation"); + if (row.state === "requested") { + row = this.setState(row, "db_creating"); + this.journal(at, "db_creating", "requested", "db_creating", actor, { + request_id: provisioningRequestId(row.tenant_id), + }); + } + const requestId = provisioningRequestId(row.tenant_id); + const intent = { requestId, tenantId: row.tenant_id, jurisdiction: row.jurisdiction as Jurisdiction }; + + const adopted = await provider.findDatabase(requestId); + if (adopted !== null) { + row = this.setState(row, "db_ready", { turso_db_id: adopted.dbId, turso_db_url: adopted.dbUrl }); + this.journal(at, "db_ready", "db_creating", "db_ready", actor, { adopted: true }); + return json(rowView(row)); + } + for (let attempt = 1; attempt <= MAX_CREATE_ATTEMPTS; attempt++) { + try { + const handle = await provider.createDatabase(intent); + row = this.setState(row, "db_ready", { turso_db_id: handle.dbId, turso_db_url: handle.dbUrl }); + this.journal(at, "db_ready", "db_creating", "db_ready", actor, { attempt }); + return json(rowView(row)); + } catch (e) { + const retryable = !(e instanceof ProviderError) || e.retryable; + // The create may have landed despite the error (a lost + // response is the normal shape of this): look before + // deciding anything. + const landed = await provider.findDatabase(requestId); + if (landed !== null) { + row = this.setState(row, "db_ready", { turso_db_id: landed.dbId, turso_db_url: landed.dbUrl }); + this.journal(at, "db_ready", "db_creating", "db_ready", actor, { adopted: true, attempt }); + return json(rowView(row)); + } + if (!retryable) { + row = this.setState(row, "failed"); + this.journal(at, "failed", "db_creating", "failed", actor, { + reason: "provider_refused", + attempt, + }); + return json(rowView(row)); + } + this.journal(at, "create_attempt_failed", "db_creating", "db_creating", actor, { + attempt, + retryable: true, + }); + } + } + // Retryable failures outlasted the in-call attempts: stay + // db_creating. The next provision call resumes with the same + // request id — the tenant is never failed on a transient fault. + return json({ ...rowView(row), provisioning: "in_progress" }, 202); + } + + /** Step 5's signal: the TenantDO has bootstrapped the tenant + * schema (its own idempotent bootstrap, in user-do.ts). The ops + * object only records the observation — activation (§4 step 7) + * is refused until it exists. */ + private async bootstrapObserved(req: Request): Promise { + const actor = this.actor(req); + this.requireActor(actor, ["platform"], "schema bootstrap observation"); + const body = await this.body(req); + const at = this.at(body); + const row = this.requireRow("schema bootstrap observation"); + this.requireState(row, ["db_ready", "active"], "schema bootstrap observation"); + this.setMeta("schema_bootstrap_observed", "1"); + if (body.schemaVersion !== undefined) { + if (!Number.isInteger(body.schemaVersion) || (body.schemaVersion as number) < 0) { + throw new FailClosed(400, "invalid_body", "schemaVersion must be a non-negative integer"); + } + this.setState(row, row.state, { schema_version: body.schemaVersion }); + } + this.journal(at, "schema_bootstrap_observed", row.state, row.state, actor); + return json(rowView(this.requireRow("schema bootstrap observation"))); + } + + /** Step 7: activation, once schema bootstrap has been observed. */ + private async activate(req: Request): Promise { + const actor = this.actor(req); + this.requireActor(actor, ["platform"], "activation"); + const at = this.at(await this.body(req)); + let row = this.requireRow("activation"); + if (row.state === "active") return json(rowView(row)); + this.requireState(row, ["db_ready"], "activation"); + if (this.meta("schema_bootstrap_observed") !== "1") { + throw new FailClosed( + 409, + "bootstrap_not_observed", + "activation: §4 step 7 requires schema bootstrap to have been observed first", + ); + } + row = this.setState(row, "active"); + this.journal(at, "active", "db_ready", "active", actor); + return json(rowView(row)); + } + + /** Step 8: suspension — operator role, or an abuse/ceiling + * trigger. Reversible (resume below); data is untouched and + * existing tokens expire on their own TTL (E4's surface). */ + private async suspend(req: Request): Promise { + const actor = this.actor(req); + this.requireActor(actor, ["operator", "trigger"], "suspension"); + const at = this.at(await this.body(req)); + let row = this.requireRow("suspension"); + if (row.state === "suspended") return json(rowView(row)); + this.requireState(row, ["active"], "suspension"); + row = this.setState(row, "suspended"); + this.journal(at, "suspended", "active", "suspended", actor); + return json(rowView(row)); + } + + /** Suspension reversed: suspended ──► active (operator only — + * the role that may suspend is the role that may lift it). */ + private async resume(req: Request): Promise { + const actor = this.actor(req); + this.requireActor(actor, ["operator"], "resume"); + const at = this.at(await this.body(req)); + let row = this.requireRow("resume"); + if (row.state === "active") return json(rowView(row)); + this.requireState(row, ["suspended"], "resume"); + row = this.setState(row, "active"); + this.journal(at, "active", "suspended", "active", actor); + return json(rowView(row)); + } + + /** Step 9: export-only — a user request (owner), an operator + * forcing it, or the ceiling trigger. Reads and export stay; + * writes refuse (the rule #3811 states, enforced on the data + * plane). Abuse may suspend, but §4 does not name it here. */ + private async exportOnly(req: Request): Promise { + const actor = this.actor(req); + this.requireActor(actor, ["owner", "operator", "trigger"], "export-only"); + if (actor.role === "trigger" && actor.id !== "ceiling") { + throw new FailClosed( + 403, + "actor_not_permitted", + "export-only: §4 names the ceiling trigger here, not abuse; failing closed", + ); + } + const at = this.at(await this.body(req)); + let row = this.requireRow("export-only"); + if (row.state === "export_only") return json(rowView(row)); + this.requireState(row, ["active", "suspended"], "export-only"); + const from = row.state; + row = this.setState(row, "export_only"); + this.journal(at, "export_only", from, "export_only", actor); + return json(rowView(row)); + } + + /** Step 10: deletion, two-phase. Initiation (the account + * holder, from export_only) revokes every credential FIRST and + * opens the cooling-off window. Completion — the same route, + * once the window has elapsed — drops the database and writes + * the tombstone; the tenancy rows are retained. A failed drop + * leaves the tenant in deleting with its credentials already + * revoked: the safe half-state. */ + private async delete(req: Request): Promise { + const actor = this.actor(req); + const body = await this.body(req); + const at = this.at(body); + let row = this.requireRow("deletion"); + if (row.state === "deleted") return json(rowView(row)); + if (row.state !== "deleting") { + this.requireActor(actor, ["owner"], "deletion"); + this.requireState(row, ["export_only"], "deletion"); + // Phase 1: revocation first, before anything irreversible. + this.sql().exec( + "UPDATE credential SET revoked_at = ? WHERE tenant_id = ? AND revoked_at IS NULL", + at, + row.tenant_id, + ); + this.setMeta("deletion_requested_at", at); + row = this.setState(row, "deleting"); + this.journal(at, "deleting", "export_only", "deleting", actor, { phase: "revoked" }); + return json(rowView(row)); + } + // Completion: the holder who opened the window, or the + // platform driving its own sweep — nobody else. + this.requireActor(actor, ["owner", "platform"], "deletion completion"); + const requestedAt = this.meta("deletion_requested_at"); + const windowMs = this.coolingOffMs(); + if (requestedAt === null || Date.parse(at) - Date.parse(requestedAt) < windowMs) { + throw new FailClosed( + 409, + "cooling_off", + "deletion: the cooling-off window (§4 step 10) has not elapsed; the tenant stays in deleting with its credentials revoked", + ); + } + // Phase 2: the drop. Only the platform credential may drop a + // database, and it acts through the provider seam. + if (row.turso_db_id !== null) { + const provider = this.provider("deletion"); + await provider.dropDatabase(row.turso_db_id); + } + row = this.setState(row, "deleted", { deleted_at: at }); + this.journal(at, "deleted", "deleting", "deleted", actor, { phase: "dropped" }); + return json(rowView(row)); + } + + /** The row, readable in every state — a suspended or + * export-only tenant's state must never look like loss (§4). */ + private async getState(req: Request): Promise { + const actor = this.actor(req); + this.requireActor(actor, ["owner", "operator", "platform"], "state read"); + return json(rowView(this.requireRow("state read"))); + } + + async fetch(req: Request): Promise { + await this.ready; + return this.serialized(async () => { + try { + if (this.tenantId === null) { + throw new FailClosed(401, "invalid_binding", "this object's name is not a minted binding id; failing closed"); + } + if (!this.schemaPresent) { + throw new FailClosed( + 503, + "tenancy_schema_missing", + "the tenancy migrations have not been applied to this object's storage; failing closed", + ); + } + const path = new URL(req.url).pathname; + const route = `${req.method} ${path}`; + switch (route) { + case "POST /v1/tenant/request": + return await this.request(req); + case "POST /v1/tenant/provision": + return await this.provision(req); + case "POST /v1/tenant/bootstrap-observed": + return await this.bootstrapObserved(req); + case "POST /v1/tenant/activate": + return await this.activate(req); + case "POST /v1/tenant/suspend": + return await this.suspend(req); + case "POST /v1/tenant/resume": + return await this.resume(req); + case "POST /v1/tenant/export-only": + return await this.exportOnly(req); + case "POST /v1/tenant/delete": + return await this.delete(req); + case "GET /v1/tenant/state": + return await this.getState(req); + default: + return json({ error: "not_found" }, 404); + } + } catch (e) { + if (e instanceof FailClosed) return json({ error: e.code, message: e.message }, e.status); + throw e; + } + }); + } +} diff --git a/pkgs/id/hosted-worker/src/worker.ts b/pkgs/id/hosted-worker/src/worker.ts index c48be13b89..a24f2df614 100644 --- a/pkgs/id/hosted-worker/src/worker.ts +++ b/pkgs/id/hosted-worker/src/worker.ts @@ -15,6 +15,11 @@ import { FailClosed, parseBindingId, parseJurisdiction, userStub, type ObjectNam import { HDR_BINDING, HDR_IROH, HDR_JURISDICTION, HDR_ROUTED, bodyTooLarge, requestBodyLimit } from "./user-do.ts"; export { UserDO } from "./user-do.ts"; +// The tenancy control plane's per-tenant operations object (E2 of +// #9083, #12797). Exported and bound so the platform knows the +// class; the front door does not route to it — the tenancy Worker +// drives it over internal calls. +export { TenantOpsDO } from "./tenant-ops.ts"; interface Env { USERS: ObjectNamespaceLike; diff --git a/pkgs/id/hosted-worker/test/tenant-ops.test.ts b/pkgs/id/hosted-worker/test/tenant-ops.test.ts new file mode 100644 index 0000000000..93ef4d9d7c --- /dev/null +++ b/pkgs/id/hosted-worker/test/tenant-ops.test.ts @@ -0,0 +1,538 @@ +// E2 of #9083 (issue #12797): the TenantOpsDO provisioning state +// machine. +// +// Oracle: the hosted-tenancy design record +// (doc/2026-11-17T16-55-00Z_design_hosted-tenancy-architecture) +// section 4 (the lifecycle: transitions, who may do each step, +// intent-first creation, two-phase deletion) and section 11 +// item 2 ("tests prove concurrent sign-ups create one database"). +// +// Harness style follows test/bridge-do.test.ts: the DO class is +// constructed directly over a fake state whose SQL storage is a +// real node:sqlite database — here with the actual tenancy +// migrations applied (the same files test/tenancy-schema.test.ts +// pins), so the machine is exercised against the real E1 schema, +// never a copy of it. The Turso provider is a fake implementing +// the idempotency contract the design requires of it. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DatabaseSync } from "node:sqlite"; +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { + HDR_ACTOR_ID, + HDR_ACTOR_ROLE, + HDR_TRIGGER, + MAX_CREATE_ATTEMPTS, + ProviderError, + TenantOpsDO, + provisioningRequestId, + type TenantDatabaseHandle, + type TenantDatabaseProvider, +} from "../src/tenant-ops.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const migrationsDir = join(here, "..", "tenancy", "migrations"); + +const BINDING = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const OTHER_BINDING = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +const ACCOUNT = "acct-1"; +const T0 = "2026-11-24T00:00:00.000Z"; + +function freshTenancyDb(): DatabaseSync { + const db = new DatabaseSync(":memory:"); + db.exec("PRAGMA foreign_keys = ON"); + const files = readdirSync(migrationsDir) + .filter((f) => f.endsWith(".sql")) + .sort(); + for (const f of files) db.exec(readFileSync(join(migrationsDir, f), "utf8")); + return db; +} + +function fakeSql(db: DatabaseSync) { + 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[] }; + }, + }; +} + +class FakeProvider implements TenantDatabaseProvider { + byRequest = new Map(); + createCalls = 0; + dropCalls: string[] = []; + createDelayMs = 0; + /** Test script for createDatabase; return null to fall through + * to the default idempotent create. */ + onCreate: ((intent: { requestId: string }) => Promise) | null = null; + private seq = 0; + + async createDatabase(intent: { requestId: string }): Promise { + this.createCalls++; + if (this.createDelayMs > 0) await new Promise((r) => setTimeout(r, this.createDelayMs)); + if (this.onCreate !== null) { + const scripted = await this.onCreate(intent); + if (scripted !== null) return scripted; + } + return this.register(intent.requestId); + } + + register(requestId: string): TenantDatabaseHandle { + const existing = this.byRequest.get(requestId); + if (existing) return existing; + this.seq++; + const handle = { dbId: `db-${this.seq}`, dbUrl: `https://db-${this.seq}.turso.io` }; + this.byRequest.set(requestId, handle); + return handle; + } + + async findDatabase(requestId: string): Promise { + return this.byRequest.get(requestId) ?? null; + } + + async dropDatabase(dbId: string): Promise { + this.dropCalls.push(dbId); + for (const [requestId, handle] of this.byRequest) { + if (handle.dbId === dbId) this.byRequest.delete(requestId); + } + } +} + +function makeOps(db: DatabaseSync, env: Record = {}, binding: string = BINDING) { + const state = { + id: { name: binding }, + storage: { sql: fakeSql(db) }, + blockConcurrencyWhile: async (fn: () => Promise): Promise => fn(), + }; + return new TenantOpsDO(state as never, env as never); +} + +function seedBinding(db: DatabaseSync, status = "active", binding: string = BINDING) { + db.prepare( + "INSERT OR IGNORE INTO account (account_id, sub, email_contact, created_at, state, tier) VALUES (?, ?, NULL, ?, 'active', 'standard')", + ).run(ACCOUNT, "provider-subject-1", T0); + db.prepare( + "INSERT INTO binding (binding_id, account_id, iroh_id, status, bound_at, superseded_by) VALUES (?, ?, 'iroh-public-key', ?, ?, NULL)", + ).run(binding, ACCOUNT, status, T0); +} + +interface Actor { + role: string; + id: string; + trigger?: string; +} +const OWNER: Actor = { role: "owner", id: BINDING }; +const PLATFORM: Actor = { role: "platform", id: "tenant-ops" }; +const OPERATOR: Actor = { role: "operator", id: "operator-1" }; +const ABUSE: Actor = { role: "trigger", id: "abuse", trigger: "abuse" }; +const CEILING: Actor = { role: "trigger", id: "ceiling", trigger: "ceiling" }; + +async function call( + ops: TenantOpsDO, + method: string, + path: string, + actor: Actor | null, + body?: Record, +): Promise<{ status: number; body: Record }> { + const headers = new Headers(); + if (actor !== null) { + headers.set(HDR_ACTOR_ROLE, actor.role); + headers.set(HDR_ACTOR_ID, actor.id); + if (actor.trigger !== undefined) headers.set(HDR_TRIGGER, actor.trigger); + } + const res = await ops.fetch( + new Request("https://do" + path, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + }), + ); + return { status: res.status, body: (await res.json()) as Record }; +} + +const post = (ops: TenantOpsDO, path: string, actor: Actor | null, body?: Record) => + call(ops, "POST", path, actor, body ?? {}); + +function tenantRow(db: DatabaseSync, binding: string = BINDING) { + return db.prepare("SELECT * FROM tenant_db WHERE tenant_id = ?").get(binding) as + | Record + | undefined; +} + +/** Drive a tenant to `active` the §4 way; returns the provider. */ +async function provisionedToActive(db: DatabaseSync, ops: TenantOpsDO) { + await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + await post(ops, "/v1/tenant/provision", PLATFORM); + await post(ops, "/v1/tenant/bootstrap-observed", PLATFORM, { schemaVersion: 3 }); + const res = await post(ops, "/v1/tenant/activate", PLATFORM); + assert.equal(res.body.state, "active"); +} + +test("the §4 lifecycle, end to end, with two-phase deletion", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider, TENANT_DELETION_COOLING_OFF_MS: "60000" }); + + let res = await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "eu", at: T0 }); + assert.equal(res.status, 200); + assert.equal(res.body.state, "requested"); + assert.equal(res.body.jurisdiction, "eu"); + assert.equal(res.body.turso_db_id, null); + + res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.body.state, "db_ready"); + assert.equal(res.body.turso_db_id, "db-1"); + assert.equal(provider.createCalls, 1); + + res = await post(ops, "/v1/tenant/bootstrap-observed", PLATFORM, { schemaVersion: 3 }); + assert.equal(res.body.schema_version, 3); + res = await post(ops, "/v1/tenant/activate", PLATFORM); + assert.equal(res.body.state, "active"); + + res = await post(ops, "/v1/tenant/suspend", OPERATOR); + assert.equal(res.body.state, "suspended"); + // Suspension must not look like loss: the state still answers. + res = await call(ops, "GET", "/v1/tenant/state", OWNER); + assert.equal(res.status, 200); + assert.equal(res.body.state, "suspended"); + + res = await post(ops, "/v1/tenant/resume", OPERATOR); + assert.equal(res.body.state, "active"); + res = await post(ops, "/v1/tenant/export-only", OWNER); + assert.equal(res.body.state, "export_only"); + + // A live credential (metadata only, as E1/E4 keep it) to prove + // deletion's phase 1 revokes before anything is dropped. + db.prepare( + "INSERT INTO credential (credential_id, tenant_id, audience, scope, issued_at, expires_at, revoked_at, issuer, jti) VALUES ('cred-1', ?, 'db-1', 'readwrite', ?, ?, NULL, 'tenant-ops', 'jti-1')", + ).run(BINDING, T0, "2027-01-01T00:00:00.000Z"); + + res = await post(ops, "/v1/tenant/delete", OWNER, { at: "2026-11-25T00:00:00.000Z" }); + assert.equal(res.body.state, "deleting"); + const cred = db.prepare("SELECT revoked_at FROM credential WHERE credential_id = 'cred-1'").get() as { + revoked_at: string; + }; + assert.equal(cred.revoked_at, "2026-11-25T00:00:00.000Z", "revocation is phase 1, at initiation"); + assert.deepEqual(provider.dropCalls, [], "nothing is dropped inside the cooling-off window"); + + res = await post(ops, "/v1/tenant/delete", PLATFORM, { at: "2026-11-25T00:02:00.000Z" }); + assert.equal(res.body.state, "deleted"); + assert.equal(res.body.deleted_at, "2026-11-25T00:02:00.000Z"); + assert.deepEqual(provider.dropCalls, ["db-1"]); + // The tombstone: the row is retained, marked deleted. + const row = tenantRow(db); + assert.equal(row?.state, "deleted"); + assert.equal(row?.deleted_at, "2026-11-25T00:02:00.000Z"); + + const events = ( + db.prepare("SELECT event FROM ops_journal ORDER BY seq").all() as { event: string }[] + ).map((r) => r.event); + assert.deepEqual(events, [ + "requested", + "db_creating", + "db_ready", + "schema_bootstrap_observed", + "active", + "suspended", + "active", + "export_only", + "deleting", + "deleted", + ]); +}); + +test("concurrent sign-ups create exactly one database (§11 item 2)", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + provider.createDelayMs = 25; // widen the race window: without serialisation, both drivers reach the provider + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider }); + + // Two sign-ups race: duplicate requests, then duplicate + // provisioning drives, all in flight at once. + const [r1, r2] = await Promise.all([ + post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }), + post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }), + ]); + assert.equal(r1.body.state, "requested"); + assert.equal(r2.body.state, "requested"); + const [p1, p2] = await Promise.all([ + post(ops, "/v1/tenant/provision", PLATFORM), + post(ops, "/v1/tenant/provision", PLATFORM), + ]); + assert.equal(p1.body.state, "db_ready"); + assert.equal(p2.body.state, "db_ready"); + assert.equal(p1.body.turso_db_id, p2.body.turso_db_id); + assert.equal(provider.createCalls, 1, "one binding, one database, however the sign-ups race"); + const count = db.prepare("SELECT COUNT(*) AS n FROM tenant_db").get() as { n: number }; + assert.equal(count.n, 1); + + // A restarted object (a second instance over the same tenancy + // DB) re-driving provisioning still creates nothing. + const ops2 = makeOps(db, { TENANT_DB_PROVIDER: provider }); + const p3 = await post(ops2, "/v1/tenant/provision", PLATFORM); + assert.equal(p3.body.state, "db_ready"); + assert.equal(provider.createCalls, 1); +}); + +test("intent-first: a crash after creation adopts the existing database", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + // The intent already made a database; the row still says + // db_creating (the crash took the response with it). + const handle = provider.register(provisioningRequestId(BINDING)); + db.prepare( + "INSERT INTO tenant_db (tenant_id, participant_kind, turso_db_id, turso_db_url, jurisdiction, backend, state, schema_version, created_at, deleted_at) VALUES (?, 'user_hosted', NULL, NULL, 'us', 'turso', 'db_creating', 0, ?, NULL)", + ).run(BINDING, T0); + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider }); + const res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.body.state, "db_ready"); + assert.equal(res.body.turso_db_id, handle.dbId); + assert.equal(provider.createCalls, 0, "adoption, not a second creation"); +}); + +test("a create whose response is lost is adopted, not duplicated", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + provider.onCreate = async (intent) => { + provider.register(intent.requestId); // the database exists… + throw new Error("connection reset"); // …but the response never arrived + }; + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider }); + await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + const res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.body.state, "db_ready"); + assert.equal(provider.createCalls, 1); +}); + +test("retryable failures retry with the same request id, then succeed", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + const requestIds: string[] = []; + let failuresLeft = 2; + provider.onCreate = async (intent) => { + requestIds.push(intent.requestId); + if (failuresLeft > 0) { + failuresLeft--; + throw new ProviderError("provider busy", true); + } + return null; + }; + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider }); + await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + const res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.body.state, "db_ready"); + assert.equal(provider.createCalls, 3); + assert.ok(requestIds.every((id) => id === provisioningRequestId(BINDING))); +}); + +test("retryable failures that outlast the attempts leave db_creating, never failed", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + provider.onCreate = async () => { + throw new ProviderError("provider busy", true); + }; + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider }); + await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + const res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.status, 202); + assert.equal(res.body.state, "db_creating"); + assert.equal(provider.createCalls, MAX_CREATE_ATTEMPTS); + // The provider heals; the same tenant completes under the same + // request id, no fresh sign-up needed. + provider.onCreate = null; + const res2 = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res2.body.state, "db_ready"); +}); + +test("a permanent provider refusal fails the tenant and leaves no database", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + provider.onCreate = async () => { + throw new ProviderError("jurisdiction not offered", false); + }; + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider }); + await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + const res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.body.state, "failed"); + assert.equal(await provider.findDatabase(provisioningRequestId(BINDING)), null); + assert.equal(tenantRow(db)?.turso_db_id, null); +}); + +test("validation: no database before a binding exists (§4)", async () => { + const db = freshTenancyDb(); + const provider = new FakeProvider(); + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider }); + // No binding row at all: the request is recorded and fails + // validation on the row — the diagram's requested ──► failed edge. + let res = await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + assert.equal(res.body.state, "failed"); + res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.status, 409); + assert.equal(provider.createCalls, 0); + + // A superseded binding is not an active binding either. + const db2 = freshTenancyDb(); + seedBinding(db2, "superseded"); + const ops2 = makeOps(db2, { TENANT_DB_PROVIDER: provider }); + res = await post(ops2, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + assert.equal(res.body.state, "failed"); + assert.equal(provider.createCalls, 0); + + // A jurisdiction outside the closed vocabulary refuses before + // any row exists. + const db3 = freshTenancyDb(); + seedBinding(db3); + const ops3 = makeOps(db3, { TENANT_DB_PROVIDER: provider }); + res = await post(ops3, "/v1/tenant/request", OWNER, { jurisdiction: "apac", at: T0 }); + assert.equal(res.status, 403); + assert.equal(tenantRow(db3), undefined); +}); + +test("activation waits for observed schema bootstrap (§4 steps 5+7)", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const ops = makeOps(db, { TENANT_DB_PROVIDER: new FakeProvider() }); + await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + await post(ops, "/v1/tenant/provision", PLATFORM); + const early = await post(ops, "/v1/tenant/activate", PLATFORM); + assert.equal(early.status, 409); + assert.equal(early.body.error, "bootstrap_not_observed"); + assert.equal(tenantRow(db)?.state, "db_ready"); + await post(ops, "/v1/tenant/bootstrap-observed", PLATFORM, {}); + const res = await post(ops, "/v1/tenant/activate", PLATFORM); + assert.equal(res.body.state, "active"); +}); + +test("only the actors §4 names can perform each step", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider, TENANT_DELETION_COOLING_OFF_MS: "0" }); + + // Each step at its §4 doorstep: the forbidden actors try first + // (the tenant must not move), then the named actor performs it. + const steps: { + path: string; + doorstep: string | null; + forbidden: Actor[]; + legit: Actor; + body?: Record; + lands: string; + }[] = [ + { path: "/v1/tenant/request", doorstep: null, forbidden: [OPERATOR, PLATFORM, ABUSE], legit: OWNER, body: { jurisdiction: "us", at: T0 }, lands: "requested" }, + { path: "/v1/tenant/provision", doorstep: "requested", forbidden: [OWNER, OPERATOR, ABUSE], legit: PLATFORM, lands: "db_ready" }, + { path: "/v1/tenant/bootstrap-observed", doorstep: "db_ready", forbidden: [OWNER, OPERATOR], legit: PLATFORM, body: {}, lands: "db_ready" }, + { path: "/v1/tenant/activate", doorstep: "db_ready", forbidden: [OWNER, OPERATOR, CEILING], legit: PLATFORM, lands: "active" }, + { path: "/v1/tenant/suspend", doorstep: "active", forbidden: [OWNER, PLATFORM], legit: OPERATOR, lands: "suspended" }, + { path: "/v1/tenant/resume", doorstep: "suspended", forbidden: [OWNER, PLATFORM, ABUSE], legit: OPERATOR, lands: "active" }, + { path: "/v1/tenant/export-only", doorstep: "active", forbidden: [PLATFORM, ABUSE], legit: OWNER, lands: "export_only" }, + { path: "/v1/tenant/delete", doorstep: "export_only", forbidden: [OPERATOR, PLATFORM, CEILING], legit: OWNER, body: { at: T0 }, lands: "deleting" }, + ]; + for (const step of steps) { + assert.equal(tenantRow(db)?.state ?? null, step.doorstep, `doorstep for ${step.path}`); + for (const actor of step.forbidden) { + const res = await post(ops, step.path, actor, { at: T0, jurisdiction: "us" }); + assert.equal(res.status, 403, `${step.path} by ${actor.role}/${actor.id} must refuse`); + assert.equal(res.body.error, "actor_not_permitted"); + assert.equal(tenantRow(db)?.state ?? null, step.doorstep, `${step.path} by ${actor.role} must not move the tenant`); + } + const ok = await post(ops, step.path, step.legit, step.body ?? {}); + assert.equal(ok.status, 200, `${step.path} by its §4 actor`); + assert.equal(ok.body.state, step.lands); + } + // Deletion completion by the holder, window already elapsed (0): + let res = await post(ops, "/v1/tenant/delete", OWNER, { at: T0 }); + assert.equal(res.body.state, "deleted"); + + // An owner of a DIFFERENT binding is not this tenant's owner. + const db2 = freshTenancyDb(); + seedBinding(db2); + const ops2 = makeOps(db2, { TENANT_DB_PROVIDER: new FakeProvider() }); + res = await post(ops2, "/v1/tenant/request", { role: "owner", id: OTHER_BINDING }, { jurisdiction: "us" }); + assert.equal(res.status, 403); + assert.equal(tenantRow(db2), undefined); + + // No actor at all fails closed. + res = await post(ops2, "/v1/tenant/request", null, { jurisdiction: "us" }); + assert.equal(res.status, 401); +}); + +test("the named trigger actors work where §4 names them — and only there", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const ops = makeOps(db, { TENANT_DB_PROVIDER: new FakeProvider() }); + await provisionedToActive(db, ops); + let res = await post(ops, "/v1/tenant/suspend", ABUSE); + assert.equal(res.body.state, "suspended", "abuse may suspend"); + await post(ops, "/v1/tenant/resume", OPERATOR); + res = await post(ops, "/v1/tenant/export-only", CEILING); + assert.equal(res.body.state, "export_only", "the ceiling trigger may force export-only"); +}); + +test("deletion refuses before export-only and inside the cooling-off window", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const provider = new FakeProvider(); + const ops = makeOps(db, { TENANT_DB_PROVIDER: provider, TENANT_DELETION_COOLING_OFF_MS: "60000" }); + await provisionedToActive(db, ops); + // From active, deletion is not a §4 transition at all. + let res = await post(ops, "/v1/tenant/delete", OWNER, { at: T0 }); + assert.equal(res.status, 409); + assert.equal(res.body.error, "invalid_transition"); + await post(ops, "/v1/tenant/export-only", OWNER); + res = await post(ops, "/v1/tenant/delete", OWNER, { at: "2026-11-25T00:00:00.000Z" }); + assert.equal(res.body.state, "deleting"); + res = await post(ops, "/v1/tenant/delete", OWNER, { at: "2026-11-25T00:00:30.000Z" }); + assert.equal(res.status, 409); + assert.equal(res.body.error, "cooling_off"); + assert.deepEqual(provider.dropCalls, [], "the drop waits for the window"); + assert.equal(tenantRow(db)?.state, "deleting"); +}); + +test("transitions from the wrong state refuse, and repeats are idempotent", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const ops = makeOps(db, { TENANT_DB_PROVIDER: new FakeProvider() }); + await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + for (const path of ["/v1/tenant/suspend", "/v1/tenant/resume", "/v1/tenant/export-only", "/v1/tenant/activate"]) { + const actor = path === "/v1/tenant/activate" ? PLATFORM : OPERATOR; + const res = await post(ops, path, actor, {}); + assert.equal(res.status, 409, `${path} from requested`); + assert.equal(res.body.error, "invalid_transition"); + } + await provisionedToActive(db, ops); + // Repeats of completed steps answer with the row, not an error. + let res = await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us" }); + assert.equal(res.body.state, "active"); + res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.body.state, "active"); + res = await post(ops, "/v1/tenant/suspend", OPERATOR); + assert.equal(res.body.state, "suspended"); + res = await post(ops, "/v1/tenant/suspend", OPERATOR); + assert.equal(res.body.state, "suspended", "suspend is idempotent"); +}); + +test("no provider configured: provisioning fails closed, nothing is created", async () => { + const db = freshTenancyDb(); + seedBinding(db); + const ops = makeOps(db, {}); + await post(ops, "/v1/tenant/request", OWNER, { jurisdiction: "us", at: T0 }); + const res = await post(ops, "/v1/tenant/provision", PLATFORM); + assert.equal(res.status, 503); + assert.equal(res.body.error, "provider_unavailable"); + assert.equal(tenantRow(db)?.state, "requested", "the row does not advance on a guess"); +}); diff --git a/pkgs/id/hosted-worker/wrangler.toml b/pkgs/id/hosted-worker/wrangler.toml index 28697fd892..d7b51e2a54 100644 --- a/pkgs/id/hosted-worker/wrangler.toml +++ b/pkgs/id/hosted-worker/wrangler.toml @@ -10,10 +10,21 @@ compatibility_date = "2025-06-01" name = "USERS" class_name = "UserDO" +# The tenancy provisioning state machine (E2 of #9083, #12797): +# one object per tenant, named by binding_id, driven by the tenancy +# Worker — never routed by this front door. +[[durable_objects.bindings]] +name = "TENANT_OPS" +class_name = "TenantOpsDO" + [[migrations]] tag = "v1" new_sqlite_classes = ["UserDO"] +[[migrations]] +tag = "v2" +new_sqlite_classes = ["TenantOpsDO"] + # 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). From 71356ecd25e20cf7197cea506463068d4d601293 Mon Sep 17 00:00:00 2001 From: felix Date: Tue, 24 Nov 2026 13:09:25 +0000 Subject: [PATCH 2/2] docs(id): book + package docs for the TenantOpsDO slice (#12797) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Book live update (book-live-update rule): the slice adds src/tenant-ops.ts and the TENANT_OPS binding, which moves statements in the id book — reference/hosted-worker.md gains the binding row, a TenantOpsDO routes section and the unrouted-surface row; concepts/hosted.md's package enumeration gains tenant-ops.ts. design/hosted-editions.md checked: its tenancy statements are about a running service, which this scaffold slice is not, so nothing there moves. Package READMEs updated for the same facts. --- pkgs/id/book/concepts/hosted.md | 2 +- pkgs/id/book/reference/hosted-worker.md | 22 +++++++++++++++++++++- pkgs/id/hosted-worker/README.md | 14 ++++++++++++++ pkgs/id/hosted-worker/tenancy/README.md | 13 ++++++++++--- 4 files changed, 46 insertions(+), 5 deletions(-) diff --git a/pkgs/id/book/concepts/hosted.md b/pkgs/id/book/concepts/hosted.md index 537c535a6a..2c25e556d9 100644 --- a/pkgs/id/book/concepts/hosted.md +++ b/pkgs/id/book/concepts/hosted.md @@ -51,7 +51,7 @@ Any other path or method returns 404 with `{"error":"not_found"}`. Bridge routes Read the table as a data plane, because that is what it is. The hosted object holds one bound user's KV, blob references, and a signed-object bridge store. As a sync peer it holds signed objects and fork evidence; it assigns no order, re-signs nothing, and serves no authoritative snapshot. Ordering and authority stay with the authors' chains, exactly as on a native node. -Also in the package, but not routed by `worker.ts`, are `src/provisioning.ts` and `provisioning-surface.ts` (a provisioning surface), `src/account-directory.ts`, `src/admission-gate.ts`, `src/export.ts`, and a currency gateway proof of concept under `src/currency/` (`gateway`, `ledger`, `relay`, `crypto`; #2298). The currency proof of concept is explicitly not the permanent currency service: it is an in-process ledger stub modelled on TigerBeetle, with gateway-signed balance snapshots and a UserDO relay reconciling by request-ID lookup. [Currency, tokens and metering](currency.md) covers it in place. +Also in the package, but not routed by `worker.ts`, are `src/provisioning.ts` and `provisioning-surface.ts` (a provisioning surface), `src/account-directory.ts`, `src/admission-gate.ts`, `src/export.ts`, `src/tenant-ops.ts` (the `TenantOpsDO` provisioning state machine of the tenancy design §4 — exported and bound as `TENANT_OPS`, but driven by the tenancy control plane, not the front door), and a currency gateway proof of concept under `src/currency/` (`gateway`, `ledger`, `relay`, `crypto`; #2298). The currency proof of concept is explicitly not the permanent currency service: it is an in-process ledger stub modelled on TigerBeetle, with gateway-signed balance snapshots and a UserDO relay reconciling by request-ID lookup. [Currency, tokens and metering](currency.md) covers it in place. ## What it does not yet do diff --git a/pkgs/id/book/reference/hosted-worker.md b/pkgs/id/book/reference/hosted-worker.md index 4affad09cc..2e0236e2c8 100644 --- a/pkgs/id/book/reference/hosted-worker.md +++ b/pkgs/id/book/reference/hosted-worker.md @@ -1,6 +1,6 @@ # The hosted Worker API -Source: https://github.com/developing-today/code/blob/main/pkgs/id/hosted-worker/src/worker.ts, https://github.com/developing-today/code/blob/main/pkgs/id/hosted-worker/src/user-do.ts, https://github.com/developing-today/code/blob/main/pkgs/id/hosted-worker/wrangler.toml, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/README.md +Source: https://github.com/developing-today/code/blob/main/pkgs/id/hosted-worker/src/worker.ts, https://github.com/developing-today/code/blob/main/pkgs/id/hosted-worker/src/user-do.ts, https://github.com/developing-today/code/blob/main/pkgs/id/hosted-worker/src/tenant-ops.ts, https://github.com/developing-today/code/blob/main/pkgs/id/hosted-worker/wrangler.toml, https://github.com/developing-today/code/blob/main/pkgs/id/worker-poc/README.md This chapter documents the hosted Worker **as it stands**. Two packages exist, and neither is a live service: @@ -55,6 +55,7 @@ From `wrangler.toml`: Worker name `id-hosted-worker`, `compatibility_date` `2025 | Binding / var | Type | Notes | | --------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `USERS` | Durable Object namespace → `UserDO` | Migration tag `v1`, `new_sqlite_classes = ["UserDO"]`. | +| `TENANT_OPS` | Durable Object namespace → `TenantOpsDO` | Migration tag `v2`, `new_sqlite_classes = ["TenantOpsDO"]`. One object per tenant, named by `binding_id`. Exported by `worker.ts` but never routed by the front door; the tenancy Worker drives it. | | `BLOBS` | R2 bucket `id-hosted-blobs` | Content-addressed blob bytes. Local emulation only. In the `UserDO` interface the binding is optional, and the code that needs it fails closed without it. | | `USER_CEILING_BYTES` | String var, optional | Per-user storage ceiling. Absent or empty means no ceiling. A malformed value fails writes closed. Also read by the front door for the body limit: `MAX_BODY_BYTES` is a 100 MiB cap. | | `BRIDGE_WAITING_PER_AUTHOR` | String var, optional | Bridge waiting-pool bound, per author. Absent means the native default in `bridge-store.ts`. A malformed value fails bridge writes closed. | @@ -101,6 +102,24 @@ Failure shapes: - A KV key outside `[A-Za-z0-9._-]{1,128}` is not a valid route key. - A blob path whose segment is not 64 hex characters does not name a blob. +## TenantOpsDO routes + +Implementation: `src/tenant-ops.ts` (E2 of the hosted-tenancy component, #12797), implementing the provisioning lifecycle of the tenancy design record §4 over the central tenancy DB's `tenant_db` row (schema baseline in `pkgs/id/hosted-worker/tenancy/`). One object per tenant, named by `binding_id`. The front door does not route to it; the caller is the tenancy Worker, which sets the actor on internal headers (`x-tenancy-actor-role`, `x-tenancy-actor-id`, `x-tenancy-trigger`) after authentication, and every step refuses an actor §4 does not name for it. All routes are POST except the state read. + +| Method | Path | Who (§4) | Effect | +| ------ | ------------------------------- | ------------------------------------- | ---------------------------------------------------------------------- | +| POST | `/v1/tenant/request` | owner (the bound binding) | Record the row `requested` with its provisioning intent; a missing or inactive binding fails validation on the row (`failed`). Idempotent. | +| POST | `/v1/tenant/provision` | platform (the object itself) | `requested` → `db_creating` → `db_ready`: create the tenant database through the provider seam under the deterministic request id; retries adopt the database the intent already made instead of creating a second one. | +| POST | `/v1/tenant/bootstrap-observed` | platform | Record that the TenantDO's schema bootstrap has been observed; activation is refused until this exists. | +| POST | `/v1/tenant/activate` | platform | `db_ready` → `active`. | +| POST | `/v1/tenant/suspend` | operator, or the abuse/ceiling trigger | `active` → `suspended`. Reversible; data untouched. | +| POST | `/v1/tenant/resume` | operator | `suspended` → `active`. | +| POST | `/v1/tenant/export-only` | owner, operator, or the ceiling trigger | `active`/`suspended` → `export_only`: reads and export stay, writes refuse. | +| POST | `/v1/tenant/delete` | owner (initiate); owner or platform (complete) | Two-phase: initiation (from `export_only` only) revokes all credential metadata and opens the cooling-off window (`deleting`); completion after the window drops the database and writes the tombstone (`deleted`, row retained). | +| GET | `/v1/tenant/state` | owner, operator, platform | The registry row. Answers in every state — suspension must not look like loss. | + +Failure shapes: no or unknown actor → `401`; an actor §4 does not name for the step (including an owner naming a different binding) → `403 actor_not_permitted`; a step attempted from a state §4 does not allow → `409 invalid_transition`; activation before observed bootstrap → `409 bootstrap_not_observed`; deletion inside the cooling-off window → `409 cooling_off`. With no database provider configured, provisioning and drops fail closed with `503 provider_unavailable` and the row does not advance. Credential issuance is a later slice (E4); this surface mints nothing and only revokes, as deletion's first phase. + ### The README route list is a first-slice fossil (WEB-9) The `hosted-worker` README describes the UserDO routes as `GET /v1/state` and `PUT|GET /v1/kv/`, calls the KV store minimal, and states that R2 blobs, metering and caps are later steps and out of scope. The code implements blobs (PUT, GET, DELETE), usage and metering, export, KV DELETE, and the full bridge. The README's later sections cover the bridge and export but never revise that paragraph, and blobs, usage and KV-delete appear in no README route list. That is disagreement WEB-9; the table above is the implemented surface. @@ -112,6 +131,7 @@ These modules exist in the package but are not routed by `worker.ts`: | Module | What it is | | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `src/provisioning.ts`, `src/provisioning-surface.ts` | The provisioning surface. | +| `src/tenant-ops.ts` | `TenantOpsDO`, the tenancy provisioning state machine (see TenantOpsDO routes above). Exported and bound, but driven by the tenancy Worker, not the front door. | | `src/account-directory.ts` | Account directory. | | `src/admission-gate.ts` | Admission gate. | | `src/export.ts` | Export support behind `/v1/bridge/export`. | diff --git a/pkgs/id/hosted-worker/README.md b/pkgs/id/hosted-worker/README.md index 541ff8e9d3..cc4fc981d3 100644 --- a/pkgs/id/hosted-worker/README.md +++ b/pkgs/id/hosted-worker/README.md @@ -43,6 +43,20 @@ content, no keys and no token values (design §2.3, "never central"); `test/tenancy-schema.test.ts` fails if a content/key/token column ever appears. See `tenancy/README.md`. +- `src/tenant-ops.ts` — `TenantOpsDO` (E2 of #9083, #12797): one + object per tenant, named by `binding_id`, implementing the design + §4 provisioning state machine over the `tenant_db` row — + `requested → db_creating → db_ready → active`, suspension, + export-only, and two-phase deletion (credential revocation, + cooling-off window, drop, tombstone). Creation is intent-first + under a deterministic request id, so concurrent sign-ups create + exactly one database; every step checks the actor §4 names for + it. Bound as `TENANT_OPS` in `wrangler.toml` but not routed by + the front door — the tenancy Worker drives it. The Turso + management API sits behind a provider seam; unconfigured, it + fails closed. `test/tenant-ops.test.ts` exercises the machine + against the real tenancy migrations. + ## Local reality check (verified 2026-11-03, wrangler dev / workerd) Local workerd does **not** implement jurisdiction restrictions: diff --git a/pkgs/id/hosted-worker/tenancy/README.md b/pkgs/id/hosted-worker/tenancy/README.md index 9c7faf4008..b3336238d1 100644 --- a/pkgs/id/hosted-worker/tenancy/README.md +++ b/pkgs/id/hosted-worker/tenancy/README.md @@ -10,7 +10,13 @@ and nothing else. Design record: This directory is the schema home for that database. The tenant **data** plane (per-user databases and the `UserDO` that serves them) is `../src/`; this is the control plane above it, queried by tenancy -Workers and the `TenancyOpsDO` of later E slices. +Workers and driven, per tenant, by the `TenantOpsDO` in +`../src/tenant-ops.ts` (E2, #12797): the §4 provisioning state +machine over the `tenant_db` row — intent-first idempotent creation, +retry, compensation, and the two-phase deletion. E2 needed no schema +change: the baseline row already carries every field the machine +writes, and the machine's own journal lives in the object's storage, +not in this database. ## The invariant (design §2.3, "never central") @@ -37,8 +43,9 @@ tables and the sync/publish protocols never branch on "hosted". Numbered, append-only SQL files in `migrations/`, applied in order. `0001_tenancy_baseline.sql` is the §2.1 baseline (E1, #12796); later -E slices (E2 provisioning, E4 credentials, E5 publish) add migrations -here rather than editing landed ones. `meta.schema_version` records +E slices add migrations here rather than editing landed ones when +they need schema the baseline lacks (E2 provisioning needed none; +E4 credentials and E5 publish are the expected next authors). `meta.schema_version` records the applied baseline, mirroring the `UserDO` bootstrap pattern in `../src/user-do.ts`.