From 480ce4e1f0933b7ac2d89aa7cac98177dfc14650 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:31:49 +0000 Subject: [PATCH 01/22] CONTRACT: feat(ui-server, ui-sdk): a host GitHub API relay for module cron jobs (#4259) A module job granted a github.com repository reaches its API through a per-run Unix-socket relay bound read-only into its worker. The relay adds BRAIN_UI_MODULE_GITHUB_TOKEN (no fallback), relays granted REST reads and repository GraphQL queries, and writes only what BRAIN_UI_MODULE_GITHUB_WRITES enables per repository; each write is a github_write Activity event. Co-Authored-By: Claude Opus 5.5 --- .changeset/4259-module-github-relay.md | 6 + docs/decisions/governed-writable-workers.md | 16 ++ docs/hosting/agent-workers.md | 5 + docs/integration-contract.md | 8 + docs/integration-contract/package-api.md | 23 ++ docs/modules.md | 27 ++ .../ui-sdk/src/server/maintenance-worker.ts | 3 + packages/ui-sdk/src/server/worker-launcher.ts | 17 +- packages/ui-server/src/bin/brain-ui-cron.ts | 2 + packages/ui-server/src/brain/host-boundary.ts | 6 + packages/ui-server/src/config/env.ts | 33 +++ packages/ui-server/src/cron/emit.ts | 3 + packages/ui-server/src/cron/run-job.ts | 27 +- packages/ui-server/src/github/module-relay.ts | 256 ++++++++++++++++++ .../tests/cron-module-github-relay.test.ts | 75 +++++ .../maintenance-module-github-relay.test.ts | 56 ++++ .../tests/module-github-relay.test.ts | 135 +++++++++ 17 files changed, 695 insertions(+), 3 deletions(-) create mode 100644 .changeset/4259-module-github-relay.md create mode 100644 packages/ui-server/src/github/module-relay.ts create mode 100644 packages/ui-server/tests/cron-module-github-relay.test.ts create mode 100644 packages/ui-server/tests/maintenance-module-github-relay.test.ts create mode 100644 packages/ui-server/tests/module-github-relay.test.ts diff --git a/.changeset/4259-module-github-relay.md b/.changeset/4259-module-github-relay.md new file mode 100644 index 0000000000..69dceafc7f --- /dev/null +++ b/.changeset/4259-module-github-relay.md @@ -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. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 08e7d87cc5..66b5641429 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -603,6 +603,22 @@ 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, because +a maintenance worker has no network namespace route to the host. A token placed +in the job's worker and leaving API writes to the operator's own host jobs +were both rejected. + 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. diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index bb0e0c9bf2..23c804f1b1 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -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 diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 93ec8afb11..c792c89dca 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -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-ui/modules//`, diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 3e829dc991..82a00edbce 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1023,6 +1023,29 @@ the mirror read-only and `url.file://.insteadOf` rewrites for the URL's plain, `/`, `.git` and `.git/` spellings. It never receives a Git credential. The crontab layout is unchanged. + + +**Additive module GitHub relay (0.45.0, #4259).** A module job granted a +`https://github.com//` 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///…` +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, only where +the operator's `BRAIN_UI_MODULE_GITHUB_WRITES` enables them for that repository, +`POST /repos//issues//comments` with exactly `{ body }` (`issue_comment`) +and `PATCH /repos//issues/` 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, 502 +or 503 (`unavailable` without the token). 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 }`. 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 diff --git a/docs/modules.md b/docs/modules.md index ac67655325..3debc86b79 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -162,6 +162,33 @@ 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 token and has no +network. 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///…` 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. +- **Writes:** only what the operator enables per repository in + `BRAIN_UI_MODULE_GITHUB_WRITES`, as `https://github.com//#`: + `issue_comment` (`POST /repos//issues//comments` with `{ body }`) and + `issue_state` (`PATCH /repos//issues/` 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, a redirect, more + than 500 calls in a run) is refused before any request leaves the host. + ### Hygiene checks read the index through `ctx.queries` A hygiene check receives `{ queries, root, config }`. `queries` is a frozen diff --git a/packages/ui-sdk/src/server/maintenance-worker.ts b/packages/ui-sdk/src/server/maintenance-worker.ts index 1c3ba9c827..dd8ba593b4 100644 --- a/packages/ui-sdk/src/server/maintenance-worker.ts +++ b/packages/ui-sdk/src/server/maintenance-worker.ts @@ -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. */ @@ -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 } : {}), diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index de3aaf75f6..7e0a2993a2 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -210,6 +210,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 @@ -382,11 +389,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 { @@ -399,7 +410,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`); } /** @@ -485,6 +496,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"); @@ -726,6 +738,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)); diff --git a/packages/ui-server/src/bin/brain-ui-cron.ts b/packages/ui-server/src/bin/brain-ui-cron.ts index ddd8889f6d..9fea70797d 100644 --- a/packages/ui-server/src/bin/brain-ui-cron.ts +++ b/packages/ui-server/src/bin/brain-ui-cron.ts @@ -177,6 +177,8 @@ if (subcommand === "run") { // Module jobs only: the operator's allow-list, never the brain, bounds what is fetched (#3380). repositories: cronJobRepositories({ boundary: host.boundary, dbPath: config.dbPath, moduleDiscoveryEnv: config.moduleDiscoveryEnv, env: config.childEnv, allowList: config.moduleRepositories.allowed }), + // Their granted GitHub repositories' API, through the module GitHub relay (#4259). + githubRelay: { token: config.moduleGitHub.token, writes: config.moduleGitHub.writes }, }); } finally { await host.close(); } process.exit(code); diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 874fe8af29..8edbc09438 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -89,6 +89,11 @@ export interface BrainExecution { * mirror read-only, with a Git URL rewrite onto it. Never a credential. */ repositories?: readonly ModuleRepositoryAccess[]; + /** + * @internal The cron runner's module GitHub relay directory for this job + * (#4259), bound read-only into its worker. It holds no credential. + */ + githubRelay?: string; /** @internal Take the contention lock after writer-gate admission, never before it. */ lock?: { keyed: import("@schlessera/brain-ui-sdk/server").KeyedLock; key: string }; /** @internal The turn whose tool started this run: its relayed provider spend is charged there (#1673). */ @@ -486,6 +491,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { env, credentials: execution.credentials, ...(relay ? { providerRelay: relay.dir, maskEnvFiles: true } : {}), + ...("githubRelay" in execution && execution.githubRelay ? { githubRelay: execution.githubRelay } : {}), ...(execution.credentials && options.home ? { home: options.home } : {}), readPaths: [...(exec.wrapper ? [exec.wrapper] : []), ...serverInstallation(), ...(repositories?.readPaths ?? [])], ...(repositories ? { gitConfig: repositories.gitConfig } : {}), diff --git a/packages/ui-server/src/config/env.ts b/packages/ui-server/src/config/env.ts index b3224d3bc1..5198dc60be 100644 --- a/packages/ui-server/src/config/env.ts +++ b/packages/ui-server/src/config/env.ts @@ -21,6 +21,7 @@ import { ATTACHMENT_POOL_DEFAULT_BYTES, isThinkingLevel, type ThinkingLevel } fr import { CRON_CONTROL_ENV_NAMES } from "../cron/emit.js"; import { parseRepositoryAllowList } from "../brain/module-repositories.js"; +import { parseModuleGitHubWrites, type ModuleGitHubWrite } from "../github/module-relay.js"; import { parseProviderRecipientOrigins } from "../brain/provider-recipients.js"; import { SEVERITIES, type Severity } from "../observability/types.js"; @@ -203,6 +204,26 @@ export const ENV_VARS: readonly EnvVarDescriptor[] = [ default: "(empty — no module repository is fetched)", required: false, }, + { + name: "BRAIN_UI_MODULE_GITHUB_TOKEN", + description: + "GitHub token for the module GitHub relay (#4259): the GitHub API calls a module cron job makes to the repositories it was granted " + + "(the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories, with Issues read " + + "and, only where BRAIN_UI_MODULE_GITHUB_WRITES enables a write, Issues write. No fallback: GITHUB_TOKEN, the sync token and " + + "BRAIN_UI_GITHUB_TOOLS_TOKEN are never used, and without this one every relayed call is refused. Read by the cron runner only, " + + "never forwarded to a job or worker.", + default: null, + required: false, + }, + { + name: "BRAIN_UI_MODULE_GITHUB_WRITES", + description: + "Operator list of the GitHub writes a module cron job may make through the module GitHub relay (#4259), comma or whitespace separated, " + + "each `https://github.com//#` with operation `issue_comment` or `issue_state`. A repository must also be granted " + + "to the job. Read by the cron runner only. Empty enables no write.", + default: "(empty — no write)", + required: false, + }, { name: "BRAIN_UI_SYNC_GITHUB_TOKEN", description: @@ -1025,6 +1046,8 @@ export interface CronConfig { cliProviderOrigins: ReadonlyMap; /** BRAIN_UI_MODULE_REPOSITORIES: the operator's allow-list of repositories a module job may read (#3380). */ moduleRepositories: { allowed: string[]; invalid: string[] }; + /** The module GitHub relay's credential and enabled writes (#4259); the token is read only here. */ + moduleGitHub: { token: () => string | undefined; writes: Map>; invalid: string[] }; } function scheduleInferenceOrigins(raw: string | undefined): string[] | null { @@ -1389,6 +1412,7 @@ export function resolveCronConfig( exec: execConfig(env), cliProviderOrigins: parseCliProviderOrigins(env.BRAIN_UI_CLI_PROVIDER_ORIGINS), moduleRepositories: parseRepositoryAllowList(env.BRAIN_UI_MODULE_REPOSITORIES), + moduleGitHub: { token: moduleGitHubTokenSource(env), ...parseModuleGitHubWrites(env.BRAIN_UI_MODULE_GITHUB_WRITES) }, }; } @@ -1482,6 +1506,15 @@ export function githubToolsTokenSource(env: NodeJS.ProcessEnv = process.env): () return () => token; } +/** + * The module GitHub relay's credential (#4259): `BRAIN_UI_MODULE_GITHUB_TOKEN` + * and nothing else, read once into a closure. + */ +export function moduleGitHubTokenSource(env: NodeJS.ProcessEnv = process.env): () => string | undefined { + const token = env.BRAIN_UI_MODULE_GITHUB_TOKEN?.trim() || undefined; + return () => token; +} + /** * The pi config directory, resolved with EXACTLY the precedence pi-web-access * uses for its `web-search.json` (PI_CODING_AGENT_DIR, then XDG_CONFIG_HOME/pi, diff --git a/packages/ui-server/src/cron/emit.ts b/packages/ui-server/src/cron/emit.ts index e6c4fb1287..9531737f41 100644 --- a/packages/ui-server/src/cron/emit.ts +++ b/packages/ui-server/src/cron/emit.ts @@ -319,6 +319,9 @@ export const CRON_CONTROL_ENV_NAMES: readonly string[] = [ "BRAIN_UI_MAINTENANCE_TEMP_BUDGET_BYTES", // The operator's module repository allow-list (#3380): the runner reads it, no job receives it. "BRAIN_UI_MODULE_REPOSITORIES", + // The module GitHub relay's credential and enabled writes (#4259): the runner reads them, no job receives them. + "BRAIN_UI_MODULE_GITHUB_TOKEN", + "BRAIN_UI_MODULE_GITHUB_WRITES", ]; export function emitEnvironment( diff --git a/packages/ui-server/src/cron/run-job.ts b/packages/ui-server/src/cron/run-job.ts index 557387ca4f..04872eb40a 100644 --- a/packages/ui-server/src/cron/run-job.ts +++ b/packages/ui-server/src/cron/run-job.ts @@ -16,6 +16,7 @@ import { cronJobClass, type HostBoundary } from "../brain/host-boundary.js"; import { parseSyncResult, syncActivityAttrs, syncMessage } from "../brain/sync-result.js"; import { execWrapperSpawnOptions } from "@schlessera/brain-ui-sdk/internal"; import type { JobRepositories } from "./job-repositories.js"; +import { githubRepositoryOf, startModuleGitHubRelay, type ModuleGitHubRelay, type ModuleGitHubRelayOptions } from "../github/module-relay.js"; import { wrapCommand } from "@schlessera/brain-ui-sdk/server"; /** Tail of stderr retained for the cron_runs error row. */ @@ -65,6 +66,8 @@ interface SpawnedJob { interface RunRecorder { /** `attrs` join the root span's own on its terminal write. */ finish(error: string | undefined, output: string, exitCode: number, attrs?: Record): void; + /** One event on the run's root span; fail-open. */ + event?(type: string, payload: unknown): void; close(): void; } @@ -84,6 +87,12 @@ interface RunJobOptions { * before it launches. A refusal fails the run without starting the job. */ repositories?: (jobName: string, command: readonly string[]) => Promise; + /** + * @internal The module GitHub relay (#4259): a job granted GitHub + * repositories reaches their API through a per-run host relay that holds + * this credential and allows only these writes. + */ + githubRelay?: Pick; stdout?: TextSink; stderr?: TextSink; } @@ -205,6 +214,9 @@ async function startRecord( }, HEARTBEAT_MS); return { + event(type, payload) { + try { store.appendEvent(rootSpanId, type, payload); } catch { /* Enrichment only. */ } + }, finish(error, output, exitCode, attrs) { record.finish(error); try { @@ -276,6 +288,8 @@ export async function runJob( const held = syncJob ? holdStdout(stdout) : null; let spanAttrs: Record | undefined = syncJob ? syncActivityAttrs(null) : undefined; + // A job's module GitHub relay (#4259) lives exactly as long as its run. + let githubRelay: ModuleGitHubRelay | undefined; try { const spawn = dependencies.spawn ?? ((command, spawnOptions) => Bun.spawn(command, spawnOptions)); // Through the exec wrapper like every other child. A scheduled job runs a @@ -309,9 +323,16 @@ export async function runJob( if (access && !access.ok) throw new JobRefusedError(access.reason); // The sink is the one host file the job may append to. closeSync(openSync(sinkPath, "a", 0o600)); + // Its granted GitHub repositories' API, through a per-run host relay (#4259). + const githubRepositories = access?.ok ? access.repositories.map(repository => githubRepositoryOf(repository.url)).filter((name): name is string => name !== null) : []; + if (githubRepositories.length && options.githubRelay) { + githubRelay = startModuleGitHubRelay({ ...options.githubRelay, repositories: githubRepositories, + observe: write => recorder?.event?.("github_write", write) }); + } proc = await options.boundary.launch({ argv: options.command, env, ...cronJobClass(options.jobName), purpose: `cron ${options.jobName}`, writeFiles: [sinkPath], ...(syncJob ? { sync: true } : {}), - ...(access?.ok && access.repositories.length ? { repositories: access.repositories } : {}) }); + ...(access?.ok && access.repositories.length ? { repositories: access.repositories } : {}), + ...(githubRelay ? { githubRelay: githubRelay.dir } : {}) }); } else { proc = spawn(wrapCommand(options.command, cronExec.wrapper), { stdin: "inherit", @@ -380,6 +401,10 @@ export async function runJob( } } + try { await githubRelay?.stop(); } catch (error) { + writeLine(stderr, `[cron-run] failed to stop the module GitHub relay: ${messageOf(error)}`); + } + if (recorder) { try { recorder.finish(errorMessage, outputTail.trim(), exitCode, spanAttrs); diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts new file mode 100644 index 0000000000..c9bcd68eb3 --- /dev/null +++ b/packages/ui-server/src/github/module-relay.ts @@ -0,0 +1,256 @@ +/** + * The host GitHub API relay for module cron jobs (#4259). + * + * A scheduled module job runs in a maintenance worker with no credential and + * no network. A job whose repositories the host granted (the module's + * `repositories` ∩ `BRAIN_UI_MODULE_REPOSITORIES`, the same grant as its read + * mirror) also gets this per-run relay: a Unix socket in a private directory + * the launcher binds read-only into that one worker. The job sends ordinary + * GitHub API requests to the socket; the relay: + * + * - forwards only to `https://api.github.com`, never a redirect, with the host + * credential `BRAIN_UI_MODULE_GITHUB_TOKEN` and no other token; + * - reads: REST `GET /repos///…` for a granted repository, and + * GraphQL queries (never a mutation or subscription) whose only root field + * is `repository(owner:, name:)` naming a granted repository; + * - writes: only an operation the operator enabled for that repository in + * `BRAIN_UI_MODULE_GITHUB_WRITES`: `issue_comment` + * (`POST /repos//issues//comments`, `{ body }`) and `issue_state` + * (`PATCH /repos//issues/`, `{ state, state_reason? }`); + * - refuses everything else before any request leaves the host, with a + * message naming the setting, and bounds request size, response size and + * calls per run. It reports each write, never the token. + */ +import { chmodSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { workerIdentityHelper } from "@schlessera/brain-ui-sdk/internal"; +import { GITHUB_API_ORIGIN } from "@schlessera/brain-ui-sdk/tool-contracts"; + +/** The relay's socket name in its private directory. */ +export const MODULE_GITHUB_RELAY_SOCKET_NAME = "github.sock"; +/** The write operations an operator can enable per repository. */ +export const MODULE_GITHUB_WRITES = ["issue_comment", "issue_state"] as const; +export type ModuleGitHubWrite = (typeof MODULE_GITHUB_WRITES)[number]; +/** A request body larger than this is refused before it is forwarded. */ +export const MAX_MODULE_GITHUB_REQUEST_BYTES = 1024 * 1024; +/** A response larger than this is refused rather than relayed. */ +export const MAX_MODULE_GITHUB_RESPONSE_BYTES = 16 * 1024 * 1024; +/** Calls one run may make through the relay. */ +export const MAX_MODULE_GITHUB_CALLS = 500; +const RESPONSE_HEADERS = ["content-type", "link", "etag", "x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-github-request-id"]; +const NAME = /^[A-Za-z0-9_.-]{1,100}$/; + +/** One write the relay forwarded, for the job's Activity run. */ +export interface ModuleGitHubWriteRecord { repository: string; operation: ModuleGitHubWrite; number: number; status: number } + +export interface ModuleGitHubRelayOptions { + /** The host credential, read at the edge; absent refuses every call. */ + token: () => string | undefined; + /** Granted repositories as `owner/repo`. */ + repositories: readonly string[]; + /** Operator-enabled writes per granted `owner/repo`. */ + writes: ReadonlyMap>; + observe?: (write: ModuleGitHubWriteRecord) => void; + /** @internal Test seams. */ + fetch?: typeof fetch; origin?: string; maxCalls?: number; +} + +export interface ModuleGitHubRelay { dir: string; socketPath: string; stop(): Promise } + +const lower = (repository: string) => repository.toLowerCase(); + +/** `owner/repo` of a granted GitHub repository URL, or null for any other host. */ +export function githubRepositoryOf(url: string): string | null { + try { + const parsed = new URL(url); + if (parsed.protocol !== "https:" || parsed.hostname.toLowerCase() !== "github.com" || parsed.port || parsed.username || parsed.password) return null; + const parts = parsed.pathname.replace(/\/+$/, "").replace(/\.git$/, "").split("/").filter(Boolean); + return parts.length === 2 && parts.every(part => NAME.test(part)) ? `${parts[0]}/${parts[1]}` : null; + } catch { return null; } +} + +/** + * The operator's write list: entries `#`, + * comma or whitespace separated. An unknown operation or a non-GitHub URL is + * reported invalid and enables nothing. + */ +export function parseModuleGitHubWrites(raw: string | undefined): { writes: Map>; invalid: string[] } { + const writes = new Map>(), invalid: string[] = []; + for (const entry of (raw ?? "").split(/[\s,]+/).filter(Boolean)) { + const hash = entry.lastIndexOf("#"); + const repository = hash > 0 ? githubRepositoryOf(entry.slice(0, hash)) : null; + const operation = entry.slice(hash + 1) as ModuleGitHubWrite; + if (!repository || !MODULE_GITHUB_WRITES.includes(operation)) { invalid.push(entry); continue; } + const key = lower(repository); + writes.set(key, (writes.get(key) ?? new Set()).add(operation)); + } + return { writes, invalid }; +} + +class Refusal extends Error { constructor(readonly status: number, readonly code: string, message: string) { super(message); } } +const refuse = (status: number, code: string, message: string): never => { throw new Refusal(status, code, message); }; + +/** GraphQL text with strings, block strings and comments blanked, so structure can be read. */ +function graphqlStructure(query: string): string { + return query.replace(/"""[\s\S]*?"""|"(?:[^"\\\n]|\\.)*"|#[^\n]*/g, match => " ".repeat(match.length)); +} + +/** + * The repository a query reads, when it is one query operation whose only root + * selection is `repository(owner:, name:)`; null otherwise. Arguments are + * string literals or `$variables` resolved from `variables`. + */ +export function graphqlQueryRepository(query: string, variables: unknown): string | null { + const text = graphqlStructure(query); + // Top-level definitions: exactly one operation, and it is a query (or the `{ … }` shorthand). + let depth = 0, operations = 0, start = -1, end = -1, header = ""; + let buffer = ""; + for (let i = 0; i < text.length; i++) { + const char = text[i]!; + if (char === "{") { if (depth === 0) { operations++; start = i; header = buffer.trim(); buffer = ""; } depth++; } + else if (char === "}") { depth--; if (depth < 0) return null; if (depth === 0) end = i; } + else if (depth === 0) buffer += char; + } + if (depth !== 0 || operations !== 1 || buffer.trim() || start < 0 || end < 0) return null; + if (header && !/^query(?:\s+[_A-Za-z][_0-9A-Za-z]*)?\s*(?:\([^)]*\))?$/.test(header)) return null; + // The root selection set: one field, `repository`, with no alias, spread or directive. + const root = text.slice(start + 1, end); + let inner = 0, fields = ""; + for (const char of root) { + if (char === "{" || char === "(") inner++; + if (inner === 0) fields += char; + if (char === "}" || char === ")") inner--; + } + if (!/^\s*repository\s*$/.test(fields)) return null; + const open = root.indexOf("("), close = root.indexOf(")"); + if (!/^\s*repository\s*$/.test(root.slice(0, open)) || open < 0 || close < open) return null; + // The argument text itself, from the original query (blanking keeps every offset). + const args = query.slice(start + 1, end).slice(open + 1, close); + const values = variables && typeof variables === "object" && !Array.isArray(variables) ? variables as Record : {}; + const pairs = args.split(",").map(pair => pair.trim()).filter(Boolean); + if (pairs.length !== 2) return null; + const parsed = new Map(); + for (const pair of pairs) { + const match = /^([_A-Za-z][_0-9A-Za-z]*)\s*:\s*(\$[_A-Za-z][_0-9A-Za-z]*|"[^"\\]*")$/.exec(pair); + if (!match) return null; + const value = match[2]!.startsWith("$") ? values[match[2]!.slice(1)] : match[2]!.slice(1, -1); + if (typeof value !== "string" || !NAME.test(value)) return null; + parsed.set(match[1]!, value); + } + const owner = parsed.get("owner"), name = parsed.get("name"); + return owner && name ? `${owner}/${name}` : null; +} + +async function boundedBody(request: Request): Promise { + const declared = Number(request.headers.get("content-length") ?? "0"); + if (declared > MAX_MODULE_GITHUB_REQUEST_BYTES) refuse(413, "too_large", `A relayed request body is at most ${MAX_MODULE_GITHUB_REQUEST_BYTES} bytes.`); + const bytes = new Uint8Array(await request.arrayBuffer()); + if (bytes.byteLength > MAX_MODULE_GITHUB_REQUEST_BYTES) refuse(413, "too_large", `A relayed request body is at most ${MAX_MODULE_GITHUB_REQUEST_BYTES} bytes.`); + return new TextDecoder().decode(bytes); +} + +function jsonObject(text: string): Record { + let value: unknown; + try { value = JSON.parse(text); } catch { refuse(400, "invalid_body", "The relayed request body must be a JSON object."); } + if (!value || typeof value !== "object" || Array.isArray(value)) refuse(400, "invalid_body", "The relayed request body must be a JSON object."); + return value as Record; +} + +export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): ModuleGitHubRelay { + const origin = options.origin ?? GITHUB_API_ORIGIN; + const granted = new Map(options.repositories.map(repository => [lower(repository), repository])); + const maxCalls = options.maxCalls ?? MAX_MODULE_GITHUB_CALLS; + let calls = 0; + // Private to this server user; the one worker of this run sees only the bound socket. + const dir = mkdtempSync(join(tmpdir(), "brain-module-github-")); + const separateIdentity = Boolean(workerIdentityHelper()); + chmodSync(dir, separateIdentity ? 0o750 : 0o700); + const socketPath = join(dir, MODULE_GITHUB_RELAY_SOCKET_NAME); + const repositoryOf = (owner: string, name: string): string => { + const key = lower(`${owner}/${name}`); + if (!granted.has(key)) refuse(403, "repository_not_granted", `${owner}/${name} is not granted to this job: list it in the module's repositories and in BRAIN_UI_MODULE_REPOSITORIES.`); + return key; + }; + const writeAllowed = (repository: string, operation: ModuleGitHubWrite) => { + if (!options.writes.get(repository)?.has(operation)) + refuse(403, "write_not_enabled", `${operation} on ${granted.get(repository)} is not enabled: add https://github.com/${granted.get(repository)}#${operation} to BRAIN_UI_MODULE_GITHUB_WRITES.`); + }; + + async function handle(request: Request): Promise { + const url = new URL(request.url); + const method = request.method.toUpperCase(); + const path = url.pathname; + if (path.split("/").some(part => part === "." || part === "..") || path.includes("//")) refuse(400, "invalid_path", "The relayed path is not a plain GitHub API path."); + let body: string | undefined; + let write: { repository: string; operation: ModuleGitHubWrite; number: number } | undefined; + const repo = /^\/repos\/([^/]+)\/([^/]+)(\/.*)?$/.exec(path); + if (method === "GET" && repo) { + repositoryOf(decodeURIComponent(repo[1]!), decodeURIComponent(repo[2]!)); + } else if (method === "POST" && path === "/graphql" && !url.search) { + body = await boundedBody(request); + const value = jsonObject(body); + if (typeof value.query !== "string" || Object.keys(value).some(key => !["query", "variables", "operationName"].includes(key))) + refuse(400, "invalid_body", "A relayed GraphQL request is { query, variables?, operationName? }."); + const target = graphqlQueryRepository(value.query as string, value.variables); + if (!target) refuse(403, "graphql_not_allowed", "Only a GraphQL query whose one root field is repository(owner:, name:) on a granted repository is relayed; mutations and other roots are refused."); + repositoryOf(...(target!.split("/") as [string, string])); + } else if (method === "POST" && repo && /^\/issues\/[1-9][0-9]{0,9}\/comments$/.test(repo[3] ?? "") && !url.search) { + const repository = repositoryOf(decodeURIComponent(repo[1]!), decodeURIComponent(repo[2]!)); + writeAllowed(repository, "issue_comment"); + body = await boundedBody(request); + const value = jsonObject(body); + if (typeof value.body !== "string" || !value.body.trim() || Object.keys(value).length !== 1) refuse(400, "invalid_body", "An issue comment is { body } with nonempty text."); + write = { repository, operation: "issue_comment", number: Number(repo[3]!.split("/")[2]) }; + } else if (method === "PATCH" && repo && /^\/issues\/[1-9][0-9]{0,9}$/.test(repo[3] ?? "") && !url.search) { + const repository = repositoryOf(decodeURIComponent(repo[1]!), decodeURIComponent(repo[2]!)); + writeAllowed(repository, "issue_state"); + body = await boundedBody(request); + const value = jsonObject(body); + const keys = Object.keys(value); + if (!["open", "closed"].includes(value.state as string) || keys.some(key => key !== "state" && key !== "state_reason") + || (value.state_reason !== undefined && !["completed", "not_planned", "reopened", null].includes(value.state_reason as string | null))) + refuse(400, "invalid_body", "An issue state change is { state: open|closed, state_reason? } and nothing else."); + write = { repository, operation: "issue_state", number: Number(repo[3]!.split("/")[2]) }; + } else { + refuse(403, "not_relayed", `${method} ${path} is not relayed: reads are GET under a granted /repos/// or a repository GraphQL query; writes are issue_comment and issue_state.`); + } + const token = options.token(); + if (!token) refuse(503, "unavailable", "The module GitHub relay has no credential: set BRAIN_UI_MODULE_GITHUB_TOKEN on the host."); + if (++calls > maxCalls) refuse(429, "budget_exceeded", `This run made its ${maxCalls} relayed GitHub calls.`); + const upstream = await (options.fetch ?? fetch)(new URL(`${path}${url.search}`, origin), { + method, redirect: "manual", ...(body !== undefined ? { body } : {}), + headers: { authorization: `Bearer ${token}`, accept: request.headers.get("accept")?.startsWith("application/vnd.github") ? request.headers.get("accept")! : "application/vnd.github+json", + "x-github-api-version": "2022-11-28", "user-agent": "brain-ui-module", ...(body !== undefined ? { "content-type": "application/json" } : {}) }, + }); + if (upstream.status >= 300 && upstream.status < 400) { await upstream.body?.cancel(); refuse(502, "redirect", "GitHub redirected; the relay never follows a redirect."); } + const bytes = new Uint8Array(await upstream.arrayBuffer()); + if (bytes.byteLength > MAX_MODULE_GITHUB_RESPONSE_BYTES) refuse(502, "response_too_large", `A relayed response is at most ${MAX_MODULE_GITHUB_RESPONSE_BYTES} bytes.`); + if (write) { try { options.observe?.({ ...write, repository: granted.get(write.repository)!, status: upstream.status }); } catch { /* Recording never fails the call. */ } } + const headers = new Headers(); + for (const name of RESPONSE_HEADERS) { const value = upstream.headers.get(name); if (value) headers.set(name, value); } + return new Response(bytes, { status: upstream.status, headers }); + } + + const server = Bun.serve({ + unix: socketPath, + async fetch(request) { + try { return await handle(request); } + catch (error) { + if (error instanceof Refusal) return Response.json({ message: error.message, brain_relay_refusal: error.code }, { status: error.status }); + return Response.json({ message: "The module GitHub relay could not reach GitHub.", brain_relay_refusal: "upstream_unreachable" }, { status: 502 }); + } + }, + }); + chmodSync(socketPath, separateIdentity ? 0o660 : 0o600); + let stopping: Promise | undefined; + return { + dir, socketPath, + stop() { + return stopping ??= (async () => { + await server.stop(true); + rmSync(dir, { recursive: true, force: true }); + })(); + }, + }; +} diff --git a/packages/ui-server/tests/cron-module-github-relay.test.ts b/packages/ui-server/tests/cron-module-github-relay.test.ts new file mode 100644 index 0000000000..8d0e490226 --- /dev/null +++ b/packages/ui-server/tests/cron-module-github-relay.test.ts @@ -0,0 +1,75 @@ +/** + * The cron runner gives a module job its GitHub relay (#4259) only for the + * GitHub repositories the host granted it, for exactly the run's lifetime, and + * records each relayed write on the job's Activity run. The worker is a stub + * boundary that calls the relay the way a job inside the worker would; the + * upstream is a loopback GitHub stand-in. + */ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runJob } from "../src/cron/run-job.js"; +import { createUiDb } from "../src/db/client.js"; +import { parseModuleGitHubWrites } from "../src/github/module-relay.js"; +import type { HostBoundary, BrainExecution } from "../src/brain/host-boundary.js"; + +const TOKEN = "odysseus-module-github-token"; +let upstream: ReturnType; +const seen: Array<{ method: string; path: string; authorization: string | null }> = []; +let dir: string; +beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), "odysseus-cron-github-")); + upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) { + seen.push({ method: request.method, path: new URL(request.url).pathname, authorization: request.headers.get("authorization") }); + return Response.json({ id: 1 }); + } }); +}); +afterAll(() => { upstream.stop(true); rmSync(dir, { recursive: true, force: true }); }); + +const JOB = { jobName: "beacon-run", command: ["brain", "beacon", "run"] }; +const finished = () => ({ stdout: new ReadableStream({ start(c) { c.close(); } }), stderr: new ReadableStream({ start(c) { c.close(); } }), + exited: Promise.resolve(0), settled: Promise.resolve(), signalCode: null, kill() {} }); + +test("a job granted a GitHub repository reaches its API through the run's relay, which records writes and ends with the run", async () => { + const launched: BrainExecution[] = []; + const statuses: number[] = []; + const boundary = { isolated: () => true, brainPath: dir, launch: async (execution: BrainExecution) => { + launched.push(execution); + const socket = join(execution.githubRelay!, "github.sock"); + for (const [method, path, body] of [["GET", "/repos/ithaca/watchtower/issues", undefined], ["POST", "/repos/ithaca/watchtower/issues/7/comments", { body: "Why closed?" }]] as const) { + const response = await fetch(`http://localhost${path}`, { method, unix: socket, ...(body ? { body: JSON.stringify(body) } : {}) } as RequestInit); + statuses.push(response.status); await response.arrayBuffer(); + } + return finished(); + } } as unknown as HostBoundary; + const dbPath = join(dir, "ui.db"); + const code = await runJob({ ...JOB, dbPath, childEnv: { PATH: "/usr/bin:/bin" }, exec: {}, boundary, + stdout: { write() {} }, stderr: { write() {} }, + repositories: async () => ({ ok: true, notes: [], repositories: [{ url: "https://github.com/ithaca/watchtower", mirror: join(dir, "mirror.git") }, + { url: "http://127.0.0.1:9/ithaca/harbor", mirror: join(dir, "harbor.git") }] }), + githubRelay: { token: () => TOKEN, writes: parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment").writes, origin: upstream.url.origin } }, + { sinkPath: join(dir, "sink.jsonl") }); + expect(code).toBe(0); + expect(statuses, "JOB_REACHES_RELAY").toEqual([200, 200]); + expect(seen.every(entry => entry.authorization === `Bearer ${TOKEN}`), "HOST_TOKEN_ADDED").toBe(true); + expect(launched[0]!.env, "TOKEN_NOT_IN_JOB_ENV").not.toHaveProperty("BRAIN_UI_MODULE_GITHUB_TOKEN"); + expect(JSON.stringify(launched[0]!.env)).not.toContain(TOKEN); + expect(existsSync(launched[0]!.githubRelay!), "RELAY_ENDS_WITH_RUN").toBe(false); + const db = createUiDb(dbPath); + try { + const events = db.query("SELECT payload FROM activity_events WHERE event_type = 'github_write'").all() as { payload: string }[]; + expect(events.map(row => JSON.parse(row.payload).v), "WRITE_ON_ACTIVITY_RUN").toEqual([{ repository: "ithaca/watchtower", operation: "issue_comment", number: 7, status: 200 }]); + } finally { db.close(); } +}); + +test("a job granted no GitHub repository gets no relay", async () => { + const launched: BrainExecution[] = []; + const boundary = { isolated: () => true, brainPath: dir, launch: async (execution: BrainExecution) => { launched.push(execution); return finished(); } } as unknown as HostBoundary; + const code = await runJob({ ...JOB, dbPath: join(dir, "ui-none.db"), childEnv: { PATH: "/usr/bin:/bin" }, exec: {}, boundary, + stdout: { write() {} }, stderr: { write() {} }, + repositories: async () => ({ ok: true, notes: [], repositories: [{ url: "http://127.0.0.1:9/ithaca/harbor", mirror: join(dir, "harbor.git") }] }), + githubRelay: { token: () => TOKEN, writes: new Map() } }, { sinkPath: join(dir, "sink-none.jsonl") }); + expect(code).toBe(0); + expect(launched[0]!.githubRelay, "NO_GITHUB_GRANT_NO_RELAY").toBeUndefined(); +}); diff --git a/packages/ui-server/tests/maintenance-module-github-relay.test.ts b/packages/ui-server/tests/maintenance-module-github-relay.test.ts new file mode 100644 index 0000000000..f6f7691e0d --- /dev/null +++ b/packages/ui-server/tests/maintenance-module-github-relay.test.ts @@ -0,0 +1,56 @@ +/** + * A credential-free maintenance worker reaches the module GitHub relay (#4259) + * under real bubblewrap: the relay's socket is bound read-only at + * `/run/brain-github`, the worker holds no token and no network, and its + * request reaches the loopback GitHub stand-in with the host's token. + */ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { createNativeBrainManagerClient } from "@schlessera/brain-ui-sdk/internal"; +import { createHostBoundary } from "../src/brain/host-boundary.js"; +import { startModuleGitHubRelay } from "../src/github/module-relay.js"; +import { createNativeAppFixture } from "./helpers/native-app-fixture.js"; + +const ROOT = resolve(import.meta.dir, "../../.."); +const TOKEN = "odysseus-module-github-token"; +let upstream: ReturnType; +const seen: Array<{ path: string; authorization: string | null }> = []; +let root: string, brain: string; +const cleanup: Array<() => Promise | void> = []; + +beforeAll(() => { + upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) { + seen.push({ path: new URL(request.url).pathname, authorization: request.headers.get("authorization") }); + return Response.json([{ number: 7, title: "Watchtower lamp" }]); + } }); + mkdirSync(join(ROOT, "tmp"), { recursive: true }); + root = mkdtempSync(join(ROOT, "tmp/maintenance-module-github-")); + brain = join(root, "brain"); + mkdirSync(join(brain, "notes"), { recursive: true }); + writeFileSync(join(brain, "notes/ithaca.md"), "---\ntype: note\ntitle: Ithaca harbour\ncreated: 2026-07-12\nupdated: 2026-07-12\n---\nTelemachus keeps the watchtower lit.\n"); +}); +afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); seen.length = 0; }); +afterAll(() => { upstream.stop(true); rmSync(root, { recursive: true, force: true }); }); + +test("a credential-free maintenance worker reaches the relay through its socket, holding no token and no network", async () => { + const state = mkdtempSync(join(root, "state-")); + const native = createNativeAppFixture(brain); cleanup.push(native.close); + const host = createHostBoundary({ brainPath: brain, dbPath: join(state, "ui.db"), exec: {}, nativeManager: createNativeBrainManagerClient(native.nativeBrain) }); + const relay = startModuleGitHubRelay({ token: () => TOKEN, repositories: ["ithaca/watchtower"], writes: new Map(), origin: upstream.url.origin }); + cleanup.push(() => relay.stop()); + const program = `const socket = process.env.BRAIN_MODULE_GITHUB_SOCKET; + const relayed = await fetch("http://localhost/repos/ithaca/watchtower/issues", { unix: socket }).then(r => r.status, e => String(e)); + const direct = await fetch(${JSON.stringify(upstream.url.origin)} + "/repos/ithaca/watchtower/issues").then(r => r.status, () => "unreachable"); + console.log(JSON.stringify({ socket, relayed, direct, env: process.env }));`; + const child = await host.launch({ argv: [process.execPath, "--config=/dev/null", "-e", program], env: { PATH: "/usr/bin:/bin" }, + credentials: false, gate: "shared", purpose: "Odysseus module job", githubRelay: relay.dir }); + const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + expect(exitCode, stderr).toBe(0); + const observed = JSON.parse(stdout.trim().split("\n").at(-1)!) as { socket: string; relayed: number | string; direct: number | string; env: Record }; + expect(observed.socket, "WORKER_SOCKET_PATH").toBe("/run/brain-github/github.sock"); + expect(observed.relayed, "WORKER_REACHES_RELAY").toBe(200); + expect(observed.direct, "WORKER_HAS_NO_NETWORK").toBe("unreachable"); + expect(stdout, "WORKER_HOLDS_NO_TOKEN").not.toContain(TOKEN); + expect(seen, "RELAY_ADDS_HOST_TOKEN").toEqual([{ path: "/repos/ithaca/watchtower/issues", authorization: `Bearer ${TOKEN}` }]); +}, 120_000); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts new file mode 100644 index 0000000000..e4e9391835 --- /dev/null +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -0,0 +1,135 @@ +/** + * The module GitHub relay (#4259): a module cron job's only route to the + * GitHub API of its granted repositories. The upstream is a loopback GitHub + * stand-in; no real token and no network. + */ +import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; +import { moduleGitHubTokenSource } from "../src/config/env.js"; +import { graphqlQueryRepository, parseModuleGitHubWrites, startModuleGitHubRelay, type ModuleGitHubRelay, type ModuleGitHubWriteRecord } from "../src/github/module-relay.js"; + +const TOKEN = "odysseus-module-github-token"; +let upstream: ReturnType; +const seen: Array<{ method: string; path: string; authorization: string | null; body: string }> = []; +let redirect = false; + +beforeAll(() => { + upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { + const url = new URL(request.url); + seen.push({ method: request.method, path: `${url.pathname}${url.search}`, authorization: request.headers.get("authorization"), body: await request.text() }); + if (redirect) return new Response(null, { status: 302, headers: { location: "https://elsewhere.example/" } }); + return Response.json({ ok: true, path: url.pathname }, { headers: { link: '; rel="next"' } }); + } }); +}); +afterAll(() => { upstream.stop(true); }); +const relays: ModuleGitHubRelay[] = []; +afterEach(async () => { for (const relay of relays.splice(0)) await relay.stop(); seen.length = 0; redirect = false; }); + +function relay(options: { token?: string | undefined; writes?: string; maxCalls?: number } = {}) { + const writes: ModuleGitHubWriteRecord[] = []; + const started = startModuleGitHubRelay({ token: () => "token" in options ? options.token : TOKEN, repositories: ["ithaca/watchtower"], + writes: parseModuleGitHubWrites(options.writes ?? "").writes, observe: write => { writes.push(write); }, + origin: upstream.url.origin, ...(options.maxCalls ? { maxCalls: options.maxCalls } : {}) }); + relays.push(started); + const call = (method: string, path: string, body?: unknown, headers: Record = {}) => fetch(`http://localhost${path}`, { + method, unix: started.socketPath, headers: { authorization: "Bearer worker-supplied", ...headers }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + } as RequestInit); + return { call, writes, started }; +} + +describe("module GitHub relay reads (#4259)", () => { + test("a granted repository read is forwarded with the host token only, and pagination headers come back", async () => { + const { call } = relay(); + const response = await call("GET", "/repos/ithaca/watchtower/issues?state=closed"); + expect(response.status).toBe(200); + expect(response.headers.get("link"), "RELAY_KEEPS_LINK").toContain("page=2"); + expect(seen, "RELAY_FORWARDS_WITH_HOST_TOKEN").toEqual([{ method: "GET", path: "/repos/ithaca/watchtower/issues?state=closed", authorization: `Bearer ${TOKEN}`, body: "" }]); + }); + + test("a repository outside the grant, and any other path, is refused before a request leaves the host", async () => { + const { call } = relay(); + const foreign = await call("GET", "/repos/sparta/barracks/issues"); + expect(foreign.status, "FOREIGN_REPOSITORY_REFUSED").toBe(403); + expect((await foreign.json()).brain_relay_refusal).toBe("repository_not_granted"); + expect((await call("GET", "/user")).status, "NON_REPOSITORY_PATH_REFUSED").toBe(403); + expect((await call("DELETE", "/repos/ithaca/watchtower")).status, "DELETE_REFUSED").toBe(403); + expect((await call("GET", "/repos/ithaca/watchtower/../../sparta/barracks")).status).not.toBe(200); + expect(seen, "NOTHING_FORWARDED").toEqual([]); + }); + + test("a repository GraphQL query is forwarded; a mutation, another root, an alias or a second root is refused", async () => { + const { call } = relay(); + const query = "query Closed($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { issues(last: 5, states: CLOSED) { nodes { number } } } }"; + expect((await call("POST", "/graphql", { query, variables: { owner: "ithaca", name: "watchtower" } })).status, "GRAPHQL_QUERY_FORWARDED").toBe(200); + expect(seen).toHaveLength(1); + const refused = [ + { query: 'mutation { closeIssue(input: { issueId: "I_1" }) { clientMutationId } }' }, + { query: "{ viewer { login } }" }, + { query: '{ r: repository(owner: "ithaca", name: "watchtower") { id } }' }, + { query: '{ repository(owner: "ithaca", name: "watchtower") { id } viewer { login } }' }, + { query: query, variables: { owner: "sparta", name: "barracks" } }, + { query: '{ repository(owner: "ithaca", name: "watchtower") { id } } mutation { addComment(input: {}) { clientMutationId } }' }, + ]; + for (const body of refused) { + const response = await call("POST", "/graphql", body); + expect(response.status, `GRAPHQL_REFUSED: ${body.query}`).toBe(403); + } + expect(seen, "REFUSED_GRAPHQL_NOT_FORWARDED").toHaveLength(1); + }); + + test("without BRAIN_UI_MODULE_GITHUB_TOKEN every call is refused, naming the setting", async () => { + const { call } = relay({ token: undefined }); + const response = await call("GET", "/repos/ithaca/watchtower/issues"); + expect(response.status).toBe(503); + expect((await response.json()).message, "NO_TOKEN_NAMES_SETTING").toContain("BRAIN_UI_MODULE_GITHUB_TOKEN"); + expect(seen).toEqual([]); + expect(moduleGitHubTokenSource({ GITHUB_TOKEN: "x", BRAIN_UI_SYNC_GITHUB_TOKEN: "y", BRAIN_UI_GITHUB_TOOLS_TOKEN: "z" })(), "NO_TOKEN_FALLBACK").toBeUndefined(); + expect(moduleGitHubTokenSource({ BRAIN_UI_MODULE_GITHUB_TOKEN: ` ${TOKEN} ` })()).toBe(TOKEN); + }); + + test("a redirect is never followed, and the call budget is enforced", async () => { + redirect = true; + const { call } = relay({ maxCalls: 1 }); + expect((await call("GET", "/repos/ithaca/watchtower")).status, "REDIRECT_REFUSED").toBe(502); + redirect = false; + const over = await call("GET", "/repos/ithaca/watchtower"); + expect(over.status, "BUDGET_ENFORCED").toBe(429); + expect(seen).toHaveLength(1); + }); +}); + +describe("module GitHub relay writes (#4259)", () => { + const COMMENTS = "/repos/ithaca/watchtower/issues/7/comments"; + test("a write the operator has not enabled is refused before any request, naming the setting", async () => { + const { call } = relay({ writes: "https://github.com/ithaca/watchtower#issue_state" }); + const response = await call("POST", COMMENTS, { body: "Telemachus asks why this closed." }); + expect(response.status).toBe(403); + expect((await response.json()).message, "WRITE_NAMES_SETTING").toContain("BRAIN_UI_MODULE_GITHUB_WRITES"); + expect(seen).toEqual([]); + }); + + test("enabled writes are forwarded and recorded; a malformed write body is refused", async () => { + const { call, writes } = relay({ writes: "https://github.com/ithaca/watchtower#issue_comment https://github.com/Ithaca/Watchtower#issue_state" }); + expect((await call("POST", COMMENTS, { body: "Telemachus asks why this closed." })).status, "COMMENT_FORWARDED").toBe(200); + expect((await call("PATCH", "/repos/ithaca/watchtower/issues/7", { state: "open" })).status, "STATE_FORWARDED").toBe(200); + expect((await call("PATCH", "/repos/ithaca/watchtower/issues/7", { state: "open", title: "Renamed" })).status, "STATE_EXTRA_FIELD_REFUSED").toBe(400); + expect((await call("POST", COMMENTS, { body: "x", extra: true })).status, "COMMENT_EXTRA_FIELD_REFUSED").toBe(400); + expect(seen.map(entry => `${entry.method} ${entry.path}`)).toEqual([`POST ${COMMENTS}`, "PATCH /repos/ithaca/watchtower/issues/7"]); + expect(writes, "WRITES_RECORDED").toEqual([ + { repository: "ithaca/watchtower", operation: "issue_comment", number: 7, status: 200 }, + { repository: "ithaca/watchtower", operation: "issue_state", number: 7, status: 200 }, + ]); + }); + + test("the operator list parses only GitHub repositories and known operations", () => { + const parsed = parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment, https://gitlab.com/ithaca/x#issue_comment https://github.com/ithaca/watchtower#merge"); + expect([...parsed.writes.get("ithaca/watchtower") ?? []]).toEqual(["issue_comment"]); + expect(parsed.invalid).toEqual(["https://gitlab.com/ithaca/x#issue_comment", "https://github.com/ithaca/watchtower#merge"]); + }); +}); + +test("graphqlQueryRepository reads literal and variable arguments and ignores strings and comments", () => { + expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { id } }', {})).toBe("ithaca/watchtower"); + expect(graphqlQueryRepository('# mutation { x }\nquery { repository(name: $n, owner: $o) { description } }', { o: "ithaca", n: "watchtower" })).toBe("ithaca/watchtower"); + expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { ...Fields } } fragment Fields on Repository { id }', {})).toBeNull(); + expect(graphqlQueryRepository("subscription { repository(owner: \"ithaca\", name: \"watchtower\") { id } }", {})).toBeNull(); +}); From 3e1c4369a241c10f11174eaa5f03f09aa504895f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:32:28 +0000 Subject: [PATCH 02/22] fix(ui-server): keep the module relay's bounds module-private (#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/github/module-relay.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index c9bcd68eb3..8fd03e249e 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -28,16 +28,16 @@ import { workerIdentityHelper } from "@schlessera/brain-ui-sdk/internal"; import { GITHUB_API_ORIGIN } from "@schlessera/brain-ui-sdk/tool-contracts"; /** The relay's socket name in its private directory. */ -export const MODULE_GITHUB_RELAY_SOCKET_NAME = "github.sock"; +const MODULE_GITHUB_RELAY_SOCKET_NAME = "github.sock"; /** The write operations an operator can enable per repository. */ -export const MODULE_GITHUB_WRITES = ["issue_comment", "issue_state"] as const; +const MODULE_GITHUB_WRITES = ["issue_comment", "issue_state"] as const; export type ModuleGitHubWrite = (typeof MODULE_GITHUB_WRITES)[number]; /** A request body larger than this is refused before it is forwarded. */ -export const MAX_MODULE_GITHUB_REQUEST_BYTES = 1024 * 1024; +const MAX_MODULE_GITHUB_REQUEST_BYTES = 1024 * 1024; /** A response larger than this is refused rather than relayed. */ -export const MAX_MODULE_GITHUB_RESPONSE_BYTES = 16 * 1024 * 1024; +const MAX_MODULE_GITHUB_RESPONSE_BYTES = 16 * 1024 * 1024; /** Calls one run may make through the relay. */ -export const MAX_MODULE_GITHUB_CALLS = 500; +const MAX_MODULE_GITHUB_CALLS = 500; const RESPONSE_HEADERS = ["content-type", "link", "etag", "x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-github-request-id"]; const NAME = /^[A-Za-z0-9_.-]{1,100}$/; From 0527e2707f67852c4966d67f774aff38cafdfcb7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:33:11 +0000 Subject: [PATCH 03/22] docs(ui-server): regenerate the environment table for the module GitHub relay (#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/ui-server/README.md b/packages/ui-server/README.md index 08347f0bd9..0c6bea133c 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -383,6 +383,8 @@ under the [service terms](../geo/README.md#configuration). | `BRAIN_UI_MAINTENANCE_TEMP_BYTES` | Per-maintenance-command temporary-write allowance in bytes, covering its private /tmp, scratch and XDG directories. Positive page-aligned integer. Separate from agent turn temp, runtime state and output staging; overflow is ENOSPC. | 268435456 | | `BRAIN_UI_MODEL_DISCOVERY` | Model discovery against the Anthropic Models API; "0"/"off"/"false" disables. Defaults ON, except under a test runner (NODE_ENV=test) where it defaults OFF. | on (off under NODE_ENV=test) | | `BRAIN_UI_MODEL_TTL_HOURS` | How long a model-discovery result stays fresh, in hours. | 24 | +| `BRAIN_UI_MODULE_GITHUB_TOKEN` | GitHub token for the module GitHub relay (#4259): the GitHub API calls a module cron job makes to the repositories it was granted (the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories, with Issues read and, only where BRAIN_UI_MODULE_GITHUB_WRITES enables a write, Issues write. No fallback: GITHUB_TOKEN, the sync token and BRAIN_UI_GITHUB_TOOLS_TOKEN are never used, and without this one every relayed call is refused. Read by the cron runner only, never forwarded to a job or worker. | — | +| `BRAIN_UI_MODULE_GITHUB_WRITES` | Operator list of the GitHub writes a module cron job may make through the module GitHub relay (#4259), comma or whitespace separated, each `https://github.com//#` with operation `issue_comment` or `issue_state`. A repository must also be granted to the job. Read by the cron runner only. Empty enables no write. | (empty — no write) | | `BRAIN_UI_MODULE_REPOSITORIES` | Operator allow-list of repository URLs (comma or whitespace separated, HTTPS) a module cron job may read. The host fetches a repository a module's `repositories` config asks for only when this list names it too, using the sync transport's credential (BRAIN_UI_SYNC_GITHUB_TOKEN, else GITHUB_TOKEN); the job's worker reads a host mirror and never holds the credential. Read by the cron runner only, never forwarded to a job. Empty refuses every request. | (empty — no module repository is fetched) | | `BRAIN_UI_NATIVE_BRAIN_DELTA_BYTES` | Positive bound for one native metadata delta stream; exceeding it refuses the observation explicitly. Content and retained-history capacities are separate. | 67108864 (64 MiB) | | `BRAIN_UI_NATIVE_BRAIN_LEASE_PATH` | Persistent native checkpoint ownership ledger outside the brain. Defaults beside DB_PATH; required explicitly when the UI database is ephemeral. Keep this path across restarts so dead-owner checkpoints can be reclaimed. | DB_PATH.native-leases.sqlite | From b718919a31231eae83fa8bed7e439b89ef7116d5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:42:45 +0000 Subject: [PATCH 04/22] fix(ui-server, ui-sdk): close GraphQL parsing bypasses, keep the relay token host-only, name settings in refusals (#4259) The relay now relays only a strict GraphQL subset (no comments, block strings, escapes or carriage returns) and checks operationName against the one query. BRAIN_UI_MODULE_GITHUB_TOKEN joins the host-only secrets and the stripped host credentials. Every out-of-grant refusal names its setting. Tests now put the token in the inputs and check the worker's environ and cmdline. Co-Authored-By: Claude Opus 5.5 --- packages/ui-sdk/src/server/subprocess-env.ts | 6 +++-- .../ui-sdk/tests/host-git-credentials.test.ts | 2 ++ packages/ui-sdk/tests/subprocess-env.test.ts | 10 ++++++++ packages/ui-server/src/github/module-relay.ts | 17 ++++++++++---- .../tests/cron-module-github-relay.test.ts | 8 ++++++- .../maintenance-module-github-relay.test.ts | 13 ++++++++--- .../tests/module-github-relay.test.ts | 23 +++++++++++++++---- 7 files changed, 63 insertions(+), 16 deletions(-) diff --git a/packages/ui-sdk/src/server/subprocess-env.ts b/packages/ui-sdk/src/server/subprocess-env.ts index f2f2b73c17..e795fdbdd9 100644 --- a/packages/ui-sdk/src/server/subprocess-env.ts +++ b/packages/ui-sdk/src/server/subprocess-env.ts @@ -24,7 +24,7 @@ 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 @@ -32,7 +32,7 @@ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; * * @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); @@ -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", ]); diff --git a/packages/ui-sdk/tests/host-git-credentials.test.ts b/packages/ui-sdk/tests/host-git-credentials.test.ts index 6830c16d64..4ba83a5776 100644 --- a/packages/ui-sdk/tests/host-git-credentials.test.ts +++ b/packages/ui-sdk/tests/host-git-credentials.test.ts @@ -14,6 +14,7 @@ const hostEnv = { BRAIN_UI_SYNC_GITHUB_TOKEN: "odysseus-sync-git-token", BRAIN_UI_SKILLS_GITHUB_TOKEN: "odysseus-skills-git-token", BRAIN_UI_GITHUB_TOOLS_TOKEN: "odysseus-github-tools-token", + BRAIN_UI_MODULE_GITHUB_TOKEN: "odysseus-module-github-token", OPENAI_API_KEY: "odysseus-provider-key", }; @@ -25,6 +26,7 @@ for (const credentials of [true, false]) { expect(launch.env.GITHUB_TOKEN).toBeUndefined(); expect(launch.env.BRAIN_UI_SYNC_GITHUB_TOKEN).toBeUndefined(); expect(launch.env.BRAIN_UI_GITHUB_TOOLS_TOKEN, "SDK_MAINTENANCE_GITHUB_TOOLS_TOKEN_ABSENT").toBeUndefined(); + expect(launch.env.BRAIN_UI_MODULE_GITHUB_TOKEN, "SDK_MAINTENANCE_MODULE_GITHUB_TOKEN_ABSENT").toBeUndefined(); if (credentials) expect(launch.env.OPENAI_API_KEY).toBe(hostEnv.OPENAI_API_KEY); else expect(launch.env.OPENAI_API_KEY).toBeUndefined(); expect(env).toEqual(hostEnv); diff --git a/packages/ui-sdk/tests/subprocess-env.test.ts b/packages/ui-sdk/tests/subprocess-env.test.ts index 0d529f51be..c6bd13dcd3 100644 --- a/packages/ui-sdk/tests/subprocess-env.test.ts +++ b/packages/ui-sdk/tests/subprocess-env.test.ts @@ -145,4 +145,14 @@ describe("subprocess environment descriptor", () => { } expect(SUBPROCESS_ENV.APIFY_TOKEN).toEqual([]); }); + + test("the module GitHub relay's token reaches no audience, even when the escape hatch or a spawn names it (#4259)", () => { + const sentinel = "odysseus-module-github-token-never-in-a-worker"; + const env = { BRAIN_UI_MODULE_GITHUB_TOKEN: sentinel, PATH: "/usr/bin", BRAIN_UI_SUBPROCESS_ENV_EXTRA: "BRAIN_UI_MODULE_GITHUB_TOKEN" }; + expect(parseSubprocessEnvExtra(env.BRAIN_UI_SUBPROCESS_ENV_EXTRA), "MODULE_GITHUB_TOKEN_EXTRA_REFUSED").toEqual([]); + for (const audience of ["cron", "agent", "brainCli"] as const) { + const filtered = filterSubprocessEnv(env, audience, ["BRAIN_UI_MODULE_GITHUB_TOKEN"]); + expect(JSON.stringify(filtered), `MODULE_GITHUB_TOKEN_WITHHELD: ${audience}`).not.toContain(sentinel); + } + }); }); diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index 8fd03e249e..78301432cd 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -101,7 +101,11 @@ function graphqlStructure(query: string): string { * selection is `repository(owner:, name:)`; null otherwise. Arguments are * string literals or `$variables` resolved from `variables`. */ -export function graphqlQueryRepository(query: string, variables: unknown): string | null { +export function graphqlQueryRepository(query: string, variables: unknown, operationName?: unknown): string | null { + // A strict subset, so this reader and GitHub's parser cannot disagree about + // where a string or comment ends: no comments, block strings, escapes, + // carriage returns or other control characters. + if (/[#\\\r]|"""|[\u0000-\u0008\u000b-\u001f\u007f]/.test(query)) return null; const text = graphqlStructure(query); // Top-level definitions: exactly one operation, and it is a query (or the `{ … }` shorthand). let depth = 0, operations = 0, start = -1, end = -1, header = ""; @@ -113,7 +117,10 @@ export function graphqlQueryRepository(query: string, variables: unknown): strin else if (depth === 0) buffer += char; } if (depth !== 0 || operations !== 1 || buffer.trim() || start < 0 || end < 0) return null; - if (header && !/^query(?:\s+[_A-Za-z][_0-9A-Za-z]*)?\s*(?:\([^)]*\))?$/.test(header)) return null; + const operation = /^query(?:\s+([_A-Za-z][_0-9A-Za-z]*))?\s*(?:\([^)]*\))?$/.exec(header); + if (header && !operation) return null; + // GitHub runs the operation `operationName` names: it must be this one. + if (operationName !== undefined && operationName !== null && operationName !== operation?.[1]) return null; // The root selection set: one field, `repository`, with no alias, spread or directive. const root = text.slice(start + 1, end); let inner = 0, fields = ""; @@ -192,8 +199,8 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const value = jsonObject(body); if (typeof value.query !== "string" || Object.keys(value).some(key => !["query", "variables", "operationName"].includes(key))) refuse(400, "invalid_body", "A relayed GraphQL request is { query, variables?, operationName? }."); - const target = graphqlQueryRepository(value.query as string, value.variables); - if (!target) refuse(403, "graphql_not_allowed", "Only a GraphQL query whose one root field is repository(owner:, name:) on a granted repository is relayed; mutations and other roots are refused."); + const target = graphqlQueryRepository(value.query as string, value.variables, value.operationName); + if (!target) refuse(403, "graphql_not_allowed", "Only one GraphQL query whose one root field is repository(owner:, name:), without comments, block strings or escapes, is relayed; mutations and other roots are refused. The repository must be granted through the module's repositories and BRAIN_UI_MODULE_REPOSITORIES."); repositoryOf(...(target!.split("/") as [string, string])); } else if (method === "POST" && repo && /^\/issues\/[1-9][0-9]{0,9}\/comments$/.test(repo[3] ?? "") && !url.search) { const repository = repositoryOf(decodeURIComponent(repo[1]!), decodeURIComponent(repo[2]!)); @@ -213,7 +220,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul refuse(400, "invalid_body", "An issue state change is { state: open|closed, state_reason? } and nothing else."); write = { repository, operation: "issue_state", number: Number(repo[3]!.split("/")[2]) }; } else { - refuse(403, "not_relayed", `${method} ${path} is not relayed: reads are GET under a granted /repos/// or a repository GraphQL query; writes are issue_comment and issue_state.`); + refuse(403, "not_relayed", `${method} ${path} is not relayed: reads are GET under a /repos/// granted through BRAIN_UI_MODULE_REPOSITORIES, or a repository GraphQL query; the only writes are issue_comment and issue_state, enabled in BRAIN_UI_MODULE_GITHUB_WRITES.`); } const token = options.token(); if (!token) refuse(503, "unavailable", "The module GitHub relay has no credential: set BRAIN_UI_MODULE_GITHUB_TOKEN on the host."); diff --git a/packages/ui-server/tests/cron-module-github-relay.test.ts b/packages/ui-server/tests/cron-module-github-relay.test.ts index 8d0e490226..97792481b0 100644 --- a/packages/ui-server/tests/cron-module-github-relay.test.ts +++ b/packages/ui-server/tests/cron-module-github-relay.test.ts @@ -44,7 +44,13 @@ test("a job granted a GitHub repository reaches its API through the run's relay, return finished(); } } as unknown as HostBoundary; const dbPath = join(dir, "ui.db"); - const code = await runJob({ ...JOB, dbPath, childEnv: { PATH: "/usr/bin:/bin" }, exec: {}, boundary, + // The runner's own configuration never forwards the relay's token to a job. + const { resolveCronConfig } = await import("../src/config/env.js"); + const config = resolveCronConfig({ BRAIN_PATH: dir, DB_PATH: dbPath, PATH: "/usr/bin:/bin", BRAIN_UI_MODULE_GITHUB_TOKEN: TOKEN, + BRAIN_UI_SUBPROCESS_ENV_EXTRA: "BRAIN_UI_MODULE_GITHUB_TOKEN" }, ["BRAIN_UI_MODULE_GITHUB_TOKEN"]); + expect(config.moduleGitHub.token(), "RUNNER_READS_TOKEN").toBe(TOKEN); + expect(JSON.stringify(config.childEnv), "CHILD_ENV_HAS_NO_TOKEN").not.toContain(TOKEN); + const code = await runJob({ ...JOB, dbPath, childEnv: config.childEnv, exec: {}, boundary, stdout: { write() {} }, stderr: { write() {} }, repositories: async () => ({ ok: true, notes: [], repositories: [{ url: "https://github.com/ithaca/watchtower", mirror: join(dir, "mirror.git") }, { url: "http://127.0.0.1:9/ithaca/harbor", mirror: join(dir, "harbor.git") }] }), diff --git a/packages/ui-server/tests/maintenance-module-github-relay.test.ts b/packages/ui-server/tests/maintenance-module-github-relay.test.ts index f6f7691e0d..968e6359b3 100644 --- a/packages/ui-server/tests/maintenance-module-github-relay.test.ts +++ b/packages/ui-server/tests/maintenance-module-github-relay.test.ts @@ -42,12 +42,19 @@ test("a credential-free maintenance worker reaches the relay through its socket, const program = `const socket = process.env.BRAIN_MODULE_GITHUB_SOCKET; const relayed = await fetch("http://localhost/repos/ithaca/watchtower/issues", { unix: socket }).then(r => r.status, e => String(e)); const direct = await fetch(${JSON.stringify(upstream.url.origin)} + "/repos/ithaca/watchtower/issues").then(r => r.status, () => "unreachable"); - console.log(JSON.stringify({ socket, relayed, direct, env: process.env }));`; - const child = await host.launch({ argv: [process.execPath, "--config=/dev/null", "-e", program], env: { PATH: "/usr/bin:/bin" }, + const fs = require("node:fs"); + const proc = { environ: fs.readFileSync("/proc/self/environ", "utf8"), cmdline: fs.readFileSync("/proc/self/cmdline", "utf8") }; + console.log(JSON.stringify({ socket, relayed, direct, env: process.env, proc, relayDir: fs.readdirSync("/run/brain-github") }));`; + // A misconfigured host that hands the job the relay's token anyway: it never reaches the worker. + const child = await host.launch({ argv: [process.execPath, "--config=/dev/null", "-e", program], env: { PATH: "/usr/bin:/bin", BRAIN_UI_MODULE_GITHUB_TOKEN: TOKEN }, credentials: false, gate: "shared", purpose: "Odysseus module job", githubRelay: relay.dir }); const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exitCode, stderr).toBe(0); - const observed = JSON.parse(stdout.trim().split("\n").at(-1)!) as { socket: string; relayed: number | string; direct: number | string; env: Record }; + const observed = JSON.parse(stdout.trim().split("\n").at(-1)!) as { socket: string; relayed: number | string; direct: number | string; env: Record; + proc: { environ: string; cmdline: string }; relayDir: string[] }; + expect(observed.env.BRAIN_UI_MODULE_GITHUB_TOKEN, "WORKER_ENV_HAS_NO_TOKEN").toBeUndefined(); + expect(`${observed.proc.environ}${observed.proc.cmdline}`, "WORKER_PROCESS_HAS_NO_TOKEN").not.toContain(TOKEN); + expect(observed.relayDir, "RELAY_DIR_HOLDS_ONLY_THE_SOCKET").toEqual(["github.sock"]); expect(observed.socket, "WORKER_SOCKET_PATH").toBe("/run/brain-github/github.sock"); expect(observed.relayed, "WORKER_REACHES_RELAY").toBe(200); expect(observed.direct, "WORKER_HAS_NO_NETWORK").toBe("unreachable"); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index e4e9391835..67fed18778 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -51,7 +51,9 @@ describe("module GitHub relay reads (#4259)", () => { expect(foreign.status, "FOREIGN_REPOSITORY_REFUSED").toBe(403); expect((await foreign.json()).brain_relay_refusal).toBe("repository_not_granted"); expect((await call("GET", "/user")).status, "NON_REPOSITORY_PATH_REFUSED").toBe(403); - expect((await call("DELETE", "/repos/ithaca/watchtower")).status, "DELETE_REFUSED").toBe(403); + const removal = await call("DELETE", "/repos/ithaca/watchtower"); + expect(removal.status, "DELETE_REFUSED").toBe(403); + expect((await removal.json()).message, "NOT_RELAYED_NAMES_SETTINGS").toMatch(/BRAIN_UI_MODULE_REPOSITORIES.*BRAIN_UI_MODULE_GITHUB_WRITES/); expect((await call("GET", "/repos/ithaca/watchtower/../../sparta/barracks")).status).not.toBe(200); expect(seen, "NOTHING_FORWARDED").toEqual([]); }); @@ -61,7 +63,7 @@ describe("module GitHub relay reads (#4259)", () => { const query = "query Closed($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { issues(last: 5, states: CLOSED) { nodes { number } } } }"; expect((await call("POST", "/graphql", { query, variables: { owner: "ithaca", name: "watchtower" } })).status, "GRAPHQL_QUERY_FORWARDED").toBe(200); expect(seen).toHaveLength(1); - const refused = [ + const refused: Array<{ query: string; variables?: unknown; operationName?: string }> = [ { query: 'mutation { closeIssue(input: { issueId: "I_1" }) { clientMutationId } }' }, { query: "{ viewer { login } }" }, { query: '{ r: repository(owner: "ithaca", name: "watchtower") { id } }' }, @@ -69,11 +71,21 @@ describe("module GitHub relay reads (#4259)", () => { { query: query, variables: { owner: "sparta", name: "barracks" } }, { query: '{ repository(owner: "ithaca", name: "watchtower") { id } } mutation { addComment(input: {}) { clientMutationId } }' }, ]; + // Strings and comments this reader and GitHub's parser could end in different places (review of #4265). + refused.push( + { query: 'query Q { repository(owner: "ithaca", name: "watchtower") { id } } # x\r mutation M { closeIssue(input: { issueId: "I_1" }) { clientMutationId } }', operationName: "M" } as never, + { query: '{ repository(owner: "ithaca", name: "watchtower") { label(name: """a \\""" b""") { id } } } """ repository(owner: "sparta", name: "barracks") { id } """' }, + { query: '{ repository(owner: "ithaca", name: "watchtower") { label(name: "a\\"b") { id } } }' }, + ); for (const body of refused) { const response = await call("POST", "/graphql", body); expect(response.status, `GRAPHQL_REFUSED: ${body.query}`).toBe(403); + expect((await response.json()).message, "GRAPHQL_REFUSAL_NAMES_SETTING").toContain("BRAIN_UI_MODULE_REPOSITORIES"); } - expect(seen, "REFUSED_GRAPHQL_NOT_FORWARDED").toHaveLength(1); + // operationName must name the one query. + expect((await call("POST", "/graphql", { query, operationName: "Other", variables: { owner: "ithaca", name: "watchtower" } })).status, "OPERATION_NAME_MISMATCH_REFUSED").toBe(403); + expect((await call("POST", "/graphql", { query, operationName: "Closed", variables: { owner: "ithaca", name: "watchtower" } })).status, "OPERATION_NAME_MATCH_FORWARDED").toBe(200); + expect(seen, "REFUSED_GRAPHQL_NOT_FORWARDED").toHaveLength(2); }); test("without BRAIN_UI_MODULE_GITHUB_TOKEN every call is refused, naming the setting", async () => { @@ -127,9 +139,10 @@ describe("module GitHub relay writes (#4259)", () => { }); }); -test("graphqlQueryRepository reads literal and variable arguments and ignores strings and comments", () => { +test("graphqlQueryRepository reads literal and variable arguments, and refuses comments, escapes and block strings", () => { expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { id } }', {})).toBe("ithaca/watchtower"); - expect(graphqlQueryRepository('# mutation { x }\nquery { repository(name: $n, owner: $o) { description } }', { o: "ithaca", n: "watchtower" })).toBe("ithaca/watchtower"); + expect(graphqlQueryRepository('query {\n repository(name: $n, owner: $o) { label(name: "bug") { id } }\n}', { o: "ithaca", n: "watchtower" })).toBe("ithaca/watchtower"); + expect(graphqlQueryRepository('# mutation { x }\nquery { repository(name: $n, owner: $o) { description } }', { o: "ithaca", n: "watchtower" }), "COMMENT_REFUSED").toBeNull(); expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { ...Fields } } fragment Fields on Repository { id }', {})).toBeNull(); expect(graphqlQueryRepository("subscription { repository(owner: \"ithaca\", name: \"watchtower\") { id } }", {})).toBeNull(); }); From 4d058d61d61107d44e6a9512a9558223e8042fc5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:56:48 +0000 Subject: [PATCH 05/22] fix(ui-server): bound relay reads while streaming, and record a write once GitHub answers (#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/github/module-relay.ts | 38 +++++++++++++++---- .../tests/module-github-relay.test.ts | 29 ++++++++++++-- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index 78301432cd..4ae10410ea 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -53,7 +53,7 @@ export interface ModuleGitHubRelayOptions { writes: ReadonlyMap>; observe?: (write: ModuleGitHubWriteRecord) => void; /** @internal Test seams. */ - fetch?: typeof fetch; origin?: string; maxCalls?: number; + fetch?: typeof fetch; origin?: string; maxCalls?: number; maxResponseBytes?: number; } export interface ModuleGitHubRelay { dir: string; socketPath: string; stop(): Promise } @@ -149,12 +149,31 @@ export function graphqlQueryRepository(query: string, variables: unknown, operat return owner && name ? `${owner}/${name}` : null; } +/** A stream's bytes, read chunk by chunk and abandoned as soon as they pass `limit`: never held past the bound. */ +async function readBounded(stream: ReadableStream | null, limit: number): Promise { + if (!stream) return new Uint8Array(); + const reader = stream.getReader(); + const chunks: Uint8Array[] = []; let total = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > limit) { await reader.cancel().catch(() => {}); return null; } + chunks.push(value); + } + } finally { reader.releaseLock(); } + const bytes = new Uint8Array(total); let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } + return bytes; +} + async function boundedBody(request: Request): Promise { const declared = Number(request.headers.get("content-length") ?? "0"); if (declared > MAX_MODULE_GITHUB_REQUEST_BYTES) refuse(413, "too_large", `A relayed request body is at most ${MAX_MODULE_GITHUB_REQUEST_BYTES} bytes.`); - const bytes = new Uint8Array(await request.arrayBuffer()); - if (bytes.byteLength > MAX_MODULE_GITHUB_REQUEST_BYTES) refuse(413, "too_large", `A relayed request body is at most ${MAX_MODULE_GITHUB_REQUEST_BYTES} bytes.`); - return new TextDecoder().decode(bytes); + const bytes = await readBounded(request.body, MAX_MODULE_GITHUB_REQUEST_BYTES); + if (!bytes) refuse(413, "too_large", `A relayed request body is at most ${MAX_MODULE_GITHUB_REQUEST_BYTES} bytes.`); + return new TextDecoder().decode(bytes!); } function jsonObject(text: string): Record { @@ -168,6 +187,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const origin = options.origin ?? GITHUB_API_ORIGIN; const granted = new Map(options.repositories.map(repository => [lower(repository), repository])); const maxCalls = options.maxCalls ?? MAX_MODULE_GITHUB_CALLS; + const maxResponseBytes = options.maxResponseBytes ?? MAX_MODULE_GITHUB_RESPONSE_BYTES; let calls = 0; // Private to this server user; the one worker of this run sees only the bound socket. const dir = mkdtempSync(join(tmpdir(), "brain-module-github-")); @@ -230,13 +250,15 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul headers: { authorization: `Bearer ${token}`, accept: request.headers.get("accept")?.startsWith("application/vnd.github") ? request.headers.get("accept")! : "application/vnd.github+json", "x-github-api-version": "2022-11-28", "user-agent": "brain-ui-module", ...(body !== undefined ? { "content-type": "application/json" } : {}) }, }); - if (upstream.status >= 300 && upstream.status < 400) { await upstream.body?.cancel(); refuse(502, "redirect", "GitHub redirected; the relay never follows a redirect."); } - const bytes = new Uint8Array(await upstream.arrayBuffer()); - if (bytes.byteLength > MAX_MODULE_GITHUB_RESPONSE_BYTES) refuse(502, "response_too_large", `A relayed response is at most ${MAX_MODULE_GITHUB_RESPONSE_BYTES} bytes.`); + // GitHub has answered: a write it may have performed is recorded now, whatever happens to its body. if (write) { try { options.observe?.({ ...write, repository: granted.get(write.repository)!, status: upstream.status }); } catch { /* Recording never fails the call. */ } } + if (upstream.status >= 300 && upstream.status < 400) { await upstream.body?.cancel(); refuse(502, "redirect", "GitHub redirected; the relay never follows a redirect."); } + if (Number(upstream.headers.get("content-length") ?? "0") > maxResponseBytes) { await upstream.body?.cancel(); refuse(502, "response_too_large", `A relayed response is at most ${MAX_MODULE_GITHUB_RESPONSE_BYTES} bytes.`); } + const bytes = await readBounded(upstream.body, maxResponseBytes); + if (!bytes) refuse(502, "response_too_large", `A relayed response is at most ${MAX_MODULE_GITHUB_RESPONSE_BYTES} bytes.`); const headers = new Headers(); for (const name of RESPONSE_HEADERS) { const value = upstream.headers.get(name); if (value) headers.set(name, value); } - return new Response(bytes, { status: upstream.status, headers }); + return new Response(Buffer.from(bytes!), { status: upstream.status, headers }); } const server = Bun.serve({ diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index 67fed18778..b76f7abb48 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -11,24 +11,30 @@ const TOKEN = "odysseus-module-github-token"; let upstream: ReturnType; const seen: Array<{ method: string; path: string; authorization: string | null; body: string }> = []; let redirect = false; +let large = 0; beforeAll(() => { upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { const url = new URL(request.url); seen.push({ method: request.method, path: `${url.pathname}${url.search}`, authorization: request.headers.get("authorization"), body: await request.text() }); if (redirect) return new Response(null, { status: 302, headers: { location: "https://elsewhere.example/" } }); + if (large) { + // A chunked body with no length: only reading it shows its size. + let sent = 0; + return new Response(new ReadableStream({ pull(controller) { if (sent >= large) return controller.close(); sent += 1024; controller.enqueue(new Uint8Array(1024)); } }), { status: 201 }); + } return Response.json({ ok: true, path: url.pathname }, { headers: { link: '; rel="next"' } }); } }); }); afterAll(() => { upstream.stop(true); }); const relays: ModuleGitHubRelay[] = []; -afterEach(async () => { for (const relay of relays.splice(0)) await relay.stop(); seen.length = 0; redirect = false; }); +afterEach(async () => { for (const relay of relays.splice(0)) await relay.stop(); seen.length = 0; redirect = false; large = 0; }); -function relay(options: { token?: string | undefined; writes?: string; maxCalls?: number } = {}) { +function relay(options: { token?: string | undefined; writes?: string; maxCalls?: number; maxResponseBytes?: number } = {}) { const writes: ModuleGitHubWriteRecord[] = []; const started = startModuleGitHubRelay({ token: () => "token" in options ? options.token : TOKEN, repositories: ["ithaca/watchtower"], writes: parseModuleGitHubWrites(options.writes ?? "").writes, observe: write => { writes.push(write); }, - origin: upstream.url.origin, ...(options.maxCalls ? { maxCalls: options.maxCalls } : {}) }); + origin: upstream.url.origin, ...(options.maxCalls ? { maxCalls: options.maxCalls } : {}), ...(options.maxResponseBytes ? { maxResponseBytes: options.maxResponseBytes } : {}) }); relays.push(started); const call = (method: string, path: string, body?: unknown, headers: Record = {}) => fetch(`http://localhost${path}`, { method, unix: started.socketPath, headers: { authorization: "Bearer worker-supplied", ...headers }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), @@ -132,6 +138,23 @@ describe("module GitHub relay writes (#4259)", () => { ]); }); + test("an oversized response is refused while it is read, and a write GitHub answered is still recorded", async () => { + const { call, writes } = relay({ writes: "https://github.com/ithaca/watchtower#issue_comment", maxResponseBytes: 8 * 1024 }); + large = 64 * 1024; + const response = await call("POST", COMMENTS, { body: "Telemachus asks why this closed." }); + expect(response.status, "OVERSIZED_RESPONSE_REFUSED").toBe(502); + expect((await response.json()).brain_relay_refusal).toBe("response_too_large"); + expect(writes, "ANSWERED_WRITE_RECORDED").toEqual([{ repository: "ithaca/watchtower", operation: "issue_comment", number: 7, status: 201 }]); + }); + + test("a chunked request body past the bound is refused", async () => { + const { started } = relay({ writes: "https://github.com/ithaca/watchtower#issue_comment" }); + const big = new ReadableStream({ start(controller) { for (let i = 0; i < 1100; i++) controller.enqueue(new Uint8Array(1024).fill(32)); controller.close(); } }); + const response = await fetch(`http://localhost${COMMENTS}`, { method: "POST", unix: started.socketPath, body: big } as RequestInit); + expect(response.status, "CHUNKED_REQUEST_BOUNDED").toBe(413); + expect(seen).toEqual([]); + }); + test("the operator list parses only GitHub repositories and known operations", () => { const parsed = parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment, https://gitlab.com/ithaca/x#issue_comment https://github.com/ithaca/watchtower#merge"); expect([...parsed.writes.get("ithaca/watchtower") ?? []]).toEqual(["issue_comment"]); From 7b8eccffd206e6661f8e1ad8bd48c5ede9bc5ff6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 15:45:44 +0000 Subject: [PATCH 06/22] fix(ui-server, ui-sdk): keep relayed GraphQL inside its repository; cover /etc/environment in every worker (#4259) Below the granted repository root, fields that reach another repository, owner or account are refused. A container's /etc/environment carries the cron runner's credentials for pam_env; every host-view worker now covers it. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 8 +++++ packages/ui-sdk/src/server/worker-launcher.ts | 15 +++++++-- .../ui-sdk/tests/host-git-credentials.test.ts | 13 +++++++- packages/ui-server/src/github/module-relay.ts | 33 +++++++++++++++++++ .../maintenance-module-github-relay.test.ts | 7 ++-- .../tests/module-github-relay.test.ts | 10 ++++++ 6 files changed, 81 insertions(+), 5 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 66b5641429..e4b19678af 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -619,6 +619,14 @@ a maintenance worker has no network namespace route to 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 must stay inside its granted repository: below the +`repository(owner:, name:)` root, no field that reaches another repository, +an owner or the account (`owner`, `repositories`, `forks`, `parent`, `search`, +`viewer` and the like) is relayed. 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. diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index 7e0a2993a2..5080a2dc9b 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -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"; @@ -447,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; } @@ -706,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, diff --git a/packages/ui-sdk/tests/host-git-credentials.test.ts b/packages/ui-sdk/tests/host-git-credentials.test.ts index 4ba83a5776..0479dde11d 100644 --- a/packages/ui-sdk/tests/host-git-credentials.test.ts +++ b/packages/ui-sdk/tests/host-git-credentials.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { maintenanceLaunch } from "../src/server/maintenance-worker.js"; @@ -49,3 +49,14 @@ for (const maintenance of [false, true]) { }); }); } + +test("every host-view worker covers /etc/environment, where a container keeps the cron runner's credentials (#4259)", () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-worker-etc-environment-")); roots.push(root); + const brain = join(root, "brain"); mkdirSync(brain); + for (const maintenance of [undefined, { credentials: false, network: false, readPaths: [process.execPath] }]) { + const argv = workerCommand({ brainPath: brain, command: ["/bin/true"], env: { PATH: "/usr/bin:/bin" }, ...(maintenance ? { maintenance } : {}) }); + const covered = argv.some((arg, i) => arg === "--ro-bind" && argv[i + 1] === "/dev/null" && argv[i + 2] === "/etc/environment"); + // A host without the file has nothing to cover. + expect(covered, `ETC_ENVIRONMENT_COVERED: ${maintenance ? "maintenance" : "agent"}`).toBe(existsSync("/etc/environment")); + } +}); diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index 4ae10410ea..b2264defd7 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -130,6 +130,9 @@ export function graphqlQueryRepository(query: string, variables: unknown, operat if (char === "}" || char === ")") inner--; } if (!/^\s*repository\s*$/.test(fields)) return null; + // Below the root, no field may reach another repository, owner or the + // account: the grant names repositories, not what the token can traverse to. + if (selectedFields(root.slice(root.indexOf("repository") + "repository".length)).some(name => CROSS_REPOSITORY_FIELDS.has(name))) return null; const open = root.indexOf("("), close = root.indexOf(")"); if (!/^\s*repository\s*$/.test(root.slice(0, open)) || open < 0 || close < open) return null; // The argument text itself, from the original query (blanking keeps every offset). @@ -149,6 +152,36 @@ export function graphqlQueryRepository(query: string, variables: unknown, operat return owner && name ? `${owner}/${name}` : null; } +/** + * Fields that select another repository, an owner's repositories, an account + * or a global node or search, wherever they appear below the granted root. + */ +const CROSS_REPOSITORY_FIELDS = new Set(["repository", "repositories", "repositoryOwner", "owner", "organization", "user", "viewer", + "forks", "parent", "templateRepository", "search", "node", "nodes_by_id", "resource", "topic", "enterprise", "sponsorable", + "pinnedItems", "starredRepositories", "watching", "repositoriesContributedTo", "topRepositories", "mergeQueue"]); + +/** + * Every selected field name in GraphQL selection text whose strings are + * blanked: identifiers outside argument lists that are not alias or argument + * names (`name:`), variables, fragment spreads or directives. + */ +function selectedFields(text: string): string[] { + const names: string[] = []; + let args = 0; + const token = /\$?[_A-Za-z][_0-9A-Za-z]*|\.\.\.|@|[(){}:]/g; + const tokens = [...text.matchAll(token)].map(match => match[0]); + for (let i = 0; i < tokens.length; i++) { + const current = tokens[i]!; + if (current === "(") { args++; continue; } + if (current === ")") { args--; continue; } + if (args > 0 || current.startsWith("$") || /^[(){}:@]$|^\.\.\.$/.test(current)) continue; + if (tokens[i - 1] === "@" || tokens[i - 1] === "...") continue; + if (tokens[i + 1] === ":") continue; + names.push(current); + } + return names; +} + /** A stream's bytes, read chunk by chunk and abandoned as soon as they pass `limit`: never held past the bound. */ async function readBounded(stream: ReadableStream | null, limit: number): Promise { if (!stream) return new Uint8Array(); diff --git a/packages/ui-server/tests/maintenance-module-github-relay.test.ts b/packages/ui-server/tests/maintenance-module-github-relay.test.ts index 968e6359b3..df6de0f5b4 100644 --- a/packages/ui-server/tests/maintenance-module-github-relay.test.ts +++ b/packages/ui-server/tests/maintenance-module-github-relay.test.ts @@ -43,7 +43,8 @@ test("a credential-free maintenance worker reaches the relay through its socket, const relayed = await fetch("http://localhost/repos/ithaca/watchtower/issues", { unix: socket }).then(r => r.status, e => String(e)); const direct = await fetch(${JSON.stringify(upstream.url.origin)} + "/repos/ithaca/watchtower/issues").then(r => r.status, () => "unreachable"); const fs = require("node:fs"); - const proc = { environ: fs.readFileSync("/proc/self/environ", "utf8"), cmdline: fs.readFileSync("/proc/self/cmdline", "utf8") }; + const proc = { environ: fs.readFileSync("/proc/self/environ", "utf8"), cmdline: fs.readFileSync("/proc/self/cmdline", "utf8"), + etcEnvironment: (() => { try { return fs.readFileSync("/etc/environment", "utf8"); } catch (error) { return error.code; } })() }; console.log(JSON.stringify({ socket, relayed, direct, env: process.env, proc, relayDir: fs.readdirSync("/run/brain-github") }));`; // A misconfigured host that hands the job the relay's token anyway: it never reaches the worker. const child = await host.launch({ argv: [process.execPath, "--config=/dev/null", "-e", program], env: { PATH: "/usr/bin:/bin", BRAIN_UI_MODULE_GITHUB_TOKEN: TOKEN }, @@ -51,9 +52,11 @@ test("a credential-free maintenance worker reaches the relay through its socket, const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exitCode, stderr).toBe(0); const observed = JSON.parse(stdout.trim().split("\n").at(-1)!) as { socket: string; relayed: number | string; direct: number | string; env: Record; - proc: { environ: string; cmdline: string }; relayDir: string[] }; + proc: { environ: string; cmdline: string; etcEnvironment: string }; relayDir: string[] }; expect(observed.env.BRAIN_UI_MODULE_GITHUB_TOKEN, "WORKER_ENV_HAS_NO_TOKEN").toBeUndefined(); expect(`${observed.proc.environ}${observed.proc.cmdline}`, "WORKER_PROCESS_HAS_NO_TOKEN").not.toContain(TOKEN); + // The cron runner's environment file is covered: empty, never the host's. + expect([ "", "ENOENT" ], "WORKER_ETC_ENVIRONMENT_COVERED").toContain((observed.proc as { etcEnvironment: string }).etcEnvironment); expect(observed.relayDir, "RELAY_DIR_HOLDS_ONLY_THE_SOCKET").toEqual(["github.sock"]); expect(observed.socket, "WORKER_SOCKET_PATH").toBe("/run/brain-github/github.sock"); expect(observed.relayed, "WORKER_REACHES_RELAY").toBe(200); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index b76f7abb48..0cc04159f3 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -77,6 +77,13 @@ describe("module GitHub relay reads (#4259)", () => { { query: query, variables: { owner: "sparta", name: "barracks" } }, { query: '{ repository(owner: "ithaca", name: "watchtower") { id } } mutation { addComment(input: {}) { clientMutationId } }' }, ]; + // Nested traversal to another repository or owner (third review of #4265). + refused.push( + { query: '{ repository(owner: "ithaca", name: "watchtower") { owner { repository(name: "barracks") { issues(first: 5) { nodes { title } } } } } }' }, + { query: '{ repository(owner: "ithaca", name: "watchtower") { owner { repositories(first: 5) { nodes { name } } } } }' }, + { query: '{ repository(owner: "ithaca", name: "watchtower") { forks(first: 5) { nodes { name } } parent { name } } }' }, + { query: '{ repository(owner: "ithaca", name: "watchtower") { issue(number: 7) { repository { name } } } }' }, + ); // Strings and comments this reader and GitHub's parser could end in different places (review of #4265). refused.push( { query: 'query Q { repository(owner: "ithaca", name: "watchtower") { id } } # x\r mutation M { closeIssue(input: { issueId: "I_1" }) { clientMutationId } }', operationName: "M" } as never, @@ -163,6 +170,9 @@ describe("module GitHub relay writes (#4259)", () => { }); test("graphqlQueryRepository reads literal and variable arguments, and refuses comments, escapes and block strings", () => { + // A close event's closer, as a heartbeat check reads it, stays inside the repository. + expect(graphqlQueryRepository('query Closed($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { timelineItems(last: 5, itemTypes: [CLOSED_EVENT]) { nodes { ... on ClosedEvent { createdAt actor { login } closer { __typename ... on PullRequest { number merged } } } } } } } }', + { owner: "ithaca", name: "watchtower", number: 7 }), "NESTED_IN_REPOSITORY_ALLOWED").toBe("ithaca/watchtower"); expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { id } }', {})).toBe("ithaca/watchtower"); expect(graphqlQueryRepository('query {\n repository(name: $n, owner: $o) { label(name: "bug") { id } }\n}', { o: "ithaca", n: "watchtower" })).toBe("ithaca/watchtower"); expect(graphqlQueryRepository('# mutation { x }\nquery { repository(name: $n, owner: $o) { description } }', { o: "ithaca", n: "watchtower" }), "COMMENT_REFUSED").toBeNull(); From 4922accd5517c55e34611c773884d8a2b7852b65 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:07:26 +0000 Subject: [PATCH 07/22] test(ui-server): read the journal from its own database; accept an unreadable covered file Co-Authored-By: Claude Opus 5.5 --- .../ui-server/tests/maintenance-module-github-relay.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/maintenance-module-github-relay.test.ts b/packages/ui-server/tests/maintenance-module-github-relay.test.ts index df6de0f5b4..7c2cfeadee 100644 --- a/packages/ui-server/tests/maintenance-module-github-relay.test.ts +++ b/packages/ui-server/tests/maintenance-module-github-relay.test.ts @@ -55,8 +55,8 @@ test("a credential-free maintenance worker reaches the relay through its socket, proc: { environ: string; cmdline: string; etcEnvironment: string }; relayDir: string[] }; expect(observed.env.BRAIN_UI_MODULE_GITHUB_TOKEN, "WORKER_ENV_HAS_NO_TOKEN").toBeUndefined(); expect(`${observed.proc.environ}${observed.proc.cmdline}`, "WORKER_PROCESS_HAS_NO_TOKEN").not.toContain(TOKEN); - // The cron runner's environment file is covered: empty, never the host's. - expect([ "", "ENOENT" ], "WORKER_ETC_ENVIRONMENT_COVERED").toContain((observed.proc as { etcEnvironment: string }).etcEnvironment); + // The cron runner's environment file is covered: empty or unreadable, never the host's bytes. + expect(["", "ENOENT", "EACCES"], "WORKER_ETC_ENVIRONMENT_COVERED").toContain((observed.proc as { etcEnvironment: string }).etcEnvironment); expect(observed.relayDir, "RELAY_DIR_HOLDS_ONLY_THE_SOCKET").toEqual(["github.sock"]); expect(observed.socket, "WORKER_SOCKET_PATH").toBe("/run/brain-github/github.sock"); expect(observed.relayed, "WORKER_REACHES_RELAY").toBe(200); From 000c1811bd10da9ed890f81c79f9c322b41fb010 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:30:48 +0000 Subject: [PATCH 08/22] docs(ui-server): state the relayed GraphQL boundary truthfully; refuse more repository-selecting fields (#4259) The field denylist refuses fields that select another repository, owner or account by name; deeper traversal is bounded by the token's scope, which the docs now require the operator to limit to the granted repositories. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 13 +++++++++---- docs/integration-contract/package-api.md | 4 +++- docs/modules.md | 5 ++++- packages/ui-server/README.md | 2 +- packages/ui-server/src/config/env.ts | 2 +- packages/ui-server/src/github/module-relay.ts | 11 ++++++----- 6 files changed, 24 insertions(+), 13 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index e4b19678af..43f4302f60 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -619,10 +619,15 @@ a maintenance worker has no network namespace route to 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 must stay inside its granted repository: below the -`repository(owner:, name:)` root, no field that reaches another repository, -an owner or the account (`owner`, `repositories`, `forks`, `parent`, `search`, -`viewer` and the like) is relayed. Every host-view worker, agent and +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. The token's own scope is therefore the +read boundary below the root, and the operator limits +`BRAIN_UI_MODULE_GITHUB_TOKEN` to the repositories module jobs are granted. 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. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 82a00edbce..b6562d1e9e 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1034,7 +1034,9 @@ directory, alive only for that run. HTTP requests to it are relayed to fallback), never following a redirect. Relayed: `GET /repos///…` 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, only where +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//issues//comments` with exactly `{ body }` (`issue_comment`) and `PATCH /repos//issues/` with `{ state, state_reason? }` diff --git a/docs/modules.md b/docs/modules.md index 3debc86b79..2c71e6fa39 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -178,7 +178,10 @@ const issues = await github("/repos/ithaca/watchtower/issues?state=closed").then - **Reads:** `GET` under `/repos///…` 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. + `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, so limit the token to the granted repositories. - **Writes:** only what the operator enables per repository in `BRAIN_UI_MODULE_GITHUB_WRITES`, as `https://github.com//#`: `issue_comment` (`POST /repos//issues//comments` with `{ body }`) and diff --git a/packages/ui-server/README.md b/packages/ui-server/README.md index 0c6bea133c..ced48d6c38 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -383,7 +383,7 @@ under the [service terms](../geo/README.md#configuration). | `BRAIN_UI_MAINTENANCE_TEMP_BYTES` | Per-maintenance-command temporary-write allowance in bytes, covering its private /tmp, scratch and XDG directories. Positive page-aligned integer. Separate from agent turn temp, runtime state and output staging; overflow is ENOSPC. | 268435456 | | `BRAIN_UI_MODEL_DISCOVERY` | Model discovery against the Anthropic Models API; "0"/"off"/"false" disables. Defaults ON, except under a test runner (NODE_ENV=test) where it defaults OFF. | on (off under NODE_ENV=test) | | `BRAIN_UI_MODEL_TTL_HOURS` | How long a model-discovery result stays fresh, in hours. | 24 | -| `BRAIN_UI_MODULE_GITHUB_TOKEN` | GitHub token for the module GitHub relay (#4259): the GitHub API calls a module cron job makes to the repositories it was granted (the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories, with Issues read and, only where BRAIN_UI_MODULE_GITHUB_WRITES enables a write, Issues write. No fallback: GITHUB_TOKEN, the sync token and BRAIN_UI_GITHUB_TOOLS_TOKEN are never used, and without this one every relayed call is refused. Read by the cron runner only, never forwarded to a job or worker. | — | +| `BRAIN_UI_MODULE_GITHUB_TOKEN` | GitHub token for the module GitHub relay (#4259): the GitHub API calls a module cron job makes to the repositories it was granted (the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories (it is the read boundary for data a GraphQL query reaches through them), with Issues read and, only where BRAIN_UI_MODULE_GITHUB_WRITES enables a write, Issues write. No fallback: GITHUB_TOKEN, the sync token and BRAIN_UI_GITHUB_TOOLS_TOKEN are never used, and without this one every relayed call is refused. Read by the cron runner only, never forwarded to a job or worker. | — | | `BRAIN_UI_MODULE_GITHUB_WRITES` | Operator list of the GitHub writes a module cron job may make through the module GitHub relay (#4259), comma or whitespace separated, each `https://github.com//#` with operation `issue_comment` or `issue_state`. A repository must also be granted to the job. Read by the cron runner only. Empty enables no write. | (empty — no write) | | `BRAIN_UI_MODULE_REPOSITORIES` | Operator allow-list of repository URLs (comma or whitespace separated, HTTPS) a module cron job may read. The host fetches a repository a module's `repositories` config asks for only when this list names it too, using the sync transport's credential (BRAIN_UI_SYNC_GITHUB_TOKEN, else GITHUB_TOKEN); the job's worker reads a host mirror and never holds the credential. Read by the cron runner only, never forwarded to a job. Empty refuses every request. | (empty — no module repository is fetched) | | `BRAIN_UI_NATIVE_BRAIN_DELTA_BYTES` | Positive bound for one native metadata delta stream; exceeding it refuses the observation explicitly. Content and retained-history capacities are separate. | 67108864 (64 MiB) | diff --git a/packages/ui-server/src/config/env.ts b/packages/ui-server/src/config/env.ts index 5198dc60be..54fd471fde 100644 --- a/packages/ui-server/src/config/env.ts +++ b/packages/ui-server/src/config/env.ts @@ -208,7 +208,7 @@ export const ENV_VARS: readonly EnvVarDescriptor[] = [ name: "BRAIN_UI_MODULE_GITHUB_TOKEN", description: "GitHub token for the module GitHub relay (#4259): the GitHub API calls a module cron job makes to the repositories it was granted " + - "(the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories, with Issues read " + + "(the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories (it is the read boundary for data a GraphQL query reaches through them), with Issues read " + "and, only where BRAIN_UI_MODULE_GITHUB_WRITES enables a write, Issues write. No fallback: GITHUB_TOKEN, the sync token and " + "BRAIN_UI_GITHUB_TOOLS_TOKEN are never used, and without this one every relayed call is refused. Read by the cron runner only, " + "never forwarded to a job or worker.", diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index b2264defd7..e97aca56d0 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -153,12 +153,13 @@ export function graphqlQueryRepository(query: string, variables: unknown, operat } /** - * Fields that select another repository, an owner's repositories, an account - * or a global node or search, wherever they appear below the granted root. + * Fields that select another repository, owner or account by name, wherever + * they appear below the granted root. Not every traversal GitHub's schema + * offers: the token's own scope bounds the rest (docs/modules.md). */ -const CROSS_REPOSITORY_FIELDS = new Set(["repository", "repositories", "repositoryOwner", "owner", "organization", "user", "viewer", - "forks", "parent", "templateRepository", "search", "node", "nodes_by_id", "resource", "topic", "enterprise", "sponsorable", - "pinnedItems", "starredRepositories", "watching", "repositoriesContributedTo", "topRepositories", "mergeQueue"]); +const CROSS_REPOSITORY_FIELDS = new Set(["repository", "repositories", "repositoryOwner", "owner", "organization", "organizations", "user", "viewer", + "forks", "parent", "templateRepository", "headRepository", "baseRepository", "headRepositoryOwner", "search", "node", "resource", "topic", + "enterprise", "sponsorable", "pinnedItems", "starredRepositories", "watching", "repositoriesContributedTo", "topRepositories", "gists"]); /** * Every selected field name in GraphQL selection text whose strings are From 8b4771e7a8aae825d98dec242fc967995130cdee Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:42:55 +0000 Subject: [PATCH 09/22] fix(ui-server): allow connection edges in relayed GraphQL; record the token-scope ruling (#4259) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 8 +++++--- docs/modules.md | 3 ++- packages/ui-server/src/github/module-relay.ts | 2 +- packages/ui-server/tests/module-github-relay.test.ts | 1 + 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 43f4302f60..e29f73da2f 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -625,9 +625,11 @@ 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. The token's own scope is therefore the -read boundary below the root, and the operator limits -`BRAIN_UI_MODULE_GITHUB_TOKEN` to the repositories module jobs are granted. Every host-view worker, agent and +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. diff --git a/docs/modules.md b/docs/modules.md index 2c71e6fa39..02bdd59444 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -181,7 +181,8 @@ const issues = await github("/repos/ithaca/watchtower/issues?state=closed").then `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, so limit the token to the granted repositories. + 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//#`: `issue_comment` (`POST /repos//issues//comments` with `{ body }`) and diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index e97aca56d0..e0f83ae4d6 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -158,7 +158,7 @@ export function graphqlQueryRepository(query: string, variables: unknown, operat * offers: the token's own scope bounds the rest (docs/modules.md). */ const CROSS_REPOSITORY_FIELDS = new Set(["repository", "repositories", "repositoryOwner", "owner", "organization", "organizations", "user", "viewer", - "forks", "parent", "templateRepository", "headRepository", "baseRepository", "headRepositoryOwner", "search", "node", "resource", "topic", + "forks", "parent", "templateRepository", "headRepository", "baseRepository", "headRepositoryOwner", "search", "resource", "enterprise", "sponsorable", "pinnedItems", "starredRepositories", "watching", "repositoriesContributedTo", "topRepositories", "gists"]); /** diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index 0cc04159f3..bafd159d42 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -174,6 +174,7 @@ test("graphqlQueryRepository reads literal and variable arguments, and refuses c expect(graphqlQueryRepository('query Closed($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { timelineItems(last: 5, itemTypes: [CLOSED_EVENT]) { nodes { ... on ClosedEvent { createdAt actor { login } closer { __typename ... on PullRequest { number merged } } } } } } } }', { owner: "ithaca", name: "watchtower", number: 7 }), "NESTED_IN_REPOSITORY_ALLOWED").toBe("ithaca/watchtower"); expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { id } }', {})).toBe("ithaca/watchtower"); + expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { issues(first: 5) { edges { node { number } } } } }', {}), "CONNECTION_EDGES_ALLOWED").toBe("ithaca/watchtower"); expect(graphqlQueryRepository('query {\n repository(name: $n, owner: $o) { label(name: "bug") { id } }\n}', { o: "ithaca", n: "watchtower" })).toBe("ithaca/watchtower"); expect(graphqlQueryRepository('# mutation { x }\nquery { repository(name: $n, owner: $o) { description } }', { o: "ithaca", n: "watchtower" }), "COMMENT_REFUSED").toBeNull(); expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { ...Fields } } fragment Fields on Repository { id }', {})).toBeNull(); From bdc8e973cf8a6ebf064405c6bad02f8eb247a58b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:57:01 +0000 Subject: [PATCH 10/22] fix(ui-server): accept comma-less GraphQL arguments on the granted root (#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/github/module-relay.ts | 11 ++++++----- packages/ui-server/tests/module-github-relay.test.ts | 2 ++ 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index e0f83ae4d6..bfe878f1d1 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -138,12 +138,13 @@ export function graphqlQueryRepository(query: string, variables: unknown, operat // The argument text itself, from the original query (blanking keeps every offset). const args = query.slice(start + 1, end).slice(open + 1, close); const values = variables && typeof variables === "object" && !Array.isArray(variables) ? variables as Record : {}; - const pairs = args.split(",").map(pair => pair.trim()).filter(Boolean); - if (pairs.length !== 2) return null; + // GraphQL commas are optional: the arguments are exactly two `name: value` + // pairs, separated by whitespace and/or commas, with nothing else between. + const pair = /([_A-Za-z][_0-9A-Za-z]*)\s*:\s*(\$[_A-Za-z][_0-9A-Za-z]*|"[^"\\]*")/g; + const pairs = [...args.matchAll(pair)]; + if (pairs.length !== 2 || args.replace(pair, "").replace(/[\s,]/g, "") !== "") return null; const parsed = new Map(); - for (const pair of pairs) { - const match = /^([_A-Za-z][_0-9A-Za-z]*)\s*:\s*(\$[_A-Za-z][_0-9A-Za-z]*|"[^"\\]*")$/.exec(pair); - if (!match) return null; + for (const match of pairs) { const value = match[2]!.startsWith("$") ? values[match[2]!.slice(1)] : match[2]!.slice(1, -1); if (typeof value !== "string" || !NAME.test(value)) return null; parsed.set(match[1]!, value); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index bafd159d42..e93161fdf5 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -174,6 +174,8 @@ test("graphqlQueryRepository reads literal and variable arguments, and refuses c expect(graphqlQueryRepository('query Closed($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { timelineItems(last: 5, itemTypes: [CLOSED_EVENT]) { nodes { ... on ClosedEvent { createdAt actor { login } closer { __typename ... on PullRequest { number merged } } } } } } } }', { owner: "ithaca", name: "watchtower", number: 7 }), "NESTED_IN_REPOSITORY_ALLOWED").toBe("ithaca/watchtower"); expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { id } }', {})).toBe("ithaca/watchtower"); + expect(graphqlQueryRepository('query { repository(owner:"ithaca" name:"watchtower") { id } }', {}), "COMMALESS_ARGUMENTS_ALLOWED").toBe("ithaca/watchtower"); + expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower", extra) { id } }', {}), "STRAY_ARGUMENT_TEXT_REFUSED").toBeNull(); expect(graphqlQueryRepository('{ repository(owner: "ithaca", name: "watchtower") { issues(first: 5) { edges { node { number } } } } }', {}), "CONNECTION_EDGES_ALLOWED").toBe("ithaca/watchtower"); expect(graphqlQueryRepository('query {\n repository(name: $n, owner: $o) { label(name: "bug") { id } }\n}', { o: "ithaca", n: "watchtower" })).toBe("ithaca/watchtower"); expect(graphqlQueryRepository('# mutation { x }\nquery { repository(name: $n, owner: $o) { description } }', { o: "ithaca", n: "watchtower" }), "COMMENT_REFUSED").toBeNull(); From 50d7947f77db8cec058f53b2d6aeb6c0eb18ba83 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:10:41 +0000 Subject: [PATCH 11/22] fix(ui-server): bound the relay's calls in flight (#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/github/module-relay.ts | 13 +++++++++-- .../tests/module-github-relay.test.ts | 22 ++++++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index bfe878f1d1..8ed141b1a7 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -38,6 +38,8 @@ const MAX_MODULE_GITHUB_REQUEST_BYTES = 1024 * 1024; const MAX_MODULE_GITHUB_RESPONSE_BYTES = 16 * 1024 * 1024; /** Calls one run may make through the relay. */ const MAX_MODULE_GITHUB_CALLS = 500; +/** Calls in flight at once, so request and response buffers bound the runner's memory too. */ +const MAX_MODULE_GITHUB_CONCURRENT = 8; const RESPONSE_HEADERS = ["content-type", "link", "etag", "x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-github-request-id"]; const NAME = /^[A-Za-z0-9_.-]{1,100}$/; @@ -53,7 +55,7 @@ export interface ModuleGitHubRelayOptions { writes: ReadonlyMap>; observe?: (write: ModuleGitHubWriteRecord) => void; /** @internal Test seams. */ - fetch?: typeof fetch; origin?: string; maxCalls?: number; maxResponseBytes?: number; + fetch?: typeof fetch; origin?: string; maxCalls?: number; maxResponseBytes?: number; maxConcurrent?: number; } export interface ModuleGitHubRelay { dir: string; socketPath: string; stop(): Promise } @@ -223,6 +225,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const granted = new Map(options.repositories.map(repository => [lower(repository), repository])); const maxCalls = options.maxCalls ?? MAX_MODULE_GITHUB_CALLS; const maxResponseBytes = options.maxResponseBytes ?? MAX_MODULE_GITHUB_RESPONSE_BYTES; + const maxConcurrent = options.maxConcurrent ?? MAX_MODULE_GITHUB_CONCURRENT; let calls = 0; // Private to this server user; the one worker of this run sees only the bound socket. const dir = mkdtempSync(join(tmpdir(), "brain-module-github-")); @@ -296,14 +299,20 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul return new Response(Buffer.from(bytes!), { status: upstream.status, headers }); } + let active = 0; const server = Bun.serve({ unix: socketPath, async fetch(request) { + // Refused before any byte is read: at most this many requests are held at once. + if (active >= maxConcurrent) { + return Response.json({ message: `The module GitHub relay serves at most ${maxConcurrent} calls at once; retry after one finishes.`, brain_relay_refusal: "relay_busy" }, { status: 503 }); + } + active++; try { return await handle(request); } catch (error) { if (error instanceof Refusal) return Response.json({ message: error.message, brain_relay_refusal: error.code }, { status: error.status }); return Response.json({ message: "The module GitHub relay could not reach GitHub.", brain_relay_refusal: "upstream_unreachable" }, { status: 502 }); - } + } finally { active--; } }, }); chmodSync(socketPath, separateIdentity ? 0o660 : 0o600); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index e93161fdf5..e1b3367adf 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -12,11 +12,13 @@ let upstream: ReturnType; const seen: Array<{ method: string; path: string; authorization: string | null; body: string }> = []; let redirect = false; let large = 0; +let hold: Promise | null = null; beforeAll(() => { upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { const url = new URL(request.url); seen.push({ method: request.method, path: `${url.pathname}${url.search}`, authorization: request.headers.get("authorization"), body: await request.text() }); + if (hold) await hold; if (redirect) return new Response(null, { status: 302, headers: { location: "https://elsewhere.example/" } }); if (large) { // A chunked body with no length: only reading it shows its size. @@ -28,13 +30,13 @@ beforeAll(() => { }); afterAll(() => { upstream.stop(true); }); const relays: ModuleGitHubRelay[] = []; -afterEach(async () => { for (const relay of relays.splice(0)) await relay.stop(); seen.length = 0; redirect = false; large = 0; }); +afterEach(async () => { for (const relay of relays.splice(0)) await relay.stop(); seen.length = 0; redirect = false; large = 0; hold = null; }); -function relay(options: { token?: string | undefined; writes?: string; maxCalls?: number; maxResponseBytes?: number } = {}) { +function relay(options: { token?: string | undefined; writes?: string; maxCalls?: number; maxResponseBytes?: number; maxConcurrent?: number } = {}) { const writes: ModuleGitHubWriteRecord[] = []; const started = startModuleGitHubRelay({ token: () => "token" in options ? options.token : TOKEN, repositories: ["ithaca/watchtower"], writes: parseModuleGitHubWrites(options.writes ?? "").writes, observe: write => { writes.push(write); }, - origin: upstream.url.origin, ...(options.maxCalls ? { maxCalls: options.maxCalls } : {}), ...(options.maxResponseBytes ? { maxResponseBytes: options.maxResponseBytes } : {}) }); + origin: upstream.url.origin, ...(options.maxCalls ? { maxCalls: options.maxCalls } : {}), ...(options.maxResponseBytes ? { maxResponseBytes: options.maxResponseBytes } : {}), ...(options.maxConcurrent ? { maxConcurrent: options.maxConcurrent } : {}) }); relays.push(started); const call = (method: string, path: string, body?: unknown, headers: Record = {}) => fetch(`http://localhost${path}`, { method, unix: started.socketPath, headers: { authorization: "Bearer worker-supplied", ...headers }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), @@ -111,6 +113,20 @@ describe("module GitHub relay reads (#4259)", () => { expect(moduleGitHubTokenSource({ BRAIN_UI_MODULE_GITHUB_TOKEN: ` ${TOKEN} ` })()).toBe(TOKEN); }); + test("calls beyond the in-flight bound are refused before they are read", async () => { + let release!: () => void; + hold = new Promise(resolve => { release = resolve; }); + const { call } = relay({ maxConcurrent: 2 }); + const first = call("GET", "/repos/ithaca/watchtower/issues"), second = call("GET", "/repos/ithaca/watchtower/pulls"); + while (seen.length < 2) await Bun.sleep(5); + const third = await call("GET", "/repos/ithaca/watchtower/labels"); + expect(third.status, "IN_FLIGHT_BOUND").toBe(503); + expect((await third.json()).brain_relay_refusal).toBe("relay_busy"); + release(); + expect([(await first).status, (await second).status]).toEqual([200, 200]); + expect((await call("GET", "/repos/ithaca/watchtower/labels")).status, "BOUND_FREES_AFTER_FINISH").toBe(200); + }); + test("a redirect is never followed, and the call budget is enforced", async () => { redirect = true; const { call } = relay({ maxCalls: 1 }); From cfc2226aa76402c797878f793e7b3840359c30a2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:20:04 +0000 Subject: [PATCH 12/22] fix(ui-server): name the right next step for every refusal (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/github/module-relay.ts | 12 +++++++++--- packages/ui-server/tests/module-github-relay.test.ts | 3 +++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index 8ed141b1a7..30e9a08e6d 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -242,6 +242,12 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul refuse(403, "write_not_enabled", `${operation} on ${granted.get(repository)} is not enabled: add https://github.com/${granted.get(repository)}#${operation} to BRAIN_UI_MODULE_GITHUB_WRITES.`); }; + /** A path segment, decoded; a malformed escape is refused as an invalid path, never mistaken for an upstream failure. */ + const segment = (raw: string): string => { + try { return decodeURIComponent(raw); } + catch { return refuse(400, "invalid_path", "The relayed path has a malformed escape: reads are GET under a /repos/// granted through BRAIN_UI_MODULE_REPOSITORIES."); } + }; + async function handle(request: Request): Promise { const url = new URL(request.url); const method = request.method.toUpperCase(); @@ -251,7 +257,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul let write: { repository: string; operation: ModuleGitHubWrite; number: number } | undefined; const repo = /^\/repos\/([^/]+)\/([^/]+)(\/.*)?$/.exec(path); if (method === "GET" && repo) { - repositoryOf(decodeURIComponent(repo[1]!), decodeURIComponent(repo[2]!)); + repositoryOf(segment(repo[1]!), segment(repo[2]!)); } else if (method === "POST" && path === "/graphql" && !url.search) { body = await boundedBody(request); const value = jsonObject(body); @@ -261,14 +267,14 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul if (!target) refuse(403, "graphql_not_allowed", "Only one GraphQL query whose one root field is repository(owner:, name:), without comments, block strings or escapes, is relayed; mutations and other roots are refused. The repository must be granted through the module's repositories and BRAIN_UI_MODULE_REPOSITORIES."); repositoryOf(...(target!.split("/") as [string, string])); } else if (method === "POST" && repo && /^\/issues\/[1-9][0-9]{0,9}\/comments$/.test(repo[3] ?? "") && !url.search) { - const repository = repositoryOf(decodeURIComponent(repo[1]!), decodeURIComponent(repo[2]!)); + const repository = repositoryOf(segment(repo[1]!), segment(repo[2]!)); writeAllowed(repository, "issue_comment"); body = await boundedBody(request); const value = jsonObject(body); if (typeof value.body !== "string" || !value.body.trim() || Object.keys(value).length !== 1) refuse(400, "invalid_body", "An issue comment is { body } with nonempty text."); write = { repository, operation: "issue_comment", number: Number(repo[3]!.split("/")[2]) }; } else if (method === "PATCH" && repo && /^\/issues\/[1-9][0-9]{0,9}$/.test(repo[3] ?? "") && !url.search) { - const repository = repositoryOf(decodeURIComponent(repo[1]!), decodeURIComponent(repo[2]!)); + const repository = repositoryOf(segment(repo[1]!), segment(repo[2]!)); writeAllowed(repository, "issue_state"); body = await boundedBody(request); const value = jsonObject(body); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index e1b3367adf..edc19aedc3 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -59,6 +59,9 @@ describe("module GitHub relay reads (#4259)", () => { expect(foreign.status, "FOREIGN_REPOSITORY_REFUSED").toBe(403); expect((await foreign.json()).brain_relay_refusal).toBe("repository_not_granted"); expect((await call("GET", "/user")).status, "NON_REPOSITORY_PATH_REFUSED").toBe(403); + const malformed = await call("GET", "/repos/ithaca/%E0/issues"); + expect(malformed.status, "MALFORMED_ESCAPE_REFUSED").toBe(400); + expect((await malformed.json()).message, "MALFORMED_ESCAPE_NAMES_SETTING").toContain("BRAIN_UI_MODULE_REPOSITORIES"); const removal = await call("DELETE", "/repos/ithaca/watchtower"); expect(removal.status, "DELETE_REFUSED").toBe(403); expect((await removal.json()).message, "NOT_RELAYED_NAMES_SETTINGS").toMatch(/BRAIN_UI_MODULE_REPOSITORIES.*BRAIN_UI_MODULE_GITHUB_WRITES/); From cbce80585a9a177b0c4a6be4b63783bbea406946 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:30:17 +0000 Subject: [PATCH 13/22] fix(ui-server): truthful sync review rationale and reports; relay refusals, lost writes and bounds recorded (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- docs/integration-contract/package-api.md | 8 +++++--- packages/ui-server/src/github/module-relay.ts | 11 +++++++++-- .../tests/module-github-relay.test.ts | 18 +++++++++++++++++- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index b6562d1e9e..51291fadb2 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1042,11 +1042,13 @@ the operator's `BRAIN_UI_MODULE_GITHUB_WRITES` enables them for that repository, and `PATCH /repos//issues/` 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, 502 -or 503 (`unavailable` without the token). Request bodies are bounded at 1 MiB, -responses at 16 MiB and calls at 500 per run. The response keeps GitHub's status, +or 503 (`unavailable` without the token). A call beyond 8 in flight is refused with 503 `relay_busy` before anything is +read. 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 }`. Neither setting reaches a job. +`{ 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 diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index 30e9a08e6d..ce831bb600 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -252,7 +252,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const url = new URL(request.url); const method = request.method.toUpperCase(); const path = url.pathname; - if (path.split("/").some(part => part === "." || part === "..") || path.includes("//")) refuse(400, "invalid_path", "The relayed path is not a plain GitHub API path."); + if (path.split("/").some(part => part === "." || part === "..") || path.includes("//")) refuse(400, "invalid_path", "The relayed path is not a plain GitHub API path: reads are GET under a /repos/// granted through BRAIN_UI_MODULE_REPOSITORIES."); let body: string | undefined; let write: { repository: string; operation: ModuleGitHubWrite; number: number } | undefined; const repo = /^\/repos\/([^/]+)\/([^/]+)(\/.*)?$/.exec(path); @@ -289,11 +289,18 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const token = options.token(); if (!token) refuse(503, "unavailable", "The module GitHub relay has no credential: set BRAIN_UI_MODULE_GITHUB_TOKEN on the host."); if (++calls > maxCalls) refuse(429, "budget_exceeded", `This run made its ${maxCalls} relayed GitHub calls.`); - const upstream = await (options.fetch ?? fetch)(new URL(`${path}${url.search}`, origin), { + let upstream: Response; + try { + upstream = await (options.fetch ?? fetch)(new URL(`${path}${url.search}`, origin), { method, redirect: "manual", ...(body !== undefined ? { body } : {}), headers: { authorization: `Bearer ${token}`, accept: request.headers.get("accept")?.startsWith("application/vnd.github") ? request.headers.get("accept")! : "application/vnd.github+json", "x-github-api-version": "2022-11-28", "user-agent": "brain-ui-module", ...(body !== undefined ? { "content-type": "application/json" } : {}) }, }); + } catch (error) { + // GitHub may have performed a write whose answer was lost: it is recorded with an unknown status (0). + if (write) { try { options.observe?.({ ...write, repository: granted.get(write.repository)!, status: 0 }); } catch { /* Recording never fails the call. */ } } + throw error; + } // GitHub has answered: a write it may have performed is recorded now, whatever happens to its body. if (write) { try { options.observe?.({ ...write, repository: granted.get(write.repository)!, status: upstream.status }); } catch { /* Recording never fails the call. */ } } if (upstream.status >= 300 && upstream.status < 400) { await upstream.body?.cancel(); refuse(502, "redirect", "GitHub redirected; the relay never follows a redirect."); } diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index edc19aedc3..faab7ef822 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -57,7 +57,12 @@ describe("module GitHub relay reads (#4259)", () => { const { call } = relay(); const foreign = await call("GET", "/repos/sparta/barracks/issues"); expect(foreign.status, "FOREIGN_REPOSITORY_REFUSED").toBe(403); - expect((await foreign.json()).brain_relay_refusal).toBe("repository_not_granted"); + const refusal = await foreign.json(); + expect(refusal.brain_relay_refusal).toBe("repository_not_granted"); + expect(refusal.message, "NOT_GRANTED_NAMES_SETTING").toContain("BRAIN_UI_MODULE_REPOSITORIES"); + const doubled = await call("GET", "/repos//sparta/barracks"); + expect(doubled.status, "DOUBLE_SLASH_REFUSED").toBe(400); + expect((await doubled.json()).message, "INVALID_PATH_NAMES_SETTING").toContain("BRAIN_UI_MODULE_REPOSITORIES"); expect((await call("GET", "/user")).status, "NON_REPOSITORY_PATH_REFUSED").toBe(403); const malformed = await call("GET", "/repos/ithaca/%E0/issues"); expect(malformed.status, "MALFORMED_ESCAPE_REFUSED").toBe(400); @@ -181,6 +186,17 @@ describe("module GitHub relay writes (#4259)", () => { expect(seen).toEqual([]); }); + test("a write whose upstream answer is lost is still recorded, with an unknown status", async () => { + const writes: ModuleGitHubWriteRecord[] = []; + const lost = startModuleGitHubRelay({ token: () => TOKEN, repositories: ["ithaca/watchtower"], + writes: parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment").writes, observe: write => { writes.push(write); }, + fetch: (async () => { throw new Error("connection reset after the request was sent"); }) as unknown as typeof fetch }); + relays.push(lost); + const response = await fetch(`http://localhost${COMMENTS}`, { method: "POST", unix: lost.socketPath, body: JSON.stringify({ body: "Why closed?" }) } as RequestInit); + expect(response.status).toBe(502); + expect(writes, "LOST_WRITE_RECORDED").toEqual([{ repository: "ithaca/watchtower", operation: "issue_comment", number: 7, status: 0 }]); + }); + test("the operator list parses only GitHub repositories and known operations", () => { const parsed = parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment, https://gitlab.com/ithaca/x#issue_comment https://github.com/ithaca/watchtower#merge"); expect([...parsed.writes.get("ithaca/watchtower") ?? []]).toEqual(["issue_comment"]); From 6b3296cf5579cc92b1be13b824213406759e7dae Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:43:15 +0000 Subject: [PATCH 14/22] fix(ui-server): name the right refusals and launch class (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 5 +++-- docs/modules.md | 3 +-- packages/ui-server/src/bin/brain-ui-cron.ts | 2 +- packages/ui-server/src/cron/run-job.ts | 10 +++++++-- packages/ui-server/src/github/module-relay.ts | 4 ++-- .../tests/cron-module-github-relay.test.ts | 12 ++++++++++ .../maintenance-module-github-relay.test.ts | 22 +++++++++---------- 7 files changed, 38 insertions(+), 20 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index e29f73da2f..5c95493a5c 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -614,8 +614,9 @@ 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, because -a maintenance worker has no network namespace route to the host. A token placed +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. diff --git a/docs/modules.md b/docs/modules.md index 02bdd59444..ca2078e81a 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -165,8 +165,7 @@ 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 token and has no -network. The relay is a Unix socket named in `BRAIN_MODULE_GITHUB_SOCKET` +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: diff --git a/packages/ui-server/src/bin/brain-ui-cron.ts b/packages/ui-server/src/bin/brain-ui-cron.ts index 9fea70797d..948e9e01b1 100644 --- a/packages/ui-server/src/bin/brain-ui-cron.ts +++ b/packages/ui-server/src/bin/brain-ui-cron.ts @@ -178,7 +178,7 @@ if (subcommand === "run") { repositories: cronJobRepositories({ boundary: host.boundary, dbPath: config.dbPath, moduleDiscoveryEnv: config.moduleDiscoveryEnv, env: config.childEnv, allowList: config.moduleRepositories.allowed }), // Their granted GitHub repositories' API, through the module GitHub relay (#4259). - githubRelay: { token: config.moduleGitHub.token, writes: config.moduleGitHub.writes }, + githubRelay: { token: config.moduleGitHub.token, writes: config.moduleGitHub.writes, invalid: config.moduleGitHub.invalid }, }); } finally { await host.close(); } process.exit(code); diff --git a/packages/ui-server/src/cron/run-job.ts b/packages/ui-server/src/cron/run-job.ts index 04872eb40a..42f20255ff 100644 --- a/packages/ui-server/src/cron/run-job.ts +++ b/packages/ui-server/src/cron/run-job.ts @@ -92,7 +92,10 @@ interface RunJobOptions { * repositories reaches their API through a per-run host relay that holds * this credential and allows only these writes. */ - githubRelay?: Pick; + githubRelay?: Pick & { + /** Entries of BRAIN_UI_MODULE_GITHUB_WRITES that enable nothing; named on each run that gets a relay. */ + invalid?: readonly string[]; + }; stdout?: TextSink; stderr?: TextSink; } @@ -326,7 +329,10 @@ export async function runJob( // Its granted GitHub repositories' API, through a per-run host relay (#4259). const githubRepositories = access?.ok ? access.repositories.map(repository => githubRepositoryOf(repository.url)).filter((name): name is string => name !== null) : []; if (githubRepositories.length && options.githubRelay) { - githubRelay = startModuleGitHubRelay({ ...options.githubRelay, repositories: githubRepositories, + if (options.githubRelay.invalid?.length) + writeLine(stderr, `[cron-run] ${options.jobName}: BRAIN_UI_MODULE_GITHUB_WRITES ignores invalid entries (expected https://github.com//#issue_comment or #issue_state): ${options.githubRelay.invalid.join(", ")}`); + const { invalid: _invalid, ...relayOptions } = options.githubRelay; + githubRelay = startModuleGitHubRelay({ ...relayOptions, repositories: githubRepositories, observe: write => recorder?.event?.("github_write", write) }); } proc = await options.boundary.launch({ argv: options.command, env, ...cronJobClass(options.jobName), diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index ce831bb600..6ab7350df7 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -1,8 +1,8 @@ /** * The host GitHub API relay for module cron jobs (#4259). * - * A scheduled module job runs in a maintenance worker with no credential and - * no network. A job whose repositories the host granted (the module's + * A scheduled module job runs in a maintenance worker that holds no GitHub + * credential. A job whose repositories the host granted (the module's * `repositories` ∩ `BRAIN_UI_MODULE_REPOSITORIES`, the same grant as its read * mirror) also gets this per-run relay: a Unix socket in a private directory * the launcher binds read-only into that one worker. The job sends ordinary diff --git a/packages/ui-server/tests/cron-module-github-relay.test.ts b/packages/ui-server/tests/cron-module-github-relay.test.ts index 97792481b0..bdf7c287a0 100644 --- a/packages/ui-server/tests/cron-module-github-relay.test.ts +++ b/packages/ui-server/tests/cron-module-github-relay.test.ts @@ -69,6 +69,18 @@ test("a job granted a GitHub repository reaches its API through the run's relay, } finally { db.close(); } }); +test("invalid write entries are named on the run, not dropped silently", async () => { + let err = ""; + const boundary = { isolated: () => true, brainPath: dir, launch: async () => finished() } as unknown as HostBoundary; + const code = await runJob({ ...JOB, dbPath: join(dir, "ui-invalid.db"), childEnv: { PATH: "/usr/bin:/bin" }, exec: {}, boundary, + stdout: { write() {} }, stderr: { write(text: string) { err += text; } }, + repositories: async () => ({ ok: true, notes: [], repositories: [{ url: "https://github.com/ithaca/watchtower", mirror: join(dir, "mirror.git") }] }), + githubRelay: { token: () => TOKEN, writes: new Map(), invalid: ["https://github.com/ithaca/watchtower#issue-comment"] } }, { sinkPath: join(dir, "sink-invalid.jsonl") }); + expect(code).toBe(0); + expect(err, "INVALID_WRITES_NAMED").toContain("BRAIN_UI_MODULE_GITHUB_WRITES ignores invalid entries"); + expect(err).toContain("#issue-comment"); +}); + test("a job granted no GitHub repository gets no relay", async () => { const launched: BrainExecution[] = []; const boundary = { isolated: () => true, brainPath: dir, launch: async (execution: BrainExecution) => { launched.push(execution); return finished(); } } as unknown as HostBoundary; diff --git a/packages/ui-server/tests/maintenance-module-github-relay.test.ts b/packages/ui-server/tests/maintenance-module-github-relay.test.ts index 7c2cfeadee..af2c0a94d7 100644 --- a/packages/ui-server/tests/maintenance-module-github-relay.test.ts +++ b/packages/ui-server/tests/maintenance-module-github-relay.test.ts @@ -1,14 +1,16 @@ /** - * A credential-free maintenance worker reaches the module GitHub relay (#4259) - * under real bubblewrap: the relay's socket is bound read-only at - * `/run/brain-github`, the worker holds no token and no network, and its - * request reaches the loopback GitHub stand-in with the host's token. + * A module job's maintenance worker, launched with the cron runner's own class + * (credentialed, exclusive), reaches the module GitHub relay (#4259) under real + * bubblewrap: the relay's socket is bound read-only at `/run/brain-github`, the + * worker holds no relay token in its environment, process or + * `/etc/environment`, and its request reaches the loopback GitHub stand-in + * with the host's token. */ import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { createNativeBrainManagerClient } from "@schlessera/brain-ui-sdk/internal"; -import { createHostBoundary } from "../src/brain/host-boundary.js"; +import { createHostBoundary, cronJobClass } from "../src/brain/host-boundary.js"; import { startModuleGitHubRelay } from "../src/github/module-relay.js"; import { createNativeAppFixture } from "./helpers/native-app-fixture.js"; @@ -33,7 +35,7 @@ beforeAll(() => { afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); seen.length = 0; }); afterAll(() => { upstream.stop(true); rmSync(root, { recursive: true, force: true }); }); -test("a credential-free maintenance worker reaches the relay through its socket, holding no token and no network", async () => { +test("a module job's maintenance worker, launched as the cron runner launches it, reaches the relay through its socket and holds no token", async () => { const state = mkdtempSync(join(root, "state-")); const native = createNativeAppFixture(brain); cleanup.push(native.close); const host = createHostBoundary({ brainPath: brain, dbPath: join(state, "ui.db"), exec: {}, nativeManager: createNativeBrainManagerClient(native.nativeBrain) }); @@ -41,17 +43,16 @@ test("a credential-free maintenance worker reaches the relay through its socket, cleanup.push(() => relay.stop()); const program = `const socket = process.env.BRAIN_MODULE_GITHUB_SOCKET; const relayed = await fetch("http://localhost/repos/ithaca/watchtower/issues", { unix: socket }).then(r => r.status, e => String(e)); - const direct = await fetch(${JSON.stringify(upstream.url.origin)} + "/repos/ithaca/watchtower/issues").then(r => r.status, () => "unreachable"); const fs = require("node:fs"); const proc = { environ: fs.readFileSync("/proc/self/environ", "utf8"), cmdline: fs.readFileSync("/proc/self/cmdline", "utf8"), etcEnvironment: (() => { try { return fs.readFileSync("/etc/environment", "utf8"); } catch (error) { return error.code; } })() }; - console.log(JSON.stringify({ socket, relayed, direct, env: process.env, proc, relayDir: fs.readdirSync("/run/brain-github") }));`; + console.log(JSON.stringify({ socket, relayed, env: process.env, proc, relayDir: fs.readdirSync("/run/brain-github") }));`; // A misconfigured host that hands the job the relay's token anyway: it never reaches the worker. const child = await host.launch({ argv: [process.execPath, "--config=/dev/null", "-e", program], env: { PATH: "/usr/bin:/bin", BRAIN_UI_MODULE_GITHUB_TOKEN: TOKEN }, - credentials: false, gate: "shared", purpose: "Odysseus module job", githubRelay: relay.dir }); + ...cronJobClass("beacon-run"), purpose: "Odysseus module job", githubRelay: relay.dir }); const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exitCode, stderr).toBe(0); - const observed = JSON.parse(stdout.trim().split("\n").at(-1)!) as { socket: string; relayed: number | string; direct: number | string; env: Record; + const observed = JSON.parse(stdout.trim().split("\n").at(-1)!) as { socket: string; relayed: number | string; env: Record; proc: { environ: string; cmdline: string; etcEnvironment: string }; relayDir: string[] }; expect(observed.env.BRAIN_UI_MODULE_GITHUB_TOKEN, "WORKER_ENV_HAS_NO_TOKEN").toBeUndefined(); expect(`${observed.proc.environ}${observed.proc.cmdline}`, "WORKER_PROCESS_HAS_NO_TOKEN").not.toContain(TOKEN); @@ -60,7 +61,6 @@ test("a credential-free maintenance worker reaches the relay through its socket, expect(observed.relayDir, "RELAY_DIR_HOLDS_ONLY_THE_SOCKET").toEqual(["github.sock"]); expect(observed.socket, "WORKER_SOCKET_PATH").toBe("/run/brain-github/github.sock"); expect(observed.relayed, "WORKER_REACHES_RELAY").toBe(200); - expect(observed.direct, "WORKER_HAS_NO_NETWORK").toBe("unreachable"); expect(stdout, "WORKER_HOLDS_NO_TOKEN").not.toContain(TOKEN); expect(seen, "RELAY_ADDS_HOST_TOKEN").toEqual([{ path: "/repos/ithaca/watchtower/issues", authorization: `Bearer ${TOKEN}` }]); }, 120_000); From 55326618f5c7658d993c1f56f2e2666bd93215dc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:54:08 +0000 Subject: [PATCH 15/22] fix(ui-server): record the real cause of a refused sync review; every relayed write in the run output (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/cron/run-job.ts | 6 +++++- packages/ui-server/tests/cron-module-github-relay.test.ts | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/cron/run-job.ts b/packages/ui-server/src/cron/run-job.ts index 42f20255ff..84a25b6026 100644 --- a/packages/ui-server/src/cron/run-job.ts +++ b/packages/ui-server/src/cron/run-job.ts @@ -333,7 +333,11 @@ export async function runJob( writeLine(stderr, `[cron-run] ${options.jobName}: BRAIN_UI_MODULE_GITHUB_WRITES ignores invalid entries (expected https://github.com//#issue_comment or #issue_state): ${options.githubRelay.invalid.join(", ")}`); const { invalid: _invalid, ...relayOptions } = options.githubRelay; githubRelay = startModuleGitHubRelay({ ...relayOptions, repositories: githubRepositories, - observe: write => recorder?.event?.("github_write", write) }); + // Each write reaches the run's own output too, so it is recorded even where Activity tracking is unavailable. + observe: write => { + writeLine(stderr, `[cron-run] ${options.jobName}: github_write ${write.operation} ${write.repository}#${write.number} status ${write.status}`); + recorder?.event?.("github_write", write); + } }); } proc = await options.boundary.launch({ argv: options.command, env, ...cronJobClass(options.jobName), purpose: `cron ${options.jobName}`, writeFiles: [sinkPath], ...(syncJob ? { sync: true } : {}), diff --git a/packages/ui-server/tests/cron-module-github-relay.test.ts b/packages/ui-server/tests/cron-module-github-relay.test.ts index bdf7c287a0..d9a5aa478c 100644 --- a/packages/ui-server/tests/cron-module-github-relay.test.ts +++ b/packages/ui-server/tests/cron-module-github-relay.test.ts @@ -50,8 +50,9 @@ test("a job granted a GitHub repository reaches its API through the run's relay, BRAIN_UI_SUBPROCESS_ENV_EXTRA: "BRAIN_UI_MODULE_GITHUB_TOKEN" }, ["BRAIN_UI_MODULE_GITHUB_TOKEN"]); expect(config.moduleGitHub.token(), "RUNNER_READS_TOKEN").toBe(TOKEN); expect(JSON.stringify(config.childEnv), "CHILD_ENV_HAS_NO_TOKEN").not.toContain(TOKEN); + let err = ""; const code = await runJob({ ...JOB, dbPath, childEnv: config.childEnv, exec: {}, boundary, - stdout: { write() {} }, stderr: { write() {} }, + stdout: { write() {} }, stderr: { write(text: string) { err += text; } }, repositories: async () => ({ ok: true, notes: [], repositories: [{ url: "https://github.com/ithaca/watchtower", mirror: join(dir, "mirror.git") }, { url: "http://127.0.0.1:9/ithaca/harbor", mirror: join(dir, "harbor.git") }] }), githubRelay: { token: () => TOKEN, writes: parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment").writes, origin: upstream.url.origin } }, @@ -62,6 +63,7 @@ test("a job granted a GitHub repository reaches its API through the run's relay, expect(launched[0]!.env, "TOKEN_NOT_IN_JOB_ENV").not.toHaveProperty("BRAIN_UI_MODULE_GITHUB_TOKEN"); expect(JSON.stringify(launched[0]!.env)).not.toContain(TOKEN); expect(existsSync(launched[0]!.githubRelay!), "RELAY_ENDS_WITH_RUN").toBe(false); + expect(err, "WRITE_IN_RUN_OUTPUT").toContain("github_write issue_comment ithaca/watchtower#7 status 200"); const db = createUiDb(dbPath); try { const events = db.query("SELECT payload FROM activity_events WHERE event_type = 'github_write'").all() as { payload: string }[]; From 3886c6d4b6b6d72a0c4f980e671cd247c1eab404 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:05:35 +0000 Subject: [PATCH 16/22] fix(ui-server): record a sync policy read failure by its cause; native edit-path test; relay settles in-flight writes and names settings (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/github/module-relay.ts | 30 ++++++++++++------- .../tests/module-github-relay.test.ts | 18 ++++++++++- 2 files changed, 37 insertions(+), 11 deletions(-) diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index 6ab7350df7..8dd52c3a46 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -38,6 +38,8 @@ const MAX_MODULE_GITHUB_REQUEST_BYTES = 1024 * 1024; const MAX_MODULE_GITHUB_RESPONSE_BYTES = 16 * 1024 * 1024; /** Calls one run may make through the relay. */ const MAX_MODULE_GITHUB_CALLS = 500; +/** How long stopping waits for calls in flight, so a write GitHub performs is still recorded. */ +const STOP_SETTLE_MS = 10_000; /** Calls in flight at once, so request and response buffers bound the runner's memory too. */ const MAX_MODULE_GITHUB_CONCURRENT = 8; const RESPONSE_HEADERS = ["content-type", "link", "etag", "x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-github-request-id"]; @@ -55,7 +57,7 @@ export interface ModuleGitHubRelayOptions { writes: ReadonlyMap>; observe?: (write: ModuleGitHubWriteRecord) => void; /** @internal Test seams. */ - fetch?: typeof fetch; origin?: string; maxCalls?: number; maxResponseBytes?: number; maxConcurrent?: number; + fetch?: typeof fetch; origin?: string; maxCalls?: number; maxResponseBytes?: number; maxConcurrent?: number; stopSettleMs?: number; } export interface ModuleGitHubRelay { dir: string; socketPath: string; stop(): Promise } @@ -215,8 +217,8 @@ async function boundedBody(request: Request): Promise { function jsonObject(text: string): Record { let value: unknown; - try { value = JSON.parse(text); } catch { refuse(400, "invalid_body", "The relayed request body must be a JSON object."); } - if (!value || typeof value !== "object" || Array.isArray(value)) refuse(400, "invalid_body", "The relayed request body must be a JSON object."); + try { value = JSON.parse(text); } catch { refuse(400, "invalid_body", "The relayed request body must be a JSON object; the only writes are those BRAIN_UI_MODULE_GITHUB_WRITES enables."); } + if (!value || typeof value !== "object" || Array.isArray(value)) refuse(400, "invalid_body", "The relayed request body must be a JSON object; the only writes are those BRAIN_UI_MODULE_GITHUB_WRITES enables."); return value as Record; } @@ -226,6 +228,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const maxCalls = options.maxCalls ?? MAX_MODULE_GITHUB_CALLS; const maxResponseBytes = options.maxResponseBytes ?? MAX_MODULE_GITHUB_RESPONSE_BYTES; const maxConcurrent = options.maxConcurrent ?? MAX_MODULE_GITHUB_CONCURRENT; + const stopSettleMs = options.stopSettleMs ?? STOP_SETTLE_MS; let calls = 0; // Private to this server user; the one worker of this run sees only the bound socket. const dir = mkdtempSync(join(tmpdir(), "brain-module-github-")); @@ -262,7 +265,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul body = await boundedBody(request); const value = jsonObject(body); if (typeof value.query !== "string" || Object.keys(value).some(key => !["query", "variables", "operationName"].includes(key))) - refuse(400, "invalid_body", "A relayed GraphQL request is { query, variables?, operationName? }."); + refuse(400, "invalid_body", "A relayed GraphQL request is { query, variables?, operationName? }, a read of a repository granted through BRAIN_UI_MODULE_REPOSITORIES."); const target = graphqlQueryRepository(value.query as string, value.variables, value.operationName); if (!target) refuse(403, "graphql_not_allowed", "Only one GraphQL query whose one root field is repository(owner:, name:), without comments, block strings or escapes, is relayed; mutations and other roots are refused. The repository must be granted through the module's repositories and BRAIN_UI_MODULE_REPOSITORIES."); repositoryOf(...(target!.split("/") as [string, string])); @@ -271,7 +274,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul writeAllowed(repository, "issue_comment"); body = await boundedBody(request); const value = jsonObject(body); - if (typeof value.body !== "string" || !value.body.trim() || Object.keys(value).length !== 1) refuse(400, "invalid_body", "An issue comment is { body } with nonempty text."); + if (typeof value.body !== "string" || !value.body.trim() || Object.keys(value).length !== 1) refuse(400, "invalid_body", "An issue comment is { body } with nonempty text and nothing else: the issue_comment write BRAIN_UI_MODULE_GITHUB_WRITES enables allows no other field."); write = { repository, operation: "issue_comment", number: Number(repo[3]!.split("/")[2]) }; } else if (method === "PATCH" && repo && /^\/issues\/[1-9][0-9]{0,9}$/.test(repo[3] ?? "") && !url.search) { const repository = repositoryOf(segment(repo[1]!), segment(repo[2]!)); @@ -281,7 +284,7 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const keys = Object.keys(value); if (!["open", "closed"].includes(value.state as string) || keys.some(key => key !== "state" && key !== "state_reason") || (value.state_reason !== undefined && !["completed", "not_planned", "reopened", null].includes(value.state_reason as string | null))) - refuse(400, "invalid_body", "An issue state change is { state: open|closed, state_reason? } and nothing else."); + refuse(400, "invalid_body", "An issue state change is { state: open|closed, state_reason? } and nothing else: the issue_state write BRAIN_UI_MODULE_GITHUB_WRITES enables allows no other field."); write = { repository, operation: "issue_state", number: Number(repo[3]!.split("/")[2]) }; } else { refuse(403, "not_relayed", `${method} ${path} is not relayed: reads are GET under a /repos/// granted through BRAIN_UI_MODULE_REPOSITORIES, or a repository GraphQL query; the only writes are issue_comment and issue_state, enabled in BRAIN_UI_MODULE_GITHUB_WRITES.`); @@ -312,16 +315,20 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul return new Response(Buffer.from(bytes!), { status: upstream.status, headers }); } - let active = 0; + let active = 0, stopping = false; + const inFlight = new Set>(); const server = Bun.serve({ unix: socketPath, async fetch(request) { + if (stopping) return Response.json({ message: "The run ended; the module GitHub relay takes no new calls.", brain_relay_refusal: "relay_stopped" }, { status: 503 }); // Refused before any byte is read: at most this many requests are held at once. if (active >= maxConcurrent) { return Response.json({ message: `The module GitHub relay serves at most ${maxConcurrent} calls at once; retry after one finishes.`, brain_relay_refusal: "relay_busy" }, { status: 503 }); } active++; - try { return await handle(request); } + const call = handle(request); + inFlight.add(call); void call.finally(() => inFlight.delete(call)).catch(() => {}); + try { return await call; } catch (error) { if (error instanceof Refusal) return Response.json({ message: error.message, brain_relay_refusal: error.code }, { status: error.status }); return Response.json({ message: "The module GitHub relay could not reach GitHub.", brain_relay_refusal: "upstream_unreachable" }, { status: 502 }); @@ -329,11 +336,14 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul }, }); chmodSync(socketPath, separateIdentity ? 0o660 : 0o600); - let stopping: Promise | undefined; + let stopped: Promise | undefined; return { dir, socketPath, + /** Takes no new call, lets calls in flight finish (and record their writes) for a bounded time, then closes. */ stop() { - return stopping ??= (async () => { + return stopped ??= (async () => { + stopping = true; + if (inFlight.size) await Promise.race([Promise.allSettled([...inFlight]), Bun.sleep(stopSettleMs)]); await server.stop(true); rmSync(dir, { recursive: true, force: true }); })(); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index faab7ef822..4dc85d106c 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -160,7 +160,9 @@ describe("module GitHub relay writes (#4259)", () => { const { call, writes } = relay({ writes: "https://github.com/ithaca/watchtower#issue_comment https://github.com/Ithaca/Watchtower#issue_state" }); expect((await call("POST", COMMENTS, { body: "Telemachus asks why this closed." })).status, "COMMENT_FORWARDED").toBe(200); expect((await call("PATCH", "/repos/ithaca/watchtower/issues/7", { state: "open" })).status, "STATE_FORWARDED").toBe(200); - expect((await call("PATCH", "/repos/ithaca/watchtower/issues/7", { state: "open", title: "Renamed" })).status, "STATE_EXTRA_FIELD_REFUSED").toBe(400); + const extra = await call("PATCH", "/repos/ithaca/watchtower/issues/7", { state: "open", title: "Renamed" }); + expect(extra.status, "STATE_EXTRA_FIELD_REFUSED").toBe(400); + expect((await extra.json()).message, "EXTRA_FIELD_NAMES_SETTING").toContain("BRAIN_UI_MODULE_GITHUB_WRITES"); expect((await call("POST", COMMENTS, { body: "x", extra: true })).status, "COMMENT_EXTRA_FIELD_REFUSED").toBe(400); expect(seen.map(entry => `${entry.method} ${entry.path}`)).toEqual([`POST ${COMMENTS}`, "PATCH /repos/ithaca/watchtower/issues/7"]); expect(writes, "WRITES_RECORDED").toEqual([ @@ -197,6 +199,20 @@ describe("module GitHub relay writes (#4259)", () => { expect(writes, "LOST_WRITE_RECORDED").toEqual([{ repository: "ithaca/watchtower", operation: "issue_comment", number: 7, status: 0 }]); }); + test("stopping lets a write in flight finish and be recorded, and takes no new call", async () => { + let release!: () => void; + hold = new Promise(resolve => { release = resolve; }); + const { call, writes, started } = relay({ writes: "https://github.com/ithaca/watchtower#issue_comment" }); + const pending = call("POST", COMMENTS, { body: "Telemachus asks why this closed." }); + while (seen.length < 1) await Bun.sleep(5); + const stopping = started.stop(); + await Bun.sleep(20); + release(); + await stopping; + expect((await pending).status, "IN_FLIGHT_WRITE_FINISHES").toBe(200); + expect(writes, "IN_FLIGHT_WRITE_RECORDED").toEqual([{ repository: "ithaca/watchtower", operation: "issue_comment", number: 7, status: 200 }]); + }); + test("the operator list parses only GitHub repositories and known operations", () => { const parsed = parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment, https://gitlab.com/ithaca/x#issue_comment https://github.com/ithaca/watchtower#merge"); expect([...parsed.writes.get("ithaca/watchtower") ?? []]).toEqual(["issue_comment"]); From c3b47ec872e96a26cee4136665ee209de27f70d2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:19:03 +0000 Subject: [PATCH 17/22] test(ui-server): drop an assertion that cannot fail; the path guard refuses empty segments (#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/github/module-relay.ts | 3 ++- packages/ui-server/tests/module-github-relay.test.ts | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index 8dd52c3a46..27a3f4750a 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -255,7 +255,8 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const url = new URL(request.url); const method = request.method.toUpperCase(); const path = url.pathname; - if (path.split("/").some(part => part === "." || part === "..") || path.includes("//")) refuse(400, "invalid_path", "The relayed path is not a plain GitHub API path: reads are GET under a /repos/// granted through BRAIN_UI_MODULE_REPOSITORIES."); + // URL parsing has already removed dot segments; an empty segment (`//`) is what remains to refuse. + if (path.includes("//")) refuse(400, "invalid_path", "The relayed path is not a plain GitHub API path: reads are GET under a /repos/// granted through BRAIN_UI_MODULE_REPOSITORIES."); let body: string | undefined; let write: { repository: string; operation: ModuleGitHubWrite; number: number } | undefined; const repo = /^\/repos\/([^/]+)\/([^/]+)(\/.*)?$/.exec(path); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index 4dc85d106c..9531918d50 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -70,7 +70,6 @@ describe("module GitHub relay reads (#4259)", () => { const removal = await call("DELETE", "/repos/ithaca/watchtower"); expect(removal.status, "DELETE_REFUSED").toBe(403); expect((await removal.json()).message, "NOT_RELAYED_NAMES_SETTINGS").toMatch(/BRAIN_UI_MODULE_REPOSITORIES.*BRAIN_UI_MODULE_GITHUB_WRITES/); - expect((await call("GET", "/repos/ithaca/watchtower/../../sparta/barracks")).status).not.toBe(200); expect(seen, "NOTHING_FORWARDED").toEqual([]); }); From 68ded67a74577b65cf7c3ae001036a4113b09d0b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:28:00 +0000 Subject: [PATCH 18/22] fix(ui-server): record relay_stopped in the contract and prove it (#4259) Co-Authored-By: Claude Opus 5.5 --- docs/integration-contract/package-api.md | 3 ++- packages/ui-server/tests/module-github-relay.test.ts | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 51291fadb2..2a0a92995c 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1043,7 +1043,8 @@ and `PATCH /repos//issues/` 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, 502 or 503 (`unavailable` without the token). A call beyond 8 in flight is refused with 503 `relay_busy` before anything is -read. Request bodies are bounded at 1 MiB, responses at 16 MiB and calls at 500 +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: diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index 9531918d50..5e72d53d00 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -206,6 +206,9 @@ describe("module GitHub relay writes (#4259)", () => { while (seen.length < 1) await Bun.sleep(5); const stopping = started.stop(); await Bun.sleep(20); + const late = await call("GET", "/repos/ithaca/watchtower/issues"); + expect(late.status, "STOPPING_TAKES_NO_NEW_CALL").toBe(503); + expect((await late.json()).brain_relay_refusal).toBe("relay_stopped"); release(); await stopping; expect((await pending).status, "IN_FLIGHT_WRITE_FINISHES").toBe(200); From 7e98e6a32572d789a908d2f87ecad8bea34a379b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:37:30 +0000 Subject: [PATCH 19/22] fix(ui-server): record a write still unanswered when the relay stops (#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/github/module-relay.ts | 17 +++++++++++++++-- .../ui-server/tests/module-github-relay.test.ts | 12 ++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/github/module-relay.ts b/packages/ui-server/src/github/module-relay.ts index 27a3f4750a..7c10feb319 100644 --- a/packages/ui-server/src/github/module-relay.ts +++ b/packages/ui-server/src/github/module-relay.ts @@ -251,6 +251,14 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul catch { return refuse(400, "invalid_path", "The relayed path has a malformed escape: reads are GET under a /repos/// granted through BRAIN_UI_MODULE_REPOSITORIES."); } }; + const pendingWrites = new Map(); + const record = (key: symbol, status: number) => { + const write = pendingWrites.get(key); + if (!write) return; + pendingWrites.delete(key); + try { options.observe?.({ ...write, repository: granted.get(write.repository)!, status }); } catch { /* Recording never fails the call. */ } + }; + async function handle(request: Request): Promise { const url = new URL(request.url); const method = request.method.toUpperCase(); @@ -293,6 +301,9 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul const token = options.token(); if (!token) refuse(503, "unavailable", "The module GitHub relay has no credential: set BRAIN_UI_MODULE_GITHUB_TOKEN on the host."); if (++calls > maxCalls) refuse(429, "budget_exceeded", `This run made its ${maxCalls} relayed GitHub calls.`); + // A write is pending from the moment it is sent; it is recorded exactly once, when GitHub answers or when the relay stops. + const sent = write ? Symbol("write") : undefined; + if (sent) pendingWrites.set(sent, write!); let upstream: Response; try { upstream = await (options.fetch ?? fetch)(new URL(`${path}${url.search}`, origin), { @@ -302,11 +313,11 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul }); } catch (error) { // GitHub may have performed a write whose answer was lost: it is recorded with an unknown status (0). - if (write) { try { options.observe?.({ ...write, repository: granted.get(write.repository)!, status: 0 }); } catch { /* Recording never fails the call. */ } } + if (sent) record(sent, 0); throw error; } // GitHub has answered: a write it may have performed is recorded now, whatever happens to its body. - if (write) { try { options.observe?.({ ...write, repository: granted.get(write.repository)!, status: upstream.status }); } catch { /* Recording never fails the call. */ } } + if (sent) record(sent, upstream.status); if (upstream.status >= 300 && upstream.status < 400) { await upstream.body?.cancel(); refuse(502, "redirect", "GitHub redirected; the relay never follows a redirect."); } if (Number(upstream.headers.get("content-length") ?? "0") > maxResponseBytes) { await upstream.body?.cancel(); refuse(502, "response_too_large", `A relayed response is at most ${MAX_MODULE_GITHUB_RESPONSE_BYTES} bytes.`); } const bytes = await readBounded(upstream.body, maxResponseBytes); @@ -345,6 +356,8 @@ export function startModuleGitHubRelay(options: ModuleGitHubRelayOptions): Modul return stopped ??= (async () => { stopping = true; if (inFlight.size) await Promise.race([Promise.allSettled([...inFlight]), Bun.sleep(stopSettleMs)]); + // A write still unanswered when the window closes is recorded with an unknown status (0). + for (const key of [...pendingWrites.keys()]) record(key, 0); await server.stop(true); rmSync(dir, { recursive: true, force: true }); })(); diff --git a/packages/ui-server/tests/module-github-relay.test.ts b/packages/ui-server/tests/module-github-relay.test.ts index 5e72d53d00..4796279050 100644 --- a/packages/ui-server/tests/module-github-relay.test.ts +++ b/packages/ui-server/tests/module-github-relay.test.ts @@ -215,6 +215,18 @@ describe("module GitHub relay writes (#4259)", () => { expect(writes, "IN_FLIGHT_WRITE_RECORDED").toEqual([{ repository: "ithaca/watchtower", operation: "issue_comment", number: 7, status: 200 }]); }); + test("a write still unanswered when the stop window closes is recorded with an unknown status", async () => { + hold = new Promise(() => {}); + const writes: ModuleGitHubWriteRecord[] = []; + const slow = startModuleGitHubRelay({ token: () => TOKEN, repositories: ["ithaca/watchtower"], origin: upstream.url.origin, stopSettleMs: 30, + writes: parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment").writes, observe: write => { writes.push(write); } }); + relays.push(slow); + void fetch(`http://localhost${COMMENTS}`, { method: "POST", unix: slow.socketPath, body: JSON.stringify({ body: "Why closed?" }) } as RequestInit).catch(() => {}); + while (seen.length < 1) await Bun.sleep(5); + await slow.stop(); + expect(writes, "UNANSWERED_WRITE_RECORDED_AT_STOP").toEqual([{ repository: "ithaca/watchtower", operation: "issue_comment", number: 7, status: 0 }]); + }); + test("the operator list parses only GitHub repositories and known operations", () => { const parsed = parseModuleGitHubWrites("https://github.com/ithaca/watchtower#issue_comment, https://gitlab.com/ithaca/x#issue_comment https://github.com/ithaca/watchtower#merge"); expect([...parsed.writes.get("ithaca/watchtower") ?? []]).toEqual(["issue_comment"]); From dd3faa4b13ac83831dfcef34c87660060184b210 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:46:59 +0000 Subject: [PATCH 20/22] docs(modules): a redirect is refused after GitHub answers, never followed (#4259) Co-Authored-By: Claude Opus 5.5 --- docs/modules.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/modules.md b/docs/modules.md index ca2078e81a..b41a8c0bc8 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -189,8 +189,9 @@ const issues = await github("/repos/ithaca/watchtower/issues?state=closed").then 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, a redirect, more - than 500 calls in a run) is refused before any request leaves the host. + 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` From 43142ab923bf3df502d78bc938d279ec9187806a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:54:36 +0000 Subject: [PATCH 21/22] docs(contract): the relay's 502 refusals come after a call is forwarded (#4259) Co-Authored-By: Claude Opus 5.5 --- docs/integration-contract/package-api.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 2a0a92995c..027667c921 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1041,8 +1041,10 @@ the operator's `BRAIN_UI_MODULE_GITHUB_WRITES` enables them for that repository, `POST /repos//issues//comments` with exactly `{ body }` (`issue_comment`) and `PATCH /repos//issues/` 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, 502 -or 503 (`unavailable` without the token). A call beyond 8 in flight is refused with 503 `relay_busy` before anything is +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, From 6086ef6698805a91c4426955fb589bdafb7958ac Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:02:49 +0000 Subject: [PATCH 22/22] fix(ui-sdk, ui-server): reserve the relay's mount point; state the host-fallback limit of the relay token (#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-sdk/src/server/worker-launcher.ts | 2 +- packages/ui-sdk/tests/host-git-credentials.test.ts | 7 +++++++ packages/ui-server/README.md | 2 +- packages/ui-server/src/config/env.ts | 4 +++- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index 5080a2dc9b..2a4d66ec73 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -644,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)))); diff --git a/packages/ui-sdk/tests/host-git-credentials.test.ts b/packages/ui-sdk/tests/host-git-credentials.test.ts index 0479dde11d..f464a39907 100644 --- a/packages/ui-sdk/tests/host-git-credentials.test.ts +++ b/packages/ui-sdk/tests/host-git-credentials.test.ts @@ -60,3 +60,10 @@ test("every host-view worker covers /etc/environment, where a container keeps th expect(covered, `ETC_ENVIRONMENT_COVERED: ${maintenance ? "maintenance" : "agent"}`).toBe(existsSync("/etc/environment")); } }); + +test("a runtime or read path cannot take the module GitHub relay's mount point (#4259)", () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-worker-relay-mount-")); roots.push(root); + const brain = join(root, "brain"); mkdirSync(brain); + expect(() => workerCommand({ brainPath: brain, command: ["/bin/true"], env: { PATH: "/usr/bin:/bin" }, + maintenance: { credentials: false, network: false, readPaths: [process.execPath, "/run/brain-github"] } }), "RELAY_MOUNT_RESERVED").toThrow(); +}); diff --git a/packages/ui-server/README.md b/packages/ui-server/README.md index ced48d6c38..f41fafafce 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -383,7 +383,7 @@ under the [service terms](../geo/README.md#configuration). | `BRAIN_UI_MAINTENANCE_TEMP_BYTES` | Per-maintenance-command temporary-write allowance in bytes, covering its private /tmp, scratch and XDG directories. Positive page-aligned integer. Separate from agent turn temp, runtime state and output staging; overflow is ENOSPC. | 268435456 | | `BRAIN_UI_MODEL_DISCOVERY` | Model discovery against the Anthropic Models API; "0"/"off"/"false" disables. Defaults ON, except under a test runner (NODE_ENV=test) where it defaults OFF. | on (off under NODE_ENV=test) | | `BRAIN_UI_MODEL_TTL_HOURS` | How long a model-discovery result stays fresh, in hours. | 24 | -| `BRAIN_UI_MODULE_GITHUB_TOKEN` | GitHub token for the module GitHub relay (#4259): the GitHub API calls a module cron job makes to the repositories it was granted (the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories (it is the read boundary for data a GraphQL query reaches through them), with Issues read and, only where BRAIN_UI_MODULE_GITHUB_WRITES enables a write, Issues write. No fallback: GITHUB_TOKEN, the sync token and BRAIN_UI_GITHUB_TOOLS_TOKEN are never used, and without this one every relayed call is refused. Read by the cron runner only, never forwarded to a job or worker. | — | +| `BRAIN_UI_MODULE_GITHUB_TOKEN` | GitHub token for the module GitHub relay (#4259): the GitHub API calls a module cron job makes to the repositories it was granted (the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories (it is the read boundary for data a GraphQL query reaches through them), with Issues read and, only where BRAIN_UI_MODULE_GITHUB_WRITES enables a write, Issues write. No fallback: GITHUB_TOKEN, the sync token and BRAIN_UI_GITHUB_TOOLS_TOKEN are never used, and without this one every relayed call is refused. Read by the cron runner only, never forwarded to a job or worker, and covered in every worker's view of /etc/environment. The relay exists only where jobs run in maintenance workers: on a host without the worker boundary, repository jobs run as host processes with the runner's own access, like any other runner credential. | — | | `BRAIN_UI_MODULE_GITHUB_WRITES` | Operator list of the GitHub writes a module cron job may make through the module GitHub relay (#4259), comma or whitespace separated, each `https://github.com//#` with operation `issue_comment` or `issue_state`. A repository must also be granted to the job. Read by the cron runner only. Empty enables no write. | (empty — no write) | | `BRAIN_UI_MODULE_REPOSITORIES` | Operator allow-list of repository URLs (comma or whitespace separated, HTTPS) a module cron job may read. The host fetches a repository a module's `repositories` config asks for only when this list names it too, using the sync transport's credential (BRAIN_UI_SYNC_GITHUB_TOKEN, else GITHUB_TOKEN); the job's worker reads a host mirror and never holds the credential. Read by the cron runner only, never forwarded to a job. Empty refuses every request. | (empty — no module repository is fetched) | | `BRAIN_UI_NATIVE_BRAIN_DELTA_BYTES` | Positive bound for one native metadata delta stream; exceeding it refuses the observation explicitly. Content and retained-history capacities are separate. | 67108864 (64 MiB) | diff --git a/packages/ui-server/src/config/env.ts b/packages/ui-server/src/config/env.ts index 54fd471fde..5f175e6ba0 100644 --- a/packages/ui-server/src/config/env.ts +++ b/packages/ui-server/src/config/env.ts @@ -211,7 +211,9 @@ export const ENV_VARS: readonly EnvVarDescriptor[] = [ "(the module's `repositories` and BRAIN_UI_MODULE_REPOSITORIES). Use a fine-grained token limited to those repositories (it is the read boundary for data a GraphQL query reaches through them), with Issues read " + "and, only where BRAIN_UI_MODULE_GITHUB_WRITES enables a write, Issues write. No fallback: GITHUB_TOKEN, the sync token and " + "BRAIN_UI_GITHUB_TOOLS_TOKEN are never used, and without this one every relayed call is refused. Read by the cron runner only, " + - "never forwarded to a job or worker.", + "never forwarded to a job or worker, and covered in every worker's view of /etc/environment. The relay exists only where jobs run in " + + "maintenance workers: on a host without the worker boundary, repository jobs run as host processes with the runner's own access, " + + "like any other runner credential.", default: null, required: false, },