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
10 changes: 10 additions & 0 deletions .changeset/immutable-reference-blob-reads.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"@schlessera/brain-ui-server": minor
---

Prepare bounded immutable Git-object reads for managed reference source. The
host's offline, credential-free transport returns an exact byte range with
blob identity, mode and SHA-256 evidence after checking the full object hash.
Literal paths, regular-blob modes, size limits and cancellation are enforced.
Actual backend read delivery, durable read correlation and repository trust
remain separate requirements.
27 changes: 24 additions & 3 deletions docs/decisions/reference-source-acquisition.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,11 @@ the previous root, so a refresh fetches only new objects. Then
2. The **network transport** fetches one ref into it. It is the only worker
that may hold a credential: the granted host variable, delivered through a
fixed credential helper, with one allowed protocol and no redirects
(`async fetch({ repository, ref, token, root, signal, wire })`, `packages/ui-server/src/brain/reference-transport.ts:211-232`).
(`async fetch({ repository, ref, token, root, signal, wire })`, `packages/ui-server/src/brain/reference-transport.ts:231-252`).
3. A separate **checkout worker** has no credential and no network. It checks
out the commit and evaluates the repository's attributes. No filter or
hook is configured, so none runs
(`async checkout({ root, commit, signal })`, `packages/ui-server/src/brain/reference-transport.ts:233-242`).
(`async checkout({ root, commit, signal })`, `packages/ui-server/src/brain/reference-transport.ts:253-263`).
4. The live grant is read again, the root is sealed, the grant is read
again, and only then is the root published.

Expand Down Expand Up @@ -269,10 +269,31 @@ to the current native sealed root, refusing a different root/generation or
contradictory brain/ref/commit. These host facts are outside repository content
and provider history and are not read receipts. Normal source/worktree file
tools remain workspace restriction signals; shell-local-read coverage retains
its documented limitation. Actual immutable regular-blob/range/digest evidence,
its documented limitation. Model-delivery-bound immutable regular-blob/range/digest evidence,
approved-owner matching and complete managed-path native/backend qualification
remain required before repository trust can be enabled.

### Bounded immutable object reads

The transport's host-only `readBlob` primitive reads from the attested sealed
acquisition's Git object database, rather than its checkout. A caller supplies
the recorded commit/tree and a literal normalized Git path. Only regular blob
modes qualify. The credential-free offline maintenance worker bounds the full
blob to 4 MiB, verifies its complete Git object hash, then returns at most
64 KiB with the actual byte range and SHA-256 digest. The host validates that
envelope and exact base64 bytes again; cancellation after the worker returns
still withholds the result
(`readBlob`, `packages/ui-server/src/brain/reference-transport.ts:174-189`).

Git pathspec syntax is disabled, so punctuation in a filename remains literal.
Symlinks, gitlinks and directories never become blob reads. Checkout edits or
an altered `origin` cannot replace the selected object bytes. The caller still
owns native root attestation and live authority checks across waits. This
primitive does not itself connect a read to a backend's actual model delivery;
that durable acquisition/read correlation and approved-owner matching remain
necessary for a source-trust decision. Ordinary file reads keep their existing
workspace restrictions, and no directory, credential or hostname grants trust.

## Admission

At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or
Expand Down
18 changes: 17 additions & 1 deletion docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,23 @@ never actual model-content reads or an independently approved owner boundary.
File-tool reads under the reference/worktree worker roots continue to produce
ordinary workspace restriction signals. No repository trust capability is
enabled. Tool names, descriptions, input/result schemas and provider history
are unchanged; actual immutable blob/range/digest evidence remains required.
are unchanged; actual model-delivery-bound immutable blob/range/digest evidence
remains required.

The internal reference transport now has an optional `readBlob` operation
for a host-selected sealed acquisition root, exact commit and tree, literal
Git path, byte offset and maximum range. Its caller must attest the root and
recheck live turn/principal/grant authority after waits. It reads regular Git
blobs (`100644` or `100755`) from the immutable object database, checks the
complete object's Git hash and returns exact bytes, blob ID/mode, tree,
total byte size, offset, returned length and the range's SHA-256 digest.
The full blob is bounded to 4194304 bytes; a returned range is at most 65536
bytes. An offset at EOF returns the empty range; an offset beyond EOF refuses.
Symlinks, gitlinks, directories, traversal, malformed UTF-8 paths, a different
tree, corrupt objects and malformed byte evidence refuse. The fixed worker
has neither credentials nor network, and cancellation withholds a late result.
This primitive is host-only and creates no model-delivery receipt, new agent
tool, repository trust capability or backend read-equivalence claim.

## Prepared ordinary inference transport (internal #1665)

