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-read-identity-observation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-server": patch
---

Bind immutable reference read evidence to the requesting turn's fresh managed GitHub identity observation, including reused acquisitions. Refuse reads whose observation does not match their sealed acquisition or changes before recording.
16 changes: 16 additions & 0 deletions docs/decisions/reference-source-acquisition.md
Original file line number Diff line number Diff line change
Expand Up @@ -420,3 +420,19 @@ catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-s
against the simple-quota Btrfs pool. It acquires the 1,200-file repository
into a quota-limited root and reads it through its view from a bubblewrap
sandbox. The withdrawn root is reclaimed.

## Read-bound identity observations

Each managed request retains its own frozen fixed-wire identity observation,
including cache reuse by another principal or turn. The observation binds the
host-generated read invocation ID, served brain, principal, turn, selected root,
full ref and commit. The reader and writer compare that ID with the invocation
that requested the transport, so another read of the same source cannot supply
its observation. Observation time is captured when fixed metadata validation
succeeds, before publication, recording or lease waits.
Immutable read evidence snapshots this observation separately from the original
acquisition and the writer checks their stable repository/current-owner IDs and
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.
6 changes: 4 additions & 2 deletions packages/ui-server/src/brain/github-reference-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,15 @@ export function createGitHubReferenceAccess(options: {
if (result.status !== 200) throw new ReferenceTransportError([401, 403, 404].includes(result.status) ? "denied" : "unavailable", "GitHub repository identity is unavailable");
const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.cloneUrl, result.value);
if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access");
let identityObservedAt = now();
openingMetadata = false;
// Source/worktree effects outlive wire shutdown, but not this authority.
const assertAuthority = () => {
authorize("git", credential !== null); authorize("metadata", credential !== null);
};
const assertCurrent = () => { wire.signal.throwIfAborted(); assertAuthority(); };
assertCurrent();
return Object.freeze({ identity: Object.freeze(identity), repository, credential, wire,
return Object.freeze({ identity: Object.freeze(identity), get identityObservedAt() { return identityObservedAt; }, repository, credential, wire,
domain: grant ? "private" as const : "public" as const, grantId: grant?.id ?? null, assertCurrent, assertAuthority,
/** A final fixed metadata observation must still describe this exact acquisition. */
async revalidate() {
Expand All @@ -100,6 +101,7 @@ export function createGitHubReferenceAccess(options: {
assertCurrent();
if (result.status !== 200 || !sameGitHubReferenceIdentity(identity, parseGitHubReferenceMetadata(location.cloneUrl, result.value)))
throw new ReferenceTransportError("denied", "GitHub repository identity changed during acquisition");
identityObservedAt = now();
} catch (error) {
const interrupted = signal?.aborted || (currentOperation && !currentOperation());
await wire.close();
Expand Down Expand Up @@ -162,7 +164,7 @@ export function createGitHubReferenceAccess(options: {
const access = await repositoryMetadata(input, false);
const { identity, domain, grantId, wire, credential, repository, assertCurrent, assertAuthority, revalidate, close } = access;
let resolved: Extract<ReferenceCheck, { ok: true }> | undefined;
return Object.freeze({ identity, domain, grantId, revision, signal: wire.signal, bytes: wire.bytes, assertCurrent, assertAuthority, revalidate, close,
return Object.freeze({ identity, get identityObservedAt() { return access.identityObservedAt; }, domain, grantId, revision, signal: wire.signal, bytes: wire.bytes, assertCurrent, assertAuthority, revalidate, close,
async resolve() {
assertCurrent();
const result = await options.transport.resolve({ repository, revision, token: credential, wire, signal: wire.signal });
Expand Down
27 changes: 27 additions & 0 deletions packages/ui-server/src/brain/reference-acquisition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import type { createGitHubReferenceAccess } from "./github-reference-access.js";
export interface ReferenceAcquisitionContext {
/** Both values come from the admitted host turn, never from tool input. */
turnId: string;
/** Host read invocation identity, generated before requesting this transport. */
operationId?: string;
egress: Parameters<ReturnType<typeof createGitHubReferenceAccess>["open"]>[0]["egress"];
/** Principal/turn and shared recorder health, read again after host waits. */
current(): boolean;
Expand Down Expand Up @@ -43,3 +45,28 @@ export function referenceAcquisitionMatches(db: Database, id: string, record: Na
&& (!expected.identity || row.repository_id === expected.identity.repositoryId && row.owner_id === expected.identity.ownerId
&& row.owner === expected.identity.owner && row.repository_name === expected.identity.repository));
}

/** One request's fixed-wire observation, including when it reuses an older sealed acquisition. */
export interface ReferenceIdentityObservation {
operationId: string;
brain: string;
principalId: string;
turnId: string;
identity: GitHubReferenceIdentity;
ref: string;
commit: string;
rootId: string;
observedAt: number;
}

/** Recording checks correlation, never converts retained metadata into source trust. */
export function referenceIdentityObservationMatches(observation: ReferenceIdentityObservation | undefined, acquisition: {
brain: string; repository_id: string; owner_id: string; owner: string; repository_name: string; ref: string; commit_id: string;
}, expected: { operationId: string; brain: string; principalId: string; turnId: string; rootId: string }): boolean {
const o = observation;
return Boolean(o && typeof o.operationId === "string" && /^[A-Za-z0-9_-]{1,128}$/u.test(o.operationId) && o.operationId === expected.operationId && Number.isSafeInteger(o.observedAt) && o.observedAt > 0
&& o.brain === expected.brain && o.brain === acquisition.brain && o.principalId === expected.principalId && o.turnId === expected.turnId
&& o.rootId === expected.rootId && o.ref === acquisition.ref && o.commit === acquisition.commit_id
&& o.identity.repositoryId === acquisition.repository_id && o.identity.ownerId === acquisition.owner_id
&& o.identity.owner === acquisition.owner && o.identity.repository === acquisition.repository_name);
}
7 changes: 7 additions & 0 deletions packages/ui-server/src/brain/reference-read-writes.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
/** Read evidence shares the reference writer FIFO; it never grants source trust. */
import { referenceIdentityObservationMatches, type ReferenceIdentityObservation } from "./reference-acquisition.js";
import type { Database } from "bun:sqlite";
import { isLiveReferenceGrant } from "../db/reference-grants.js";
import { sourceAuthorityCurrent, type SourceAuthority } from "./reference-source-authority.js";

interface ReferenceReadRecord {
id: string;
operationId: string;
turnId: string;
toolCallId: string;
principalId: string;
Expand All @@ -22,6 +24,11 @@ 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 acquired = acquisition as Parameters<typeof referenceIdentityObservationMatches>[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");
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)
Expand Down
20 changes: 13 additions & 7 deletions packages/ui-server/src/brain/reference-read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
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";
import { referenceAcquisitionMatches, type ReferenceAcquisitionContext } from "./reference-acquisition.js";
import { referenceAcquisitionMatches, referenceIdentityObservationMatches, type ReferenceAcquisitionContext } from "./reference-acquisition.js";
import { githubReferenceRepository } from "./github-reference-identity.js";
import { validReferenceBlobInput } from "./reference-blob.js";
import { ReferenceSourceError, type ReferenceSources, type ReferencePool } from "./reference-source.js";
Expand Down Expand Up @@ -65,24 +65,29 @@ export function createReferenceReads(options: {
// Failed operations also consumed their runtime call identity. A retry
// must be a new model call, rather than relabeling an earlier result.
used.add(toolCallId);
const operationId = randomUUID();
let lease: Awaited<ReturnType<ReferenceSources["request"]>> | undefined;
try {
// This API accepts a raw clone location, not an already-normalized
// authority key. Preserve real repository names ending in `.git`.
lease = await options.sources.request({ principalId, repository: location.cloneUrl, revision: request.revision, acquisition: context, signal });
lease = await options.sources.request({ principalId, repository: location.cloneUrl, revision: request.revision, acquisition: { ...context!, operationId }, signal });
const assertAuthority = () => { live(); lease!.assertAuthority(); };
assertAuthority();
// Only the selected native sealed root and retained acquisition may
// select a host directory. A checkout path supplied by a worker cannot.
const record = await options.pool.poolSeal(lease.rootId, signal);
assertAuthority();
const acquired = db.query("SELECT * FROM reference_acquisitions WHERE root_id = ?").get(lease.rootId) as {
brain: string; acquisition_id: string; commit_id: string; tree_id: string; ref: string; owner: string; repository_name: string;
repository_id: string; owner_id: string; brain: string; acquisition_id: string; commit_id: string; tree_id: string; ref: string; owner: string; repository_name: string;
} | null;
if (!record.path || record.publicationRevoked !== false || lease.readGrantId === undefined || !acquired
|| lease.repository !== location.canonical || acquired.owner !== location.owner || acquired.repository_name !== location.repository
|| !referenceAcquisitionMatches(db, lease.rootId, record, { brain: options.brain, commit: lease.commit, ref: acquired.ref }))
throw new ReferenceSourceError("unavailable", "No authoritative immutable acquisition is available for this read.");
const identityObservation = lease.identityObservation && structuredClone(lease.identityObservation);
if (!referenceIdentityObservationMatches(identityObservation, acquired, { operationId, brain: options.brain, principalId, turnId, rootId: lease.rootId }))
throw new ReferenceSourceError("unavailable", "No current transport identity is bound to this immutable read.");
const observationSnapshot = JSON.stringify(identityObservation);
const acquisitionSnapshot = JSON.stringify(acquired), nativeRoot = JSON.stringify(record.root), rootPath = record.path;
const authority = sourceAuthority(db, lease.domain === "public" ? "public" : `private:${principalId}`, lease.repository, lease.revision);
const returned = await readBlob({ root: rootPath, commit: lease.commit, tree: acquired.tree_id, path: request.path,
Expand All @@ -93,8 +98,9 @@ export function createReferenceReads(options: {
if (after.path !== rootPath || JSON.stringify(after.root) !== nativeRoot || after.publicationRevoked !== false
|| !referenceAcquisitionMatches(db, lease.rootId, after, { brain: options.brain, commit: lease.commit, ref: acquired.ref }))
throw new ReferenceSourceError("unavailable", "The native source identity changed during the read.");
// Defensive copy: neither a transport-owned buffer nor its mutable
// object can change the bytes between recording and tool delivery.
if (JSON.stringify(lease.identityObservation) !== observationSnapshot)
throw new ReferenceSourceError("unavailable", "The read transport identity changed before delivery.");
// Defensive copy: transport-owned buffers cannot change recorded bytes.
const bytes = Buffer.from(blob.bytes);
if (bytes.length !== blob.length || blob.offset !== request.offset || blob.tree !== acquired.tree_id
|| digest(bytes) !== blob.digest || blob.length !== Math.min(request.maximum, blob.totalBytes - request.offset))
Expand All @@ -103,10 +109,10 @@ 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(), turnId, toolCallId, principalId, acquisition: acquisitionSnapshot,
await write("referenceReadPrepare", { id: randomUUID(), 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" }), responseDigest: digest(JSON.stringify(result)), at: Date.now() }, lease.rootId, lease.readGrantId, authority);
trusted: false, trustRevision: "0", identityObservation }), responseDigest: digest(JSON.stringify(result)), at: Date.now() }, lease.rootId, lease.readGrantId, authority);
assertAuthority();
return result;
} catch (error) {
Expand Down
9 changes: 7 additions & 2 deletions packages/ui-server/src/brain/reference-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { coveringReferenceGrant, isLiveReferenceGrant, referenceRepository, refe
import { referenceRevision, ReferenceTransportError, type ReferenceTransport } from "./reference-transport.js";
import { GitHubReferenceMetadataError, type createGitHubReferenceAccess } from "./github-reference-access.js";
import { githubReferenceRepository } from "./github-reference-identity.js";
import { referenceAcquisitionMatches, type ReferenceAcquisition, type ReferenceAcquisitionContext } from "./reference-acquisition.js";
import { referenceAcquisitionMatches, type ReferenceAcquisition, type ReferenceAcquisitionContext, type ReferenceIdentityObservation } from "./reference-acquisition.js";
import { authorityRepository, sourceAuthority, sourceAuthorityCurrent, type SourceAuthority } from "./reference-source-authority.js";

type GitHubAccess = Awaited<ReturnType<ReturnType<typeof createGitHubReferenceAccess>["open"]>>;
Expand Down Expand Up @@ -77,6 +77,8 @@ export interface ReferenceSourceLease {
assertAuthority(): void;
/** The exact live grant selected for this managed request; null for anonymous access. Host-only. */
readGrantId?: string | null;
/** Fresh fixed-wire metadata for this request, never the cached acquisition timestamp. */
identityObservation?: Readonly<ReferenceIdentityObservation>;
/** Ends this reader's protection against capacity eviction. Idempotent. */
release(): void;
}
Expand Down Expand Up @@ -652,7 +654,7 @@ export function createReferenceSources(options: {
const context = input.acquisition;
if (!context || !context.turnId || !context.current()) throw new ReferenceSourceError("unavailable", "Managed GitHub acquisition needs a live admitted turn and its network budget.");
const controller = new AbortController(), signal = input.signal ? AbortSignal.any([input.signal, controller.signal]) : controller.signal;
const id = randomUUID();
const id = context.operationId ?? randomUUID();
const publicFence = authorityFences.get(sourceKey(PUBLIC, repository.canonical, revision)) ?? 0;
const privateFence = authorityFences.get(sourceKey(privateDomain(input.principalId), repository.canonical, revision)) ?? 0;
const publicRepositoryFence = authorityFences.get(sourceKey(PUBLIC, repository.canonical, "")) ?? 0;
Expand Down Expand Up @@ -782,6 +784,9 @@ export function createReferenceSources(options: {
assertTurn(); currentAccess.assertAuthority();
});
result.readGrantId = currentAccess.grantId;
result.identityObservation = Object.freeze({ operationId: id, brain: options.brain, principalId: input.principalId,
turnId: context.turnId, identity: Object.freeze({ ...currentAccess.identity }), ref: check.ref, commit: check.commit,
rootId: selectedRoot, observedAt: currentAccess.identityObservedAt });
assertCurrent();
return { kind: "source", row: current, stale: false, error: null };
} catch (error) {
Expand Down
Loading
Loading