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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/3613-approved-owner-read-resolution.md
Original file line number Diff line number Diff line change
@@ -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.
45 changes: 45 additions & 0 deletions docs/decisions/reference-source-acquisition.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 6 additions & 2 deletions packages/ui-server/src/app.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -426,6 +427,8 @@ export async function createApp(options: CreateAppOptions = {}): Promise<BrainUi
const nativeLeases = await createNativeBrainLeaseManager(nativeClient, { statePath: nativeLeasePath, brainPath: nativeReady.brainPath, fsid: nativeReady.fsid, brainUuid: nativeReady.brainUuid })
.catch(error => { if (ephemeralJournal) rmSync(journalRoot, { recursive: true, force: true }); throw error; });
const bootCleanup: (() => void | Promise<void>)[] = [];
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",
Expand Down Expand Up @@ -563,7 +566,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise<BrainUi
}
// The agent tools (#2432) reach both services only through the turn's own access.
const referenceTools = referenceSources ? createReferenceTools({ sources: referenceSources, ...(referenceWorktrees ? { worktrees: referenceWorktrees } : {}),
reads: createReferenceReads({ db, brain: nativeReady.brainUuid, sources: referenceSources, pool: nativeManager, transport: referenceTransport }),
reads: createReferenceReads({ db, ownerRoot: ownerContinuity.root, ownerPolicy: () => trustSettings.ownerPolicy(), brain: nativeReady.brainUuid, sources: referenceSources, pool: nativeManager, transport: referenceTransport }),
log: brainLog }) : undefined;
if (referenceWorktrees) {
bootCleanup.push(() => referenceWorktrees.close());
Expand Down Expand Up @@ -1341,7 +1344,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise<BrainUi
const piExcluded = () => 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;
Expand Down Expand Up @@ -1545,6 +1548,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise<BrainUi
// Consumers have drained; close the shared write connection before its reader.
await attempt(() => 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.");
Expand Down
30 changes: 30 additions & 0 deletions packages/ui-server/src/brain/reference-owner-native-root.ts
Original file line number Diff line number Diff line change
@@ -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<ReferenceOwnerRoot> | 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(); }
}
94 changes: 94 additions & 0 deletions packages/ui-server/src/brain/reference-owner-resolution.ts
Original file line number Diff line number Diff line change
@@ -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<TrustSelector, { kind: "github_owner" | "github_repository" }>;
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<ReferenceOwnerRoot> | undefined, observation: Readonly<ReferenceIdentityObservation>, 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(); }
}
24 changes: 24 additions & 0 deletions packages/ui-server/src/brain/reference-owner-root-kernel.ts
Original file line number Diff line number Diff line change
@@ -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<typeof load> | undefined;
export async function inspectPinnedReferenceRoot(fd: number) {
const selected = pending ??= load();
let libc: Awaited<typeof selected>;
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)) };
}
Loading
Loading