diff --git a/.changeset/gate-holder-death.md b/.changeset/gate-holder-death.md new file mode 100644 index 0000000000..97f6aa6e0e --- /dev/null +++ b/.changeset/gate-holder-death.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-sdk": patch +--- + +A worker launch whose server dies before releasing the start gate no longer starts its payload (#3392). bubblewrap's `--block-fd` starts the sandbox on the gate's end-of-file, and a dead server's gate reads end-of-file, so the payload used to run without its state, mounts or folder qualification. The gate now runs inside the sandbox in the trusted `/bin/sh`: it needs a complete `go` line, refuses end-of-file, a partial line or any other line, and closes its descriptor before the payload starts. Payload stdin is unchanged. diff --git a/docs/decisions/container-fresh-proc.md b/docs/decisions/container-fresh-proc.md index dce96b15c4..bc5341256d 100644 --- a/docs/decisions/container-fresh-proc.md +++ b/docs/decisions/container-fresh-proc.md @@ -1,7 +1,7 @@ # A fresh /proc for agent workers in a container The agent worker launcher gives every worker its own user and PID namespaces -and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:509-689`). +and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:518-698`). Under Docker's default masked `/proc` paths the kernel refuses that procfs mount, so every turn on such a host refuses with `bwrap: Can't mount proc on /newroot/proc: Operation not permitted` (#1622, @@ -22,7 +22,7 @@ does not change. /proc because the parent /proc has masked or covered paths; in Docker, run the container with --security-opt systempaths=unconfined", followed by bubblewrap's own line. Every other launch failure keeps the generic list - (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1636`). + (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1650`). The match is on bubblewrap's literal message, not a guess from the environment: a host that refuses for another reason is not told to change Docker options. @@ -145,7 +145,7 @@ most host-global `/proc` files check only the file mode, not a capability. **Ruling on #1629 (2026-10-11): a root-run server's worker gets its whole `/proc` read-only. Root servers still qualify.** `workerCommand` adds `--remount-ro /proc` after `--proc /proc` when the server's uid or effective -uid is 0 (`rootProcCover`, `packages/ui-sdk/src/server/worker-launcher.ts:334-336`). +uid is 0 (`rootProcCover`, `packages/ui-sdk/src/server/worker-launcher.ts:343-345`). Measured as container root with `systempaths=unconfined` and the seccomp profile above, with bubblewrap `0.9.0` from the image and the host's `0.12.0`, each in the ordinary and the restricted mode: diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 1ab8c2dae3..0e1c3ceb01 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -596,7 +596,7 @@ lists the keys each first-party command reads. The launcher withholds every provider credential in the subprocess descriptor from a governed or strict turn worker, except what its backend declares for its own inference and what an operator admits (`const turnProfile`, -`packages/ui-sdk/src/server/worker-launcher.ts:680-690`). A relayed turn keeps no +`packages/ui-sdk/src/server/worker-launcher.ts:689-699`). A relayed turn keeps no key. An unrelayed one keeps only its runtime's own inference credential, under the 2026-10-22 ruling that hosts without managed native storage keep today's inference credentials; pi resolves its own credentials there, so it keeps all @@ -1029,7 +1029,7 @@ worker's command starts, the server opens that tmpfs from outside through the sandbox's `/proc//root`. It waits until the path is a tmpfs of exactly the allowance on another device than the server's own `/tmp`, and keeps the descriptor -(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1136-1164`). +(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1150-1178`). Every later read goes through that descriptor, after the worker's namespace is gone as well, and never enters another mount, so runtime state below `/tmp` is never read as turn temp. The allowance (256 MiB by default, @@ -2190,7 +2190,7 @@ a filesystem socket that is visible through the read-only host root: a Docker socket, a session bus, an SSH agent or a host proxy. Each of those is an unrecorded way out, and some reach privileged host effects. The launcher already masks `.git` in restricted workers for exactly this reason -(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:226`). +(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:235`). `governed` and `strict` workers therefore mask the host's runtime and state directories with empty read-only tmpfs mounts. Maintenance workers share the @@ -2208,7 +2208,7 @@ The worker's private `/tmp` and the other host masks remain in place. After the masks, the launcher re-binds only the explicit runtime inputs the worker needs, read-only, with the same resolution the restricted envelope uses -(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1911`): +(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1925`): - the Bun executable; - the backend entry's package, its `node_modules` chains and linked workspace @@ -2232,7 +2232,7 @@ such ancestor with empty tmpfs instead; it never binds that ancestor's real contents. Search permission uses the helper's primary shared group class when that group owns the directory, including when only the other class has execute permission. Existing canonical aliases and nested masks fold into that cover -(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:385-444`). +(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:394-453`). This supports disjoint private-state layouts, including a nested operational database below a server-owned `0700` parent. New ancestor coverage that would @@ -2308,9 +2308,9 @@ and subdirectories through retained aliases. It does not restore unrelated host-temp siblings or make runtime bytes writable. The concrete checks and mounts are in (`validateRuntimePlacement`, -`packages/ui-sdk/src/server/worker-launcher.ts:609-615`), -(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:636-675`) -and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:791-809`). +`packages/ui-sdk/src/server/worker-launcher.ts:618-624`), +(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:645-684`) +and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:800-818`). Alias restoration recognizes names already supplied by a read-only bind or an explicit system-view symlink. It does not mount a canonical executable over an existing alias such as `/bin/sh`; missing owned temporary paths still receive @@ -3341,7 +3341,7 @@ before mounting them: both belong to the server, helper mode uses its primary GID and exact `0750`/`0660` modes, and no-helper mode retains exact `0700`/`0600`. Missing endpoints, aliases, non-sockets, foreign ownership and wider modes refuse before payload execution -(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:250-284`). +(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:259-293`). This compatibility check does not change default autonomous admission or add another route. @@ -3479,11 +3479,11 @@ An ordinary group-shared directory was accessible, but the worker's private mount and namespace links through `/proc/` were denied. Changing the private directory to `0770` did not remove that process-access barrier. The current launcher opens mounts directly (`function openPrivateState`, -`packages/ui-sdk/src/server/worker-launcher.ts:1099-1127`; +`packages/ui-sdk/src/server/worker-launcher.ts:1113-1141`; `function* openPrivateTurnTempSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1136-1162`) before population and +`packages/ui-sdk/src/server/worker-launcher.ts:1150-1176`) before population and start-gate release (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1325-1413`). Group modes and a uid +`packages/ui-sdk/src/server/worker-launcher.ts:1339-1427`). Group modes and a uid switch alone therefore cannot implement the selected cross-uid lifecycle. **Authority and launch.** One trusted external supervisor owns each worker diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 50049fdd26..dc07f25139 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -98,7 +98,7 @@ Each governed or strict turn whose journal is recording opens one worker generation, and every worker of that turn binds the generation's root-owned directory whole at `/tmp/brain-worktrees`, inside the turn's own `/tmp` (`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/run-session.ts:571-583`; -`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:852-863`). +`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:861-872`). A granted worktree appears there as `/tmp/brain-worktrees//` on the worker's next path lookup; the worker cannot create entries beside it, and a restricted worker never binds a generation. Nothing returns a host path to the @@ -212,7 +212,7 @@ nothing. **Shared source is read through views.** Each such turn's workers bind the public view and their principal's private view whole and read-only at `/tmp/brain-reference/public` and `/tmp/brain-reference/private` -(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:864-875`). +(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:873-884`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition (`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:741-753`). diff --git a/docs/decisions/policy-write-boundary.md b/docs/decisions/policy-write-boundary.md index b5d303e104..37a558ead8 100644 --- a/docs/decisions/policy-write-boundary.md +++ b/docs/decisions/policy-write-boundary.md @@ -497,13 +497,13 @@ sessions. before the runtime starts and read it after the worker is gone, while the tmpfs is reachable only inside the worker. The launcher does both from the host (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1325-1581`): +`packages/ui-sdk/src/server/worker-launcher.ts:1339-1595`): 1. It finds the sandbox's first process from the kernel's record of bubblewrap's only child, then opens the tmpfs root through `/proc//root` and keeps that directory descriptor (`function openPrivateState`, - `packages/ui-sdk/src/server/worker-launcher.ts:1099-1123`). bubblewrap's + `packages/ui-sdk/src/server/worker-launcher.ts:1113-1137`). bubblewrap's process exists before its mounts do, so the open is accepted only once the path is its own mount (a device other than its parent's), a tmpfs of exactly the allowance, and empty; until then it would name the host's @@ -513,7 +513,7 @@ host (`function* launchAgentWorkerSteps`, code: the absolute `/bin/sh` reads one line from the worker's stdin with its `read` builtin, which only the server writes, and then becomes the command; closed stdin or any other line ends the worker unstarted - (`const STATE_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:56`). + (`const STATE_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:54`). The gate runs no `PATH` lookup, so nothing in the worker's environment or the brain can stand in for it, and the shell reads a pipe a byte at a time, so the runtime's own input is untouched. The server copies the snapshot in @@ -677,3 +677,78 @@ exported; a server killed mid-turn leaves no worker behind; and the actual Claude runtime's full-state turn ends as `worker_state_exceeded` with its unsaved answer absent from history. A root-run server's copy-in, limit and copy-out were also measured in that container. + +### The start gate fails closed on its holder's death — 2026-11-03 + +Ruling on [#3392](https://github.com/schlessera/brain-kit/issues/3392). It +amends the runtime-state mechanism above (step 4 and the +`--block-fd`/`--info-fd` alternative) and the live launch that moved to +bubblewrap's `--block-fd` with the separate-identity work +([#2069](https://github.com/schlessera/brain-kit/pull/2069)). + +**Decision.** A status-gated live launch no longer uses bubblewrap's +`--block-fd`. The fixed host launch shell still opens the server-held gate FIFO +as fd 4 after the bootstrap's descriptor filter. bubblewrap passes it into the +sandbox, where the trusted absolute `/bin/sh` reads one line from it, requires +exactly `go`, closes fd 4 and only then execs the payload. EOF, a partial line +or any other line ends the sandbox with exit 125. `release()` writes `go\n` +(`const START_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:65`). + +**Why.** bubblewrap proceeds past `--block-fd` on EOF: its sandbox child reads +one byte and ignores the result. That child arms `PR_SET_PDEATHSIG` only after +the read, in its init process and again before exec (source review of +[bubblewrap 0.11.1](https://github.com/containers/bubblewrap/releases/tag/v0.11.1)), +so `--die-with-parent` does not cover the gate window. In the spike's probe +(a rootless container with no network, Bun 1.4.4, bubblewrap 0.11.1), when +the server died between spawn and release, the kernel closed the gate writer and the +unqualified payload ran 25/25 (24/25 with `--die-with-parent`). With the +in-sandbox gate it ran 0/25 in each server-death case: EOF, a lone `g`, and +`go` with no newline. + +Two guards now hold the window. With no `--block-fd` read in the way, the +sandbox's PID 1 arms its parent-death signal before it forks the gate shell, so +a dead server's `--die-with-parent` chain usually ends the namespace first. +Where the gate does read end-of-file (its writer closed while bubblewrap +lives), the gate's own refusal keeps the payload out. #3387's ordering, which +kills a refused launch's sandbox before closing its gate, stays as a further +guard. + +**What changes in the descriptor rule.** The gate descriptor now exists inside +the sandbox, but only in the trusted shell, before any payload process exists. +It is closed before `exec`: the payload's descriptor table has no fd 4. Payload +stdin is still the protocol pipe, byte for byte. The bootstrap still refuses +every unexpected inherited descriptor. The status child PID is bubblewrap's +PID-1 reaper, as it already was after release. + +Step 4 above now reads: if the server dies before release, the gate shell +reads EOF or the namespace is killed with bubblewrap, and the payload never +starts. After release, `--die-with-parent` ends the worker. + +**Alternatives rejected.** + +- *A trusted keeper holding the gate writer:* its own death reopens the hole + (25/25 when killed with the server). It also needs a PID hand-off, and + becomes a broker to close the hand-off gap. +- *`--sync-fd`:* signals sandbox exit outwards. It is not a gate. +- *`--userns-block-fd`:* gates before the mounts exist, needs the server to + write the uid/gid maps, and fails closed only by accident or by hanging. +- *A heartbeat gate:* needs an in-sandbox reader anyway and adds timers. +- *A pre-frozen cgroup:* optional per host, with an unfrozen window from spawn + to freeze. + +**Cost.** One extra shell exec: about 0.5 ms from release to payload start +(p50 1.89 ms against 1.41 ms). + +**Proof.** `packages/ui-sdk/tests/gate-holder-crash.test.ts` runs the real +governed launch in a separate server process, SIGKILLs it during setup and +after setup before release (synchronous and asynchronous launches, and after a +partial or wrong gate line), waits until every process of the launch is dead +and requires no payload marker. Further cases close the gate's writer while the +server lives, so only the gate's refusal of EOF and of a partial line stands +between it and the payload. A released control starts the payload exactly once, +with descriptors 0-2 only and stdin byte-identical. + +**Not covered.** The separate-UID identity helper gates with its own +`--block-fd` pipe. Whether its death fails closed is tracked in +[#3402](https://github.com/schlessera/brain-kit/issues/3402). Post-release +server death is unchanged. diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 773ca521ef..407602e71e 100644 --- a/docs/decisions/worker-writable-areas.md +++ b/docs/decisions/worker-writable-areas.md @@ -81,7 +81,7 @@ on the transcript persist path and is not part of this record. **One resolution, two consumers.** `prepareWorkerSandbox` resolves the areas and per-turn XDG layout once per worker -(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:901-942`). +(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:910-951`). The backend passes the result both to the launcher, which turns it into bubblewrap arguments, and to `workerSandboxNote`, which renders the agent's note (`export function workerSandboxNote`, `packages/ui-sdk/src/server/worker-sandbox.ts:592-657`). @@ -89,7 +89,7 @@ The launcher re-checks the resolved layout against the actual launch: the same brain and envelope, each writable area still a real directory at its own path in the brain. The backend selects runtime HOME separately. A mismatch refuses the launch instead of binding something the note does not -describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:823-853`). +describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:832-862`). A launch without a resolved layout keeps the 0.41 view: only the per-turn scratch is writable. @@ -153,7 +153,7 @@ through the roadblock path. This is a worker write boundary, not an immutable view: host-side changes to that directory remain visible. A backend may select a different runtime HOME as described below; it does not make the host home writable. `prepareWorkerSandbox` resolves this same XDG mode on every eligible host (`export function prepareWorkerSandbox`, -`packages/ui-sdk/src/server/worker-launcher.ts:901-942`). Host-backed overlay +`packages/ui-sdk/src/server/worker-launcher.ts:910-951`). Host-backed overlay uppers cannot live on the worker's private tmpfs; keeping them would leave an unbounded write area. Tools reading XDG config see the per-turn directory, while direct reads of real HOME retain the read-only host view. diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 728269e6f6..07054a8049 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -91,7 +91,7 @@ owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before the payload starts (`if (input.egress)`, -`packages/ui-sdk/src/server/worker-launcher.ts:552-567`). This does not select +`packages/ui-sdk/src/server/worker-launcher.ts:561-576`). This does not select the ordinary inference route or enable the proxy by default. Native output stages use the existing manager's active stage identity. The @@ -1436,18 +1436,24 @@ the keys, unmetered. Worker-host status says which applies. ### Worker startup status The live launcher reads bubblewrap's `--json-status-fd` through a dedicated, -unlinked pipe. Before releasing its `--block-fd` start gate, it checks that -the reported child descends from this launch and runs in a different PID -namespace. Runtime-state and turn-temp mounts are verified and initial state -is populated while that gate is closed. The trusted bootstrap still rejects -unexpected inherited descriptors; a fixed host shell opens only the status -and gate channels afterwards, and bubblewrap closes both before the payload -runs. Setup refusal ends the unstarted worker. bubblewrap starts the payload -on the gate's end-of-file as it does on its go byte, so a refused gate stays -open until bubblewrap and every process it gated are confirmed dead. The +unlinked pipe. Before releasing its start gate, it checks that the reported +child descends from this launch and runs in a different PID namespace. +Runtime-state and turn-temp mounts are verified and initial state is populated +while that gate is closed. The trusted bootstrap still rejects unexpected +inherited descriptors; a fixed host shell opens only the status and gate +channels afterwards. bubblewrap keeps the status channel out of the sandbox. +The gate channel reaches only the trusted absolute `/bin/sh` that runs first +inside it: that shell reads one line, requires exactly `go`, closes the gate +descriptor and only then becomes the payload, so the payload holds neither +channel and its stdin is untouched. End-of-file, a partial line or any other +line ends the sandbox unstarted. So a server that dies before release, which +closes the gate's only writer, never starts the payload. bubblewrap's own +`--block-fd` is not used, because it starts the payload on end-of-file. + +Setup refusal ends the unstarted worker. As a second guard, a refused gate +stays open until bubblewrap and every process it gated are confirmed dead. The refusal stops bubblewrap and kills its children and the verified sandbox -process itself; bubblewrap's own death does not end that process, even with -`--die-with-parent`. A gate whose processes never die stays open. +process itself. A gate whose processes never die stays open. This startup qualification does not provide a separate worker UID or the external descriptor broker. The separate-UID implementation remains tracked diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index f5dd00c464..342401461b 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -48,12 +48,21 @@ const TMPFS_MAGIC = 0x01021994; * reads one server-owned stdin line before becoming the worker command. * Closed stdin or any other line ends the worker unstarted. Only the * absolute shell and its builtins run here, never a PATH lookup. Reads are - * byte-sized, so nothing past the gate line is consumed. Live launches use - * bubblewrap's --block-fd instead: workerBootstrap reopens its trusted gate - * after Bun execve and the inherited-descriptor filter, preserving payload - * stdin and leaving no gate descriptor in the sandbox command. + * byte-sized, so nothing past the gate line is consumed. Live status launches + * use START_GATE on fd 4 instead, preserving payload stdin. */ const STATE_GATE = ["/bin/sh", "-c", 'IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"', "brain-worker-state-gate"]; +/** + * The start gate of every status-gated live launch (#3392). workerBootstrap's + * fixed host shell opens the server-held gate FIFO as fd 4 after Bun execve + * and the inherited-descriptor filter; bubblewrap passes it into the sandbox + * without `--block-fd`, which would proceed on the writer's EOF. This trusted + * absolute shell, before any payload process exists, needs one complete `go` + * line: EOF (a dead server), a partial line or any other line exits 125. It + * closes fd 4 before the payload exec, so the payload holds no gate + * descriptor. Only the shell and its builtins run, never a PATH lookup. + */ +const START_GATE = ["/bin/sh", "-c", 'IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"', "brain-worker-start-gate"]; /** What the server writes to open the gate. */ const STATE_GATE_OPEN = "go\n"; /** How long a launch waits for bubblewrap to report and mount, like the probe's bound. */ @@ -966,13 +975,18 @@ export function workerBootstrap(input: WorkerLaunch, cgroup?: string, status?: { if (![status.source, status.gateSource].every(source => new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(source))) throw new WorkerHostError("invalid trusted worker status source"); const bwrap = argv.indexOf(Bun.which("bwrap")!); if (bwrap < 0) throw new WorkerHostError("worker status requires the trusted bubblewrap launch"); - argv.splice(bwrap + 1, 0, "--json-status-fd", "3", "--block-fd", "4"); - // Every status-qualified launch waits, including commands without state. - // The PID cannot exit/recycle before verification and freezer setup. - if (gated(input)) argv.splice(argv.length - payloadCommand(input).length - STATE_GATE.length, STATE_GATE.length); + argv.splice(bwrap + 1, 0, "--json-status-fd", "3"); + // Every status-qualified launch waits on START_GATE, including commands + // without state, in place of the stdin gate. The PID cannot exit/recycle + // before verification and freezer setup: bubblewrap's reaper outlives + // its blocked gate shell. + const payloadStart = argv.length - payloadCommand(input).length; + if (gated(input)) argv.splice(payloadStart - STATE_GATE.length, STATE_GATE.length, ...START_GATE); + else argv.splice(payloadStart, 0, ...START_GATE); // Bun execve closes descriptors above stdio. Reopen only these host-owned - // FIFOs after the unchanged bootstrap filter. bubblewrap closes both - // descriptors in its sandbox child before any payload can run. + // FIFOs after the unchanged bootstrap filter. bubblewrap keeps the status + // writer out of its sandbox child; the gate reader reaches only + // START_GATE, which closes it before the payload exec. argv = ["/bin/sh", "-c", 'exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"', "brain-worker-status", status.source, status.gateSource, ...argv]; } return { command: [process.execPath, entry], env: { diff --git a/packages/ui-sdk/src/server/worker-status.ts b/packages/ui-sdk/src/server/worker-status.ts index 7697fb5a96..7d864739eb 100644 --- a/packages/ui-sdk/src/server/worker-status.ts +++ b/packages/ui-sdk/src/server/worker-status.ts @@ -148,18 +148,18 @@ export function* createWorkerStatusPipeSteps() { } } return { source, gateSource, - release() { if (gateClosed) throw new Error("Worker start gate is closed"); writeSync(gateWriter!, "g"); closeGate(); }, + release() { if (gateClosed) throw new Error("Worker start gate is closed"); writeSync(gateWriter!, "go\n"); closeGate(); }, childPid(supervisor: number, deadline: number): number { return runWorkerStepsSync(childPidSteps(supervisor, deadline)); }, /** `childPid`, waiting through steps so an asynchronous launch keeps its event loop (#2416). */ childPidSteps, closeWriter() { if (!writerClosed) { writerClosed = true; closeSync(writer!); } }, /** - * Closes the channel. bubblewrap's --block-fd treats the gate's EOF like - * its go byte, so an unreleased gate stays open until the supervisor and - * every process it gated are dead (#3387). Its supervisor is killed for - * that. A gate whose processes never die stays open for good: a held - * descriptor, never a released payload. Only a gate with no supervisor, - * which nothing can have opened, closes at once. + * Closes the channel. The in-sandbox start gate refuses on the gate's + * EOF (#3392). As a second guard, an unreleased gate still stays open + * until the supervisor and every process it gated are dead (#3387). Its + * supervisor is killed for that. A gate whose processes never die stays + * open for good: a held descriptor, never a released payload. Only a + * gate with no supervisor, which nothing can have opened, closes at once. */ close(supervisor?: WorkerStatusSupervisor) { if (closed) return; diff --git a/packages/ui-sdk/tests/fixtures/gate-holder-crash-server.ts b/packages/ui-sdk/tests/fixtures/gate-holder-crash-server.ts new file mode 100644 index 0000000000..80a6fae0ea --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/gate-holder-crash-server.ts @@ -0,0 +1,91 @@ +// A "server" for gate-holder-crash.test.ts (#3392). It runs the real +// status-gated governed launch and stops, holding the start gate's only +// writer, at one point before the gate is released. It prints `armed` with +// its launch's processes there (bubblewrap's tree, taken before any gate +// write) and blocks until the test SIGKILLs it. +// +// bun gate-holder-crash-server.ts setup +// blocks inside populateState: the state is mounted, folder +// qualification has not run. +// bun gate-holder-crash-server.ts release[-async] [eof] +// blocks inside release(), after every setup step, having written +// (a JSON string, possibly empty) into the gate. With `eof` +// it then closes every gate writer it holds while it lives on, so the +// gate reads end-of-file with no parent-death cascade behind it. +import { spyOn } from "bun:test"; +import { closeSync, constants, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, writeFileSync, writeSync } from "node:fs"; +import { join } from "node:path"; +import * as status from "../../src/server/worker-status.js"; + +const [brain, mode, token, eof] = process.argv.slice(2) as [string, string, string | undefined, string | undefined]; +const TOKEN_SETTLE_MS = 300; + +let supervisor: number | undefined; +let processes: Array<{ pid: number; start: string }> = []; +/** A process and all its descendants, by PID and start time. */ +function tree(pid: number): Array<{ pid: number; start: string }> { + let start: string | undefined, children: number[] = []; + try { + start = readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19]; + children = readdirSync(`/proc/${pid}/task`).flatMap(task => + readFileSync(`/proc/${pid}/task/${task}/children`, "utf8").trim().split(/\s+/).filter(Boolean).map(Number)); + } catch { /* exited meanwhile */ } + return start === undefined ? [] : [{ pid, start }, ...children.flatMap(tree)]; +} +function snapshot() { + if (supervisor === undefined) throw new Error("no supervisor was spawned"); + processes = tree(supervisor); +} +function armed(): never { + writeSync(1, `${JSON.stringify({ armed: true, launch: processes })}\n`); + for (;;) Bun.sleepSync(60_000); +} + +const spawn = Bun.spawn; +spyOn(Bun, "spawn").mockImplementation(((...args: Parameters) => { + const child = (spawn as (...a: unknown[]) => ReturnType)(...args); + if (supervisor === undefined && (args[1] as { env?: Record } | undefined)?.env?.BRAIN_WORKER_LAUNCH) supervisor = child.pid; + return child; +}) as typeof Bun.spawn); + +const create = status.createWorkerStatusPipeSteps; +spyOn(status, "createWorkerStatusPipeSteps").mockImplementation(function* () { + const channel = yield* create(); + if (mode.startsWith("release")) channel.release = () => { + snapshot(); + const written = JSON.parse(token ?? '""') as string; + if (written) { + // A second writer on the same unlinked FIFO; it dies with this process too. + const gate = openSync(channel.gateSource, constants.O_WRONLY); + writeSync(gate, written); + closeSync(gate); + } + if (eof === "eof") { + // The channel's own writer: the same FIFO as the gate source, open for writing. + const gate = readlinkSync(channel.gateSource); + for (const fd of readdirSync("/proc/self/fd").map(Number)) { + try { + if (readlinkSync(`/proc/self/fd/${fd}`) === gate && (parseInt(/^flags:\s*([0-7]+)/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`, "utf8"))![1]!, 8) & 3) === constants.O_WRONLY) closeSync(fd); + } catch { /* the listing's own descriptor */ } + } + } + // Time for a gate that wrongly accepts this to start the payload while + // its server still lives, rather than racing --die-with-parent. + if (written || eof === "eof") Bun.sleepSync(TOKEN_SETTLE_MS); + armed(); + }; + return channel; +} as typeof create); + +const { launchAgentWorker, launchAgentWorkerAsync, prepareWorkerSandbox } = await import("../../src/server/worker-launcher.js"); +mkdirSync(join(brain, "context/policies"), { recursive: true }); +writeFileSync(join(brain, "context/policies/governance.md"), "Athena sets the policy.\n"); +mkdirSync(join(brain, "group/private"), { recursive: true }); +const sandbox = prepareWorkerSandbox(brain, { profile: "governed", areas: [], folderPaths: ["group/private"] }); +if (sandbox.profile !== "governed") throw new Error(`governed sandbox unavailable: ${sandbox.fallbackReason}`); +const launch = { brainPath: brain, sandbox, env: {}, stateBytes: 1024 * 1024, + ...(mode === "setup" ? { populateState: () => { snapshot(); armed(); } } : {}), + command: ["/bin/sh", "-c", "printf Odysseus >> payload-started.md"] }; +if (mode === "release-async") await launchAgentWorkerAsync(launch); +else launchAgentWorker(launch); +throw new Error("the launch released its gate"); diff --git a/packages/ui-sdk/tests/gate-holder-crash.test.ts b/packages/ui-sdk/tests/gate-holder-crash.test.ts new file mode 100644 index 0000000000..8184ec9f14 --- /dev/null +++ b/packages/ui-sdk/tests/gate-holder-crash.test.ts @@ -0,0 +1,121 @@ +import { afterEach, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { launchAgentWorker, prepareWorkerSandbox } from "../src/server/worker-launcher.js"; + +// The start gate's only writer belongs to the server. When the server dies +// before release, the kernel closes that writer; the gated payload must still +// never start (#3392). Each case runs the real status-gated governed launch +// in a separate "server" process, waits for it to stop before release with an +// authenticated sandbox, SIGKILLs it, and waits until every process of the +// launch is dead before looking for the payload's marker. +const SERVER = join(import.meta.dir, "fixtures/gate-holder-crash-server.ts"); +const DEATH_MS = 10_000; + +const roots: string[] = []; +const owned: Array<{ pid: number; start: string }> = []; +afterEach(() => { + for (const process_ of owned.splice(0)) if (alive(process_)) try { process.kill(process_.pid, "SIGKILL"); } catch { /* gone */ } + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +function stat(pid: number): string[] | undefined { + try { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" "); } catch { return undefined; } +} +function alive(target: { pid: number; start: string }): boolean { + const fields = stat(target.pid); + return fields !== undefined && fields[19] === target.start && !["Z", "X", "x"].includes(fields[0]!); +} +async function readLine(stream: ReadableStream, deadline: number): Promise { + const reader = stream.getReader(); + let text = ""; + try { + while (!text.includes("\n")) { + const next = await Promise.race([reader.read(), Bun.sleep(Math.max(0, deadline - Date.now())).then(() => "timeout" as const)]); + if (next === "timeout") throw new Error("the server did not arm in time"); + if (next.done) break; + text += new TextDecoder().decode(next.value); + } + } finally { reader.releaseLock(); } + return text.split("\n")[0]!; +} + +async function crashBeforeRelease(mode: string, token?: string, eof?: "eof"): Promise<{ brain: string; launch: number }> { + const brain = mkdtempSync(join(tmpdir(), "gate-holder-crash-")); roots.push(brain); + const server = Bun.spawn([process.execPath, SERVER, brain, mode, ...token === undefined ? [] : [JSON.stringify(token)], ...eof ? [eof] : []], + { env: { ...process.env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + owned.push({ pid: server.pid, start: stat(server.pid)?.[19] ?? "" }); + const line = await readLine(server.stdout, Date.now() + 15_000).catch(async error => { + server.kill("SIGKILL"); await server.exited; + throw new Error(`${String(error)}: ${await new Response(server.stderr).text()}`); + }); + // The launch's processes before any gate write: bubblewrap and its + // sandbox's PID 1, which outlives the gate shell it forks. + const { armed, launch } = JSON.parse(line) as { armed: boolean; launch: Array<{ pid: number; start: string }> }; + expect(armed).toBe(true); + expect(launch.length, "the launch's sandbox was waiting at its gate").toBeGreaterThanOrEqual(2); + owned.push(...launch); + server.kill("SIGKILL"); + await server.exited; + expect(server.signalCode, "the gate holder died by SIGKILL").toBe("SIGKILL"); + const deadline = Date.now() + DEATH_MS; + while (launch.some(alive) && Date.now() < deadline) await Bun.sleep(5); + expect(launch.filter(alive), "every process of the launch ended after the holder's death").toEqual([]); + return { brain, launch: launch.length }; +} + +test("a gate holder killed during setup never starts the payload", async () => { + const { brain } = await crashBeforeRelease("setup"); + expect(existsSync(join(brain, "payload-started.md")), "HOLDER_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +test("a gate holder killed after setup, before release, never starts the payload", async () => { + const { brain } = await crashBeforeRelease("release"); + expect(existsSync(join(brain, "payload-started.md")), "HOLDER_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +test("an asynchronous launch's gate holder killed before release never starts the payload", async () => { + const { brain } = await crashBeforeRelease("release-async"); + expect(existsSync(join(brain, "payload-started.md")), "HOLDER_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +for (const [token, name] of [["g", "PARTIAL_BYTE"], ["go", "PARTIAL_LINE"], ["goo\n", "WRONG_LINE"], ["Go\n", "WRONG_CASE"]] as const) { + test(`a gate written ${JSON.stringify(token)}, then its holder's death, never starts the payload`, async () => { + const { brain } = await crashBeforeRelease("release", token); + expect(existsSync(join(brain, "payload-started.md")), `${name}_PAYLOAD_NEVER_STARTS`).toBe(false); + }, 30_000); +} + +// A dead server also kills bubblewrap (--die-with-parent) and with it the +// sandbox's PID namespace, often before the gate shell runs again. These +// cases close the gate's writer while the server lives, so only the gate's +// own refusal of end-of-file and of an incomplete line keeps the payload out. +for (const [token, name] of [["", "WRITER_EOF"], ["g", "WRITER_EOF_AFTER_BYTE"], ["go", "WRITER_EOF_AFTER_PARTIAL_LINE"]] as const) { + test(`a gate whose writer closes after ${JSON.stringify(token)} never starts the payload`, async () => { + const { brain } = await crashBeforeRelease("release", token, "eof"); + expect(existsSync(join(brain, "payload-started.md")), `${name}_PAYLOAD_NEVER_STARTS`).toBe(false); + }, 30_000); +} + +test("a released gate starts the payload once, with no gate descriptor and its stdin intact", async () => { + const brain = mkdtempSync(join(tmpdir(), "gate-holder-crash-")); roots.push(brain); + mkdirSync(join(brain, "context/policies"), { recursive: true }); + writeFileSync(join(brain, "context/policies/governance.md"), "Athena sets the policy.\n"); + mkdirSync(join(brain, "group/private"), { recursive: true }); + const sandbox = prepareWorkerSandbox(brain, { profile: "governed", areas: [], folderPaths: ["group/private"] }); + expect(sandbox.profile, sandbox.fallbackReason).toBe("governed"); + // The payload's own descriptor table, listed by an external `ls` with no + // redirection, which would make dash save a descriptor of its own. + const worker = launchAgentWorker({ brainPath: brain, sandbox, env: {}, stateBytes: 1024 * 1024, + command: ["/bin/sh", "-c", 'ls /proc/$$/fd; printf Odysseus >> payload-started.md; cat > payload-stdin.md'] }); + // A gate line and bytes a line reader would stop at, all for the payload. + const input = Buffer.concat([Buffer.from("go\nPenelope weaves\n"), Buffer.from([0x00, 0xff, 0x0a]), Buffer.from("Ithaca")]); + worker.stdin.end(input); + const drain = async (stream: NodeJS.ReadableStream) => { let text = ""; for await (const chunk of stream) text += String(chunk); return text; }; + const [exit, out, err] = await Promise.all([worker.exited, drain(worker.stdout), drain(worker.stderr)]); + expect(exit, out + err).toBe(0); + expect(readFileSync(join(brain, "payload-started.md"), "utf8"), "RELEASED_PAYLOAD_STARTS_ONCE").toBe("Odysseus"); + expect(out.trim().split("\n"), "PAYLOAD_HOLDS_NO_GATE_DESCRIPTOR").toEqual(["0", "1", "2"]); + expect(readFileSync(join(brain, "payload-stdin.md")).equals(input), "PAYLOAD_STDIN_BYTE_IDENTICAL").toBe(true); +}, 30_000); diff --git a/packages/ui-sdk/tests/refused-launch-gate.test.ts b/packages/ui-sdk/tests/refused-launch-gate.test.ts index c11a7724da..f0e23b12e6 100644 --- a/packages/ui-sdk/tests/refused-launch-gate.test.ts +++ b/packages/ui-sdk/tests/refused-launch-gate.test.ts @@ -10,6 +10,9 @@ import { createWorkerStatusPipe, type WorkerStatusSupervisor } from "../src/serv // (#3387). Each case delays every kill, of bubblewrap and, for longer, of any // process signalled by PID, standing in for processes the scheduler has not // yet let die. Only a gate that waits for their deaths keeps the payload out. +// The live launch now gates in the sandbox and refuses EOF itself (#3392); the +// fixtures below keep bubblewrap's EOF-opening --block-fd on purpose, so they +// prove this ordering as a guard of its own. const SIGNAL_DELAY_MS = 200; const PID_SIGNAL_DELAY_MS = 2 * SIGNAL_DELAY_MS;