diff --git a/experiments/git-read-qualification.md b/experiments/git-read-qualification.md new file mode 100644 index 0000000000..8d5d908f58 --- /dev/null +++ b/experiments/git-read-qualification.md @@ -0,0 +1,212 @@ +# Repository read qualification: managed acquisition, immutable bytes + +Qualification for [#3612](https://github.com/schlessera/brain-kit/issues/3612), +2026-11-05, against main `35217d283b849b5ef81700d5d4c2ec7486405d12`. +This records a bounded experiment and its selected implementation route. It is +not an approval of a production trust exemption. The shared session-safety +plan/ADR is owned separately by #3599 and is not changed here. + +## Selected route + +Use the existing explicit managed reference acquisition operation, with new +host-verified identity and immutable-input evidence before repository trust +can affect taint. Ordinary shell `clone`, `fetch` and `pull` keep their existing +egress, credential and taint restrictions. Report **Managed repository reads +only; shell Git and writable workspace reads are not verified** when exposing +this capability. No hostname, command-window or directory exemption is added. + +The smart-HTTP relay plus URL rewriting candidate is rejected for this first +implementation. The experiment can clone, fetch and pull with Git protocol v2, +and can refuse receive-pack and unrelated paths. Nevertheless a worker can +request `refs/pull/7/head` through the exact same allowed upload-pack endpoint +using the relay's credential. The returned foreign commit was created on an +orphan branch and is absent from the allowed `main` history. This is a concrete +counterexample to endpoint-only authorization, not proof that a future fully +parsed Git protocol implementation is impossible. That substantially larger +implementation is unnecessary for the managed fallback. + +URL rewriting is compatibility configuration, not authority. A changed origin +selects another repo, and a longer `insteadOf` changes the transport. The +fixture sends every bypass to a closed loopback port. A configured pull also +updates the local worktree and executes its post-merge hook. Therefore approving +its read phase cannot approve the whole pull, hooks, merge/rebase or writes. +Ordinary outward operations retain independent permission checks. + +## Real runtime evidence and its limits + +Run `bun run test ./experiments/git-read-qualification.test.ts` from the root. +The suite prints the installed Git/Bun versions and JSON exit-code receipts +for every Git subprocess, including expected nonzero refusals. The evaluated +installation is Git 2.53.0 and Bun 1.4.4. No external repository, provider or +credential is used; fixture identities and the pinned 2026-07-12 Git dates use +the Odysseus world. + +The loopback origin uses the installed `git http-backend`, with separate +`odysseus/navigation` public and `penelope/loom` private bare repositories on +the same listener. A separate candidate relay supplies only a fictional token. +Real Git exercises v2 discovery/fetch, clone, annotated tag fetch, pull, an +orphan PR ref, receive-pack refusal, origin/config changes, parallel unrelated +public traffic, redirects and cancellation of a stalled HTTP request. + +The existing `createReferenceTransport` runs its actual argv/environment with +real Git through its `run` test seam. `createReferenceSources` runs with the +actual in-memory UI database, live principals/grants and directory-backed pool +double. The suite proves credential availability alone is insufficient, +principal separation, anonymous public traffic, credentialed private fetch, +credential-free offline checkout launch metadata, revocation of cached source, +and omission of the foreign commit from the fixed-ref acquisition. This is +not proof of the native maintenance worker, Btrfs sealing, kernel quotas or +production read-only mounts. The pool double deliberately permits edits so the +immutable-object counterexample can be exercised. + +The standard `scripts/test-offline.sh` was attempted and refused UID mapping +with `Operation not permitted`. Bubblewrap can create a network namespace here, +but cannot bring up its loopback interface (`RTNETLINK ... Operation not +permitted`). The successful fixture run uses only explicit loopback transports, +a complete fixed Git environment, no recursive submodules/filters and the +repository network preload. Native Git is not instrumented by that preload; +this run does not claim OS network isolation. A production-candidate runtime +must repeat under the permitted offline native harness. Missing hosted proof +is not green. + +## Concrete boundary to reuse and strengthen + +- `createReferenceTransport`, `packages/ui-server/src/brain/reference-transport.ts:97-166`, + owns credentialed `ls-remote`/single-ref fetch. It disables redirects, ambient + global/system config, hooks, interactive credentials and other protocols. + Checkout is a separate credential-free/network-free launch. Host config is + rewritten; source attributes do not install filters. Do not pass worker Git + config, headers, URL, helpers, refspecs or HTTP request bodies into this path. +- `createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:91-782`, + already separates anonymous public domains from per-principal private domains, + rechecks grants around queueing/publication, binds sealed root/commit leases, + cancels revoked work and recovers its catalog. Its authority/freshness windows + are not sufficient evidence of *current trust identity* on every new read. +- `coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:158-164`, + is access authority, independently of any incoming-source trust rule. Grant + presence never establishes repo ownership. A token must be taken only after + live principal/brain/grant checks and must not reach a worker-facing relay. +- `startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:123-352`, + remains unchanged: CONNECT cannot see a repository path. Its allow/deny, + recipient permissions and turn byte limits are not waived. +- `inputTaintSource`, `packages/ui-server/src/activity/ingestion-taint.ts:95-109`, + needs authoritative immutable-input evidence before a future narrow matcher + can alter the current workspace-read classification. Both backends must + consume the same host evidence, never worker assertions or timing guesses. + +The fixed transport is internal, not an authorization endpoint: `fetch` accepts +an internal ref and expects its caller to have resolved it. Do not expose that +method directly to arbitrary workers. In the production trust route, accept +only a canonical GitHub owner/repo and one short branch/tag name; reject raw +SHA, `refs/*`, ambiguous branch/tag collisions and arbitrary refspecs. Resolve +only `refs/heads/` or `refs/tags/`, record the chosen full ref and +commit, compare resolve/fetch identities and refuse a moved target rather than +publishing mismatched proof. Branch/tag names alone do not authenticate authors +or promise that their history contains no merged contributions from forks. + +## Identity, namespace and credentials + +The first implementation is concrete GitHub HTTPS, not a generic transport +seam. Canonicalize exactly two path segments on `github.com`, case-insensitively, +with optional `.git`. Reject userinfo, encoded separators, extra components, +lookalike hosts and traversal before URL normalization. The existing generic +reference parser is an access parser; it is not a verified GitHub identity. + +Obtain repository ID, current owner identity/namespace, repository name and +canonical transport location from a fixed host-owned GitHub metadata lookup, +never from a worker's remote, HTTP headers or returned source files. Git smart +HTTP does not itself provide GitHub's repository ID. Bind the verified metadata +to the actual acquisition; refresh/revalidate before publication and new trusted +input admission. Unknown, stale, redirected or mismatched metadata supplies no +trust. A transfer during metadata/acquisition is restrictive and must be covered +by production race tests; this local fixture cannot prove GitHub transactionality. + +An exact selector pins the stable repo ID **and** the approved owner boundary. +A rename within that owner can match after authoritative revalidation; a +transfer cannot. Reuse of the old repo name with a new ID cannot match. An owner +selector explicitly covers current and future repos currently in that namespace, +including repos later transferred in, and stops matching repos transferred out. +Require current authoritative metadata, no prefix/substring matching. The fixture +models these restrictive semantics; it is not an implementation of the metadata +lookup. Account namespace rename/reassignment must not be inferred from a Git +redirect; require fresh owner review when that boundary cannot be verified. + +Private acquisition still requires the existing live reference grant for the +brain/principal/repository and independently available named credential. Public +source and public identity lookup remain anonymous. Never probe a sequence of +host credentials to see which works. Reject before any private metadata request +unless separately authorized. Current credential recipients are `github.com` +and test loopback; sending the same credential to `api.github.com` is **not** +automatically authorized by that rule. The fixed metadata credential recipient +and authority are a remaining production architecture ruling for #3613. Options +are an explicitly approved fixed API credential path with separate recipient +checks, or no repository auto-trust when anonymous identity metadata is +unavailable. Do not remove a genuine decision label based on this experiment. + +## Immutable provenance and revocation + +A production acquisition record must bind host operation ID, brain, principal +and authority epoch, public/private domain, live grant ID, verified repo/owner +identity, canonical location, full ordinary ref, fetched commit and tree, sealed +pool root ID/generation, identity-validation time and policy revision. This is +host evidence stored outside the source and provider conversation. A root path +or source lease alone lacks stable GitHub identity and is insufficient. + +A read record binds that acquisition to the *actual returned bytes*: root +identity/generation, commit/tree, normalized Git path, regular blob ID/mode, +byte range/digest, detector version and matched trust-rule revision. Prefer +bounded object reads from the host-owned sealed acquisition. The fixture reads +regular blobs by commit and rejects symlinks, gitlinks and traversal; replacing +the checkout README or origin leaves those bytes unchanged. It assumes an +honest host-supplied mirror mapping and does not qualify an attacker-writable +`.git` directory. No caller may select a host root/mirror by arbitrary path. + +Do not follow symlinks, hard links, nested repositories, submodule gitlinks or +foreign mounts into mutable storage for trusted reads. A hard-linked worktree +file is still mutable and receives no path-based exemption. Explicit untrusted +file marks win over repository trust. Normal worker workspace/search reads, +untracked files, mixed sources and edited files retain current restrictions. +Persist root/commit/identity mapping across restart; unknown or missing mappings +report unsupported/unverified. Recheck live principal/grant and trust revision +at read admission and after waits. Revocation fences future reads and cancels +in-flight private acquisition; it cannot erase already delivered bytes or edit +provider history. Source refresh issues new immutable provenance, never silently +relabels an old read. + +## Supported forms and restrictive fallback + +| Form | Managed trust route | +| --- | --- | +| Ordinary branch or tag over canonical GitHub HTTPS | Supported only after host identity/ref/commit binding and live independent access checks. | +| Shell clone/fetch/pull; push/force push/history rewrite | Existing restrictions; no new exemption. Pull's configured local mutation is never authorized by a network-read decision. | +| PR/fork refs and raw object IDs | Refuse as request targets. Fork repository requires its own verified identity/rule/grant. No ancestry-based trust claim. | +| HTTP redirects and renamed/transfer redirects | No following; revalidate identity explicitly or refuse. | +| SSH/scp, git://, file://, custom remote/credential helpers | Unsupported for this trust capability, even when ordinary reference access supports local files. | +| Submodules, LFS, filters, recursive fetch | No recursive network or hydration. Gitlink/pointer/config bytes may be inspected as untrusted data; their foreign content gets no inherited trust. | +| Symlinks, nested repos, hard-linked mutable worktree, foreign mounts | No directory exemption; only verified regular immutable blobs qualify. | +| Generic HTTP, credential probes, receive-pack, arbitrary ref/object fetch | No worker-facing authenticated relay exists in the selected route. | + +## Production proof obligations + +#3613 must prove the fixed metadata recipient/identity path, arbitrary-client +refusal, live revocation during acquisition/read/publication, namespace and +ref movement races, bounded metadata/protocol bodies and response bytes, +wall-clock/cancellation, quotas and cleanup, restart/root-mapping recovery, +TOCTOU/escape mutations and both backend entry points. Count actual network +bytes, including discovery, auth retries and metadata; pack disk size and process +stdout limits are not network byte ceilings. Stop acquisition before delivering +bytes beyond the admitted budget. The present transport has a deadline and +native storage limits but no demonstrated per-turn network-byte accounting; +this is an explicit implementing gap, not a capability granted by the spike. + +No browser UI, production contracts, credentials, exemptions or provider-facing +history changed here. #3613 owns its additive interfaces, effective-taint +contracts, minor changeset and reviewed breaking-before-1.0 metadata. Repository +transparency remains independent of initial trigger review and origin CRUD. + +Sources checked: installed Git commands and transport source above; +[Git protocol v2](https://git-scm.com/docs/gitprotocol-v2/2.53.0), +[Git URL rewriting/configuration](https://git-scm.com/docs/git-config/2.53.0), +[GitHub repository metadata](https://docs.github.com/en/rest/repos/repos#get-a-repository), +the [reviewed design](https://github.com/schlessera/brain-kit/issues/3596#issuecomment-6652590345) +and [review disposition](https://github.com/schlessera/brain-kit/issues/3596#issuecomment-6652590730). diff --git a/experiments/git-read-qualification.test.ts b/experiments/git-read-qualification.test.ts new file mode 100644 index 0000000000..f190f681db --- /dev/null +++ b/experiments/git-read-qualification.test.ts @@ -0,0 +1,180 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { chmodSync, existsSync, symlinkSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { createUiDb } from "../packages/ui-server/src/db/client"; +import { createPrincipal } from "../packages/ui-server/src/db/principals"; +import { createReferenceGrant, referenceRepository, revokeReferenceGrant } from "../packages/ui-server/src/db/reference-grants"; +import { createReferenceSources } from "../packages/ui-server/src/brain/reference-source"; +import { createReferenceTransport, referenceRevision } from "../packages/ui-server/src/brain/reference-transport"; +import { referencePoolDouble } from "../packages/ui-server/tests/helpers/reference-pool-double"; +import { candidateRelay, checked, git, immutableBlob, localRunner, matches, origin, receipts, scratch } from "./git-read-qualification"; +import type { MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; + +const fixture = scratch(), TOKEN = "fixture-loom-acquisition-only", path = "/penelope/loom.git"; +const publicWork = fixture.dir("navigation"), privateWork = fixture.dir("loom"); +const publicBare = fixture.dir("navigation.git"), privateBare = fixture.dir("loom.git"); +let upstream: ReturnType, relay: ReturnType, main: string, foreign: string; +let clone: string; +beforeAll(async () => { + for (const [work, bare, text] of [[publicWork, publicBare, "Ithaca navigation"], [privateWork, privateBare, "Penelope loom"]]) { + await checked(work!, "init", "-q", "-b", "main"); + writeFileSync(join(work!, "README.md"), `${text}\n`); + writeFileSync(join(work!, ".gitattributes"), "README.md filter=sentinel\n"); + writeFileSync(join(work!, ".gitmodules"), '[submodule "foreign"]\n\tpath = foreign\n\turl = https://ithaca.invalid/foreign.git\n'); + symlinkSync("../outside", join(work!, "escape")); + await checked(work!, "add", "."); await checked(work!, "commit", "-q", "-m", "Set sail"); + await checked(work!, "tag", "-a", "voyage", "-m", "Voyage tag"); + await checked(bare!, "init", "-q", "--bare"); + await checked(work!, "push", bare!, "main", "--tags"); + await checked(bare!, "symbolic-ref", "HEAD", "refs/heads/main"); + await checked(bare!, "config", "http.uploadpack", "true"); + } + main = await checked(privateBare, "rev-parse", "main"); + await checked(privateWork, "checkout", "-q", "--orphan", "foreign"); + writeFileSync(join(privateWork, "foreign.md"), "Foreign proposal outside ordinary branches and tags\n"); + await checked(privateWork, "add", "."); await checked(privateWork, "commit", "-q", "-m", "Foreign proposal"); + foreign = await checked(privateWork, "rev-parse", "HEAD"); + await checked(privateWork, "push", privateBare, "HEAD:refs/pull/7/head"); + await checked(privateWork, "checkout", "-q", "main"); + // Nested repository entry is a gitlink, never a trusted regular source file. + await checked(privateWork, "update-index", "--add", "--cacheinfo", `160000,${foreign},nested`); + await checked(privateWork, "commit", "-q", "-m", "Record foreign gitlink"); + await checked(privateWork, "push", privateBare, "main"); + main = await checked(privateBare, "rev-parse", "main"); + upstream = origin([{ path: "/odysseus/navigation.git", directory: publicBare, token: null }, { path, directory: privateBare, token: TOKEN }]); + relay = candidateRelay(upstream.server.url, path, TOKEN); + clone = fixture.dir("ordinary-clone"); + console.log(`QUALIFICATION ${await checked(fixture.root, "--version")}; Bun ${Bun.version}; fixed date 2026-07-12`); +}); +afterAll(() => { + relay?.stop(true); upstream?.server.stop(true); fixture.close(); + console.log(`GIT_EXIT_RECEIPTS ${JSON.stringify(receipts)}`); +}); +const rewrite = () => ["-c", "protocol.version=2", "-c", `url.${relay.url}.insteadOf=http://127.0.0.1:1/`]; +const fake = () => `http://127.0.0.1:1${path}`; // Failing rewrites cannot reach an external host. + +test("rewrite supports real clone/fetch/pull, but config changes bypass it and endpoint-only relay admits foreign refs", async () => { + expect((await git(fixture.root, ...rewrite(), "clone", "--single-branch", "--branch", "main", fake(), clone)).code).toBe(0); + expect(await checked(clone, "rev-parse", "HEAD")).toBe(main); + expect((await git(clone, ...rewrite(), "fetch", "origin", "refs/tags/voyage")).code).toBe(0); + await checked(clone, "config", "pull.rebase", "false"); + expect((await git(clone, ...rewrite(), "pull", "--ff-only")).code).toBe(0); + writeFileSync(join(clone, ".git/hooks/post-merge"), "#!/bin/sh\nprintf hook > hook-fired\n"); + chmodSync(join(clone, ".git/hooks/post-merge"), 0o755); + writeFileSync(join(privateWork, "README.md"), "Penelope loom refreshed\n"); + await checked(privateWork, "add", "README.md"); await checked(privateWork, "commit", "-q", "-m", "Refresh loom"); + await checked(privateWork, "push", privateBare, "main"); + main = await checked(privateBare, "rev-parse", "main"); + expect((await git(clone, ...rewrite(), "pull", "--ff-only")).code).toBe(0); + expect(await checked(clone, "rev-parse", "HEAD")).toBe(main); + expect(existsSync(join(clone, "hook-fired")), "PULL_EXECUTES_LOCAL_CONFIGURED_MUTATION").toBe(true); + // Ref payload has no connection to a tool/window/name-based approval of `main`. + expect((await git(clone, ...rewrite(), "fetch", "origin", "refs/pull/7/head:refs/proposal/7")).code, "CANDIDATE_FOREIGN_REF_REACHES_CREDENTIALED_UPLOAD_PACK").toBe(0); + expect(await checked(clone, "rev-parse", "refs/proposal/7")).toBe(foreign); + expect(await checked(clone, "cat-file", "blob", `${foreign}:foreign.md`)).toContain("Foreign proposal"); + expect(upstream.facts.some(x => x.protocol === "version=2" && x.body.includes("command=fetch"))).toBe(true); + expect(upstream.facts.some(x => x.body.includes("ref-prefix refs/pull/7/head"))).toBe(true); + expect((await git(clone, ...rewrite(), "push", "origin", "HEAD:refs/heads/forbidden")).code).not.toBe(0); + expect((await git(privateBare, "show-ref", "--verify", "refs/heads/forbidden")).code).not.toBe(0); + await checked(clone, "remote", "set-url", "origin", "http://127.0.0.1:1/odysseus/navigation.git"); + expect((await git(clone, ...rewrite(), "fetch", "origin")).code).not.toBe(0); + // A longer insteadOf wins over the host-injected rewrite; demonstrate with an inert closed port. + expect((await git(clone, ...rewrite(), "-c", `url.http://127.0.0.1:1/.insteadOf=${fake()}`, "ls-remote", fake())).code).not.toBe(0); +}); + +test("relay's path gate refuses writes, generic HTTP and other repos while unrelated traffic proceeds", async () => { + const before = upstream.facts.length; + const requests = ["/penelope/loom.git/HEAD", "/odysseus/navigation.git/info/refs?service=git-upload-pack", `${path}/info/refs?service=git-receive-pack`, `${path}/git-receive-pack`, `${path}/objects/${foreign}`]; + const results = await Promise.all(requests.map(p => fetch(new URL(p, relay.url)))); + expect(results.map(r => r.status)).toEqual(requests.map(() => 403)); + expect(upstream.facts.length).toBe(before); + const [other, permitted] = await Promise.all([ + git(fixture.root, "ls-remote", `${upstream.server.url}odysseus/navigation.git`, "refs/heads/main"), + git(fixture.root, ...rewrite(), "ls-remote", fake(), "refs/heads/main"), + ]); + expect(other.code).toBe(0); expect(permitted.code).toBe(0); + expect(upstream.facts.filter(x => x.path.startsWith("/odysseus/")).every(x => x.authorized)).toBe(true); +}); + +test("fixed host acquisition isolates two principals, grants and credentials and evaluates content offline", async () => { + const db = createUiDb(":memory:"), launches: MaintenanceCommand[] = []; + const transport = createReferenceTransport({ brainPath: fixture.dir("brain"), run: localRunner(launches) }); + const sources = createReferenceSources({ db, pool: referencePoolDouble(fixture.dir("pool")), transport, brain: "ithaca", + credentials: { GITHUB_TOKEN: TOKEN } }); + const odysseus = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const penelope = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + const publicURL = `${upstream.server.url}odysseus/navigation.git`, privateURL = `${upstream.server.url}penelope/loom.git`; + try { + await expect(sources.request({ principalId: penelope.id, repository: privateURL, revision: "main" }), "AVAILABLE_CREDENTIAL_IS_NOT_AUTHORITY").rejects.toMatchObject({ code: "unauthorized" }); + const grant = createReferenceGrant(db, { brain: "ithaca", principalId: penelope.id, repositoryPrefix: privateURL, credential: "GITHUB_TOKEN", createdBy: penelope.id, now: Date.now() }); + const [navigation, loom] = await Promise.all([ + sources.request({ principalId: odysseus.id, repository: publicURL, revision: "main" }), + sources.request({ principalId: penelope.id, repository: privateURL, revision: "main" }), + ]); + expect(navigation.domain).toBe("public"); expect(loom.domain).toBe("private"); expect(loom.commit).toBe(main); + const root = join(loom.viewPath, loom.name), expected = await checked(privateBare, "show", "main:README.md"); + expect(await immutableBlob(join(root, ".git"), loom.commit, "README.md")).toBe(expected); + await expect(immutableBlob(join(root, ".git"), loom.commit, "escape")).rejects.toThrow("not an immutable regular blob"); + await expect(immutableBlob(join(root, ".git"), loom.commit, "nested")).rejects.toThrow("not an immutable regular blob"); + await expect(immutableBlob(join(root, ".git"), loom.commit, "../outside")).rejects.toThrow("unsupported path"); + expect(existsSync(join(root, "foreign.md"))).toBe(false); + expect((await git(root, "cat-file", "-e", `${foreign}^{commit}`)).code, "FIXED_REF_FETCH_OMITS_FOREIGN_COMMIT").not.toBe(0); + // Worker edits and origin rewrites do not change the selected immutable Git object. + writeFileSync(join(root, "README.md"), "Unverified worker edit\n"); + await checked(root, "config", "remote.origin.url", "https://ithaca.invalid/foreign.git"); + expect(await immutableBlob(join(root, ".git"), loom.commit, "README.md")).toBe(expected); + await expect(sources.request({ principalId: odysseus.id, repository: privateURL, revision: "main" })).rejects.toMatchObject({ code: "unauthorized" }); + const credentialed = launches.filter(x => x.env?.BRAIN_REFERENCE_TOKEN === TOKEN); + expect(credentialed.length).toBeGreaterThan(0); + expect(credentialed.every(x => x.command.includes("ls-remote") || x.command.includes("fetch"))).toBe(true); + const checkout = launches.filter(x => x.command.includes("checkout")); + expect(checkout.length).toBeGreaterThan(0); + expect(checkout.every(x => !x.credentials && !x.transport?.network && !x.env?.BRAIN_REFERENCE_TOKEN), "CHECKOUT_HAS_NO_CREDENTIAL_OR_NETWORK_AUTHORITY").toBe(true); + expect(credentialed.every(x => x.command.includes(privateURL))).toBe(true); + navigation.release(); loom.release(); + revokeReferenceGrant(db, { brain: "ithaca", principalId: penelope.id, id: grant.id, now: Date.now() }); + await sources.revoke({ grantIds: [grant.id], principalIds: [] }); + await expect(sources.request({ principalId: penelope.id, repository: privateURL, revision: "main" }), "REVOKED_GRANT_REFUSES_CACHED_SOURCE").rejects.toMatchObject({ code: "unauthorized" }); + } finally { await sources.close(); db.close(); } +}); + +test("production branch/tag resolver refuses direct PR and object selection; redirects remain disabled", async () => { + const launches: MaintenanceCommand[] = [], transport = createReferenceTransport({ brainPath: fixture.root, run: localRunner(launches) }); + const repository = referenceRepository(`${upstream.server.url}odysseus/navigation.git`); + expect(await transport.resolve({ repository, revision: referenceRevision("main"), token: null })).toMatchObject({ ok: true, ref: "refs/heads/main" }); + expect(await transport.resolve({ repository, revision: referenceRevision("voyage"), token: null })).toMatchObject({ ok: true, ref: "refs/tags/voyage" }); + expect(() => referenceRevision(foreign)).toThrow(); + expect(await transport.resolve({ repository: referenceRepository(`${upstream.server.url}penelope/loom.git`), revision: referenceRevision("refs/pull/7/head"), token: TOKEN })).toMatchObject({ ok: false, reason: "missing" }); + for (const input of ["git@ithaca.invalid:odysseus/navigation", "ssh://ithaca.invalid/odysseus/navigation", "ext::sentinel", "https://ithaca.invalid/a%2fb", "https://ithaca.invalid/a/../b"]) expect(() => referenceRepository(input)).toThrow(); + const before = upstream.facts.length; + const redirect = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return Response.redirect(`${upstream.server.url}penelope/loom.git/info/refs?service=git-upload-pack`, 302); } }); + try { + expect(await transport.resolve({ repository: referenceRepository(`${redirect.url}odysseus/navigation.git`), revision: "main", token: TOKEN })).toMatchObject({ ok: false }); + expect(upstream.facts.length, "REDIRECT_NEVER_RECEIVES_CREDENTIAL_OR_REQUEST").toBe(before); + } finally { redirect.stop(true); } +}); + +test("a real stalled Git request is cancelled and does not produce a source", async () => { + let started!: () => void; + const entered = new Promise(resolve => { started = resolve; }); + const stalled = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { started(); return new Promise(() => {}); } }); + const launches: MaintenanceCommand[] = [], controller = new AbortController(); + const transport = createReferenceTransport({ brainPath: fixture.root, run: localRunner(launches), timeoutMs: 2000 }); + try { + const pending = transport.resolve({ repository: referenceRepository(`${stalled.url}penelope/loom.git`), revision: "main", token: TOKEN, signal: controller.signal }); + await entered; const abortedAt = performance.now(); controller.abort(); + expect(await pending, "CANCELLED_GIT_NEVER_REPORTS_A_COMMIT").toMatchObject({ ok: false, reason: "unavailable" }); + expect(performance.now() - abortedAt, "CANCELLATION_STOPS_GIT_HELPER_TREE_PROMPTLY").toBeLessThan(1500); + expect(launches.length).toBe(1); + } finally { stalled.stop(true); } +}); + +test("exact identity follows rename within approved owner, never transfer/name reuse; owner scope includes future repos", () => { + const repo = { kind: "repo", id: "repository-ithaca-1", owner: "odysseus" } as const; + expect(matches(repo, { id: repo.id, owner: "ODYSSEUS", name: "renamed" })).toBe(true); + expect(matches(repo, { id: repo.id, owner: "penelope", name: "navigation" })).toBe(false); + expect(matches(repo, { id: "replacement", owner: "odysseus", name: "navigation" })).toBe(false); + expect(matches(repo, null)).toBe(false); + expect(matches({ kind: "owner", owner: "odysseus" }, { id: "future", owner: "odysseus", name: "new-voyage" })).toBe(true); + expect(matches({ kind: "owner", owner: "odysseus" }, { id: "future", owner: "odysseus-crew", name: "new-voyage" })).toBe(false); +}); diff --git a/experiments/git-read-qualification.ts b/experiments/git-read-qualification.ts new file mode 100644 index 0000000000..649b6225be --- /dev/null +++ b/experiments/git-read-qualification.ts @@ -0,0 +1,112 @@ +/** #3612 offline qualification only. Nothing here is imported by production. */ +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; +import type { runMaintenanceWorker } from "@schlessera/brain-ui-sdk/internal"; + +export const gitEnv = { PATH: "/usr/bin:/bin", HOME: "/nonexistent", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", + GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "/bin/false", GIT_AUTHOR_NAME: "Odysseus", GIT_AUTHOR_EMAIL: "odysseus@ithaca.example", + GIT_COMMITTER_NAME: "Odysseus", GIT_COMMITTER_EMAIL: "odysseus@ithaca.example", GIT_AUTHOR_DATE: "2026-07-12T10:00:00Z", GIT_COMMITTER_DATE: "2026-07-12T10:00:00Z" }; +export interface Exit { code: number; stdout: string; stderr: string } +export const receipts: { args: string[]; code: number }[] = []; +export async function git(cwd: string, ...args: string[]): Promise { + const child = Bun.spawn(["/usr/bin/git", "-C", cwd, ...args], { env: gitEnv, stdout: "pipe", stderr: "pipe", timeout: 10_000 }); + const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + receipts.push({ args, code }); + return { code, stdout: stdout.trim(), stderr }; +} +export async function checked(cwd: string, ...args: string[]): Promise { + const result = await git(cwd, ...args); + if (result.code !== 0) throw new Error(`git ${args[0]} exit ${result.code}: ${result.stderr}`); + return result.stdout; +} + +/** Execute the production transport's exact argv/env with real Git, not its native sandbox. */ +export function localRunner(launches: MaintenanceCommand[]): typeof runMaintenanceWorker { + return (async (input: MaintenanceCommand & { signal?: AbortSignal; timeoutMs?: number }) => { + launches.push(input); + input.signal?.throwIfAborted(); + // Keep the experiment's real Git helper tree bounded too. This is not the production launcher. + const child = Bun.spawn(["/usr/bin/setsid", ...input.command], { env: input.env, stdout: "pipe", stderr: "pipe" }); + let killed = false; + const stop = () => { killed = true; try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } }; + input.signal?.addEventListener("abort", stop, { once: true }); + const timer = setTimeout(stop, Math.min(input.timeoutMs ?? 10_000, 10_000)); + try { + const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + receipts.push({ args: ["setsid", ...input.command], code: exitCode }); + return { stdout, stderr, exitCode, killed }; + } finally { clearTimeout(timer); input.signal?.removeEventListener("abort", stop); } + }) as typeof runMaintenanceWorker; +} + +export interface Repo { path: string; directory: string; token: string | null } +export interface RequestFact { path: string; protocol: string | null; authorized: boolean; body: string } +export function origin(repos: Repo[]) { + const facts: RequestFact[] = []; + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { + const url = new URL(request.url), repo = repos.find(item => url.pathname.startsWith(`${item.path}/`)); + if (!repo) return new Response("not found", { status: 404 }); + const token = repo.token, auth = request.headers.get("authorization"); + const authorized = token === null ? auth === null : auth === `Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`; + const body = new Uint8Array(await request.arrayBuffer()), protocol = request.headers.get("git-protocol"); + facts.push({ path: url.pathname, protocol, authorized, body: new TextDecoder().decode(body) }); + if (!authorized) return new Response("credentials required", { status: 401, headers: { "WWW-Authenticate": 'Basic realm="ithaca"' } }); + const child = Bun.spawn(["/usr/bin/git", "http-backend"], { stdin: body, stdout: "pipe", stderr: "pipe", env: { + ...gitEnv, GIT_PROJECT_ROOT: repo.directory, GIT_HTTP_EXPORT_ALL: "1", HTTP_GIT_PROTOCOL: protocol ?? "", + REQUEST_METHOD: request.method, PATH_INFO: url.pathname.slice(repo.path.length), QUERY_STRING: url.search.slice(1), + CONTENT_TYPE: request.headers.get("content-type") ?? "", CONTENT_LENGTH: String(body.length), + } }); + const [output, stderr, code] = await Promise.all([new Response(child.stdout).arrayBuffer(), new Response(child.stderr).text(), child.exited]); + receipts.push({ args: ["http-backend", url.pathname], code }); + if (code !== 0) return new Response(stderr, { status: 500 }); + const bytes = Buffer.from(output), separator = bytes.indexOf("\r\n\r\n"), headers = new Headers(); + if (separator < 0) throw new Error("missing CGI headers"); + let status = 200; + for (const line of bytes.subarray(0, separator).toString().split("\r\n")) { + const colon = line.indexOf(":"), name = line.slice(0, colon), value = line.slice(colon + 1).trim(); + if (name.toLowerCase() === "status") status = Number(value.split(" ")[0]); else headers.append(name, value); + } + return new Response(bytes.subarray(separator + 4), { status, headers }); + } }); + return { server, facts }; +} + +/** Deliberately insufficient candidate: endpoint filtering does not bind protocol-v2 refs. */ +export function candidateRelay(upstream: URL, path: string, token: string) { + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { + const url = new URL(request.url); + const discovery = request.method === "GET" && url.pathname === `${path}/info/refs` && url.search === "?service=git-upload-pack"; + const read = request.method === "POST" && url.pathname === `${path}/git-upload-pack` && url.search === ""; + if (!discovery && !read) return new Response("unsupported", { status: 403 }); + const headers = new Headers({ authorization: `Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}` }); + for (const name of ["content-type", "git-protocol"]) if (request.headers.has(name)) headers.set(name, request.headers.get(name)!); + return fetch(new URL(url.pathname + url.search, upstream), { method: request.method, headers, redirect: "manual", + ...(read ? { body: await request.arrayBuffer() } : {}) }); + } }); + return server; +} + +export function scratch() { + const root = mkdtempSync(join(tmpdir(), "git-read-qualification-")); + return { root, dir(name: string) { const path = join(root, name); mkdirSync(path, { recursive: true }); return path; }, + close() { rmSync(root, { force: true, recursive: true }); } }; +} + +export interface Identity { id: string; owner: string; name: string } +export type Selector = { kind: "repo"; id: string; owner: string } | { kind: "owner"; owner: string }; +/** Fixture for the selected restrictive identity semantics; metadata must be host-verified. */ +export function matches(selector: Selector, identity: Identity | null): boolean { + return identity !== null && identity.owner.toLowerCase() === selector.owner.toLowerCase() + && (selector.kind === "owner" || identity.id === selector.id); +} + +/** Host-bound immutable objects only: never open the worker's mutable worktree path. */ +export async function immutableBlob(mirror: string, commit: string, path: string): Promise { + if (!/^[0-9a-f]{40}$/.test(commit) || !/^[A-Za-z0-9._/-]+$/.test(path) || path.split("/").some(x => !x || x === "." || x === ".." || x === ".git")) throw new Error("unsupported path"); + const entry = await checked(mirror, "ls-tree", commit, "--", path); + if (!/^(100644|100755) blob [0-9a-f]{40}\t/.test(entry) || entry.split("\n").length !== 1) throw new Error("not an immutable regular blob"); + const oid = entry.split(" ")[2]!.split("\t")[0]!; + return checked(mirror, "cat-file", "blob", oid); +}