Expand Down
2 changes: 1 addition & 1 deletion docs/plans/reviewable-session-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public design or its fixtures. Fictional examples use the Odysseus world.
([reference-source grants](../decisions/reference-source-grants.md)). Its
fixed Git transport separates network acquisition from credential-free,
network-free checkout (`createReferenceTransport`,
`packages/ui-server/src/brain/reference-transport.ts:118-215`).
`packages/ui-server/src/brain/reference-transport.ts:122-265`).
- The Security and Devices & agents surfaces already exist; policy facts are
currently read-only (`AgentPolicyGroup`,
`packages/ui-react/src/components/settings/agent-policy-group.tsx:8-51`).
Expand Down
108 changes: 108 additions & 0 deletions packages/ui-server/src/brain/reference-blob.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/** Fixed offline Git-object reader. Its caller owns and attests the sealed acquisition root. */
import { createHash } from "node:crypto";
import { isAbsolute } from "node:path";

const REFERENCE_BLOB_MAXIMUM = 4 * 1024 * 1024;
export const REFERENCE_BLOB_RANGE_MAXIMUM = 65_536;

export interface ReferenceBlobInput {
/** Host-selected sealed acquisition, never a worker-supplied directory. */
root: string;
commit: string;
tree: string;
path: string;
offset: number;
maximum: number;
signal?: AbortSignal;
}

/** Host evidence about the exact returned bytes; never a trust or private-access grant. */
export interface ReferenceBlob {
bytes: Uint8Array;
blob: string;
mode: "100644" | "100755";
tree: string;
totalBytes: number;
offset: number;
length: number;
/** SHA-256 of the returned range, including the empty range at EOF. */
digest: string;
}

export function validReferenceBlobInput(input: ReferenceBlobInput): boolean {
return typeof input.root === "string" && isAbsolute(input.root) && !input.root.includes("\0")
&& typeof input.commit === "string" && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(input.commit)
&& typeof input.tree === "string" && input.tree.length === input.commit.length && /^[0-9a-f]+$/.test(input.tree)
&& typeof input.path === "string" && Buffer.byteLength(input.path) <= 4096 && !/[\\\u0000-\u001f\u007f]/u.test(input.path)
&& Buffer.from(input.path).toString("utf8") === input.path
&& input.path.split("/").every(part => part && part !== "." && part !== ".." && part.toLowerCase() !== ".git")
&& Number.isSafeInteger(input.offset) && input.offset >= 0 && input.offset <= REFERENCE_BLOB_MAXIMUM
&& Number.isSafeInteger(input.maximum) && input.maximum >= 1 && input.maximum <= REFERENCE_BLOB_RANGE_MAXIMUM;
}

/**
* Reads objects, never checkout files. Every subprocess has bounded stdout,
* no stderr pipe to fill, literal arguments and no replace-object/pathspec
* expansion. The ordinary maintenance envelope supplies network/UID limits.
*/
export const REFERENCE_BLOB_PROGRAM = String.raw`import base64,hashlib,json,os,subprocess,sys
binary,root,commit,tree,path,offset,maximum=sys.argv[1:]
offset=int(offset);maximum=int(maximum);limit=${REFERENCE_BLOB_MAXIMUM}
class Refusal(Exception):
def __init__(self,code):self.code=code
def run(args,bound):
child=subprocess.Popen([binary,"--no-replace-objects","--literal-pathspecs","--git-dir",os.path.join(root,".git"),"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false",*args],stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
try:
data=child.stdout.read(bound+1)
if len(data)>bound:raise Refusal("unavailable")
if child.wait()!=0:raise Refusal("unavailable")
return data
finally:
if child.poll() is None:child.kill();child.wait()
child.stdout.close()
try:
actual_tree=run(["rev-parse","--verify",commit+"^{tree}"],128).decode("ascii").strip()
if actual_tree!=tree:raise Refusal("unavailable")
entry=run(["ls-tree","--full-tree","-z",commit,"--",path],8192)
rows=entry.split(b"\0")
if len(rows)!=2 or rows[1] or not rows[0]:raise Refusal("invalid")
fields=rows[0].split(b"\t",1)
if len(fields)!=2 or fields[1]!=path.encode("utf-8"):raise Refusal("invalid")
mode,kind,blob=fields[0].decode("ascii").split(" ")
if mode not in ("100644","100755") or kind!="blob":raise Refusal("invalid")
if len(blob)!=len(commit) or any(c not in "0123456789abcdef" for c in blob):raise Refusal("unavailable")
raw_size=run(["cat-file","-s",blob],32)
if not raw_size.endswith(b"\n") or not raw_size[:-1].isdigit():raise Refusal("unavailable")
size=int(raw_size)
if size>limit:raise Refusal("capacity")
if offset>size:raise Refusal("invalid")
content=run(["cat-file","blob",blob],limit)
if len(content)!=size:raise Refusal("unavailable")
object_hash=hashlib.sha1() if len(blob)==40 else hashlib.sha256()
object_hash.update(b"blob "+str(size).encode("ascii")+b"\0"+content)
if object_hash.hexdigest()!=blob:raise Refusal("unavailable")
selected=content[offset:offset+maximum]
print(json.dumps(dict(version=1,blob=blob,mode=mode,tree=tree,totalBytes=size,offset=offset,length=len(selected),digest=hashlib.sha256(selected).hexdigest(),base64=base64.b64encode(selected).decode("ascii")),separators=(",",":")))
except Refusal as error:
print(json.dumps(dict(code=error.code),separators=(",",":")));sys.exit(1)
except Exception:
print('{"code":"unavailable"}');sys.exit(1)
`;

