diff --git a/pkgs/id/hosted-worker/references/migrations/0001_reference_record.sql b/pkgs/id/hosted-worker/references/migrations/0001_reference_record.sql new file mode 100644 index 0000000000..ffbf1ab63e --- /dev/null +++ b/pkgs/id/hosted-worker/references/migrations/0001_reference_record.sql @@ -0,0 +1,97 @@ +-- 0001_reference_record.sql +-- +-- Reference record schema for the content-addressed media/data plane +-- (component F of #9078, issue #12803, slice 1 of #9084; design record +-- doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane, +-- sections 4-6). +-- +-- This migration runs in the TENANT and PUBLIC databases of component +-- E's data plane (#9083 design section 2.2) -- one copy per database +-- that can hold references. It is NOT part of the central tenancy +-- schema (tenancy/migrations/, #12796): reference rows are tenant +-- data. The central DB never holds them; its publish_record table is +-- the central-plane projection of publication, not the reference +-- itself. The references ARE the rows in the tenant and public +-- databases; GC reads them (design section 6), there is no separate +-- reference registry. +-- +-- A row carries exactly what the design requires (section "For +-- component E"): content ID, partition, class, created-by, tombstone +-- state. +-- +-- content_id the #9106 Part A content address (sha256, 64 +-- lowercase hex, the shape the landed `blobs` +-- table in src/user-do.ts already uses). An +-- identifier, never a credential: a row's +-- existence may be learnable, bytes are served +-- only after the access check in src/references.ts. +-- jurisdiction + the dedup partition (#3401). Content never +-- sensitivity_tier dedups across partitions and a reference never +-- grants outside its own partition, so both +-- halves are stored on the row and checked at +-- resolution time (design section 5). +-- class what this reference authorizes. `standard` is +-- the ordinary tenant reference; `restricted` +-- is the restricted class capability minting +-- additionally requires for tenant-restricted +-- content, set only by an authorized writer of +-- the source content; `publication` marks a +-- publication reference and is only valid in the +-- public database at tier `public`. +-- created_by binding_id of the writer (32 lowercase hex, +-- the pkgs/id hosted binding shape). References +-- are written only through the hosting database's +-- authorized write path (design section 5). +-- tombstone state tombstoned_at NULL means live. Removal +-- tombstones; rows are never hard-deleted here, +-- because the tombstone is the authoritative +-- state the GC sweep re-verifies against and +-- the audit trail of who lost access when. +-- +-- The outbox is the contract the derived reference/location index +-- (#12805) and the GC worker (#12806) consume: one event per create +-- and per remove, appended with the reference change itself. +-- Consumers page by `seq` and dedupe by `event_id` (at-least-once). +-- The index built from these events is a cache; this table and +-- content_reference are the authority. + +CREATE TABLE IF NOT EXISTS content_reference ( + reference_id TEXT PRIMARY KEY, + content_id TEXT NOT NULL, + jurisdiction TEXT NOT NULL, + sensitivity_tier TEXT NOT NULL, + class TEXT NOT NULL, + created_by TEXT NOT NULL, + created_at TEXT NOT NULL, + tombstoned_at TEXT, + CHECK (jurisdiction IN ('us','eu','fedramp')), + CHECK (sensitivity_tier IN ('public','tenant-private','tenant-restricted','staging')), + CHECK (class IN ('standard','restricted','publication')) +); + +-- Referencing is idempotent (design section 6): at most one LIVE +-- reference per (content, partition, class, writer). Re-creating an +-- existing live reference returns the existing row and emits no +-- second outbox event. +CREATE UNIQUE INDEX IF NOT EXISTS content_reference_one_live + ON content_reference (content_id, jurisdiction, sensitivity_tier, class, created_by) + WHERE tombstoned_at IS NULL; + +-- The access check and the GC mark phase both scan by content within +-- a partition. +CREATE INDEX IF NOT EXISTS content_reference_by_content + ON content_reference (content_id, jurisdiction, sensitivity_tier); + +CREATE TABLE IF NOT EXISTS reference_outbox ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + event_id TEXT NOT NULL UNIQUE, + event_type TEXT NOT NULL, + reference_id TEXT NOT NULL, + content_id TEXT NOT NULL, + jurisdiction TEXT NOT NULL, + sensitivity_tier TEXT NOT NULL, + class TEXT NOT NULL, + actor TEXT NOT NULL, + occurred_at TEXT NOT NULL, + CHECK (event_type IN ('reference.created','reference.removed')) +); diff --git a/pkgs/id/hosted-worker/src/references.ts b/pkgs/id/hosted-worker/src/references.ts new file mode 100644 index 0000000000..528c4928e9 --- /dev/null +++ b/pkgs/id/hosted-worker/src/references.ts @@ -0,0 +1,420 @@ +// Reference records for the content-addressed media/data plane +// (component F of #9078, issue #12803, slice 1 of #9084; design +// record doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane, +// sections 4-6). +// +// The schema lives in references/migrations/0001_reference_record.sql +// and runs in each tenant database and in the public database of +// component E's data plane (#9083 section 2.2) -- never in the +// central tenancy DB. This module is the store and the access check +// over that schema, written against the same minimal SqlStorage +// interface as user-do.ts so it runs unchanged on a Durable Object's +// SQLite storage or any SQLite/Turso database behind that interface. +// +// The access rule (design section 5), evaluated against authoritative +// reference state at capability-minting time: a caller may read +// content C in partition P iff +// 1. a live (non-tombstoned) reference to C exists in a database +// the caller is authorized to read, the reference's partition +// equals P, and the reference's class permits the operation; or +// 2. a live publication reference to C exists in the public DB +// (tier `public` only). +// A content hash is an identifier, never a credential: this check is +// the only path, and it never grants on hash presentation alone. +// Capability minting itself is slice #12807; this module is the +// check that slice must call. + +import { FailClosed, parseBindingId, type Jurisdiction } from "./routing.ts"; + +export type { Jurisdiction }; + +/** Sensitivity tiers (design section 4). A partition is the pair + * (jurisdiction, sensitivity tier); content never dedups across + * partitions (#3401). */ +export const SENSITIVITY_TIERS = ["public", "tenant-private", "tenant-restricted", "staging"] as const; +export type SensitivityTier = (typeof SENSITIVITY_TIERS)[number]; + +export interface Partition { + jurisdiction: Jurisdiction; + tier: SensitivityTier; +} + +/** Reference classes (design sections 4-5). `standard` is the + * ordinary tenant reference. `restricted` is the class capability + * minting additionally requires for tenant-restricted content; it + * may only be set by an authorized writer of the source content. + * `publication` marks a publication reference: valid only in the + * public database, only at tier `public`. */ +export const REFERENCE_CLASSES = ["standard", "restricted", "publication"] as const; +export type ReferenceClass = (typeof REFERENCE_CLASSES)[number]; + +export interface ReferenceRow { + reference_id: string; + content_id: string; + jurisdiction: Jurisdiction; + sensitivity_tier: SensitivityTier; + class: ReferenceClass; + created_by: string; + created_at: string; + tombstoned_at: string | null; +} + +export type ReferenceEventType = "reference.created" | "reference.removed"; + +export interface ReferenceEvent { + seq: number; + event_id: string; + event_type: ReferenceEventType; + reference_id: string; + content_id: string; + jurisdiction: Jurisdiction; + sensitivity_tier: SensitivityTier; + class: ReferenceClass; + actor: string; + occurred_at: string; +} + +interface SqlStorage { + exec(query: string, ...params: unknown[]): { toArray(): Record[] }; +} + +const CONTENT_ID_RE = /^[0-9a-f]{64}$/; + +/** Content IDs are #9106 Part A content addresses; in this plane the + * sha256 shape the landed `blobs` table already uses. Validation is + * shape-only -- a well-formed hash still grants nothing by itself. */ +export function parseContentId(raw: string): string { + if (!CONTENT_ID_RE.test(raw)) { + throw new FailClosed(400, "invalid_content_id", "content id must be 64 lowercase hex characters"); + } + return raw; +} + +function randomHexId(): string { + const bytes = new Uint8Array(16); + crypto.getRandomValues(bytes); + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +/** The DDL of references/migrations/0001_reference_record.sql, one + * statement per entry. The migration file is the canonical artifact + * for Turso-side application; this copy bootstraps stores that own + * their schema (the DO pattern of user-do.ts). A test asserts the + * two cannot drift. */ +export const REFERENCE_SCHEMA_STATEMENTS: readonly string[] = [ + `CREATE TABLE IF NOT EXISTS content_reference ( + reference_id TEXT PRIMARY KEY, + content_id TEXT NOT NULL, + jurisdiction TEXT NOT NULL, + sensitivity_tier TEXT NOT NULL, + class TEXT NOT NULL, + created_by TEXT NOT NULL, + created_at TEXT NOT NULL, + tombstoned_at TEXT, + CHECK (jurisdiction IN ('us','eu','fedramp')), + CHECK (sensitivity_tier IN ('public','tenant-private','tenant-restricted','staging')), + CHECK (class IN ('standard','restricted','publication')) +)`, + `CREATE UNIQUE INDEX IF NOT EXISTS content_reference_one_live + ON content_reference (content_id, jurisdiction, sensitivity_tier, class, created_by) + WHERE tombstoned_at IS NULL`, + `CREATE INDEX IF NOT EXISTS content_reference_by_content + ON content_reference (content_id, jurisdiction, sensitivity_tier)`, + `CREATE TABLE IF NOT EXISTS reference_outbox ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + event_id TEXT NOT NULL UNIQUE, + event_type TEXT NOT NULL, + reference_id TEXT NOT NULL, + content_id TEXT NOT NULL, + jurisdiction TEXT NOT NULL, + sensitivity_tier TEXT NOT NULL, + class TEXT NOT NULL, + actor TEXT NOT NULL, + occurred_at TEXT NOT NULL, + CHECK (event_type IN ('reference.created','reference.removed')) +)`, +]; + +function toReferenceRow(r: Record): ReferenceRow { + return { + reference_id: String(r.reference_id), + content_id: String(r.content_id), + jurisdiction: String(r.jurisdiction) as Jurisdiction, + sensitivity_tier: String(r.sensitivity_tier) as SensitivityTier, + class: String(r.class) as ReferenceClass, + created_by: String(r.created_by), + created_at: String(r.created_at), + tombstoned_at: r.tombstoned_at === null ? null : String(r.tombstoned_at), + }; +} + +function toReferenceEvent(r: Record): ReferenceEvent { + return { + seq: Number(r.seq), + event_id: String(r.event_id), + event_type: String(r.event_type) as ReferenceEventType, + reference_id: String(r.reference_id), + content_id: String(r.content_id), + jurisdiction: String(r.jurisdiction) as Jurisdiction, + sensitivity_tier: String(r.sensitivity_tier) as SensitivityTier, + class: String(r.class) as ReferenceClass, + actor: String(r.actor), + occurred_at: String(r.occurred_at), + }; +} + +export interface CreateReferenceInput { + contentId: string; + refClass: ReferenceClass; + /** binding_id of the writer, via the hosting DB's authorized write + * path (the caller of this store has already authenticated it). */ + createdBy: string; + /** True only when createdBy is an authorized writer of the source + * content. Required to mint a `restricted`-class reference + * (design section 5); ignored for other classes. */ + canMintRestricted?: boolean; + now?: string; +} + +/** One database's reference store. The store is bound to the + * database's own partition: rows it writes carry that partition, so + * a reference can never be forged into a different partition from + * inside this database (design section 5). Whether the database is + * the public DB is a fact about the database, stated at + * construction, not a per-call claim. */ +export class ReferenceStore { + private sql: SqlStorage; + readonly dbId: string; + readonly partition: Partition; + readonly isPublicDb: boolean; + private newId: () => string; + + constructor( + sql: SqlStorage, + opts: { dbId: string; partition: Partition; isPublicDb?: boolean; newId?: () => string }, + ) { + this.sql = sql; + this.dbId = opts.dbId; + this.partition = opts.partition; + this.isPublicDb = opts.isPublicDb ?? false; + this.newId = opts.newId ?? randomHexId; + } + + ensureSchema(): void { + for (const stmt of REFERENCE_SCHEMA_STATEMENTS) this.sql.exec(stmt); + } + + /** Create a reference in this database. Idempotent: if the same + * writer already holds a live reference with the same content, + * partition and class, the existing row is returned with + * `created: false` and no second outbox event is emitted (design + * section 6: referencing is idempotent and never needs to know GC + * exists). */ + createReference(input: CreateReferenceInput): { row: ReferenceRow; created: boolean } { + const contentId = parseContentId(input.contentId); + const createdBy = parseBindingId(input.createdBy); + if (!REFERENCE_CLASSES.includes(input.refClass)) { + throw new FailClosed(400, "invalid_reference_class", `unknown reference class: ${input.refClass}`); + } + if (this.partition.tier === "staging") { + // Staged content is not yet referenceable (design section 4): + // publication happens only after verification, elsewhere. + throw new FailClosed(409, "staging_not_referenceable", "staged content cannot be referenced"); + } + if (input.refClass === "restricted" && input.canMintRestricted !== true) { + throw new FailClosed( + 403, + "restricted_class_not_authorized", + "minting a restricted-class reference requires an authorized writer of the source content", + ); + } + if (input.refClass === "publication" && !(this.isPublicDb && this.partition.tier === "public")) { + throw new FailClosed( + 403, + "publication_reference_outside_public_db", + "a publication reference is only valid in the public database at tier public", + ); + } + const existing = this.sql + .exec( + `SELECT * FROM content_reference + WHERE content_id = ? AND jurisdiction = ? AND sensitivity_tier = ? + AND class = ? AND created_by = ? AND tombstoned_at IS NULL`, + contentId, + this.partition.jurisdiction, + this.partition.tier, + input.refClass, + createdBy, + ) + .toArray()[0]; + if (existing) return { row: toReferenceRow(existing), created: false }; + + const now = input.now ?? new Date().toISOString(); + const row: ReferenceRow = { + reference_id: this.newId(), + content_id: contentId, + jurisdiction: this.partition.jurisdiction, + sensitivity_tier: this.partition.tier, + class: input.refClass, + created_by: createdBy, + created_at: now, + tombstoned_at: null, + }; + this.sql.exec( + `INSERT INTO content_reference + (reference_id, content_id, jurisdiction, sensitivity_tier, class, created_by, created_at, tombstoned_at) + VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`, + row.reference_id, + row.content_id, + row.jurisdiction, + row.sensitivity_tier, + row.class, + row.created_by, + row.created_at, + ); + this.appendEvent("reference.created", row, createdBy, now); + return { row, created: true }; + } + + /** Remove a reference: tombstone it and emit the outbox event the + * index and GC consume. Revocation is reference removal (design + * section 5): after this returns, the row grants nothing. + * Removing an already-tombstoned reference is a no-op returning + * false; removing an unknown id fails closed. */ + removeReference(referenceId: string, opts: { actor: string; now?: string }): boolean { + const actor = parseBindingId(opts.actor); + const found = this.sql + .exec("SELECT * FROM content_reference WHERE reference_id = ?", referenceId) + .toArray()[0]; + if (!found) { + throw new FailClosed(404, "reference_not_found", `no reference ${referenceId} in this database`); + } + const row = toReferenceRow(found); + if (row.tombstoned_at !== null) return false; + const now = opts.now ?? new Date().toISOString(); + this.sql.exec( + "UPDATE content_reference SET tombstoned_at = ? WHERE reference_id = ?", + now, + referenceId, + ); + this.appendEvent("reference.removed", { ...row, tombstoned_at: now }, actor, now); + return true; + } + + /** All references (live and tombstoned) to a content ID in this + * database, oldest first. The access check filters further; the + * GC sweep uses the full set. */ + referencesFor(contentId: string): ReferenceRow[] { + return this.sql + .exec("SELECT * FROM content_reference WHERE content_id = ? ORDER BY created_at, reference_id", parseContentId(contentId)) + .toArray() + .map(toReferenceRow); + } + + /** Outbox events after a consumer cursor (`seq`), oldest first. + * Delivery is at-least-once; consumers dedupe by event_id. */ + outboxAfter(afterSeq: number, limit = 500): ReferenceEvent[] { + return this.sql + .exec("SELECT * FROM reference_outbox WHERE seq > ? ORDER BY seq LIMIT ?", afterSeq, limit) + .toArray() + .map(toReferenceEvent); + } + + private appendEvent(type: ReferenceEventType, row: ReferenceRow, actor: string, now: string): void { + this.sql.exec( + `INSERT INTO reference_outbox + (event_id, event_type, reference_id, content_id, jurisdiction, sensitivity_tier, class, actor, occurred_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + this.newId(), + type, + row.reference_id, + row.content_id, + row.jurisdiction, + row.sensitivity_tier, + row.class, + actor, + now, + ); + } +} + +export interface AccessRequest { + contentId: string; + /** The partition of the OBJECT being read. A reference grants only + * inside its own partition; a mismatch is a refusal, never a + * fallback (design section 5). */ + partition: Partition; + /** Databases the caller is authorized to read (component E check, + * resolved by the caller of this function). */ + authorizedDbs: ReferenceStore[]; + /** The public database's store, when the deployment has one. + * Consulted only for tier `public`, only for publication + * references. */ + publicDb?: ReferenceStore; +} + +export interface AccessDecision { + allowed: boolean; + via: "reference" | "publication" | null; + /** The granting reference, when allowed. */ + referenceId: string | null; + /** The database holding the granting reference, when allowed. */ + dbId: string | null; + reason: string; +} + +function classPermits(refClass: ReferenceClass, partition: Partition): boolean { + // A publication reference grants only through rule 2, in the + // public DB -- never as an ordinary in-DB reference. + if (refClass === "publication") return false; + // Tenant-restricted content: capability minting additionally + // requires the restricted class on the reference record. + if (partition.tier === "tenant-restricted") return refClass === "restricted"; + return refClass === "standard" || refClass === "restricted"; +} + +function samePartition(row: ReferenceRow, partition: Partition): boolean { + return row.jurisdiction === partition.jurisdiction && row.sensitivity_tier === partition.tier; +} + +/** The design section 5 access check. Pure over the given stores' + * current rows: it reads authoritative reference state and grants + * nothing that is not backed by a live row. */ +export function checkAccess(req: AccessRequest): AccessDecision { + const contentId = parseContentId(req.contentId); + for (const store of req.authorizedDbs) { + for (const row of store.referencesFor(contentId)) { + if (row.tombstoned_at !== null) continue; + if (!samePartition(row, req.partition)) continue; + if (!classPermits(row.class, req.partition)) continue; + return { + allowed: true, + via: "reference", + referenceId: row.reference_id, + dbId: store.dbId, + reason: `live ${row.class} reference in authorized database ${store.dbId}`, + }; + } + } + if (req.partition.tier === "public" && req.publicDb) { + for (const row of req.publicDb.referencesFor(contentId)) { + if (row.tombstoned_at !== null) continue; + if (!samePartition(row, req.partition)) continue; + if (row.class !== "publication") continue; + return { + allowed: true, + via: "publication", + referenceId: row.reference_id, + dbId: req.publicDb.dbId, + reason: "live publication reference in the public database", + }; + } + } + return { + allowed: false, + via: null, + referenceId: null, + dbId: null, + reason: "no live reference in an authorized database and no live publication reference", + }; +} diff --git a/pkgs/id/hosted-worker/test/references.test.ts b/pkgs/id/hosted-worker/test/references.test.ts new file mode 100644 index 0000000000..2765c27cb0 --- /dev/null +++ b/pkgs/id/hosted-worker/test/references.test.ts @@ -0,0 +1,276 @@ +// Issue #12803 (component F slice 1 of #9084): the reference record +// schema and the design section 5 access check, proven against the +// real ReferenceStore with in-memory SQLite (node:sqlite) behind its +// SQL interface -- the same harness shape as test/blobs.test.ts. +// Acceptance coverage: live/tombstoned references, cross-partition +// refusal, restricted-class minting, publication references, and the +// create/remove outbox the index (#12805) and GC (#12806) consume. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; +import { + ReferenceStore, + checkAccess, + REFERENCE_SCHEMA_STATEMENTS, + type Partition, +} from "../src/references.ts"; +import { FailClosed } from "../src/routing.ts"; + +const WRITER = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const OTHER_WRITER = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +const CONTENT = "ab".repeat(32); +const OTHER_CONTENT = "cd".repeat(32); +const T0 = "2026-11-23T00:00:00.000Z"; +const T1 = "2026-11-23T01:00:00.000Z"; + +function fakeSql() { + const db = new DatabaseSync(":memory:"); + return { + exec(query: string, ...params: unknown[]) { + const stmt = db.prepare(query); + if (/^\s*select/i.test(query)) { + const rows = stmt.all(...(params as never[])) as Record[]; + return { toArray: () => rows }; + } + stmt.run(...(params as never[])); + return { toArray: () => [] as Record[] }; + }, + }; +} + +function makeStore(dbId: string, partition: Partition, isPublicDb = false): ReferenceStore { + let n = 0; + const store = new ReferenceStore(fakeSql(), { + dbId, + partition, + isPublicDb, + newId: () => (++n).toString(16).padStart(32, "0"), + }); + store.ensureSchema(); + return store; +} + +const US_PRIVATE: Partition = { jurisdiction: "us", tier: "tenant-private" }; +const EU_PRIVATE: Partition = { jurisdiction: "eu", tier: "tenant-private" }; +const US_RESTRICTED: Partition = { jurisdiction: "us", tier: "tenant-restricted" }; +const US_PUBLIC: Partition = { jurisdiction: "us", tier: "public" }; + +test("migration file and embedded schema statements cannot drift", () => { + const url = new URL("../references/migrations/0001_reference_record.sql", import.meta.url); + const fileSql = readFileSync(url, "utf8") + .split("\n") + .filter((line) => !line.trimStart().startsWith("--")) + .join(" ") + .replace(/\s+/g, " ") + .trim(); + for (const stmt of REFERENCE_SCHEMA_STATEMENTS) { + const normalized = stmt.replace(/\s+/g, " ").trim(); + assert.ok(fileSql.includes(normalized), `migration file is missing statement: ${normalized.slice(0, 60)}...`); + } + const creates = fileSql.match(/CREATE /g) ?? []; + assert.equal(creates.length, REFERENCE_SCHEMA_STATEMENTS.length); +}); + +test("a live reference grants read in its own partition via an authorized database", () => { + const tenant = makeStore("tenant-a", US_PRIVATE); + const { row, created } = tenant.createReference({ + contentId: CONTENT, + refClass: "standard", + createdBy: WRITER, + now: T0, + }); + assert.equal(created, true); + assert.equal(row.tombstoned_at, null); + const decision = checkAccess({ contentId: CONTENT, partition: US_PRIVATE, authorizedDbs: [tenant] }); + assert.equal(decision.allowed, true); + assert.equal(decision.via, "reference"); + assert.equal(decision.referenceId, row.reference_id); + assert.equal(decision.dbId, "tenant-a"); +}); + +test("the hash alone grants nothing: no reference, no access", () => { + const tenant = makeStore("tenant-a", US_PRIVATE); + const decision = checkAccess({ contentId: CONTENT, partition: US_PRIVATE, authorizedDbs: [tenant] }); + assert.equal(decision.allowed, false); + assert.equal(decision.via, null); +}); + +test("a tombstoned reference grants nothing; removal is revocation", () => { + const tenant = makeStore("tenant-a", US_PRIVATE); + const { row } = tenant.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }); + assert.equal(checkAccess({ contentId: CONTENT, partition: US_PRIVATE, authorizedDbs: [tenant] }).allowed, true); + assert.equal(tenant.removeReference(row.reference_id, { actor: WRITER, now: T1 }), true); + assert.equal(checkAccess({ contentId: CONTENT, partition: US_PRIVATE, authorizedDbs: [tenant] }).allowed, false); + // The row survives as a tombstone -- the state GC re-verifies against. + const rows = tenant.referencesFor(CONTENT); + assert.equal(rows.length, 1); + assert.equal(rows[0].tombstoned_at, T1); +}); + +test("a reference in a database the caller is not authorized for grants nothing", () => { + const mine = makeStore("tenant-a", US_PRIVATE); + const theirs = makeStore("tenant-b", US_PRIVATE); + theirs.createReference({ contentId: CONTENT, refClass: "standard", createdBy: OTHER_WRITER, now: T0 }); + const decision = checkAccess({ contentId: CONTENT, partition: US_PRIVATE, authorizedDbs: [mine] }); + assert.equal(decision.allowed, false); +}); + +test("cross-partition refusal: a reference never grants outside its own partition", () => { + const eu = makeStore("tenant-eu", EU_PRIVATE); + eu.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }); + // Same content, same tier, different jurisdiction: refused. + assert.equal(checkAccess({ contentId: CONTENT, partition: US_PRIVATE, authorizedDbs: [eu] }).allowed, false); + // Same jurisdiction, different tier: refused. + const us = makeStore("tenant-us", US_PRIVATE); + us.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }); + assert.equal(checkAccess({ contentId: CONTENT, partition: US_PUBLIC, authorizedDbs: [us] }).allowed, false); + // And the in-partition check still passes, so the refusals above + // are the partition rule, not a broken store. + assert.equal(checkAccess({ contentId: CONTENT, partition: EU_PRIVATE, authorizedDbs: [eu] }).allowed, true); +}); + +test("publication: a live publication reference in the public DB grants any caller, unpublish revokes", () => { + const publicDb = makeStore("public", US_PUBLIC, true); + const { row } = publicDb.createReference({ + contentId: CONTENT, + refClass: "publication", + createdBy: WRITER, + now: T0, + }); + // No authorized tenant DBs at all -- the publication reference is + // the grant (design section 5, rule 2). + const decision = checkAccess({ contentId: CONTENT, partition: US_PUBLIC, authorizedDbs: [], publicDb }); + assert.equal(decision.allowed, true); + assert.equal(decision.via, "publication"); + assert.equal(decision.dbId, "public"); + // Publication never leaks into a tenant partition. + assert.equal( + checkAccess({ contentId: CONTENT, partition: US_PRIVATE, authorizedDbs: [], publicDb }).allowed, + false, + ); + // Unpublishing is reference removal. + publicDb.removeReference(row.reference_id, { actor: WRITER, now: T1 }); + assert.equal( + checkAccess({ contentId: CONTENT, partition: US_PUBLIC, authorizedDbs: [], publicDb }).allowed, + false, + ); +}); + +test("a publication reference cannot be minted outside the public database", () => { + const tenant = makeStore("tenant-a", US_PRIVATE); + assert.throws( + () => tenant.createReference({ contentId: CONTENT, refClass: "publication", createdBy: WRITER, now: T0 }), + (e: unknown) => e instanceof FailClosed && e.code === "publication_reference_outside_public_db", + ); +}); + +test("restricted-class minting requires an authorized writer of the source content", () => { + const tenant = makeStore("tenant-r", US_RESTRICTED); + assert.throws( + () => tenant.createReference({ contentId: CONTENT, refClass: "restricted", createdBy: WRITER, now: T0 }), + (e: unknown) => e instanceof FailClosed && e.code === "restricted_class_not_authorized", + ); + const { created } = tenant.createReference({ + contentId: CONTENT, + refClass: "restricted", + createdBy: WRITER, + canMintRestricted: true, + now: T0, + }); + assert.equal(created, true); +}); + +test("tenant-restricted access requires the restricted class on the reference", () => { + const tenant = makeStore("tenant-r", US_RESTRICTED); + // A standard-class reference in the same partition is not enough. + tenant.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }); + assert.equal( + checkAccess({ contentId: CONTENT, partition: US_RESTRICTED, authorizedDbs: [tenant] }).allowed, + false, + ); + // The restricted class is. + tenant.createReference({ + contentId: CONTENT, + refClass: "restricted", + createdBy: WRITER, + canMintRestricted: true, + now: T0, + }); + const decision = checkAccess({ contentId: CONTENT, partition: US_RESTRICTED, authorizedDbs: [tenant] }); + assert.equal(decision.allowed, true); + assert.equal(decision.via, "reference"); +}); + +test("referencing is idempotent: a duplicate live create returns the row and emits no second event", () => { + const tenant = makeStore("tenant-a", US_PRIVATE); + const first = tenant.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }); + const second = tenant.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T1 }); + assert.equal(second.created, false); + assert.equal(second.row.reference_id, first.row.reference_id); + assert.equal(tenant.outboxAfter(0).filter((e) => e.event_type === "reference.created").length, 1); +}); + +test("create and remove emit outbox events the index and GC consume, pageable by seq", () => { + const tenant = makeStore("tenant-a", US_PRIVATE); + const { row } = tenant.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }); + tenant.createReference({ contentId: OTHER_CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }); + tenant.removeReference(row.reference_id, { actor: WRITER, now: T1 }); + + const events = tenant.outboxAfter(0); + assert.equal(events.length, 3); + assert.deepEqual( + events.map((e) => e.event_type), + ["reference.created", "reference.created", "reference.removed"], + ); + const removed = events[2]; + assert.equal(removed.reference_id, row.reference_id); + assert.equal(removed.content_id, CONTENT); + assert.equal(removed.jurisdiction, "us"); + assert.equal(removed.sensitivity_tier, "tenant-private"); + assert.equal(removed.class, "standard"); + assert.equal(removed.actor, WRITER); + assert.equal(removed.occurred_at, T1); + // A consumer resuming from its cursor sees only what is new. + assert.deepEqual( + tenant.outboxAfter(events[1].seq).map((e) => e.event_type), + ["reference.removed"], + ); +}); + +test("removing an unknown reference fails closed; a second remove is a no-op with no second event", () => { + const tenant = makeStore("tenant-a", US_PRIVATE); + const missing = "f".repeat(32); + assert.throws( + () => tenant.removeReference(missing, { actor: WRITER, now: T0 }), + (e: unknown) => e instanceof FailClosed && e.code === "reference_not_found", + ); + const { row } = tenant.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }); + assert.equal(tenant.removeReference(row.reference_id, { actor: WRITER, now: T1 }), true); + assert.equal(tenant.removeReference(row.reference_id, { actor: WRITER, now: T1 }), false); + assert.equal(tenant.outboxAfter(0).filter((e) => e.event_type === "reference.removed").length, 1); +}); + +test("staged content is not referenceable", () => { + const staging = makeStore("staging", { jurisdiction: "us", tier: "staging" }); + assert.throws( + () => staging.createReference({ contentId: CONTENT, refClass: "standard", createdBy: WRITER, now: T0 }), + (e: unknown) => e instanceof FailClosed && e.code === "staging_not_referenceable", + ); +}); + +test("malformed content ids and binding ids fail closed", () => { + const tenant = makeStore("tenant-a", US_PRIVATE); + assert.throws( + () => tenant.createReference({ contentId: "not-a-hash", refClass: "standard", createdBy: WRITER, now: T0 }), + (e: unknown) => e instanceof FailClosed && e.code === "invalid_content_id", + ); + assert.throws( + () => tenant.createReference({ contentId: CONTENT, refClass: "standard", createdBy: "nope", now: T0 }), + (e: unknown) => e instanceof FailClosed, + ); + assert.throws( + () => checkAccess({ contentId: "nope", partition: US_PRIVATE, authorizedDbs: [tenant] }), + (e: unknown) => e instanceof FailClosed && e.code === "invalid_content_id", + ); +});