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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/test-suite-registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@
"id": "id.hosted-worker.routing",
"paths": [
"pkgs/id/hosted-worker/test/routing.test.ts",
"pkgs/id/hosted-worker/test/persistent-account-directory.test.ts",
"pkgs/id/hosted-worker/test/admission-gate.test.ts",
"pkgs/id/hosted-worker/test/provisioning.test.ts",
"pkgs/id/hosted-worker/test/blobs.test.ts",
Expand All @@ -283,7 +284,7 @@
"pkgs/id/hosted-worker/test/bridge-session.test.ts",
"pkgs/id/hosted-worker/test/bridge-do.test.ts"
],
"invocation": "cd pkgs/id/hosted-worker && npm 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)",
"invocation": "cd pkgs/id/hosted-worker && npm test (node --experimental-transform-types --test test/routing.test.ts test/persistent-account-directory.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)",
"venue": {
"workflow": ".github/workflows/id-hosted-worker-tests.yml",
"job_step": "hosted-worker-tests / Run the hosted-worker routing suite",
Expand Down
11 changes: 11 additions & 0 deletions pkgs/id/hosted-worker/migrations/0001_hosted_accounts.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- Shared jurisdiction-aware directory metadata only. Do not put user content
-- here; production D1 provisioning and residency evidence are separate gates.
CREATE TABLE IF NOT EXISTS hosted_accounts (
subject_key TEXT PRIMARY KEY NOT NULL CHECK (length(trim(subject_key)) > 0),
binding_id TEXT NOT NULL UNIQUE CHECK (length(binding_id) = 32),
jurisdiction TEXT NOT NULL CHECK (jurisdiction IN ('us', 'eu', 'fedramp')),
jurisdiction_pending TEXT CHECK (jurisdiction_pending IS NULL OR jurisdiction_pending IN ('us', 'eu', 'fedramp')),
migration_id TEXT,
phase TEXT NOT NULL,
routing_epoch INTEGER NOT NULL CHECK (routing_epoch >= 0)
);
2 changes: 1 addition & 1 deletion pkgs/id/hosted-worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"dev": "wrangler dev",
"typecheck": "tsc --noEmit",
"test": "node --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 test/export.test.ts",
"test": "node --experimental-transform-types --test test/routing.test.ts test/persistent-account-directory.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 test/export.test.ts",
"smoke": "node smoke/smoke.mjs"
},
"devDependencies": {
Expand Down
128 changes: 128 additions & 0 deletions pkgs/id/hosted-worker/src/persistent-account-directory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Durable unique-subject directory operations for #3399. This module is an
// adapter contract only: production binding/provisioning and signup wiring
// remain gated separately (#2285 / #3403).

import {
createHostedAccountRecord,
type HostedAccountRecord,
type NewHostedAccount,
} from "./account-directory.ts";
import { FailClosed, parseBindingId, parseJurisdiction } from "./routing.ts";

/** Small structural subset shared by Cloudflare D1 and the SQLite test adapter. */
export interface HostedDirectoryStatement {
bind(...values: Array<string | number | null>): HostedDirectoryStatement;
first<T extends Record<string, unknown>>(): Promise<T | null>;
}

export interface HostedDirectoryDatabase {
prepare(query: string): HostedDirectoryStatement;
}

type StoredAccountRow = Record<string, unknown> & {
subject_key: string;
binding_id: string;
jurisdiction: string;
jurisdiction_pending: string | null;
migration_id: string | null;
phase: string;
routing_epoch: number;
};

const COLUMNS =
"subject_key, binding_id, jurisdiction, jurisdiction_pending, migration_id, phase, routing_epoch";

function fromRow(row: StoredAccountRow): HostedAccountRecord {
if (
typeof row.subject_key !== "string" ||
row.subject_key.trim() === "" ||
typeof row.binding_id !== "string" ||
row.jurisdiction_pending !== null ||
row.migration_id !== null ||
row.phase !== "stable" ||
row.routing_epoch !== 0
) {
throw new FailClosed(
503,
"invalid_directory_record",
"stored hosted account record is invalid; failing closed",
);
}
return {
subjectKey: row.subject_key,
bindingId: parseBindingId(row.binding_id),
jurisdiction: parseJurisdiction(row.jurisdiction),
jurisdictionPending: null,
migrationId: null,
phase: "stable",
routingEpoch: 0,
};
}

/**
* D1-backed signup record operations. The unique indexes are the serialization
* point: concurrent insertions cannot replace an existing subject or binding.
*/
export class PersistentHostedAccountDirectory {
constructor(private readonly database: HostedDirectoryDatabase) {}

async get(subjectKey: string): Promise<HostedAccountRecord | undefined> {
const row = await this.database
.prepare(`SELECT ${COLUMNS} FROM hosted_accounts WHERE subject_key = ?`)
.bind(subjectKey)
.first<StoredAccountRow>();
return row ? fromRow(row) : undefined;
}

async signup(input: NewHostedAccount): Promise<HostedAccountRecord> {
// Match the directory contract: a duplicate subject reads its authoritative
// row and never replaces its jurisdiction with a new signup's value.
const existing = await this.get(input.subjectKey);
if (existing) return this.existingSubject(existing, input.bindingId);

const candidate = createHostedAccountRecord(input);
const inserted = await this.database
.prepare(
`INSERT INTO hosted_accounts (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?) ` +
"ON CONFLICT DO NOTHING " +
`RETURNING ${COLUMNS}`,
)
.bind(
candidate.subjectKey,
candidate.bindingId,
candidate.jurisdiction,
candidate.jurisdictionPending,
candidate.migrationId,
candidate.phase,
candidate.routingEpoch,
)
.first<StoredAccountRow>();
if (inserted) return fromRow(inserted);

// A competing signup may have won after the initial read. Re-read the
// authoritative subject row; never fall back to the candidate snapshot.
const winner = await this.get(candidate.subjectKey);
if (winner) return this.existingSubject(winner, candidate.bindingId);

// No row for this subject means another subject owns the unique binding.
throw new FailClosed(
409,
"binding_conflict",
"binding id is already assigned to another subject",
);
}

private existingSubject(
row: HostedAccountRecord,
bindingId: string,
): HostedAccountRecord {
if (row.bindingId !== bindingId) {
throw new FailClosed(
409,
"duplicate_subject_conflict",
"subject key is already bound to a different binding id; failing closed",
);
}
return row;
}
}
150 changes: 150 additions & 0 deletions pkgs/id/hosted-worker/test/persistent-account-directory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { DatabaseSync } from "node:sqlite";
import { test } from "node:test";
import {
PersistentHostedAccountDirectory,
type HostedDirectoryDatabase,
type HostedDirectoryStatement,
} from "../src/persistent-account-directory.ts";
import { FailClosed } from "../src/routing.ts";

const BINDING = "0123456789abcdef0123456789abcdef";
const OTHER_BINDING = "fedcba9876543210fedcba9876543210";

function sqliteD1(db: DatabaseSync): HostedDirectoryDatabase {
return {
prepare(query: string): HostedDirectoryStatement {
let values: Array<string | number | null> = [];
return {
bind(...bound) {
values = bound;
return this;
},
async first<T extends Record<string, unknown>>() {
// Yield before each statement so concurrent signup calls can both
// observe a missing subject before SQLite serializes their inserts.
await Promise.resolve();
return (db.prepare(query).get(...values) as T | undefined) ?? null;
},
};
},
};
}

async function createTestDirectory() {
const db = new DatabaseSync(":memory:");
const schema = await readFile(
new URL("../migrations/0001_hosted_accounts.sql", import.meta.url),
"utf8",
);
db.exec(schema);
return { db, directory: new PersistentHostedAccountDirectory(sqliteD1(db)) };
}

test("persistent duplicate signup returns the stored row without changing its policy", async () => {
const { db, directory: accountDirectory } = await createTestDirectory();
try {
const first = await accountDirectory.signup({
subjectKey: "subject-1",
bindingId: BINDING,
jurisdiction: "eu",
});
const duplicate = await accountDirectory.signup({
subjectKey: "subject-1",
bindingId: BINDING,
jurisdiction: "us",
});
assert.deepEqual(duplicate, first);
assert.equal(
db.prepare("SELECT COUNT(*) AS count FROM hosted_accounts").get()?.count,
1,
);
} finally {
db.close();
}
});

test("concurrent persistent signups for one subject preserve exactly one row", async () => {
const { db, directory: accountDirectory } = await createTestDirectory();
try {
const [left, right] = await Promise.all([
accountDirectory.signup({
subjectKey: "subject-race",
bindingId: BINDING,
jurisdiction: "eu",
}),
accountDirectory.signup({
subjectKey: "subject-race",
bindingId: BINDING,
jurisdiction: "us",
}),
]);
assert.deepEqual(left, right);
assert.equal(
db.prepare("SELECT COUNT(*) AS count FROM hosted_accounts").get()?.count,
1,
);
assert.ok(["eu", "us"].includes(left.jurisdiction));
} finally {
db.close();
}
});

test("persistent signup rejects conflicting subject and binding mappings", async () => {
const { db, directory: accountDirectory } = await createTestDirectory();
try {
await accountDirectory.signup({
subjectKey: "subject-1",
bindingId: BINDING,
jurisdiction: "eu",
});
await assert.rejects(
accountDirectory.signup({
subjectKey: "subject-1",
bindingId: OTHER_BINDING,
jurisdiction: "eu",
}),
(error: unknown) =>
error instanceof FailClosed &&
error.code === "duplicate_subject_conflict",
);
await assert.rejects(
accountDirectory.signup({
subjectKey: "subject-2",
bindingId: BINDING,
jurisdiction: "eu",
}),
(error: unknown) =>
error instanceof FailClosed && error.code === "binding_conflict",
);
assert.equal(
db.prepare("SELECT COUNT(*) AS count FROM hosted_accounts").get()?.count,
1,
);
} finally {
db.close();
}
});

test("persistent signup fails closed before creating a row for invalid jurisdiction", async () => {
const { db, directory: accountDirectory } = await createTestDirectory();
try {
await assert.rejects(
accountDirectory.signup({
subjectKey: "subject-1",
bindingId: BINDING,
jurisdiction: "unknown",
}),
(error: unknown) =>
error instanceof FailClosed &&
error.code === "unsupported_jurisdiction",
);
assert.equal(
db.prepare("SELECT COUNT(*) AS count FROM hosted_accounts").get()?.count,
0,
);
} finally {
db.close();
}
});