From 16b43b9124bf6539146521a7d551880ad17e1852 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 8 Nov 2026 11:14:29 +0000 Subject: [PATCH] CONTRACT: feat(ui-sdk): name the identity supervisor's unfinished setup step when readiness times out The separate-UID supervisor now overwrites one private 0600 progress record in the server's 0700 broker directory before each pre-ready setup step: started, listening, launch-sent, launch-acked, status-read, mounts-acked. When readySteps throws worker_identity_setup_timed_out, the launcher reads that record (no link following, non-blocking, at most 128 bytes) before close removes it. It leads the existing (detail) of the requirement, ahead of any launch stderr and within the existing 400-byte cap. The detail leads even when stderr is non-empty. A launch that never acknowledges fails its own 5 s socket wait just after the host deadline, and its stderr line ("timed out") names no step. STATE_SETUP_MS, every supervisor bound, cleanup, closeSteps/fallback ordering and identity verification are unchanged. errorClass stays worker_host_unsupported. The contract index, wire.md and http.md record the additive detail. The native qualification gains a no-launch-ack helper fault. Its launch never acknowledges, and its termination is slowed past the host deadline. The expected requirement names launch-sent, and its cleanup is confirmed. Closes #3664 Co-Authored-By: Claude Opus 5.5 --- .changeset/identity-setup-progress.md | 7 + docs/decisions/governed-writable-workers.md | 2 +- docs/integration-contract.md | 16 ++ docs/integration-contract/http.md | 4 + docs/integration-contract/wire.md | 4 + .../src/server/worker-identity-program.ts | 17 ++ packages/ui-sdk/src/server/worker-identity.ts | 27 +++- packages/ui-sdk/src/server/worker-launcher.ts | 16 +- .../identity-broker-qualification.native.ts | 16 ++ .../tests/worker-identity-progress.test.ts | 147 ++++++++++++++++++ .../tests/worker-steps-event-loop.test.ts | 2 +- scripts/prove-worker-identity.ts | 9 +- 12 files changed, 259 insertions(+), 8 deletions(-) create mode 100644 .changeset/identity-setup-progress.md create mode 100644 packages/ui-sdk/tests/worker-identity-progress.test.ts diff --git a/.changeset/identity-setup-progress.md b/.changeset/identity-setup-progress.md new file mode 100644 index 0000000000..879bab3c01 --- /dev/null +++ b/.changeset/identity-setup-progress.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-sdk": minor +--- + +**Separate-UID setup timeouts name their last step (#3664).** When a separate-UID worker's identity supervisor misses the 5,000 ms readiness deadline, the refusal's requirement now carries the supervisor's last recorded setup step in its existing parenthetical detail. For example: `worker_identity_setup_timed_out (step: launch-sent, ms: 312, sinceSpawnMs: 340)`. The steps are `started`, `listening`, `launch-sent`, `launch-acked`, `status-read` and `mounts-acked`. `step: none` means no step was recorded. `step: refused (…)` means the record was oversized, a link or malformed, and was not read. Any launch stderr follows the step after a `; `. + +The supervisor keeps that one private `0600` record in the server's own `0700` broker directory, which the broker's close removes. The record never reaches the worker. `errorClass` stays `worker_host_unsupported`, and the deadline, every supervisor bound, cleanup and identity verification are unchanged. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 10b941ffad..efa291b5b2 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -2513,7 +2513,7 @@ relative to the handle (`function requireWorkerBrainMount`, The server returns the handle before release, and the coordinator refuses to release the start gate, or open a second view, while one is held (`if operation == 'release':`, -`packages/ui-sdk/src/server/worker-identity-program.ts:189-209`). +`packages/ui-sdk/src/server/worker-identity-program.ts:206-226`). The view grants observation of exactly what the gated worker sees at its own brain path, and nothing the server cannot already read: the live brain, the diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 67b9c2ce0e..d974c18408 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,22 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Setup timeouts name their step (additive, 0.45.0, #3664) + +A separate-UID worker launch that misses its identity readiness deadline still +refuses with `errorClass: "worker_host_unsupported"` and the requirement +`worker_identity_setup_timed_out`. That requirement now always carries a +parenthetical detail, which it never had before. The detail names the +supervisor's last recorded setup step, for example +`(step: launch-sent, ms: 312, sinceSpawnMs: 340)`. The steps are `started`, +`listening`, `launch-sent`, `launch-acked`, `status-read` and `mounts-acked`. +`step: none` means no step was recorded, and `step: refused (…)` means the record +was not read. Any launch stderr follows after `; `, within the existing 400-byte +detail. Requirement text is descriptive and other requirements already carry +such a detail, so no field, class or meaning changes. See +[wire](integration-contract/wire.md) and [the worker-host status](integration-contract/http.md). +This ships in a minor. + ## Observed live content map (additive, 0.45.0, #3630) `ConversationOrientation.knowledge[].topic` additionally accepts `content_map`: diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 9557c7e027..d8a097c00d 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -223,6 +223,10 @@ The status reports; it does not decide. A pass is never cached and a known failure never short-circuits a turn: every turn runs its own probe and refuses with `worker_host_unsupported` naming the requirement ([maintainer ruling](https://github.com/schlessera/brain-kit/issues/1632#issuecomment-6112509133)). +A requirement may end in a parenthetical detail. When a turn's separate-UID +launch times out during identity setup, its refusal names the supervisor's last +recorded setup step there. The probe's own requirement is unchanged +([additive, #3664](../integration-contract.md#setup-timeouts-name-their-step-additive-0450-3664)). Clients must tolerate either mode being absent. diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index fd03962435..ec787b747e 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -939,6 +939,10 @@ SessionHistoryMessage.failure?: TurnFailure // on the assistant message the fa the host refused before runtime initialization because its required worker boundary probe failed; the message names the requirement and the verified Linux/qualifying WSL2 route. It creates no backend session or transcript. + The requirement is descriptive text, not an enumerated value; it may carry a + parenthetical detail. A separate-UID setup timeout names the supervisor's last + recorded step there (additive, #3664): + `worker_identity_setup_timed_out (step: launch-sent, ms: 312, sinceSpawnMs: 340)`. `worker_resource_limit` (#1660) means a host resource limit ended the turn's worker; the message names the limit, its value and whether an rlimit or the worker's cgroup enforced it. diff --git a/packages/ui-sdk/src/server/worker-identity-program.ts b/packages/ui-sdk/src/server/worker-identity-program.ts index 329cff356b..7c0b8711df 100644 --- a/packages/ui-sdk/src/server/worker-identity-program.ts +++ b/packages/ui-sdk/src/server/worker-identity-program.ts @@ -3,6 +3,7 @@ export const WORKER_IDENTITY_SUPERVISOR = String.raw` import array, errno, json, os, select, signal, socket, stat, struct, subprocess, sys, time MAX_PACKET = 65536 +STARTED = time.monotonic() cfg = json.loads(sys.argv[1]) server_uid = os.getuid() if server_uid == 0: @@ -10,9 +11,20 @@ if server_uid == 0: def identity(pid): text = open('/proc/%s/stat' % pid).read().rsplit(') ', 1)[1].split() return {'pid': pid, 'start': text[19]} +def progress(step): + # Diagnostic only (#3664): the last setup step reached, for a host readiness + # timeout. One private 0600 record in the server's 0700 directory, never the worker's. + path = cfg['ready'] + '.progress' + try: + fd = os.open(path + '.tmp', os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600) + try: os.write(fd, json.dumps({'step': step, 'ms': int((time.monotonic() - STARTED) * 1000), 'wallMs': int(time.time() * 1000)}, separators=(',', ':')).encode()) + finally: os.close(fd) + os.rename(path + '.tmp', path) + except OSError: pass server = dict(cfg['server'], uid=server_uid) if identity(server['pid'])['start'] != server['start']: raise RuntimeError('worker_identity_server_changed') +progress('started') supervisor = identity(os.getpid()) base = {'version': 1, 'launch': cfg['launch'], 'server': server, 'supervisor': supervisor} held = {} @@ -104,6 +116,7 @@ def cleanup_owned(): listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) listener.bind(cfg['socket']); os.chmod(cfg['socket'], 0o600); listener.listen(4) +progress('listening') status_read, status_write = os.pipe() gate_read, gate_write = os.pipe() launch_local, launch_remote = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) @@ -127,9 +140,11 @@ try: launch_local.sendmsg([json.dumps(dict(base, argv=argv, statusFd=status_write, gateFd=gate_read, roots=cfg['roots'], keeper=cfg.get('stage', {}).get('keeper'), cgroup=cfg.get('cgroup'), **({'view': cfg['view']} if cfg.get('view') else {}))).encode()], authority) + progress('launch-sent') ack, fds = packet(launch_local) for fd in fds: os.close(fd) if fds: raise RuntimeError('worker_identity_unexpected_launch_handles') + progress('launch-acked') if stage_ticket is not None: os.close(stage_ticket); stage_ticket = None os.close(status_write); os.close(gate_read) status = b''; deadline = time.monotonic() + 5 @@ -142,10 +157,12 @@ try: status += chunk if len(status) > 4096: raise RuntimeError('worker_identity_malformed_status') reported = json.loads(status.split(b'\n', 1)[0]).get('child-pid') + progress('status-read') if type(reported) is not int or reported <= 1: raise RuntimeError('worker_identity_malformed_status') worker = identity(reported) answer, descriptors = helper('mounts', {'worker': worker, 'roots': cfg['roots']}) pending = descriptors + progress('mounts-acked') if len(descriptors) != len(cfg['roots']) or len(answer.get('roots', [])) != len(descriptors): raise RuntimeError('worker_identity_unexpected_mount_handles') if type(answer.get('workerUid')) is not int or not 0 < answer['workerUid'] < 0xffffffff or answer['workerUid'] == server_uid: diff --git a/packages/ui-sdk/src/server/worker-identity.ts b/packages/ui-sdk/src/server/worker-identity.ts index 8c6519b884..f8e4a9aee1 100644 --- a/packages/ui-sdk/src/server/worker-identity.ts +++ b/packages/ui-sdk/src/server/worker-identity.ts @@ -1,5 +1,5 @@ /** Host-only identity broker client. No authority from this module enters a payload. */ -import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, statfsSync } from "node:fs"; +import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, rmSync, statfsSync } from "node:fs"; import { isAbsolute, join } from "node:path"; import { tmpdir } from "node:os"; import { workerIdentityHelperInput } from "../config/env.js"; @@ -15,6 +15,10 @@ export function workerCleanupUnconfirmed(error: unknown): boolean { return typeof error === "object" && error !== null && "cleanupUnconfirmed" in error && error.cleanupUnconfirmed === true; } export interface IdentityRoot { name: "state" | "temp"; path: string; bytes: number } +/** The supervisor's setup steps, in order, as its progress record names them (#3664). */ +const SETUP_STEPS = new Set(["started", "listening", "launch-sent", "launch-acked", "status-read", "mounts-acked"]); +/** The largest progress record read; the supervisor writes about 60 bytes. */ +const SETUP_PROGRESS_BYTES = 128; interface Ready { ok: true; workerUid: number; worker: { pid: number; start: string }; roots: Record } /** Resolve only trusted host configuration, never a worker's child environment. */ @@ -202,6 +206,27 @@ export function prepareWorkerIdentity(helper: string, argv: string[], roots: Ide try { request("signal", { signal: "KILL" }); } catch { fallback(["signal"]); } }, + /** + * The supervisor's last recorded setup step, for a readiness timeout's + * detail (#3664). Read before close removes the directory; never follows + * a link, never blocks and never reads more than the bound. + */ + setupProgress(spawnedAt: number): string { + let fd: number | undefined; + try { + fd = openSync(`${readyPath}.progress`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + if (!fstatSync(fd).isFile()) return "step: refused (not a regular file)"; + const chunk = Buffer.alloc(SETUP_PROGRESS_BYTES + 1), length = readSync(fd, chunk, 0, chunk.length, 0); + if (length > SETUP_PROGRESS_BYTES) return "step: refused (oversized)"; + const record = JSON.parse(chunk.subarray(0, length).toString("utf8")) as { step?: unknown; ms?: unknown; wallMs?: unknown } | null; + if (!record || typeof record.step !== "string" || !SETUP_STEPS.has(record.step) || !Number.isSafeInteger(record.ms) || (record.ms as number) < 0 + || !Number.isSafeInteger(record.wallMs)) return "step: refused (malformed)"; + return `step: ${record.step}, ms: ${record.ms as number}, sinceSpawnMs: ${(record.wallMs as number) - spawnedAt}`; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + return code === "ENOENT" ? "step: none" : code === "ELOOP" ? "step: refused (symlink)" : error instanceof SyntaxError ? "step: refused (malformed)" : "step: refused (unreadable)"; + } finally { if (fd !== undefined) closeSync(fd); } + }, close() { runWorkerStepsSync(closeSteps()); }, /** `close`, with the same refusal and fallback cleanup, as steps (#2844). */ closeSteps, diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index fa8a6c3aff..48134ecc1a 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -1371,6 +1371,8 @@ export function* launchAgentWorkerSteps(input: WorkerLaunch): WorkerSteps | undefined; let identityBroker: ReturnType | undefined; let identityFinished = false, identityReferences = 0; + /** A setup timeout's last recorded supervisor step, read before close removes it (#3664). */ + let setupProgress = ""; let completeMaintenanceSetup: (() => void) | undefined; let failMaintenanceSetup: ((error: unknown) => void) | undefined; const identityHandles: WorkerStateHandle[] = []; @@ -1444,7 +1446,11 @@ export function* launchAgentWorkerSteps(input: WorkerLaunch): WorkerSteps["ready"]> | undefined; try { identityReady = identityBroker ? yield* identityBroker.readySteps(child.pid, deadline) : undefined; } - catch (error) { throw new WorkerHostError(error instanceof Error ? error.message : String(error)); } + catch (error) { + const requirement = error instanceof Error ? error.message : String(error); + if (requirement === "worker_identity_setup_timed_out") setupProgress = identityBroker!.setupProgress(deadline - STATE_SETUP_MS); + throw new WorkerHostError(requirement); + } try { pid = identityReady?.worker.pid ?? (yield* status!.childPidSteps(child.pid, deadline)); } catch (error) { throw new WorkerHostError(error instanceof Error ? error.message : String(error)); } status?.closeWriter(); @@ -1581,7 +1587,9 @@ export function* launchAgentWorkerSteps(input: WorkerLaunch): WorkerSteps { try { await areaOutput?.cleanup(); } finally { if (!input.preparedOutput) await startupView?.cleanup(); } }).catch(() => { /* Native broker retains unresolved release intent for recovery. */ }); else { void Promise.resolve(areaOutput?.cleanup()).finally(() => input.preparedOutput ? undefined : startupView?.cleanup()).catch(() => { /* No child ran; durable ownership retains unresolved release intent. */ }); } if (detail) { - throw new WorkerHostError(NO_TMPFS_SIZE.test(detail) - ? `bubblewrap 0.7 or later, for the worker's size-limited tmpfs mounts (${detail})` + throw new WorkerHostError(NO_TMPFS_SIZE.test(diagnostics) + ? `bubblewrap 0.7 or later, for the worker's size-limited tmpfs mounts (${diagnostics})` : `${(error as WorkerHostError).requirement} (${detail})`); } throw error; diff --git a/packages/ui-sdk/tests/identity-broker-qualification.native.ts b/packages/ui-sdk/tests/identity-broker-qualification.native.ts index 786a344b14..730f7b16b6 100644 --- a/packages/ui-sdk/tests/identity-broker-qualification.native.ts +++ b/packages/ui-sdk/tests/identity-broker-qualification.native.ts @@ -229,6 +229,22 @@ print(json.dumps(dict(uid=os.getuid(),value=value)))`, {sandbox:{brain,profile:" } } finally { if (configured !== undefined) process.env.BRAIN_UI_WORKER_IDENTITY_HELPER = configured; } }); + await check("a helper that never acknowledges launch times out naming launch-sent, and its cleanup is confirmed", async () => { + const configured = process.env.BRAIN_UI_WORKER_IDENTITY_HELPER; + process.env.BRAIN_UI_WORKER_IDENTITY_HELPER = "/usr/local/bin/identity-helper-fault-no-launch-ack"; + const marker = join(brain, "no-launch-ack-payload"); + try { + let refusal: { requirement?: string; errorClass?: string; message?: string } | undefined; + try { launch(`open('${marker}','w').write('unexpected')`); } catch (error) { refusal = error as typeof refusal; } + console.log(JSON.stringify({ setupTimeout: { requirement: refusal?.requirement, errorClass: refusal?.errorClass } })); + // An unconfirmed cleanup would refuse as WorkerIdentityCleanupError, with no requirement. + expect(refusal?.errorClass, "NO_LAUNCH_ACK_REFUSES_AS_HOST_UNSUPPORTED").toBe("worker_host_unsupported"); + expect(refusal?.requirement, "NO_LAUNCH_ACK_NAMES_LAUNCH_SENT") + .toMatch(/^worker_identity_setup_timed_out \(step: launch-sent, ms: \d+, sinceSpawnMs: -?\d+(;|\)$)/); + expect(existsSync(marker), "NO_LAUNCH_ACK_KEEPS_GATE_CLOSED").toBe(false); + await until(() => workerPids().length === 0, "NO_LAUNCH_ACK_LEFT_WORKER"); + } finally { if (configured !== undefined) process.env.BRAIN_UI_WORKER_IDENTITY_HELPER = configured; } + }); await check("helper final exec resets inherited ignored signals and pipelines stay quiet", async () => { for(const [command,verify] of [ [["/usr/bin/cat","/proc/self/status"],(output:string)=>expect(output.match(/^SigIgn:\s+([0-9a-f]+)$/m)?.[1]).toBe("0000000000000000")], diff --git a/packages/ui-sdk/tests/worker-identity-progress.test.ts b/packages/ui-sdk/tests/worker-identity-progress.test.ts new file mode 100644 index 0000000000..a6a5add032 --- /dev/null +++ b/packages/ui-sdk/tests/worker-identity-progress.test.ts @@ -0,0 +1,147 @@ +// #3664: a separate-UID readiness timeout names the supervisor's last recorded setup step. +import { expect, spyOn, test } from "bun:test"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { launchAgentWorker, launchAgentWorkerAsync } from "../src/server/worker-launcher"; +import * as identity from "../src/server/worker-identity"; +import { runWorkerStepsAsync } from "../src/server/worker-steps"; +import { createFixtureWorkerStartupView } from "./helpers/worker-startup-view-fixture.js"; +import { identityControl } from "./helpers/identity-control-fixture.js"; + +const ROOT = resolve(import.meta.dir, "../../.."); +const IDENTITY_HELPER = "/usr/lib/odysseus/identity-helper"; +type Broker = ReturnType; + +function fixture() { + mkdirSync(join(ROOT, "tmp"), { recursive: true }); + const root = mkdtempSync(join(ROOT, "tmp/identity-progress-")); + const brain = join(root, "brain"); + mkdirSync(join(brain, "notes"), { recursive: true }); + return { root, brain, cleanup: () => rmSync(root, { recursive: true, force: true }) }; +} + +const readyPath = (broker: Broker) => (JSON.parse(broker.command.at(-1)!) as { ready: string }).ready; + +/** + * `prepareWorkerIdentity` at the launcher's seam, with its real `readySteps`: + * the supervisor never publishes `ready`, so the launch reaches its own + * deadline. `progress` is the record the supervisor would have left. The close + * runs the real control client against a stand-in socket. + */ +function timeoutSeam(progress?: object) { + const prepare = identity.prepareWorkerIdentity; + const controls: ReturnType[] = [], brokers: Broker[] = []; + const spy = spyOn(identity, "prepareWorkerIdentity").mockImplementation((...args: Parameters) => { + const real = prepare(...args); + brokers.push(real); + controls.push(identityControl(real, { delayMs: 50 })); + if (progress) writeFileSync(`${readyPath(real)}.progress`, JSON.stringify(progress), { mode: 0o600 }); + return { ...real, command: ["/bin/sh", "-c", "exec sleep 30"] }; + }); + return { + operations: () => controls.map(control => control.operations()), + released: () => brokers.map(broker => existsSync(dirname(readyPath(broker)))), + restore: async () => { spy.mockRestore(); for (const control of controls) await control.stop(); for (const broker of brokers) broker.discard(); }, + }; +} + +async function timedOutLaunch(progress: object | undefined, form: "async" | "sync") { + const f = fixture(), view = createFixtureWorkerStartupView(f.brain); + const helper = spyOn(identity, "workerIdentityHelper").mockReturnValue(IDENTITY_HELPER); + const seam = timeoutSeam(progress); + try { + const input = { brainPath: f.brain, startupView: view, command: ["/bin/true"], env: {} }; + const started = Date.now(); + const work = form === "async" ? launchAgentWorkerAsync(input) : Promise.resolve().then(() => launchAgentWorker(input)); + const refusal = await work.then(() => new Error("launch_succeeded"), (error: unknown) => error) as Error & { requirement?: string; errorClass?: string }; + return { refusal, elapsed: Date.now() - started, operations: seam.operations(), released: seam.released() }; + } finally { await seam.restore(); helper.mockRestore(); view.cleanup(); f.cleanup(); } +} + +test("a readiness timeout names the supervisor's last recorded step, keeps its class and still closes the broker", async () => { + const { refusal, elapsed, operations, released } = await timedOutLaunch({ step: "launch-sent", ms: 312, wallMs: Date.now() + 40 }, "async"); + expect(refusal.name, "TIMEOUT_REFUSES_AS_WORKER_HOST_ERROR").toBe("WorkerHostError"); + expect(refusal.errorClass).toBe("worker_host_unsupported"); + expect(refusal.requirement, "TIMEOUT_REQUIREMENT_NAMES_RECORDED_STEP") + .toMatch(/^worker_identity_setup_timed_out \(step: launch-sent, ms: 312, sinceSpawnMs: -?\d+\)$/); + expect(refusal.message).toStartWith("Agent worker boundary unavailable: worker_identity_setup_timed_out (step: launch-sent, ms: 312, "); + // The unchanged deadline and the unchanged confirmed close. + expect(elapsed).toBeGreaterThanOrEqual(5_000); + expect(operations, "TIMEOUT_STILL_CLOSES_BROKER").toEqual([["close", "close:answered"]]); + expect(released, "CONFIRMED_CLOSE_STILL_RELEASES_BROKER").toEqual([false]); +}, 30_000); + +test("a readiness timeout with no progress record says step: none", async () => { + const { refusal, operations } = await timedOutLaunch(undefined, "sync"); + expect(refusal.errorClass).toBe("worker_host_unsupported"); + expect(refusal.requirement, "MISSING_RECORD_READS_AS_NONE").toBe("worker_identity_setup_timed_out (step: none)"); + expect(operations).toEqual([["close", "close:answered"]]); +}, 30_000); + +test("the progress read refuses an oversized, linked, non-regular or malformed record without reading through it", () => { + const broker = identity.prepareWorkerIdentity(IDENTITY_HELPER, ["/bin/true"], []); + const outside = mkdtempSync(join(ROOT, "tmp/identity-progress-outside-")); + try { + const record = `${readyPath(broker)}.progress`, spawnedAt = Date.now(); + const valid = JSON.stringify({ step: "mounts-acked", ms: 20, wallMs: spawnedAt + 25 }); + writeFileSync(record, valid); + expect(broker.setupProgress(spawnedAt)).toBe("step: mounts-acked, ms: 20, sinceSpawnMs: 25"); + writeFileSync(record, JSON.stringify({ step: "launch-sent", ms: 1, wallMs: spawnedAt, pad: "x".repeat(100) })); + expect(broker.setupProgress(spawnedAt), "OVERSIZED_RECORD_REFUSED").toBe("step: refused (oversized)"); + rmSync(record); + // A link to a well-formed record elsewhere is refused, not followed. + const target = join(outside, "progress"); + writeFileSync(target, valid); + symlinkSync(target, record); + expect(broker.setupProgress(spawnedAt), "LINKED_RECORD_REFUSED").toBe("step: refused (symlink)"); + rmSync(record); + mkdirSync(record); + expect(broker.setupProgress(spawnedAt), "DIRECTORY_RECORD_REFUSED").toBe("step: refused (not a regular file)"); + rmSync(record, { recursive: true }); + if (Bun.spawnSync(["mkfifo", record]).exitCode === 0) { + // A FIFO with no writer neither blocks the read nor counts as a record. + expect(broker.setupProgress(spawnedAt), "FIFO_RECORD_REFUSED").toBe("step: refused (not a regular file)"); + rmSync(record); + } + for (const body of ["{", JSON.stringify({ step: "bwrap-exec", ms: 1, wallMs: spawnedAt }), JSON.stringify({ step: "started", ms: -1, wallMs: spawnedAt }), "null"]) { + writeFileSync(record, body); + expect(broker.setupProgress(spawnedAt), `MALFORMED_RECORD_REFUSED ${body}`).toBe("step: refused (malformed)"); + } + } finally { broker.discard(); rmSync(outside, { recursive: true, force: true }); } +}); + +test("the real supervisor records each setup step it reaches: a helper that never acknowledges launch leaves launch-sent", async () => { + const work = mkdtempSync(join(ROOT, "tmp/identity-progress-supervisor-")); + const pidFile = join(work, "helper.pid"), helper = join(work, "never-acknowledges"); + // Stands in for the root helper: it starts its `launch` operation and never answers it. + writeFileSync(helper, `#!/bin/sh\necho $$ > ${pidFile}\nexec /bin/sleep 20\n`); + chmodSync(helper, 0o700); + const bwrap = "/usr/lib/odysseus/bwrap"; + const broker = identity.prepareWorkerIdentity(helper, [bwrap, "--", "/bin/true"], []); + const command = broker.command.slice(0, -1); + const config = { ...JSON.parse(broker.command.at(-1)!) as object, bwrap }; + const spawnedAt = Date.now(); + const supervisor = Bun.spawn([...command, JSON.stringify(config)], { env: {}, stdin: "ignore", stdout: "ignore", stderr: "pipe" }); + try { + const record = `${readyPath(broker)}.progress`; + const deadline = Date.now() + 10_000; + while (!broker.setupProgress(spawnedAt).startsWith("step: launch-sent")) { + if (supervisor.exitCode !== null || Date.now() >= deadline) + throw new Error(`supervisor never recorded launch-sent: ${broker.setupProgress(spawnedAt)}`); + await Bun.sleep(5); + } + // The host's real wait reaches its own deadline and reads the same record. + const refusal = await runWorkerStepsAsync(broker.readySteps(supervisor.pid, Date.now() + 200)).then(() => undefined, (error: Error) => error.message); + expect(refusal).toBe("worker_identity_setup_timed_out"); + expect(broker.setupProgress(spawnedAt), "REAL_SUPERVISOR_RECORDS_LAUNCH_SENT").toMatch(/^step: launch-sent, ms: \d+, sinceSpawnMs: \d+$/); + // A private record in the server's private directory: no new path for anyone else. + const info = statSync(record), directory = statSync(dirname(record)); + expect({ mode: info.mode & 0o777, uid: info.uid, size: info.size <= 128, directory: directory.mode & 0o777 }) + .toEqual({ mode: 0o600, uid: process.getuid!(), size: true, directory: 0o700 }); + expect(existsSync(`${record}.tmp`), "NO_TEMPORARY_RECORD_REMAINS").toBe(false); + } finally { + supervisor.kill("SIGKILL"); await supervisor.exited; + try { process.kill(Number(readFileSync(pidFile, "utf8")), "SIGKILL"); } catch { /* It may never have started, or already ended. */ } + broker.discard(); rmSync(work, { recursive: true, force: true }); + } +}, 30_000); diff --git a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts index 8ff9a05830..a1124b5f6c 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -546,7 +546,7 @@ test("a failed asynchronous launch closes its separate-UID broker through awaite } finally { spawns.restore(); await seam.restore(); } }; try { - const confirmed = { refusal: "worker_identity_setup_timed_out", unconfirmed: false, operations: [["close", "close:answered"]], + const confirmed = { refusal: "worker_identity_setup_timed_out (step: none)", unconfirmed: false, operations: [["close", "close:answered"]], trace: ["close", "closed", "worker-killed"], killed: ["SIGKILL" as NodeJS.Signals] }; expect(await runs(() => launchAgentWorkerAsync(launch(views[0]!))), "ASYNC_LAUNCH_AWAITS_BROKER_CLOSE") .toEqual({ ...confirmed, spawns: { sync: 0, async: 1 } }); diff --git a/scripts/prove-worker-identity.ts b/scripts/prove-worker-identity.ts index c19e7c9fcf..ee5b75ac6a 100644 --- a/scripts/prove-worker-identity.ts +++ b/scripts/prove-worker-identity.ts @@ -193,11 +193,18 @@ if (import.meta.main) { "extra-fd": [' send(connection, {"workerUid": WORKER_UID, "roots": result["roots"]}, fds)', ' fds.append(os.dup(fds[0]))\n send(connection, {"workerUid": WORKER_UID, "roots": result["roots"]}, fds)'], "no-view": [' elif operation == "view":\n view(connection, request, token, record)', ' elif operation == "view":\n refuse("operation")'], "host-view": [' fd = os.open("/proc/%s/root%s" % (value["pid"], record["view"]), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)', ' fd = os.open(record["view"], os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)'], + // #3664: launch never acknowledges. Its termination is slowed past the host's + // readiness deadline, so the supervisor's own failure record cannot win that race. + "no-launch-ack": [' send(connection, {})\n connection.close()\n parent = os.getppid()', ' time.sleep(60)\n send(connection, {})\n connection.close()\n parent = os.getppid()'], "foreign-mount": [' info = os.stat(source)', ' foreign = source + "/foreign"\n os.mkdir(foreign, 0o755)\n foreign_options = ("size=4096,mode=2770,uid=%s,gid=%s" % (SERVER_UID, SHARED_GID)).encode()\n if libc.mount(b"tmpfs", foreign.encode(), b"tmpfs", 2 | 4, foreign_options): refuse("foreign_fixture_mount")\n info = os.stat(source)'], }; + const faultFollowups: Record = { + "no-launch-ack": [' deadline, previous = time.monotonic() + 2, None', ' time.sleep(1.5)\n deadline, previous = time.monotonic() + 2, None'], + }; const faultHashes: Record = {}; for (const [name, [before, after]] of Object.entries(faultEdits)) { - const script = changed(helperScript, before, after), scriptPath = join(artifact, `fault-${name}.py`); + const followup = faultFollowups[name]; + const script = followup ? changed(changed(helperScript, before, after), ...followup) : changed(helperScript, before, after), scriptPath = join(artifact, `fault-${name}.py`); writeFileSync(scriptPath, script); const parsed = Bun.spawnSync(["python3", "-I", "-S", "-c", "import ast,sys;ast.parse(open(sys.argv[1]).read())", scriptPath], { stdout: "pipe", stderr: "pipe" }); if (parsed.exitCode !== 0) throw Error(`Invalid fault fixture ${name}: ${parsed.stderr.toString()}`);