Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
480ce4e
CONTRACT: feat(ui-server, ui-sdk): a host GitHub API relay for module…
schlessera Nov 20, 2026
3e1c436
fix(ui-server): keep the module relay's bounds module-private (#4259)
schlessera Nov 20, 2026
0527e27
docs(ui-server): regenerate the environment table for the module GitH…
schlessera Nov 20, 2026
b718919
fix(ui-server, ui-sdk): close GraphQL parsing bypasses, keep the rela…
schlessera Nov 20, 2026
4d058d6
fix(ui-server): bound relay reads while streaming, and record a write…
schlessera Nov 20, 2026
7b8eccf
fix(ui-server, ui-sdk): keep relayed GraphQL inside its repository; c…
schlessera Nov 20, 2026
4922acc
test(ui-server): read the journal from its own database; accept an un…
schlessera Nov 20, 2026
000c181
docs(ui-server): state the relayed GraphQL boundary truthfully; refus…
schlessera Nov 20, 2026
8b4771e
fix(ui-server): allow connection edges in relayed GraphQL; record the…
schlessera Nov 20, 2026
bdc8e97
fix(ui-server): accept comma-less GraphQL arguments on the granted ro…
schlessera Nov 20, 2026
50d7947
fix(ui-server): bound the relay's calls in flight (#4259)
schlessera Nov 20, 2026
cfc2226
fix(ui-server): name the right next step for every refusal (review of…
schlessera Nov 20, 2026
cbce805
fix(ui-server): truthful sync review rationale and reports; relay ref…
schlessera Nov 20, 2026
6b3296c
fix(ui-server): name the right refusals and launch class (review of #…
schlessera Nov 20, 2026
5532661
fix(ui-server): record the real cause of a refused sync review; every…
schlessera Nov 20, 2026
3886c6d
fix(ui-server): record a sync policy read failure by its cause; nativ…
schlessera Nov 20, 2026
c3b47ec
test(ui-server): drop an assertion that cannot fail; the path guard r…
schlessera Nov 20, 2026
68ded67
fix(ui-server): record relay_stopped in the contract and prove it (#4…
schlessera Nov 20, 2026
7e98e6a
fix(ui-server): record a write still unanswered when the relay stops …
schlessera Nov 20, 2026
dd3faa4
docs(modules): a redirect is refused after GitHub answers, never foll…
schlessera Nov 20, 2026
43142ab
docs(contract): the relay's 502 refusals come after a call is forward…
schlessera Nov 20, 2026
6086ef6
fix(ui-sdk, ui-server): reserve the relay's mount point; state the ho…
schlessera Nov 20, 2026
7f974c4
Merge remote-tracking branch 'origin/main' into feat/4259-module-gith…
schlessera Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/4259-module-github-relay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@schlessera/brain-ui-server": minor
"@schlessera/brain-ui-sdk": minor
---

A module cron job can now call the GitHub API of the repositories it was granted (#4259) without holding a token. A job whose module's `repositories` and the host's `BRAIN_UI_MODULE_REPOSITORIES` grant a `github.com` repository gets a per-run relay socket, named in `BRAIN_MODULE_GITHUB_SOCKET`. The relay forwards REST `GET` reads and repository GraphQL queries with the host's new `BRAIN_UI_MODULE_GITHUB_TOKEN`, which has no fallback. It forwards writes (`issue_comment`, `issue_state`) only where the operator enables them per repository in `BRAIN_UI_MODULE_GITHUB_WRITES`. Everything else is refused before a request leaves the host. Each write is recorded on the job's Activity run.
32 changes: 32 additions & 0 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,38 @@ credential sent only to `https://github.com`, and a transport worker that
never mounts the brain
([the contract](../integration-contract/package-api.md#module-repositories)).

**The GitHub API of a granted repository — 2026-11-20
([#4259](https://github.com/schlessera/brain-kit/issues/4259), maintainer ruling
option 1).** A module job that must read issues or write to them reaches the
GitHub API through a host relay, never a token in its worker. The relay's grant
is the read grant above: only the job's granted `github.com` repositories. A
dedicated host-only credential, `BRAIN_UI_MODULE_GITHUB_TOKEN`, has no fallback
to `GITHUB_TOKEN`, the sync token or `BRAIN_UI_GITHUB_TOOLS_TOKEN`. Reads are
REST `GET` and repository-rooted GraphQL queries. Writes are a fixed operation
set (`issue_comment`, `issue_state`), each enabled per repository by the
operator's `BRAIN_UI_MODULE_GITHUB_WRITES` in host configuration, so editing
`brain.config.ts` cannot widen it. The relay is a per-run Unix socket in a
private server-owned directory, bound read-only into that one worker: only
that run's worker can reach it, where a loopback port would answer any process
on the host. A token placed
in the job's worker and leaving API writes to the operator's own host jobs
were both rejected.

A GraphQL read is rooted at a granted repository, as the ruling states.
Below that root, the relay also refuses fields that select another repository,
owner or account by name (`repository`, `repositories`, `owner`, `forks`,
`parent`, `search`, `viewer`, `headRepository` and the like). That denylist
cannot close every traversal GitHub's schema offers: an author's other issues,
or a cross-referencing issue elsewhere, still answer with whatever the token
can read, as the REST timeline does. By the maintainer's 2026-11-20 ruling on #4259,
the token's own scope is the read boundary below the root. One
`BRAIN_UI_MODULE_GITHUB_TOKEN` serves every module job, so the operator limits it
to the union of the repositories module jobs are granted. REST-only reads and a
token per module were not taken. Every host-view worker, agent and
maintenance alike, also covers `/etc/environment`. A container writes the cron
runner's environment there for pam_env, host-only credentials included, and a
worker builds its environment explicitly and never reads that file.

The protected list below keeps the policy intact, keeps secrets out of workers,
and stops a turn from steering later turns' permissions or start-up code.

Expand Down
5 changes: 5 additions & 0 deletions docs/hosting/agent-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,11 @@ refuses rather than run git on the host.
into a private mirror beside the sync mirror, using the sync credential.
The job's worker reads that mirror through a Git URL rewrite and holds no
Git credential. Leave the setting empty to fetch nothing.
- **A module job's GitHub API calls** to those granted GitHub repositories go
through a per-run host relay socket (#4259), never a token in the worker. The
relay adds `BRAIN_UI_MODULE_GITHUB_TOKEN` (no fallback) and allows writes only
where `BRAIN_UI_MODULE_GITHUB_WRITES` enables them per repository. Leave the
token unset to refuse every call.

**When the boundary holds.** `governed` is the default profile, so the
boundary holds wherever `governed` can run, and from then on for good: once
Expand Down
8 changes: 8 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,14 @@ worker reads the mirror through a Git URL rewrite without any credential. See
[the package API component](integration-contract/package-api.md#module-repositories).
This ships in a minor; no breaking ruling is required.

## Module GitHub relay (additive, 0.45.0, #4259)

A module cron job granted a GitHub repository reaches its API through a per-run
host relay socket named in `BRAIN_MODULE_GITHUB_SOCKET`. It forwards granted
reads and only operator-enabled writes (`BRAIN_UI_MODULE_GITHUB_WRITES`) with the
host's `BRAIN_UI_MODULE_GITHUB_TOKEN`; the worker holds no token. See
[the package API component](integration-contract/package-api.md#module-github-relay).

## Module state area (additive, 0.45.0, #3380)

A module keeps durable state in `<brain>/.brain-ui/modules/<module-name>/`,
Expand Down
30 changes: 30 additions & 0 deletions docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,36 @@ the mirror read-only and `url.file://<mirror>.insteadOf` rewrites for the
URL's plain, `/`, `.git` and `.git/` spellings. It never receives a Git
credential. The crontab layout is unchanged.

<a id="module-github-relay"></a>

**Additive module GitHub relay (0.45.0, #4259).** A module job granted a
`https://github.com/<owner>/<repo>` repository above also gets
`BRAIN_MODULE_GITHUB_SOCKET=/run/brain-github/github.sock` in its maintenance
worker: a per-run Unix socket bound read-only from a private server-owned
directory, alive only for that run. HTTP requests to it are relayed to
`https://api.github.com` with the host's `BRAIN_UI_MODULE_GITHUB_TOKEN` (no
fallback), never following a redirect. Relayed: `GET /repos/<owner>/<repo>/…`
for a granted repository; `POST /graphql` with `{ query, variables?,
operationName? }` when the query is one query operation whose only root field
is `repository(owner:, name:)` naming a granted repository and no field below it
selects another repository, owner or account by name (nested traversal is
otherwise bounded by the token's scope); and, only where
the operator's `BRAIN_UI_MODULE_GITHUB_WRITES` enables them for that repository,
`POST /repos/<r>/issues/<n>/comments` with exactly `{ body }` (`issue_comment`)
and `PATCH /repos/<r>/issues/<n>` with `{ state, state_reason? }`
(`issue_state`). Every other request is refused before anything leaves the
host, with `{ message, brain_relay_refusal }` and status 400, 403, 413, 429 or
503 (`unavailable` without the token). A forwarded call fails with 502 after
GitHub answers or fails to: `redirect` (never followed), `response_too_large`
or `upstream_unreachable`. A call beyond 8 in flight is refused with 503 `relay_busy` before anything is
read, and a call that arrives after the run ended, while calls in flight settle
for up to 10 seconds, with 503 `relay_stopped`. Request bodies are bounded at 1 MiB, responses at 16 MiB and calls at 500
per run. The response keeps GitHub's status,
body and `content-type`, `link`, `etag`, rate-limit and request-id headers. Each
forwarded write is a `github_write` event on the job's Activity root span:
`{ repository, operation, number, status }`, with `status: 0` when the request
was sent but its answer was lost. Neither setting reaches a job.

**Additive protected scratch retention (#1743).** The existing module helper
`pruneScratch(root, now?, options?)` accepts optional
`options.protectedPaths: readonly string[]`. These brain-relative or absolute
Expand Down
31 changes: 31 additions & 0 deletions docs/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,37 @@ modules: {
This applies to scheduled jobs on a host that runs repository jobs in
maintenance workers. A module command run by hand gets no mirror.

### Calling the GitHub API from a scheduled job

A job also gets the GitHub **API** of the GitHub repositories it was granted
above, through a host relay (#4259). The worker still holds no GitHub token. The relay is a Unix socket named in `BRAIN_MODULE_GITHUB_SOCKET`
(`/run/brain-github/github.sock`), and lives only as long as the run. Send it
ordinary GitHub API requests:

```ts
const github = (path: string, init: RequestInit = {}) =>
fetch(`http://localhost${path}`, { ...init, unix: process.env.BRAIN_MODULE_GITHUB_SOCKET } as RequestInit);
const issues = await github("/repos/ithaca/watchtower/issues?state=closed").then(r => r.json());
```

- **Reads:** `GET` under `/repos/<owner>/<repo>/…` for a granted repository,
and `POST /graphql` with a query (never a mutation) whose one root field is
`repository(owner:, name:)` naming a granted repository. Fields that select
another repository or owner by name are refused below the root. Other
nested data (an author's other issues, a cross-reference) is bounded by the
token's own scope. One token serves every module job, so limit it to the
union of the repositories module jobs are granted.
- **Writes:** only what the operator enables per repository in
`BRAIN_UI_MODULE_GITHUB_WRITES`, as `https://github.com/<owner>/<repo>#<operation>`:
`issue_comment` (`POST /repos/<r>/issues/<n>/comments` with `{ body }`) and
`issue_state` (`PATCH /repos/<r>/issues/<n>` with `{ state, state_reason? }`).
Each write is recorded on the job's Activity run as a `github_write` event.
- The host adds its own `BRAIN_UI_MODULE_GITHUB_TOKEN`, and no other token.
Without it, every call is refused with a message that names the setting.
Anything else (another repository, another path or method, more than 500
calls in a run or 8 at once) is refused before any request leaves the host.
A redirect GitHub answers with is never followed, and the call fails.

### Hygiene checks read the index through `ctx.queries`

A hygiene check receives `{ queries, root, config }`. `queries` is a frozen
Expand Down
3 changes: 3 additions & 0 deletions packages/ui-sdk/src/server/maintenance-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ export interface MaintenanceCommand {
maskEnvFiles?: boolean;
/** The server's CLI provider relay directory for a credentialed command (#1673). */
providerRelay?: string;
/** The cron runner's module GitHub relay directory for a module job (#4259); it holds no credential. */
githubRelay?: string;
/** The host network. Defaults to `credentials`. */
network?: boolean;
/** The server's home, shown to a credentialed worker. */
Expand Down Expand Up @@ -206,6 +208,7 @@ export function maintenanceLaunch(input: MaintenanceCommand): WorkerLaunch {
credentials: input.credentials,
...(input.credentials && input.maskEnvFiles ? { maskEnvFiles: true } : {}),
...(input.credentials && input.providerRelay ? { providerRelay: input.providerRelay } : {}),
...(input.githubRelay ? { githubRelay: input.githubRelay } : {}),
...(home ? { home: { path: home, overlay: false } } : {}),
readPaths: [process.execPath, ...(input.readPaths ?? [])],
...(input.maskPaths ? { maskPaths: input.maskPaths } : {}),
Expand Down
6 changes: 4 additions & 2 deletions packages/ui-sdk/src/server/subprocess-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;

/**
* Host-only secrets no subprocess may receive (#3159; the host GitHub tools'
* credential, #3797), and the shared Apify ledger's location (#3162): a
* credential, #3797; the module GitHub relay's credential, #4259), and the shared Apify ledger's location (#3162): a
* worker's own `brain apify` must find neither
* the credential nor the accounting it would spend against. Unlike a server-only
* descriptor entry, neither the operator escape hatch nor a per-spawn
* addition can admit one: the host makes every request that needs it.
*
* @internal First-party implementation; no compatibility guarantee.
*/
export const HOST_ONLY_SECRET_ENV: readonly string[] = Object.freeze(["APIFY_TOKEN", "BRAIN_APIFY_LEDGER", "BRAIN_UI_GITHUB_TOOLS_TOKEN"]);
export const HOST_ONLY_SECRET_ENV: readonly string[] = Object.freeze(["APIFY_TOKEN", "BRAIN_APIFY_LEDGER", "BRAIN_UI_GITHUB_TOOLS_TOKEN", "BRAIN_UI_MODULE_GITHUB_TOKEN"]);
const admissible = (name: string) =>
ENV_NAME.test(name) && name !== SUBPROCESS_ENV_EXTRA_NAME && !HOST_ONLY_SECRET_ENV.includes(name);

Expand Down Expand Up @@ -251,4 +251,6 @@ export const HOST_GIT_CREDENTIAL_ENV: readonly string[] = Object.freeze([
// The host GitHub tools' credential (#3797): stripped from every worker,
// including credentialed maintenance.
"BRAIN_UI_GITHUB_TOOLS_TOKEN",
// The module GitHub relay's credential (#4259): the cron runner's relay holds it, no worker does.
"BRAIN_UI_MODULE_GITHUB_TOKEN",
]);
34 changes: 29 additions & 5 deletions packages/ui-sdk/src/server/worker-launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,13 @@ export interface WorkerLaunch {
* `/tmp/.X11-unix`.
*/
export const HOST_MASKS = ["/run", "/var", "/home", "/root", "/mnt", "/media", "/srv"] as const;
/**
* Host files covered in every host-view worker (#4259): a container's
* `/etc/environment` carries the cron runner's environment, its host-only
* credentials included, for pam_env. A worker's environment is built
* explicitly and never reads it.
*/
export const HOST_FILE_MASKS = ["/etc/environment"] as const;

/** The private, empty `$HOME` of a credential-free maintenance worker, on its own `/tmp`. */
export const MAINTENANCE_HOME = "/tmp/brain-maintenance-home";
Expand Down Expand Up @@ -210,6 +217,13 @@ export interface MaintenanceEnvelope {
* `BRAIN_PROVIDER_RELAY_SOCKET`. Only a credentialed worker gets one.
*/
providerRelay?: string;
/**
* The cron runner's private module GitHub relay directory (#4259), bound
* read-only at {@link WORKER_MODULE_GITHUB_DIR}; the launcher names its
* socket in `BRAIN_MODULE_GITHUB_SOCKET`. It holds no credential, so a
* credential-free worker may get one.
*/
githubRelay?: string;
/**
* The server's home, made visible again below the home masks. Only a
* credentialed worker gets it (the interim exposure the decision record
Expand Down Expand Up @@ -382,11 +396,15 @@ function rlimitPrefix(plan: WorkerLimitsPlan): string[] {

/** Where a relayed maintenance worker reaches the CLI provider relay (#1673). */
export const WORKER_PROVIDER_RELAY_DIR = "/run/brain-providers";
/** Where a module cron job's worker reaches the host GitHub relay (#4259). */
export const WORKER_MODULE_GITHUB_DIR = "/run/brain-github";
/** The variable naming that relay's socket inside the worker. */
export const MODULE_GITHUB_SOCKET_ENV = "BRAIN_MODULE_GITHUB_SOCKET";
/**
* A private server-owned directory holding one server-owned socket, outside
* the brain: never a path a worker or the brain could have supplied.
*/
function serverSocketDirectory(requested: string, socket: string, brain: string): string {
function serverSocketDirectory(requested: string, socket: string, brain: string, purpose = "the provider relay"): string {
const separateIdentity = Boolean(workerIdentityHelper());
const serverUid = process.getuid?.(), serverGid = process.getgid?.();
try {
Expand All @@ -399,7 +417,7 @@ function serverSocketDirectory(requested: string, socket: string, brain: string)
&& (!separateIdentity || directoryInfo.gid === serverGid && socketInfo.gid === serverGid)
&& !holds(brain, directory) && !holds(directory, brain)) return directory;
} catch { /* Missing, aliased or unreadable IPC is never launch authority. */ }
throw new WorkerHostError("the provider relay requires its private server-owned directory and socket");
throw new WorkerHostError(`${purpose} requires its private server-owned directory and socket`);
}

/**
Expand Down Expand Up @@ -436,7 +454,7 @@ function maintenanceMounts(envelope: MaintenanceEnvelope, brain: string, egressM
}))) throw new WorkerHostError("a private mask ancestor overlaps the brain or required runtime");
return covered;
};
for (const requested of [...HOST_MASKS, ...(envelope.maskPaths ?? [])]) {
for (const requested of [...HOST_MASKS, ...HOST_FILE_MASKS, ...(envelope.maskPaths ?? [])]) {
if (!isAbsolute(requested)) throw new WorkerHostError("maintenance worker masks must be absolute paths");
let path: string;
try { path = realpathSync(requested); } catch { continue; }
Expand Down Expand Up @@ -485,6 +503,7 @@ function maintenanceMounts(envelope: MaintenanceEnvelope, brain: string, egressM
if (!envelope.credentials) throw new WorkerHostError("only a credentialed maintenance worker reaches the provider relay");
argv.push("--ro-bind", serverSocketDirectory(envelope.providerRelay, "relay.sock", brain), WORKER_PROVIDER_RELAY_DIR);
}
if (envelope.githubRelay) argv.push("--ro-bind", serverSocketDirectory(envelope.githubRelay, "github.sock", brain, "the module GitHub relay"), WORKER_MODULE_GITHUB_DIR);
if (envelope.network) {
try {
if (lstatSync("/etc/resolv.conf").isSymbolicLink() && statSync("/etc/resolv.conf").isFile()) bindBack("/etc/resolv.conf");
Expand Down Expand Up @@ -625,7 +644,7 @@ export function workerCommand(input: WorkerLaunch): string[] {
if (input.sandbox?.dataTree && (maintenance || transport || workerProfile(input.sandbox) === "governed" || !input.startupView))
throw new WorkerHostError("a turn data tree belongs only to a worker on an immutable startup view");
const emptyHome = !input.restricted && input.env.HOME === WORKER_EMPTY_HOME;
const reservedRuntimePaths = ["/proc", "/dev", scratch, WORKER_STATE, ...(emptyHome ? [WORKER_EMPTY_HOME] : []), WORKER_AREA_ROOT, WORKER_DATA_ROOT, WORKER_WORKTREE_ROOT, WORKER_REFERENCE_ROOT, WORKER_XDG_HOME, WORKER_INFERENCE_DIR, WORKER_EGRESS_DIR, WORKER_PROVIDER_RELAY_DIR,
const reservedRuntimePaths = ["/proc", "/dev", scratch, WORKER_STATE, ...(emptyHome ? [WORKER_EMPTY_HOME] : []), WORKER_AREA_ROOT, WORKER_DATA_ROOT, WORKER_WORKTREE_ROOT, WORKER_REFERENCE_ROOT, WORKER_XDG_HOME, WORKER_INFERENCE_DIR, WORKER_EGRESS_DIR, WORKER_PROVIDER_RELAY_DIR, WORKER_MODULE_GITHUB_DIR,
MAINTENANCE_HOME, ...Object.values(MAINTENANCE_XDG_DIRS), "/tmp/brain-maintenance-output",
...(maintenance?.output ? [maintenance.output.target] : []), ...(transport ? [transport.mirror, ...(transport.writePaths ?? [])] : [])];
const runtimeEntries = input.command.filter((path, index) => isAbsolute(path) && existsSync(path) && (index === 0 || !reservedRuntimePaths.some(reserved => holds(reserved, runtimeCanonicalName(path)) || holds(runtimeCanonicalName(path), reserved))));
Expand Down Expand Up @@ -694,7 +713,11 @@ export function workerCommand(input: WorkerLaunch): string[] {
const clear = argv.pop();
const copies = input.areaOutput && input.sandbox?.profile === "strict"
? input.sandbox.areas.filter(area => area.mount.writable).map(area => ({ from: join(brain, area.rel), to: `${WORKER_AREA_ROOT}/${area.name}` })) : [];
argv.push(...maintenanceEnvMasks(input.startupView?.root ?? brain, brain, copies), clear!);
// An agent worker's host view covers the host files too (#4259); a restricted or transport root has none of them.
const hostFiles = input.restricted || transport ? [] : HOST_FILE_MASKS.flatMap(path => {
try { return statSync(path).isFile() ? ["--ro-bind", "/dev/null", path] : []; } catch { return []; }
});
argv.push(...maintenanceEnvMasks(input.startupView?.root ?? brain, brain, copies), ...hostFiles, clear!);
}

// A private tmpfs of exactly the allowance. Nothing on the host backs it,
Expand Down Expand Up @@ -726,6 +749,7 @@ export function workerCommand(input: WorkerLaunch): string[] {
if (withheld?.length) argv.push("--setenv", WITHHELD_KEYS_ENV, withheld.join(","));
if (providerRelay) argv.push("--setenv", PROVIDER_RELAY_SOCKET_ENV, WORKER_PROVIDER_RELAY_SOCKET);
else if (maintenance?.providerRelay) argv.push("--setenv", PROVIDER_RELAY_SOCKET_ENV, `${WORKER_PROVIDER_RELAY_DIR}/relay.sock`);
if (maintenance?.githubRelay) argv.push("--setenv", MODULE_GITHUB_SOCKET_ENV, `${WORKER_MODULE_GITHUB_DIR}/github.sock`);
argv.push(...writable.env, "--setenv", "BRAIN_WORKER_SCRATCH", scratch,
"--chdir", transport ? transport.mirror : brain, "--", ...rlimitPrefix(launchLimits(input)), ...(gated(input) ? [...STATE_GATE] : []),
...payloadCommand(input));
Expand Down
Loading
Loading