From 33325124bb5875c64166c70cd1f2703c38fdc418 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 11:14:11 +0000 Subject: [PATCH] fix(ui-sdk): keep a separate-identity payload out when its coordinator dies before release A separate-UID launch was gated only by bubblewrap's --block-fd on a pipe whose sole writer is the same-UID identity coordinator. bubblewrap starts the sandbox on that pipe's end-of-file, so a coordinator SIGKILLed after spawn and before release (alone, or together with the server) started the unqualified payload. Every separate-identity payload now runs behind STATE_GATE, the trusted absolute /bin/sh that needs one complete `go` line on stdin and refuses end-of-file or anything else. The server writes that line only after the coordinator confirms its release. The live launch and the synchronous host probe both do this. The identity helper protocol is unchanged: it requires --block-fd and never constrains the command after `--`. Adds a same-UID stand-in helper and a crash suite that runs the real launcher and coordinator. Records the ruling in policy-write-boundary.md and the host protocol doc, and moves the worker-launcher citations the edit shifted. Closes #3402 Co-Authored-By: Claude Opus 5.5 --- .changeset/identity-gate-holder-death.md | 5 + docs/decisions/container-fresh-proc.md | 6 +- docs/decisions/governed-writable-workers.md | 24 ++-- docs/decisions/managed-worktrees.md | 4 +- docs/decisions/policy-write-boundary.md | 64 ++++++++- docs/decisions/worker-writable-areas.md | 6 +- docs/hosting/agent-workers.md | 12 +- packages/ui-sdk/src/server/worker-launcher.ts | 27 +++- .../tests/fixtures/identity-gate-helper.py | 95 ++++++++++++++ .../identity-gate-holder-crash-server.ts | 88 +++++++++++++ .../tests/identity-gate-holder-crash.test.ts | 121 ++++++++++++++++++ 11 files changed, 421 insertions(+), 31 deletions(-) create mode 100644 .changeset/identity-gate-holder-death.md create mode 100755 packages/ui-sdk/tests/fixtures/identity-gate-helper.py create mode 100644 packages/ui-sdk/tests/fixtures/identity-gate-holder-crash-server.ts create mode 100644 packages/ui-sdk/tests/identity-gate-holder-crash.test.ts diff --git a/.changeset/identity-gate-holder-death.md b/.changeset/identity-gate-holder-death.md new file mode 100644 index 0000000000..bbe6564ab1 --- /dev/null +++ b/.changeset/identity-gate-holder-death.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-sdk": patch +--- + +A separate-UID worker launch whose identity coordinator dies before releasing the start gate no longer starts its payload (#3402). The coordinator's gate is bubblewrap's `--block-fd`, which starts the sandbox on end-of-file. Every separate-identity payload now also waits behind the trusted stdin gate, a complete `go` line that the server writes only after the coordinator confirms the release. The identity helper protocol is unchanged, and payload stdin after the gate line is byte-identical. diff --git a/docs/decisions/container-fresh-proc.md b/docs/decisions/container-fresh-proc.md index bc5341256d..ca0a773b7b 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:518-698`). +and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:539-719`). 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:1650`). + (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1696`). 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:343-345`). +uid is 0 (`rootProcCover`, `packages/ui-sdk/src/server/worker-launcher.ts:360-362`). 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 9c25a99843..910a4939fe 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -625,7 +625,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:689-699`). A relayed turn keeps no +`packages/ui-sdk/src/server/worker-launcher.ts:708-718`). 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 @@ -1070,7 +1070,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:1150-1178`). +(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1175-1203`). 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, @@ -2270,7 +2270,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:235`). +(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:252`). `governed` and `strict` workers therefore mask the host's runtime and state directories with empty read-only tmpfs mounts. Maintenance workers share the @@ -2288,7 +2288,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:1925`): +(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1972`): - the Bun executable; - the backend entry's package, its `node_modules` chains and linked workspace @@ -2312,7 +2312,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:394-453`). +(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:411-470`). This supports disjoint private-state layouts, including a nested operational database below a server-owned `0700` parent. New ancestor coverage that would @@ -2388,9 +2388,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: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`). +`packages/ui-sdk/src/server/worker-launcher.ts:637-643`), +(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:664-703`) +and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:665-683`). 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 @@ -3422,7 +3422,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:259-293`). +(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:276-310`). This compatibility check does not change default autonomous admission or add another route. @@ -3560,11 +3560,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:1113-1141`; +`packages/ui-sdk/src/server/worker-launcher.ts:1138-1166`; `function* openPrivateTurnTempSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1150-1176`) before population and +`packages/ui-sdk/src/server/worker-launcher.ts:1175-1201`) before population and start-gate release (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1339-1427`). Group modes and a uid +`packages/ui-sdk/src/server/worker-launcher.ts:1364-1452`). 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 c5af5d30b2..2dfea0817e 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/session-run/admission.ts:191-203`; -`// 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:886-897`). 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:873-884`). +(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). 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:745-776`). diff --git a/docs/decisions/policy-write-boundary.md b/docs/decisions/policy-write-boundary.md index a2dc882b98..268ea6bd5e 100644 --- a/docs/decisions/policy-write-boundary.md +++ b/docs/decisions/policy-write-boundary.md @@ -507,13 +507,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:1339-1595`): +`packages/ui-sdk/src/server/worker-launcher.ts:1364-1622`): 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:1113-1137`). bubblewrap's + `packages/ui-sdk/src/server/worker-launcher.ts:1138-1162`). 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 @@ -523,7 +523,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:54`). + (`const STATE_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:58`). 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 @@ -702,7 +702,7 @@ 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`). +(`const START_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:69`). **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 @@ -760,5 +760,57 @@ 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. +[#3402](https://github.com/schlessera/brain-kit/issues/3402), and the next +section rules on it. Post-release server death is unchanged. + +### The identity helper's start gate fails closed too — 2026-11-03 + +Ruling on [#3402](https://github.com/schlessera/brain-kit/issues/3402), applying +the decision above to the separate-UID launch. + +**The hole.** A separate-identity launch does not use the server's fd 4 gate. +Its same-UID coordinator (`WORKER_IDENTITY_SUPERVISOR`) holds the only writer +of its own gate pipe. The helper protocol puts that pipe on bubblewrap's +`--block-fd` and the helper refuses a launch without it +([the host protocol](../hosting/agent-workers.md#separate-worker-identity)). +The launcher also removed `STATE_GATE` from these payloads. So the payload's +only gate was `--block-fd`, which opens on end-of-file. Probed on a Linux host +with bubblewrap 0.11.1, using the real launcher and coordinator against a +same-UID stand-in helper: a coordinator SIGKILLed after spawn and before +release started the payload, both during setup and after it, for synchronous +and asynchronous launches. A server and coordinator killed together also +started the payload. The helper's parent-death signal kills the outer +bubblewrap but not its sandbox child, as above. + +**Decision.** Every separate-identity payload now runs behind `STATE_GATE`, the +trusted absolute `/bin/sh` that reads one complete `go` line from stdin and +refuses end-of-file or anything else with exit 125 +(`function identityStartGate`, +`packages/ui-sdk/src/server/worker-launcher.ts:80`). That covers launches with +and without runtime state. The server writes that line only after the +coordinator has confirmed its release, and it holds stdin's only writer. So the +payload starts only when both holders have authorised it. If either dies before +release, the payload stays out. If only the coordinator dies, `--block-fd` +opens, but the gate shell still waits on the server, which never writes the +line. The synchronous host probe's identity path does the same. + +**Why stdin and not the fd 4 gate.** The fd 4 gate needs bubblewrap to run +without `--block-fd` and a descriptor that survives into the sandbox. The +helper protocol is a published contract: it requires `--block-fd`, and the +helper closes every other descriptor before it execs bubblewrap. Changing that +would break every installed helper. The protocol never constrains the command +after `--`, so a stdin gate there needs no helper change. This is the original +runtime-state gate (step 2 above), and it reads a byte at a time, so payload +stdin after the gate line is unchanged. + +**Proof.** `packages/ui-sdk/tests/identity-gate-holder-crash.test.ts` runs the +real launcher and coordinator in a separate server process, against +`tests/fixtures/identity-gate-helper.py`. That fixture implements the launch, +mount, signal and cleanup operations as the server's own UID. It SIGKILLs the +coordinator during setup, after setup before release (synchronous, +asynchronous and without runtime state), and together with the server. It also +kills the server alone. Each case waits until every process of the launch is +dead and requires no payload marker. The released control starts the payload +once, with descriptors 0-2 only and stdin byte-identical. The stand-in drops no +identity: the cross-UID behaviour stays proven by the disposable-container +qualification. diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index a164f6e208..1289a3a9dc 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:910-951`). +(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:935-976`). 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:832-862`). +describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:857-887`). 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:910-951`). Host-backed overlay +`packages/ui-sdk/src/server/worker-launcher.ts:935-976`). 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 1495b92420..0859656e47 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -60,6 +60,16 @@ fixed worker-UID raw reading and owned cleanup. SCM_RIGHTS transfers only explic descriptors; unexpected handles, substituted roots, wrong filesystem/size, malformed status, stale identities and unrelated targets refuse. +The coordinator's gate pipe is not the payload's only gate. bubblewrap starts +its sandbox when that pipe reads end-of-file, which happens when the +coordinator dies. So every separate-identity payload also runs behind the +trusted stdin gate: an absolute `/bin/sh` that needs one complete `go` line +before it becomes the command. The server writes that line only after the +coordinator confirms the release. A coordinator or server that dies before +release never starts the payload. Helpers see no protocol change, because the +gate is part of the command after `--` +([the ruling](../decisions/policy-write-boundary.md#the-identity-helpers-start-gate-fails-closed-too--2026-11-03)). + Before releasing bubblewrap's private start gate, the coordinator retains verified runtime-state and turn-temp directory handles. Their tmpfs superblocks must represent both outside UIDs: creating them in a user @@ -91,7 +101,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:561-576`). This does not select +`packages/ui-sdk/src/server/worker-launcher.ts:580-595`). 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 diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index 3f8da70b26..de3aaf75f6 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -50,7 +50,10 @@ const TMPFS_MAGIC = 0x01021994; * 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 status launches - * use START_GATE on fd 4 instead, preserving payload stdin. + * use START_GATE on fd 4 instead, preserving payload stdin. Every + * separate-identity launch keeps this gate behind its coordinator's + * --block-fd, which opens on the coordinator's death (#3402): see + * `identityStartGate`. */ const STATE_GATE = ["/bin/sh", "-c", 'IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"', "brain-worker-state-gate"]; /** @@ -64,6 +67,19 @@ const STATE_GATE = ["/bin/sh", "-c", 'IFS= read -r go && [ "$go" = go ] || exit * 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"]; +/** + * A separate-identity payload's own start gate (#3402). The helper protocol + * gates bubblewrap with `--block-fd` on a pipe whose only writer is the + * same-UID coordinator, and bubblewrap starts the sandbox on that pipe's + * end-of-file, so a coordinator that dies before release would start the + * payload. STATE_GATE in front of every such payload needs one complete `go` + * line on stdin as well, which only the server writes, and only after the + * coordinator has confirmed its release. The helper protocol is unchanged: it + * never constrains the command after `--`. + */ +function identityStartGate(argv: string[], payload: readonly string[], input: Pick): void { + if (!gated(input)) argv.splice(argv.length - payload.length, 0, ...STATE_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. */ @@ -1427,7 +1443,7 @@ export function* launchAgentWorkerSteps(input: WorkerLaunch): WorkerSteps("status"); if (result.failure) throw new WorkerHostError(`worker_identity_supervision_failed: ${result.failure}`); diff --git a/packages/ui-sdk/tests/fixtures/identity-gate-helper.py b/packages/ui-sdk/tests/fixtures/identity-gate-helper.py new file mode 100755 index 0000000000..6091ef98f3 --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/identity-gate-helper.py @@ -0,0 +1,95 @@ +#!/usr/bin/python3 -I +"""Same-UID stand-in for the identity helper, for identity-gate-holder-crash.test.ts (#3402). + +It speaks the --brain-worker-identity-v1 operations the real coordinator +(WORKER_IDENTITY_SUPERVISOR) uses for a launch, so that coordinator and the +real launcher run unchanged on a host without root. Like the qualified helper +it refuses a launch without --json-status-fd/--block-fd pipes, --die-with-parent +or --unshare-pid, arms its parent-death signal and execs bubblewrap with only +stdio and those two descriptors. It drops no identity: the separate UID is +proven by the disposable-container qualification, not here. +""" +import array, ctypes, json, os, signal, socket, stat, sys + +MAX_PACKET = 65536 +libc = ctypes.CDLL(None, use_errno=True) + + +def receive(connection): + data, controls, flags, _ = connection.recvmsg(MAX_PACKET + 1, socket.CMSG_SPACE(16 * 4)) + fds = [] + for level, kind, value in controls: + values = array.array("i") + values.frombytes(value[:len(value) - len(value) % values.itemsize]) + fds.extend(values) + if controls and any(level != socket.SOL_SOCKET or kind != socket.SCM_RIGHTS for level, kind, _ in controls): + raise RuntimeError("unexpected_control") + if flags & (socket.MSG_TRUNC | socket.MSG_CTRUNC): + raise RuntimeError("packet_bound") + return json.loads(data), fds + + +def send(connection, payload, fds=()): + control = [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))] if fds else [] + connection.sendmsg([json.dumps(dict(ok=True, **payload)).encode()], control) + + +def children(pid): + found = [] + try: + for task in os.listdir("/proc/%d/task" % pid): + with open("/proc/%d/task/%s/children" % (pid, task)) as stream: + found.extend(int(value) for value in stream.read().split()) + except (FileNotFoundError, ProcessLookupError): + pass + return found + + +def tree(pid): + return [pid] + [each for child in children(pid) for each in tree(child)] + + +operation, connection = sys.argv[2], socket.socket(fileno=int(sys.argv[3])) +request, fds = receive(connection) +supervisor = request["supervisor"]["pid"] +if operation == "launch": + argv = request["argv"] + options = argv[:argv.index("--")] + for key, flag in (("statusFd", "--json-status-fd"), ("gateFd", "--block-fd")): + fd = request[key] + if options.count(flag) != 1 or options[options.index(flag) + 1] != str(fd) or not stat.S_ISFIFO(os.fstat(fd).st_mode): + raise RuntimeError("status_gate") + if "--die-with-parent" not in options or "--unshare-pid" not in options: + raise RuntimeError("missing_lifecycle_boundary") + send(connection, {}) + connection.close() + parent = os.getppid() + if libc.prctl(1, signal.SIGKILL, 0, 0, 0) or os.getppid() != parent: + raise RuntimeError("supervisor_lost_at_launch") + allowed = {0, 1, 2, request["statusFd"], request["gateFd"]} + for name in os.listdir("/proc/self/fd"): + if int(name) not in allowed: + try: os.close(int(name)) + except OSError: pass + os.execve("/usr/bin/env", ["env", "--default-signal", *argv], {}) +elif operation == "mounts": + worker = request["worker"]["pid"] + receipts, handles = [], [] + for root in request["roots"]: + fd = os.open("/proc/%d/root%s" % (worker, root["path"]), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(fd) + receipts.append({"name": root["name"], "bytes": root["bytes"], "dev": info.st_dev, "ino": info.st_ino}) + handles.append(fd) + # Any UID but the server's: this stand-in does not change identity. + send(connection, {"workerUid": os.getuid() + 1, "roots": receipts}, handles) +elif operation == "signal": + number = getattr(signal, "SIG" + request["signal"]) + for pid in tree(supervisor): + if pid not in (supervisor, os.getpid()): + try: os.kill(pid, number) + except ProcessLookupError: pass + send(connection, {"complete": True}) +elif operation == "cleanup": + send(connection, {"complete": True}) +else: + raise RuntimeError("unsupported_operation") diff --git a/packages/ui-sdk/tests/fixtures/identity-gate-holder-crash-server.ts b/packages/ui-sdk/tests/fixtures/identity-gate-holder-crash-server.ts new file mode 100644 index 0000000000..e83211f11f --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/identity-gate-holder-crash-server.ts @@ -0,0 +1,88 @@ +// A "server" for identity-gate-holder-crash.test.ts (#3402). It runs the +// real separate-identity launch, whose coordinator holds bubblewrap's +// --block-fd gate writer, against a same-UID stand-in helper, and stops at +// one point before release. It prints `armed` with the coordinator's PID and +// the launch's processes there, and blocks until the test kills it. +// +// bun identity-gate-holder-crash-server.ts setup +// blocks inside populateState: the state is mounted and verified. +// bun identity-gate-holder-crash-server.ts release[-async|-stateless] +// blocks in place of the coordinator's release, after every setup step. +// bun identity-gate-holder-crash-server.ts run +// the released control: the payload lists its descriptors and copies its +// stdin; prints the exit code and output once it has ended. +import { spyOn } from "bun:test"; +import { mkdirSync, readdirSync, readFileSync, writeFileSync, writeSync } from "node:fs"; +import { join } from "node:path"; +import * as identity from "../../src/server/worker-identity.js"; +import type { WorkerSteps } from "../../src/server/worker-steps.js"; + +const [brain, mode] = process.argv.slice(2) as [string, string]; +const HELPER = join(import.meta.dir, "identity-gate-helper.py"); + +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 armed(): never { + if (supervisor === undefined) throw new Error("no coordinator was spawned"); + processes = tree(supervisor); + writeSync(1, `${JSON.stringify({ armed: true, supervisor: processes[0], 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); + +// The host's trusted helper is root-owned; this stand-in is selected directly. +spyOn(identity, "workerIdentityHelper").mockReturnValue(HELPER); +const prepare = identity.prepareWorkerIdentity; +spyOn(identity, "prepareWorkerIdentity").mockImplementation(((...args: Parameters) => { + const broker = prepare(...args); + const requestSteps = broker.requestSteps; + if (mode.startsWith("release")) broker.requestSteps = function* (operation: string, input?: object): WorkerSteps { + if (operation === "release") armed(); + return yield* requestSteps(operation, input); + } as typeof requestSteps; + return broker; +}) as typeof prepare); + +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"); +const sandbox = prepareWorkerSandbox(brain, { profile: "governed", areas: [] }); +if (sandbox.profile !== "governed") throw new Error(`governed sandbox unavailable: ${sandbox.fallbackReason}`); +if (mode === "run") { + // 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. + worker.stdin.end(Buffer.concat([Buffer.from("go\nPenelope weaves\n"), Buffer.from([0x00, 0xff, 0x0a]), Buffer.from("Ithaca")])); + const drain = async (stream: NodeJS.ReadableStream) => { let text = ""; for await (const chunk of stream) text += String(chunk); return text; }; + const output = Promise.all([drain(worker.stdout), drain(worker.stderr)]); + const exit = await worker.exited; + // The coordinator shares the streams and ends once the last handle is released. + worker.state?.close(); + const [out, err] = await output; + writeSync(1, `${JSON.stringify({ exit, out, err })}\n`); + process.exit(0); +} +// `release-stateless` launches without runtime state, so no stdin gate is in its argv already. +const launch = { brainPath: brain, sandbox, env: {}, ...(mode === "release-stateless" ? {} : { stateBytes: 1024 * 1024 }), + ...(mode === "setup" ? { populateState: () => 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/identity-gate-holder-crash.test.ts b/packages/ui-sdk/tests/identity-gate-holder-crash.test.ts new file mode 100644 index 0000000000..c058a47b04 --- /dev/null +++ b/packages/ui-sdk/tests/identity-gate-holder-crash.test.ts @@ -0,0 +1,121 @@ +import { afterEach, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// A separate-identity launch is gated by its coordinator, which holds +// bubblewrap's --block-fd writer. bubblewrap starts the sandbox on that +// gate's end-of-file, so a coordinator that died before release let the +// payload run (#3402). Each case runs the real launcher and coordinator in a +// separate "server" process, against a same-UID stand-in helper, stops before +// release, kills the gate holders, and waits until every process of the +// launch is dead before looking for the payload's marker. +const SERVER = join(import.meta.dir, "fixtures/identity-gate-holder-crash-server.ts"); +const DEATH_MS = 10_000; +/** Time for a gate that wrongly opens to start the payload while the server still lives. */ +const SETTLE_MS = 500; + +type Identity = { pid: number; start: string }; +const roots: string[] = []; +const owned: Identity[] = []; +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: Identity): 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]!; +} +function server(brain: string, mode: string) { + const child = Bun.spawn([process.execPath, SERVER, brain, mode], { env: { ...process.env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + owned.push({ pid: child.pid, start: stat(child.pid)?.[19] ?? "" }); + return child; +} + +/** Kill `victims` ("coordinator", "server" or both) before release; return the brain once the launch is dead. */ +async function crashBeforeRelease(mode: string, victims: ReadonlyArray<"coordinator" | "server">): Promise { + const brain = mkdtempSync(join(tmpdir(), "identity-gate-holder-crash-")); roots.push(brain); + const child = server(brain, mode); + const line = await readLine(child.stdout, Date.now() + 15_000).catch(async error => { + child.kill("SIGKILL"); await child.exited; + throw new Error(`${String(error)}: ${await new Response(child.stderr).text()}`); + }); + // The coordinator, bubblewrap and its sandbox's PID 1, before any gate write. + const { armed, supervisor, launch } = JSON.parse(line) as { armed: boolean; supervisor: Identity; launch: Identity[] }; + expect(armed).toBe(true); + expect(launch.length, "the launch's sandbox was waiting at its gate").toBeGreaterThanOrEqual(3); + owned.push(...launch); + if (victims.includes("coordinator")) process.kill(supervisor.pid, "SIGKILL"); + if (victims.includes("server")) child.kill("SIGKILL"); + if (!victims.includes("server")) { + // The server still holds every writer it owns, as a live server would. + await Bun.sleep(SETTLE_MS); + child.kill("SIGKILL"); + } + await child.exited; + expect(child.signalCode, "the server 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 holders' death").toEqual([]); + return brain; +} + +test("a coordinator killed during setup never starts the payload", async () => { + const brain = await crashBeforeRelease("setup", ["coordinator"]); + expect(existsSync(join(brain, "payload-started.md")), "COORDINATOR_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +test("a coordinator killed after setup, before release, never starts the payload", async () => { + const brain = await crashBeforeRelease("release", ["coordinator"]); + expect(existsSync(join(brain, "payload-started.md")), "COORDINATOR_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +test("an asynchronous launch's coordinator killed before release never starts the payload", async () => { + const brain = await crashBeforeRelease("release-async", ["coordinator"]); + expect(existsSync(join(brain, "payload-started.md")), "COORDINATOR_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +test("a stateless launch's coordinator killed before release never starts the payload", async () => { + const brain = await crashBeforeRelease("release-stateless", ["coordinator"]); + expect(existsSync(join(brain, "payload-started.md")), "STATELESS_COORDINATOR_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +test("a server and coordinator killed together before release never start the payload", async () => { + const brain = await crashBeforeRelease("release", ["coordinator", "server"]); + expect(existsSync(join(brain, "payload-started.md")), "HOLDERS_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +test("a server killed before release, its coordinator alive, never starts the payload", async () => { + const brain = await crashBeforeRelease("release", ["server"]); + expect(existsSync(join(brain, "payload-started.md")), "SERVER_DEATH_PAYLOAD_NEVER_STARTS").toBe(false); +}, 30_000); + +test("a released identity launch starts the payload once, with stdio only and its stdin intact", async () => { + const brain = mkdtempSync(join(tmpdir(), "identity-gate-holder-crash-")); roots.push(brain); + const child = server(brain, "run"); + const [code, output, errors] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code, errors).toBe(0); + const { exit, out, err } = JSON.parse(output.trim().split("\n").at(-1)!) as { exit: number; out: string; err: string }; + 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"]); + const input = Buffer.concat([Buffer.from("go\nPenelope weaves\n"), Buffer.from([0x00, 0xff, 0x0a]), Buffer.from("Ithaca")]); + expect(readFileSync(join(brain, "payload-stdin.md")).equals(input), "PAYLOAD_STDIN_BYTE_IDENTICAL").toBe(true); +}, 30_000);