From b47996bfda9379cdb1f055a4011be625b8a8dac8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 13:26:27 +0000 Subject: [PATCH 1/8] fix(ui-server): refuse reference commits that moved during acquisition --- .../ui-server/src/brain/reference-source.ts | 5 +++-- .../ui-server/tests/reference-source.test.ts | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 39eda68da1..3d94ac2042 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -321,7 +321,7 @@ export function createReferenceSources(options: { return { kind: "source", row: row(domain, repository.canonical, revision)!, stale: false, error: null }; } try { - await acquire(signal, { ...input, credential, ref: check.ref, previous: existing }); + await acquire(signal, { ...input, credential, ref: check.ref, expectedCommit: check.commit, previous: existing }); return { kind: "source", row: row(domain, repository.canonical, revision)!, stale: false, error: null }; } catch (error) { if (signal.aborted) throw error; @@ -402,7 +402,7 @@ export function createReferenceSources(options: { } async function acquire(signal: AbortSignal, input: { domain: string; principalId: string | null; repository: ReferenceRepository; revision: string; grant: ReferenceGrant | null; - credential: string | null; ref: string; previous: SourceRow | null }) { + credential: string | null; ref: string; expectedCommit: string; previous: SourceRow | null }) { const { domain, repository, revision } = input, key = sourceKey(domain, repository.canonical, revision); const name = referenceSourceName(repository, revision), view = await viewFor(domain); const staging = { id: randomUUID() }; @@ -414,6 +414,7 @@ export function createReferenceSources(options: { const record = await create(staging, previousRoot, signal, key); recheck(); const { commit } = await transport.fetch({ repository, ref: input.ref, token: input.credential, root: record.path!, signal }); + if (commit !== input.expectedCommit) throw new ReferenceTransportError("unavailable", "The reference moved after resolution; request it again."); await transport.checkout({ root: record.path!, commit, signal }); signal.throwIfAborted(); recheck(); diff --git a/packages/ui-server/tests/reference-source.test.ts b/packages/ui-server/tests/reference-source.test.ts index 3c72fbb182..f66e128666 100644 --- a/packages/ui-server/tests/reference-source.test.ts +++ b/packages/ui-server/tests/reference-source.test.ts @@ -86,6 +86,26 @@ function service(options: { limits?: Record; capacityRoots?: num const read = (lease: ReferenceSourceLease) => readFileSync(join(lease.viewPath, lease.name, "README.md"), "utf8").trim(); const minutes = (count: number) => { clock += count * 60_000; }; +test("a ref that moves after resolution is refused before source publication", async () => { + const { sources, state, repos } = service(); + const principal = owner(); + const held = deferred(); + state.gate = held; + const pending = sources.request({ principalId: principal.id, repository: PUBLIC, revision: "main" }); + try { + await until(() => state.fetches.length === 1); + expect(state.fetches, "REFERENCE_MOVED_REF_FETCH_REACHED_BARRIER").toHaveLength(1); + repos.get(PUBLIC)!.tip = "f".repeat(40); + held.resolve(); + await expect(pending, "REFERENCE_MOVED_REF_NOT_PUBLISHED").rejects.toMatchObject({ code: "unavailable" }); + expect(db.query("SELECT * FROM reference_sources WHERE root_id IS NOT NULL").all(), "REFERENCE_MOVED_REF_NO_VISIBLE_SOURCE").toEqual([]); + } finally { + held.resolve(); + await pending.then(lease => lease.release(), () => {}); + await sources.close(); + } +}); + describe("authority and sharing domains", () => { test("public source is shared host-wide and only ever fetched anonymously", async () => { const { sources, state } = service(); From 93a2b87970adc10eafd02a8154962aafe1d33108 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 14:44:26 +0000 Subject: [PATCH 2/8] feat(ui-server): validate fixed GitHub reference identities --- .../src/brain/github-reference-identity.ts | 62 +++++++++++++++++++ .../tests/github-reference-identity.test.ts | 59 ++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 packages/ui-server/src/brain/github-reference-identity.ts create mode 100644 packages/ui-server/tests/github-reference-identity.test.ts diff --git a/packages/ui-server/src/brain/github-reference-identity.ts b/packages/ui-server/src/brain/github-reference-identity.ts new file mode 100644 index 0000000000..aba48b14bb --- /dev/null +++ b/packages/ui-server/src/brain/github-reference-identity.ts @@ -0,0 +1,62 @@ +/** Fixed GitHub metadata validation. Parsing alone establishes no transport, access or source trust. */ +import { parseTrustGithub, TrustSelectorSchema } from "@schlessera/brain-common/internal/governance-policy"; + +export interface GitHubReferenceRepository { + owner: string; + repository: string; + canonical: string; + cloneUrl: string; + metadataUrl: string; +} + +export interface GitHubReferenceIdentity extends GitHubReferenceRepository { + repositoryId: string; + ownerId: string; + private: boolean; +} + +/** Reject ambiguous syntax before a URL parser can erase traversal or separators. */ +export function githubReferenceRepository(input: unknown): GitHubReferenceRepository { + if (typeof input !== "string") throw new Error("Use one canonical GitHub owner/repository"); + const location = parseTrustGithub(input.replace(/^https:\/\/github\.com\//iu, "https://github.com/")); + if (!location.repository) throw new Error("A repository is required for reference acquisition"); + const { owner, repository } = location; + const canonical = `https://github.com/${owner}/${repository}`; + return { owner, repository, canonical, cloneUrl: `${canonical}.git`, metadataUrl: `https://api.github.com/repos/${owner}/${repository}` }; +} + +function providerId(value: unknown): string { + if (typeof value === "number") { + if (!Number.isSafeInteger(value) || value < 1) throw new Error("GitHub metadata has an unsupported stable identity"); + value = String(value); + } + if (typeof value !== "string" || !/^[1-9][0-9]{0,19}$/u.test(value)) throw new Error("GitHub metadata has an unsupported stable identity"); + return value; +} + +/** Validate only the fields the fixed host request consumes; no worker claims become verification flags. */ +export function parseGitHubReferenceMetadata(repository: unknown, input: unknown): GitHubReferenceIdentity { + const requested = githubReferenceRepository(repository); + if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("GitHub identity metadata is unavailable"); + const value = input as Record; + const owner = value.owner; + if (!owner || typeof owner !== "object" || Array.isArray(owner)) throw new Error("GitHub owner identity metadata is unavailable"); + const details = owner as Record; + if (typeof details.login !== "string" || typeof value.name !== "string") throw new Error("GitHub metadata has invalid repository names"); + const selector = TrustSelectorSchema.parse({ kind: "github_repository", host: "github.com", owner: details.login.toLowerCase(), + repository: value.name.toLowerCase(), repositoryId: providerId(value.id) }); + if (selector.kind !== "github_repository") throw new Error("GitHub repository identity is unavailable"); + if (selector.owner !== requested.owner || selector.repository !== requested.repository) + throw new Error("GitHub metadata does not match the requested repository"); + if (typeof value.full_name !== "string" || value.full_name.toLowerCase() !== `${requested.owner}/${requested.repository}` + || typeof value.clone_url !== "string" || value.clone_url.toLowerCase() !== requested.cloneUrl + || typeof value.url !== "string" || value.url.toLowerCase() !== requested.metadataUrl + || typeof value.private !== "boolean") throw new Error("GitHub metadata does not bind the fixed repository transport"); + return { ...requested, repositoryId: selector.repositoryId, ownerId: providerId(details.id), private: value.private }; +} + +/** Both observations must describe one unchanged acquisition; this does not authorize either observation. */ +export function sameGitHubReferenceIdentity(before: GitHubReferenceIdentity, after: GitHubReferenceIdentity): boolean { + return before.repositoryId === after.repositoryId && before.ownerId === after.ownerId + && before.canonical === after.canonical && before.private === after.private; +} diff --git a/packages/ui-server/tests/github-reference-identity.test.ts b/packages/ui-server/tests/github-reference-identity.test.ts new file mode 100644 index 0000000000..2248f5aa26 --- /dev/null +++ b/packages/ui-server/tests/github-reference-identity.test.ts @@ -0,0 +1,59 @@ +import { expect, test } from "bun:test"; +import { githubReferenceRepository, parseGitHubReferenceMetadata, sameGitHubReferenceIdentity } from "../src/brain/github-reference-identity"; + +function metadata(overrides: Record = {}): Record { + return { id: 101, owner: { id: 201, login: "Odysseus" }, name: "Ithaca", full_name: "Odysseus/Ithaca", + clone_url: "https://github.com/Odysseus/Ithaca.git", url: "https://api.github.com/repos/Odysseus/Ithaca", private: false, ...overrides }; +} + +test("one canonical repository fixes both Git and metadata recipients", () => { + const expected = { owner: "odysseus", repository: "ithaca", canonical: "https://github.com/odysseus/ithaca", + cloneUrl: "https://github.com/odysseus/ithaca.git", metadataUrl: "https://api.github.com/repos/odysseus/ithaca" }; + for (const input of ["Odysseus/Ithaca", "https://github.com/Odysseus/Ithaca.git", "HTTPS://GITHUB.COM/Odysseus/Ithaca"]) + expect(githubReferenceRepository(input), "GITHUB_REFERENCE_FIXED_RECIPIENTS").toEqual(expected); + expect(githubReferenceRepository("odysseus/charts.git.git").repository, "one optional transport suffix is removed").toBe("charts.git"); +}); + +test("userinfo, helpers, traversal, other recipients and extra path segments are refused before URL normalization", () => { + for (const input of [undefined, null, 7, "odysseus", "odysseus/.", "odysseus/..", "odysseus//ithaca", "odysseus/ithaca/extra", + "odysseus/ithaca/", "odysseus/../ithaca", "-odysseus/ithaca", "ody--sseus/ithaca", "odysseus/ithaca?x=1", + "https://github.com/odysseus/../ithaca", "https://github.com/odysseus%2fcrew/ithaca", "https://github.com/odysseus/ithaca%2fextra", + "https://github.com@calypso.example/odysseus/ithaca", "https://token@github.com/odysseus/ithaca", "https://github.com:443/odysseus/ithaca", + "https://github.com./odysseus/ithaca", "https://github.com.evil.example/odysseus/ithaca", "http://github.com/odysseus/ithaca", + "git@github.com:odysseus/ithaca", "ext::git anything", "file:///odysseus/ithaca", " odysseus/ithaca", "odysseus/ithaca "]) + expect(() => githubReferenceRepository(input), "GITHUB_REFERENCE_AMBIGUOUS_LOCATION_REFUSED").toThrow(); +}); + +test("metadata binds independent stable repository and owner identities to the requested transport", () => { + const identity = parseGitHubReferenceMetadata("odysseus/ithaca", metadata()); + expect(identity).toEqual({ ...githubReferenceRepository("odysseus/ithaca"), repositoryId: "101", ownerId: "201", private: false }); + expect(Object.keys(identity)).not.toContain("verifiedBy"); + expect(() => parseGitHubReferenceMetadata("penelope/ithaca", metadata()), "GITHUB_REFERENCE_FOREIGN_OWNER_REFUSED").toThrow(); + expect(() => parseGitHubReferenceMetadata("odysseus/loom", metadata()), "GITHUB_REFERENCE_FOREIGN_REPOSITORY_REFUSED").toThrow(); +}); + +test("the API document cannot substitute a remote, generic endpoint or differently named source", () => { + for (const changes of [{ full_name: "penelope/ithaca" }, { clone_url: "https://github.com/penelope/ithaca.git" }, + { clone_url: "https://github.com/odysseus/ithaca.git?service=git-receive-pack" }, { clone_url: "ssh://git@github.com/odysseus/ithaca" }, + { url: "https://api.github.com/repos/penelope/ithaca" }, { url: "https://api.github.com/repositories/101" }, { private: "false" }, + { owner: { id: 201, login: "odysseus/crew" } }, { name: "../ithaca" }, { full_name: undefined }, { clone_url: undefined }, { url: undefined }]) + expect(() => parseGitHubReferenceMetadata("odysseus/ithaca", metadata(changes)), "GITHUB_REFERENCE_METADATA_TRANSPORT_BOUND").toThrow(); +}); + +test("stable IDs never round or acquire a value from an absent or malformed field", () => { + for (const id of [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, "0", "01", "1e2", "-1", "1.0", "1".repeat(21), null, undefined]) { + expect(() => parseGitHubReferenceMetadata("odysseus/ithaca", metadata({ id })), "GITHUB_REFERENCE_REPOSITORY_ID_EXACT").toThrow(); + expect(() => parseGitHubReferenceMetadata("odysseus/ithaca", metadata({ owner: { id, login: "Odysseus" } })), "GITHUB_REFERENCE_OWNER_ID_EXACT").toThrow(); + } + expect(parseGitHubReferenceMetadata("odysseus/ithaca", metadata({ id: "12345678901234567890" })).repositoryId).toBe("12345678901234567890"); +}); + +test("transfer, namespace reassignment, name reuse and privacy changes cannot be one unchanged acquisition", () => { + const original = parseGitHubReferenceMetadata("odysseus/ithaca", metadata()); + expect(sameGitHubReferenceIdentity(original, parseGitHubReferenceMetadata("odysseus/ithaca", metadata()))).toBe(true); + for (const changed of [metadata({ id: 102 }), metadata({ owner: { id: 202, login: "Odysseus" } }), metadata({ private: true })]) + expect(sameGitHubReferenceIdentity(original, parseGitHubReferenceMetadata("odysseus/ithaca", changed)), "GITHUB_REFERENCE_CHANGED_IDENTITY_REFUSED").toBe(false); + const renamed = parseGitHubReferenceMetadata("odysseus/argo", metadata({ name: "argo", full_name: "Odysseus/Argo", + clone_url: "https://github.com/Odysseus/Argo.git", url: "https://api.github.com/repos/Odysseus/Argo" })); + expect(sameGitHubReferenceIdentity(original, renamed), "a rename needs fresh validation, not an in-flight substitution").toBe(false); +}); From 1702eef15c97707d34c7428f076f165c8c23e376 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 14:51:24 +0000 Subject: [PATCH 3/8] CONTRACT: feat(ui-server): require explicit GitHub metadata credential permission --- .../ithaca-reference-metadata-permission.md | 5 ++ docs/http-api.md | 12 +++- docs/integration-contract/http.md | 12 ++++ .../088_reference_metadata_recipient.sql | 4 ++ packages/ui-server/src/db/reference-grants.ts | 25 +++++--- .../ui-server/src/middleware/principals.ts | 6 +- .../tests/account-writes-offloop.test.ts | 23 ++++++- .../ui-server/tests/reference-grants.test.ts | 61 +++++++++++++++++++ 8 files changed, 137 insertions(+), 11 deletions(-) create mode 100644 .changeset/ithaca-reference-metadata-permission.md create mode 100644 packages/ui-server/migrations/088_reference_metadata_recipient.sql diff --git a/.changeset/ithaca-reference-metadata-permission.md b/.changeset/ithaca-reference-metadata-permission.md new file mode 100644 index 0000000000..e7c6fb1adb --- /dev/null +++ b/.changeset/ithaca-reference-metadata-permission.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +Add separate owner permission for the fixed GitHub identity metadata credential recipient. Existing repository access grants keep their original recipient authority. diff --git a/docs/http-api.md b/docs/http-api.md index 70c948b582..5c2751b7ca 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -530,7 +530,8 @@ itself. for that principal's live grants, oldest first; `created_at` is epoch milliseconds. An unknown, revoked, expired or non-cookie principal is 404. - **POST `/api/auth/principals/:id/reference-grants`**, JSON body - `{ repositoryPrefix: string, credential?: string | null }`. The prefix is an + `{ repositoryPrefix: string, credential?: string | null, + metadataCredentialRecipient?: "https://api.github.com" | null }`. The prefix is an HTTPS URL without user info, query or fragment, a loopback `http://` URL, or an absolute `file:///` path; it may be a bare HTTPS origin. Empty, `.` and `..` segments, whitespace, control characters, backslashes and percent-encoding @@ -543,6 +544,15 @@ itself. is 201 with the grant object. Malformed or non-object JSON is 400; an unknown or unusable target principal is 404; an identical live grant is 409; 256 live grants is 503. + The optional `metadataCredentialRecipient` is independent owner permission + to send that named credential to the fixed GitHub identity metadata operation + (#3613). It requires a GitHub HTTPS prefix and a non-null named credential; + any other value or recipient is 400. Omitted or null grants no API recipient + permission, including on migrated records. When explicitly granted, the + response and list entry additionally carry + `metadata_credential_recipient: "https://api.github.com"`. The permission + shares the grant's brain, principal, repository scope and live revocation. + It grants neither generic HTTP access nor repository source trust. - **DELETE `/api/auth/principals/:id/reference-grants/:grantId`**, body ignored, revokes that principal's live grant and returns `{ ok: true }`. Revocation applies to the next authority check, including in-flight private diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 421460b697..192032acde 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1129,6 +1129,18 @@ its principal applies to the next authority check, including in-flight private refreshes. The routes add no credential storage and return no credential value. The [grant decision](../decisions/reference-source-grants.md) records the ruling. +Additive #3613: grant creation also accepts optional +`metadataCredentialRecipient: "https://api.github.com" | null`. Only an owner +may give this separate fixed metadata credential-recipient permission on a +GitHub HTTPS grant with a named credential. Other recipients and +credentialless/non-GitHub grants are refused. Existing and omitted/null grants +have no additional permission. Explicit permission persists through the shared +FULL writer and is returned as optional +`metadata_credential_recipient: "https://api.github.com"` in create/list +receipts; legacy receipt shapes remain unchanged. It shares the live grant's +brain/principal/repository scope and revocation. The field establishes no +transport or source-trust qualification and exposes no generic API relay. + ## Content renderer bootstrap declarations (additive, #2087) Authenticated `GET /api/status` includes optional `contentRenderers`, an array of diff --git a/packages/ui-server/migrations/088_reference_metadata_recipient.sql b/packages/ui-server/migrations/088_reference_metadata_recipient.sql new file mode 100644 index 0000000000..f6dd2c2748 --- /dev/null +++ b/packages/ui-server/migrations/088_reference_metadata_recipient.sql @@ -0,0 +1,4 @@ +-- Separate, explicit owner permission for a fixed GitHub metadata recipient. +-- Existing reference grants do not acquire another credential recipient. +ALTER TABLE reference_grants ADD COLUMN metadata_credential_recipient TEXT + CHECK (metadata_credential_recipient IS NULL OR metadata_credential_recipient = 'https://api.github.com'); diff --git a/packages/ui-server/src/db/reference-grants.ts b/packages/ui-server/src/db/reference-grants.ts index abc5e28088..72b5d13c6a 100644 --- a/packages/ui-server/src/db/reference-grants.ts +++ b/packages/ui-server/src/db/reference-grants.ts @@ -17,6 +17,7 @@ export const REFERENCE_GRANT_RETENTION_MS = 30 * 24 * 60 * 60 * 1_000; const MAX_REPOSITORY_LENGTH = 2048; const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]); const GITHUB = "https://github.com"; +export const REFERENCE_METADATA_CREDENTIAL_RECIPIENT = "https://api.github.com"; /** * Existing host credential selectors a grant may name, and the origin each may @@ -92,15 +93,19 @@ export interface ReferenceGrant { principalId: string; repositoryPrefix: string; credential: string | null; + /** Explicit owner permission for the fixed identity operation; absent on legacy grants. */ + metadataCredentialRecipient?: typeof REFERENCE_METADATA_CREDENTIAL_RECIPIENT; createdBy: string; createdAt: number; revokedAt: number | null; } -interface GrantRow { id: string; brain: string; principal_id: string; repository_prefix: string; credential: string | null; created_by: string; created_at: number; revoked_at: number | null } -const COLUMNS = "g.id, g.brain, g.principal_id, g.repository_prefix, g.credential, g.created_by, g.created_at, g.revoked_at"; +interface GrantRow { id: string; brain: string; principal_id: string; repository_prefix: string; credential: string | null; created_by: string; created_at: number; revoked_at: number | null; + metadata_credential_recipient: typeof REFERENCE_METADATA_CREDENTIAL_RECIPIENT | null } +const COLUMNS = "g.id, g.brain, g.principal_id, g.repository_prefix, g.credential, g.created_by, g.created_at, g.revoked_at, g.metadata_credential_recipient"; const fromRow = (row: GrantRow): ReferenceGrant => ({ id: row.id, brain: row.brain, principalId: row.principal_id, repositoryPrefix: row.repository_prefix, - credential: row.credential, createdBy: row.created_by, createdAt: row.created_at, revokedAt: row.revoked_at }); + credential: row.credential, createdBy: row.created_by, createdAt: row.created_at, revokedAt: row.revoked_at, + ...(row.metadata_credential_recipient ? { metadataCredentialRecipient: row.metadata_credential_recipient } : {}) }); /** A live grant has no revocation and a usable cookie-bearing principal. */ const LIVE = `g.revoked_at IS NULL AND p.revoked_at IS NULL AND p.expires_at > ? AND p.kind IN ('owner', 'agent')`; @@ -116,12 +121,18 @@ export class ReferenceGrantDuplicateError extends Error { export function createReferenceGrant(db: Database, input: { brain: string; principalId: string; repositoryPrefix: unknown; credential: unknown; createdBy: string; now: number; + metadataCredentialRecipient?: unknown; }): ReferenceGrant { const prefix = referenceRepository(input.repositoryPrefix, { prefix: true }); if (input.credential !== null && typeof input.credential !== "string") throw new ReferenceRepositoryError("credential must be a string or null"); assertGrantCredential(input.credential, prefix); + const metadataRecipient = input.metadataCredentialRecipient ?? null; + if (metadataRecipient !== null && (metadataRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT + || prefix.origin !== GITHUB || input.credential === null)) + throw new ReferenceRepositoryError("metadata credential permission requires the fixed API recipient, a GitHub prefix and a named host credential"); const grant: ReferenceGrant = { id: randomBytes(16).toString("base64url"), brain: input.brain, principalId: input.principalId, - repositoryPrefix: prefix.canonical, credential: input.credential, createdBy: input.createdBy, createdAt: input.now, revokedAt: null }; + repositoryPrefix: prefix.canonical, credential: input.credential, createdBy: input.createdBy, createdAt: input.now, revokedAt: null, + ...(metadataRecipient === REFERENCE_METADATA_CREDENTIAL_RECIPIENT ? { metadataCredentialRecipient: metadataRecipient } : {}) }; db.transaction(() => { const target = resolvePrincipal(db, input.principalId), creator = resolvePrincipal(db, input.createdBy); if (!target || !isCookieBearingPrincipal(target) || !isUsablePrincipal(target, input.now)) throw new ReferenceGrantPrincipalError(); @@ -131,8 +142,8 @@ export function createReferenceGrant(db: Database, input: { if (live.count >= MAX_LIVE_REFERENCE_GRANTS) throw new ReferenceGrantLimitError(); if (db.prepare(`SELECT 1 FROM reference_grants g WHERE g.revoked_at IS NULL AND g.brain = ? AND g.principal_id = ? AND g.repository_prefix = ? AND g.credential IS ?`) .get(grant.brain, grant.principalId, grant.repositoryPrefix, grant.credential)) throw new ReferenceGrantDuplicateError(); - db.prepare(`INSERT INTO reference_grants (id, brain, principal_id, repository_prefix, credential, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`) - .run(grant.id, grant.brain, grant.principalId, grant.repositoryPrefix, grant.credential, grant.createdBy, grant.createdAt); + db.prepare(`INSERT INTO reference_grants (id, brain, principal_id, repository_prefix, credential, created_by, created_at, metadata_credential_recipient) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) + .run(grant.id, grant.brain, grant.principalId, grant.repositoryPrefix, grant.credential, grant.createdBy, grant.createdAt, metadataRecipient); }).immediate(); return grant; } @@ -146,7 +157,7 @@ export function listReferenceGrants(db: Database, brain: string, principalId: st /** Revoke one live grant of this principal; returns it, or null when none matched. */ export function revokeReferenceGrant(db: Database, input: { brain: string; principalId: string; id: string; now: number }): ReferenceGrant | null { const row = db.prepare(`UPDATE reference_grants SET revoked_at = ? WHERE id = ? AND brain = ? AND principal_id = ? AND revoked_at IS NULL - RETURNING id, brain, principal_id, repository_prefix, credential, created_by, created_at, revoked_at`).get(input.now, input.id, input.brain, input.principalId) as GrantRow | null; + RETURNING id, brain, principal_id, repository_prefix, credential, created_by, created_at, revoked_at, metadata_credential_recipient`).get(input.now, input.id, input.brain, input.principalId) as GrantRow | null; return row ? fromRow(row) : null; } diff --git a/packages/ui-server/src/middleware/principals.ts b/packages/ui-server/src/middleware/principals.ts index 0643885b5b..d4f38047bf 100644 --- a/packages/ui-server/src/middleware/principals.ts +++ b/packages/ui-server/src/middleware/principals.ts @@ -56,6 +56,7 @@ function grantJson(grant: ReferenceGrant) { principal_id: grant.principalId, repository_prefix: grant.repositoryPrefix, credential: grant.credential, + ...(grant.metadataCredentialRecipient ? { metadata_credential_recipient: grant.metadataCredentialRecipient } : {}), created_by: grant.createdBy, created_at: grant.createdAt, }; @@ -225,9 +226,9 @@ export function principalManagementRoutes( }); app.post("/auth/principals/:id/reference-grants", requireJson(), async (c) => { - let body: { repositoryPrefix?: unknown; credential?: unknown }; + let body: { repositoryPrefix?: unknown; credential?: unknown; metadataCredentialRecipient?: unknown }; try { - const result = await readJsonBody<{ repositoryPrefix?: unknown; credential?: unknown }>(c); + const result = await readJsonBody(c); if (result instanceof Response) return result; if (!result || typeof result !== "object" || Array.isArray(result)) { return c.json({ error: "Invalid request body" }, 400); @@ -245,6 +246,7 @@ export function principalManagementRoutes( principalId, repositoryPrefix: body.repositoryPrefix, credential: body.credential === undefined ? null : body.credential, + metadataCredentialRecipient: body.metadataCredentialRecipient, createdBy: caller.id, now: Date.now(), }); diff --git a/packages/ui-server/tests/account-writes-offloop.test.ts b/packages/ui-server/tests/account-writes-offloop.test.ts index ab6b4b917c..68bef3c9db 100644 --- a/packages/ui-server/tests/account-writes-offloop.test.ts +++ b/packages/ui-server/tests/account-writes-offloop.test.ts @@ -11,7 +11,7 @@ import { openSqliteWriter } from "../src/db/write-worker.js"; import { createPrincipal, PrincipalCreatorNotUsableError, PrincipalCredentialNotFoundError, PrincipalLimitError, resolvePrincipal } from "../src/db/principals.js"; import { accountWrites, registerAccountWrites } from "../src/db/account-writes.js"; import { registerPrincipalWrites } from "../src/db/principal-writes.js"; -import { createReferenceGrant, ReferenceGrantDuplicateError, ReferenceGrantPrincipalError, ReferenceRepositoryError } from "../src/db/reference-grants.js"; +import { coveringReferenceGrant, createReferenceGrant, referenceRepository, ReferenceGrantDuplicateError, ReferenceGrantPrincipalError, ReferenceRepositoryError } from "../src/db/reference-grants.js"; import { principalManagementRoutes } from "../src/middleware/principals.js"; import { authGuard, authRoutes, createLoginRateLimiter, type AuthRuntime } from "../src/middleware/auth.js"; import { createPasskeyChallenges, passkeyManagementRoutes, passkeyPublicRoutes, type PasskeyContext, type PasskeyDeps } from "../src/middleware/passkeys.js"; @@ -70,6 +70,27 @@ for (const operation of ["mint", "revoke", "grant", "revokeGrant"] as const) { }); } +test("explicit metadata recipient commits through FULL account writes and a queued revoked owner cannot grant it", async () => { + const f = fixture(); + try { + const sites = await watchWriteSites(f.db, f.writer, ["reference_grants"]); + const input = { repositoryPrefix: "https://github.com/odysseus/ithaca", credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com" }; + const response = await f.app.request(`/api/auth/principals/${f.agent.id}/reference-grants`, json("POST", input)); + expect(response.status).toBe(201); + expect(await response.json(), "REFERENCE_API_PERMISSION_FULL_RECEIPT").toHaveProperty("metadata_credential_recipient", "https://api.github.com"); + expect(await sites.log(), "REFERENCE_API_PERMISSION_FULL_WRITER").toEqual(["reference_grants"]); + expect(coveringReferenceGrant(f.db, { brain: "ithaca", principalId: f.agent.id, + repository: referenceRepository(input.repositoryPrefix), now: Date.now() })).toHaveProperty("metadataCredentialRecipient", "https://api.github.com"); + const held = f.writer.channel(probe, { table: "odysseus_log" }); await held.ready; + const slow = held.call("slow", "Calypso", 150); + const revoke = accountWrites(f.db).revokePrincipal(f.owner.id, Date.now()); + const refused = expectRejection(accountWrites(f.db).createGrant({ ...input, repositoryPrefix: "https://github.com/odysseus/loom", + brain: "ithaca", principalId: f.agent.id, createdBy: f.owner.id, now: Date.now() }), ReferenceGrantPrincipalError, "REFERENCE_API_PERMISSION_RECHECKS_QUEUED_OWNER"); + await Promise.all([slow, revoke, refused]); + expect(f.db.query("SELECT 1 FROM reference_grants WHERE repository_prefix = ?").get("https://github.com/odysseus/loom")).toBeNull(); + } finally { await f.close(); } +}); + for (const operation of ["publicKey", "subscribe", "unsubscribe", "unbindPrincipal"] as const) { test(`push ${operation} commits on the write worker at FULL, never on the app connection`, async () => { const f = fixture(); diff --git a/packages/ui-server/tests/reference-grants.test.ts b/packages/ui-server/tests/reference-grants.test.ts index 2f71142ed6..9ddad3bae3 100644 --- a/packages/ui-server/tests/reference-grants.test.ts +++ b/packages/ui-server/tests/reference-grants.test.ts @@ -1,5 +1,8 @@ import { beforeEach, describe, expect, test } from "bun:test"; import { Hono } from "hono"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { generateSignedCookie } from "hono/cookie"; import type { AppEnv } from "../src/app-env"; @@ -66,6 +69,33 @@ describe("reference grant records", () => { expect(covering(telemachus.id, "https://github.com/odysseus/ithaca", "another-brain"), "REFERENCE_GRANT_BRAIN_SUBSTITUTION").toBeNull(); }); + test("API credential permission is explicit, durable and scoped to a live repository grant", () => { + const penelope = owner(), telemachus = agent(penelope.id); + const legacy = grant(telemachus.id, penelope.id, "https://github.com/odysseus", "GITHUB_TOKEN"); + expect(legacy).not.toHaveProperty("metadataCredentialRecipient"); + expect(covering(telemachus.id, "https://github.com/odysseus/ithaca")).not.toHaveProperty("metadataCredentialRecipient"); + const record = createReferenceGrant(db, { brain: BRAIN, principalId: telemachus.id, createdBy: penelope.id, + repositoryPrefix: "https://github.com/odysseus/ithaca", credential: "GITHUB_TOKEN", now: Date.now(), + metadataCredentialRecipient: "https://api.github.com" }); + expect(covering(telemachus.id, "https://github.com/odysseus/ithaca"), "REFERENCE_API_RECIPIENT_EXPLICITLY_PERSISTED") + .toHaveProperty("metadataCredentialRecipient", "https://api.github.com"); + expect(covering(penelope.id, "https://github.com/odysseus/ithaca"), "REFERENCE_API_PERMISSION_PRINCIPAL_BOUND").toBeNull(); + revokeReferenceGrant(db, { brain: BRAIN, principalId: telemachus.id, id: record.id, now: Date.now() }); + expect(covering(telemachus.id, "https://github.com/odysseus/ithaca")).not.toHaveProperty("metadataCredentialRecipient"); + }); + + test("API credential permission never accepts another recipient, a credentialless grant or another repository host", () => { + const penelope = owner(); + for (const [repositoryPrefix, credential, metadataCredentialRecipient] of [ + ["https://github.com/odysseus", "GITHUB_TOKEN", "https://github.com"], + ["https://github.com/odysseus", "GITHUB_TOKEN", "https://api.github.com.evil.example"], + ["https://github.com/odysseus", "GITHUB_TOKEN", true], + ["https://github.com/odysseus", null, "https://api.github.com"], + ["http://127.0.0.1:8418/odysseus", "GITHUB_TOKEN", "https://api.github.com"], + ]) expect(() => createReferenceGrant(db, { brain: BRAIN, principalId: penelope.id, createdBy: penelope.id, + repositoryPrefix, credential, metadataCredentialRecipient, now: Date.now() }), "REFERENCE_API_RECIPIENT_BOUNDARY").toThrow(); + }); + test("the longest covering prefix wins", () => { const penelope = owner(); grant(penelope.id, penelope.id, "https://github.com/odysseus", "GITHUB_TOKEN"); @@ -73,6 +103,25 @@ describe("reference grant records", () => { expect(covering(penelope.id, "https://github.com/odysseus/ithaca")?.credential).toBe(narrow.credential); }); + test("upgrading legacy grants and reopening preserves only explicitly granted API permission", () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-reference-grants-")), path = join(root, "ui.db"); + let disk = createUiDb(path); + try { + const principal = createPrincipal(disk, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + const input = { brain: BRAIN, principalId: principal.id, createdBy: principal.id, repositoryPrefix: "https://github.com/odysseus", + credential: "GITHUB_TOKEN", now: Date.now() }; + createReferenceGrant(disk, input); + disk.exec("ALTER TABLE reference_grants DROP COLUMN metadata_credential_recipient; DELETE FROM _migrations WHERE filename = '088_reference_metadata_recipient.sql'"); + disk.close(); disk = createUiDb(path); + const read = () => coveringReferenceGrant(disk, { brain: BRAIN, principalId: principal.id, + repository: referenceRepository("https://github.com/odysseus/ithaca"), now: Date.now() }); + expect(read(), "REFERENCE_LEGACY_UPGRADE_DOES_NOT_GRANT_API_RECIPIENT").not.toHaveProperty("metadataCredentialRecipient"); + createReferenceGrant(disk, { ...input, repositoryPrefix: "https://github.com/odysseus/ithaca", metadataCredentialRecipient: "https://api.github.com" }); + disk.close(); disk = createUiDb(path); + expect(read(), "REFERENCE_API_RECIPIENT_SURVIVES_RESTART").toHaveProperty("metadataCredentialRecipient", "https://api.github.com"); + } finally { disk.close(); rmSync(root, { recursive: true, force: true }); } + }); + test("revoking the grant or its principal removes authority immediately", () => { const penelope = owner(), telemachus = agent(penelope.id); const first = grant(telemachus.id, penelope.id, "file:///srv/fixtures"); @@ -150,6 +199,18 @@ describe("owner-only reference grant routes", () => { expect(revoked).toEqual([{ grantIds: [], principalIds: [telemachus.id] }]); }); + test("only an owner can create explicit API permission and its receipt lists the fixed recipient", async () => { + const penelope = owner(), telemachus = agent(penelope.id), header = await cookie(penelope.id), instance = app(); + const body = { repositoryPrefix: "https://github.com/odysseus/ithaca", credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com" }; + expect((await instance.request(`/api/auth/principals/${telemachus.id}/reference-grants`, json("POST", await cookie(telemachus.id), body))).status, + "REFERENCE_API_RECIPIENT_OWNER_ONLY").toBe(403); + const response = await instance.request(`/api/auth/principals/${telemachus.id}/reference-grants`, json("POST", header, body)); + expect(response.status).toBe(201); + expect(await response.json(), "REFERENCE_API_RECIPIENT_OWNER_RECEIPT").toHaveProperty("metadata_credential_recipient", "https://api.github.com"); + const listed = await instance.request(`/api/auth/principals/${telemachus.id}/reference-grants`, { headers: { cookie: header } }); + expect((await listed.json() as { grants: unknown[] }).grants[0], "REFERENCE_API_RECIPIENT_OWNER_LIST").toHaveProperty("metadata_credential_recipient", "https://api.github.com"); + }); + test("validation, unknown principals, duplicates and non-owners refuse", async () => { const penelope = owner(), telemachus = agent(penelope.id), header = await cookie(penelope.id), instance = app(); const post = (target: string, body: unknown, as = header) => instance.request(`/api/auth/principals/${target}/reference-grants`, json("POST", as, body)); From a066609970b7df2ab39c31370b523cc86c5de27b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 14:57:37 +0000 Subject: [PATCH 4/8] CONTRACT: fix(ui-server): refuse ambiguous managed reference targets --- .../ithaca-reference-metadata-permission.md | 2 + .../decisions/reference-source-acquisition.md | 7 +++ docs/integration-contract/mcp.md | 7 +++ .../src/brain/reference-transport.ts | 25 +++++++-- .../tests/reference-ref-validation.test.ts | 55 +++++++++++++++++++ .../tests/reference-transport.test.ts | 10 ++++ 6 files changed, 101 insertions(+), 5 deletions(-) create mode 100644 packages/ui-server/tests/reference-ref-validation.test.ts diff --git a/.changeset/ithaca-reference-metadata-permission.md b/.changeset/ithaca-reference-metadata-permission.md index e7c6fb1adb..8036354142 100644 --- a/.changeset/ithaca-reference-metadata-permission.md +++ b/.changeset/ithaca-reference-metadata-permission.md @@ -3,3 +3,5 @@ --- Add separate owner permission for the fixed GitHub identity metadata credential recipient. Existing repository access grants keep their original recipient authority. + +Refuse ambiguous branch/tag resolution and malformed or foreign ref advertisements before managed source acquisition. diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index b2a9cfe43a..0aa60302af 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -22,6 +22,13 @@ reported commit ([#2430](https://github.com/schlessera/brain-kit/issues/2430)). Repository locations follow the grant record's rules: HTTPS without credentials, loopback HTTP, or an absolute `file://` path. +The managed-only qualification in #3613 additionally refuses a short name +shared by a branch and a tag, raw full refs/refspecs and malformed or +conflicting advertisements. Resolution binds the requested full ref and +commit; fetching a moved commit cannot publish it as the earlier resolution. +These checks do not establish repository identity, immutable-read provenance +or network-byte qualification by themselves. + ## Sharing domains Each source lives in exactly one domain, and a domain is one pool view. diff --git a/docs/integration-contract/mcp.md b/docs/integration-contract/mcp.md index b6f6d124d9..fba3ede499 100644 --- a/docs/integration-contract/mcp.md +++ b/docs/integration-contract/mcp.md @@ -1229,6 +1229,13 @@ are exported from `@schlessera/brain-ui-sdk/tool-contracts` and `/server`. | `reference_source` | `repository` (1–2048 characters: https without credentials, loopback http or absolute `file://`), `revision` (1–200 characters, a branch or tag) | `{ ok: true, source, guidance }` | | `reference_worktree` | `action`: `request` (with `repository`, `revision`), `access`, `renew` or `release` (with `worktreeId`, 1–64 characters), or `list` (no other field) | `{ ok: true, action, worktree, guidance }`; for `list`, `{ ok: true, action: "list", worktrees, truncated, guidance }` with at most 20 worktrees, most recent activity first | +Managed acquisition requires one unambiguous short branch/tag name (#3613). +Raw `refs/...` names, refspecs and raw 40/64-hex object IDs are refused before +transport dispatch. A branch and a tag sharing the requested short name are +ambiguous even when they currently name identical commits. Only the requested +ordinary full ref and its own annotated-tag peel may resolve; malformed, +duplicate, foreign or oversized advertisements do not select a source. + Inputs are strict objects: an action given a field it does not take, or missing one it needs, is invalid. Principal, profile, brain, session, worker generation and paths are never inputs; the host takes them from the diff --git a/packages/ui-server/src/brain/reference-transport.ts b/packages/ui-server/src/brain/reference-transport.ts index 3d3b282582..a4e7719d05 100644 --- a/packages/ui-server/src/brain/reference-transport.ts +++ b/packages/ui-server/src/brain/reference-transport.ts @@ -54,7 +54,7 @@ export function referenceRevision(input: unknown): string { if (typeof input !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._/+-]{0,199}$/.test(input) || input.includes("..") || input.includes("//") || input.endsWith("/") || input.endsWith(".") || input.endsWith(".lock") || input.split("/").some(part => part.startsWith(".") || part.endsWith(".lock"))) throw new ReferenceTransportError("invalid", "revision must be one branch or tag name"); - if (/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(input)) + if (input.startsWith("refs/") || /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(input)) throw new ReferenceTransportError("invalid", "request a branch or tag; a managed worktree pins an exact reported commit"); return input; } @@ -114,6 +114,7 @@ export function createReferenceTransport(options: { } return { async resolve({ repository, revision, token, signal }) { + revision = referenceRevision(revision); const scratch = mkdtempSync(join(tmpdir(), "brain-reference-resolve-")); try { const result = await run(command({ repository, token, network: true, mirror: scratch, signal, @@ -122,15 +123,29 @@ export function createReferenceTransport(options: { if (result.killed) return { ok: false, reason: "unavailable", detail: "reference resolution timed out or was cancelled" }; if (result.exitCode === 2) return { ok: false, reason: "missing", detail: `no branch or tag named ${revision}` }; if (result.exitCode !== 0) return { ok: false, reason: classify(result.stderr), detail: result.stderr.trim().slice(-500) || `exit ${result.exitCode}` }; - const rows = new Map(result.stdout.trim().split("\n").map(line => line.split("\t")).filter(row => row.length === 2 && /^[0-9a-f]{40,64}$/.test(row[0]!)) - .map(row => [row[1]!, row[0]!])); + // Only the three explicitly requested advertisement rows may decide + // this source. A Map must not erase conflicting duplicate identities. + const allowed = new Set([`refs/heads/${revision}`, `refs/tags/${revision}`, `refs/tags/${revision}^{}`]); + const rows = new Map(); + if (Buffer.byteLength(result.stdout) > 4096) throw new ReferenceTransportError("invalid", "reference advertisement exceeds its bound"); + const advertised = result.stdout.endsWith("\n") ? result.stdout.slice(0, -1) : result.stdout; + for (const line of advertised ? advertised.split("\n") : []) { + const fields = line.split("\t"), [commit, ref] = fields; + if (fields.length !== 2 || !commit || !ref || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit) + || !allowed.has(ref) || rows.has(ref)) throw new ReferenceTransportError("invalid", "reference advertisement is ambiguous or malformed"); + rows.set(ref, commit); + } const head = rows.get(`refs/heads/${revision}`), peeled = rows.get(`refs/tags/${revision}^{}`), tag = rows.get(`refs/tags/${revision}`); + if ((head && (tag || peeled)) || (peeled && !tag)) throw new ReferenceTransportError("invalid", "request one unambiguous branch or tag"); if (head) return { ok: true, commit: head, ref: `refs/heads/${revision}` }; if (peeled ?? tag) return { ok: true, commit: (peeled ?? tag)!, ref: `refs/tags/${revision}` }; return { ok: false, reason: "missing", detail: `no branch or tag named ${revision}` }; } finally { rmSync(scratch, { recursive: true, force: true }); } }, async fetch({ repository, ref, token, root, signal }) { + const target = /^refs\/(?:heads|tags)\/(.+)$/.exec(ref); + if (!target) throw new ReferenceTransportError("invalid", "fetch requires one resolved ordinary branch or tag"); + referenceRevision(target[1]); const gitDir = prepareReferenceGitDirectory(root); const fetched = await run(command({ repository, token, network: true, mirror: gitDir, signal, argv: [git(), "--git-dir", gitDir, ...networkArgs(repository, token), "fetch", "--no-tags", "--no-write-fetch-head", "--", repository.url, `+${ref}:refs/reference/source`] })); @@ -143,11 +158,11 @@ export function createReferenceTransport(options: { const parsed = await run(command({ token: null, network: false, mirror: gitDir, signal, argv: [git(), "--git-dir", gitDir, "-c", "core.hooksPath=/dev/null", "rev-parse", "--verify", "refs/reference/source^{commit}"] })); const commit = parsed.stdout.trim(); - if (parsed.killed || parsed.exitCode !== 0 || !/^[0-9a-f]{40,64}$/.test(commit)) throw new ReferenceTransportError("unavailable", "fetched reference commit is unreadable"); + if (parsed.killed || parsed.exitCode !== 0 || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit)) throw new ReferenceTransportError("unavailable", "fetched reference commit is unreadable"); return { commit }; }, async checkout({ root, commit, signal }) { - if (!/^[0-9a-f]{40,64}$/.test(commit)) throw new ReferenceTransportError("invalid", "checkout needs one commit id"); + if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit)) throw new ReferenceTransportError("invalid", "checkout needs one commit id"); const gitDir = prepareReferenceGitDirectory(root); const result = await run(command({ token: null, network: false, mirror: root, signal, argv: [git(), "--git-dir", gitDir, "--work-tree", root, "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "checkout", "--force", "--detach", commit] })); diff --git a/packages/ui-server/tests/reference-ref-validation.test.ts b/packages/ui-server/tests/reference-ref-validation.test.ts new file mode 100644 index 0000000000..43eef724e8 --- /dev/null +++ b/packages/ui-server/tests/reference-ref-validation.test.ts @@ -0,0 +1,55 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createReferenceTransport } from "../src/brain/reference-transport"; +import { referenceRepository } from "../src/db/reference-grants"; + +const repository = referenceRepository("https://github.com/odysseus/ithaca"); +const commit = "a".repeat(40), tag = "b".repeat(40); +function transport(stdout: string) { + const calls: string[][] = []; + return { calls, service: createReferenceTransport({ brainPath: "/unused", run: async input => { + calls.push(input.command); return { stdout, stderr: "", exitCode: 0, killed: false }; + } }) }; +} + +test("resolution refuses branch/tag ambiguity even when they currently name identical commits", async () => { + for (const target of [commit, tag]) { + const { service } = transport(`${commit}\trefs/heads/main\n${target}\trefs/tags/main\n`); + await expect(service.resolve({ repository, revision: "main", token: null }), "REFERENCE_AMBIGUOUS_REF_NEVER_SELECTED").rejects.toMatchObject({ reason: "invalid" }); + } +}); + +test("resolution binds exactly one requested full ref and peels only its own annotated tag", async () => { + const cases = [{ stdout: `${commit}\trefs/heads/main\n`, commit, ref: "refs/heads/main" }, + { stdout: `${tag}\trefs/tags/main\n${commit}\trefs/tags/main^{}\n`, commit, ref: "refs/tags/main" }]; + for (const { stdout, ...expected } of cases) { + expect(await transport(stdout).service.resolve({ repository, revision: "main", token: null })).toEqual({ ok: true, ...expected }); + } +}); + +test("malformed, duplicate, foreign and unbounded advertised identities never become a source", async () => { + for (const output of [`${commit}\trefs/heads/main\n${tag}\trefs/heads/main\n`, `${commit}\trefs/pull/7/head\n`, + `${commit}\trefs/heads/main\n${tag}\trefs/tags/loom\n`, `${"a".repeat(41)}\trefs/heads/main\n`, + `${commit}\trefs/tags/main^{}\n`, `${commit}\trefs/heads/main\nmalformed\n`, `${commit}\trefs/heads/main\n`.repeat(500), + ` ${commit}\trefs/heads/main\n`, `${commit}\trefs/heads/main \n`, `${commit}\trefs/heads/main\n\n`]) { + await expect(transport(output).service.resolve({ repository, revision: "main", token: null }), "REFERENCE_ADVERTISED_REF_EXACT").rejects.toMatchObject({ reason: "invalid" }); + } +}); + +test("raw refs and object IDs are refused before any network command or staging write", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-reference-ref-")); + try { + for (const revision of ["refs/pull/7/head", "refs/heads/main", "refs/tags/main", "a".repeat(40), "A".repeat(40), "a".repeat(64)]) { + const { calls, service } = transport(`${commit}\trefs/heads/${revision}\n`); + await expect(service.resolve({ repository, revision, token: null }), "REFERENCE_RAW_REF_NOT_DISPATCHED").rejects.toMatchObject({ reason: "invalid" }); + expect(calls).toEqual([]); + } + for (const ref of ["refs/pull/7/head", commit, "refs/heads/main:refs/heads/loom", "refs/tags/../main", "refs/heads/refs/pull/7/head"]) { + const { calls, service } = transport(""); + await expect(service.fetch({ repository, ref, token: null, root }), "REFERENCE_FOREIGN_FETCH_NOT_DISPATCHED").rejects.toMatchObject({ reason: "invalid" }); + expect(calls).toEqual([]); expect(readdirSync(root)).toEqual([]); + } + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/packages/ui-server/tests/reference-transport.test.ts b/packages/ui-server/tests/reference-transport.test.ts index f58b9e5d66..f99679470c 100644 --- a/packages/ui-server/tests/reference-transport.test.ts +++ b/packages/ui-server/tests/reference-transport.test.ts @@ -93,6 +93,16 @@ test("the transport resolves public revisions anonymously and private ones only .toMatchObject({ ok: true, commit: git(join(fixture, "srv", "loom.git"), "rev-parse", "main") }); }, 60_000); +test("an ambiguous branch and tag name is refused by the actual Git transport", async () => { + if (await privateMaintenanceTest(import.meta.path, "an ambiguous branch and tag name is refused by the actual Git transport", 60000)) return; + const repository = referenceRepository(url("public", "ithaca")), bare = join(fixture, "srv", "ithaca.git"); + git(bare, "tag", "main", "refs/heads/main"); + try { + await expect(createReferenceTransport({ brainPath: brain }).resolve({ repository, revision: "main", token: null }), + "REFERENCE_AMBIGUOUS_BRANCH_TAG_REFUSED").rejects.toMatchObject({ reason: "invalid" }); + } finally { git(bare, "tag", "-d", "main"); } +}, 60_000); + test("acquisition publishes a complete thousand-file checkout and keeps the credential out of source evaluation", async () => { if (await privateMaintenanceTest(import.meta.path, "acquisition publishes a complete thousand-file checkout and keeps the credential out of source evaluation", 180000)) return; const db = createUiDb(":memory:"); From ea596652bf97847d01ab6f648ed7b3634b7fe5cb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 15:07:10 +0000 Subject: [PATCH 5/8] chore(ui-server): keep reference identity types private --- packages/ui-server/src/brain/github-reference-identity.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/brain/github-reference-identity.ts b/packages/ui-server/src/brain/github-reference-identity.ts index aba48b14bb..6d36221e6c 100644 --- a/packages/ui-server/src/brain/github-reference-identity.ts +++ b/packages/ui-server/src/brain/github-reference-identity.ts @@ -1,7 +1,7 @@ /** Fixed GitHub metadata validation. Parsing alone establishes no transport, access or source trust. */ import { parseTrustGithub, TrustSelectorSchema } from "@schlessera/brain-common/internal/governance-policy"; -export interface GitHubReferenceRepository { +interface GitHubReferenceRepository { owner: string; repository: string; canonical: string; @@ -9,7 +9,7 @@ export interface GitHubReferenceRepository { metadataUrl: string; } -export interface GitHubReferenceIdentity extends GitHubReferenceRepository { +interface GitHubReferenceIdentity extends GitHubReferenceRepository { repositoryId: string; ownerId: string; private: boolean; From 673605d1de2d6b83edd3b324371636ea69244622 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 15:10:04 +0000 Subject: [PATCH 6/8] CONTRACT: docs(ui-server): define metadata permission replacement --- docs/http-api.md | 2 ++ docs/integration-contract/http.md | 2 ++ packages/ui-server/tests/reference-ref-validation.test.ts | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/http-api.md b/docs/http-api.md index 5c2751b7ca..231645ce4f 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -553,6 +553,8 @@ itself. `metadata_credential_recipient: "https://api.github.com"`. The permission shares the grant's brain, principal, repository scope and live revocation. It grants neither generic HTTP access nor repository source trust. + Changing this permission uses revoke/recreate; duplicate matching keeps the + existing principal/prefix/credential identity and does not expand a grant. - **DELETE `/api/auth/principals/:id/reference-grants/:grantId`**, body ignored, revokes that principal's live grant and returns `{ ok: true }`. Revocation applies to the next authority check, including in-flight private diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 192032acde..96766a94b9 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1140,6 +1140,8 @@ FULL writer and is returned as optional receipts; legacy receipt shapes remain unchanged. It shares the live grant's brain/principal/repository scope and revocation. The field establishes no transport or source-trust qualification and exposes no generic API relay. +Changing recipient permission uses revoke/recreate; an existing grant with +the same principal/prefix/credential remains a duplicate. ## Content renderer bootstrap declarations (additive, #2087) diff --git a/packages/ui-server/tests/reference-ref-validation.test.ts b/packages/ui-server/tests/reference-ref-validation.test.ts index 43eef724e8..b14d16fecc 100644 --- a/packages/ui-server/tests/reference-ref-validation.test.ts +++ b/packages/ui-server/tests/reference-ref-validation.test.ts @@ -10,7 +10,7 @@ const commit = "a".repeat(40), tag = "b".repeat(40); function transport(stdout: string) { const calls: string[][] = []; return { calls, service: createReferenceTransport({ brainPath: "/unused", run: async input => { - calls.push(input.command); return { stdout, stderr: "", exitCode: 0, killed: false }; + calls.push([...input.command]); return { stdout, stderr: "", exitCode: 0, killed: false }; } }) }; } From fcc7f624fd367f7188799d8d7cd5e6ac400baabc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 15:13:20 +0000 Subject: [PATCH 7/8] fix(ui-server): preserve actionable reference resolution refusals --- packages/ui-server/src/brain/reference-source.ts | 5 ++++- .../ui-server/tests/reference-source.test.ts | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 3d94ac2042..63e0af6d2e 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -299,7 +299,10 @@ export function createReferenceSources(options: { input = { ...input, grant }; const credential = token(grant); const existing = row(domain, repository.canonical, revision); - const check = await transport.resolve({ repository, revision, token: credential, signal }); + const check = await transport.resolve({ repository, revision, token: credential, signal }).catch((error: unknown) => { + if (error instanceof ReferenceTransportError && error.reason === "invalid") throw new ReferenceSourceError("invalid", error.message); + throw error; + }); signal.throwIfAborted(); if (!check.ok) { const detail = check.detail; diff --git a/packages/ui-server/tests/reference-source.test.ts b/packages/ui-server/tests/reference-source.test.ts index f66e128666..b538b28324 100644 --- a/packages/ui-server/tests/reference-source.test.ts +++ b/packages/ui-server/tests/reference-source.test.ts @@ -86,6 +86,22 @@ function service(options: { limits?: Record; capacityRoots?: num const read = (lease: ReferenceSourceLease) => readFileSync(join(lease.viewPath, lease.name, "README.md"), "utf8").trim(); const minutes = (count: number) => { clock += count * 60_000; }; +test("ambiguous advertisements refuse one source explicitly without private fallback or a global latch", async () => { + const { sources, state } = service(), principal = owner(); + grant(principal.id, principal.id); + state.onResolve = () => { throw new ReferenceTransportError("invalid", "request one unambiguous branch or tag"); }; + try { + await expect(sources.request({ principalId: principal.id, repository: PUBLIC, revision: "main" }), + "REFERENCE_AMBIGUOUS_SOURCE_ACTIONABLE_REFUSAL").rejects.toMatchObject({ code: "invalid", message: "request one unambiguous branch or tag" }); + expect(state.resolves).toEqual([{ repository: PUBLIC, token: null }]); + expect(state.fetches).toEqual([]); + state.onResolve = null; + const healthy = await sources.request({ principalId: principal.id, repository: PUBLIC, revision: "main" }); + expect(healthy.stale, "REFERENCE_REFUSAL_CLEARS_ON_UNAMBIGUOUS_RETRY").toBe(false); + healthy.release(); + } finally { await sources.close(); } +}); + test("a ref that moves after resolution is refused before source publication", async () => { const { sources, state, repos } = service(); const principal = owner(); From 8cab65afcb542b32bcecdd9347bfbf3b20d4c9a5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 15:16:44 +0000 Subject: [PATCH 8/8] docs(ui-server): refresh reference guard source citations --- docs/decisions/managed-worktrees.md | 8 ++++---- docs/decisions/reference-source-acquisition.md | 16 ++++++++-------- docs/decisions/reference-source-grants.md | 10 +++++----- docs/plans/reviewable-session-safety.md | 2 +- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 0b52dc27f0..c5af5d30b2 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -215,7 +215,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:873-884`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:741-753`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:745-776`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -255,7 +255,7 @@ check before a new mount) applies to the bind itself. The maintainer ruled on before a turn's workers bind a view, every source in it whose validation lapsed is validated again, including sources a running turn reads; one that fails is withheld from the new bind, and a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:565-603`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:569-607`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -269,7 +269,7 @@ withheld from the new bind, and a running reader keeps its existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:501-512`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:505-516`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -288,7 +288,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:609-618`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:613-622`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 0aa60302af..a9a287b489 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:91-782`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:91-786`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -52,7 +52,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:293-339`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:293-342`). - Inside both windows a request reuses the published source without any network call. @@ -79,18 +79,18 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:404-456`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:407-460`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. 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 - (`fetch({ repository, ref, token, root, signal })`, `packages/ui-server/src/brain/reference-transport.ts:133-148`). + (`fetch({ repository, ref, token, root, signal })`, `packages/ui-server/src/brain/reference-transport.ts:145-163`). 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:149-159`). + (`async checkout({ root, commit, signal })`, `packages/ui-server/src/brain/reference-transport.ts:164-174`). 4. The live grant is read again, the root is sealed, the grant is read again, and only then is the root published. @@ -132,7 +132,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:363-379`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:366-382`). There is no idle expiry. ## Revocation and recovery @@ -145,14 +145,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:651-671`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:655-675`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:674-718`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:678-722`). ## Evidence diff --git a/docs/decisions/reference-source-grants.md b/docs/decisions/reference-source-grants.md index 4803485546..f2b34f2ff4 100644 --- a/docs/decisions/reference-source-grants.md +++ b/docs/decisions/reference-source-grants.md @@ -28,7 +28,7 @@ The maintainer selected **owner-managed grant records** on 2026-10-22 ## The record A grant is one row of the UI database's `reference_grants` table -(`createReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:117-138`). +(`createReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:122-149`). The table holds the served brain's identity, the principal, the canonical repository prefix, the credential name or null, the granting owner and the revocation time. It stores no credential value. A grant is **live** while it @@ -47,17 +47,17 @@ owner session ends when that session does. A repository location is HTTPS without user info, query or fragment; loopback `http://`; or an absolute `file:///` path -(`referenceRepository`, `packages/ui-server/src/db/reference-grants.ts:51-75`). +(`referenceRepository`, `packages/ui-server/src/db/reference-grants.ts:52-76`). SSH is refused: no grantable credential is an SSH key. The canonical form lowercases the origin and drops a trailing slash and a hosted `.git` suffix. A prefix covers itself and every path below it at a segment boundary, so `…/odysseus` never covers `…/odysseus-crew`. The longest covering live prefix wins, read at the moment of use -(`coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:158-164`). +(`coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:169-175`). A grant names its credential from a fixed list of existing host selectors, each with the one origin it may be sent to -(`REFERENCE_HOST_CREDENTIALS`, `packages/ui-server/src/db/reference-grants.ts:26-30`): +(`REFERENCE_HOST_CREDENTIALS`, `packages/ui-server/src/db/reference-grants.ts:27-31`): `BRAIN_UI_SYNC_GITHUB_TOKEN`, `BRAIN_UI_SKILLS_GITHUB_TOKEN` and `GITHUB_TOKEN`, all for `https://github.com`. Loopback origins may also receive them, because they stay on this host; that is how the offline fixtures exercise a @@ -78,7 +78,7 @@ anonymous success there says nothing about who may read the host path. Revocation is checked, not cached. Every new mount and every step that could publish private source asks for the live covering grant again. The revoke routes also report the lost authority synchronously -(`app.delete("/auth/principals/:id/reference-grants/:grantId"`, `packages/ui-server/src/middleware/principals.ts:272-293`), +(`app.delete("/auth/principals/:id/reference-grants/:grantId"`, `packages/ui-server/src/middleware/principals.ts:274-295`), so the acquisition layer can cancel in-flight private work rather than wait for its next check. Revocation cannot retract bytes a reader has already read. diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 846fa18c9c..bad5d53123 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:97-170`). + `packages/ui-server/src/brain/reference-transport.ts:97-176`). - 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`).