/** Treat the worker's envelope as untrusted; JSON decoding must preserve exact bytes. */
export function parseReferenceBlob(text: string, input: ReferenceBlobInput): ReferenceBlob {
if (Buffer.byteLength(text) > 2 * REFERENCE_BLOB_RANGE_MAXIMUM + 4096) throw Error("Immutable reference receipt exceeds its bound");
const value = JSON.parse(text);
if (!value || Object.keys(value).sort().join(",") !== "base64,blob,digest,length,mode,offset,totalBytes,tree,version"
|| value.version !== 1 || typeof value.blob !== "string" || value.blob.length !== input.commit.length || !/^[0-9a-f]+$/.test(value.blob)
|| !["100644", "100755"].includes(value.mode) || value.tree !== input.tree || value.offset !== input.offset
|| !Number.isSafeInteger(value.totalBytes) || value.totalBytes < input.offset || value.totalBytes > REFERENCE_BLOB_MAXIMUM
|| value.length !== Math.min(input.maximum, value.totalBytes - input.offset)
|| typeof value.digest !== "string" || !/^[0-9a-f]{64}$/.test(value.digest) || typeof value.base64 !== "string"
|| value.base64.length > Math.ceil(REFERENCE_BLOB_RANGE_MAXIMUM / 3) * 4) throw Error("Invalid immutable reference byte evidence");
const bytes = Buffer.from(value.base64, "base64");
if (bytes.length !== value.length || bytes.toString("base64") !== value.base64 || createHash("sha256").update(bytes).digest("hex") !== value.digest)
throw Error("Invalid immutable reference range digest");
return { bytes, blob: value.blob, mode: value.mode, tree: value.tree, totalBytes: value.totalBytes,
offset: value.offset, length: value.length, digest: value.digest };
}
20 changes: 20 additions & 0 deletions packages/ui-server/src/brain/reference-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { MaintenanceTempBusyError, runMaintenanceWorker, type MaintenanceCommand
import type { ReferenceRepository } from "../db/reference-grants.js";
import { githubReferenceRepository } from "./github-reference-identity.js";
import type { GitHubReferenceWire } from "./github-reference-wire.js";
import { parseReferenceBlob, REFERENCE_BLOB_PROGRAM, REFERENCE_BLOB_RANGE_MAXIMUM, validReferenceBlobInput,
type ReferenceBlob, type ReferenceBlobInput } from "./reference-blob.js";

/** Fixed configuration of every acquired reference repository; nothing repository-controlled is ever configuration. */
export const REFERENCE_GIT_CONFIG = `[core]
Expand Down Expand Up @@ -61,6 +63,8 @@ export interface ReferenceTransport {
checkout(input: { root: string; commit: string; signal?: AbortSignal }): Promise<void>;
/** Host-only, offline tree identity; required by managed acquisition, never supplied by a caller. */
tree?(input: { root: string; commit: string; signal?: AbortSignal }): Promise<string>;
/** Fixed offline object read; callers must bind and attest the sealed root and live authority. */
readBlob?(input: ReferenceBlobInput): Promise<ReferenceBlob>;
}

function assertWireRepository(repository: ReferenceRepository, wire?: GitHubReferenceWire): void {
Expand Down Expand Up @@ -167,6 +171,22 @@ export function createReferenceTransport(options: {
return result;
}
return {
async readBlob({ ...input }) {
input.signal?.throwIfAborted();
if (!validReferenceBlobInput(input)) throw new ReferenceTransportError("invalid", "Reference blob reads need an ordinary Git path and bounded byte range.");
const result = await run({ ...command({ token: null, network: false, mirror: input.root, signal: input.signal,
argv: ["/usr/bin/python3", "-I", "-S", "-c", REFERENCE_BLOB_PROGRAM, git(), input.root, input.commit, input.tree, input.path,
String(input.offset), String(input.maximum)] }), outputBytes: 2 * REFERENCE_BLOB_RANGE_MAXIMUM + 4096 });
input.signal?.throwIfAborted();
if (result.killed) throw new ReferenceTransportError("unavailable", "The immutable reference read timed out or was cancelled.");
if (result.exitCode !== 0) {
let reason: "invalid" | "unavailable" | "capacity" = "unavailable";
try { const value = JSON.parse(result.stdout); if (Object.keys(value).join(",") === "code" && ["invalid", "capacity"].includes(value.code)) reason = value.code; } catch { /* Unreadable worker receipts refuse. */ }
throw new ReferenceTransportError(reason, "The selected immutable regular blob could not be read within its bounds.");
}
try { return parseReferenceBlob(result.stdout, input); }
catch { throw new ReferenceTransportError("unavailable", "The immutable reference byte evidence is invalid."); }
},
async tree({ root, commit, signal }) {
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit)) throw new ReferenceTransportError("invalid", "tree inspection needs one commit id");
const result = await run(command({ token: null, network: false, mirror: root, signal,
Expand Down
Loading
Loading