From b332f6e894a632caa2c2d837fccbab5cbb1c6aa6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 18:12:16 +0000 Subject: [PATCH 1/3] CONTRACT: feat(ui-server): add bounded immutable reference blob reads --- .changeset/immutable-reference-blob-reads.md | 10 ++ .../decisions/reference-source-acquisition.md | 27 +++- docs/integration-contract/package-api.md | 18 ++- docs/plans/reviewable-session-safety.md | 2 +- .../ui-server/src/brain/reference-blob.ts | 108 ++++++++++++++ .../src/brain/reference-transport.ts | 20 +++ .../ui-server/tests/reference-blob.test.ts | 141 ++++++++++++++++++ .../tests/reference-transport.test.ts | 8 +- .../native-proof/managed-reference-source.ts | 8 + 9 files changed, 336 insertions(+), 6 deletions(-) create mode 100644 .changeset/immutable-reference-blob-reads.md create mode 100644 packages/ui-server/src/brain/reference-blob.ts create mode 100644 packages/ui-server/tests/reference-blob.test.ts diff --git a/.changeset/immutable-reference-blob-reads.md b/.changeset/immutable-reference-blob-reads.md new file mode 100644 index 0000000000..b4e16fd83e --- /dev/null +++ b/.changeset/immutable-reference-blob-reads.md @@ -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. diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 2171baf75d..224fbfe82e 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -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. @@ -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 diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 6a453d8cbd..a2f63792ed 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -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) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index d6109f0a4f..36903e053d 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -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`). diff --git a/packages/ui-server/src/brain/reference-blob.ts b/packages/ui-server/src/brain/reference-blob.ts new file mode 100644 index 0000000000..7712c43f09 --- /dev/null +++ b/packages/ui-server/src/brain/reference-blob.ts @@ -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"; + +export 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 }; +} diff --git a/packages/ui-server/src/brain/reference-transport.ts b/packages/ui-server/src/brain/reference-transport.ts index 8374f24fa5..5814a8abc6 100644 --- a/packages/ui-server/src/brain/reference-transport.ts +++ b/packages/ui-server/src/brain/reference-transport.ts @@ -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] @@ -61,6 +63,8 @@ export interface ReferenceTransport { checkout(input: { root: string; commit: string; signal?: AbortSignal }): Promise; /** Host-only, offline tree identity; required by managed acquisition, never supplied by a caller. */ tree?(input: { root: string; commit: string; signal?: AbortSignal }): Promise; + /** Fixed offline object read; callers must bind and attest the sealed root and live authority. */ + readBlob?(input: ReferenceBlobInput): Promise; } function assertWireRepository(repository: ReferenceRepository, wire?: GitHubReferenceWire): void { @@ -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, diff --git a/packages/ui-server/tests/reference-blob.test.ts b/packages/ui-server/tests/reference-blob.test.ts new file mode 100644 index 0000000000..09489476e9 --- /dev/null +++ b/packages/ui-server/tests/reference-blob.test.ts @@ -0,0 +1,141 @@ +import { afterEach, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { deflateSync } from "node:zlib"; +import { createReferenceTransport } from "../src/brain/reference-transport"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +function fixture() { + const root = mkdtempSync(join(tmpdir(), "reference-blob-")); roots.push(root); + const environment = { PATH: "/usr/bin:/bin", HOME: root, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", + GIT_AUTHOR_NAME: "Odysseus", GIT_AUTHOR_EMAIL: "odysseus@example.test", GIT_COMMITTER_NAME: "Odysseus", GIT_COMMITTER_EMAIL: "odysseus@example.test", + GIT_AUTHOR_DATE: "2026-07-12T12:00:00Z", GIT_COMMITTER_DATE: "2026-07-12T12:00:00Z" }; + function git(...args: string[]) { + const child = Bun.spawnSync(["/usr/bin/git", "-c", "core.hooksPath=/dev/null", ...args], { cwd: root, env: environment }); + if (child.exitCode !== 0) throw Error(child.stderr.toString()); + return child.stdout.toString().trim(); + } + git("init", "--quiet", "-b", "main"); + const bytes = Buffer.from([0, 255, 10, 240, 159, 154, 162, 128, 13, 10, 65]); + writeFileSync(join(root, "chart.bin"), bytes); + writeFileSync(join(root, "star*.md"), "The Sirens sing.\n"); + writeFileSync(join(root, "star-other.md"), "A different chart.\n"); + writeFileSync(join(root, ":(glob)star.md"), "A literal Git path.\n"); + mkdirSync(join(root, "notes")); writeFileSync(join(root, "notes/empty.md"), ""); + symlinkSync("chart.bin", join(root, "alias")); + git("add", "."); git("commit", "--quiet", "-m", "Ithaca charts"); + const commit = git("rev-parse", "HEAD"), tree = git("rev-parse", "HEAD^{tree}"); + const launches: Parameters[0]["run"]>>[0][] = []; + // Actual installed Git and Python execute the production program. This + // direct runner does not claim maintenance-worker or native isolation. + const run: NonNullable[0]["run"]> = async input => { + launches.push(input); + const child = Bun.spawn([...input.command], { env: input.env, stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + const abort = () => child.kill("SIGKILL"); input.signal?.addEventListener("abort", abort, { once: true }); + try { + const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + return { stdout, stderr, exitCode, killed: input.signal?.aborted ?? false }; + } finally { input.signal?.removeEventListener("abort", abort); } + }; + const transport = createReferenceTransport({ brainPath: root, run }); + const read = (path: string, offset = 0, maximum = 65_536) => { + expect(typeof transport.readBlob, "IMMUTABLE_REFERENCE_BLOB_READ_IMPLEMENTED").toBe("function"); + return transport.readBlob!({ root, commit, tree, path, offset, maximum }); + }; + return { root, bytes, git, commit, tree, launches, run, transport, read }; +} + +test("an immutable binary range is bound to its original Git blob, despite checkout edits and origin changes", async () => { + const f = fixture(), blob = f.git("rev-parse", "HEAD:chart.bin"); + writeFileSync(join(f.root, "chart.bin"), "Different worktree bytes."); + f.git("remote", "add", "origin", "https://github.com/poseidon/sea.git"); + const result = await f.read("chart.bin", 2, 7); + expect(Buffer.from(result.bytes), "IMMUTABLE_REFERENCE_RANGE_BYTES").toEqual(f.bytes.subarray(2, 9)); + expect(result).toMatchObject({ blob, mode: "100644", tree: f.tree, totalBytes: f.bytes.length, offset: 2, length: 7, + digest: createHash("sha256").update(f.bytes.subarray(2, 9)).digest("hex") }); + expect(f.launches.length).toBe(1); + expect(f.launches[0]!.credentials, "IMMUTABLE_REFERENCE_READ_NO_CREDENTIALS").toBe(false); + expect(f.launches[0]!.transport?.network, "IMMUTABLE_REFERENCE_READ_OFFLINE").toBe(false); + expect(Object.keys(f.launches[0]!.env).some(key => /TOKEN|SECRET|PASSWORD/.test(key))).toBe(false); +}); + +test("Git pathspec metacharacters select exactly the literal immutable path", async () => { + const f = fixture(); + expect(Buffer.from((await f.read("star*.md")).bytes).toString()).toBe("The Sirens sing.\n"); + expect(Buffer.from((await f.read(":(glob)star.md")).bytes).toString()).toBe("A literal Git path.\n"); +}); + +test("a regular executable blob and an empty blob retain exact object mode and byte bounds", async () => { + const f = fixture(); + chmodSync(join(f.root, "star*.md"), 0o755); f.git("add", "star*.md"); f.git("commit", "--quiet", "-m", "Make the chart executable"); + const commit = f.git("rev-parse", "HEAD"), tree = f.git("rev-parse", "HEAD^{tree}"); + expect((await f.transport.readBlob!({ root: f.root, commit, tree, path: "star*.md", offset: 0, maximum: 1024 })).mode).toBe("100755"); + const empty = await f.read("notes/empty.md"); + expect(empty.length).toBe(0); expect(empty.totalBytes).toBe(0); + expect(Buffer.from(empty.bytes)).toEqual(Buffer.alloc(0)); + expect(empty.digest).toBe(createHash("sha256").update("").digest("hex")); + expect((await f.read("chart.bin", f.bytes.length)).length).toBe(0); +}); + +test("symlinks, directories, gitlinks and absent entries are never immutable regular blob reads", async () => { + const f = fixture(); + for (const path of ["alias", "alias/child", "notes", "absent.md"]) + await expect(f.read(path), `IMMUTABLE_REFERENCE_NON_BLOB_REFUSED:${path}`).rejects.toMatchObject({ reason: "invalid" }); + f.git("update-index", "--add", "--cacheinfo", `160000,${f.commit},foreign`); f.git("commit", "--quiet", "-m", "Record a foreign submodule"); + await expect(f.transport.readBlob!({ root: f.root, commit: f.git("rev-parse", "HEAD"), tree: f.git("rev-parse", "HEAD^{tree}"), path: "foreign", offset: 0, maximum: 1024 }), + "IMMUTABLE_REFERENCE_GITLINK_REFUSED").rejects.toMatchObject({ reason: "invalid" }); +}); + +test("invalid relative paths and numeric bounds are refused before launching a worker", async () => { + const f = fixture(); + for (const path of ["", "/chart.bin", "../chart.bin", "notes/../chart.bin", "notes//empty.md", ".git/config", "chart.bin\u0000other", "notes\\empty.md", "\ud800.md"]) + await expect(f.read(path)).rejects.toMatchObject({ reason: "invalid" }); + for (const [offset, maximum] of [[-1, 1], [0.5, 1], [0, 0], [0, 65_537], [Number.MAX_SAFE_INTEGER + 1, 1]]) + await expect(f.read("chart.bin", offset, maximum)).rejects.toMatchObject({ reason: "invalid" }); + expect(f.launches, "IMMUTABLE_REFERENCE_INVALID_INPUT_NO_WORKER").toHaveLength(0); +}); + +test("a different expected tree and corrupted blob objects refuse without returning bytes", async () => { + const f = fixture(); + await expect(f.transport.readBlob!({ root: f.root, commit: f.commit, tree: "a".repeat(40), path: "chart.bin", offset: 0, maximum: 1024 }), + "IMMUTABLE_REFERENCE_TREE_MISMATCH").rejects.toMatchObject({ reason: "unavailable" }); + const blob = f.git("rev-parse", "HEAD:chart.bin"), object = join(f.root, ".git/objects", blob.slice(0, 2), blob.slice(2)); + chmodSync(object, 0o644); writeFileSync(object, deflateSync(Buffer.from("blob 6\u0000forged"))); + await expect(f.read("chart.bin"), "IMMUTABLE_REFERENCE_OBJECT_HASH_CHECK").rejects.toMatchObject({ reason: "unavailable" }); +}); + +test("oversized blobs refuse before their body is returned", async () => { + const f = fixture(); + const allowed = Buffer.alloc(4 * 1024 * 1024, 0xa5); + writeFileSync(join(f.root, "bounded.bin"), allowed); + writeFileSync(join(f.root, "large.bin"), Buffer.alloc(4 * 1024 * 1024 + 1)); + f.git("add", "bounded.bin", "large.bin"); f.git("commit", "--quiet", "-m", "Add bounded charts"); + const commit = f.git("rev-parse", "HEAD"), tree = f.git("rev-parse", "HEAD^{tree}"); + const boundary = await f.transport.readBlob!({ root: f.root, commit, tree, path: "bounded.bin", offset: 0, maximum: 65_536 }); + expect(Buffer.from(boundary.bytes), "IMMUTABLE_REFERENCE_FULL_BOUND_ACCEPTED").toEqual(allowed.subarray(0, 65_536)); + expect(boundary).toMatchObject({ totalBytes: allowed.length, length: 65_536 }); + await expect(f.transport.readBlob!({ root: f.root, commit, tree, path: "large.bin", offset: 0, maximum: 1 }), + "IMMUTABLE_REFERENCE_BLOB_BOUND").rejects.toMatchObject({ reason: "capacity" }); +}); + +test("a cancelled read launches nothing, and malformed worker byte evidence is refused", async () => { + const f = fixture(), controller = new AbortController(); controller.abort(); + await expect(f.transport.readBlob!({ root: f.root, commit: f.commit, tree: f.tree, path: "chart.bin", offset: 0, maximum: 1024, signal: controller.signal })).rejects.toBeDefined(); + expect(f.launches, "IMMUTABLE_REFERENCE_CANCELLED_NO_WORKER").toHaveLength(0); + const late = new AbortController(); + const cancelled = createReferenceTransport({ brainPath: f.root, run: async input => { + const result = await f.run(input); late.abort(); return result; + } }); + await expect(cancelled.readBlob!({ root: f.root, commit: f.commit, tree: f.tree, path: "chart.bin", offset: 0, maximum: 1024, signal: late.signal }), + "IMMUTABLE_REFERENCE_CANCELLED_RESULT_WITHHELD").rejects.toBeDefined(); + const transport = createReferenceTransport({ brainPath: f.root, run: async input => { + const result = await f.run(input), value = JSON.parse(result.stdout); value.digest = "0".repeat(64); + return { ...result, stdout: JSON.stringify(value) }; + } }); + await expect(transport.readBlob!({ root: f.root, commit: f.commit, tree: f.tree, path: "chart.bin", offset: 0, maximum: 1024 }), + "IMMUTABLE_REFERENCE_RETURNED_DIGEST_CHECK").rejects.toMatchObject({ reason: "unavailable" }); +}); diff --git a/packages/ui-server/tests/reference-transport.test.ts b/packages/ui-server/tests/reference-transport.test.ts index f99679470c..a4a008a71f 100644 --- a/packages/ui-server/tests/reference-transport.test.ts +++ b/packages/ui-server/tests/reference-transport.test.ts @@ -116,7 +116,8 @@ test("acquisition publishes a complete thousand-file checkout and keeps the cred }) as typeof Bun.spawn); try { const penelope = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 86_400 }); - const sources = createReferenceSources({ db, pool, transport: createReferenceTransport({ brainPath: brain }), brain: "ithaca", credentials: { BRAIN_UI_SYNC_GITHUB_TOKEN: TOKEN } }); + const transport = createReferenceTransport({ brainPath: brain }); + const sources = createReferenceSources({ db, pool, transport, brain: "ithaca", credentials: { BRAIN_UI_SYNC_GITHUB_TOKEN: TOKEN } }); const shared = await sources.request({ principalId: penelope.id, repository: url("public", "ithaca"), revision: "main" }); const tree = join(shared.viewPath, shared.name); expect(shared.domain).toBe("public"); @@ -125,6 +126,11 @@ test("acquisition publishes a complete thousand-file checkout and keeps the cred expect(readFileSync(join(tree, ".git/config"), "utf8"), "REFERENCE_SOURCE_HOST_GIT_CONFIG").toBe(REFERENCE_GIT_CONFIG); expect(readFileSync(join(tree, "README.md"), "utf8"), "REFERENCE_SOURCE_UNDEFINED_FILTER_INERT").toBe("Ithaca public chart\n"); expect(shared.commit).toBe(git(join(fixture, "srv", "ithaca.git"), "rev-parse", "main")); + const acquired = await pool.poolSeal(shared.rootId); + const blob = await transport.readBlob!({ root: acquired.path!, commit: shared.commit, + tree: git(join(fixture, "srv", "ithaca.git"), "rev-parse", "main^{tree}"), path: "README.md", offset: 7, maximum: 6 }); + expect(Buffer.from(blob.bytes).toString(), "REFERENCE_SOURCE_ACTUAL_MAINTENANCE_BLOB_READ").toBe("public"); + expect(blob).toMatchObject({ mode: "100644", offset: 7, length: 6, totalBytes: 20 }); await expect(sources.request({ principalId: penelope.id, repository: url("private", "loom"), revision: "main" }), "REFERENCE_SOURCE_PRIVATE_NEEDS_GRANT") .rejects.toMatchObject({ code: "unauthorized" }); diff --git a/scripts/native-proof/managed-reference-source.ts b/scripts/native-proof/managed-reference-source.ts index 86cbf37714..1b5dea92b3 100644 --- a/scripts/native-proof/managed-reference-source.ts +++ b/scripts/native-proof/managed-reference-source.ts @@ -104,6 +104,14 @@ export async function proveManagedReferenceSource(client: ReturnType value.authorization === null), "MANAGED_NATIVE_PUBLIC_ANONYMOUS").toBe(true); expect(egress.usedBytes(), "MANAGED_NATIVE_ACTUAL_TURN_NETWORK_CHARGED").toBeGreaterThan(0); note("managed-source-native", { commit, tree, root: record.root, mapping, usedBytes: egress.usedBytes(), kernelWriteRefusal: refusal, From 37987d2569eef5b159e2c4b51976b2fbea389a55 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 18:13:56 +0000 Subject: [PATCH 2/3] fix(ui-server): keep the blob limit private to its reader --- packages/ui-server/src/brain/reference-blob.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/src/brain/reference-blob.ts b/packages/ui-server/src/brain/reference-blob.ts index 7712c43f09..e6918c03b4 100644 --- a/packages/ui-server/src/brain/reference-blob.ts +++ b/packages/ui-server/src/brain/reference-blob.ts @@ -2,7 +2,7 @@ import { createHash } from "node:crypto"; import { isAbsolute } from "node:path"; -export const REFERENCE_BLOB_MAXIMUM = 4 * 1024 * 1024; +const REFERENCE_BLOB_MAXIMUM = 4 * 1024 * 1024; export const REFERENCE_BLOB_RANGE_MAXIMUM = 65_536; export interface ReferenceBlobInput { From 8632aa485296254592993b01b1f3947dbd67e261 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 18:19:52 +0000 Subject: [PATCH 3/3] fix(ui-server): retain the admitted read signal across waits --- packages/ui-server/src/brain/reference-transport.ts | 2 +- packages/ui-server/tests/reference-blob.test.ts | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/src/brain/reference-transport.ts b/packages/ui-server/src/brain/reference-transport.ts index 5814a8abc6..e915fc290e 100644 --- a/packages/ui-server/src/brain/reference-transport.ts +++ b/packages/ui-server/src/brain/reference-transport.ts @@ -171,7 +171,7 @@ export function createReferenceTransport(options: { return result; } return { - async readBlob(input) { + 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, diff --git a/packages/ui-server/tests/reference-blob.test.ts b/packages/ui-server/tests/reference-blob.test.ts index 09489476e9..0c2b395a2a 100644 --- a/packages/ui-server/tests/reference-blob.test.ts +++ b/packages/ui-server/tests/reference-blob.test.ts @@ -85,6 +85,7 @@ test("symlinks, directories, gitlinks and absent entries are never immutable reg const f = fixture(); for (const path of ["alias", "alias/child", "notes", "absent.md"]) await expect(f.read(path), `IMMUTABLE_REFERENCE_NON_BLOB_REFUSED:${path}`).rejects.toMatchObject({ reason: "invalid" }); + expect(Buffer.from((await f.read("star*.md")).bytes).toString(), "IMMUTABLE_REFERENCE_OTHER_BLOB_REMAINS_USABLE").toBe("The Sirens sing.\n"); f.git("update-index", "--add", "--cacheinfo", `160000,${f.commit},foreign`); f.git("commit", "--quiet", "-m", "Record a foreign submodule"); await expect(f.transport.readBlob!({ root: f.root, commit: f.git("rev-parse", "HEAD"), tree: f.git("rev-parse", "HEAD^{tree}"), path: "foreign", offset: 0, maximum: 1024 }), "IMMUTABLE_REFERENCE_GITLINK_REFUSED").rejects.toMatchObject({ reason: "invalid" }); @@ -127,10 +128,11 @@ test("a cancelled read launches nothing, and malformed worker byte evidence is r await expect(f.transport.readBlob!({ root: f.root, commit: f.commit, tree: f.tree, path: "chart.bin", offset: 0, maximum: 1024, signal: controller.signal })).rejects.toBeDefined(); expect(f.launches, "IMMUTABLE_REFERENCE_CANCELLED_NO_WORKER").toHaveLength(0); const late = new AbortController(); + const pending = { root: f.root, commit: f.commit, tree: f.tree, path: "chart.bin", offset: 0, maximum: 1024, signal: late.signal }; const cancelled = createReferenceTransport({ brainPath: f.root, run: async input => { - const result = await f.run(input); late.abort(); return result; + const result = await f.run(input); late.abort(); pending.signal = new AbortController().signal; return result; } }); - await expect(cancelled.readBlob!({ root: f.root, commit: f.commit, tree: f.tree, path: "chart.bin", offset: 0, maximum: 1024, signal: late.signal }), + await expect(cancelled.readBlob!(pending), "IMMUTABLE_REFERENCE_CANCELLED_RESULT_WITHHELD").rejects.toBeDefined(); const transport = createReferenceTransport({ brainPath: f.root, run: async input => { const result = await f.run(input), value = JSON.parse(result.stdout); value.digest = "0".repeat(64);