diff --git a/.changeset/3962-safety-durable-account.md b/.changeset/3962-safety-durable-account.md new file mode 100644 index 0000000000..cdb51829f4 --- /dev/null +++ b/.changeset/3962-safety-durable-account.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +A chat stays continuable after the login that started it is pruned (#3962). Every owner sign-in is its own principal, and cleanup deletes a login 30 days after it expires or is revoked; the chat's safety history then named a principal nobody could vouch for, so every later turn was refused as a safety principal mismatch. The host now stores the account with the safety history when it writes it, from the principal's own row, and another owner login keeps continuing, reading and reviewing that history and its taint. The stored account is no credential: a pruned, expired or revoked login regains nothing, another account is still refused, corrupt or contradictory evidence is refused, and history whose login was already pruned before upgrading stays unknown. Attribution and safety records are not rewritten. diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 7bc3eea9da..58627d516b 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -167,14 +167,40 @@ decides it. A principal id always matches itself. Two different ids match only when both resolve to principals whose `accountScope` is the same partition in every auth mode, which today means two owner logins. An agent, ambient or system principal therefore matches only itself, and a missing or -unresolvable principal (a pruned row, say) matches no other id. The decision -trigger (`087_safety_account_partition.sql`) applies the same rule. +unresolvable principal matches no other id, unless its record stored its +account (#3962, below). The decision trigger +(`089_safety_durable_account.sql`, replacing 087's) applies the same rule. Rows keep the principal that wrote them; nothing is rewritten. What belongs to one login stays exact: a turn's own collection, its catalog creation, read snapshots and cursors, review handles and their receipts, per-principal limits, and the principal a verdict names. +### A chat's safety history outlives its login (#3962) + +Ruled by the maintainer on 2026-11-11 (option A). Principal rows do not last: +cleanup deletes a login 30 days after it expires or is revoked, and the chat +that login started would then refuse every later login. So the host stores +the account with the safety history instead of keeping login rows longer. +`safety_sessions`, `safety_collections` and `dialogue_owners` carry +`principal_account` beside `principal_id`, written by the server from the +principal's own row when the record is written (`principalAccount` in +`account-partition.ts`): `owner` for an owner login, empty for a principal +that is only itself. A request, a client or a model never supplies it. + +`sameAccount` reads a record's stored account only when its principal row is +gone. A live row decides by itself, and a live row that disagrees with the +stored account, or a stored value no host writes, makes the record match +nobody, its own principal included; that refusal stays within the record's +chat. The stored account is evidence, not a credential: the caller is passed +as a bare id and proves its account by its own current row, so a pruned, +expired or revoked login regains nothing. History written before 089 gained an +account only where a principal row still proved it at upgrade; proof already +deleted is not reconstructed, and that history stays unknown. Principal +retention is unchanged, and nothing reaches the provider-facing conversation. +The same stored account is the ownership evidence a voice conversation's +dialogue owner carries. + ## Human authority and policy publication Initially **only a live password-mode human owner** may commit a verdict or diff --git a/docs/http-api.md b/docs/http-api.md index 7bcf216d94..e0cd5b4f9f 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -2258,7 +2258,9 @@ The live principal must belong to the retained history's account (#3952). A principal id always matches itself. Two different ids match only when both resolve to the same account partition in every auth mode, which today means two owner logins; a delegated, ambient or system principal matches only -itself, and a missing or unresolvable principal matches no other id. A cursor +itself, and a missing or unresolvable principal matches no other id, unless +the history recorded the owner account beside it when it was written: an owner +login's history stays the owner's after that login is pruned (#3962). A cursor stays with the one login that read it: another login's cursor is refused as expired (409). The existing native-history and dialogue APIs keep their visibility rules. diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 22a77073e0..2f7e8192bb 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -345,6 +345,24 @@ snapshots, review handles, receipts and the verdict's `principalId` stay bound to the exact principal. Nothing previously accepted is refused, and stored rows are not rewritten ([decision](../decisions/session-safety-reviews.md#a-chats-safety-history-belongs-to-its-account-3952)). + + +### A chat's safety history outlives the login that started it (additive, #3962) + +The same turn, safety read and owner review keep accepting another owner +login after the login that wrote the history has been pruned. The host stores +each safety record's account beside its principal when it writes it, from the +principal's own row, so a pruned owner login's record still names the owner +account. That stored account is never a credential: the caller is still a +current, authorized login, and a pruned, expired or revoked principal gains +nothing. A record written before this change, whose principal is already +gone, stays unknown and refused. Stored evidence that is corrupt, or that a +live principal row contradicts, matches no principal at all, its own +included. Nothing previously accepted is refused except a record whose stored +evidence is contradictory, which no released host writes, and attribution, +records, verdicts, gaps and generations are not rewritten +([decision](../decisions/session-safety-reviews.md#a-chats-safety-history-outlives-its-login-3962)). + ### Root server warning (additive, #1638) diff --git a/packages/ui-server/migrations/089_safety_durable_account.sql b/packages/ui-server/migrations/089_safety_durable_account.sql new file mode 100644 index 0000000000..54cdd7becf --- /dev/null +++ b/packages/ui-server/migrations/089_safety_durable_account.sql @@ -0,0 +1,82 @@ +-- A chat's safety history keeps the account that owned it after the login +-- that wrote it is pruned (#3962). Principal rows do not last: cleanup deletes +-- a login 30 days after it expires or is revoked, and an owner login then +-- became an id nobody could vouch for, so no later login could continue the +-- chat it started. +-- +-- `principal_account` sits beside each record's `principal_id`. The server +-- writes it from the principal row when the record is written: 'owner' for an +-- owner login, NULL for a principal whose account is only itself (an agent, +-- an ambient identity, a system principal). `principal_id` stays the +-- attribution and is never rewritten. The account is evidence, not a +-- credential: the caller still has to be a current, authorized login. +-- +-- Legacy rows gain an account only from verified evidence: a principal row +-- that still exists and is an owner login. A row whose principal is already +-- gone keeps NULL and stays unknown. Nothing is owner by default, and no +-- record, verdict, gap or generation changes. +ALTER TABLE safety_sessions ADD COLUMN principal_account TEXT; +ALTER TABLE safety_collections ADD COLUMN principal_account TEXT; +ALTER TABLE dialogue_owners ADD COLUMN principal_account TEXT; +UPDATE safety_sessions SET principal_account='owner' + WHERE principal_id IN (SELECT id FROM principals WHERE kind='owner'); +UPDATE safety_collections SET principal_account='owner' + WHERE principal_id IN (SELECT id FROM principals WHERE kind='owner'); +UPDATE dialogue_owners SET principal_account='owner' + WHERE principal_id IN (SELECT id FROM principals WHERE kind='owner'); + +-- 081's discovery trigger inserted by position; name the columns now. +DROP TRIGGER IF EXISTS safety_catalog_discovery; +CREATE TRIGGER safety_catalog_discovery AFTER INSERT ON sessions BEGIN + INSERT INTO safety_sessions(session_id,history_owner_id,generation,principal_id,origin_turn,classification,backend_id) + VALUES(NEW.id,lower(hex(randomblob(16))),'1',NULL,NULL,'discovered',NEW.backend_id); + UPDATE safety_meta SET scope_rows=scope_rows+1,scope_bytes=scope_bytes+2048 WHERE singleton=1; +END; + +-- Same account, as `sameAccount` in `src/middleware/account-partition.ts` +-- decides it. A record's evidence is consistent when its account is NULL, or +-- 'owner' with no principal row that says otherwise. Corrupt or +-- contradictory evidence matches nobody, not even its own principal. A +-- consistent record matches its exact principal, and an owner record (its +-- account is 'owner', or it has none and its principal row is an owner login) +-- matches any owner login. Every other boundary of 087 is unchanged. +-- Comparisons use IS: inside the dialogue owner's NOT EXISTS a NULL would +-- skip the rejection and admit the verdict, so no term there may be NULL. +DROP TRIGGER IF EXISTS safety_decision_identity; +CREATE TRIGGER safety_decision_identity BEFORE INSERT ON safety_decisions + WHEN NOT EXISTS ( + SELECT 1 FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id + JOIN safety_sessions s ON s.session_id=NEW.session_id + WHERE r.id=NEW.occurrence_id AND r.kind='occurrence' + AND s.history_owner_id=NEW.history_owner_id AND s.generation=NEW.generation + AND (s.principal_account IS NULL OR (s.principal_account IS 'owner' + AND NOT EXISTS (SELECT 1 FROM principals WHERE id=s.principal_id AND kind<>'owner'))) + AND (s.principal_id=NEW.principal_id OR ( + (s.principal_account IS 'owner' OR EXISTS (SELECT 1 FROM principals WHERE id=s.principal_id AND kind='owner')) + AND EXISTS (SELECT 1 FROM principals WHERE id=NEW.principal_id AND kind='owner'))) + AND (c.principal_account IS NULL OR (c.principal_account IS 'owner' + AND NOT EXISTS (SELECT 1 FROM principals WHERE id=c.principal_id AND kind<>'owner'))) + AND (c.principal_id=NEW.principal_id OR ( + (c.principal_account IS 'owner' OR EXISTS (SELECT 1 FROM principals WHERE id=c.principal_id AND kind='owner')) + AND EXISTS (SELECT 1 FROM principals WHERE id=NEW.principal_id AND kind='owner'))) + AND c.generation=s.generation + AND (c.session_id=s.session_id OR (c.generation=s.generation AND ( + c.history_owner_id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id) + OR c.history_owner_id IN (SELECT id FROM dialogue_aliases WHERE owner_id= + COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id))))) + AND NOT EXISTS (SELECT 1 FROM safety_retired_turns WHERE turn_id=c.turn_id) + AND NOT EXISTS (SELECT 1 FROM chat_retired_identities WHERE kind='session' AND id=s.session_id) + AND NOT EXISTS (SELECT 1 FROM chat_retired_identities WHERE kind='dialogue_owner' AND id=s.history_owner_id) + AND NOT EXISTS (SELECT 1 FROM chat_retired_identities WHERE kind='dialogue_owner' AND id= + COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id)) + AND NOT EXISTS (SELECT 1 FROM dialogue_owners d WHERE d.id= + COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id) + AND (CAST(d.generation AS TEXT) IS NOT NEW.generation + OR NOT (d.principal_account IS NULL OR (d.principal_account IS 'owner' + AND NOT EXISTS (SELECT 1 FROM principals WHERE id=d.principal_id AND kind<>'owner'))) + OR NOT (d.principal_id IS NEW.principal_id OR ( + (d.principal_account IS 'owner' OR EXISTS (SELECT 1 FROM principals WHERE id=d.principal_id AND kind='owner')) + AND EXISTS (SELECT 1 FROM principals WHERE id=NEW.principal_id AND kind='owner'))))) + AND COALESCE((SELECT x.state FROM safety_records x WHERE x.occurrence_id=r.id AND x.kind='exposure' + ORDER BY length(x.sequence) DESC,x.sequence DESC LIMIT 1),r.state)='finalized' + ) BEGIN SELECT RAISE(ABORT,'safety decision identity or exposure mismatch'); END; diff --git a/packages/ui-server/src/governance/safety-history.ts b/packages/ui-server/src/governance/safety-history.ts index f8154f1b12..c229b4d2a5 100644 --- a/packages/ui-server/src/governance/safety-history.ts +++ b/packages/ui-server/src/governance/safety-history.ts @@ -44,21 +44,22 @@ export class SafetyHistory { if(this.closed)throw new SafetyReadUnavailable(); if(!this.valid(principal))throw new SafetyReadUnavailable("unauthorized"); if("sessionId" in target){ - const s=this.db.query("SELECT session_id,history_owner_id,generation,principal_id FROM safety_sessions WHERE session_id=?").get(target.sessionId) as - {session_id:string;history_owner_id:string;generation:string;principal_id:string|null}|null; - // Another login of the chat's account reads it; nobody else does (#3952). - if(!s||!sameAccount(this.db,s.principal_id,principal.id))throw new SafetyReadUnavailable(); - const owner=this.db.query("SELECT principal_id,generation FROM dialogue_owners WHERE id=?").get(s.history_owner_id) as {principal_id:string;generation:number}|null; - if(owner&&(!sameAccount(this.db,owner.principal_id,principal.id)||String(owner.generation)!==s.generation))throw new SafetyReadUnavailable("generation_changed"); + const s=this.db.query("SELECT session_id,history_owner_id,generation,principal_id,principal_account FROM safety_sessions WHERE session_id=?").get(target.sessionId) as + {session_id:string;history_owner_id:string;generation:string;principal_id:string|null;principal_account:string|null}|null; + // Another login of the chat's account reads it; nobody else does + // (#3952). The stored account outlives the login that wrote it (#3962). + if(!s||!sameAccount(this.db,{principalId:s.principal_id,account:s.principal_account},principal.id))throw new SafetyReadUnavailable(); + const owner=this.db.query("SELECT principal_id,principal_account,generation FROM dialogue_owners WHERE id=?").get(s.history_owner_id) as {principal_id:string;principal_account:string|null;generation:number}|null; + if(owner&&(!sameAccount(this.db,{principalId:owner.principal_id,account:owner.principal_account},principal.id)||String(owner.generation)!==s.generation))throw new SafetyReadUnavailable("generation_changed"); try{assertLive(this.db,[["session",s.session_id],["dialogue_owner",s.history_owner_id]]);}catch{throw new SafetyReadUnavailable();} return {sessionId:s.session_id,historyOwnerId:s.history_owner_id,historyGeneration:s.generation}; } - const c=this.db.query("SELECT session_id,principal_id,history_owner_id,generation FROM safety_collections WHERE id=? AND turn_id=?").get(target.bindingId,target.turnId) as - {session_id:string|null;principal_id:string|null;history_owner_id:string;generation:string}|null; - if(!c||!sameAccount(this.db,c.principal_id,principal.id)||this.db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(target.turnId))throw new SafetyReadUnavailable(); + const c=this.db.query("SELECT session_id,principal_id,principal_account,history_owner_id,generation FROM safety_collections WHERE id=? AND turn_id=?").get(target.bindingId,target.turnId) as + {session_id:string|null;principal_id:string|null;principal_account:string|null;history_owner_id:string;generation:string}|null; + if(!c||!sameAccount(this.db,{principalId:c.principal_id,account:c.principal_account},principal.id)||this.db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(target.turnId))throw new SafetyReadUnavailable(); if(c.session_id)return this.authorize(principal,{sessionId:c.session_id}); - const owner=this.db.query("SELECT generation,principal_id FROM dialogue_owners WHERE id=?").get(c.history_owner_id) as {generation:number;principal_id:string}|null; - if(owner&&(String(owner.generation)!==c.generation||!sameAccount(this.db,owner.principal_id,principal.id)))throw new SafetyReadUnavailable("generation_changed"); + const owner=this.db.query("SELECT generation,principal_id,principal_account FROM dialogue_owners WHERE id=?").get(c.history_owner_id) as {generation:number;principal_id:string;principal_account:string|null}|null; + if(owner&&(String(owner.generation)!==c.generation||!sameAccount(this.db,{principalId:owner.principal_id,account:owner.principal_account},principal.id)))throw new SafetyReadUnavailable("generation_changed"); try{assertLive(this.db,[["dialogue_owner",c.history_owner_id]]);}catch{throw new SafetyReadUnavailable();} return {turnId:target.turnId,bindingId:target.bindingId}; } diff --git a/packages/ui-server/src/governance/safety-reviews.ts b/packages/ui-server/src/governance/safety-reviews.ts index 2d8f7648f0..7bae539cce 100644 --- a/packages/ui-server/src/governance/safety-reviews.ts +++ b/packages/ui-server/src/governance/safety-reviews.ts @@ -59,27 +59,30 @@ function receipt(body: SafetyReviewBody, requestId: string | null, operationId: verdict: committed ? "committed" : "unresolved", projection, reason }; } /** Unknown/foreign identity never creates a session or reveals its projection. - * A chat belongs to its account: any owner login reviews it (#3952). */ + * A chat belongs to its account: any owner login reviews it (#3952), after + * the login that wrote it is pruned too (#3962). */ export function safetyReviewTarget(db: Database, body: SafetyReviewBody, principalId: string): "retired" | "unavailable" | null { - const s = db.query(`SELECT principal_id FROM safety_sessions WHERE session_id=? AND history_owner_id=? AND generation=?`) - .get(body.session.sessionId, body.session.historyOwnerId, body.session.historyGeneration) as { principal_id: string | null } | null; - if (!s || !sameAccount(db, s.principal_id, principalId)) return "unavailable"; + const s = db.query(`SELECT principal_id,principal_account FROM safety_sessions WHERE session_id=? AND history_owner_id=? AND generation=?`) + .get(body.session.sessionId, body.session.historyOwnerId, body.session.historyGeneration) as { principal_id: string | null; principal_account: string | null } | null; + if (!s || !sameAccount(db, { principalId: s.principal_id, account: s.principal_account }, principalId)) return "unavailable"; const canonical = (db.query("SELECT owner_id FROM dialogue_aliases WHERE id=?").get(body.session.historyOwnerId) as {owner_id:string}|null)?.owner_id ?? body.session.historyOwnerId; try { assertLive(db, [["session", body.session.sessionId], ["dialogue_owner", body.session.historyOwnerId], ["dialogue_owner",canonical]]); } catch (error) { if (error instanceof ChatRetiredError) return "retired"; throw error; } - const owner = db.query("SELECT generation,principal_id FROM dialogue_owners WHERE id=?").get(canonical) as { generation: number; principal_id: string } | null; - if (owner && (String(owner.generation) !== body.session.historyGeneration || !sameAccount(db, owner.principal_id, principalId))) return "unavailable"; + const owner = db.query("SELECT generation,principal_id,principal_account FROM dialogue_owners WHERE id=?").get(canonical) as + { generation: number; principal_id: string; principal_account: string | null } | null; + if (owner && (String(owner.generation) !== body.session.historyGeneration + || !sameAccount(db, { principalId: owner.principal_id, account: owner.principal_account }, principalId))) return "unavailable"; return null; } function eligible(db: Database, body: SafetyReviewBody, actor: SafetyReviewer): string | null { - const r = db.query(`SELECT c.turn_id,c.principal_id,c.generation,r.state,COALESCE((SELECT x.state FROM safety_records x + const r = db.query(`SELECT c.turn_id,c.principal_id,c.principal_account,c.generation,r.state,COALESCE((SELECT x.state FROM safety_records x WHERE x.occurrence_id=r.id AND x.kind='exposure' ORDER BY length(x.sequence) DESC,x.sequence DESC LIMIT 1),r.state) final_state FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE r.id=? AND r.kind='occurrence'`) - .get(body.occurrenceId) as { turn_id: string; principal_id: string | null; generation: string; final_state: string } | null; + .get(body.occurrenceId) as { turn_id: string; principal_id: string | null; principal_account: string | null; generation: string; final_state: string } | null; // The aggregate also includes adopted provisional collections. Use its // canonical membership; a direct session_id filter strands those events. - if (!r || !sameAccount(db, r.principal_id, actor.principalId) || r.generation !== body.session.historyGeneration || !safetyScopeTurns(db, null, body.session.sessionId).has(r.turn_id) + if (!r || !sameAccount(db, { principalId: r.principal_id, account: r.principal_account }, actor.principalId) || r.generation !== body.session.historyGeneration || !safetyScopeTurns(db, null, body.session.sessionId).has(r.turn_id) || db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(r.turn_id)) return "unavailable"; if (db.query("SELECT 1 FROM safety_decisions WHERE occurrence_id=?").get(body.occurrenceId)) return "already_resolved"; return r.final_state === "finalized" ? null : "not_finalized"; diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index fc2a928182..6bdbfa967a 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -4,7 +4,7 @@ import { safetyQueue } from "./safety-queue.js"; import { assertLive,ChatRetiredError } from "../ws/chat-lifecycle.js"; import { occurrence, type Occurrence } from "./occurrence.js"; import type { GovernanceEventRow } from "./events.js"; -import { sameAccount } from "../middleware/account-partition.js"; +import { principalAccount, sameAccount } from "../middleware/account-partition.js"; const SAFETY_DETECTORS = ["tool_web_input", "tool_file_input", "tool_search_output", "external_mcp_input", "attachment_input", "compute_input", "unproxied_shell_input", "proxy_input", "explicit_untrusted_input"] as const; @@ -24,9 +24,11 @@ export interface SafetyCollectionInput { turnId: string; bindingId: string; prin restricted?: boolean } interface Collection { id: string; turn_id: string; session_id: string | null; principal_id: string | null; history_owner_id: string | null; generation: string; backend_id: string; started_at: number; ended: number; acknowledged: string; gap: string | null; failure: string | null; - policy_hash:string|null; start_revision: string; end_revision: string | null; restricted_begin: number; failure_cause: string | null } + policy_hash:string|null; start_revision: string; end_revision: string | null; restricted_begin: number; failure_cause: string | null; + /** The durable account of `principal_id`, captured by the server when this was written (#3962). */ + principal_account: string | null } interface Session { session_id: string; history_owner_id: string; generation: string; principal_id: string | null; - classification: string; origin_turn: string | null; backend_id: string | null } + classification: string; origin_turn: string | null; backend_id: string | null; principal_account: string | null } export class SafetyUnavailable extends Error { constructor(message: string) { super(message); } } /** What a capacity refusal spent, so a refusal can say what frees it: `turn` * room frees itself (pending writes settle, or only this one record is too @@ -209,16 +211,17 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s if(input.sessionId&&!session)throw new SafetyUnavailable("Unknown safety session; discover catalog history first"); let owner=input.historyOwnerId??session?.history_owner_id??input.bindingId,generation=session?.generation??"1",uncollectedOwner=false; if(owner){ - const d=one<{id:string;principal_id:string;generation:number}|null>(db,`SELECT id,principal_id,generation FROM dialogue_owners + const d=one<{id:string;principal_id:string;principal_account:string|null;generation:number}|null>(db,`SELECT id,principal_id,principal_account,generation FROM dialogue_owners WHERE id=COALESCE((SELECT id FROM dialogue_owners WHERE session_id=?),(SELECT owner_id FROM dialogue_aliases WHERE id=?),?)`,input.sessionId,owner,owner); // A chat's history belongs to its account: another login of the same - // owner continues it, and nobody else does (#3952). - if(d){if(!sameAccount(db,d.principal_id,input.principalId))throw new SafetyUnavailable("Safety history ownership mismatch");owner=d.id;generation=actualGeneration(d.generation); + // owner continues it, and nobody else does (#3952), even after the login + // that wrote it is pruned (#3962). + if(d){if(!sameAccount(db,{principalId:d.principal_id,account:d.principal_account},input.principalId))throw new SafetyUnavailable("Safety history ownership mismatch");owner=d.id;generation=actualGeneration(d.generation); uncollectedOwner=!db.query("SELECT 1 FROM safety_collections WHERE history_owner_id=? AND generation=? LIMIT 1").get(owner,generation); } } assertLive(db,[["dialogue_owner",owner]]); - if(session?.principal_id&&!sameAccount(db,session.principal_id,input.principalId))throw new SafetyUnavailable("Safety principal mismatch"); + if(session?.principal_id&&!sameAccount(db,{principalId:session.principal_id,account:session.principal_account},input.principalId))throw new SafetyUnavailable("Safety principal mismatch"); const n=one<{n:number}>(db, input.sessionId?"SELECT COUNT(*) n FROM safety_collections WHERE session_id=?":"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL",...(input.sessionId?[input.sessionId]:[])); if(n.n>=(input.sessionId?SAFETY_LIMITS.epochs:SAFETY_LIMITS.unbound))throw new SafetyCapacityExhausted("Safety coverage capacity exhausted",input.sessionId?"chat":unboundScope(db)); if(input.sessionId===null){ @@ -232,14 +235,15 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s if(owner&&one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE history_owner_id=? AND generation=?",owner,generation).n>=128)throw new SafetyCapacityExhausted("Safety coverage capacity exhausted","chat"); if(input.policyHash!==undefined&&input.policyHash!==null&&!/^[a-f0-9]{64}$/.test(input.policyHash))throw new SafetyUnavailable("Invalid safety policy hash"); const gap=restricted?"recording_failed":uncollectedOwner?"missing_history_owner_collection":input.sessionId&&!session?.principal_id?"unknown_history_owner":session?.backend_id&&session.backend_id!==input.backendId?"backend_history_not_reconstructed":null; - db.query(`INSERT INTO safety_collections(id,turn_id,session_id,principal_id,history_owner_id,generation,backend_id,started_at,gap,start_revision) - VALUES (?,?,?,?,?,?,?,?,?,?)`).run(input.bindingId,input.turnId,input.sessionId,input.principalId,owner,generation,input.backendId,input.at,gap,advance(db)); + // The account comes from the principal's own row, never from the input. + db.query(`INSERT INTO safety_collections(id,turn_id,session_id,principal_id,principal_account,history_owner_id,generation,backend_id,started_at,gap,start_revision) + VALUES (?,?,?,?,?,?,?,?,?,?,?)`).run(input.bindingId,input.turnId,input.sessionId,input.principalId,principalAccount(db,input.principalId),owner,generation,input.backendId,input.at,gap,advance(db)); db.query("UPDATE safety_collections SET policy_hash=?,restricted_begin=? WHERE id=?").run(input.policyHash??null,restricted?1:0,input.bindingId); db.query("UPDATE safety_meta SET scope_rows=scope_rows+1,scope_bytes=scope_bytes+2048 WHERE singleton=1").run(); if(input.sessionId)bindSafetyCollection(db,input.turnId,input.sessionId); if(input.sourceSessionId){ - const sourceOwner=one<{principal_id:string|null}|null>(db,"SELECT principal_id FROM safety_sessions WHERE session_id=?",input.sourceSessionId); - if(sourceOwner?.principal_id&&!sameAccount(db,sourceOwner.principal_id,input.principalId))throw new SafetyUnavailable("Safety fork history ownership mismatch"); + const sourceOwner=one<{principal_id:string|null;principal_account:string|null}|null>(db,"SELECT principal_id,principal_account FROM safety_sessions WHERE session_id=?",input.sourceSessionId); + if(sourceOwner?.principal_id&&!sameAccount(db,{principalId:sourceOwner.principal_id,account:sourceOwner.principal_account},input.principalId))throw new SafetyUnavailable("Safety fork history ownership mismatch"); safetyProjection(db,null,input.sourceSessionId); // Also validates retirement. db.query("UPDATE safety_collections SET gap=CASE WHEN restricted_begin=1 THEN gap ELSE 'inherited_history_not_reconstructed' END WHERE id=?").run(input.bindingId); const records=db.query(`SELECT r.* FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id @@ -256,16 +260,22 @@ export function safetyCatalogCreated(db:Database,sessionId:string,principalId:st if(db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId))throw new ChatRetiredError(); const c=collection(db,turnId); if(c){assertLive(db,[["dialogue_owner",c.history_owner_id]]);if(c.ended)throw new SafetyUnavailable("Safety collection ended before catalog creation");}if(!c||c.session_id!==null||c.principal_id!==principalId)return; - db.query("UPDATE safety_sessions SET principal_id=?,origin_turn=?,classification='new',history_owner_id=?,generation=? WHERE session_id=? AND classification='discovered'").run(principalId,turnId,c.history_owner_id,c.generation,sessionId); + db.query("UPDATE safety_sessions SET principal_id=?,principal_account=?,origin_turn=?,classification='new',history_owner_id=?,generation=? WHERE session_id=? AND classification='discovered'").run(principalId,c.principal_account,turnId,c.history_owner_id,c.generation,sessionId); } export function bindSafetyCollection(db:Database,turnId:string,sessionId:string):void { const c=collection(db,turnId);if(!c)return; live(db,c); const s=one(db,"SELECT * FROM safety_sessions WHERE session_id=?",sessionId);if(!s)throw new SafetyUnavailable("Safety catalog binding absent"); if(c.session_id&&c.session_id!==sessionId)throw new SafetyUnavailable("Safety binding is once-only"); - const d=one<{id:string;principal_id:string;generation:number}|null>(db,"SELECT id,principal_id,generation FROM dialogue_owners WHERE session_id=?",sessionId); - const principal=d?.principal_id??s.principal_id??one<{principal_id:string}|null>(db,"SELECT principal_id FROM chat_session_owners WHERE session_id=?",sessionId)?.principal_id??null; - if(c.principal_id&&principal&&!sameAccount(db,principal,c.principal_id))throw new SafetyUnavailable("Safety binding owner mismatch"); + const d=one<{id:string;principal_id:string;principal_account:string|null;generation:number}|null>(db,"SELECT id,principal_id,principal_account,generation FROM dialogue_owners WHERE session_id=?",sessionId); + // The chat's owner, with the account its record stored. The catalog owner + // row stores none, so its account is read from the principal's row now. + const catalog=d||s.principal_id?null:one<{principal_id:string}|null>(db,"SELECT principal_id FROM chat_session_owners WHERE session_id=?",sessionId)?.principal_id??null; + const bound=d?{principalId:d.principal_id,account:d.principal_account}:s.principal_id?{principalId:s.principal_id,account:s.principal_account} + :{principalId:catalog,account:principalAccount(db,catalog)}; + const principal=bound.principalId??null; + const writer={principalId:c.principal_id,account:c.principal_account}; + if(c.principal_id&&principal&&!sameAccount(db,bound,writer))throw new SafetyUnavailable("Safety binding owner mismatch"); if(c.history_owner_id&&d&&c.history_owner_id!==d.id&&c.history_owner_id!==s.history_owner_id){ const alias=one<{owner_id:string}|null>(db,"SELECT owner_id FROM dialogue_aliases WHERE id=?",c.history_owner_id); if(alias?.owner_id!==d.id)throw new SafetyUnavailable("Contradictory safety history owner"); @@ -273,9 +283,9 @@ export function bindSafetyCollection(db:Database,turnId:string,sessionId:string) // The catalog announcement precedes DialogueJournal adoption. Resolve both // the native-session owner and the retained provisional owner, never the // discovery row's placeholder generation. - const retained=c.history_owner_id?one<{id:string;principal_id:string;generation:number}|null>(db, - "SELECT id,principal_id,generation FROM dialogue_owners WHERE id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=?),?)",c.history_owner_id,c.history_owner_id):null; - if(retained&&!sameAccount(db,retained.principal_id,c.principal_id))throw new SafetyUnavailable("Safety retained owner mismatch"); + const retained=c.history_owner_id?one<{id:string;principal_id:string;principal_account:string|null;generation:number}|null>(db, + "SELECT id,principal_id,principal_account,generation FROM dialogue_owners WHERE id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=?),?)",c.history_owner_id,c.history_owner_id):null; + if(retained&&!sameAccount(db,{principalId:retained.principal_id,account:retained.principal_account},writer))throw new SafetyUnavailable("Safety retained owner mismatch"); const owner=d?.id??retained?.id??s.history_owner_id,gen=d?actualGeneration(d.generation):retained?actualGeneration(retained.generation):s.generation; if(retained&&actualGeneration(retained.generation)!==c.generation)throw new SafetyUnavailable("Safety history generation changed"); assertLive(db,[["session",sessionId],["dialogue_owner",owner]]); @@ -293,7 +303,8 @@ export function bindSafetyCollection(db:Database,turnId:string,sessionId:string) const previous=one<{session_id:string;history_owner_id:string;generation:string}|null>(db,"SELECT * FROM safety_bindings WHERE turn_id=?",turnId); if(previous&&(previous.session_id!==sessionId||previous.history_owner_id!==owner||previous.generation!==gen))throw new SafetyUnavailable("Safety SessionKey binding changed"); db.query("INSERT INTO safety_bindings VALUES(?,?,?,?,?,?) ON CONFLICT DO NOTHING").run(c.id,turnId,sessionId,owner,gen,advance(db)); - db.query("UPDATE safety_sessions SET history_owner_id=?,generation=?,principal_id=COALESCE(principal_id,?) WHERE session_id=?").run(owner,gen,principal,sessionId); + db.query(`UPDATE safety_sessions SET history_owner_id=?,generation=?,principal_account=CASE WHEN principal_id IS NULL THEN ? ELSE principal_account END, + principal_id=COALESCE(principal_id,?) WHERE session_id=?`).run(owner,gen,principal?bound.account??principalAccount(db,principal):null,principal,sessionId); db.query("UPDATE safety_collections SET session_id=?,history_owner_id=?,generation=?,gap=COALESCE(gap,?) WHERE id=?") .run(sessionId,owner,gen,principal?null:"unknown_history_owner",c.id);advance(db); } diff --git a/packages/ui-server/src/middleware/account-partition.ts b/packages/ui-server/src/middleware/account-partition.ts index c2247255c8..549362367b 100644 --- a/packages/ui-server/src/middleware/account-partition.ts +++ b/packages/ui-server/src/middleware/account-partition.ts @@ -71,26 +71,73 @@ export function accountScope(principal: Principal, authMode: AuthMode): string | // A record keeps who made it, not the auth mode it was made under. const EVERY_AUTH_MODE: Record = { password: true, tailscale: true, proxy: true, none: true }; +/** + * The account a principal is in every auth mode, or null when it has none + * that holds across modes (#3962). Only this can be stored as a record's + * durable account: today that is "owner" for an owner login. An ambient + * principal's account depends on the mode, and an agent or system principal + * has none, so each of those stays only itself. + */ +export function durableAccount(principal: Principal): string | null { + const scopes = new Set((Object.keys(EVERY_AUTH_MODE) as AuthMode[]).map(mode => accountScope(principal, mode))); + const [only] = scopes; + return scopes.size === 1 && only !== undefined ? only : null; +} + +/** Every value `durableAccount` can return. Anything else stored is corrupt. */ +const DURABLE_ACCOUNTS: ReadonlySet = new Set(["owner"]); + +/** + * The durable account to store beside a record's `principal_id` when the + * server writes it (#3962): read from that principal's own row, never taken + * from a request, a client or a model. Null for an unknown principal. + */ +export function principalAccount(db: Database, principalId: string | null | undefined): string | null { + const principal = principalId ? resolvePrincipal(db, principalId) : null; + return principal ? durableAccount(principal) : null; +} + +/** A stored record's principal, with the durable account written beside it. */ +export interface AccountRecord { principalId: string | null | undefined; account: string | null | undefined } +/** A bare id is a principal with no stored evidence: a caller, or a legacy record. */ +export type AccountParty = AccountRecord | string | null | undefined; + +/** What a party proves about its account; null when it is missing or its evidence is corrupt or contradictory. */ +function accountEvidence(db: Database, party: AccountParty): { id: string; account: string | null } | null { + const { principalId: id, account: stored } = typeof party === "object" && party !== null ? party : { principalId: party, account: null }; + if (!id) return null; + if (stored !== null && stored !== undefined && !DURABLE_ACCOUNTS.has(stored)) return null; + const principal = resolvePrincipal(db, id); + if (!principal) return { id, account: stored ?? null }; + const account = durableAccount(principal); + // A live row that disagrees with the stored account: neither is believed. + if (stored !== null && stored !== undefined && stored !== account) return null; + return { id, account }; +} + /** * Whether `principal` is the same account as the principal a record is bound * to (#3952): a chat's safety history, for one, belongs to the account, so * another device's login continues it. A principal id always matches itself. - * Two different ids match only when both resolve to principals that - * `accountScope` puts in the same partition in every auth mode, which today + * Two different ids match only when both are in the same durable account, + * the account `accountScope` puts them in in every auth mode, which today * means two owner logins: the one owner mints a principal at every sign-in. * An ambient principal shares the owner's partition only in some modes, and - * an agent or system principal holds none, so each matches only itself. A - * missing or unresolvable principal is unknown and matches no other id. + * an agent or system principal holds none, so each matches only itself. + * + * A record passed with its stored account keeps that account after its + * principal row is pruned (#3962), so a later owner login continues the + * history the first login wrote. A bare id has no stored evidence: a missing + * or unresolvable principal is then unknown and matches no other id. Stored + * evidence that is corrupt, or that a live principal row contradicts, matches + * nobody. The account is never a credential: a caller is passed as a bare id + * and proves its account only by its own current row. */ -export function sameAccount(db: Database, bound: string | null | undefined, principal: string | null | undefined): boolean { - if (!bound || !principal) return false; - if (bound === principal) return true; - const a = resolvePrincipal(db, bound), b = resolvePrincipal(db, principal); +export function sameAccount(db: Database, bound: AccountParty, principal: AccountParty): boolean { + const a = accountEvidence(db, bound), b = accountEvidence(db, principal); if (!a || !b) return false; - return (Object.keys(EVERY_AUTH_MODE) as AuthMode[]).every(mode => { - const scope = accountScope(a, mode); - return scope !== null && scope === accountScope(b, mode); - }); + if (a.id === b.id) return true; + return a.account !== null && a.account === b.account; } export function deriveAccountPartitionKey(seed: string, root: string, scope: string): string { diff --git a/packages/ui-server/src/ws/dialogue-storage.ts b/packages/ui-server/src/ws/dialogue-storage.ts index e2d7435530..cd3a3e453f 100644 --- a/packages/ui-server/src/ws/dialogue-storage.ts +++ b/packages/ui-server/src/ws/dialogue-storage.ts @@ -10,6 +10,7 @@ import { dialogueRecordSchema, } from "@schlessera/brain-ui-sdk/schemas"; import { assertLive, isRetired } from "./chat-lifecycle.js"; +import { principalAccount } from "../middleware/account-partition.js"; export interface DialogueOwner { id: string; @@ -142,10 +143,12 @@ export function openDialogue(db: Database, input: DialogueOpen, activeEpochs?:Re const safety=input.sessionId?db.query("SELECT history_owner_id FROM safety_sessions WHERE session_id=? AND principal_id=? AND classification='new'").get(input.sessionId,input.principalId) as {history_owner_id:string}|null:null; const id = safety?.history_owner_id ?? input.conversationId; db.prepare( - "INSERT INTO dialogue_owners(id,principal_id,session_id,coverage,created_at) VALUES(?,?,?,?,?)" + "INSERT INTO dialogue_owners(id,principal_id,principal_account,session_id,coverage,created_at) VALUES(?,?,?,?,?,?)" ).run( id, input.principalId, + // The durable account of the owner, from its own row (#3962). + principalAccount(db, input.principalId), input.sessionId ?? null, input.sessionId && hasUnretainedVoice(db, input.principalId, input.sessionId) ? "legacy" : "complete", Date.now() diff --git a/packages/ui-server/tests/safety-account-partition.test.ts b/packages/ui-server/tests/safety-account-partition.test.ts index fad38c4690..af6577047d 100644 --- a/packages/ui-server/tests/safety-account-partition.test.ts +++ b/packages/ui-server/tests/safety-account-partition.test.ts @@ -1,17 +1,18 @@ -/** A chat's safety history binds to the account, not the exact login (#3952). */ +/** A chat's safety history binds to the account, not the exact login (#3952), and outlives the login that wrote it (#3962). */ import { expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createUiDb } from "../src/db/client"; -import { createPrincipal, resolveAmbientPrincipal, resolveSystemPrincipal } from "../src/db/principals"; +import { createPrincipal, isUsablePrincipal, PRINCIPAL_RETENTION_MS, prunePrincipals, resolveAmbientPrincipal, resolvePrincipal, resolveSystemPrincipal, + revokePrincipal, type Principal } from "../src/db/principals"; import { openSqliteWriter } from "../src/db/write-worker"; import { createGovernanceWrites } from "../src/governance/event-writes"; import { createSafetyCollector } from "../src/governance/safety-collector"; import { SafetyHistory } from "../src/governance/safety-history"; import { safetyCatalogCreated, safetyRecords } from "../src/governance/safety-store"; import { safetyReviewTarget, type SafetyReviewBody, type SafetyReviewer } from "../src/governance/safety-reviews"; -import { sameAccount } from "../src/middleware/account-partition"; +import { durableAccount, sameAccount } from "../src/middleware/account-partition"; import { openDialogue } from "../src/ws/dialogue-storage"; import { rejection } from "./helpers/expect-rejection"; @@ -20,8 +21,9 @@ async function fixture() { const db = createUiDb(path), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); // Every sign-in mints its own owner principal: one on the ship, one at home. const ship = createPrincipal(db, { authMethod: "password", label: "Odysseus on the ship", ttlSeconds: 3600 }); - const home = createPrincipal(db, { authMethod: "password", label: "Odysseus at Ithaca", ttlSeconds: 3600 }); - const agent = createPrincipal(db, { authMethod: "delegated", label: "Mentor", createdBy: ship.id, ttlSeconds: 3600 }); + // The later logins outlive the ship's, so pruning the ship's leaves them. + const home = createPrincipal(db, { authMethod: "password", label: "Odysseus at Ithaca", ttlSeconds: 7200 }); + const agent = createPrincipal(db, { authMethod: "delegated", label: "Mentor", createdBy: ship.id, ttlSeconds: 7200 }); const penelope = resolveAmbientPrincipal(db, "proxy", "penelope", "Penelope"); const telemachus = resolveAmbientPrincipal(db, "proxy", "telemachus", "Telemachus"); const system = resolveSystemPrincipal(db, { identity: "harbour-watch", label: "Harbour watch" }); @@ -53,7 +55,22 @@ async function fixture() { .all() as { turn_id: string; principal_id: string | null; session_id: string; history_owner_id: string }[]; const session = () => db.query("SELECT principal_id,history_owner_id,generation FROM safety_sessions WHERE session_id='ithaca'").get() as { principal_id: string | null; history_owner_id: string; generation: string }; - return { root, db, writer, writes, ship, home, agent, penelope, telemachus, system, triggers, taint, start, resume, collections, session, + /** The real cleanup path: the ship's login is revoked, or expires, and is pruned once retention has passed. */ + const prune = (how: "revoked" | "expired") => { + if (how === "revoked") { revokePrincipal(db, ship.id, Date.now()); prunePrincipals(db, Date.now() + PRINCIPAL_RETENTION_MS + 1); } + else prunePrincipals(db, ship.expiresAt + PRINCIPAL_RETENTION_MS + 1); + expect(resolvePrincipal(db, ship.id), `SAFETY_SHIP_LOGIN_PRUNED: ${how}`).toBeNull(); + expect(resolvePrincipal(db, home.id), "SAFETY_HOME_LOGIN_SURVIVES_PRUNING").not.toBeNull(); + }; + /** Only a current, usable login is authorized, as the host checks it. */ + const authorized = (principal: Principal) => { const row = resolvePrincipal(db, principal.id); return row !== null && isUsablePrincipal(row, Date.now()); }; + /** Each record that names the chat's owner, with the account stored beside it. */ + const accounts = () => ({ + session: db.query("SELECT principal_id,principal_account FROM safety_sessions WHERE session_id='ithaca'").get(), + collections: db.query("SELECT turn_id,principal_id,principal_account FROM safety_collections ORDER BY turn_id").all(), + owners: db.query("SELECT id,principal_id,principal_account FROM dialogue_owners ORDER BY id").all(), + }); + return { root, path, db, writer, writes, ship, home, agent, penelope, telemachus, system, triggers, taint, start, resume, collections, session, prune, authorized, accounts, async close() { await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } }; } type Fixture = Awaited>; @@ -121,7 +138,7 @@ test("an owner login never takes over a chat bound to an agent or to another pro } }); -test("a chat's rows keep the principal that wrote them, and an owner login whose row is gone is unknown", async () => { +test("a chat's rows keep the principal that wrote them, and a legacy owner login whose row is gone is unknown", async () => { const f = await fixture(); try { await f.start(); const before = { session: f.session(), records: safetyRecords(f.db, "ithaca") }; @@ -132,9 +149,16 @@ test("a chat's rows keep the principal that wrote them, and an owner login whose // The login that started the chat still continues it. await f.resume("return-to-the-ship", f.ship.id); expect(f.collections().map(c => [c.turn_id, c.principal_id])).toEqual([["homecoming", f.home.id], ["return-to-the-ship", f.ship.id], ["voyage", f.ship.id]]); - // A pruned principal row leaves only an id nobody can vouch for. - f.db.query("DELETE FROM principals WHERE id=?").run(f.ship.id); - expect(await refusedBy(f.resume("after-pruning", f.home.id)), "SAFETY_PRUNED_OWNER_IS_UNKNOWN").toBe("Safety principal mismatch"); + // History written before #3962 stored no account. Its login still + // resolves, so another owner login continues it as before. + f.db.exec("UPDATE safety_sessions SET principal_account=NULL; UPDATE safety_collections SET principal_account=NULL"); + await f.resume("legacy-homecoming", f.home.id); + // Once that login is pruned, only an id nobody can vouch for is left. + f.prune("revoked"); + expect(await refusedBy(f.resume("after-pruning", f.home.id)), "SAFETY_PRUNED_LEGACY_OWNER_IS_UNKNOWN").toBe("Safety principal mismatch"); + const history = new SafetyHistory(f.db, f.authorized, async () => {}); + expect(await rejection(history.read(f.home, { sessionId: "ithaca" })), "SAFETY_PRUNED_LEGACY_OWNER_READ_REFUSED").toHaveProperty("reason", "unavailable"); + history.close(); } finally { await f.close(); } }); @@ -199,17 +223,18 @@ test("the decision trigger refuses another account's verdict on each record that const { first } = await f.start(); if (record === "dialogue owner") openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" }); const { history_owner_id: owner } = f.session(); - // Only the named record still names the ship's login; the others name the agent. - if (record !== "session") f.db.query("UPDATE safety_sessions SET principal_id=? WHERE session_id='ithaca'").run(f.agent.id); - if (record !== "collection") f.db.query("UPDATE safety_collections SET principal_id=? WHERE turn_id='voyage'").run(f.agent.id); + // Only the named record still names the ship's login; the others name + // the agent, with the agent's account (it has none beyond itself). + if (record !== "session") f.db.query("UPDATE safety_sessions SET principal_id=?,principal_account=NULL WHERE session_id='ithaca'").run(f.agent.id); + if (record !== "collection") f.db.query("UPDATE safety_collections SET principal_id=?,principal_account=NULL WHERE turn_id='voyage'").run(f.agent.id); let sequence = 999000; const decide = () => f.db.query("INSERT INTO safety_decisions VALUES(?,?,?,?,?,?,?,?,?,?,?)").run(crypto.randomUUID(), first, "ithaca", owner, "1", String(sequence++), f.agent.id, crypto.randomUUID(), 1, "safe", "owner_history"); expect(decide, `SAFETY_DECISION_TRIGGER_CHECKS_THE_${record.toUpperCase()}`).toThrow("safety decision identity or exposure mismatch"); // Control: with that record the agent's too, the same verdict is admitted. - if (record === "session") f.db.query("UPDATE safety_sessions SET principal_id=? WHERE session_id='ithaca'").run(f.agent.id); - if (record === "collection") f.db.query("UPDATE safety_collections SET principal_id=? WHERE turn_id='voyage'").run(f.agent.id); - if (record === "dialogue owner") f.db.query("UPDATE dialogue_owners SET principal_id=? WHERE id=?").run(f.agent.id, owner); + if (record === "session") f.db.query("UPDATE safety_sessions SET principal_id=?,principal_account=NULL WHERE session_id='ithaca'").run(f.agent.id); + if (record === "collection") f.db.query("UPDATE safety_collections SET principal_id=?,principal_account=NULL WHERE turn_id='voyage'").run(f.agent.id); + if (record === "dialogue owner") f.db.query("UPDATE dialogue_owners SET principal_id=?,principal_account=NULL WHERE id=?").run(f.agent.id, owner); decide(); } finally { await f.close(); } } @@ -226,3 +251,193 @@ test("only the same principal or two owner logins are one account", async () => for (const [bound, principal, same] of pairs) expect(sameAccount(f.db, bound, principal), `${bound} / ${principal}`).toBe(same); } finally { await f.close(); } }); + +/** The review the home login gives on the ship's occurrence. */ +function reviewBody(f: Fixture, occurrenceId: string): SafetyReviewBody { + const state = f.writes.safety(null, "ithaca"); + return { version: 1, session: state.session!, occurrenceId, expectedEvidenceRevision: state.evidenceRevision, verdict: "safe" }; +} + +for (const [how, voice] of [["revoked", false], ["expired", true]] as const) { + test(`after the starting login is ${how} and pruned, another owner login continues, binds, reads, forks and reviews the chat${voice ? " and its voice owner" : ""}`, async () => { + const f = await fixture(); try { + const { first, bindingId } = await f.start(); + if (voice) openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" }); + const before = { session: f.session(), records: safetyRecords(f.db, "ithaca"), voyage: f.collections().find(c => c.turn_id === "voyage") }; + f.prune(how); + // Admission and binding: the turn joins the same history and its taint. + await f.resume("homecoming", f.home.id); + expect(f.collections().find(c => c.turn_id === "homecoming"), "SAFETY_PRUNED_OWNER_CHAT_CONTINUES") + .toEqual({ turn_id: "homecoming", principal_id: f.home.id, session_id: "ithaca", history_owner_id: before.session.history_owner_id }); + const turn = f.writes.safety("homecoming", "ithaca"); + expect([turn.unresolvedCount, turn.earliestUnresolvedId, turn.restriction], "SAFETY_PRUNED_OWNER_TAINT_INHERITED").toEqual([1, first, "restricted"]); + if (!voice) { + // A turn begun before it knew its chat binds to it afterwards. + const landfall = crypto.randomUUID(); + await f.writes.safetyBegin({ turnId: "landfall", bindingId: landfall, sessionId: null, principalId: f.home.id, backendId: "claude", at: 3 }); + await f.writes.bind("landfall", "ithaca"); + expect(f.collections().find(c => c.turn_id === "landfall")?.session_id, "SAFETY_PRUNED_OWNER_LATE_BINDING").toBe("ithaca"); + } + // Reads, of the chat and of the turn the pruned login wrote. + const history = new SafetyHistory(f.db, f.authorized, async () => {}); + const page = await history.read(f.home, { sessionId: "ithaca" }); + expect(page.identity, "SAFETY_PRUNED_OWNER_CHAT_READ").toEqual({ sessionId: "ithaca", historyOwnerId: before.session.history_owner_id, historyGeneration: "1" }); + expect(page.records.filter(r => r.kind === "occurrence").map(r => r.id)[0]).toBe(first); + expect((await history.read(f.home, { turnId: "voyage", bindingId })).identity, "SAFETY_PRUNED_OWNER_TURN_READ").toEqual(page.identity); + // The stored account is no credential: the pruned login itself is refused. + expect(await rejection(history.read(f.ship, { sessionId: "ithaca" })), "SAFETY_PRUNED_LOGIN_NOT_AUTHORIZED").toHaveProperty("reason", "unauthorized"); + history.close(); + // Inherited history: a fork carries the taint. + await f.writes.safetyBegin({ turnId: "telemachy", bindingId: crypto.randomUUID(), sessionId: null, principalId: f.home.id, backendId: "claude", sourceSessionId: "ithaca", at: 4 }); + expect(f.writes.safety("telemachy", null).unresolvedCount, "SAFETY_PRUNED_OWNER_FORK_INHERITS_TAINT").toBe(1); + // Nothing the ship wrote was rewritten. + expect(f.session(), "SAFETY_PRUNED_OWNER_ATTRIBUTION_KEPT").toEqual(before.session); + expect(f.collections().find(c => c.turn_id === "voyage"), "SAFETY_PRUNED_OWNER_COLLECTION_KEPT").toEqual(before.voyage); + expect(safetyRecords(f.db, "ithaca").slice(0, before.records.length), "SAFETY_PRUNED_OWNER_RECORDS_KEPT").toEqual(before.records); + // A review decision on the pruned login's occurrence, through the trigger. + const actor: SafetyReviewer = { principalId: f.home.id, channel: "owner_history" }; + expect(safetyReviewTarget(f.db, reviewBody(f, first), f.home.id), "SAFETY_PRUNED_OWNER_REVIEW_TARGET").toBeNull(); + const prepared = await f.writes.safetyPrepareReview(reviewBody(f, first), actor); + expect(prepared.stage, "SAFETY_PRUNED_OWNER_REVIEW_PREPARED").toBe("prepared"); + expect((await f.writes.safetyCommitReview(prepared.requestId!, reviewBody(f, first), actor)).stage, "SAFETY_PRUNED_OWNER_REVIEW_COMMITTED").toBe("verdict_committed"); + expect(f.db.query("SELECT occurrence_id,principal_id FROM safety_decisions").all()).toEqual([{ occurrence_id: first, principal_id: f.home.id }]); + expect(f.writes.safety(null, "ithaca").unresolvedCount).toBe(0); + } finally { await f.close(); } + }); +} + +test("after the starting login is pruned, another account's principal is still refused, and only that chat refuses it", async () => { + const f = await fixture(); try { + const { first, bindingId } = await f.start(); + f.prune("revoked"); + for (const [name, principalId] of foreign(f)) + expect(await refusedBy(f.resume(`intruder-${name}`, principalId)), `SAFETY_PRUNED_FOREIGN_REFUSED: ${name}`).toBe("Safety principal mismatch"); + const history = new SafetyHistory(f.db, () => true, async () => {}); + for (const principal of [f.agent, f.penelope, f.system]) { + expect(await rejection(history.read(principal, { sessionId: "ithaca" })), `SAFETY_PRUNED_FOREIGN_READ_REFUSED: ${principal.label}`).toHaveProperty("reason", "unavailable"); + expect(await rejection(history.read(principal, { turnId: "voyage", bindingId })), `SAFETY_PRUNED_FOREIGN_TURN_READ_REFUSED: ${principal.label}`).toHaveProperty("reason", "unavailable"); + expect(safetyReviewTarget(f.db, reviewBody(f, first), principal.id), `SAFETY_PRUNED_FOREIGN_REVIEW_REFUSED: ${principal.label}`).toBe("unavailable"); + } + history.close(); + openDialogue(f.db, { conversationId: "argos-voice", principalId: f.home.id, epoch: 1, providerId: "voice", sessionId: "ithaca" }); + for (const [name, principalId] of foreign(f)) + expect(await refusedBy(f.resume(`listener-${name}`, principalId)), `SAFETY_PRUNED_FOREIGN_DIALOGUE_REFUSED: ${name}`).toBe("Safety history ownership mismatch"); + // A refused turn never extended the chat, and another chat starts as usual. + expect(f.collections().map(c => c.turn_id)).toEqual(["voyage"]); + await f.writes.safetyBegin({ turnId: "phaeacia", bindingId: crypto.randomUUID(), sessionId: null, principalId: f.agent.id, backendId: "claude", at: 5 }); + await f.writes.safetyReady("phaeacia", "claude", 1); + expect(f.writes.safety("phaeacia", null).restriction, "SAFETY_REFUSAL_CONTAINED_TO_ITS_CHAT").toBe("normal"); + } finally { await f.close(); } +}); + +test("corrupt or contradictory account evidence matches nobody, and only its chat refuses", async () => { + for (const [name, principal, account] of [["corrupt", "ship", "admiral"], ["contradicted by a live row", "agent", "owner"]] as const) { + const f = await fixture(); try { + const { first } = await f.start(); + f.db.query("UPDATE safety_sessions SET principal_id=?,principal_account=? WHERE session_id='ithaca'").run(f[principal].id, account); + // Neither another owner login nor the recorded principal itself continues it. + for (const caller of [f.home, f[principal]]) + expect(await refusedBy(f.resume(`doubt-${caller === f.home ? "home" : principal}`, caller.id)), `SAFETY_BAD_ACCOUNT_REFUSED: ${name} / ${caller.label}`).toBe("Safety principal mismatch"); + const history = new SafetyHistory(f.db, () => true, async () => {}); + expect(await rejection(history.read(f.home, { sessionId: "ithaca" })), `SAFETY_BAD_ACCOUNT_READ_REFUSED: ${name}`).toHaveProperty("reason", "unavailable"); + history.close(); + expect(safetyReviewTarget(f.db, reviewBody(f, first), f.home.id), `SAFETY_BAD_ACCOUNT_REVIEW_REFUSED: ${name}`).toBe("unavailable"); + const { history_owner_id: owner } = f.session(); + expect(() => f.db.query("INSERT INTO safety_decisions VALUES(?,?,?,?,?,?,?,?,?,?,?)").run(crypto.randomUUID(), first, "ithaca", owner, "1", "999000", + f.home.id, crypto.randomUUID(), 1, "safe", "owner_history"), `SAFETY_BAD_ACCOUNT_TRIGGER_REFUSED: ${name}`).toThrow("safety decision identity or exposure mismatch"); + await f.writes.safetyBegin({ turnId: "phaeacia", bindingId: crypto.randomUUID(), sessionId: null, principalId: f.home.id, backendId: "claude", at: 5 }); + await f.writes.safetyReady("phaeacia", "claude", 1); + expect(f.writes.safety("phaeacia", null).restriction, `SAFETY_BAD_ACCOUNT_CONTAINED: ${name}`).toBe("normal"); + } finally { await f.close(); } + } +}); + +test("the server writes each record's account from its principal's row, never from the turn's input", async () => { + const f = await fixture(); try { + await f.start(); + openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" }); + await f.resume("homecoming", f.home.id); + // An input that claims an account is ignored: only the principal's row counts. + for (const [turnId, principalId] of [["mentor", f.agent.id], ["penelope", f.penelope.id], ["watch", f.system.id], ["stranger", "pruned-login"]] as const) + await f.writes.safetyBegin({ turnId, bindingId: crypto.randomUUID(), sessionId: null, principalId, backendId: "claude", at: 6, + ...{ principalAccount: "owner", principal_account: "owner", account: "owner" } } as never); + const { session, collections, owners } = f.accounts(); + expect(session, "SAFETY_SESSION_ACCOUNT_CAPTURED").toEqual({ principal_id: f.ship.id, principal_account: "owner" }); + expect(collections, "SAFETY_COLLECTION_ACCOUNT_CAPTURED").toEqual([ + { turn_id: "homecoming", principal_id: f.home.id, principal_account: "owner" }, + { turn_id: "mentor", principal_id: f.agent.id, principal_account: null }, + { turn_id: "penelope", principal_id: f.penelope.id, principal_account: null }, + { turn_id: "stranger", principal_id: "pruned-login", principal_account: null }, + { turn_id: "voyage", principal_id: f.ship.id, principal_account: "owner" }, + { turn_id: "watch", principal_id: f.system.id, principal_account: null }, + ]); + expect(owners, "SAFETY_DIALOGUE_OWNER_ACCOUNT_CAPTURED").toEqual([{ id: f.session().history_owner_id, principal_id: f.ship.id, principal_account: "owner" }]); + } finally { await f.close(); } +}); + +test("upgrading gives legacy history an account only where a principal row still proves it", async () => { + const f = await fixture(); + let db = f.db; + try { + await f.start(); + openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" }); + await f.resume("homecoming", f.home.id); + f.db.query("INSERT INTO dialogue_owners(id,principal_id,coverage,created_at) VALUES('mentor-voice',?,'complete',0)").run(f.agent.id); + const owner = f.session().history_owner_id, records = safetyRecords(f.db, "ithaca"); + // The tables as they stood before 089, with the ship's login pruned before the upgrade. + f.db.exec(`DROP TRIGGER safety_decision_identity; + ALTER TABLE safety_sessions DROP COLUMN principal_account; ALTER TABLE safety_collections DROP COLUMN principal_account; + ALTER TABLE dialogue_owners DROP COLUMN principal_account; DELETE FROM _migrations WHERE filename='089_safety_durable_account.sql'`); + f.prune("revoked"); + await f.writer.close(); f.db.close(); db = createUiDb(f.path); + expect(db.query("SELECT principal_id,principal_account FROM safety_sessions WHERE session_id='ithaca'").get(), "SAFETY_UPGRADE_LOST_PROOF_STAYS_UNKNOWN") + .toEqual({ principal_id: f.ship.id, principal_account: null }); + expect(db.query("SELECT turn_id,principal_id,principal_account FROM safety_collections ORDER BY turn_id").all(), "SAFETY_UPGRADE_COLLECTION_ACCOUNTS").toEqual([ + { turn_id: "homecoming", principal_id: f.home.id, principal_account: "owner" }, + { turn_id: "voyage", principal_id: f.ship.id, principal_account: null }, + ]); + expect(db.query("SELECT id,principal_id,principal_account FROM dialogue_owners ORDER BY id='mentor-voice'").all(), "SAFETY_UPGRADE_OWNER_ACCOUNTS").toEqual([ + { id: owner, principal_id: f.ship.id, principal_account: null }, + { id: "mentor-voice", principal_id: f.agent.id, principal_account: null }, + ]); + expect(safetyRecords(db, "ithaca"), "SAFETY_UPGRADE_REWRITES_NO_HISTORY").toEqual(records); + } finally { db.close(); rmSync(f.root, { recursive: true, force: true }); } +}); + +test("a stored account keeps an owner record matching other owner logins once its row is pruned, and nothing else", async () => { + const f = await fixture(); try { + expect([f.ship, f.agent, f.penelope, f.system].map(durableAccount), "SAFETY_DURABLE_ACCOUNTS").toEqual(["owner", null, null, null]); + const ship = (account: string | null) => ({ principalId: f.ship.id, account }), agent = (account: string | null) => ({ principalId: f.agent.id, account }); + const live: [Parameters[1], string | null, boolean][] = [ + [ship("owner"), f.home.id, true], [ship(null), f.home.id, true], [ship("admiral"), f.home.id, false], [ship("admiral"), f.ship.id, false], + [agent(null), f.agent.id, true], [agent("owner"), f.agent.id, false], [agent("owner"), f.ship.id, false], [agent(null), f.ship.id, false], + ]; + for (const [bound, principal, same] of live) expect(sameAccount(f.db, bound, principal), `live ${JSON.stringify(bound)} / ${principal}`).toBe(same); + f.prune("revoked"); + const pruned: [Parameters[1], string | null, boolean][] = [ + [ship("owner"), f.home.id, true], [ship(null), f.home.id, false], [f.ship.id, f.home.id, false], [ship("admiral"), f.home.id, false], + [ship("owner"), f.agent.id, false], [ship("owner"), f.system.id, false], [ship("owner"), "pruned-login", false], [ship("owner"), null, false], + [{ principalId: null, account: "owner" }, f.home.id, false], + ]; + for (const [bound, principal, same] of pruned) expect(sameAccount(f.db, bound, principal), `pruned ${JSON.stringify(bound)} / ${principal}`).toBe(same); + } finally { await f.close(); } +}); + +test("the decision trigger refuses a verdict when the chat's dialogue owner is another account or unknown, with no stored account", async () => { + for (const [name, owner] of [["foreign agent", "agent"], ["pruned unknown", "pruned-login"]] as const) { + const f = await fixture(); try { + const { first } = await f.start(); + openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" }); + const { history_owner_id: ownerId } = f.session(); + // The session and the collection are the owner's; only the dialogue owner is not. + f.db.query("UPDATE dialogue_owners SET principal_id=?,principal_account=NULL WHERE id=?").run(owner === "agent" ? f.agent.id : owner, ownerId); + let sequence = 998000; + const decide = () => f.db.query("INSERT INTO safety_decisions VALUES(?,?,?,?,?,?,?,?,?,?,?)").run(crypto.randomUUID(), first, "ithaca", + ownerId, "1", String(sequence++), f.home.id, crypto.randomUUID(), 1, "safe", "owner_history"); + expect(decide, `SAFETY_DECISION_TRIGGER_REFUSES_NULL_ACCOUNT_DIALOGUE_OWNER: ${name}`).toThrow("safety decision identity or exposure mismatch"); + // Control: the same verdict on the owner's dialogue owner is admitted. + f.db.query("UPDATE dialogue_owners SET principal_id=?,principal_account='owner' WHERE id=?").run(f.ship.id, ownerId); + decide(); + } finally { await f.close(); } + } +}); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 801c973fc8..8ffb2e26b3 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -66,9 +66,11 @@ test("real upgrade classifies old sessions both with and without first-taint row for(const {name} of triggers)f.db.exec(`DROP TRIGGER ${name}`); const tables=f.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'safety_%'").all() as {name:string}[]; for(const {name} of tables)f.db.exec(`DROP TABLE ${name}`); - // 085 extends the safety tables 081 recreates, so it replays with them. - f.db.query("DELETE FROM _migrations WHERE filename IN ('081_session_safety.sql','085_safety_recording_containment.sql')").run(); - f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('legacy-clean',0,0),('legacy-tainted',0,0); INSERT INTO dialogue_owners VALUES('legacy-provisional','odysseus',NULL,1,'complete',0)"); + // 085 and 089 extend the safety tables 081 recreates, so they replay with + // them; 089's column on dialogue_owners goes too. + f.db.exec("ALTER TABLE dialogue_owners DROP COLUMN principal_account"); + f.db.query("DELETE FROM _migrations WHERE filename IN ('081_session_safety.sql','085_safety_recording_containment.sql','089_safety_durable_account.sql')").run(); + f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('legacy-clean',0,0),('legacy-tainted',0,0); INSERT INTO dialogue_owners(id,principal_id,session_id,generation,coverage,created_at) VALUES('legacy-provisional','odysseus',NULL,1,'complete',0)"); f.db.query("INSERT INTO governance_events(session_id,turn_id,at,kind,schema_version,actor,payload) VALUES('legacy-tainted','old-turn',0,'taint',1,'interactive',?)") .run(JSON.stringify({source:"web_fetch",tool:"WebFetch",detail:null})); f.db.close();const restored=createUiDb(f.path),replayWriter=openSqliteWriter(restored),replayWrites=createGovernanceWrites(restored,replayWriter); @@ -141,7 +143,7 @@ test("provisional retirement refuses null-session late callbacks even after priv const {createPrincipal}=await import("../src/db/principals"),{retireChat}=await import("../src/ws/chat-lifecycle"); const {cleanChatStore}=await import("../src/ws/chat-store-cleanup"); const principal=createPrincipal(f.db,{authMethod:"password",label:"Odysseus",ttlSeconds:60}); - f.db.query("INSERT INTO dialogue_owners VALUES('provisional',?,NULL,1,'complete',0)").run(principal.id); + f.db.query("INSERT INTO dialogue_owners(id,principal_id,session_id,generation,coverage,created_at) VALUES('provisional',?,NULL,1,'complete',0)").run(principal.id); await f.writes.safetyBegin({turnId:"provisional-turn",bindingId:crypto.randomUUID(),historyOwnerId:"provisional",principalId:principal.id,sessionId:null,backendId:"claude",at:0}); await f.writes.firstTaint({kind:"taint",turnId:"provisional-turn",sessionId:null,actor:"interactive",model:null,profile:null,payload:{source:"web_fetch",tool:"WebFetch",detail:null}}); const retired=retireChat(f.db,{operationId:"retire-provisional",principalId:principal.id,target:{ownerId:"provisional"},expected:{backendId:null,generation:1},removableBackends:[],at:Date.now()}); @@ -344,7 +346,7 @@ test("an unsupported recorder stops and persists a gap when input detection exce test("an imported provisional alias binds its actual owner and generation without inventing complete past coverage",async()=>{ const f=fixture();try{ - f.db.exec("INSERT INTO dialogue_owners VALUES('canonical-owner','odysseus',NULL,9,'complete',0); INSERT INTO dialogue_aliases VALUES('native-alias','canonical-owner')"); + f.db.exec("INSERT INTO dialogue_owners(id,principal_id,session_id,generation,coverage,created_at) VALUES('canonical-owner','odysseus',NULL,9,'complete',0); INSERT INTO dialogue_aliases VALUES('native-alias','canonical-owner')"); const bindingId=crypto.randomUUID();await f.writes.safetyBegin({turnId:"adopt-import",bindingId,historyOwnerId:"native-alias",principalId:"odysseus",sessionId:null,backendId:"claude",at:1}); f.db.exec("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('adopted',0,0,'claude'); INSERT INTO chat_session_owners VALUES('adopted','odysseus',0); UPDATE dialogue_owners SET session_id='adopted' WHERE id='canonical-owner'"); safetyCatalogCreated(f.db,"adopted","odysseus","adopt-import");await f.writes.bind("adopt-import","adopted");await f.writes.safetyReady("adopt-import","claude",1); @@ -451,7 +453,7 @@ for(const mode of ["provisional-nine","typed-resume"] as const)test(`real emissi try{ let expectedOwner:string=bindingId; if(mode==="provisional-nine"){ - f.db.exec("INSERT INTO dialogue_owners VALUES('canonical-nine','odysseus',NULL,9,'complete',0)"); + f.db.exec("INSERT INTO dialogue_owners(id,principal_id,session_id,generation,coverage,created_at) VALUES('canonical-nine','odysseus',NULL,9,'complete',0)"); await host.dialogue.open({conversationId:"voice-source",principalId:"odysseus",epoch:1,providerId:"odyssey",historyOwnerId:"canonical-nine"}); host.dialogue.adoptTurn(turnId,"canonical-nine","odysseus");expectedOwner="canonical-nine"; }