diff --git a/.changeset/3613-approved-owner-read-resolution.md b/.changeset/3613-approved-owner-read-resolution.md new file mode 100644 index 0000000000..664498f97f --- /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. 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 03ad50d967..93eba5f80c 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -436,3 +436,48 @@ 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 +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 +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. 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 +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. 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 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 +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 6ce136dac5..0291dd4e96 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"; @@ -426,6 +427,8 @@ export async function createApp(options: CreateAppOptions = {}): Promise { if (ephemeralJournal) rmSync(journalRoot, { recursive: true, force: true }); throw error; }); const bootCleanup: (() => void | Promise)[] = []; + const ownerContinuity = await createReferenceOwnerContinuity(config.brainPath, nativeReady); + bootCleanup.push(() => ownerContinuity.close()); try { const nativeRecovery = await nativeLeases.recoverDeadOwners(); if (nativeRecovery.unknown.length || nativeRecovery.retainedUnverifiable) observability.logger("brain").emit({ severityText: "WARN", @@ -563,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()); @@ -1341,7 +1344,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, originEnforcement: true, + const trustSettings = createTrustSettings({ root: config.brainPath, ownerRoot: ownerContinuity.root, db, writer, lock: workerLock, originEnforcement: true, github: createTrustGitHubIdentity({ root: config.brainPath, access: githubReferenceAccess }), authority: id => { if (authMode !== "password") return null; @@ -1545,6 +1548,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/src/brain/reference-owner-native-root.ts b/packages/ui-server/src/brain/reference-owner-native-root.ts new file mode 100644 index 0000000000..489cf4c760 --- /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"; +interface ReferenceOwnerNativeIdentity { fsid: string; uuid: string } +export interface ReferenceOwnerRoot { path: string; device: number; inode: number; native: ReferenceOwnerNativeIdentity } +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 new file mode 100644 index 0000000000..6b032b96f0 --- /dev/null +++ b/packages/ui-server/src/brain/reference-owner-resolution.ts @@ -0,0 +1,94 @@ +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 { 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"); +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), + 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 { 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; + operationId: string; + 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 }[]; +} + +/** + * 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, policy?: ReferenceOwnerPolicy): ReferenceOwnerResolution { + const unavailable = (): ReferenceOwnerResolution => ({ version: 1, operationId: observation.operationId, + state: "unavailable", policyHash: null, trustRevision: null, policyError: null, bindings: [] }); + if (!root) return unavailable(); + try { + 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.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; + 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 || proof.policyRoot.fsid !== root.native.fsid || proof.policyRoot.uuid !== root.native.uuid || 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. + if (trustPolicyGeneration(root.path) !== selected.generation) return unavailable(); + return { version: 1, operationId: observation.operationId, state: bindings.length ? "available" : "unavailable", + policyHash, trustRevision: projection.revision, policyError: selected.error, bindings }; + } catch { return unavailable(); } +} 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/src/brain/reference-read-writes.ts b/packages/ui-server/src/brain/reference-read-writes.ts index dcbde1daf3..2bc3dc4bee 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 ReferenceOwnerPolicy, 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,8 @@ import { sourceAuthorityCurrent, type SourceAuthority } from "./reference-source interface ReferenceReadRecord { id: string; + ownerRoot?: ReferenceOwnerRoot; + ownerPolicy?: ReferenceOwnerPolicy; operationId: string; turnId: string; toolCallId: string; @@ -24,16 +27,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!, record.ownerPolicy); 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..d9fbecb3a6 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 { 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"; @@ -30,10 +31,13 @@ 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; }) { - const { db } = options, write = referenceWrites(db); + const { db } = options, write = referenceWrites(db), ownerRoot = options.ownerRoot; const calls = new Map>(); return { end(turnId: string) { calls.delete(turnId); }, @@ -109,10 +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(), 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 }), 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!, 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 8244bdad15..ae4466aaa9 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -1,3 +1,5 @@ +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"; @@ -84,6 +86,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; /** The composed host has installed the origin admission and stream fences. */ originEnforcement?: true; github?: ReturnType; @@ -114,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 => { @@ -212,6 +210,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, @@ -333,6 +339,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: 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; 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..75b50cb82f --- /dev/null +++ b/packages/ui-server/tests/reference-owner-lifecycle.test.ts @@ -0,0 +1,22 @@ +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"; + +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 () => { + 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 new file mode 100644 index 0000000000..56b1d70e88 --- /dev/null +++ b/packages/ui-server/tests/reference-owner-resolution.test.ts @@ -0,0 +1,364 @@ +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"; +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 { 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"; +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 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" } }; +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 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; + 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, 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) => { + 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, ownerRoot: continuity.root, ownerPolicy: () => settings.ownerPolicy(), 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, 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 () => { + 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", "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.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"; } + 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 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"); + 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); + } + 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, 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, 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); } +}); + +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, 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); + } 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 }); +}); + +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. + 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, 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); } +}); + +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 { + 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, f.settings.ownerPolicy()).bindings, + "DELETED_ROOT_REUSE_REQUIRES_NEW_REVIEWED_APPROVAL").toEqual([]); + } finally { reopened.close(); } + } finally { rmSync(retained, { recursive: true, force: true }); } +}); + +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 = await createReferenceOwnerContinuity(f.root, nativeExpected); + const restartedSettings = createTrustSettings({ ...f.settingsOptions, ownerRoot: next.root }); + try { + expect(resolveReferenceOwners(f.db, next.root, observed.evidence.identityObservation, restartedSettings.ownerPolicy()).bindings, + "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, 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/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..54aedb4dc0 100644 --- a/scripts/native-proof/managed-reference-source.ts +++ b/scripts/native-proof/managed-reference-source.ts @@ -1,5 +1,11 @@ +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"; +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"; @@ -40,6 +46,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); + 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, ownerRoot: ownerContinuity.root, ownerPolicy: () => 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 }); @@ -126,10 +144,29 @@ 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); } } +}