From ecbec0b00f6dba0eba73a112a93fa07885722c9c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:26:15 +0000 Subject: [PATCH 1/8] feat(ui-server): bind immutable reads to approved owner evidence --- .../3613-approved-owner-read-resolution.md | 5 + .../decisions/reference-source-acquisition.md | 29 ++ packages/ui-server/src/app.ts | 2 +- .../src/brain/reference-owner-resolution.ts | 93 +++++++ .../src/brain/reference-read-writes.ts | 9 +- .../ui-server/src/brain/reference-read.ts | 11 +- .../tests/reference-owner-resolution.test.ts | 261 ++++++++++++++++++ .../ui-server/tests/reference-read.test.ts | 9 + .../native-proof/managed-reference-source.ts | 33 ++- 9 files changed, 444 insertions(+), 8 deletions(-) create mode 100644 .changeset/3613-approved-owner-read-resolution.md create mode 100644 packages/ui-server/src/brain/reference-owner-resolution.ts create mode 100644 packages/ui-server/tests/reference-owner-resolution.test.ts diff --git a/.changeset/3613-approved-owner-read-resolution.md b/.changeset/3613-approved-owner-read-resolution.md new file mode 100644 index 0000000000..6bd35c300c --- /dev/null +++ b/.changeset/3613-approved-owner-read-resolution.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Bind immutable read identity evidence to independently published Settings owner approval. Record unavailable qualification for missing or mismatched approval, repository transfer/name reuse and replaced policy roots, and recheck inside the write transaction after waits. Source trust remains disabled. diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 871fc437a9..6528476434 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -436,3 +436,32 @@ names together before recording. A changed or missing observation refuses that read; a fresh call can acquire again. Old receipts remain historical evidence, including across restart, and cannot establish current identity or source trust. Approved-owner rule evaluation remains independently required. + +## Approved-owner resolution for immutable reads + +The host read service resolves each actual transport observation against the +protected Markdown policy, its matching durable trust projection and Settings' +operation-bound approved-owner evidence. The policy root's directory identity is +captured at service construction. Links, replaced roots, invalid or incoherent +policy/projection data and missing/malformed publication proof produce unavailable +qualification; they do not prevent an otherwise authorized untrusted read. + +Exact repository approval requires the freshly observed stable repository ID, +current canonical owner and the independently approved owner ID. A same-owner +repository rename can qualify only from that new transport observation. Transfer, +repository name reuse and owner namespace reassignment cannot borrow approval. +Owner rules deliberately include future repositories currently in that same +canonical namespace and stable owner ID. A validated policy permits at most one +matching repository and one matching owner rule. Other policy edits do not erase +a retained approval of the same selector, and bounded operation-receipt pruning +or approving-login deletion does not erase the durable owner evidence. + +Resolution runs provisionally before recording and again inside the acquired +SQLite writer transaction. The recorded operation ID, policy hash/revision, +approved owner, selector and publication operation/proof hash are historical +qualification evidence. They are separate from the original acquisition and the +prepared/observed/unknown delivery state. Removal affects later resolutions and +retains earlier read evidence. This is neither a trust-at-admission decision nor +a private-access, recipient, Git-write or mutable-content grant. Every read still +produces workspace input; standing-rule enforcement and review targets remain +separately qualified work. diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index d31219f3a7..73dbc1da15 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -562,7 +562,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise referenceWorktrees.close()); diff --git a/packages/ui-server/src/brain/reference-owner-resolution.ts b/packages/ui-server/src/brain/reference-owner-resolution.ts new file mode 100644 index 0000000000..595764750a --- /dev/null +++ b/packages/ui-server/src/brain/reference-owner-resolution.ts @@ -0,0 +1,93 @@ +/** Read-only owner qualification. This records historical evidence, never a source-trust admission. */ +import { createHash } from "node:crypto"; +import { lstatSync, realpathSync } from "node:fs"; +import type { Database } from "bun:sqlite"; +import { z } from "zod"; +import { openGovernancePolicyAnchored, verifyGovernancePolicyAnchored, parseGovernancePolicy, + TrustedSourcesSchema, TrustSelectorSchema, type TrustSelector, type AnchoredGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import type { ReferenceIdentityObservation } from "./reference-acquisition.js"; + +const hash = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex"); +const digest = z.string().regex(/^[a-f0-9]{64}$/u); +const id = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/u); +const providerId = z.string().regex(/^[1-9][0-9]{0,19}$/u); +const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u).refine(value => BigInt(value) <= 18446744073709551615n); +const identitySchema = z.strictObject({ selector: TrustSelectorSchema, ownerId: providerId, private: z.boolean().nullable() }); +const proofSchema = z.strictObject({ operationId: id, principal: z.string().min(1).max(128), brain: digest, + authority: z.string().min(1).max(4096), baseHash: digest.nullable(), expectedTrustRevision: revision, + publishedTrustRevision: revision, reviewedBytesHash: digest, githubIdentity: identitySchema }); + +export interface ReferenceOwnerRoot { path: string; device: number; inode: number } +/** Bind the host's configured directory once; later aliases/replacements cannot select another brain. */ +export function captureReferenceOwnerRoot(path: string | undefined): Readonly | undefined { + if (!path) return; + try { const canonical = realpathSync(path), stat = lstatSync(canonical); + return stat.isDirectory() ? Object.freeze({ path: canonical, device: stat.dev, inode: stat.ino }) : undefined; + } catch { return; } +} + +type GitHubSelector = Extract; +export interface ReferenceOwnerResolution { + version: 1; + operationId: string; + state: "available" | "unavailable"; + policyHash: string | null; + trustRevision: string | null; + /** At most one repository and one owner rule can match a validated policy. */ + bindings: { ruleId: string; selector: GitHubSelector; approvedOwnerId: string; sameOwnerRenameRevalidated: boolean; + publicationOperationId: string; publicationProofHash: string }[]; +} + +/** + * Called only after the read's real transport observation and immutable blob + * have been checked. `root` is host configuration, never model input. A valid + * policy and its exact durable projection must agree; equal bytes cannot create + * approval. The publisher's retained boundary survives operation pruning. + */ +export function resolveReferenceOwners(db: Database, root: Readonly | undefined, observation: Readonly): ReferenceOwnerResolution { + const unavailable = (): ReferenceOwnerResolution => ({ version: 1, operationId: observation.operationId, + state: "unavailable", policyHash: null, trustRevision: null, bindings: [] }); + if (!root) return unavailable(); + let target: AnchoredGovernancePolicy | undefined; + try { + const brain = hash(root.path); + target = openGovernancePolicyAnchored(root.path); + if (target.directories[0]!.dev !== root.device || target.directories[0]!.ino !== root.inode) return unavailable(); + if (target.bytes === null) return unavailable(); + const policyHash = hash(target.bytes), parsed = parseGovernancePolicy(target.bytes); + if (!parsed.ok) return unavailable(); + const rules = TrustedSourcesSchema.parse(parsed.effective.taint.trusted_sources); + const projection = db.query("SELECT revision,rules,policy_hash,error FROM trust_settings_projection WHERE brain_id=?").get(brain) as { + revision: string; rules: string; policy_hash: string | null; error: string | null; + } | null; + if (!projection || projection.error !== null || projection.policy_hash !== policyHash || !revision.safeParse(projection.revision).success + || JSON.stringify(TrustedSourcesSchema.parse(JSON.parse(projection.rules))) !== JSON.stringify(rules)) return unavailable(); + const bindings: ReferenceOwnerResolution["bindings"] = []; + for (const rule of rules) { + const selector = rule.selector; + if (selector.kind !== "github_repository" && selector.kind !== "github_owner") continue; + const current = observation.identity; + if (selector.owner !== current.owner || (selector.kind === "github_repository" ? selector.repositoryId !== current.repositoryId : selector.ownerId !== current.ownerId)) continue; + const row = db.query("SELECT selector,identity,proof FROM trust_settings_github_boundaries WHERE brain_id=? AND rule_id=?").get(brain, rule.id) as { + selector: string; identity: string; proof: string; + } | null; + if (!row || row.selector !== JSON.stringify(selector)) continue; + try { + const identity = identitySchema.parse(JSON.parse(row.identity)), proof = proofSchema.parse(JSON.parse(row.proof)); + if (JSON.stringify(identity.selector) !== JSON.stringify(selector) || JSON.stringify(proof.githubIdentity) !== JSON.stringify(identity) + || proof.brain !== brain || BigInt(proof.publishedTrustRevision) !== BigInt(proof.expectedTrustRevision) + 1n + || BigInt(proof.publishedTrustRevision) > BigInt(projection.revision) + || identity.ownerId !== current.ownerId + || (selector.kind === "github_owner" ? identity.private !== null || identity.ownerId !== selector.ownerId : typeof identity.private !== "boolean")) continue; + bindings.push({ ruleId: rule.id, selector, approvedOwnerId: identity.ownerId, + sameOwnerRenameRevalidated: selector.kind === "github_repository" && selector.repository !== current.repository, + publicationOperationId: proof.operationId, publicationProofHash: hash(row.proof) }); + } catch { /* Malformed or incomplete publication evidence qualifies no rule. */ } + } + // Detect descriptor/name/content changes while synchronous database reads ran. + verifyGovernancePolicyAnchored(target, policyHash); + return { version: 1, operationId: observation.operationId, state: bindings.length ? "available" : "unavailable", + policyHash, trustRevision: projection.revision, bindings }; + } catch { return unavailable(); } + finally { target?.close(); } +} diff --git a/packages/ui-server/src/brain/reference-read-writes.ts b/packages/ui-server/src/brain/reference-read-writes.ts index dcbde1daf3..fa6bd8483c 100644 --- a/packages/ui-server/src/brain/reference-read-writes.ts +++ b/packages/ui-server/src/brain/reference-read-writes.ts @@ -1,4 +1,5 @@ /** Read evidence shares the reference writer FIFO; it never grants source trust. */ +import { resolveReferenceOwners, type ReferenceOwnerRoot } from "./reference-owner-resolution.js"; import { referenceIdentityObservationMatches, type ReferenceIdentityObservation } from "./reference-acquisition.js"; import type { Database } from "bun:sqlite"; import { isLiveReferenceGrant } from "../db/reference-grants.js"; @@ -6,6 +7,7 @@ import { sourceAuthorityCurrent, type SourceAuthority } from "./reference-source interface ReferenceReadRecord { id: string; + ownerRoot?: ReferenceOwnerRoot; operationId: string; turnId: string; toolCallId: string; @@ -24,16 +26,19 @@ export function readWrites(db: Database) { const source = db.query("SELECT 1 FROM reference_sources WHERE root_id = ? AND validated_at > 0").get(rootId); if (!source || JSON.stringify(acquisition) !== record.acquisition || !sourceAuthorityCurrent(db, authority) || grantId !== null && !isLiveReferenceGrant(db, grantId, Date.now())) throw new Error("Reference read authority changed before recording"); - const evidence = JSON.parse(record.evidence) as { identityObservation?: ReferenceIdentityObservation }; + const evidence = JSON.parse(record.evidence) as { identityObservation?: ReferenceIdentityObservation; ownerResolution?: ReturnType }; const acquired = acquisition as Parameters[1]; if (!referenceIdentityObservationMatches(evidence.identityObservation, acquired, { operationId: record.operationId, brain: acquired.brain, principalId: record.principalId, turnId: record.turnId, rootId, })) throw new Error("Reference read transport identity changed before recording"); + // Resolve inside the acquired writer transaction, after queued waits. + // The result is historical qualification evidence, never a trust decision. + evidence.ownerResolution = resolveReferenceOwners(db, record.ownerRoot, evidence.identityObservation!); const count = db.query("SELECT COUNT(*) AS n FROM reference_reads WHERE turn_id = ?").get(record.turnId) as { n: number }; if (count.n >= 2000) throw new Error("Reference read record capacity exceeded"); db.query(`INSERT INTO reference_reads (id, turn_id, tool_call_id, principal_id, acquisition, evidence, response_digest, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(record.id, record.turnId, record.toolCallId, record.principalId, - record.acquisition, record.evidence, record.responseDigest, record.at); + record.acquisition, JSON.stringify(evidence), record.responseDigest, record.at); }).immediate(); }, referenceReadObserve(turnId: string, toolCallId: string, digest: string | null, finalized: boolean) { diff --git a/packages/ui-server/src/brain/reference-read.ts b/packages/ui-server/src/brain/reference-read.ts index 7446f206db..6a57bea6bc 100644 --- a/packages/ui-server/src/brain/reference-read.ts +++ b/packages/ui-server/src/brain/reference-read.ts @@ -1,4 +1,5 @@ /** Immutable reference content returned through one authenticated turn and actual backend call. */ +import { captureReferenceOwnerRoot, resolveReferenceOwners } from "./reference-owner-resolution.js"; import { createHash, randomUUID } from "node:crypto"; import type { Database } from "bun:sqlite"; import { REFERENCE_READ_INPUT_SCHEMA, type ReferenceReadInput, type ReferenceToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; @@ -30,10 +31,12 @@ function finalReadText(output: string, segments?: readonly string[]): string | n } export function createReferenceReads(options: { + /** Served protected policy root; absent hosts report owner qualification unavailable. */ + brainPath?: string; db: Database; brain: string; sources: Pick; pool: Pick; transport: Pick; }) { - const { db } = options, write = referenceWrites(db); + const { db } = options, write = referenceWrites(db), ownerRoot = captureReferenceOwnerRoot(options.brainPath); const calls = new Map>(); return { end(turnId: string) { calls.delete(turnId); }, @@ -109,10 +112,12 @@ export function createReferenceReads(options: { const result: ReferenceToolResult = { ok: true, read: { repository: location.canonical, revision: request.revision, commit: lease.commit, path: request.path, offset: blob.offset, length: blob.length, totalBytes: blob.totalBytes, encoding: utf8 ? "utf8" : "base64", content: utf8 ? text : bytes.toString("base64") }, guidance }; - await write("referenceReadPrepare", { id: randomUUID(), operationId, turnId, toolCallId, principalId, acquisition: acquisitionSnapshot, + await write("referenceReadPrepare", { id: randomUUID(), ownerRoot, operationId, turnId, toolCallId, principalId, acquisition: acquisitionSnapshot, evidence: JSON.stringify({ version: 1, path: request.path, blob: blob.blob, mode: blob.mode, tree: blob.tree, offset: blob.offset, length: blob.length, totalBytes: blob.totalBytes, digest: blob.digest, grantId: lease.readGrantId, detectorVersion: 1, - trusted: false, trustRevision: "0", identityObservation }), responseDigest: digest(JSON.stringify(result)), at: Date.now() }, lease.rootId, lease.readGrantId, authority); + trusted: false, trustRevision: "0", identityObservation, + // Provisional only: the writer resolves again after its queue wait. + ownerResolution: resolveReferenceOwners(db, ownerRoot, identityObservation!) }), responseDigest: digest(JSON.stringify(result)), at: Date.now() }, lease.rootId, lease.readGrantId, authority); assertAuthority(); return result; } catch (error) { diff --git a/packages/ui-server/tests/reference-owner-resolution.test.ts b/packages/ui-server/tests/reference-owner-resolution.test.ts new file mode 100644 index 0000000000..c9c585d718 --- /dev/null +++ b/packages/ui-server/tests/reference-owner-resolution.test.ts @@ -0,0 +1,261 @@ +import { afterEach, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, renameSync } from "node:fs"; +import { connect } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { startEgressProxy } from "@schlessera/brain-ui-sdk/internal"; +import type { TrustRule } from "@schlessera/brain-common/internal/governance-policy"; +import { createUiDb } from "../src/db/client"; +import { createReferenceGrant, revokeReferenceGrant } from "../src/db/reference-grants"; +import { createPrincipal } from "../src/db/principals"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGitHubReferenceAccess } from "../src/brain/github-reference-access"; +import { createTrustGitHubIdentity } from "../src/brain/trust-github-identity"; +import { createTrustSettings } from "../src/brain/trust-settings"; +import { createReferenceSources } from "../src/brain/reference-source"; +import { createReferenceReads } from "../src/brain/reference-read"; +import { registerReferenceWrites } from "../src/brain/reference-writes"; +import { captureReferenceOwnerRoot, resolveReferenceOwners, type ReferenceOwnerResolution } from "../src/brain/reference-owner-resolution"; +import type { ReferenceIdentityObservation } from "../src/brain/reference-acquisition"; +import { heldWriter } from "./helpers/held-writer"; +import type { ReferenceTransport } from "../src/brain/reference-transport"; +import { referencePoolDouble } from "./helpers/reference-pool-double"; +import { fixtureTls } from "./fixtures/fixture-tls"; + +const cleanup: (() => void | Promise)[] = []; +afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); +const brain = "ithaca-brain", commit = "a".repeat(40), tree = "b".repeat(40); +const repositoryRule: TrustRule = { id: "ithaca", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, + selector: { kind: "github_repository", host: "github.com", owner: "odysseus", repository: "ithaca", repositoryId: "101" } }; +const ownerRule: TrustRule = { ...repositoryRule, id: "odysseus", selector: { kind: "github_owner", host: "github.com", owner: "odysseus", ownerId: "201" } }; + +async function fixture(worker = false) { + const root = mkdtempSync(join(tmpdir(), "odysseus-owner-resolution-")); cleanup.push(() => rmSync(root, { recursive: true, force: true })); + const policyPath = join(root, "context/policies/governance.md"); mkdirSync(join(root, "context/policies"), { recursive: true }); + writeFileSync(policyPath, "---\nschema_version: 1\n---\nThe voyage policy.\n"); + const db = createUiDb(join(root, "ui.db")), writer = worker ? openSqliteWriter(db) : undefined; + if (writer) registerReferenceWrites(db, writer); + cleanup.push(async () => { await writer?.close(); db.close(); }); + const owner = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + const other = createPrincipal(db, { authMethod: "password", label: "Telemachus", ttlSeconds: 3600 }); + const state = { owner: "odysseus", repository: "ithaca", ownerId: "201", repositoryId: "101", status: 200, private: false, + afterBlob: async () => {}, current: true }; + const tls = fixtureTls(join(root, "tls"), ["api.github.com"]); + const requests: string[] = []; + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { + const path = new URL(request.url).pathname; requests.push(path); + if (state.status !== 200) return new Response(null, { status: state.status }); + if (path.startsWith("/users/")) return Response.json({ id: state.ownerId, login: state.owner, type: "User", + url: `https://api.github.com/users/${state.owner}`, html_url: `https://github.com/${state.owner}` }); + if (state.private && request.headers.get("authorization") !== "Bearer odysseus-fixture-token") return new Response(null, { status: 404 }); + return Response.json({ id: state.repositoryId, owner: { id: state.ownerId, login: state.owner }, name: state.repository, + full_name: `${state.owner}/${state.repository}`, clone_url: `https://github.com/${state.owner}/${state.repository}.git`, + url: `https://api.github.com/repos/${state.owner}/${state.repository}`, private: state.private }); + } }); cleanup.push(() => server.stop(true)); + const bytes = Buffer.from("Odysseus charts Ithaca on 2026-07-12.\n"); + const transport: ReferenceTransport = { + async resolve() { return { ok: true, commit, ref: "refs/heads/main" }; }, + async fetch(input) { writeFileSync(join(input.root, "README.md"), bytes); writeFileSync(join(input.root, ".reference-commit"), commit); return { commit }; }, + async checkout() {}, async tree() { return tree; }, + async readBlob(input) { const range = bytes.subarray(input.offset, input.offset + input.maximum); await state.afterBlob(); + return { bytes: range, blob: "c".repeat(40), mode: "100644", tree, offset: input.offset, length: range.length, + totalBytes: bytes.length, digest: createHash("sha256").update(range).digest("hex") }; }, + }; + const access = createGitHubReferenceAccess({ db, brain, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, transport, + wireTransport: { ca: readFileSync(tls.ca, "utf8"), lookup: async () => [{ address: "93.184.216.34", family: 4 }], + connect: (() => connect({ host: "127.0.0.1", port: server.port! })) as typeof connect } }); + const settingsOptions = { root, db, writer, lock: createKeyedLock(), github: createTrustGitHubIdentity({ root, access }), + authority: (id: string) => id === owner.id ? "owner-epoch" : null, observe: async (_id: string, publish: () => void | Promise) => { await publish(); } }; + const settings = createTrustSettings(settingsOptions); + const change = async (change: unknown) => { + const p = await settings.list(owner.id); + return settings.prepare(owner.id, { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change }); + }; + const save = (draft: Awaited>) => settings.commit(owner.id, { version: 1, requestId: draft.receipt.requestId, + reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + const approve = async (rule = repositoryRule) => { + const result = await save(await change({ action: "create", rule })); expect(result.receipt.publication).toBe("proved"); return result; + }; + const pool = referencePoolDouble(join(root, "pool")), sources = createReferenceSources({ db, brain, pool, transport, github: access, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" } }); + cleanup.push(() => sources.close()); + const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 16 * 1048576, observe() {} }); cleanup.push(() => egress.stop()); + const reads = createReferenceReads({ db, brain, brainPath: root, pool, sources, transport }); + let call = 0; + const read = async (principalId = other.id) => { + const toolCallId = `read-${++call}`; + const result = await reads.read({ principalId, turnId: "reading-turn", toolCallId, + request: { repository: `https://github.com/${state.owner}/${state.repository}.git`, revision: "main", path: "README.md", offset: 9, maximum: 13 }, + acquisition: { turnId: "reading-turn", egress, current: () => state.current } }); + const row = db.query("SELECT evidence,acquisition FROM reference_reads WHERE tool_call_id=?").get(toolCallId) as { evidence: string; acquisition: string }; + return { result, row, evidence: JSON.parse(row.evidence) as { trusted: false; ownerResolution: ReferenceOwnerResolution; identityObservation: ReferenceIdentityObservation } }; + }; + return { root, db, writer, owner, other, state, settings, settingsOptions, change, save, approve, read, reads, requests, policyPath, sources }; +} + +for (const worker of [false, true]) test(`protected publication binds an actual fresh managed read; writer=${worker}`, async () => { + const f = await fixture(worker); await f.approve(); + const r = await f.read(); + expect(r.evidence.ownerResolution, "READ_BINDS_PUBLISHED_APPROVED_OWNER").toMatchObject({ version: 1, state: "available", + operationId: r.evidence.identityObservation.operationId, bindings: [{ ruleId: "ithaca", selector: repositoryRule.selector, + approvedOwnerId: "201", sameOwnerRenameRevalidated: false }] }); + expect(r.evidence.ownerResolution.bindings[0]!.publicationProofHash).toMatch(/^[a-f0-9]{64}$/); + expect(r.evidence.trusted).toBe(false); + expect(JSON.stringify(r.result)).not.toContain("ownerResolution"); +}); + +for (const scenario of ["rename", "transfer", "name-reuse", "namespace-reuse"]) test(`fresh metadata handles ${scenario} under the approved owner`, async () => { + const f = await fixture(); await f.approve(); const original = await f.read(); + if (scenario === "rename") f.state.repository = "nostos"; + if (scenario === "transfer") { f.state.owner = "circe"; f.state.ownerId = "202"; } + if (scenario === "name-reuse") f.state.repositoryId = "102"; + if (scenario === "namespace-reuse") f.state.ownerId = "202"; + const r = await f.read(); + expect(r.evidence.ownerResolution.state, "APPROVED_OWNER_FENCES_TRANSFER_AND_REUSE").toBe(scenario === "rename" ? "available" : "unavailable"); + expect(r.evidence.ownerResolution.bindings).toHaveLength(scenario === "rename" ? 1 : 0); + if (scenario === "rename") expect(r.evidence.ownerResolution.bindings[0]!.sameOwnerRenameRevalidated).toBe(true); + expect(JSON.parse(original.row.evidence).ownerResolution.bindings[0].selector).toEqual(repositoryRule.selector); +}); + +test("owner approval includes future repositories only in the same current namespace and stable owner", async () => { + const f = await fixture(); await f.approve(ownerRule); + f.state.repository = "fleet"; f.state.repositoryId = "103"; + expect((await f.read()).evidence.ownerResolution.bindings[0]!.ruleId).toBe("odysseus"); + f.state.ownerId = "202"; + expect((await f.read()).evidence.ownerResolution.bindings).toEqual([]); +}); + +test("equal bytes and prepared metadata cannot create approved-owner evidence", async () => { + const f = await fixture(), draft = await f.change({ action: "create", rule: repositoryRule }); + writeFileSync(f.policyPath, draft.review.proposed); await f.settings.snapshot(); + expect((await f.read()).evidence.ownerResolution.bindings, "PREPARED_IDENTITY_IS_NOT_OWNER_APPROVAL").toEqual([]); +}); + +for (const failure of ["missing", "malformed", "wrong-brain", "changed-identity", "future-revision"]) test(`a ${failure} publication proof stays unavailable`, async () => { + const f = await fixture(); await f.approve(); + const row = f.db.query("SELECT proof FROM trust_settings_github_boundaries").get() as { proof: string }; + const proof = JSON.parse(row.proof); + if (failure === "missing") f.db.exec("DELETE FROM trust_settings_github_boundaries"); + else { + if (failure === "wrong-brain") proof.brain = "a".repeat(64); + if (failure === "changed-identity") proof.githubIdentity.ownerId = "202"; + if (failure === "future-revision") { proof.expectedTrustRevision = "99"; proof.publishedTrustRevision = "100"; } + f.db.query("UPDATE trust_settings_github_boundaries SET proof=?").run(failure === "malformed" ? "{}" : JSON.stringify(proof)); + } + expect((await f.read()).evidence.ownerResolution.bindings, "UNPROVED_OWNER_BOUNDARY_NEVER_QUALIFIES").toEqual([]); +}); + +test("receipt pruning and a fresh settings reader preserve durable approval; removal affects only later reads", async () => { + const f = await fixture(true); await f.approve(); const earlier = await f.read(); + f.db.exec("DELETE FROM trust_settings_operations"); + const restarted = createTrustSettings(f.settingsOptions); await restarted.snapshot(); + expect((await f.read()).evidence.ownerResolution.bindings).toHaveLength(1); + await f.save(await f.change({ action: "remove", ruleId: "ithaca" })); + expect((await f.read()).evidence.ownerResolution.bindings).toEqual([]); + const historical = f.db.query("SELECT evidence FROM reference_reads WHERE tool_call_id='read-1'").get() as { evidence: string }; + expect(JSON.parse(historical.evidence).ownerResolution).toEqual(earlier.evidence.ownerResolution); +}); + +test("a policy removal while the blob reader waits cannot retain owner qualification", async () => { + const f = await fixture(true); await f.approve(); + f.state.afterBlob = async () => { await f.save(await f.change({ action: "remove", ruleId: "ithaca" })); }; + const r = await f.read(); + expect(r.result.ok).toBe(true); + expect(r.evidence.ownerResolution.bindings, "OWNER_RESOLUTION_RECHECKS_AFTER_READ_WAITS").toEqual([]); +}); + +test("failed fresh metadata withholds new reads rather than borrowing approved cached identity", async () => { + const f = await fixture(); await f.approve(); await f.read(); + f.state.status = 500; + await expect(f.read()).rejects.toBeInstanceOf(Error); + expect(f.db.query("SELECT count(*) n FROM reference_reads").get()).toEqual({ n: 1 }); +}); + + +test("independent owner and repository publications retain both bounded bindings after other policy edits", async () => { + const f = await fixture(); await f.approve(); const first = await f.read(); await f.approve(ownerRule); + const r = await f.read(); + expect(r.evidence.ownerResolution.bindings.map(b => b.ruleId).sort()).toEqual(["ithaca", "odysseus"]); + expect(r.evidence.ownerResolution.policyHash).not.toBe(first.evidence.ownerResolution.policyHash); + expect(r.evidence.ownerResolution.bindings.find(b => b.ruleId === "ithaca")!.publicationProofHash) + .toBe(first.evidence.ownerResolution.bindings[0]!.publicationProofHash); +}); + +for (const change of ["invalid", "symlink", "selector", "projection"]) test(`a ${change} policy boundary cannot qualify reads`, async () => { + const f = await fixture(); await f.approve(); + const previous = readFileSync(f.policyPath, "utf8"); + if (change === "invalid") writeFileSync(f.policyPath, "---\nschema_version: 9000\n---\n"); + if (change === "selector") { writeFileSync(f.policyPath, previous.replace('"repositoryId":"101"', '"repositoryId":"102"')); await f.settings.snapshot(); } + if (change === "projection") f.db.query("UPDATE trust_settings_projection SET rules='[]'").run(); + if (change === "symlink") { + renameSync(f.policyPath, f.policyPath + ".saved"); + const { symlinkSync } = await import("node:fs"); symlinkSync(f.policyPath + ".saved", f.policyPath); + } + expect((await f.read()).evidence.ownerResolution.state, "POLICY_BOUNDARY_UNKNOWN_NEVER_QUALIFIES").toBe("unavailable"); +}); + +test("replacing the configured policy root cannot borrow the previous directory's approval", async () => { + const f = await fixture(); await f.approve(); const r = await f.read(), bound = captureReferenceOwnerRoot(f.root)!; + const policy = readFileSync(f.policyPath), backup = f.root + "-old"; + renameSync(f.root, backup); + try { + mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); + expect(resolveReferenceOwners(f.db, bound, r.evidence.identityObservation).bindings, "OWNER_APPROVAL_IS_BOUND_TO_HOST_BRAIN_ROOT").toEqual([]); + } finally { rmSync(f.root, { recursive: true, force: true }); renameSync(backup, f.root); } +}); + +test("a queued writer resolves current approval rather than a pre-wait snapshot", async () => { + const f = await fixture(true); await f.approve(); + const control = await heldWriter(f.writer!, join(f.root, "ui.db")); + let observed = false; + f.state.afterBlob = async () => { await control.hold(); observed = true; }; + const posted = control.posted("referenceReadPrepare"), pending = f.read(); + try { + await posted; expect(observed).toBe(true); + // Simulate the already committed projection/boundary side of a concurrent + // protected removal while this writer waits. The policy changes too. + const current = readFileSync(f.policyPath, "utf8"); + const removed = current.replace(/"trusted_sources":\s*\[[^\n]*\]/u, '"trusted_sources":[]'); + writeFileSync(f.policyPath, removed); + control.elsewhere(db => { db.exec("DELETE FROM trust_settings_github_boundaries"); }); + control.release(); + expect((await pending).evidence.ownerResolution.bindings, "OWNER_APPROVAL_RECHECKS_IN_ACQUIRED_WRITER").toEqual([]); + } finally { await control.close(); await pending.catch(() => {}); } +}); + + +test("a reviewed label edit retains approval and approval does not depend on a retained owner login", async () => { + const f = await fixture(); await f.approve(); + await f.save(await f.change({ action: "edit", rule: { ...repositoryRule, label: "The home harbor" } })); + f.db.query("DELETE FROM principals WHERE id=?").run(f.owner.id); + expect((await f.read()).evidence.ownerResolution.bindings).toHaveLength(1); +}); + +test("a reopened database reconstructs qualification from retained boundary evidence", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(); + f.db.exec("DELETE FROM trust_settings_operations"); + const reopened = createUiDb(join(f.root, "ui.db")); + try { + const resolved = resolveReferenceOwners(reopened, captureReferenceOwnerRoot(f.root), observed.evidence.identityObservation); + expect(resolved, "OWNER_RESOLUTION_SURVIVES_DATABASE_REOPEN").toEqual(observed.evidence.ownerResolution); + const history = reopened.query("SELECT evidence FROM reference_reads").get() as { evidence: string }; + expect(JSON.parse(history.evidence).ownerResolution).toEqual(resolved); + } finally { reopened.close(); } +}); + + +test("approved ownership grants no private access and cannot outlive private-grant revocation", async () => { + const f = await fixture(true); await f.approve(); await f.read(); + f.state.private = true; + const denied = await f.read().then(() => null, error => error); + expect(denied, "OWNER_APPROVAL_NEVER_GRANTS_PRIVATE_CREDENTIAL_ACCESS").toBeInstanceOf(Error); + const grant = createReferenceGrant(f.db, { brain, principalId: f.other.id, createdBy: f.owner.id, + repositoryPrefix: "https://github.com/odysseus/ithaca", credential: "GITHUB_TOKEN", + metadataCredentialRecipient: "https://api.github.com", now: Date.now() }); + expect((await f.read()).evidence.ownerResolution.bindings).toHaveLength(1); + f.state.afterBlob = async () => { revokeReferenceGrant(f.db, { brain, principalId: f.other.id, id: grant.id, now: Date.now() }); }; + const revoked = await f.read().then(() => null, error => error); + expect(revoked, "OWNER_APPROVAL_CANNOT_OVERRIDE_LIVE_PRIVATE_REVOCATION").toBeInstanceOf(Error); + expect(f.db.query("SELECT count(*) n FROM reference_reads").get()).toEqual({ n: 2 }); +}); diff --git a/packages/ui-server/tests/reference-read.test.ts b/packages/ui-server/tests/reference-read.test.ts index b8034ed814..30621e81cb 100644 --- a/packages/ui-server/tests/reference-read.test.ts +++ b/packages/ui-server/tests/reference-read.test.ts @@ -482,3 +482,12 @@ test("another call in the same turn cannot substitute an earlier transport opera f.state.reuseObservation = true; await expect(f.call({ toolCallId: "read-2" }), "READ_REQUIRES_ITS_OWN_TRANSPORT_OPERATION").rejects.toThrow(/transport identity/); }); + +test("read evidence explicitly withholds owner qualification without protected approval", async () => { + const f = await fixture(); + await f.call(); + const row = f.db.query("SELECT evidence FROM reference_reads").get() as { evidence: string }; + expect(JSON.parse(row.evidence).ownerResolution, "READ_OWNER_RESOLUTION_IS_EXPLICITLY_UNAVAILABLE").toMatchObject({ + version: 1, state: "unavailable", bindings: [], + }); +}); diff --git a/scripts/native-proof/managed-reference-source.ts b/scripts/native-proof/managed-reference-source.ts index 7bb3db8e01..ac26f29c60 100644 --- a/scripts/native-proof/managed-reference-source.ts +++ b/scripts/native-proof/managed-reference-source.ts @@ -1,5 +1,8 @@ /** Actual managed Git/TLS acquisition, maintenance workers and native Btrfs publication. No read-trust exemption. */ import { expect } from "bun:test"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { createTrustSettings } from "../../packages/ui-server/src/brain/trust-settings.js"; +import { createTrustGitHubIdentity } from "../../packages/ui-server/src/brain/trust-github-identity.js"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { connect } from "node:net"; import { join } from "node:path"; @@ -110,7 +113,18 @@ export async function proveManagedReferenceSource(client: ReturnType id === principal.id ? "fixture-owner-epoch" : null, + observe: async (_id, publish) => { await publish(); } }); + const beforePolicy = await settings.list(principal.id); + const rule = { id: "ithaca-native", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, + selector: { kind: "github_repository" as const, host: "github.com" as const, owner: "odysseus", repository: "ithaca", repositoryId: "101" } }; + const preparedApproval = await settings.prepare(principal.id, { version: 1, expectedTrustRevision: beforePolicy.revision, + expectedPolicyHash: beforePolicy.policyHash, change: { action: "create", rule } }); + const approved = await settings.commit(principal.id, { version: 1, requestId: preparedApproval.receipt.requestId, + reviewId: preparedApproval.review.reviewId, reviewedBytesHash: preparedApproval.review.reviewedBytesHash }); + expect(approved.receipt.publication, "MANAGED_NATIVE_OWNER_APPROVAL_IS_REAL_PUBLICATION").toBe("proved"); + const reads = createReferenceReads({ db, brainPath: brain, brain: servedBrain, sources, pool: client, transport }); const tools = createReferenceTools({ sources, reads }), turnId = "odysseus-native-read"; await tools.begin(turnId, { principalId: principal.id, posture: "interactive", generation: null }); tools.attachEgress(turnId, principal.id, { egress, current: () => true }); @@ -126,10 +140,25 @@ export async function proveManagedReferenceSource(client: ReturnType Date: Fri, 20 Nov 2026 16:34:52 +0000 Subject: [PATCH 2/8] fix(ui-server): retain publication root identity across restarts --- .../decisions/reference-source-acquisition.md | 6 +++++- .../src/brain/reference-owner-resolution.ts | 5 +++-- .../ui-server/src/brain/trust-settings.ts | 1 + .../tests/reference-owner-resolution.test.ts | 21 ++++++++++++++++++- 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 6528476434..779946170c 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -442,7 +442,11 @@ Approved-owner rule evaluation remains independently required. The host read service resolves each actual transport observation against the protected Markdown policy, its matching durable trust projection and Settings' operation-bound approved-owner evidence. The policy root's directory identity is -captured at service construction. Links, replaced roots, invalid or incoherent +captured at service construction and compared with the directory device/inode +retained from the descriptor-anchored Settings publication. Restart cannot adopt +a replacement root's identical policy bytes as the old approval. Legacy proofs +without that publication root withhold qualification until a new reviewed +publication. Links, replaced roots, invalid or incoherent policy/projection data and missing/malformed publication proof produce unavailable qualification; they do not prevent an otherwise authorized untrusted read. diff --git a/packages/ui-server/src/brain/reference-owner-resolution.ts b/packages/ui-server/src/brain/reference-owner-resolution.ts index 595764750a..5fc7e9fadf 100644 --- a/packages/ui-server/src/brain/reference-owner-resolution.ts +++ b/packages/ui-server/src/brain/reference-owner-resolution.ts @@ -14,7 +14,8 @@ const providerId = z.string().regex(/^[1-9][0-9]{0,19}$/u); const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u).refine(value => BigInt(value) <= 18446744073709551615n); const identitySchema = z.strictObject({ selector: TrustSelectorSchema, ownerId: providerId, private: z.boolean().nullable() }); const proofSchema = z.strictObject({ operationId: id, principal: z.string().min(1).max(128), brain: digest, - authority: z.string().min(1).max(4096), baseHash: digest.nullable(), expectedTrustRevision: revision, + authority: z.string().min(1).max(4096), + policyRoot: z.strictObject({ device: z.number().int().nonnegative().safe(), inode: z.number().int().nonnegative().safe() }), baseHash: digest.nullable(), expectedTrustRevision: revision, publishedTrustRevision: revision, reviewedBytesHash: digest, githubIdentity: identitySchema }); export interface ReferenceOwnerRoot { path: string; device: number; inode: number } @@ -75,7 +76,7 @@ export function resolveReferenceOwners(db: Database, root: Readonly BigInt(projection.revision) || identity.ownerId !== current.ownerId || (selector.kind === "github_owner" ? identity.private !== null || identity.ownerId !== selector.ownerId : typeof identity.private !== "boolean")) continue; diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index 00bbcf2e25..0f3ae553e9 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -261,6 +261,7 @@ export function createTrustSettings(options: { receipt.stage = "file_published"; receipt.publication = "proved"; receipt.publishedTrustRevision = String(BigInt(p.revision) + 1n); await save("file_published", JSON.stringify({ operationId: receipt.operationId, principal, brain, authority: r.authority, + policyRoot: { device: target.directories[0]!.dev, inode: target.directories[0]!.ino }, baseHash: p.policyHash, expectedTrustRevision: p.revision, publishedTrustRevision: receipt.publishedTrustRevision, reviewedBytesHash: payload.proposedHash, ...(payload.githubIdentity ? { githubIdentity: payload.githubIdentity } : {}) }), payload.githubIdentity && payload.rule ? { brain, ruleId: payload.rule.id, selector: JSON.stringify(payload.rule.selector), identity: JSON.stringify(payload.githubIdentity) } : undefined); proved = true; diff --git a/packages/ui-server/tests/reference-owner-resolution.test.ts b/packages/ui-server/tests/reference-owner-resolution.test.ts index c9c585d718..c47d036b5e 100644 --- a/packages/ui-server/tests/reference-owner-resolution.test.ts +++ b/packages/ui-server/tests/reference-owner-resolution.test.ts @@ -132,12 +132,15 @@ test("equal bytes and prepared metadata cannot create approved-owner evidence", expect((await f.read()).evidence.ownerResolution.bindings, "PREPARED_IDENTITY_IS_NOT_OWNER_APPROVAL").toEqual([]); }); -for (const failure of ["missing", "malformed", "wrong-brain", "changed-identity", "future-revision"]) test(`a ${failure} publication proof stays unavailable`, async () => { +for (const failure of ["missing", "malformed", "wrong-brain", "changed-identity", "future-revision", "legacy-root", "wrong-device", "wrong-inode"]) test(`a ${failure} publication proof stays unavailable`, async () => { const f = await fixture(); await f.approve(); const row = f.db.query("SELECT proof FROM trust_settings_github_boundaries").get() as { proof: string }; const proof = JSON.parse(row.proof); if (failure === "missing") f.db.exec("DELETE FROM trust_settings_github_boundaries"); else { + if (failure === "legacy-root") delete proof.policyRoot; + if (failure === "wrong-device") proof.policyRoot.device += 1; + if (failure === "wrong-inode") proof.policyRoot.inode += 1; if (failure === "wrong-brain") proof.brain = "a".repeat(64); if (failure === "changed-identity") proof.githubIdentity.ownerId = "202"; if (failure === "future-revision") { proof.expectedTrustRevision = "99"; proof.publishedTrustRevision = "100"; } @@ -259,3 +262,19 @@ test("approved ownership grants no private access and cannot outlive private-gra expect(revoked, "OWNER_APPROVAL_CANNOT_OVERRIDE_LIVE_PRIVATE_REVOCATION").toBeInstanceOf(Error); expect(f.db.query("SELECT count(*) n FROM reference_reads").get()).toEqual({ n: 2 }); }); + +test("restart cannot apply retained approval to a replacement policy root with identical bytes", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(); + const policy = readFileSync(f.policyPath), backup = f.root + "-before-restart"; + renameSync(f.root, backup); + try { + mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); + // Retain the authoritative UI database, but construct both readers anew as + // startup does. Equal path/policy bytes must not resurrect old approval. + const reopened = createUiDb(join(backup, "ui.db")); + try { + expect(resolveReferenceOwners(reopened, captureReferenceOwnerRoot(f.root), observed.evidence.identityObservation).bindings, + "RESTART_REJECTS_APPROVAL_FROM_REPLACED_PUBLISHED_ROOT").toEqual([]); + } finally { reopened.close(); } + } finally { rmSync(f.root, { recursive: true, force: true }); renameSync(backup, f.root); } +}); From bda14c2fb779c8e02594ffafb9a147d9728b9edc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:44:16 +0000 Subject: [PATCH 3/8] fix(ui-server): require live host continuity for owner qualification --- .../3613-approved-owner-read-resolution.md | 2 +- .../decisions/reference-source-acquisition.md | 16 +++--- packages/ui-server/src/app.ts | 7 ++- .../src/brain/reference-owner-resolution.ts | 28 ++++++---- .../ui-server/src/brain/reference-read.ts | 6 +-- .../ui-server/src/brain/trust-settings.ts | 6 ++- .../tests/reference-owner-resolution.test.ts | 54 +++++++++++++++++-- .../native-proof/managed-reference-source.ts | 8 +-- 8 files changed, 95 insertions(+), 32 deletions(-) diff --git a/.changeset/3613-approved-owner-read-resolution.md b/.changeset/3613-approved-owner-read-resolution.md index 6bd35c300c..a0b8f9ce91 100644 --- a/.changeset/3613-approved-owner-read-resolution.md +++ b/.changeset/3613-approved-owner-read-resolution.md @@ -2,4 +2,4 @@ "@schlessera/brain-ui-server": patch --- -Bind immutable read identity evidence to independently published Settings owner approval. Record unavailable qualification for missing or mismatched approval, repository transfer/name reuse and replaced policy roots, and recheck inside the write transaction after waits. Source trust remains disabled. +Bind immutable read identity evidence to independently published Settings owner approval. Record unavailable qualification for missing or mismatched approval, repository transfer/name reuse and replaced policy roots, and recheck inside the write transaction after waits. Owner qualification requires a new reviewed publication after a host restart because durable directory continuity cannot be proven. Source trust remains disabled. diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 779946170c..c0ae6f33e4 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -442,11 +442,14 @@ Approved-owner rule evaluation remains independently required. The host read service resolves each actual transport observation against the protected Markdown policy, its matching durable trust projection and Settings' operation-bound approved-owner evidence. The policy root's directory identity is -captured at service construction and compared with the directory device/inode -retained from the descriptor-anchored Settings publication. Restart cannot adopt -a replacement root's identical policy bytes as the old approval. Legacy proofs -without that publication root withhold qualification until a new reviewed -publication. Links, replaced roots, invalid or incoherent +captured for one host lifetime with an open directory descriptor, which prevents +that directory inode from being reused while the host is live. Settings records +the descriptor identity and an unguessable host continuity epoch at publication. +The epoch lives in host memory and the protected UI database, never the +agent-writable policy tree. A new host lifetime has a new epoch: retained +approval remains historical and requires a new reviewed publication before owner +qualification becomes available, even for unchanged policy bytes and directory. +Legacy proofs without that continuity binding also withhold qualification. Links, replaced roots, invalid or incoherent policy/projection data and missing/malformed publication proof produce unavailable qualification; they do not prevent an otherwise authorized untrusted read. @@ -458,7 +461,8 @@ Owner rules deliberately include future repositories currently in that same canonical namespace and stable owner ID. A validated policy permits at most one matching repository and one matching owner rule. Other policy edits do not erase a retained approval of the same selector, and bounded operation-receipt pruning -or approving-login deletion does not erase the durable owner evidence. +or approving-login deletion does not erase the durable owner evidence. It does +not prove continuity across host restart. Resolution runs provisionally before recording and again inside the acquired SQLite writer transaction. The recorded operation ID, policy hash/revision, diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 73dbc1da15..cfac2b18e8 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1,3 +1,4 @@ +import { createReferenceOwnerContinuity } from "./brain/reference-owner-resolution.js"; import { createTrustSettings } from "./brain/trust-settings.js"; import { createTrustSettingsRoutes } from "./routes/trust-settings.js"; import { createTrustGitHubIdentity } from "./brain/trust-github-identity.js"; @@ -425,6 +426,8 @@ export async function createApp(options: CreateAppOptions = {}): Promise { if (ephemeralJournal) rmSync(journalRoot, { recursive: true, force: true }); throw error; }); const bootCleanup: (() => void | Promise)[] = []; + const ownerContinuity = createReferenceOwnerContinuity(config.brainPath); + bootCleanup.push(() => ownerContinuity.close()); try { const nativeRecovery = await nativeLeases.recoverDeadOwners(); if (nativeRecovery.unknown.length || nativeRecovery.retainedUnverifiable) observability.logger("brain").emit({ severityText: "WARN", @@ -562,7 +565,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise referenceWorktrees.close()); @@ -1334,7 +1337,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise unavailableBackends.some(failure => failure.backendId === "pi"); app.route("/api", createPiAuthRoutes({ agent: config.agent, excluded: piExcluded })); app.route("/api", createWebSearchRoutes({ agent: config.agent, excluded: piExcluded })); - const trustSettings = createTrustSettings({ root: config.brainPath, db, writer, lock: workerLock, + const trustSettings = createTrustSettings({ root: config.brainPath, ownerRoot: ownerContinuity.root, db, writer, lock: workerLock, github: createTrustGitHubIdentity({ root: config.brainPath, access: githubReferenceAccess }), authority: id => { if (authMode !== "password") return null; diff --git a/packages/ui-server/src/brain/reference-owner-resolution.ts b/packages/ui-server/src/brain/reference-owner-resolution.ts index 5fc7e9fadf..352790004c 100644 --- a/packages/ui-server/src/brain/reference-owner-resolution.ts +++ b/packages/ui-server/src/brain/reference-owner-resolution.ts @@ -1,6 +1,6 @@ /** Read-only owner qualification. This records historical evidence, never a source-trust admission. */ -import { createHash } from "node:crypto"; -import { lstatSync, realpathSync } from "node:fs"; +import { createHash, randomUUID } from "node:crypto"; +import { constants, openSync, fstatSync, closeSync, realpathSync } from "node:fs"; import type { Database } from "bun:sqlite"; import { z } from "zod"; import { openGovernancePolicyAnchored, verifyGovernancePolicyAnchored, parseGovernancePolicy, @@ -15,16 +15,22 @@ const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u).refine(value => Big const identitySchema = z.strictObject({ selector: TrustSelectorSchema, ownerId: providerId, private: z.boolean().nullable() }); const proofSchema = z.strictObject({ operationId: id, principal: z.string().min(1).max(128), brain: digest, authority: z.string().min(1).max(4096), - policyRoot: z.strictObject({ device: z.number().int().nonnegative().safe(), inode: z.number().int().nonnegative().safe() }), baseHash: digest.nullable(), expectedTrustRevision: revision, + policyRoot: z.strictObject({ device: z.number().int().nonnegative().safe(), inode: z.number().int().nonnegative().safe(), continuity: z.string().uuid() }), baseHash: digest.nullable(), expectedTrustRevision: revision, publishedTrustRevision: revision, reviewedBytesHash: digest, githubIdentity: identitySchema }); -export interface ReferenceOwnerRoot { path: string; device: number; inode: number } -/** Bind the host's configured directory once; later aliases/replacements cannot select another brain. */ -export function captureReferenceOwnerRoot(path: string | undefined): Readonly | undefined { - if (!path) return; - try { const canonical = realpathSync(path), stat = lstatSync(canonical); - return stat.isDirectory() ? Object.freeze({ path: canonical, device: stat.dev, inode: stat.ino }) : undefined; - } catch { return; } +export interface ReferenceOwnerRoot { path: string; device: number; inode: number; continuity: string } +/** One host lifetime. Holding the directory descriptor prevents inode reuse + * while live; the unguessable epoch withholds old approval after any restart. + * The epoch is host-only and never stored in the agent-writable policy tree. */ +export function createReferenceOwnerContinuity(path: string): { root: Readonly | undefined; close(): void } { + let fd: number | undefined; + try { + const canonical = realpathSync(path); + fd = openSync(canonical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + const stat = fstatSync(fd); + const root = Object.freeze({ path: canonical, device: stat.dev, inode: stat.ino, continuity: randomUUID() }); + return { root, close() { if (fd !== undefined) { closeSync(fd); fd = undefined; } } }; + } catch { if (fd !== undefined) closeSync(fd); return { root: undefined, close() {} }; } } type GitHubSelector = Extract; @@ -76,7 +82,7 @@ export function resolveReferenceOwners(db: Database, root: Readonly BigInt(projection.revision) || identity.ownerId !== current.ownerId || (selector.kind === "github_owner" ? identity.private !== null || identity.ownerId !== selector.ownerId : typeof identity.private !== "boolean")) continue; diff --git a/packages/ui-server/src/brain/reference-read.ts b/packages/ui-server/src/brain/reference-read.ts index 6a57bea6bc..613a59ab70 100644 --- a/packages/ui-server/src/brain/reference-read.ts +++ b/packages/ui-server/src/brain/reference-read.ts @@ -1,5 +1,5 @@ /** Immutable reference content returned through one authenticated turn and actual backend call. */ -import { captureReferenceOwnerRoot, resolveReferenceOwners } from "./reference-owner-resolution.js"; +import { type ReferenceOwnerRoot, resolveReferenceOwners } from "./reference-owner-resolution.js"; import { createHash, randomUUID } from "node:crypto"; import type { Database } from "bun:sqlite"; import { REFERENCE_READ_INPUT_SCHEMA, type ReferenceReadInput, type ReferenceToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; @@ -32,11 +32,11 @@ function finalReadText(output: string, segments?: readonly string[]): string | n export function createReferenceReads(options: { /** Served protected policy root; absent hosts report owner qualification unavailable. */ - brainPath?: string; + ownerRoot?: Readonly; db: Database; brain: string; sources: Pick; pool: Pick; transport: Pick; }) { - const { db } = options, write = referenceWrites(db), ownerRoot = captureReferenceOwnerRoot(options.brainPath); + const { db } = options, write = referenceWrites(db), ownerRoot = options.ownerRoot; const calls = new Map>(); return { end(turnId: string) { calls.delete(turnId); }, diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index 0f3ae553e9..8c4253146a 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -1,3 +1,4 @@ +import type { ReferenceOwnerRoot } from "./reference-owner-resolution.js"; /** Human Settings operations. Markdown is authoritative; these rows are bounded * request/audit receipts, never a second policy source or an agent turn. */ import { createHash, randomBytes } from "node:crypto"; @@ -80,6 +81,7 @@ export function createTrustSettings(options: { * fingerprint includes credential/lifetime identity, never a body/channel claim. */ authority(principalId: string): string | null; observe(operationId: string, operation: (publish?: (write: () => void) => Promise) => void | Promise): Promise; + ownerRoot?: Readonly; github?: ReturnType; now?: () => number; /** Host-only deterministic crash/race injection, never wired from HTTP. */ @@ -261,7 +263,9 @@ export function createTrustSettings(options: { receipt.stage = "file_published"; receipt.publication = "proved"; receipt.publishedTrustRevision = String(BigInt(p.revision) + 1n); await save("file_published", JSON.stringify({ operationId: receipt.operationId, principal, brain, authority: r.authority, - policyRoot: { device: target.directories[0]!.dev, inode: target.directories[0]!.ino }, + policyRoot: { device: target.directories[0]!.dev, inode: target.directories[0]!.ino, + ...(options.ownerRoot?.path === root && options.ownerRoot.device === target.directories[0]!.dev && options.ownerRoot.inode === target.directories[0]!.ino + ? { continuity: options.ownerRoot.continuity } : {}) }, baseHash: p.policyHash, expectedTrustRevision: p.revision, publishedTrustRevision: receipt.publishedTrustRevision, reviewedBytesHash: payload.proposedHash, ...(payload.githubIdentity ? { githubIdentity: payload.githubIdentity } : {}) }), payload.githubIdentity && payload.rule ? { brain, ruleId: payload.rule.id, selector: JSON.stringify(payload.rule.selector), identity: JSON.stringify(payload.githubIdentity) } : undefined); proved = true; diff --git a/packages/ui-server/tests/reference-owner-resolution.test.ts b/packages/ui-server/tests/reference-owner-resolution.test.ts index c47d036b5e..7d2e0206a6 100644 --- a/packages/ui-server/tests/reference-owner-resolution.test.ts +++ b/packages/ui-server/tests/reference-owner-resolution.test.ts @@ -17,7 +17,7 @@ import { createTrustSettings } from "../src/brain/trust-settings"; import { createReferenceSources } from "../src/brain/reference-source"; import { createReferenceReads } from "../src/brain/reference-read"; import { registerReferenceWrites } from "../src/brain/reference-writes"; -import { captureReferenceOwnerRoot, resolveReferenceOwners, type ReferenceOwnerResolution } from "../src/brain/reference-owner-resolution"; +import { createReferenceOwnerContinuity, resolveReferenceOwners, type ReferenceOwnerResolution } from "../src/brain/reference-owner-resolution"; import type { ReferenceIdentityObservation } from "../src/brain/reference-acquisition"; import { heldWriter } from "./helpers/held-writer"; import type { ReferenceTransport } from "../src/brain/reference-transport"; @@ -26,6 +26,7 @@ import { fixtureTls } from "./fixtures/fixture-tls"; const cleanup: (() => void | Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); +const captureReferenceOwnerRoot = (path: string) => { const c = createReferenceOwnerContinuity(path); cleanup.push(() => c.close()); return c.root; }; const brain = "ithaca-brain", commit = "a".repeat(40), tree = "b".repeat(40); const repositoryRule: TrustRule = { id: "ithaca", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, selector: { kind: "github_repository", host: "github.com", owner: "odysseus", repository: "ithaca", repositoryId: "101" } }; @@ -33,6 +34,7 @@ const ownerRule: TrustRule = { ...repositoryRule, id: "odysseus", selector: { ki async function fixture(worker = false) { const root = mkdtempSync(join(tmpdir(), "odysseus-owner-resolution-")); cleanup.push(() => rmSync(root, { recursive: true, force: true })); + const continuity = createReferenceOwnerContinuity(root); cleanup.push(() => continuity.close()); const policyPath = join(root, "context/policies/governance.md"); mkdirSync(join(root, "context/policies"), { recursive: true }); writeFileSync(policyPath, "---\nschema_version: 1\n---\nThe voyage policy.\n"); const db = createUiDb(join(root, "ui.db")), writer = worker ? openSqliteWriter(db) : undefined; @@ -66,7 +68,7 @@ async function fixture(worker = false) { const access = createGitHubReferenceAccess({ db, brain, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, transport, wireTransport: { ca: readFileSync(tls.ca, "utf8"), lookup: async () => [{ address: "93.184.216.34", family: 4 }], connect: (() => connect({ host: "127.0.0.1", port: server.port! })) as typeof connect } }); - const settingsOptions = { root, db, writer, lock: createKeyedLock(), github: createTrustGitHubIdentity({ root, access }), + const settingsOptions = { root, ownerRoot: continuity.root, db, writer, lock: createKeyedLock(), github: createTrustGitHubIdentity({ root, access }), authority: (id: string) => id === owner.id ? "owner-epoch" : null, observe: async (_id: string, publish: () => void | Promise) => { await publish(); } }; const settings = createTrustSettings(settingsOptions); const change = async (change: unknown) => { @@ -81,7 +83,7 @@ async function fixture(worker = false) { const pool = referencePoolDouble(join(root, "pool")), sources = createReferenceSources({ db, brain, pool, transport, github: access, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" } }); cleanup.push(() => sources.close()); const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 16 * 1048576, observe() {} }); cleanup.push(() => egress.stop()); - const reads = createReferenceReads({ db, brain, brainPath: root, pool, sources, transport }); + const reads = createReferenceReads({ db, brain, ownerRoot: continuity.root, pool, sources, transport }); let call = 0; const read = async (principalId = other.id) => { const toolCallId = `read-${++call}`; @@ -91,7 +93,7 @@ async function fixture(worker = false) { const row = db.query("SELECT evidence,acquisition FROM reference_reads WHERE tool_call_id=?").get(toolCallId) as { evidence: string; acquisition: string }; return { result, row, evidence: JSON.parse(row.evidence) as { trusted: false; ownerResolution: ReferenceOwnerResolution; identityObservation: ReferenceIdentityObservation } }; }; - return { root, db, writer, owner, other, state, settings, settingsOptions, change, save, approve, read, reads, requests, policyPath, sources }; + return { root, ownerRoot: continuity.root, continuity, db, writer, owner, other, state, settings, settingsOptions, change, save, approve, read, reads, requests, policyPath, sources }; } for (const worker of [false, true]) test(`protected publication binds an actual fresh managed read; writer=${worker}`, async () => { @@ -240,7 +242,7 @@ test("a reopened database reconstructs qualification from retained boundary evid f.db.exec("DELETE FROM trust_settings_operations"); const reopened = createUiDb(join(f.root, "ui.db")); try { - const resolved = resolveReferenceOwners(reopened, captureReferenceOwnerRoot(f.root), observed.evidence.identityObservation); + const resolved = resolveReferenceOwners(reopened, f.ownerRoot, observed.evidence.identityObservation); expect(resolved, "OWNER_RESOLUTION_SURVIVES_DATABASE_REOPEN").toEqual(observed.evidence.ownerResolution); const history = reopened.query("SELECT evidence FROM reference_reads").get() as { evidence: string }; expect(JSON.parse(history.evidence).ownerResolution).toEqual(resolved); @@ -278,3 +280,45 @@ test("restart cannot apply retained approval to a replacement policy root with i } finally { reopened.close(); } } finally { rmSync(f.root, { recursive: true, force: true }); renameSync(backup, f.root); } }); + +test("deleted root replacement cannot inherit approval even when the filesystem reuses its identity", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(), policy = readFileSync(f.policyPath); + const retained = mkdtempSync(join(tmpdir(), "odysseus-retained-owner-db-")); + try { + writeFileSync(join(retained, "ui.db"), f.db.serialize()); + writeFileSync(join(retained, "ui.db.journal.db"), f.db.serialize("journal")); + f.continuity.close(); // Simulate shutdown: no descriptor pins the deleted root. + rmSync(f.root, { recursive: true }); + mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); + const reopened = createUiDb(join(retained, "ui.db")); + try { + const replacement = captureReferenceOwnerRoot(f.root)!; + const row = reopened.query("SELECT proof FROM trust_settings_github_boundaries").get() as { proof: string }; + const proof = JSON.parse(row.proof); + // Deterministically model the kernel reusing the deleted directory's + // device/inode pair; deletion above is real, not a rename keeping it alive. + proof.policyRoot.device = replacement.device; proof.policyRoot.inode = replacement.inode; + reopened.query("UPDATE trust_settings_github_boundaries SET proof=?").run(JSON.stringify(proof)); + expect(resolveReferenceOwners(reopened, replacement, observed.evidence.identityObservation).bindings, + "DELETED_ROOT_REUSE_REQUIRES_NEW_REVIEWED_APPROVAL").toEqual([]); + } finally { reopened.close(); } + } finally { rmSync(retained, { recursive: true, force: true }); } +}); + +test("a new host lifetime requires reviewed republication even with an unchanged policy root", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(); + f.continuity.close(); + const next = createReferenceOwnerContinuity(f.root); + try { + expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation).bindings, + "NEW_HOST_LIFETIME_REQUIRES_REAPPROVAL").toEqual([]); + const settings = createTrustSettings({ ...f.settingsOptions, ownerRoot: next.root }); + const before = await settings.list(f.owner.id); + const draft = await settings.prepare(f.owner.id, { version: 1, expectedTrustRevision: before.revision, + expectedPolicyHash: before.policyHash, change: { action: "edit", rule: { ...repositoryRule, label: "The reviewed home harbor" } } }); + await settings.commit(f.owner.id, { version: 1, requestId: draft.receipt.requestId, + reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation).bindings, + "NEW_PUBLICATION_RESTORES_CURRENT_HOST_QUALIFICATION").toHaveLength(1); + } finally { next.close(); } +}); diff --git a/scripts/native-proof/managed-reference-source.ts b/scripts/native-proof/managed-reference-source.ts index ac26f29c60..2f18ef479b 100644 --- a/scripts/native-proof/managed-reference-source.ts +++ b/scripts/native-proof/managed-reference-source.ts @@ -1,3 +1,4 @@ +import { createReferenceOwnerContinuity } from "../../packages/ui-server/src/brain/reference-owner-resolution.js"; /** Actual managed Git/TLS acquisition, maintenance workers and native Btrfs publication. No read-trust exemption. */ import { expect } from "bun:test"; import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; @@ -43,6 +44,7 @@ export async function proveManagedReferenceSource(client: ReturnType id === principal.id ? "fixture-owner-epoch" : null, observe: async (_id, publish) => { await publish(); } }); const beforePolicy = await settings.list(principal.id); @@ -124,7 +126,7 @@ export async function proveManagedReferenceSource(client: ReturnType true }); @@ -177,6 +179,6 @@ export async function proveManagedReferenceSource(client: ReturnType Date: Fri, 20 Nov 2026 16:50:15 +0000 Subject: [PATCH 4/8] fix(ui-server): close owner continuity during normal shutdown --- packages/ui-server/src/app.ts | 1 + .../tests/reference-owner-lifecycle.test.ts | 20 +++++++++++++++++++ .../tests/reference-owner-resolution.test.ts | 3 ++- 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 packages/ui-server/tests/reference-owner-lifecycle.test.ts diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index cfac2b18e8..11f79c0a06 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1538,6 +1538,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise writer.close()); await attempt(() => db.close()); + await attempt(() => ownerContinuity.close()); clearTimeout(grace); if (failures.length === 1) throw failures[0]; if (failures.length) throw new AggregateError(failures, "Application shutdown retained failed cleanup outcomes."); diff --git a/packages/ui-server/tests/reference-owner-lifecycle.test.ts b/packages/ui-server/tests/reference-owner-lifecycle.test.ts new file mode 100644 index 0000000000..53c1f2fa68 --- /dev/null +++ b/packages/ui-server/tests/reference-owner-lifecycle.test.ts @@ -0,0 +1,20 @@ +import { expect, test } from "bun:test"; +import { readdirSync, readlinkSync } from "node:fs"; +import { httpContractApp } from "./helpers/http-contract-app"; + +function rootDescriptors(root: string): string[] { + return readdirSync("/proc/self/fd").filter(fd => { + try { return readlinkSync(`/proc/self/fd/${fd}`) === root; } catch { return false; } + }); +} + +test("normal app shutdown releases the policy-root continuity descriptor on every create/close cycle", async () => { + for (let cycle = 0; cycle < 2; cycle++) { + const t = await httpContractApp(); + try { + expect(rootDescriptors(t.brainPath).length, "RUNNING_APP_HOLDS_POLICY_ROOT_CONTINUITY").toBeGreaterThan(0); + await t.app.close(); + expect(rootDescriptors(t.brainPath), "NORMAL_APP_CLOSE_RELEASES_POLICY_ROOT_CONTINUITY").toEqual([]); + } finally { await t.close(); } + } +}); diff --git a/packages/ui-server/tests/reference-owner-resolution.test.ts b/packages/ui-server/tests/reference-owner-resolution.test.ts index 7d2e0206a6..6aef0cebf1 100644 --- a/packages/ui-server/tests/reference-owner-resolution.test.ts +++ b/packages/ui-server/tests/reference-owner-resolution.test.ts @@ -201,7 +201,8 @@ for (const change of ["invalid", "symlink", "selector", "projection"]) test(`a $ }); test("replacing the configured policy root cannot borrow the previous directory's approval", async () => { - const f = await fixture(); await f.approve(); const r = await f.read(), bound = captureReferenceOwnerRoot(f.root)!; + const f = await fixture(); await f.approve(); const r = await f.read(), bound = f.ownerRoot; + expect(resolveReferenceOwners(f.db, bound, r.evidence.identityObservation).bindings, "LIVE_ORIGINAL_ROOT_HAS_APPROVED_BINDING").toHaveLength(1); const policy = readFileSync(f.policyPath), backup = f.root + "-old"; renameSync(f.root, backup); try { From cea8cc4cf210235076cb1575bfbf15e02a3b3300 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:06:44 +0000 Subject: [PATCH 5/8] fix(ui-server): attest owner approval against pinned native brain identity --- .../3613-approved-owner-read-resolution.md | 2 +- .../decisions/reference-source-acquisition.md | 23 ++++---- .../src/brain/reference-owner-native-root.ts | 30 +++++++++++ .../src/brain/reference-owner-resolution.ts | 24 +++------ .../src/brain/reference-owner-root-kernel.ts | 24 +++++++++ .../tests/reference-owner-lifecycle.test.ts | 8 +-- .../tests/reference-owner-native-root.test.ts | 40 ++++++++++++++ .../tests/reference-owner-resolution.test.ts | 52 ++++++++++--------- .../native-proof/managed-reference-source.ts | 8 ++- scripts/native-proof/reference-owner-root.ts | 33 ++++++++++++ 10 files changed, 186 insertions(+), 58 deletions(-) create mode 100644 packages/ui-server/src/brain/reference-owner-native-root.ts create mode 100644 packages/ui-server/src/brain/reference-owner-root-kernel.ts create mode 100644 packages/ui-server/tests/reference-owner-native-root.test.ts create mode 100644 scripts/native-proof/reference-owner-root.ts diff --git a/.changeset/3613-approved-owner-read-resolution.md b/.changeset/3613-approved-owner-read-resolution.md index a0b8f9ce91..664498f97f 100644 --- a/.changeset/3613-approved-owner-read-resolution.md +++ b/.changeset/3613-approved-owner-read-resolution.md @@ -2,4 +2,4 @@ "@schlessera/brain-ui-server": patch --- -Bind immutable read identity evidence to independently published Settings owner approval. Record unavailable qualification for missing or mismatched approval, repository transfer/name reuse and replaced policy roots, and recheck inside the write transaction after waits. Owner qualification requires a new reviewed publication after a host restart because durable directory continuity cannot be proven. Source trust remains disabled. +Bind immutable read identity evidence to independently published Settings owner approval. Record unavailable qualification for missing or mismatched approval, repository transfer/name reuse and replaced policy roots, and recheck inside the write transaction after waits. Bind publication to the qualified native filesystem and live-brain subvolume UUID, preserving ordinary restart while refusing recreated roots and unqualified hosts. Source trust remains disabled. diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index c0ae6f33e4..486b7279c9 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -442,14 +442,17 @@ Approved-owner rule evaluation remains independently required. The host read service resolves each actual transport observation against the protected Markdown policy, its matching durable trust projection and Settings' operation-bound approved-owner evidence. The policy root's directory identity is -captured for one host lifetime with an open directory descriptor, which prevents -that directory inode from being reused while the host is live. Settings records -the descriptor identity and an unguessable host continuity epoch at publication. -The epoch lives in host memory and the protected UI database, never the -agent-writable policy tree. A new host lifetime has a new epoch: retained -approval remains historical and requires a new reviewed publication before owner -qualification becomes available, even for unchanged policy bytes and directory. -Legacy proofs without that continuity binding also withhold qualification. Links, replaced roots, invalid or incoherent +captured with a no-follow directory descriptor and qualified against the native +manager's filesystem ID and fixed live-brain subvolume UUID. The kernel Btrfs +identity is read from that already held descriptor, including across native +library startup waits; lexical replacement before qualification completes +withholds the result. Holding the directory descriptor prevents live inode +reuse, and each read still checks the named root against that descriptor's +identity. Publication records filesystem ID and subvolume UUID from this host +qualification. Ordinary restart requalifies the same native brain and preserves +approval; recreation at the same path, inode and policy bytes has a different +subvolume UUID and cannot inherit it. An unqualified host or legacy proof without +that native binding withholds qualification. Links, replaced roots, invalid or incoherent policy/projection data and missing/malformed publication proof produce unavailable qualification; they do not prevent an otherwise authorized untrusted read. @@ -461,8 +464,8 @@ Owner rules deliberately include future repositories currently in that same canonical namespace and stable owner ID. A validated policy permits at most one matching repository and one matching owner rule. Other policy edits do not erase a retained approval of the same selector, and bounded operation-receipt pruning -or approving-login deletion does not erase the durable owner evidence. It does -not prove continuity across host restart. +or approving-login deletion does not erase the durable owner evidence. It +is interpreted only against a freshly qualified native brain after restart. Resolution runs provisionally before recording and again inside the acquired SQLite writer transaction. The recorded operation ID, policy hash/revision, diff --git a/packages/ui-server/src/brain/reference-owner-native-root.ts b/packages/ui-server/src/brain/reference-owner-native-root.ts new file mode 100644 index 0000000000..3db812e1aa --- /dev/null +++ b/packages/ui-server/src/brain/reference-owner-native-root.ts @@ -0,0 +1,30 @@ +/** Existing Linux/Btrfs native identity, read from the actual held descriptor. */ +import { constants, openSync, closeSync, fstatSync, lstatSync, realpathSync } from "node:fs"; +import * as kernel from "./reference-owner-root-kernel.js"; +export interface ReferenceOwnerNativeIdentity { fsid: string; uuid: string } +export interface ReferenceOwnerRoot { path: string; device: number; inode: number; native: ReferenceOwnerNativeIdentity } +export type ReferenceOwnerExpectedRoot = { fsid: string; brainUuid: string }; +const unavailable = () => ({ root: undefined, close() {} }); +/** Qualification is host configuration, never a model-selected identity. */ +export async function createReferenceOwnerContinuity(path: string, expected?: ReferenceOwnerExpectedRoot): Promise<{ root: Readonly | undefined; close(): void }> { + if (!expected || !/^[a-f0-9-]{36}$/u.test(expected.fsid) || !/^[a-f0-9]{32}$/u.test(expected.brainUuid)) return unavailable(); + let fd: number | undefined; + try { + const canonical = realpathSync(path); + fd = openSync(canonical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + const held = fstatSync(fd); + const unchanged = () => { + const named = lstatSync(canonical), current = fstatSync(fd!); + return realpathSync(path) === canonical && named.isDirectory() && named.dev === held.dev && named.ino === held.ino + && current.dev === held.dev && current.ino === held.ino; + }; + if (!unchanged()) throw Error("Changed policy root"); + // Open precedes the lazy native-library wait; only this descriptor is inspected. + const actual = await kernel.inspectPinnedReferenceRoot(fd); + if (!unchanged() || actual.fsid !== expected.fsid || actual.uuid !== expected.brainUuid || actual.readOnly + || actual.receivedUuid !== "0".repeat(32) || actual.devices !== 1) throw Error("Unqualified native policy root"); + const root = Object.freeze({ path: canonical, device: held.dev, inode: held.ino, + native: Object.freeze({ fsid: actual.fsid, uuid: actual.uuid }) }); + return { root, close() { if (fd !== undefined) { closeSync(fd); fd = undefined; } } }; + } catch { if (fd !== undefined) closeSync(fd); return unavailable(); } +} diff --git a/packages/ui-server/src/brain/reference-owner-resolution.ts b/packages/ui-server/src/brain/reference-owner-resolution.ts index 352790004c..cc8692000f 100644 --- a/packages/ui-server/src/brain/reference-owner-resolution.ts +++ b/packages/ui-server/src/brain/reference-owner-resolution.ts @@ -1,6 +1,5 @@ /** Read-only owner qualification. This records historical evidence, never a source-trust admission. */ -import { createHash, randomUUID } from "node:crypto"; -import { constants, openSync, fstatSync, closeSync, realpathSync } from "node:fs"; +import { createHash } from "node:crypto"; import type { Database } from "bun:sqlite"; import { z } from "zod"; import { openGovernancePolicyAnchored, verifyGovernancePolicyAnchored, parseGovernancePolicy, @@ -15,23 +14,12 @@ const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u).refine(value => Big const identitySchema = z.strictObject({ selector: TrustSelectorSchema, ownerId: providerId, private: z.boolean().nullable() }); const proofSchema = z.strictObject({ operationId: id, principal: z.string().min(1).max(128), brain: digest, authority: z.string().min(1).max(4096), - policyRoot: z.strictObject({ device: z.number().int().nonnegative().safe(), inode: z.number().int().nonnegative().safe(), continuity: z.string().uuid() }), baseHash: digest.nullable(), expectedTrustRevision: revision, + policyRoot: z.strictObject({ fsid: z.string().uuid(), uuid: z.string().regex(/^[a-f0-9]{32}$/u) }), baseHash: digest.nullable(), expectedTrustRevision: revision, publishedTrustRevision: revision, reviewedBytesHash: digest, githubIdentity: identitySchema }); -export interface ReferenceOwnerRoot { path: string; device: number; inode: number; continuity: string } -/** One host lifetime. Holding the directory descriptor prevents inode reuse - * while live; the unguessable epoch withholds old approval after any restart. - * The epoch is host-only and never stored in the agent-writable policy tree. */ -export function createReferenceOwnerContinuity(path: string): { root: Readonly | undefined; close(): void } { - let fd: number | undefined; - try { - const canonical = realpathSync(path); - fd = openSync(canonical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); - const stat = fstatSync(fd); - const root = Object.freeze({ path: canonical, device: stat.dev, inode: stat.ino, continuity: randomUUID() }); - return { root, close() { if (fd !== undefined) { closeSync(fd); fd = undefined; } } }; - } catch { if (fd !== undefined) closeSync(fd); return { root: undefined, close() {} }; } -} +export { createReferenceOwnerContinuity } from "./reference-owner-native-root.js"; +import type { ReferenceOwnerRoot } from "./reference-owner-native-root.js"; +export type { ReferenceOwnerRoot } from "./reference-owner-native-root.js"; type GitHubSelector = Extract; export interface ReferenceOwnerResolution { @@ -82,7 +70,7 @@ export function resolveReferenceOwners(db: Database, root: Readonly BigInt(projection.revision) || identity.ownerId !== current.ownerId || (selector.kind === "github_owner" ? identity.private !== null || identity.ownerId !== selector.ownerId : typeof identity.private !== "boolean")) continue; diff --git a/packages/ui-server/src/brain/reference-owner-root-kernel.ts b/packages/ui-server/src/brain/reference-owner-root-kernel.ts new file mode 100644 index 0000000000..29dad13a2e --- /dev/null +++ b/packages/ui-server/src/brain/reference-owner-root-kernel.ts @@ -0,0 +1,24 @@ +/** Same fixed kernel UAPI as the native manager and retained startup guard. */ +import { fstatSync } from "node:fs"; +async function load() { + if (process.platform !== "linux") throw Error("Native root identity unavailable"); + const { dlopen } = await import("bun:ffi"); + return dlopen("libc.so.6", { ioctl: { args: ["i32", "u64", "ptr"], returns: "i32" } }); +} +let pending: ReturnType | undefined; +export async function inspectPinnedReferenceRoot(fd: number) { + const selected = pending ??= load(); + let libc: Awaited; + try { libc = await selected; } catch (error) { if (pending === selected) pending = undefined; throw error; } + const held = fstatSync(fd, { bigint: true }); + if (!held.isDirectory() || held.ino !== 256n) throw Error("Policy root is not a native subvolume root"); + const subvolume = Buffer.alloc(504), filesystem = Buffer.alloc(1024); + if (libc.symbols.ioctl(fd, 0x81f8943c, subvolume) < 0 || libc.symbols.ioctl(fd, 0x8400941f, filesystem) < 0) + throw Error("Policy root kernel identity unavailable"); + const current = fstatSync(fd, { bigint: true }); + if (current.dev !== held.dev || current.ino !== held.ino) throw Error("Changed policy root descriptor"); + const hex = filesystem.subarray(16, 32).toString("hex"); + return { fsid: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`, + uuid: subvolume.subarray(296, 312).toString("hex"), receivedUuid: subvolume.subarray(328, 344).toString("hex"), + readOnly: !!(subvolume.readBigUInt64LE(288) & 1n), devices: Number(filesystem.readBigUInt64LE(8)) }; +} diff --git a/packages/ui-server/tests/reference-owner-lifecycle.test.ts b/packages/ui-server/tests/reference-owner-lifecycle.test.ts index 53c1f2fa68..75b50cb82f 100644 --- a/packages/ui-server/tests/reference-owner-lifecycle.test.ts +++ b/packages/ui-server/tests/reference-owner-lifecycle.test.ts @@ -1,4 +1,5 @@ -import { expect, test } from "bun:test"; +import * as rootKernel from "../src/brain/reference-owner-root-kernel"; +import { expect, test, spyOn } from "bun:test"; import { readdirSync, readlinkSync } from "node:fs"; import { httpContractApp } from "./helpers/http-contract-app"; @@ -9,12 +10,13 @@ function rootDescriptors(root: string): string[] { } test("normal app shutdown releases the policy-root continuity descriptor on every create/close cycle", async () => { - for (let cycle = 0; cycle < 2; cycle++) { + const native = spyOn(rootKernel, "inspectPinnedReferenceRoot").mockImplementation(async () => ({ fsid: "11111111-1111-4111-8111-111111111790", uuid: "11".repeat(16), receivedUuid: "0".repeat(32), readOnly: false, devices: 1 })); + try { for (let cycle = 0; cycle < 2; cycle++) { const t = await httpContractApp(); try { expect(rootDescriptors(t.brainPath).length, "RUNNING_APP_HOLDS_POLICY_ROOT_CONTINUITY").toBeGreaterThan(0); await t.app.close(); expect(rootDescriptors(t.brainPath), "NORMAL_APP_CLOSE_RELEASES_POLICY_ROOT_CONTINUITY").toEqual([]); } finally { await t.close(); } - } + } } finally { native.mockRestore(); } }); diff --git a/packages/ui-server/tests/reference-owner-native-root.test.ts b/packages/ui-server/tests/reference-owner-native-root.test.ts new file mode 100644 index 0000000000..8a08f73104 --- /dev/null +++ b/packages/ui-server/tests/reference-owner-native-root.test.ts @@ -0,0 +1,40 @@ +import { afterEach, expect, spyOn, test } from "bun:test"; +import { fstatSync, mkdirSync, mkdtempSync, readlinkSync, renameSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as kernel from "../src/brain/reference-owner-root-kernel"; +import { createReferenceOwnerContinuity } from "../src/brain/reference-owner-native-root"; +const expected = { fsid: "11111111-1111-4111-8111-111111111790", brainUuid: "11".repeat(16) }; +const identity = { fsid: expected.fsid, uuid: expected.brainUuid, readOnly: false, receivedUuid: "0".repeat(32), devices: 1 }; +const cleanup: (() => void)[] = []; +afterEach(() => { for (const close of cleanup.splice(0).reverse()) close(); }); +function root() { const path = mkdtempSync(join(tmpdir(), "odysseus-owner-native-")); cleanup.push(() => rmSync(path, { recursive: true, force: true })); return path; } + +for (const field of ["fsid", "uuid", "readOnly", "receivedUuid", "devices"] as const) test(`actual pinned-root identity refuses mismatched ${field}`, async () => { + const path = root(); let fd = -1; + const wrong = { ...identity, [field]: field === "readOnly" ? true : field === "devices" ? 2 : "22".repeat(16) }; + const spy = spyOn(kernel, "inspectPinnedReferenceRoot").mockImplementation(async value => { fd = value; return wrong; }); cleanup.push(() => spy.mockRestore()); + const context = await createReferenceOwnerContinuity(path, expected); cleanup.push(() => context.close()); + expect(context.root, "ONLY_QUALIFIED_NATIVE_ROOT_CAN_BIND_APPROVAL").toBeUndefined(); + expect(() => fstatSync(fd), "REFUSED_NATIVE_ROOT_DESCRIPTOR_IS_CLOSED").toThrow(); +}); + +test("startup attests the already held descriptor and refuses replacement during the inspection wait", async () => { + const path = root(), previous = path + "-previous"; cleanup.push(() => rmSync(previous, { recursive: true, force: true })); + let fd = -1; + const spy = spyOn(kernel, "inspectPinnedReferenceRoot").mockImplementation(async value => { + fd = value; const held = fstatSync(value); renameSync(path, previous); mkdirSync(path); + expect(readlinkSync(`/proc/self/fd/${value}`), "NATIVE_ATTESTATION_INSPECTS_ORIGINAL_PINNED_ROOT").toBe(previous); + expect(fstatSync(value).ino).toBe(held.ino); + return identity; + }); cleanup.push(() => spy.mockRestore()); + const context = await createReferenceOwnerContinuity(path, expected); cleanup.push(() => context.close()); + expect(context.root, "STARTUP_REPLACEMENT_NEVER_ADOPTS_QUALIFIED_ROOT").toBeUndefined(); + expect(() => fstatSync(fd)).toThrow(); +}); + +test("unsupported real filesystem withholds qualification without a native stand-in", async () => { + // This fixture is an ordinary temporary directory, never a Btrfs subvolume. + const context = await createReferenceOwnerContinuity(root(), expected); cleanup.push(() => context.close()); + expect(context.root, "ORDINARY_DIRECTORY_IS_NOT_NATIVE_QUALIFICATION").toBeUndefined(); +}); diff --git a/packages/ui-server/tests/reference-owner-resolution.test.ts b/packages/ui-server/tests/reference-owner-resolution.test.ts index 6aef0cebf1..7bc0df8c58 100644 --- a/packages/ui-server/tests/reference-owner-resolution.test.ts +++ b/packages/ui-server/tests/reference-owner-resolution.test.ts @@ -1,4 +1,5 @@ -import { afterEach, expect, test } from "bun:test"; +import * as rootKernel from "../src/brain/reference-owner-root-kernel"; +import { afterEach, expect, test, spyOn } from "bun:test"; import { createHash } from "node:crypto"; import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, renameSync } from "node:fs"; import { connect } from "node:net"; @@ -26,7 +27,8 @@ import { fixtureTls } from "./fixtures/fixture-tls"; const cleanup: (() => void | Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); -const captureReferenceOwnerRoot = (path: string) => { const c = createReferenceOwnerContinuity(path); cleanup.push(() => c.close()); return c.root; }; +const nativeExpected = { fsid: "11111111-1111-4111-8111-111111111790", brainUuid: "11".repeat(16) }; +const captureReferenceOwnerRoot = async (path: string, expected = nativeExpected) => { const c = await createReferenceOwnerContinuity(path, expected); cleanup.push(() => c.close()); return c.root; }; const brain = "ithaca-brain", commit = "a".repeat(40), tree = "b".repeat(40); const repositoryRule: TrustRule = { id: "ithaca", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, selector: { kind: "github_repository", host: "github.com", owner: "odysseus", repository: "ithaca", repositoryId: "101" } }; @@ -34,7 +36,10 @@ const ownerRule: TrustRule = { ...repositoryRule, id: "odysseus", selector: { ki async function fixture(worker = false) { const root = mkdtempSync(join(tmpdir(), "odysseus-owner-resolution-")); cleanup.push(() => rmSync(root, { recursive: true, force: true })); - const continuity = createReferenceOwnerContinuity(root); cleanup.push(() => continuity.close()); + const nativeState = { uuid: nativeExpected.brainUuid }; + const nativeSpy = spyOn(rootKernel, "inspectPinnedReferenceRoot").mockImplementation(async () => ({ fsid: nativeExpected.fsid, uuid: nativeState.uuid, readOnly: false, receivedUuid: "0".repeat(32), devices: 1 })); + cleanup.push(() => nativeSpy.mockRestore()); + const continuity = await createReferenceOwnerContinuity(root, nativeExpected); cleanup.push(() => continuity.close()); const policyPath = join(root, "context/policies/governance.md"); mkdirSync(join(root, "context/policies"), { recursive: true }); writeFileSync(policyPath, "---\nschema_version: 1\n---\nThe voyage policy.\n"); const db = createUiDb(join(root, "ui.db")), writer = worker ? openSqliteWriter(db) : undefined; @@ -93,7 +98,7 @@ async function fixture(worker = false) { const row = db.query("SELECT evidence,acquisition FROM reference_reads WHERE tool_call_id=?").get(toolCallId) as { evidence: string; acquisition: string }; return { result, row, evidence: JSON.parse(row.evidence) as { trusted: false; ownerResolution: ReferenceOwnerResolution; identityObservation: ReferenceIdentityObservation } }; }; - return { root, ownerRoot: continuity.root, continuity, db, writer, owner, other, state, settings, settingsOptions, change, save, approve, read, reads, requests, policyPath, sources }; + return { root, nativeState, ownerRoot: continuity.root, continuity, db, writer, owner, other, state, settings, settingsOptions, change, save, approve, read, reads, requests, policyPath, sources }; } for (const worker of [false, true]) test(`protected publication binds an actual fresh managed read; writer=${worker}`, async () => { @@ -141,8 +146,8 @@ for (const failure of ["missing", "malformed", "wrong-brain", "changed-identity" if (failure === "missing") f.db.exec("DELETE FROM trust_settings_github_boundaries"); else { if (failure === "legacy-root") delete proof.policyRoot; - if (failure === "wrong-device") proof.policyRoot.device += 1; - if (failure === "wrong-inode") proof.policyRoot.inode += 1; + if (failure === "wrong-device") proof.policyRoot.fsid = "22222222-2222-4222-8222-222222222222"; + if (failure === "wrong-inode") proof.policyRoot.uuid = "22".repeat(16); if (failure === "wrong-brain") proof.brain = "a".repeat(64); if (failure === "changed-identity") proof.githubIdentity.ownerId = "202"; if (failure === "future-revision") { proof.expectedTrustRevision = "99"; proof.publishedTrustRevision = "100"; } @@ -274,9 +279,10 @@ test("restart cannot apply retained approval to a replacement policy root with i mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); // Retain the authoritative UI database, but construct both readers anew as // startup does. Equal path/policy bytes must not resurrect old approval. + f.nativeState.uuid = "22".repeat(16); const reopened = createUiDb(join(backup, "ui.db")); try { - expect(resolveReferenceOwners(reopened, captureReferenceOwnerRoot(f.root), observed.evidence.identityObservation).bindings, + expect(resolveReferenceOwners(reopened, await captureReferenceOwnerRoot(f.root, { ...nativeExpected, brainUuid: "22".repeat(16) }), observed.evidence.identityObservation).bindings, "RESTART_REJECTS_APPROVAL_FROM_REPLACED_PUBLISHED_ROOT").toEqual([]); } finally { reopened.close(); } } finally { rmSync(f.root, { recursive: true, force: true }); renameSync(backup, f.root); } @@ -293,33 +299,29 @@ test("deleted root replacement cannot inherit approval even when the filesystem mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); const reopened = createUiDb(join(retained, "ui.db")); try { - const replacement = captureReferenceOwnerRoot(f.root)!; - const row = reopened.query("SELECT proof FROM trust_settings_github_boundaries").get() as { proof: string }; - const proof = JSON.parse(row.proof); - // Deterministically model the kernel reusing the deleted directory's - // device/inode pair; deletion above is real, not a rename keeping it alive. - proof.policyRoot.device = replacement.device; proof.policyRoot.inode = replacement.inode; - reopened.query("UPDATE trust_settings_github_boundaries SET proof=?").run(JSON.stringify(proof)); + f.nativeState.uuid = "22".repeat(16); + const replacement = await captureReferenceOwnerRoot(f.root, { ...nativeExpected, brainUuid: f.nativeState.uuid }); + // The previous weak path/device/inode proof is gone. Native root identity + // remains different even when a Btrfs replacement reuses root inode 256. expect(resolveReferenceOwners(reopened, replacement, observed.evidence.identityObservation).bindings, "DELETED_ROOT_REUSE_REQUIRES_NEW_REVIEWED_APPROVAL").toEqual([]); } finally { reopened.close(); } } finally { rmSync(retained, { recursive: true, force: true }); } }); -test("a new host lifetime requires reviewed republication even with an unchanged policy root", async () => { +test("ordinary host restart retains approval for the same qualified native brain", async () => { const f = await fixture(); await f.approve(); const observed = await f.read(); f.continuity.close(); - const next = createReferenceOwnerContinuity(f.root); + const next = await createReferenceOwnerContinuity(f.root, nativeExpected); try { expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation).bindings, - "NEW_HOST_LIFETIME_REQUIRES_REAPPROVAL").toEqual([]); - const settings = createTrustSettings({ ...f.settingsOptions, ownerRoot: next.root }); - const before = await settings.list(f.owner.id); - const draft = await settings.prepare(f.owner.id, { version: 1, expectedTrustRevision: before.revision, - expectedPolicyHash: before.policyHash, change: { action: "edit", rule: { ...repositoryRule, label: "The reviewed home harbor" } } }); - await settings.commit(f.owner.id, { version: 1, requestId: draft.receipt.requestId, - reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); - expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation).bindings, - "NEW_PUBLICATION_RESTORES_CURRENT_HOST_QUALIFICATION").toHaveLength(1); + "ORDINARY_NATIVE_RESTART_PRESERVES_APPROVED_OWNER").toHaveLength(1); } finally { next.close(); } }); + +test("an unqualified host withholds retained owner approval", async () => { + const f = await fixture(); await f.approve(); const observed = await f.read(); + const next = await createReferenceOwnerContinuity(f.root); + try { expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation).bindings, + "UNQUALIFIED_NATIVE_HOST_WITHHOLDS_OWNER_APPROVAL").toEqual([]); } finally { next.close(); } +}); diff --git a/scripts/native-proof/managed-reference-source.ts b/scripts/native-proof/managed-reference-source.ts index 2f18ef479b..b90658c6bf 100644 --- a/scripts/native-proof/managed-reference-source.ts +++ b/scripts/native-proof/managed-reference-source.ts @@ -1,3 +1,5 @@ +import { proveReferenceOwnerRoot } from "./reference-owner-root.js"; +import { resolveReferenceOwners } from "../../packages/ui-server/src/brain/reference-owner-resolution.js"; import { createReferenceOwnerContinuity } from "../../packages/ui-server/src/brain/reference-owner-resolution.js"; /** Actual managed Git/TLS acquisition, maintenance workers and native Btrfs publication. No read-trust exemption. */ import { expect } from "bun:test"; @@ -44,7 +46,7 @@ export async function proveManagedReferenceSource(client: ReturnType) => void) { + const path = join(dirname(brain), "odysseus-owner-recreated"), policy = "---\nschema_version: 1\n---\nThe voyage policy.\n"; + const btrfs = (...args: string[]) => { const p = Bun.spawnSync(["/usr/bin/btrfs", ...args], { stdout: "pipe", stderr: "pipe" }); + expect(p.exitCode, `OWNER_NATIVE_BTRFS: ${p.stderr}`).toBe(0); }; + let exists = false; + const inspect = async () => { const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + try { return { identity: await inspectPinnedReferenceRoot(fd), inode: fstatSync(fd).ino }; } finally { closeSync(fd); } }; + try { + btrfs("subvolume", "create", path); exists = true; writeFileSync(join(path, "governance.md"), policy); + const original = await inspect(), expected = { fsid: original.identity.fsid, brainUuid: original.identity.uuid }; + const first = await createReferenceOwnerContinuity(path, expected); + try { expect(first.root, "NATIVE_ORIGINAL_ROOT_QUALIFIES").toBeDefined(); } finally { first.close(); } + const restart = await createReferenceOwnerContinuity(path, expected); + try { expect(restart.root?.native, "NATIVE_ORDINARY_RESTART_PRESERVES_IDENTITY").toEqual(first.root!.native); } finally { restart.close(); } + rmSync(join(path, "governance.md")); btrfs("subvolume", "delete", path); exists = false; + btrfs("subvolume", "create", path); exists = true; writeFileSync(join(path, "governance.md"), policy); + const replacement = await inspect(); + expect(replacement.inode, "NATIVE_REPLACEMENT_REUSES_SUBVOLUME_ROOT_INODE").toBe(original.inode); + expect(replacement.identity.fsid).toBe(original.identity.fsid); + expect(replacement.identity.uuid).not.toBe(original.identity.uuid); + expect(readFileSync(join(path, "governance.md"), "utf8")).toBe(policy); + const refused = await createReferenceOwnerContinuity(path, expected); + try { expect(refused.root, "NATIVE_RECREATED_ROOT_CANNOT_INHERIT_APPROVAL").toBeUndefined(); } finally { refused.close(); } + note("managed-source-owner-native-root-recreation", { original: original.identity, replacement: replacement.identity, + originalInode: original.inode, replacementInode: replacement.inode, samePolicyBytes: true, restartQualified: true, replacementRefused: true }); + } finally { if (exists) { rmSync(join(path, "governance.md"), { force: true }); btrfs("subvolume", "delete", path); } } +} From 388c965b5d259deb59f1bdba929db42ba9a90aa2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:06:44 +0000 Subject: [PATCH 6/8] fix(ui-server): wire native owner identity into host publication --- packages/ui-server/src/app.ts | 2 +- packages/ui-server/src/brain/trust-settings.ts | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 11f79c0a06..ae0ae82dae 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -426,7 +426,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise { if (ephemeralJournal) rmSync(journalRoot, { recursive: true, force: true }); throw error; }); const bootCleanup: (() => void | Promise)[] = []; - const ownerContinuity = createReferenceOwnerContinuity(config.brainPath); + const ownerContinuity = await createReferenceOwnerContinuity(config.brainPath, nativeReady); bootCleanup.push(() => ownerContinuity.close()); try { const nativeRecovery = await nativeLeases.recoverDeadOwners(); diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index 8c4253146a..6fbfb879c7 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -263,9 +263,8 @@ export function createTrustSettings(options: { receipt.stage = "file_published"; receipt.publication = "proved"; receipt.publishedTrustRevision = String(BigInt(p.revision) + 1n); await save("file_published", JSON.stringify({ operationId: receipt.operationId, principal, brain, authority: r.authority, - policyRoot: { device: target.directories[0]!.dev, inode: target.directories[0]!.ino, - ...(options.ownerRoot?.path === root && options.ownerRoot.device === target.directories[0]!.dev && options.ownerRoot.inode === target.directories[0]!.ino - ? { continuity: options.ownerRoot.continuity } : {}) }, + policyRoot: options.ownerRoot?.path === root && options.ownerRoot.device === target.directories[0]!.dev && options.ownerRoot.inode === target.directories[0]!.ino + ? options.ownerRoot.native : null, baseHash: p.policyHash, expectedTrustRevision: p.revision, publishedTrustRevision: receipt.publishedTrustRevision, reviewedBytesHash: payload.proposedHash, ...(payload.githubIdentity ? { githubIdentity: payload.githubIdentity } : {}) }), payload.githubIdentity && payload.rule ? { brain, ruleId: payload.rule.id, selector: JSON.stringify(payload.rule.selector), identity: JSON.stringify(payload.githubIdentity) } : undefined); proved = true; From f3e4dfc69524608a6f42abb41b6af1ae8d65257d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:07:09 +0000 Subject: [PATCH 7/8] chore(ui-server): keep native root helper types private --- packages/ui-server/src/brain/reference-owner-native-root.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/brain/reference-owner-native-root.ts b/packages/ui-server/src/brain/reference-owner-native-root.ts index 3db812e1aa..489cf4c760 100644 --- a/packages/ui-server/src/brain/reference-owner-native-root.ts +++ b/packages/ui-server/src/brain/reference-owner-native-root.ts @@ -1,9 +1,9 @@ /** Existing Linux/Btrfs native identity, read from the actual held descriptor. */ import { constants, openSync, closeSync, fstatSync, lstatSync, realpathSync } from "node:fs"; import * as kernel from "./reference-owner-root-kernel.js"; -export interface ReferenceOwnerNativeIdentity { fsid: string; uuid: string } +interface ReferenceOwnerNativeIdentity { fsid: string; uuid: string } export interface ReferenceOwnerRoot { path: string; device: number; inode: number; native: ReferenceOwnerNativeIdentity } -export type ReferenceOwnerExpectedRoot = { fsid: string; brainUuid: string }; +type ReferenceOwnerExpectedRoot = { fsid: string; brainUuid: string }; const unavailable = () => ({ root: undefined, close() {} }); /** Qualification is host configuration, never a model-selected identity. */ export async function createReferenceOwnerContinuity(path: string, expected?: ReferenceOwnerExpectedRoot): Promise<{ root: Readonly | undefined; close(): void }> { From f650b157440494998a3d0357d2258ec4f8aae871 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 10:19:19 +0000 Subject: [PATCH 8/8] fix(ui-server): resolve owner evidence through live Settings policy --- .../decisions/reference-source-acquisition.md | 17 ++++-- packages/ui-server/src/app.ts | 2 +- .../src/brain/reference-owner-resolution.ts | 40 +++++++------ .../src/brain/reference-read-writes.ts | 5 +- .../ui-server/src/brain/reference-read.ts | 8 ++- .../src/brain/trust-policy-generation.ts | 11 ++++ .../ui-server/src/brain/trust-settings.ts | 18 +++--- .../tests/reference-owner-resolution.test.ts | 57 +++++++++++++++---- .../native-proof/managed-reference-source.ts | 4 +- 9 files changed, 114 insertions(+), 48 deletions(-) create mode 100644 packages/ui-server/src/brain/trust-policy-generation.ts diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 5a0a111f9a..93eba5f80c 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -440,8 +440,9 @@ Approved-owner rule evaluation remains independently required. ## Approved-owner resolution for immutable reads The host read service resolves each actual transport observation against the -protected Markdown policy, its matching durable trust projection and Settings' -operation-bound approved-owner evidence. The policy root's directory identity is +Settings' existing live-policy interpretation, its matching durable trust +projection and operation-bound approved-owner evidence. No independent policy +parser or live cache selects owner rules. The policy root's directory identity is captured with a no-follow directory descriptor and qualified against the native manager's filesystem ID and fixed live-brain subvolume UUID. The kernel Btrfs identity is read from that already held descriptor, including across native @@ -452,9 +453,10 @@ identity. Publication records filesystem ID and subvolume UUID from this host qualification. Ordinary restart requalifies the same native brain and preserves approval; recreation at the same path, inode and policy bytes has a different subvolume UUID and cannot inherit it. An unqualified host or legacy proof without -that native binding withholds qualification. Links, replaced roots, invalid or incoherent -policy/projection data and missing/malformed publication proof produce unavailable -qualification; they do not prevent an otherwise authorized untrusted read. +that native binding withholds qualification. Replaced roots, verification races, incoherent projection data +and missing/malformed publication proof produce unavailable qualification. Stable +invalid/unreadable policy retains Settings' last-valid rules and records its +honest error; they do not prevent an otherwise authorized untrusted read. Exact repository approval requires the freshly observed stable repository ID, current canonical owner and the independently approved owner ID. A same-owner @@ -468,7 +470,10 @@ or approving-login deletion does not erase the durable owner evidence. It is interpreted only against a freshly qualified native brain after restart. Resolution runs provisionally before recording and again inside the acquired -SQLite writer transaction. The recorded operation ID, policy hash/revision, +SQLite writer transaction against the host snapshot and current metadata +generation and durable projection. A generation change during the queue wait +withholds only this qualification; a later read uses a new live Settings +snapshot. The recorded operation ID, policy hash/revision, approved owner, selector and publication operation/proof hash are historical qualification evidence. They are separate from the original acquisition and the prepared/observed/unknown delivery state. Removal affects later resolutions and diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 18e75b1d06..0291dd4e96 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -566,7 +566,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise trustSettings.ownerPolicy(), brain: nativeReady.brainUuid, sources: referenceSources, pool: nativeManager, transport: referenceTransport }), log: brainLog }) : undefined; if (referenceWorktrees) { bootCleanup.push(() => referenceWorktrees.close()); diff --git a/packages/ui-server/src/brain/reference-owner-resolution.ts b/packages/ui-server/src/brain/reference-owner-resolution.ts index cc8692000f..6b032b96f0 100644 --- a/packages/ui-server/src/brain/reference-owner-resolution.ts +++ b/packages/ui-server/src/brain/reference-owner-resolution.ts @@ -1,9 +1,10 @@ +import { lstatSync } from "node:fs"; +import { trustPolicyGeneration } from "./trust-policy-generation.js"; /** Read-only owner qualification. This records historical evidence, never a source-trust admission. */ import { createHash } from "node:crypto"; import type { Database } from "bun:sqlite"; import { z } from "zod"; -import { openGovernancePolicyAnchored, verifyGovernancePolicyAnchored, parseGovernancePolicy, - TrustedSourcesSchema, TrustSelectorSchema, type TrustSelector, type AnchoredGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import { TrustedSourcesSchema, TrustSelectorSchema, type TrustSelector } from "@schlessera/brain-common/internal/governance-policy"; import type { ReferenceIdentityObservation } from "./reference-acquisition.js"; const hash = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex"); @@ -21,6 +22,13 @@ export { createReferenceOwnerContinuity } from "./reference-owner-native-root.js import type { ReferenceOwnerRoot } from "./reference-owner-native-root.js"; export type { ReferenceOwnerRoot } from "./reference-owner-native-root.js"; +export interface ReferenceOwnerPolicy { + rules: import("@schlessera/brain-common/internal/governance-policy").TrustRule[]; + revision: string; policyHash: string | null; error: string | null; generation: string; +} +const policySchema = z.strictObject({ rules: TrustedSourcesSchema, revision, policyHash: digest.nullable(), + error: z.string().nullable(), generation: z.string().min(1).max(4096) }); + type GitHubSelector = Extract; export interface ReferenceOwnerResolution { version: 1; @@ -28,6 +36,7 @@ export interface ReferenceOwnerResolution { state: "available" | "unavailable"; policyHash: string | null; trustRevision: string | null; + policyError: string | null; /** At most one repository and one owner rule can match a validated policy. */ bindings: { ruleId: string; selector: GitHubSelector; approvedOwnerId: string; sameOwnerRenameRevalidated: boolean; publicationOperationId: string; publicationProofHash: string }[]; @@ -39,24 +48,22 @@ export interface ReferenceOwnerResolution { * policy and its exact durable projection must agree; equal bytes cannot create * approval. The publisher's retained boundary survives operation pruning. */ -export function resolveReferenceOwners(db: Database, root: Readonly | undefined, observation: Readonly): ReferenceOwnerResolution { +export function resolveReferenceOwners(db: Database, root: Readonly | undefined, observation: Readonly, policy?: ReferenceOwnerPolicy): ReferenceOwnerResolution { const unavailable = (): ReferenceOwnerResolution => ({ version: 1, operationId: observation.operationId, - state: "unavailable", policyHash: null, trustRevision: null, bindings: [] }); + state: "unavailable", policyHash: null, trustRevision: null, policyError: null, bindings: [] }); if (!root) return unavailable(); - let target: AnchoredGovernancePolicy | undefined; try { - const brain = hash(root.path); - target = openGovernancePolicyAnchored(root.path); - if (target.directories[0]!.dev !== root.device || target.directories[0]!.ino !== root.inode) return unavailable(); - if (target.bytes === null) return unavailable(); - const policyHash = hash(target.bytes), parsed = parseGovernancePolicy(target.bytes); - if (!parsed.ok) return unavailable(); - const rules = TrustedSourcesSchema.parse(parsed.effective.taint.trusted_sources); + const brain = hash(root.path), selected = policySchema.parse(policy); + const named = lstatSync(root.path); + if (!named.isDirectory() || named.dev !== root.device || named.ino !== root.inode) return unavailable(); + if (trustPolicyGeneration(root.path) !== selected.generation) return unavailable(); + const { policyHash, rules } = selected; const projection = db.query("SELECT revision,rules,policy_hash,error FROM trust_settings_projection WHERE brain_id=?").get(brain) as { revision: string; rules: string; policy_hash: string | null; error: string | null; } | null; - if (!projection || projection.error !== null || projection.policy_hash !== policyHash || !revision.safeParse(projection.revision).success - || JSON.stringify(TrustedSourcesSchema.parse(JSON.parse(projection.rules))) !== JSON.stringify(rules)) return unavailable(); + if (!projection || projection.revision !== selected.revision || !revision.safeParse(projection.revision).success + || JSON.stringify(TrustedSourcesSchema.parse(JSON.parse(projection.rules))) !== JSON.stringify(rules) + || selected.error !== null && projection.policy_hash !== policyHash) return unavailable(); const bindings: ReferenceOwnerResolution["bindings"] = []; for (const rule of rules) { const selector = rule.selector; @@ -80,9 +87,8 @@ export function resolveReferenceOwners(db: Database, root: Readonly= 2000) throw new Error("Reference read record capacity exceeded"); db.query(`INSERT INTO reference_reads (id, turn_id, tool_call_id, principal_id, acquisition, evidence, response_digest, created_at) diff --git a/packages/ui-server/src/brain/reference-read.ts b/packages/ui-server/src/brain/reference-read.ts index 613a59ab70..d9fbecb3a6 100644 --- a/packages/ui-server/src/brain/reference-read.ts +++ b/packages/ui-server/src/brain/reference-read.ts @@ -1,5 +1,5 @@ /** Immutable reference content returned through one authenticated turn and actual backend call. */ -import { type ReferenceOwnerRoot, resolveReferenceOwners } from "./reference-owner-resolution.js"; +import { type ReferenceOwnerPolicy, type ReferenceOwnerRoot, resolveReferenceOwners } from "./reference-owner-resolution.js"; import { createHash, randomUUID } from "node:crypto"; import type { Database } from "bun:sqlite"; import { REFERENCE_READ_INPUT_SCHEMA, type ReferenceReadInput, type ReferenceToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; @@ -33,6 +33,7 @@ function finalReadText(output: string, segments?: readonly string[]): string | n export function createReferenceReads(options: { /** Served protected policy root; absent hosts report owner qualification unavailable. */ ownerRoot?: Readonly; + ownerPolicy?(): ReferenceOwnerPolicy | undefined; db: Database; brain: string; sources: Pick; pool: Pick; transport: Pick; }) { @@ -112,12 +113,13 @@ export function createReferenceReads(options: { const result: ReferenceToolResult = { ok: true, read: { repository: location.canonical, revision: request.revision, commit: lease.commit, path: request.path, offset: blob.offset, length: blob.length, totalBytes: blob.totalBytes, encoding: utf8 ? "utf8" : "base64", content: utf8 ? text : bytes.toString("base64") }, guidance }; - await write("referenceReadPrepare", { id: randomUUID(), ownerRoot, operationId, turnId, toolCallId, principalId, acquisition: acquisitionSnapshot, + const ownerPolicy = options.ownerPolicy?.(); + await write("referenceReadPrepare", { id: randomUUID(), ownerRoot, ownerPolicy, operationId, turnId, toolCallId, principalId, acquisition: acquisitionSnapshot, evidence: JSON.stringify({ version: 1, path: request.path, blob: blob.blob, mode: blob.mode, tree: blob.tree, offset: blob.offset, length: blob.length, totalBytes: blob.totalBytes, digest: blob.digest, grantId: lease.readGrantId, detectorVersion: 1, trusted: false, trustRevision: "0", identityObservation, // Provisional only: the writer resolves again after its queue wait. - ownerResolution: resolveReferenceOwners(db, ownerRoot, identityObservation!) }), responseDigest: digest(JSON.stringify(result)), at: Date.now() }, lease.rootId, lease.readGrantId, authority); + ownerResolution: resolveReferenceOwners(db, ownerRoot, identityObservation!, ownerPolicy) }), responseDigest: digest(JSON.stringify(result)), at: Date.now() }, lease.rootId, lease.readGrantId, authority); assertAuthority(); return result; } catch (error) { diff --git a/packages/ui-server/src/brain/trust-policy-generation.ts b/packages/ui-server/src/brain/trust-policy-generation.ts new file mode 100644 index 0000000000..df449d3107 --- /dev/null +++ b/packages/ui-server/src/brain/trust-policy-generation.ts @@ -0,0 +1,11 @@ +/** Metadata fence shared with Settings' single live-policy interpretation. No cache. */ +import { lstatSync } from "node:fs"; +import { join } from "node:path"; +export function trustPolicyGeneration(root: string): string { + return [root, join(root, "context"), join(root, "context/policies"), join(root, "context/policies/governance.md")].map((path, index) => { + try { + const info = lstatSync(path, { bigint: true }); + return [info.dev, info.ino, info.mode, info.nlink, ...(index === 3 ? [info.size, info.mtimeNs, info.ctimeNs] : [])].map(String).join(":"); + } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; } + }).join("|"); +} diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index 7d07c27986..bdaac0ac0b 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -1,4 +1,5 @@ -import type { ReferenceOwnerRoot } from "./reference-owner-resolution.js"; +import { trustPolicyGeneration } from "./trust-policy-generation.js"; +import type { ReferenceOwnerPolicy, ReferenceOwnerRoot } from "./reference-owner-resolution.js"; /** Human Settings operations. Markdown is authoritative; these rows are bounded * request/audit receipts, never a second policy source or an agent turn. */ import { createHash, randomBytes } from "node:crypto"; @@ -116,12 +117,7 @@ export function createTrustSettings(options: { let liveCache: { observation: Observation; base: LiveProjection; value: LiveProjection } | undefined; // Metadata is the per-chunk fence. Include every ancestry identity and the // file's nanosecond change identity, without reading policy bytes or SQLite. - const generation = () => [root, join(root, "context"), join(root, "context/policies"), join(root, "context/policies/governance.md")].map((path, index) => { - try { - const info = lstatSync(path, { bigint: true }); - return [info.dev, info.ino, info.mode, info.nlink, ...(index === 3 ? [info.size, info.mtimeNs, info.ctimeNs] : [])].map(String).join(":"); - } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; } - }).join("|"); + const generation = () => trustPolicyGeneration(root); /** One state machine for live reads and durable refresh. Changed verification * always fences; stable invalid/unreadable bytes retain last-valid evidence. */ const observePolicy = (): Observation => { @@ -203,6 +199,14 @@ export function createTrustSettings(options: { }); }; return { + /** Snapshot the existing live interpretation; writers fence its generation after waits. */ + ownerPolicy(): ReferenceOwnerPolicy | undefined { + try { + const before = generation(), p = live.read(); + if (generation() !== before) return; + return { rules: p.rules, revision: p.revision, policyHash: p.policyHash, error: p.error, generation: before }; + } catch { return; } + }, live, /** The other protected publisher already owns the shared brain lock. */ refreshLocked: refresh, diff --git a/packages/ui-server/tests/reference-owner-resolution.test.ts b/packages/ui-server/tests/reference-owner-resolution.test.ts index 7bc0df8c58..56b1d70e88 100644 --- a/packages/ui-server/tests/reference-owner-resolution.test.ts +++ b/packages/ui-server/tests/reference-owner-resolution.test.ts @@ -88,7 +88,7 @@ async function fixture(worker = false) { const pool = referencePoolDouble(join(root, "pool")), sources = createReferenceSources({ db, brain, pool, transport, github: access, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" } }); cleanup.push(() => sources.close()); const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 16 * 1048576, observe() {} }); cleanup.push(() => egress.stop()); - const reads = createReferenceReads({ db, brain, ownerRoot: continuity.root, pool, sources, transport }); + const reads = createReferenceReads({ db, brain, ownerRoot: continuity.root, ownerPolicy: () => settings.ownerPolicy(), pool, sources, transport }); let call = 0; const read = async (principalId = other.id) => { const toolCallId = `read-${++call}`; @@ -192,7 +192,7 @@ test("independent owner and repository publications retain both bounded bindings .toBe(first.evidence.ownerResolution.bindings[0]!.publicationProofHash); }); -for (const change of ["invalid", "symlink", "selector", "projection"]) test(`a ${change} policy boundary cannot qualify reads`, async () => { +for (const change of ["invalid", "symlink", "selector", "projection"]) test(`a ${change} policy boundary follows the Settings live interpretation`, async () => { const f = await fixture(); await f.approve(); const previous = readFileSync(f.policyPath, "utf8"); if (change === "invalid") writeFileSync(f.policyPath, "---\nschema_version: 9000\n---\n"); @@ -202,17 +202,19 @@ for (const change of ["invalid", "symlink", "selector", "projection"]) test(`a $ renameSync(f.policyPath, f.policyPath + ".saved"); const { symlinkSync } = await import("node:fs"); symlinkSync(f.policyPath + ".saved", f.policyPath); } - expect((await f.read()).evidence.ownerResolution.state, "POLICY_BOUNDARY_UNKNOWN_NEVER_QUALIFIES").toBe("unavailable"); + const resolution = (await f.read()).evidence.ownerResolution; + expect(resolution.state, "POLICY_BOUNDARY_USES_SETTINGS_LIVE_INTERPRETATION").toBe(change === "invalid" || change === "symlink" ? "available" : "unavailable"); + if (change === "invalid" || change === "symlink") expect(resolution.policyError).toBe("policy_unavailable"); }); test("replacing the configured policy root cannot borrow the previous directory's approval", async () => { const f = await fixture(); await f.approve(); const r = await f.read(), bound = f.ownerRoot; - expect(resolveReferenceOwners(f.db, bound, r.evidence.identityObservation).bindings, "LIVE_ORIGINAL_ROOT_HAS_APPROVED_BINDING").toHaveLength(1); + expect(resolveReferenceOwners(f.db, bound, r.evidence.identityObservation, f.settings.ownerPolicy()).bindings, "LIVE_ORIGINAL_ROOT_HAS_APPROVED_BINDING").toHaveLength(1); const policy = readFileSync(f.policyPath), backup = f.root + "-old"; renameSync(f.root, backup); try { mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(f.policyPath, policy); - expect(resolveReferenceOwners(f.db, bound, r.evidence.identityObservation).bindings, "OWNER_APPROVAL_IS_BOUND_TO_HOST_BRAIN_ROOT").toEqual([]); + expect(resolveReferenceOwners(f.db, bound, r.evidence.identityObservation, f.settings.ownerPolicy()).bindings, "OWNER_APPROVAL_IS_BOUND_TO_HOST_BRAIN_ROOT").toEqual([]); } finally { rmSync(f.root, { recursive: true, force: true }); renameSync(backup, f.root); } }); @@ -248,7 +250,7 @@ test("a reopened database reconstructs qualification from retained boundary evid f.db.exec("DELETE FROM trust_settings_operations"); const reopened = createUiDb(join(f.root, "ui.db")); try { - const resolved = resolveReferenceOwners(reopened, f.ownerRoot, observed.evidence.identityObservation); + const resolved = resolveReferenceOwners(reopened, f.ownerRoot, observed.evidence.identityObservation, f.settings.ownerPolicy()); expect(resolved, "OWNER_RESOLUTION_SURVIVES_DATABASE_REOPEN").toEqual(observed.evidence.ownerResolution); const history = reopened.query("SELECT evidence FROM reference_reads").get() as { evidence: string }; expect(JSON.parse(history.evidence).ownerResolution).toEqual(resolved); @@ -282,7 +284,7 @@ test("restart cannot apply retained approval to a replacement policy root with i f.nativeState.uuid = "22".repeat(16); const reopened = createUiDb(join(backup, "ui.db")); try { - expect(resolveReferenceOwners(reopened, await captureReferenceOwnerRoot(f.root, { ...nativeExpected, brainUuid: "22".repeat(16) }), observed.evidence.identityObservation).bindings, + expect(resolveReferenceOwners(reopened, await captureReferenceOwnerRoot(f.root, { ...nativeExpected, brainUuid: "22".repeat(16) }), observed.evidence.identityObservation, f.settings.ownerPolicy()).bindings, "RESTART_REJECTS_APPROVAL_FROM_REPLACED_PUBLISHED_ROOT").toEqual([]); } finally { reopened.close(); } } finally { rmSync(f.root, { recursive: true, force: true }); renameSync(backup, f.root); } @@ -303,7 +305,7 @@ test("deleted root replacement cannot inherit approval even when the filesystem const replacement = await captureReferenceOwnerRoot(f.root, { ...nativeExpected, brainUuid: f.nativeState.uuid }); // The previous weak path/device/inode proof is gone. Native root identity // remains different even when a Btrfs replacement reuses root inode 256. - expect(resolveReferenceOwners(reopened, replacement, observed.evidence.identityObservation).bindings, + expect(resolveReferenceOwners(reopened, replacement, observed.evidence.identityObservation, f.settings.ownerPolicy()).bindings, "DELETED_ROOT_REUSE_REQUIRES_NEW_REVIEWED_APPROVAL").toEqual([]); } finally { reopened.close(); } } finally { rmSync(retained, { recursive: true, force: true }); } @@ -313,8 +315,9 @@ test("ordinary host restart retains approval for the same qualified native brain const f = await fixture(); await f.approve(); const observed = await f.read(); f.continuity.close(); const next = await createReferenceOwnerContinuity(f.root, nativeExpected); + const restartedSettings = createTrustSettings({ ...f.settingsOptions, ownerRoot: next.root }); try { - expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation).bindings, + expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation, restartedSettings.ownerPolicy()).bindings, "ORDINARY_NATIVE_RESTART_PRESERVES_APPROVED_OWNER").toHaveLength(1); } finally { next.close(); } }); @@ -322,6 +325,40 @@ test("ordinary host restart retains approval for the same qualified native brain test("an unqualified host withholds retained owner approval", async () => { const f = await fixture(); await f.approve(); const observed = await f.read(); const next = await createReferenceOwnerContinuity(f.root); - try { expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation).bindings, + try { expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation, f.settings.ownerPolicy()).bindings, "UNQUALIFIED_NATIVE_HOST_WITHHOLDS_OWNER_APPROVAL").toEqual([]); } finally { next.close(); } }); + +test("owner qualification retains the Settings last-valid rules with an honest error and clears it on recovery", async () => { + const f = await fixture(); await f.approve(); const policy = readFileSync(f.policyPath); + writeFileSync(f.policyPath, "---\nschema_version: 9000\n---\n"); + const restricted = await f.read(); + expect(restricted.evidence.ownerResolution, "OWNER_QUALIFICATION_SHARES_LIVE_LAST_VALID_POLICY").toMatchObject({ state: "available", policyError: "policy_unavailable" }); + expect(restricted.evidence.trusted).toBe(false); + writeFileSync(f.policyPath, policy); + expect((await f.read()).evidence.ownerResolution).toMatchObject({ state: "available", policyError: null }); +}); + +test("an unrelated policy edit binds owner evidence to the live verified hash without a second projection cache", async () => { + const f = await fixture(); await f.approve(); const first = await f.read(); + writeFileSync(f.policyPath, readFileSync(f.policyPath, "utf8") + "\nThe fleet reviews the harbor.\n"); + const live = f.settings.live.read(), current = await f.read(); + expect(current.evidence.ownerResolution.policyHash, "OWNER_EVIDENCE_USES_VERIFIED_LIVE_POLICY_HASH").toBe(live.policyHash); + expect(current.evidence.ownerResolution.policyHash).not.toBe(first.evidence.ownerResolution.policyHash); + expect(current.evidence.ownerResolution.state).toBe("available"); +}); + +test("the queued owner writer fences a changed live generation even when projection and boundary remain unchanged", async () => { + const f = await fixture(true); await f.approve(); + const control = await heldWriter(f.writer!, join(f.root, "ui.db")); + f.state.afterBlob = async () => { await control.hold(); }; + const posted = control.posted("referenceReadPrepare"), pending = f.read(); + try { + await posted; + writeFileSync(f.policyPath, readFileSync(f.policyPath, "utf8") + "\nThe fleet reviews the harbor.\n"); + control.release(); + expect((await pending).evidence.ownerResolution.state, "OWNER_WRITER_FENCES_LIVE_GENERATION_AFTER_QUEUE").toBe("unavailable"); + f.state.afterBlob = async () => {}; + expect((await f.read()).evidence.ownerResolution.state, "NEXT_READ_RECOVERS_WITH_FRESH_SETTINGS_LIVE_SNAPSHOT").toBe("available"); + } finally { await control.close(); await pending.catch(() => {}); } +}); diff --git a/scripts/native-proof/managed-reference-source.ts b/scripts/native-proof/managed-reference-source.ts index b90658c6bf..54aedb4dc0 100644 --- a/scripts/native-proof/managed-reference-source.ts +++ b/scripts/native-proof/managed-reference-source.ts @@ -128,7 +128,7 @@ export async function proveManagedReferenceSource(client: ReturnType settings.ownerPolicy(), brain: servedBrain, sources, pool: client, transport }); const tools = createReferenceTools({ sources, reads }), turnId = "odysseus-native-read"; await tools.begin(turnId, { principalId: principal.id, posture: "interactive", generation: null }); tools.attachEgress(turnId, principal.id, { egress, current: () => true }); @@ -152,7 +152,7 @@ export async function proveManagedReferenceSource(client: ReturnType