diff --git a/CHANGELOG.md b/CHANGELOG.md index b6636379f..ab1f99b56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,15 @@ 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 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 + 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 @@ -67,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` @@ -159,6 +169,53 @@ 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 `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 `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, + full-screen ones do not, and a bare `adb shell` is refused + (`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` gains a `daemon` block, `{ health, mode }`. + `health` moves into it from the top level, and `mode` (`worker`/`gateway`, + 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 + 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 + 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 770f9895e..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 @@ -693,6 +694,30 @@ 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. + +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 26f8d2345..d8a0ee38a 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.) @@ -480,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/CLIENT.md b/docs/CLIENT.md index 7f9b733a5..7d5af1c8d 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -78,6 +78,73 @@ 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`. +## 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. + +```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.exec( + { 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. + +`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, 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 +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. 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 — 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: + +- **No pseudo-terminal.** Line-oriented commands work; full-screen and + 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. +- **`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..2522ce23e 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,17 +58,20 @@ 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 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/docs/HTTP-API.md b/docs/HTTP-API.md index 4f460a8c0..d8cd4ff79 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 — @@ -115,13 +128,19 @@ 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 -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: + +```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 @@ -352,118 +371,146 @@ 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`. -### `DELETE /v1/leases/{id}` - -Role: `agent` (own lease); `operator` may release any lease. - -→ `202 { "released": true, "device": { "id": "dev_1a2b", "state": "reclaiming" } }` - -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)). +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 — 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": ["install", "booted", "/tmp/MyApp.app"], - "stdin": null, "requesterId": null } +{ "tool": "simctl", "args": ["list", "devices"], "stdin": "y\n" } ``` -`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 +`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` +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. 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 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: +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 +written, then exactly one terminal event: ``` event: output -data: {"stream":"stdout","chunk":"Installing...\n"} +data: {"stream":"stdout","chunk":"== Devices ==\n"} event: output -data: {"stream":"stderr","chunk":"warning: ...\n"} - -: keepalive +data: {"stream":"stderr","chunk":"No devices found\n"} 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. +`chunk` is whatever the command wrote, decoded as UTF-8 and forwarded +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` — 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` for a `tool` outside - `simctl`/`adb`. -- `400 BAD_REQUEST` — a malformed body. + 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. -- `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). + +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 +data: {"error":{"code":"EXEC_TIMEOUT","message":"..."}} +``` + +`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. 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). + +### `DELETE /v1/leases/{id}` + +Role: `agent` (own lease); `operator` may release any lease. + +→ `202 { "released": true, "device": { "id": "dev_1a2b", "state": "reclaiming" } }` + +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`. ### `GET /v1/uplink` (WebSocket upgrade) diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index a9d85798c..0d60bba6c 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -159,6 +159,43 @@ 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 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`, +`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 +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. @@ -424,6 +461,147 @@ 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. + +## 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` +/ `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`. + ## iOS slim mode: accepted costs and feature loss (#87) `ios.slim` (opt-in, default off) has the iOS driver disable ~170 launchd @@ -528,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 @@ -697,3 +802,42 @@ 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 + { 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` diff --git a/e2e/device-exec.test.ts b/e2e/device-exec.test.ts new file mode 100644 index 000000000..54289de8b --- /dev/null +++ b/e2e/device-exec.test.ts @@ -0,0 +1,298 @@ +import { createServer } from "node:net"; +import { describe, expect, it } from "vitest"; + +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 + * 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, 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`. */ +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; +} + +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; +} + +/** 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; +} + +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", + }, + auth, + ); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toContain("text/event-stream"); + + const frames = await readSse(response); + expect(frames.at(-1)).toEqual({ data: { exitCode: 3 }, event: "exit" }); + // 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(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(chunksOf(frames, "stderr")).toBe("a warning"); + + // `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" }); + + await env.cli(["release", leaseId]); + }); + + 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); + + // 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 errorCodeOf(bareShell)).toBe("PASSTHROUGH_REFUSED"); + + // The same command with something to run is not the interactive shell, and goes through. + 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", + }); + + // 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 0e3175df6..17ab015b6 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"; @@ -116,17 +117,45 @@ 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 = - "process.stdout.write(JSON.stringify({" + - "argv: process.argv.slice(1)," + - // 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. + "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);" + + // `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," + "platform: process.env.SIMLOCK_FAKE_PASSTHROUGH_PLATFORM ?? null," + + "...(stdin === undefined ? {} : { stdin })," + "}));" + - "process.exit(Number(process.env.SIMLOCK_FAKE_PASSTHROUGH_EXIT ?? 0));"; + "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. + "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 @@ -315,7 +344,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" && isBareShell(args)) { + 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( @@ -453,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); } 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/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/admin/index.ts b/src/admin/index.ts index cb5a4b9eb..ca61841cf 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -20,6 +20,10 @@ export type { DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, + ExecInput, + ExecOutput, + DeviceOutputChunk, + ExecOptions, DoctorReport, DoctorRunInput, EventPush, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index dfbfdef17..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, @@ -368,6 +370,497 @@ 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. + * + * 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, + daemon: { health: "running" as const, mode: "gateway" as const }, + }; + 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({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.resolve({ leases: [ownLease] }), + exec: (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); + // `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"); + // 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({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + 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({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.resolve({ leases: [ownLease] }), + exec: () => + 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 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({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.resolve({ leases: [ownLease] }), + exec: () => + Promise.reject( + new SimlockError( + "EXEC_TIMEOUT", + "domain", + "`adb logcat` exceeded exec.timeoutMs (600000ms) and was killed", + {}, + ), + ), + }), + }), + ), + ).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")), + exec: (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("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[] = []; + + await expect( + runCli( + ["adb", "shell", "cat"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve(gatewayStatus), + listLeases: () => Promise.resolve({ leases: [ownLease] }), + exec: (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] }), + exec: (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 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", "lse_ignored", "shell", "getprop"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + exec: () => 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: ["shell", "getprop"], tool: "adb" }]); + 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. + 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 () => { const output = outputCapture(); @@ -2127,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 { @@ -2160,26 +2698,29 @@ 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 }, + }, + daemon: { health: "running", mode: "worker" }, + queueDepth: 0, +}; + +function fakeClient(overrides: Partial = {}): SimlockAdminClient { const emptyCatalog: CatalogGetOutput = { platforms: [] }; const emptyDoctor: DoctorReport = { findings: [] }; const emptyLeaseList: LeaseListOutput = { leases: [] }; @@ -2214,9 +2755,10 @@ 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: {} }), + 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 }), @@ -2497,6 +3039,8 @@ async function startInMemoryDaemon(options: { function testConfig(): Config { return { + mode: "worker", + 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..8d2558d5d 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -173,6 +173,14 @@ export interface CliEnvironment { * child process, the same way every other external effect here is injected. */ readonly runPassthrough?: (command: PassthroughCommand) => Promise; + /** + * 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 readStdin?: () => Promise; } /** @@ -347,6 +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.readStdin`. */ + readonly readStdin?: () => Promise; readonly parentPid?: number; } @@ -412,6 +422,7 @@ export function buildCliEnvironment( return requireObject(JSON.parse(await filesystem.readFile(configPath)) as unknown); }, runPassthrough: ports.runPassthrough ?? spawnPassthrough, + readStdin: ports.readStdin ?? readPipedStdin, writeConfigFile: async (contents) => { await filesystem.mkdirp(dataDirectory); await filesystem.writeFileAtomic(configPath, `${JSON.stringify(contents, null, 2)}\n`); @@ -448,6 +459,25 @@ 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. + */ +export 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"); @@ -557,7 +587,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: 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), + environment, + token, + ); case "mcp": return await runMcp(rest.slice(1), environment); default: @@ -595,24 +633,54 @@ 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 { - const run = environment.runPassthrough; - if (run === undefined) throw new Error("Tool passthrough is unavailable"); + // `--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 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 -- + // 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 daemon; + try { + ({ daemon } = await client.getStatus()); + } catch (error: unknown) { + await client.close(); + throw error; + } + if (daemon.mode === "gateway") { + try { + return await runRemotePassthrough(tool, rest, environment, client, leaseFlag); + } 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) { + await client.close(); + throw new Error("Tool passthrough is unavailable"); + } 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. - 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. @@ -621,6 +689,156 @@ 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, + client: SimlockAdminClient, + leaseFlag: string | undefined, +): Promise { + try { + 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.exec( + { + args: [...args], + 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 + // 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) { + 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 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 + * 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[]; +} { + let leaseFlag: string | undefined; + 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 += 2; + continue; + } + if (argument.startsWith("--lease=")) { + leaseFlag = argument.slice("--lease=".length); + if (leaseFlag === "") throw new UsageError("--lease requires a lease id"); + index += 1; + continue; + } + // 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: args.slice(index) }; +} + +/** + * Which lease the remote command runs against: the one this invocation's requester id holds. + * + * `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 = + 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`, + ); + } + 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. */ @@ -1561,7 +1779,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]; @@ -1586,7 +1804,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/client/index.ts b/src/client/index.ts index 46f697513..8dcb7d370 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -21,6 +21,10 @@ export type { CatalogGetOutput, DeviceRecoveredPush, DeviceUnhealthyPush, + ExecInput, + ExecOutput, + DeviceOutputChunk, + ExecOptions, DoctorReport, DoctorRunInput, DriverPassthroughInput, diff --git a/src/contract/errors.ts b/src/contract/errors.ts index aef0856fa..01e37643e 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 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", @@ -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..36ac93d1e 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", () => { @@ -50,6 +51,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" }, ]; @@ -192,7 +198,7 @@ describe("operation input/output round trips", () => { }, global: { running: 0, maxRunning: 2, reserved: 0, overLimit: false, warm: 0 }, }, - health: "running", + daemon: { health: "running", mode: "worker" }, queueDepth: 0, }; expect(OPERATIONS["status.get"].output.parse(status)).toBeDefined(); @@ -205,6 +211,58 @@ 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" }); + + // `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({ + 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 } }, @@ -219,6 +277,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..ba17de8b6 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -80,7 +80,16 @@ export const statusGet = defineOperation({ devices: z.array(statusDeviceSchema), leases: z.array(leaseRecordSchema), capacity: statusCapacitySchema, - health: daemonHealthSchema, + /** + * 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`. + */ + daemon: z.object({ health: daemonHealthSchema, mode: z.enum(["worker", "gateway"]) }), queueDepth: z.number(), }), }); @@ -216,6 +225,111 @@ 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"`, 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 + * 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 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({ + name: "device.exec", + role: "agent", + input: z + .object({ + leaseId: z.string(), + tool: z.string().min(1), + 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). 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(), + }) + .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() }), + /** + * `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`. 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; + * 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") { + if (input.requesterId !== undefined) return false; + 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) ----------------------------------------------------------------- // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. @@ -403,6 +517,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/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/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/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/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..d3a06c05b 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -10,6 +10,8 @@ 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: {}, eventBuffer: { capacity: 100 }, diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index 4cd71a1e0..2d2e28cd1 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -6,6 +6,8 @@ import { idleDestroyRule } from "./idle-destroy.js"; const gibibyte = 1024 ** 3; const config: Config = { + mode: "worker", + 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..4c24b03d7 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -4,6 +4,8 @@ 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: {}, eventBuffer: { capacity: 1 }, diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 6ae8d4b9f..1b314be69 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -98,6 +98,82 @@ 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"); + + // `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"); + + await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode: "broker" })); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).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. + 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/core/config.ts b/src/core/config.ts index 600434071..1a1c3b369 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 @@ -50,7 +59,18 @@ const DEFAULT_LEASE_MAX_TTL_MS = 4 * 60 * 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 @@ -92,6 +112,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 }; @@ -186,6 +212,7 @@ export async function loadConfig({ overrideConfig, ) as unknown as Config; validateLeaseTtls(merged); + validateGatewayNeedsHttp(merged); return deepFreeze(merged); } @@ -216,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; @@ -290,6 +334,7 @@ function asObject(value: unknown): Layer { function defaultConfig(systemStats: SystemStats, strategy: CapacityStrategyName): Config { return { + mode: "worker", capacity: { strategy, config: defaultCapacityOptions(strategy, systemStats), @@ -316,6 +361,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 }, @@ -383,6 +429,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 @@ -390,6 +437,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), @@ -420,6 +468,7 @@ function configValidators(strategy: CapacityStrategyName): Record = {}): Config { return { + mode: "worker", + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, drivers: {}, eventBuffer: { capacity: 10 }, 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-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index d85e891f1..4903fee63 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -25,6 +25,8 @@ 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: {}, 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..61b179607 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -22,6 +22,8 @@ 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: {}, downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, 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-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index 53e135884..98b49dd2c 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -17,6 +17,8 @@ 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: {}, eventBuffer: { capacity: 100 }, 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/core/nuke.test.ts b/src/core/nuke.test.ts index 50360aa92..229d94bd7 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -145,6 +145,8 @@ function sequence() { function config(): Config { return { + mode: "worker", + 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..2b7f87f30 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -44,6 +44,8 @@ class MutableFreeDiskFilesystem extends MemoryFilesystem { function config(): Config { return { + mode: "worker", + 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..0132878fd 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -15,6 +15,8 @@ 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: {}, eventBuffer: { capacity: 100 }, 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 e00896dc0..5512e729b 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -7,15 +7,20 @@ import { FakeDriver, LeaseEngine, Nuke, + PassthroughRefusedError, 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"; import { TokenStore } from "../http/token-store.js"; import type { DispatchSession } from "./dispatcher.js"; @@ -33,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"]; @@ -51,9 +69,26 @@ 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; + /** 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; + /** 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 = 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({ @@ -70,15 +105,27 @@ 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[], 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. + 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, @@ -128,7 +175,9 @@ 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, reaper, registry, @@ -691,6 +740,507 @@ 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([]); + }); + + /** + * 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, 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 a + // non-admin session may not name a `requesterId` at all, regardless of whose it is. + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + 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, 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 }); + }); + + 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" }, + 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 }); + + 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("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( + "device.exec", + { args: [], leaseId, tool: "bash" }, + session({ principal: "tok_agent" }), + ), + ).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("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({ + clock, + exec: { timeoutMs: 1_000 }, + processRunner: { spawnStreaming: () => handle } as unknown as ProcessRunner, + }); + + const pending = dispatcher.dispatch( + "device.exec", + { args: ["list", "devices"], leaseId, tool: "simctl" }, + session({ principal: "tok_agent" }), + ); + await flush(); + + // 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); + + await expect(pending).resolves.toEqual({ exitCode: 7 }); + // 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); + + 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); + }); +}); + +/** 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++}` }; @@ -699,9 +1249,12 @@ function sequence() { function testConfig( downloadsPolicy: Config["downloads"]["policy"] = "on-request", leaseOverrides: Partial = {}, + execOverrides: Partial = {}, ): Config { return { + mode: "worker", drivers: {}, + exec: { timeoutMs: 600_000, ...execOverrides }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, eventBuffer: { capacity: 100 }, health: { diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 1dfa1023e..4e03bdda9 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,47 @@ 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. + * + * **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 | 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 + * 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. */ 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; + +/** 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 { @@ -102,6 +145,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 +238,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, @@ -234,6 +292,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, @@ -281,7 +341,11 @@ 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], queueDepth: this.options.queue.queueDepth, }; @@ -402,6 +466,110 @@ 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); + + // `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 }, + // 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 }), + }); + // 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) }; + }; + + /** + * 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; + 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"); + killTimer = this.options.clock.setTimer(EXEC_SIGKILL_GRACE_MS, () => { + killQuietly(handle, "SIGKILL"); + }); + // 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( + "EXEC_TIMEOUT", + `\`${tool} ${args.join(" ")}\` exceeded exec.timeoutMs (${String(timeoutMs)}ms) and was killed`, + ); + } finally { + if (timer !== undefined) 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 +666,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 +683,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/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/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/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 { // 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); @@ -506,6 +514,222 @@ 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("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("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(); + 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); @@ -861,7 +1085,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(); @@ -869,7 +1093,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(); }); @@ -2316,6 +2540,10 @@ 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; + /** Replaces the real socket host, for a test that has to control a frame's write. */ + readonly host?: ConnectionHost; } = {}, ) { const directory = @@ -2380,15 +2608,18 @@ 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, + ...(options.processRunner === undefined ? {} : { processRunner: options.processRunner }), queue: engine, reaper, registry, @@ -2406,6 +2637,156 @@ 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({ + 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 | Promise, + ) { + this.#result = new Promise((resolve) => { + this.#resolve = resolve; + }); + } + + emit(stream: "stdout" | "stderr", chunk: string): void | Promise { + return 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) => { @@ -2504,6 +2885,8 @@ function testConfig( iosMaxDevices = 1, ): Config { return { + mode: "worker", + exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, drivers: {}, eventBuffer: { capacity: 100 }, diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 1746f960d..77a127c4c 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -20,10 +20,11 @@ import type { PassthroughResolver, QueueControl, } from "../core/lease-ports.js"; -import type { Clock, IpcConnection, Logger } from "../ports/index.js"; +import type { Clock, IpcConnection, Logger, ProcessRunner } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; import { parseRequestFrame, serializeFrame, type RequestFrame } from "../daemon-protocol/index.js"; import { + describeSchemaIssues, helloRequestSchema, helloReplySchema, leaseRelease, @@ -49,6 +50,13 @@ type RequestId = string | number; interface Connection { readonly socket: IpcConnection; + /** + * Detaches this connection's request-scoped pushes (`progress` for an in-flight + * `lease.request`, `output` for an in-flight `device.exec`) when the socket goes away, so a + * push callback that outlives the connection writes nothing instead of throwing into whatever + * operation is still running. One set for both families: they are disposed for the same + * reason and at the same moment. + */ readonly progressDisposers: Set<() => 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,73 @@ 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), + // 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 { + 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. + * + * 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, + 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 +1296,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/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 173e9d8a6..ab7f794ce 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -1831,6 +1831,154 @@ describe("AndroidDriver.create", () => { ); }); + 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 + // 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"], + ["-H", "other-host", "devices"], + ["-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( + /supplies the adb server itself/, + ); + } + + // 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"], + // `-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", + String(adbServerPort), + ...args, + ]); + } + }); + + 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 + // 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`. 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), + "shell", + "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. + 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 +2364,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 +2375,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 +2382,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..2c90d665c 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"; @@ -239,6 +240,112 @@ 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."; +/** + * 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`). + * + * 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. + * + * 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 -- 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"]; + +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; +} + +/** 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" }; + +/** + * 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 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 { 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, kind: "refused" }; + if (arity === "value") index += 1; + } + 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 { readonly sequence: readonly string[]; readonly reason: string; @@ -255,6 +362,27 @@ const REFUSED_ADB_SEQUENCES: readonly { }, ]; +/** + * Whether this is `adb shell` with nothing after it -- the interactive shell. Recognised by + * 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 { + const walked = walkGlobals(args); + return ( + walked.kind === "subcommand" && + args[walked.index] === "shell" && + walked.index === args.length - 1 + ); +} + const allocationsByRunner = new WeakMap(); /** True when `sequence` appears as consecutive arguments starting anywhere in `args`. */ @@ -457,8 +585,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 +594,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, @@ -482,6 +621,14 @@ export class AndroidDriver implements Driver { `Refusing \`simlock adb ${refused.sequence.join(" ")}\`: ${refused.reason} ${RECLAIM_INSTEAD}`, ); } + + const scopeFlag = callerSuppliedScopeFlag(args); + if (scopeFlag !== undefined) { + throw new PassthroughRefusedError( + this.passthroughTool, + `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.`, + ); + } } /** 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/app.test.ts b/src/http/app.test.ts index f53a5d322..8ea29a5e7 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, }; @@ -697,6 +697,279 @@ 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" }); + + // 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); + 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.onStarted?.(); + 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("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, 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", { + 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.session.onStarted?.(); + operatorCall.resolve({ exitCode: 0 }); + await asOperator; + + // 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", + }); + 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 + // "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", 2); + expect(nullCall.input).toEqual({ args: ["list"], leaseId: "lse_1", tool: "simctl" }); + nullCall.session.onStarted?.(); + nullCall.resolve({ exitCode: 0 }); + await withNulls; + }); + + 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 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", + ); + + 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("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" + // 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); + + // 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(); + }); + }); + 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/http/app.ts b/src/http/app.ts index a0c04db34..8caf15e6e 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"; @@ -18,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 { @@ -70,6 +72,35 @@ 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. + * + * `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.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 { device: body.device, @@ -194,7 +225,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 +363,88 @@ 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 { 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, 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 + // 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). + // 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, ...(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 }), + }), + ) + .then( + (result) => ({ exitCode: result.exitCode, kind: "exited" }) as const, + (error: unknown) => ({ error, kind: "failed" }) as const, + ); + + // 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) { + relay.attach((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(); + }); + // The command keeps running after a client disconnects; what ends here is this + // route's interest in its output, terminally. + return () => relay.drop(); + }, + }); + }, + ); + 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 +650,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..100ab26ec 100644 --- a/src/http/dispatcher-session.ts +++ b/src/http/dispatcher-session.ts @@ -44,6 +44,21 @@ 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. + * + * **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; readonly manageEventSubscription?: (subscribe: boolean) => string | undefined; }, ): DispatchSession { @@ -52,5 +67,7 @@ export function buildHttpSession( principal: identity.requesterId, 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/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 }); }); 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/output-relay.test.ts b/src/http/output-relay.test.ts new file mode 100644 index 000000000..7a5554d0a --- /dev/null +++ b/src/http/output-relay.test.ts @@ -0,0 +1,163 @@ +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 -- 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", () => { + 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(async (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("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 + // memory-exhaustion lever with no cap on it -- which is the same defect as buffering. + const relay = new OutputRelay(); + const written: string[] = []; + relay.attach(async (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("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("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" }); + + 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(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 new file mode 100644 index 000000000..9bc00fc76 --- /dev/null +++ b/src/http/output-relay.ts @@ -0,0 +1,94 @@ +/** + * 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. `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 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 + * 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. 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` + * 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; +} + +/** 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: BufferedChunk[] = []; + #deliver: ((chunk: RelayedChunk) => Promise) | undefined; + #dropped = false; + + /** 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; + } + + /** + * 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). 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); + return new Promise((resolve) => { + this.#buffered.push({ chunk, resolve }); + }); + } + + /** 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; + 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. 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; + const queued = this.#buffered.splice(0); + for (const { resolve } of queued) resolve(); + } +} 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/http/test-fakes.ts b/src/http/test-fakes.ts index 51c256151..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", @@ -22,6 +23,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..6a7573ad1 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 ExecInput, + type ExecOutput, 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"); + execImpl: (input: ExecInput) => Promise = notStubbed("exec"); 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. + exec(input: ExecInput): Promise { + this.calls.push({ input, method: "exec" }); + return this.#dead ? this.#deadConnection() : this.execImpl(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..91b6190a7 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -46,12 +46,17 @@ export { FakeTcpProbe, NodeTcpProbe } from "./tcp-probe.js"; export type { FakeSend } from "./tcp-probe.js"; export type { TcpProbe } from "./tcp-probe.js"; export { + exitCodeOf, + ExecOutputDeliveryStalledError, NodeProcessRunner, type ProcessHandle, ProcessSpawnError, type ProcessResult, type ProcessRunner, type ProcessRunOptions, + type ProcessStreamOptions, ScriptedProcessRunner, type ScriptedProcessExpectation, + type StreamingProcessHandle, + type StreamingProcessResult, } from "./process-runner.js"; diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index abd558c7e..0cf8ae684 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -1,6 +1,30 @@ -import { describe, expect, it } from "vitest"; - -import { NodeProcessRunner, ProcessSpawnError, ScriptedProcessRunner } from "./index.js"; +import { describe, expect, it, vi } from "vitest"; + +import { + exitCodeOf, + ExecOutputDeliveryStalledError, + NodeProcessRunner, + ProcessSpawnError, + 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 () => { @@ -71,6 +95,389 @@ 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}`); + }, + }); + + // 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 () => { + 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" } }, + ]); + + 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("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("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 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; + 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)); + // 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; + }); + 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 }> = []; + + 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("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. + 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("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 + // 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(); + + 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/ports/process-runner.ts b/src/ports/process-runner.ts index 1c91b0cc4..50d55dd6c 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -1,11 +1,14 @@ 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 -// 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` @@ -51,6 +54,70 @@ 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; + /** + * 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 + * `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 +155,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 +231,287 @@ 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; + } +} + +/** + * 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 + * 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`): 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; + /** 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( + private readonly child: ChildProcess, + pid: number, + onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, + ) { + 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 }); + }; + 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) => { + 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 (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; + } + settleWhenDrained(deadline, () => 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; + } + + /** 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", + 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` 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", + // 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; + this.#pendingByStream[name] -= 1; + if (this.#pendingByStream[name] === 0) stream.resume(); + const waiters = this.#deliveryWaiters; + this.#deliveryWaiters = []; + for (const waiter of waiters) waiter(); + }; + void Promise.resolve(delivered).then(settleDelivery, settleDelivery); + }); + } +} + +/** + * 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. + * + * 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; + } + + try { + process.kill(-pid, signal); + } catch (error: unknown) { + if (isNoSuchProcessError(error)) { + return; + } + + throw error; + } } class NodeProcessHandle implements ProcessHandle { @@ -213,20 +568,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 +597,21 @@ 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 }[]; + /** + * 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 { @@ -295,6 +652,109 @@ 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; + + readonly #ignoresSigterm: boolean; + + constructor( + readonly pid: number, + expectation: ScriptedProcessExpectation, + onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, + ) { + this.#ignoresSigterm = expectation.ignoresSigterm ?? false; + this.#result = new Promise((resolve) => { + this.#resolve = resolve; + }); + 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 }); + } + } + + kill(signal: NodeJS.Signals = "SIGTERM"): void { + if (this.#ignoresSigterm && signal !== "SIGKILL") return; + 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.test.ts b/src/simlock-client/client.test.ts index ce48d5c41..35ac48617 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.exec( + { 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 }); diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index ddb03af19..97d550b4b 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, + ExecInput, + ExecOutput, + DeviceOutputChunk, DoctorReport, DoctorRunInput, DriverPassthroughInput, EventPush, + ExecOptions, EventsReplayInput, EventsReplayOutput, LeaseCancelInput, @@ -74,10 +79,14 @@ export type { DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, + ExecInput, + ExecOutput, + DeviceOutputChunk, DoctorReport, DoctorRunInput, DriverPassthroughInput, EventPush, + ExecOptions, 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). + */ + exec(input: ExecInput, options?: ExecOptions): 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(), + exec: () => rejected(), onLeaseLost: () => () => {}, onDeviceUnhealthy: () => () => {}, @@ -410,6 +429,16 @@ class SimlockClientImpl { return this.#call("driver.passthrough", input); } + async exec(input: ExecInput, options: ExecOptions = {}): 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 +657,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 +691,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..c28a58738 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 ExecInput = OpInput<"device.exec">; +/** `{ exitCode }` -- the output itself arrived as `onOutput` chunks while the command ran + * (ADR 0005 §19a). */ +export type ExecOutput = 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 `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; +} + 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;