Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/ithaca-reference-metadata-permission.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@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.

Refuse ambiguous branch/tag resolution and malformed or foreign ref advertisements before managed source acquisition.
8 changes: 4 additions & 4 deletions docs/decisions/managed-worktrees.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand Down
23 changes: 15 additions & 8 deletions docs/decisions/reference-source-acquisition.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.
Expand All @@ -45,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.
Expand All @@ -72,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.

Expand Down Expand Up @@ -125,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
Expand All @@ -138,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

Expand Down
10 changes: 5 additions & 5 deletions docs/decisions/reference-source-grants.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.

Expand Down
14 changes: 13 additions & 1 deletion docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -543,6 +544,17 @@ 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.
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
Expand Down
14 changes: 14 additions & 0 deletions docs/integration-contract/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,20 @@ 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.
Changing recipient permission uses revoke/recreate; an existing grant with
the same principal/prefix/credential remains a duplicate.

## Content renderer bootstrap declarations (additive, #2087)

Authenticated `GET /api/status` includes optional `contentRenderers`, an array of
Expand Down
7 changes: 7 additions & 0 deletions docs/integration-contract/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/reviewable-session-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public design or its fixtures. Fictional examples use the Odysseus world.
([reference-source grants](../decisions/reference-source-grants.md)). Its
fixed Git transport separates network acquisition from credential-free,
network-free checkout (`createReferenceTransport`,
`packages/ui-server/src/brain/reference-transport.ts: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`).
Expand Down
Original file line number Diff line number Diff line change
@@ -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');
62 changes: 62 additions & 0 deletions packages/ui-server/src/brain/github-reference-identity.ts
Original file line number Diff line number Diff line change
@@ -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";

interface GitHubReferenceRepository {
owner: string;
repository: string;
canonical: string;
cloneUrl: string;
metadataUrl: string;
}

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<string, unknown>;
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<string, unknown>;
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;
}
Loading
Loading