diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 262d89d3f..0353edd7b 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1481,6 +1481,8 @@ URL answers `404`. token's principal, and the lease ID is the 32-hex ID the CLI chose. `close` ends the agent-device lease and then frees the Simlock lease, so Simlock wipes the device for the next agent. +- **`devices` lists only the agent's own devices.** Before `open` it answers + an empty list; after, the devices Simlock leased to that token. - **Heartbeats keep the lease.** The CLI sends one before every command except `devices`. Once agent-device answers it, Simlock renews the lease to now plus its TTL, unless the lease already runs longer (a longer renewal by the agent @@ -1516,8 +1518,30 @@ the status. - `timed out waiting for a device; nothing was leased`. - `refused by simlock: `: Simlock refused the lease request, for example a model it does not know, or a `ttlMs` above `lease.maxTtlMs`. -- `refused: only iOS and Android`, `refused: name --platform ios or android`. -- `refused: simlock picks the device`: `--udid` or `--serial` on `open`. +- `refused: only iOS and Android`, `refused: name --platform ios or android`, + and `refused: is not available on this simlock` for a platform + whose driver is off on this worker. +- `refused: simlock picks the device`: a `--udid`, `--serial`, `--device` or + device key that is not the device Simlock leased to the agent. A + `--device` naming the leased device's model is sent on as that device's ID. +- `refused: simlock chooses the device set; run disconnect, then connect proxy + without --ios-simulator-device-set` and `refused: simlock chooses the + devices; run disconnect, then connect proxy without + --android-device-allowlist`: on any command. +- `refused: send the app from your machine as an upload`: `install` or + `reinstall` of a path on the worker. +- `refused: no device leased; run open first`: a sharded `test` with no + `--device` from an agent holding no matching device. With a device leased, + Simlock adds the agent's leased devices as `--device`. +- `refused: name the device with --udid ; run devices to see yours`: + `capabilities` or `doctor` that names no device from an agent not holding + exactly one. +- `refused: run devices on its own`, `refused: devices does not stream through + simlock`, `refused: a batch step cannot name another lease`, + `refused: malformed `, `refused: unknown method `, and + `refused: unknown route ` (answered `404`). +- `could not check your leases; try again`: Simlock could not list the + agent's leases within 5 seconds. - `refused: this agent-device is too old for simlock; upgrade it`: the CLI sent no lease ID. - `refused: send lease calls as lease RPCs`: a lease call inside diff --git a/docs/internal/COMPONENTS.md b/docs/internal/COMPONENTS.md index 2370e3817..a531b3a8b 100644 --- a/docs/internal/COMPONENTS.md +++ b/docs/internal/COMPONENTS.md @@ -114,10 +114,10 @@ modules with. | `AgentDeviceSupervisor` | `src/agent-device/host/agent-device-supervisor.ts` | Starting, watching and stopping the one agent-device daemon: reaping one a killed simlock left (by a pid record and an identity check), the private state dir and policy file, the daemon's environment, readiness through `daemon.json`, the port and `/health`, restart on death, and the availability state (`off`, `starting`, `running`, `unavailable` with a reason and remedy). | Serve agent-device traffic; report to `simlock doctor`; decide which devices exist (the drivers' environments do). | | Install lookup, compatibility, daemon environment | `src/agent-device/host/install.ts`, `src/agent-device/shared/` | Finding the agent-device install and its daemon entry; the minimum versions and RPC protocol; the environment and policy data. | Run a process. | | `AgentDeviceHealthProbe` | `src/agent-device/host/health.ts` | The `GET /health` read, with a time limit. | Judge the answer. | -| Front | `src/agent-device/front/` | The `/v1/agent-device/*` mount: the role check, the `/rpc` body check, turning an agent-device `allocate` into a simlock `lease.request` (and its cancel when the CLI leaves) and a `release` into a `lease.release`, the front map of the leases it made, and who ended each; the heartbeat, which renews the simlock lease after agent-device answers, and the renewals while a command runs. | Check a token (the app does); run the proxy. | +| Front | `src/agent-device/front/` | The `/v1/agent-device/*` mount: the role check, the route list, the `/rpc` body check, the request rules (platform, device selectors, device set, sharding, install, `devices`) and the `devices` filter, turning an agent-device `allocate` into a simlock `lease.request` (and its cancel when the CLI leaves) and a `release` into a `lease.release`, the front map of the leases it made, and who ended each; the heartbeat, which renews the simlock lease after agent-device answers, and the renewals while a command runs. | Check a token (the app does); run the proxy. | | `AgentDeviceHost`, `AgentDeviceUpstream` | `src/agent-device/host/host.ts`, `host/upstream.ts` | `@agent-device/proxy` in front of the daemon, one proxy per daemon start; the tenant each request acts as; the port the daemon is reached through and its supervisor adapter. | Know simlock leases. | | `ReleaseScopeRecord`, `AgentDeviceLeaseEnd` | `src/agent-device/host/lease-end.ts` | The host's record of each agent-device lease's release scope (filled by a recording wrapper around the proxy's upstream fetch), and the `LeaseEndParticipant` that, when simlock ends a lease, waits for a running allocate or release and releases the agent-device lease with that scope before the wipe. | Write to the front map; bound a wait with a timer (leasing's signal bounds it). | -| Wire rules | `src/agent-device/shared/` | The path prefixes, the `/rpc` body reader, the call classifier, the lease-call field reader, the release scope reader, the reply reader (an allocate reply is a success only when its release scope passes) and the front's replies. | Decide what a call means. | +| Wire rules | `src/agent-device/shared/` | The path prefixes, the route and RPC method lists, the selector reader, the `/rpc` body reader, the call classifier, the lease-call field reader, the release scope reader, the reply reader (an allocate reply is a success only when its release scope passes) and the front's replies. | Decide what a call means. | | `FakeAgentDevice` | `src/agent-device/testing.ts` | The in-memory agent-device daemon the proxy sits in front of in tests. | Appear in production code. | ## Drivers diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 738406063..8a2ab9d2f 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -112,6 +112,7 @@ function androidDriver(clock: FakeClock): FakeDriver { clock, defaultModels: { phone: ["Pixel 8"] }, knownModels: ["Pixel 8"], + modelAliases: { "Pixel 8": ["P8"] }, modelClasses: { "Pixel 8": "phone" }, platform: "android", }); @@ -1099,6 +1100,31 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(params).not.toHaveProperty("deviceKey"); }); + it("a lease whose allocate reply names device key `ios:mobile:` keeps it: a command naming that lease with that `deviceKey` reaches agent-device", async () => { + const rig = await setUp(); + const key = "ios:mobile:00008110-001A2B3C4D5E"; + rig.fake.nameDeviceKeyInNextReply(key); + await granted(rig, 1); + + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { meta: { deviceKey: key } })); + }); + + it("an allocate reply whose lease `deviceKey` is over 128 characters still succeeds and keeps the lease, with the device key left unset: no release is sent and a command naming the lease with a `deviceKey` is refused", async () => { + const rig = await setUp(); + rig.fake.nameDeviceKeyInNextReply("x".repeat(129)); + + const answer = await envelopeOf(await allocate(rig, 1)); + + expect(answer.error).toBeUndefined(); + expect(rig.fake.rpcRequests("agent_device.lease.release")).toHaveLength(0); + expect((await leases(rig)).map((lease) => lease.id)).toContain(hex(1)); + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { meta: { deviceKey: "x".repeat(129) } }), + simlockPicks, + ); + }); + it("a CLI that hangs up while agent-device makes its lease leaves neither lease: the agent-device lease is released with the reply's scope, then the simlock lease; when that release fails, the simlock lease stays until its TTL", async () => { const rig = await setUp(); rig.fake.holdAllocate(); @@ -1218,7 +1244,13 @@ describe("the agent-device front, through the whole worker daemon", () => { const chunks = ['{"progress":1}\n', '{"progress":2}\n', '{"done":true}\n']; rig.fake.streamNextCommand(chunks); - const streamed = await command(rig, "install", undefined); + const streamed = await command( + rig, + "install", + undefined, + {}, + { meta: { uploadedArtifactId: "art-1" } }, + ); expect(await streamed.text()).toBe(chunks.join("")); @@ -2061,6 +2093,21 @@ describe("simlock ending a simlock lease ends the agent-device session first", ( }); }); + it("release-all while an agent holds a device whose allocate reply named an empty device key (under 1 character) sends agent-device a release without a `deviceKey`", async () => { + const rig = await setUp(); + rig.fake.nameDeviceKeyInNextReply(""); + await granted(rig, 1); + + await releaseAll(rig); + + await expect.poll(() => releasesReceived(rig).length).toBe(1); + expect(releasesReceived(rig)[0]?.params).toEqual({ + ...scope, + leaseId: hex(1), + tenantId: principals.one, + }); + }); + it("an allocate reply whose device key is `ios:mobile:` is recorded, and release-all sends that device key in the release", async () => { const rig = await setUp(); rig.fake.nameDeviceKeyInNextReply("ios:mobile:00008110-001A2B3C4D5E"); @@ -2621,3 +2668,871 @@ describe("FakeAgentDevice as agent-device behaves", () => { ).toBeUndefined(); }); }); + +const simlockPicks = "refused: simlock picks the device"; +const onlyIosAndAndroid = "refused: only iOS and Android"; +const uploadOnly = "refused: send the app from your machine as an upload"; +const noDeviceLeased = "refused: no device leased; run open first"; +const deviceSetRefusal = + "refused: simlock chooses the device set; run disconnect, then connect proxy without --ios-simulator-device-set"; +const allowlistRefusal = + "refused: simlock chooses the devices; run disconnect, then connect proxy without --android-device-allowlist"; + +const bothDrivers = (clock: FakeClock): FakeDriver[] => [iosDriver(clock), androidDriver(clock)]; + +function runCommand( + rig: Rig, + name: string, + n: number | undefined, + fields: Record = {}, + options: Omit = {}, +): Promise { + const { meta, ...rest } = fields; + return command(rig, name, undefined, options, { + ...(n === undefined && meta === undefined + ? {} + : { meta: { ...(n === undefined ? {} : { leaseId: hex(n) }), ...(meta as object) } }), + ...rest, + }); +} + +function idOf(rig: Rig, n: number): string { + const params = receivedAllocate(rig, n); + return String(params["udid"] ?? params["serial"]); +} + +function commandsReceived(rig: Rig) { + return rig.fake.rpcRequests("agent_device.command"); +} + +// why: a refusal test starts from a request that is accepted, then changes one thing (testing rule 2). +async function forwarded( + rig: Rig, + send: () => Promise, +): Promise> { + const before = rig.fake.requests.length; + const answer = await envelopeOf(await send()); + expect(answer.error).toBeUndefined(); + expect(answer.result).toBeDefined(); + expect(rig.fake.requests.length).toBe(before + 1); + return rig.fake.requests.at(-1)?.params as Record; +} + +async function refused(rig: Rig, send: () => Promise, message: string): Promise { + const before = rig.fake.requests.length; + const answer = await envelopeOf(await send()); + expect(answer.error).toMatchObject(refusal(message)); + expect(answer.result).toBeUndefined(); + expect(rig.fake.requests.length).toBe(before); +} + +function flagsOf(params: Record): Record { + return (params["flags"] ?? {}) as Record; +} + +function batch(rig: Rig, n: number | undefined, steps: readonly Record[]) { + return runCommand(rig, "batch", n, { flags: { batchSteps: steps } }); +} + +describe("the agent-device front's request rules", () => { + describe("rule 1, the route", () => { + it.each([ + ["GET", "/health"], + ["POST", "/upload"], + ["POST", "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/upload/preflight"], + ["POST", "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/upload/finalize"], + ["PUT", "/upload/direct/ticket-1"], + ["GET", "/artifacts"], + ["GET", "/artifacts/"], + ["GET", "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/artifacts/a.png"], + ["GET", "/artifacts/dir/a.png"], + ["GET", "/sessions/tok_one:s1/requests/r1/diagnostics"], + ])("%s %s with a token reaches agent-device", async (method, path) => { + const rig = await setUp(); + + const answer = await send(rig, path, { method, ...(method === "GET" ? {} : { body: "{}" }) }); + + await answer.text(); + expect(rig.fake.requests.map((request) => request.path)).toEqual([path]); + }); + + it("POST /rpc with a token reaches agent-device", async () => { + const rig = await setUp(); + + await forwarded(rig, () => runCommand(rig, "snapshot", undefined)); + }); + + it.each([ + ["GET", "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/admin/leases"], + ["POST", "/health"], + ["POST", "/rpcx"], + ["POST", "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/rpc/x"], + ["PUT", "/upload/direct/a/b"], + ["GET", "/sessions/s1/requests/r1/diagnostics/extra"], + ])("%s %s is refused 404 and reaches nothing", async (method, path) => { + const rig = await setUp(); + await (await send(rig, "/health")).text(); + const before = rig.fake.requests.length; + + const answer = await send(rig, path, { method, ...(method === "GET" ? {} : { body: "{}" }) }); + + expect(answer.status).toBe(404); + expect(await bodyOf(answer)).toEqual({ + code: "INVALID_ARGS", + error: `refused: unknown route ${method} ${path}`, + ok: false, + }); + expect(rig.fake.requests.length).toBe(before); + }); + + it("a route refusal answers 404 with `refused: unknown route POST /rpcx`", async () => { + const rig = await setUp(); + + const answer = await send(rig, "/rpcx", { body: "{}" }); + + expect(answer.status).toBe(404); + expect(((await bodyOf(answer)) as { error: string }).error).toBe( + "refused: unknown route POST /rpcx", + ); + }); + + it("a route outside the list answers 401 without a token, and `agent-device is not available on this simlock` while agent-device is unavailable", async () => { + const rig = await setUp(); + expect((await send(rig, "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/admin/leases")).status).toBe(404); + const missing = await send(rig, "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/admin/leases", { token: null }); + expect(missing.status).toBe(401); + rig.fake.setUnavailable("found 0.20.3, need 0.21.25 or later"); + + const unavailable = await send(rig, "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/admin/leases"); + + expect(await unavailable.text()).toContain(`${notAvailable}found 0.20.3`); + expect(rig.fake.requests).toEqual([]); + }); + }); + + describe("rule 2, the RPC method", () => { + it("an unknown RPC method is refused, and `agent-device.command` with a dash is forwarded", async () => { + const rig = await setUp(); + await forwarded(rig, () => rpc(rig, "agent-device.command", { command: "snapshot" })); + + await refused( + rig, + () => rpc(rig, "agent_device.admin", { command: "snapshot" }), + "refused: unknown method agent_device.admin", + ); + }); + }); + + describe("rule 4, the platform", () => { + it("a command with `--platform android` is forwarded; with `macos` or `apple`, or `runtime.platform` `harmonyos`, it is refused", async () => { + const rig = await setUp({ drivers: bothDrivers }); + await forwarded(rig, () => + runCommand(rig, "snapshot", undefined, { flags: { platform: "android" } }), + ); + + for (const platform of ["macos", "apple"]) { + await refused( + rig, + () => runCommand(rig, "snapshot", undefined, { flags: { platform } }), + onlyIosAndAndroid, + ); + } + await refused( + rig, + () => runCommand(rig, "snapshot", undefined, { runtime: { platform: "harmonyos" } }), + onlyIosAndAndroid, + ); + }); + + it("a command with `--platform ios` while the iOS driver is off is refused with `refused: ios is not available on this simlock`", async () => { + const rig = await setUp({ drivers: (clock) => [androidDriver(clock)] }); + await forwarded(rig, () => + runCommand(rig, "snapshot", undefined, { flags: { platform: "android" } }), + ); + + await refused( + rig, + () => runCommand(rig, "snapshot", undefined, { flags: { platform: "ios" } }), + "refused: ios is not available on this simlock", + ); + }); + + it("a batch step whose `runtime.platform` is `web` is refused", async () => { + const rig = await setUp(); + await forwarded(rig, () => + batch(rig, undefined, [{ command: "snapshot", runtime: { platform: "ios" } }]), + ); + + await refused( + rig, + () => batch(rig, undefined, [{ command: "snapshot", runtime: { platform: "web" } }]), + onlyIosAndAndroid, + ); + }); + + it("a batch step with `platform: web` is refused and no step reaches agent-device", async () => { + const rig = await setUp(); + const steps = [{ command: "snapshot", flags: { platform: "ios" } }]; + await forwarded(rig, () => batch(rig, undefined, steps)); + + await refused( + rig, + () => + batch(rig, undefined, [...steps, { command: "snapshot", flags: { platform: "web" } }]), + onlyIosAndAndroid, + ); + expect(commandsReceived(rig)).toHaveLength(1); + }); + + it("`install_from_source` with a URL source and platform `ios` is forwarded, as today; with platform `web` it is refused", async () => { + const rig = await setUp(); + const params = (platform: string) => ({ + platform, + source: { kind: "url", url: "https://example.com/App.zip" }, + }); + await forwarded(rig, () => rpc(rig, "agent_device.install_from_source", params("ios"))); + + await refused( + rig, + () => rpc(rig, "agent_device.install_from_source", params("web")), + onlyIosAndAndroid, + ); + }); + }); + + describe("rule 6, device selectors", () => { + it("`udid` and `serial` of the agent's own leased device are forwarded; another device's are refused, in `flags` and in `input` alike", async () => { + const rig = await setUp({ drivers: bothDrivers }); + await granted(rig, 1); + await granted(rig, 2, { device: "Pixel 8", platform: "android" }); + await granted(rig, 3, {}, { token: secrets.two }); + const own = idOf(rig, 1); + const ownSerial = idOf(rig, 2); + const other = idOf(rig, 3); + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { flags: { udid: own } })); + await forwarded(rig, () => runCommand(rig, "snapshot", 2, { flags: { serial: ownSerial } })); + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { input: { udid: own } })); + + const attempts: [number, Record][] = [ + [1, { flags: { udid: other } }], + [1, { input: { udid: other } }], + [2, { flags: { serial: other } }], + [2, { input: { serial: other } }], + ]; + for (const [lease, fields] of attempts) { + await refused(rig, () => runCommand(rig, "snapshot", lease, fields), simlockPicks); + } + }); + + it("`--device` with the leased device's id, and its name with `_` for a space, extra spaces and other letter case, are forwarded unchanged", async () => { + const rig = await setUp(); + rig.fake.nameDeviceInNextReply({ name: "Sim Lock Phone" }); + await granted(rig, 1); + const own = idOf(rig, 1); + + for (const device of [own, "Sim Lock Phone", "sim_lock_phone", " SIM lock phone "]) { + const params = await forwarded(rig, () => + runCommand(rig, "snapshot", 1, { flags: { device } }), + ); + expect(flagsOf(params)["device"]).toBe(device); + } + }); + + it("`--device` with the leased model, or a catalog alias of it, reaches agent-device as `udid` of the leased device on iOS and `serial` on Android, with no `device`; another model is refused", async () => { + const rig = await setUp({ drivers: bothDrivers }); + await granted(rig, 1, { device: "iPhone 17 Pro" }); + await granted(rig, 2, { device: "Pixel 8", platform: "android" }); + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { flags: { udid: idOf(rig, 1) } })); + + const ios = flagsOf( + await forwarded(rig, () => + runCommand(rig, "snapshot", 1, { flags: { device: "iphone 17 pro" } }), + ), + ); + const android = flagsOf( + await forwarded(rig, () => runCommand(rig, "snapshot", 2, { flags: { device: "p8" } })), + ); + + expect(ios["udid"]).toBe(idOf(rig, 1)); + expect(ios).not.toHaveProperty("device"); + expect(android["serial"]).toBe(idOf(rig, 2)); + expect(android).not.toHaveProperty("device"); + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { flags: { device: "iPhone 16" } }), + simlockPicks, + ); + }); + + it("`--device` with the leased model in `input` is removed from `input` and sent as `flags.udid`", async () => { + const rig = await setUp(); + await granted(rig, 1, { device: "iPhone 17 Pro" }); + + const params = await forwarded(rig, () => + runCommand(rig, "snapshot", 1, { input: { device: "iPhone 17 Pro" } }), + ); + + expect(flagsOf(params)["udid"]).toBe(idOf(rig, 1)); + expect(params["input"] ?? {}).not.toHaveProperty("device"); + }); + + it("`test --device ,` is forwarded; for an agent holding two devices, `test --device \", ,,\"` is forwarded; a list with an entry naming another token's device, or the leased device's model, is refused", async () => { + const rig = await setUp(); + rig.fake.nameDeviceInNextReply({ name: "Sim Lock Phone" }); + await granted(rig, 1, { device: "iPhone 17 Pro" }); + await granted(rig, 2); + await granted(rig, 3, {}, { token: secrets.two }); + const [a, b, other] = [idOf(rig, 1), idOf(rig, 2), idOf(rig, 3)]; + const test = (device: string) => runCommand(rig, "test", 1, { flags: { device } }); + await forwarded(rig, () => test(`${a},Sim Lock Phone`)); + await forwarded(rig, () => test(` ${a}, ,${b},`)); + + await refused(rig, () => test(`${a},${other}`), simlockPicks); + await refused(rig, () => test(`${a},iPhone 17 Pro`), simlockPicks); + }); + + it("`test --device ` with no lease named is forwarded; naming the device of the token's own ended lease it is refused", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + await granted(rig, 2, { ttlMs: 600_000 }); + const [ended, alive] = [idOf(rig, 1), idOf(rig, 2)]; + await forwarded(rig, () => runCommand(rig, "test", undefined, { flags: { device: ended } })); + await rig.daemon.dispatch("lease.release", { leaseId: hex(1) }, sessionFor(principals.one)); + await expect.poll(() => listed(rig)).toEqual([hex(2)]); + + await forwarded(rig, () => runCommand(rig, "test", undefined, { flags: { device: alive } })); + await refused( + rig, + () => runCommand(rig, "test", undefined, { flags: { device: ended } }), + simlockPicks, + ); + }); + + it("with no lease named, a command with `udid`, one with `serial` and one with `device` are each refused", async () => { + const rig = await setUp(); + await granted(rig, 1); + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { flags: { udid: idOf(rig, 1) } })); + + for (const flags of [ + { udid: idOf(rig, 1) }, + { serial: "emulator-5554" }, + { device: "iPhone 16" }, + ]) { + await refused(rig, () => runCommand(rig, "snapshot", undefined, { flags }), simlockPicks); + } + }); + + it("with no lease named and no selector, a command reaches agent-device unchanged", async () => { + const rig = await setUp(); + const fields = { flags: { session: "main" }, positionals: ["a"] }; + + const params = await forwarded(rig, () => runCommand(rig, "snapshot", undefined, fields)); + + expect(params).toMatchObject({ command: "snapshot", ...fields }); + expect(Object.keys(flagsOf(params))).toEqual(["session"]); + }); + + it("a command naming its lease only in `flags.leaseId`, with its own udid, is forwarded", async () => { + const rig = await setUp(); + await granted(rig, 1); + const own = idOf(rig, 1); + await refused( + rig, + () => runCommand(rig, "snapshot", undefined, { flags: { udid: own } }), + simlockPicks, + ); + + await forwarded(rig, () => + runCommand(rig, "snapshot", undefined, { flags: { leaseId: hex(1), udid: own } }), + ); + }); + + it("a command naming agent B's lease with that lease's udid is refused; an agent holding two devices is refused lease B's udid on a command for lease A", async () => { + const rig = await setUp(); + await granted(rig, 1); + await granted(rig, 2); + await granted(rig, 3, {}, { token: secrets.two }); + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { flags: { udid: idOf(rig, 1) } })); + + await refused( + rig, + () => runCommand(rig, "snapshot", 3, { flags: { udid: idOf(rig, 3) } }), + simlockPicks, + ); + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { flags: { udid: idOf(rig, 2) } }), + simlockPicks, + ); + }); + + it("a command naming its lease with that lease's `deviceKey` is forwarded; with another lease's `deviceKey`, in `meta` or only in `flags`, it is refused; with no lease named, a stale `deviceKey` is forwarded", async () => { + const rig = await setUp(); + rig.fake.nameDeviceKeyInNextReply("key-1"); + await granted(rig, 1); + rig.fake.nameDeviceKeyInNextReply("key-2"); + await granted(rig, 2); + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { meta: { deviceKey: "key-1" } })); + + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { meta: { deviceKey: "key-2" } }), + simlockPicks, + ); + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { flags: { deviceKey: "key-2" } }), + simlockPicks, + ); + await forwarded(rig, () => + runCommand(rig, "snapshot", undefined, { meta: { deviceKey: "key-2" } }), + ); + }); + + it("a batch step with another device's udid is refused and no step reaches agent-device", async () => { + const rig = await setUp(); + await granted(rig, 1); + await granted(rig, 2, {}, { token: secrets.two }); + const steps = [{ command: "snapshot", flags: { udid: idOf(rig, 1) } }]; + await forwarded(rig, () => batch(rig, 1, steps)); + + await refused( + rig, + () => batch(rig, 1, [...steps, { command: "snapshot", flags: { udid: idOf(rig, 2) } }]), + simlockPicks, + ); + expect(commandsReceived(rig)).toHaveLength(1); + }); + + it("in a batch, a step with the leased model reaches agent-device with the leased id, a sharded `test` step is filled as rule 7 says, and a step naming another lease is refused", async () => { + const rig = await setUp(); + await granted(rig, 1, { device: "iPhone 17 Pro" }); + await granted(rig, 2, {}, { token: secrets.two }); + + const params = await forwarded(rig, () => + batch(rig, 1, [ + { command: "snapshot", flags: { device: "iPhone 17 Pro" } }, + { command: "test", flags: { shardAll: 2 } }, + ]), + ); + + const steps = flagsOf(params)["batchSteps"] as { flags: Record }[]; + expect(steps[0]?.flags["udid"]).toBe(idOf(rig, 1)); + expect(steps[0]?.flags).not.toHaveProperty("device"); + expect(steps[1]?.flags["device"]).toBe(idOf(rig, 1)); + await refused( + rig, + () => batch(rig, 1, [{ command: "snapshot", flags: { leaseId: hex(2) } }]), + "refused: a batch step cannot name another lease", + ); + }); + + it("a `udid` that is a number is refused with `refused: malformed udid`; a `shardAll` that is a string with `refused: malformed shardAll`", async () => { + const rig = await setUp(); + await granted(rig, 1); + await forwarded(rig, () => runCommand(rig, "test", 1, { flags: { shardAll: 2 } })); + + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { flags: { udid: 12 } }), + "refused: malformed udid", + ); + await refused( + rig, + () => runCommand(rig, "test", 1, { flags: { shardAll: "2" } }), + "refused: malformed shardAll", + ); + }); + + it("after simlock ended the lease, a command with that lease's udid is forwarded and agent-device's answer reaches the CLI; one TTL later the same command is refused with `refused: simlock picks the device`", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + const own = idOf(rig, 1); + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + await expect.poll(() => listed(rig)).toEqual([]); + + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { flags: { udid: own } })); + await advance(rig, 61_000, 5_000); + + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { flags: { udid: own } }), + simlockPicks, + ); + }); + }); + + describe("rule 5, device set and allowlist", () => { + it("`--ios-simulator-device-set` naming any directory is refused with the disconnect-and-reconnect message, on a command and on an allocate", async () => { + const rig = await setUp(); + await forwarded(rig, () => runCommand(rig, "snapshot", undefined)); + const set = "/var/simlock/devices"; + + await refused( + rig, + () => runCommand(rig, "snapshot", undefined, { flags: { iosSimulatorDeviceSet: set } }), + deviceSetRefusal, + ); + await refused(rig, () => allocate(rig, 1, { iosSimulatorDeviceSet: set }), deviceSetRefusal); + expect(await requestedSpecs(rig, principals.one)).toEqual([]); + }); + + it("`--android-device-allowlist` is refused with its disconnect-and-reconnect message, on a command and in a batch step", async () => { + const rig = await setUp(); + await forwarded(rig, () => batch(rig, undefined, [{ command: "snapshot" }])); + + await refused( + rig, + () => + runCommand(rig, "snapshot", undefined, { + flags: { androidDeviceAllowlist: "emulator-5554" }, + }), + allowlistRefusal, + ); + await refused( + rig, + () => + batch(rig, undefined, [ + { command: "snapshot", flags: { androidDeviceAllowlist: "emulator-5554" } }, + ]), + allowlistRefusal, + ); + }); + }); + + describe("rule 7, sharding", () => { + const shard = ( + rig: Rig, + n: number | undefined, + flags: Record = {}, + token: string = secrets.one, + ) => runCommand(rig, "test", n, { flags: { shardAll: 2, ...flags } }, { token }); + + it("`test --shard-all 2` with no `--device` reaches agent-device with `device` set to the token's leased devices, for an agent holding one device and one holding two, while another token's leased device is left out", async () => { + const rig = await setUp(); + await granted(rig, 1); + await granted(rig, 2, {}, { token: secrets.two }); + await granted(rig, 3, {}, { token: secrets.two }); + + const one = await forwarded(rig, () => shard(rig, 1)); + const two = await forwarded(rig, () => shard(rig, 2, {}, secrets.two)); + + expect(flagsOf(one)["device"]).toBe(idOf(rig, 1)); + expect(String(flagsOf(two)["device"]).split(",").sort()).toEqual( + [idOf(rig, 2), idOf(rig, 3)].sort(), + ); + }); + + it("`test --platform ios --shard-all 1` gets only the simulator's id, `--target tv` only the TV's id (a device whose reply named no target counts as `mobile`), and `--platform android` from a token holding only the simulator is refused", async () => { + const rig = await setUp({ drivers: bothDrivers }); + await granted(rig, 1); + await granted(rig, 2, { device: "Pixel 8", platform: "android" }); + rig.fake.nameDeviceInNextReply({ target: "tv" }); + await granted(rig, 3, { device: "Apple TV 4K", target: "tv" }); + + const ios = await forwarded(rig, () => + shard(rig, 1, { platform: "ios", shardAll: 1, target: "mobile" }), + ); + const tv = await forwarded(rig, () => shard(rig, 1, { shardAll: 1, target: "tv" })); + const android = await forwarded(rig, () => + shard(rig, 2, { platform: "android", shardAll: 1 }), + ); + + expect(flagsOf(ios)["device"]).toBe(idOf(rig, 1)); + expect(flagsOf(tv)["device"]).toBe(idOf(rig, 3)); + expect(flagsOf(android)["device"]).toBe(idOf(rig, 2)); + const iosOnly = await setUp({ drivers: bothDrivers }); + await granted(iosOnly, 1); + await forwarded(iosOnly, () => shard(iosOnly, 1, { platform: "ios", shardAll: 1 })); + await refused( + iosOnly, + () => shard(iosOnly, 1, { platform: "android", shardAll: 1 }), + noDeviceLeased, + ); + }); + + it('`test --shard-split 2` with `device: " , "` is filled as if no list were sent; from a token that holds no device it is refused with `refused: no device leased; run open first`', async () => { + const rig = await setUp(); + await granted(rig, 1); + const split = (token: string, n: number | undefined) => + runCommand(rig, "test", n, { flags: { device: " , ", shardSplit: 2 } }, { token }); + + const params = await forwarded(rig, () => split(secrets.one, 1)); + + expect(flagsOf(params)["device"]).toBe(idOf(rig, 1)); + await refused(rig, () => split(secrets.two, undefined), noDeviceLeased); + }); + }); + + describe("rule 8, install", () => { + it('`install` with `meta.uploadedArtifactId` is forwarded; without it, with `""` and with `" "` it is refused with `send the app from your machine as an upload`', async () => { + const rig = await setUp(); + const install = (meta: Record) => + runCommand(rig, "install", undefined, { + meta, + positionals: ["MyApp", "remote:/Users/ci/MyApp.app"], + }); + await forwarded(rig, () => install({ uploadedArtifactId: "art-1" })); + + await refused(rig, () => install({}), uploadOnly); + await refused(rig, () => install({ uploadedArtifactId: "" }), uploadOnly); + await refused(rig, () => install({ uploadedArtifactId: " " }), uploadOnly); + }); + + it('`reinstall` without an upload is refused; batch steps `install` and `" Install "` are refused and no step reaches agent-device', async () => { + const rig = await setUp(); + await forwarded(rig, () => + runCommand(rig, "reinstall", undefined, { meta: { uploadedArtifactId: "art-1" } }), + ); + await forwarded(rig, () => batch(rig, undefined, [{ command: "snapshot" }])); + const before = commandsReceived(rig).length; + + await refused(rig, () => runCommand(rig, "reinstall", undefined), uploadOnly); + await refused(rig, () => batch(rig, undefined, [{ command: "install" }]), uploadOnly); + await refused( + rig, + () => batch(rig, undefined, [{ command: "snapshot" }, { command: " Install " }]), + uploadOnly, + ); + expect(commandsReceived(rig)).toHaveLength(before); + }); + + it("a batch with an upload in `meta` still refuses its `install` step, and forwards when it has no install step", async () => { + const rig = await setUp(); + const withUpload = (steps: readonly Record[]) => + runCommand(rig, "batch", undefined, { + flags: { batchSteps: steps }, + meta: { uploadedArtifactId: "art-1" }, + }); + await forwarded(rig, () => withUpload([{ command: "snapshot" }])); + const before = commandsReceived(rig).length; + + await refused(rig, () => withUpload([{ command: "install" }]), uploadOnly); + expect(commandsReceived(rig)).toHaveLength(before); + }); + }); + + describe("rule 9, batch devices", () => { + it('batch steps `devices` and `" DEVICES "` are refused', async () => { + const rig = await setUp(); + await forwarded(rig, () => batch(rig, undefined, [{ command: "snapshot" }])); + + for (const step of ["devices", " DEVICES "]) { + await refused( + rig, + () => batch(rig, undefined, [{ command: step }]), + "refused: run devices on its own", + ); + } + }); + }); + + describe("the devices filter", () => { + const three = [{ id: "d-1" }, { id: "d-2" }, { id: "d-3" }]; + const listedIds = async (response: Response): Promise => { + const answer = await envelopeOf(response); + const data = answer.result?.["data"] as { devices: { id: string }[] } | undefined; + expect(Array.isArray(data?.devices), "expected a devices list in result.data").toBe(true); + return data?.devices.map((device) => device.id); + }; + + it("`devices` before open answers an empty list while agent-device lists three devices; after open it answers only the leased device, without agent B's", async () => { + const rig = await setUp(); + await granted(rig, 2, {}, { token: secrets.two }); + rig.fake.listDevices([...three, { id: idOf(rig, 2) }]); + const before = commandsReceived(rig).length; + + expect(await listedIds(await runCommand(rig, "devices", undefined))).toEqual([]); + expect(commandsReceived(rig)).toHaveLength(before + 1); + await granted(rig, 1); + rig.fake.listDevices([...three, { id: idOf(rig, 2) }, { id: idOf(rig, 1) }]); + + expect(await listedIds(await runCommand(rig, "devices", 1))).toEqual([idOf(rig, 1)]); + }); + + it("`devices` for an agent holding two devices answers both, and after simlock released one of the two leases (no heartbeat sent since), only the other", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + await granted(rig, 2, { ttlMs: 600_000 }); + rig.fake.listDevices([...three, { id: idOf(rig, 1) }, { id: idOf(rig, 2) }]); + + expect( + ((await listedIds(await runCommand(rig, "devices", undefined))) as string[]).sort(), + ).toEqual([idOf(rig, 1), idOf(rig, 2)].sort()); + await rig.daemon.dispatch("lease.release", { leaseId: hex(1) }, adminSession); + await expect.poll(() => listed(rig)).toEqual([hex(2)]); + + expect(await listedIds(await runCommand(rig, "devices", undefined))).toEqual([idOf(rig, 2)]); + }); + + it("a `devices` error answer from agent-device passes unchanged; a success with no list at `data.devices`, a body over 1 MiB, a non-JSON body and a list holding a non-object each answer an empty list; `devices` with `meta.requestProgress` is refused", async () => { + const rig = await setUp(); + await granted(rig, 1); + rig.fake.listDevices([{ id: idOf(rig, 1) }]); + expect(await listedIds(await runCommand(rig, "devices", 1))).toEqual([idOf(rig, 1)]); + + const failure = { + error: { + code: -32000, + data: { code: "COMMAND_FAILED", message: "inventory down" }, + message: "inventory down", + }, + id: 1, + jsonrpc: "2.0", + }; + rig.fake.answerDevicesWith(JSON.stringify(failure)); + expect(await envelopeOf(await runCommand(rig, "devices", 1))).toMatchObject({ + error: { message: "inventory down" }, + }); + const unusable = [ + JSON.stringify({ id: 1, jsonrpc: "2.0", result: { data: {}, ok: true } }), + JSON.stringify({ + id: 1, + jsonrpc: "2.0", + result: { + data: { devices: [{ id: idOf(rig, 1) }], pad: "x".repeat(1024 * 1024) }, + ok: true, + }, + }), + "not json", + JSON.stringify({ + id: 1, + jsonrpc: "2.0", + result: { data: { devices: [{ id: idOf(rig, 1) }, "stray"] }, ok: true }, + }), + ]; + for (const body of unusable) { + rig.fake.answerDevicesWith(body); + expect(await listedIds(await runCommand(rig, "devices", 1))).toEqual([]); + } + await refused( + rig, + () => runCommand(rig, "devices", 1, { meta: { requestProgress: true } }), + "refused: devices does not stream through simlock", + ); + }); + }); + + describe("the token's leased devices", () => { + it("a `test` shard fill whose lease check fails answers `COMMAND_FAILED` with `could not check your leases; try again` and reaches nothing", async () => { + const rig = await setUp(); + await granted(rig, 1); + const tap = tapDispatch(rig); + const sharded = () => runCommand(rig, "test", 1, { flags: { shardAll: 2 } }); + await forwarded(rig, sharded); + tap.rejectNext("lease.list"); + const before = rig.fake.requests.length; + + const answer = await envelopeOf(await sharded()); + + expect(answer.error).toMatchObject({ + data: { code: "COMMAND_FAILED", message: "could not check your leases; try again" }, + }); + expect(rig.fake.requests.length).toBe(before); + }); + + it("a `devices` whose lease check fails answers `COMMAND_FAILED` with `could not check your leases; try again`, not an empty list", async () => { + const rig = await setUp(); + await granted(rig, 1); + rig.fake.listDevices([{ id: idOf(rig, 1) }]); + const tap = tapDispatch(rig); + tap.rejectNext("lease.list"); + + const answer = await envelopeOf(await runCommand(rig, "devices", 1)); + + expect(answer.error).toMatchObject({ + data: { code: "COMMAND_FAILED", message: "could not check your leases; try again" }, + }); + }); + + it("a batch whose `batchSteps` is not a list is refused with `refused: malformed batchSteps`", async () => { + const rig = await setUp(); + await forwarded(rig, () => batch(rig, undefined, [{ command: "snapshot" }])); + + await refused( + rig, + () => runCommand(rig, "batch", undefined, { flags: { batchSteps: "snapshot" } }), + "refused: malformed batchSteps", + ); + }); + + it("a `flags`, `input` or `runtime` that is not an object, a batch step that is not an object or whose `command` is not a string, and a `meta.deviceKey` that is not a string are each refused with their `malformed` message", async () => { + const rig = await setUp(); + await granted(rig, 1); + await forwarded(rig, () => runCommand(rig, "snapshot", 1, { flags: {} })); + + for (const key of ["flags", "input", "runtime"]) { + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { [key]: "text" }), + `refused: malformed ${key}`, + ); + } + await refused( + rig, + () => batch(rig, 1, ["snapshot"] as unknown as Record[]), + "refused: malformed batchSteps", + ); + await refused(rig, () => batch(rig, 1, [{ command: 5 }]), "refused: malformed command"); + await refused( + rig, + () => runCommand(rig, "snapshot", 1, { meta: { deviceKey: 5 } }), + "refused: malformed deviceKey", + ); + }); + }); + + describe("rule 10, commands agent-device runs without a lease", () => { + it("`capabilities` with no selector reaches agent-device with the leased device's id; from a token holding no device it is refused; `doctor` the same", async () => { + const rig = await setUp(); + await granted(rig, 1); + for (const name of ["capabilities", "doctor"]) { + const params = await forwarded(rig, () => runCommand(rig, name, 1)); + expect(flagsOf(params)["udid"]).toBe(idOf(rig, 1)); + await refused( + rig, + () => runCommand(rig, name, undefined, {}, { token: secrets.two }), + "refused: name the device with --udid ; run devices to see yours", + ); + } + }); + + it("`capabilities` naming no lease is filled with the token's only device; with two devices it is refused unless `platform` leaves one, and then it gets that device's `serial` on Android", async () => { + const rig = await setUp({ drivers: bothDrivers }); + await granted(rig, 1, {}, { token: secrets.two }); + const only = await forwarded(rig, () => + runCommand(rig, "capabilities", undefined, {}, { token: secrets.two }), + ); + expect(flagsOf(only)["udid"]).toBe(idOf(rig, 1)); + + await granted(rig, 2, { device: "Pixel 8", platform: "android" }, { token: secrets.two }); + await refused( + rig, + () => runCommand(rig, "capabilities", undefined, {}, { token: secrets.two }), + "refused: name the device with --udid ; run devices to see yours", + ); + const android = await forwarded(rig, () => + runCommand( + rig, + "capabilities", + undefined, + { flags: { platform: "android" } }, + { token: secrets.two }, + ), + ); + expect(flagsOf(android)["serial"]).toBe(idOf(rig, 2)); + expect(flagsOf(android)).not.toHaveProperty("udid"); + }); + }); + + describe("commands the policy file refuses", () => { + it("`boot` passes the rules and reaches agent-device, as before this PR", async () => { + const rig = await setUp(); + await granted(rig, 1); + + const params = await forwarded(rig, () => runCommand(rig, "boot", 1)); + + expect(params["command"]).toBe("boot"); + }); + }); +}); diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index 2078b6f77..4046cd32d 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -6,12 +6,15 @@ import { mapError } from "../../http/errors.js"; import type { TokenIdentity } from "../../http/token-store.js"; import type { Clock } from "../../ports/index.js"; import { frontReply, failure, refusal, type FrontReply } from "../shared/replies.js"; +import { validDeviceKey } from "../shared/release-scope.js"; import { leaseCallFields, leaseIdOf, type RpcRead } from "../shared/rpc.js"; +import { addressField, asRecord } from "../shared/selectors.js"; import { ALLOCATE_SCOPE_KEYS, REPLY_SCOPE_KEYS, exchange, leaseCall, + listLeases, releaseAgentDevice, releaseSimlock, relay, @@ -55,12 +58,6 @@ function notPlain(params: Record): boolean { function deviceRefusal(fields: ReturnType): FrontReply | undefined { if (!present(fields.platform)) return refusal("refused: name --platform ios or android"); - if (fields.platform !== "ios" && fields.platform !== "android") { - return refusal("refused: only iOS and Android"); - } - if (present(fields.udid) || present(fields.serial)) { - return refusal("refused: simlock picks the device"); - } return undefined; } @@ -216,7 +213,7 @@ function forwardedBody( params: { ...rest, ttlMs: ceiling, - ...(plan.platform === "ios" ? { udid: address } : { serial: address }), + [addressField(plan.platform)]: address, }, }; } @@ -284,7 +281,10 @@ async function keepOrRelease( address, deadline: grant.lease.ttlDeadline, identity, + model: grant.device.spec.model, + platform: plan.platform, ttlMs: grant.lease.ttlMs, + ...replyFacts(reading.result), }); return relay(reply); } @@ -319,22 +319,16 @@ async function settleNoReply( if (!holds) await releaseSimlock(context, identity, plan.leaseId); } -const LIST_TIMEOUT_MS = 5_000; +function replyFacts(result: Record) { + const device = asRecord(result["device"]); + const deviceKey = asRecord(result["lease"])?.["deviceKey"]; + return { + ...(device === undefined ? {} : { target: stringOr(device["target"], "mobile") }), + ...(typeof device?.["name"] === "string" ? { name: device["name"] } : {}), + ...(validDeviceKey(deviceKey) ? { deviceKey } : {}), + }; +} -async function listLeases(context: FrontContext, identity: TokenIdentity) { - let timer: ReturnType | undefined; - const timeout = new Promise((_resolve, reject) => { - timer = context.clock.setTimer(LIST_TIMEOUT_MS, () => - reject(new Error("lease.list timed out")), - ); - }); - try { - const { leases } = await Promise.race([ - context.dispatch("lease.list", {}, buildHttpSession(identity)), - timeout, - ]); - return leases.map((lease) => ({ id: lease.id, ttlDeadline: lease.ttlDeadline })); - } finally { - if (timer !== undefined) context.clock.cancel(timer); - } +function stringOr(value: unknown, fallback: string): string { + return typeof value === "string" ? value : fallback; } diff --git a/src/agent-device/front/context.ts b/src/agent-device/front/context.ts index af5a8157f..b3c575590 100644 --- a/src/agent-device/front/context.ts +++ b/src/agent-device/front/context.ts @@ -124,3 +124,23 @@ export async function releaseAgentDevice( identity, ); } + +const LIST_TIMEOUT_MS = 5_000; + +export async function listLeases(context: FrontContext, identity: TokenIdentity) { + let timer: ReturnType | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = context.clock.setTimer(LIST_TIMEOUT_MS, () => + reject(new Error("lease.list timed out")), + ); + }); + try { + const { leases } = await Promise.race([ + context.dispatch("lease.list", {}, buildHttpSession(identity)), + timeout, + ]); + return leases.map((lease) => ({ id: lease.id, ttlDeadline: lease.ttlDeadline })); + } finally { + if (timer !== undefined) context.clock.cancel(timer); + } +} diff --git a/src/agent-device/front/devices-filter.ts b/src/agent-device/front/devices-filter.ts new file mode 100644 index 000000000..7ab11033a --- /dev/null +++ b/src/agent-device/front/devices-filter.ts @@ -0,0 +1,42 @@ +import type { TokenIdentity } from "../../http/token-store.js"; +import { failure, frontReply } from "../shared/replies.js"; +import { readBounded, readReply } from "../shared/rpc.js"; +import { asRecord } from "../shared/selectors.js"; +import { relay, type FrontContext } from "./context.js"; +import { LeaseCheckFailed, tokenDevices } from "./token-devices.js"; + +function emptyList(rpc: { readonly id: unknown }): Response { + return Response.json({ + id: rpc.id, + jsonrpc: "2.0", + result: { data: { devices: [] }, ok: true }, + }); +} + +export async function filterDevices( + context: FrontContext, + identity: TokenIdentity, + response: Response, + rpc: { readonly id: unknown }, +): Promise { + const text = await readBounded(response.body); + if (text === undefined) return emptyList(rpc); + const reading = readReply(text); + if (reading.kind === "error") return relay({ response, text }); + const devices = asRecord(reading.kind === "success" ? reading.result["data"] : undefined)?.[ + "devices" + ]; + if (reading.kind !== "success" || !Array.isArray(devices)) return emptyList(rpc); + if (!devices.every((device) => asRecord(device) !== undefined)) return emptyList(rpc); + let held: Set; + try { + held = new Set((await tokenDevices(context, identity)).map((device) => device.address)); + } catch (error) { + if (!(error instanceof LeaseCheckFailed)) throw error; + return frontReply(failure(error.message), rpc); + } + const kept = devices.filter((device) => held.has(String(asRecord(device)?.["id"]))); + const body = JSON.parse(text) as { result: { data: Record } }; + body.result.data["devices"] = kept; + return relay({ response, text: JSON.stringify(body) }); +} diff --git a/src/agent-device/front/front-map.ts b/src/agent-device/front/front-map.ts index 2fa243482..b7698ebf4 100644 --- a/src/agent-device/front/front-map.ts +++ b/src/agent-device/front/front-map.ts @@ -3,7 +3,15 @@ import type { Clock } from "../../ports/index.js"; const MAX_PRINCIPALS_PER_REFRESH = 100; -export interface FrontMapEntry { +interface DeviceFacts { + readonly platform?: "ios" | "android"; + readonly model?: string; + readonly name?: string; + readonly target?: string; + readonly deviceKey?: string; +} + +export interface FrontMapEntry extends DeviceFacts { readonly identity: TokenIdentity; readonly address: string; readonly ttlMs: number; @@ -12,7 +20,7 @@ export interface FrontMapEntry { export type EndedBy = "agent" | "simlock"; -export interface HeldView { +export interface HeldView extends DeviceFacts { readonly identity: TokenIdentity; readonly address: string; readonly ttlMs: number; @@ -25,7 +33,7 @@ export interface ListedLease { readonly ttlDeadline: number; } -interface Held { +interface Held extends DeviceFacts { readonly identity: TokenIdentity; readonly address: string; ttlMs: number; @@ -65,6 +73,13 @@ export class FrontMap { return this.#held.get(leaseId); } + liveOf(requesterId: string): readonly (HeldView & { readonly leaseId: string })[] { + this.#prune(); + return [...this.#held] + .filter(([, held]) => held.identity.requesterId === requesterId && held.endedAt === undefined) + .map(([leaseId, held]) => ({ ...held, leaseId })); + } + setTtl(leaseId: string, ttlMs: number): void { const held = this.#held.get(leaseId); if (held !== undefined) held.ttlMs = ttlMs; diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index 209acbe50..431ad0e30 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -2,17 +2,22 @@ import type { HttpMount } from "../../http/app.js"; import type { TokenIdentity } from "../../http/token-store.js"; import { FRONT_MOUNT, FRONT_PREFIX } from "../shared/paths.js"; import { failure, frontReply, notAvailable, refusal } from "../shared/replies.js"; +import { isKnownRoute } from "../shared/routes.js"; +import { commandName, asRecord } from "../shared/selectors.js"; import { classifyCall, commandLeaseId, + methodName, readRpcBody, type CallClass, type RpcRead, } from "../shared/rpc.js"; import { allocate } from "./allocate.js"; import type { FrontContext } from "./context.js"; +import { filterDevices } from "./devices-filter.js"; import { heartbeat } from "./heartbeat.js"; import { release } from "./release.js"; +import { checkRequest } from "./request-rules.js"; type RpcRequest = RpcRead & { readonly kind: "request" }; @@ -66,7 +71,15 @@ async function handleRpc( if (kind === "wrapped-lease") { return frontReply(refusal("refused: send lease calls as lease RPCs"), read); } - return routeCall(context, { identity, kind, leaseMaxTtlMs: status.leaseMaxTtlMs, read, request }); + const checked = await checkRequest(context, identity, read, status.platforms); + if (checked.kind === "refused") return frontReply(checked.reply, read); + return routeCall(context, { + identity, + kind, + leaseMaxTtlMs: status.leaseMaxTtlMs, + read: checked.read, + request, + }); } async function routeCall( @@ -90,7 +103,7 @@ async function routeCall( } if (kind === "release") return release(context, identity, read, forwarded); const leaseId = kind === "command" ? commandLeaseId(read.params) : undefined; - if (leaseId === undefined) return passThrough(context, forwarded, identity, read); + if (leaseId === undefined) return forwardCommand(context, forwarded, identity, read); return runCommand(context, request, identity, read, leaseId); } @@ -105,7 +118,7 @@ async function runCommand( request.signal.addEventListener("abort", end, { once: true }); let response: Response; try { - response = await passThrough(context, carry(request, read.text), identity, read); + response = await forwardCommand(context, carry(request, read.text), identity, read); } catch (error) { end(); throw error; @@ -145,6 +158,20 @@ function untilBodyEnds(response: Response, end: () => void): Response { }); } +// why: agent-device answers `devices` with everything its daemon sees, so the answer is cut down before the CLI gets it. +async function forwardCommand( + context: FrontContext, + request: Request, + identity: TokenIdentity, + read: RpcRequest, +): Promise { + const response = await passThrough(context, request, identity, read); + const isDevices = + methodName(read.method) === "command" && + commandName(asRecord(read.params)?.["command"]) === "devices"; + return isDevices ? filterDevices(context, identity, response, read) : response; +} + async function passThrough( context: FrontContext, request: Request, @@ -169,6 +196,13 @@ export function createFront(context: FrontContext): HttpMount { if (isRpc) return handleRpc(context, request, identity); const status = await context.link.status(); if (status.state === "unavailable") return frontReply(notAvailable(status.reason), undefined); + const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); + if (!isKnownRoute(request.method, path)) { + return frontReply( + refusal(`refused: unknown route ${request.method} ${path}`, 404), + undefined, + ); + } return passThrough(context, request, identity, undefined); }, prefix: FRONT_MOUNT, diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index 9dac488f1..b24a01a91 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -1,9 +1,14 @@ import type { TokenIdentity } from "../../http/token-store.js"; +import type { AgentDevicePlatform } from "../host/agent-device-supervisor.js"; import type { AgentDeviceHost } from "../host/host.js"; export interface HostLink { status(): Promise< - | { readonly state: "running"; readonly leaseMaxTtlMs: number } + | { + readonly state: "running"; + readonly leaseMaxTtlMs: number; + readonly platforms: readonly AgentDevicePlatform[]; + } | { readonly state: "unavailable"; readonly reason: string } >; forward(request: Request, identity: TokenIdentity): Promise; diff --git a/src/agent-device/front/request-rules.ts b/src/agent-device/front/request-rules.ts new file mode 100644 index 000000000..023c1f515 --- /dev/null +++ b/src/agent-device/front/request-rules.ts @@ -0,0 +1,383 @@ +import { findCatalogModel } from "../../core/index.js"; +import { buildHttpSession } from "../../http/dispatcher-session.js"; +import type { TokenIdentity } from "../../http/token-store.js"; +import { failure, refusal, type FrontReply } from "../shared/replies.js"; +import { isKnownRpcMethod } from "../shared/routes.js"; +import { commandLeaseId, methodName, type RpcRead } from "../shared/rpc.js"; +import { + addressField, + asRecord, + commandName, + deviceList, + malformedField, + normalizeDeviceName, + present, + type Fields, +} from "../shared/selectors.js"; +import type { FrontContext } from "./context.js"; +import { LeaseCheckFailed, tokenDevices, type TokenDevice } from "./token-devices.js"; + +type RpcRequest = Extract; + +type RulesOutcome = + | { readonly kind: "accepted"; readonly read: RpcRequest } + | { readonly kind: "refused"; readonly reply: FrontReply }; + +const SIMLOCK_PICKS = "refused: simlock picks the device"; +const ONLY_IOS_AND_ANDROID = "refused: only iOS and Android"; +const UPLOAD_ONLY = "refused: send the app from your machine as an upload"; +const NO_DEVICE_LEASED = "refused: no device leased; run open first"; +const NAME_THE_DEVICE = "refused: name the device with --udid ; run devices to see yours"; +const PLATFORMS = ["ios", "android"]; + +class Refused extends Error { + constructor(readonly reply: FrontReply) { + super(reply.message); + } +} + +const refuse = (message: string): Refused => new Refused(refusal(message)); + +interface Unit { + readonly kind: "command" | "allocate" | "install"; + readonly owner: Fields; + readonly command: string; + readonly isStep: boolean; +} + +interface Check { + readonly context: FrontContext; + readonly identity: TokenIdentity; + readonly platforms: readonly string[]; + readonly leaseId: string | undefined; + readonly leased: TokenDevice | undefined; + readonly meta: Fields; + tokenDevices(): Promise; + changed: boolean; +} + +const isFlat = (unit: Unit): boolean => unit.kind !== "command"; + +function places(unit: Unit, withRuntime = false): Fields[] { + if (isFlat(unit)) return [unit.owner]; + const keys = withRuntime ? ["flags", "input", "runtime"] : ["flags", "input"]; + return keys.map((key) => asRecord(unit.owner[key])).filter((place) => place !== undefined); +} + +function flagsOf(unit: Unit): Fields { + if (isFlat(unit)) return unit.owner; + const existing = asRecord(unit.owner["flags"]); + if (existing !== undefined) return existing; + const created: Fields = {}; + unit.owner["flags"] = created; + return created; +} + +function firstString(sources: readonly Fields[], field: string): string | undefined { + for (const source of sources) { + const value = source[field]; + if (typeof value === "string") return value; + } + return undefined; +} + +function stepsOf(unit: Unit): Unit[] { + if (unit.command !== "batch") return []; + const steps = asRecord(unit.owner["flags"])?.["batchSteps"]; + if (!present(steps)) return []; + if (!Array.isArray(steps)) throw refuse("refused: malformed batchSteps"); + return steps.flatMap((step: unknown): Unit[] => { + const owner = asRecord(step); + if (owner === undefined) throw refuse("refused: malformed batchSteps"); + if (present(owner["command"]) && typeof owner["command"] !== "string") { + throw refuse("refused: malformed command"); + } + const inner: Unit = { + command: commandName(owner["command"]), + isStep: true, + kind: "command", + owner, + }; + return [inner, ...stepsOf(inner)]; + }); +} + +function checkTypes(unit: Unit): void { + if (!isFlat(unit)) { + for (const key of ["flags", "input", "runtime"]) { + if (present(unit.owner[key]) && asRecord(unit.owner[key]) === undefined) { + throw refuse(`refused: malformed ${key}`); + } + } + } + for (const place of places(unit, true)) { + const field = malformedField(place); + if (field !== undefined) throw refuse(`refused: malformed ${field}`); + } +} + +function rulePlatform(check: Check, unit: Unit): void { + for (const place of places(unit, true)) { + const platform = place["platform"]; + if (!present(platform)) continue; + if (typeof platform !== "string" || !PLATFORMS.includes(platform)) { + throw refuse(ONLY_IOS_AND_ANDROID); + } + if (!check.platforms.includes(platform)) { + throw refuse(`refused: ${platform} is not available on this simlock`); + } + } +} + +function ruleDeviceSet(unit: Unit): void { + for (const place of places(unit)) { + if (present(place["iosSimulatorDeviceSet"])) { + throw refuse( + "refused: simlock chooses the device set; run disconnect, then connect proxy without --ios-simulator-device-set", + ); + } + if (present(place["androidDeviceAllowlist"])) { + throw refuse( + "refused: simlock chooses the devices; run disconnect, then connect proxy without --android-device-allowlist", + ); + } + } +} + +async function namesLeasedModel(check: Check, leased: TokenDevice, name: string): Promise { + if (leased.platform === undefined || leased.model === undefined) return false; + try { + const { platforms } = await check.context.dispatch( + "catalog.get", + { platform: leased.platform }, + buildHttpSession(check.identity), + ); + const entry = platforms.find((candidate) => candidate.platform === leased.platform); + const listed = entry === undefined ? undefined : findCatalogModel(entry, name); + return listed !== undefined && listed.toLowerCase() === leased.model.toLowerCase(); + } catch { + return false; + } +} + +const namesDevice = (device: TokenDevice, entry: string): boolean => + entry === device.address || + (device.name !== undefined && normalizeDeviceName(entry) === normalizeDeviceName(device.name)); + +async function ruleShardList(check: Check, unit: Unit): Promise { + const entries = places(unit).flatMap((place) => deviceList(place["device"])); + if (entries.length === 0) return; + const devices = await check.tokenDevices(); + for (const entry of entries) { + if (!devices.some((device) => namesDevice(device, entry))) throw refuse(SIMLOCK_PICKS); + } +} + +async function ruleDevice(check: Check, place: Fields): Promise { + const device = place["device"]; + if (!present(device)) return false; + const leased = check.leased; + if (leased === undefined) throw refuse(SIMLOCK_PICKS); + const name = device as string; + if (namesDevice(leased, name)) return false; + if (!(await namesLeasedModel(check, leased, name))) throw refuse(SIMLOCK_PICKS); + delete place["device"]; + check.changed = true; + return true; +} + +function wrongDeviceKey(check: Check, source: Fields): boolean { + if (check.leaseId === undefined || !present(source["deviceKey"])) return false; + return check.leased?.deviceKey === undefined || source["deviceKey"] !== check.leased.deviceKey; +} + +function ruleAddresses(check: Check, unit: Unit): void { + const leased = check.leased; + for (const place of places(unit)) { + for (const field of ["udid", "serial"]) { + if (present(place[field]) && place[field] !== leased?.address) throw refuse(SIMLOCK_PICKS); + } + if (wrongDeviceKey(check, place)) throw refuse(SIMLOCK_PICKS); + } + if (!unit.isStep && wrongDeviceKey(check, check.meta)) throw refuse(SIMLOCK_PICKS); +} + +async function ruleSelectors(check: Check, unit: Unit): Promise { + if (unit.kind === "install") return; + ruleAddresses(check, unit); + if (unit.kind === "allocate") return; + if (unit.command === "test") return ruleShardList(check, unit); + let rewritten = false; + for (const place of places(unit)) { + if (await ruleDevice(check, place)) rewritten = true; + } + if (rewritten && check.leased !== undefined) { + flagsOf(unit)[addressField(check.leased.platform)] = check.leased.address; + } +} + +async function ruleSharding(check: Check, unit: Unit): Promise { + if (unit.kind !== "command" || unit.command !== "test") return; + const found = places(unit); + if (!found.some((place) => present(place["shardAll"]) || present(place["shardSplit"]))) return; + if (found.some((place) => deviceList(place["device"]).length > 0)) return; + const platform = firstString(places(unit, true), "platform"); + const target = firstString(found, "target"); + const matching = (await check.tokenDevices()).filter( + (device) => + (platform === undefined || device.platform === platform) && + (target === undefined || (device.target ?? "mobile") === target), + ); + if (matching.length === 0) throw refuse(NO_DEVICE_LEASED); + for (const place of found) delete place["device"]; + flagsOf(unit)["device"] = matching.map((device) => device.address).join(","); + check.changed = true; +} + +function ruleInstall(check: Check, unit: Unit): void { + if (unit.kind !== "command" || (unit.command !== "install" && unit.command !== "reinstall")) { + return; + } + const upload = check.meta["uploadedArtifactId"]; + if (unit.isStep || typeof upload !== "string" || upload.trim() === "") { + throw refuse(UPLOAD_ONLY); + } +} + +async function ruleLeaseFree(check: Check, unit: Unit): Promise { + if (unit.kind !== "command" || (unit.command !== "capabilities" && unit.command !== "doctor")) { + return; + } + const found = places(unit); + if (found.some((place) => ["udid", "serial", "device"].some((key) => present(place[key])))) { + return; + } + let device = check.leased; + if (device === undefined) { + const platform = firstString(places(unit, true), "platform"); + const own = (await check.tokenDevices()).filter( + (candidate) => platform === undefined || candidate.platform === platform, + ); + if (own.length !== 1) throw refuse(NAME_THE_DEVICE); + device = own[0]; + } + if (device === undefined) throw refuse(NAME_THE_DEVICE); + flagsOf(unit)[addressField(device.platform)] = device.address; + check.changed = true; +} + +async function applyRules(check: Check, unit: Unit): Promise { + if (unit.isStep) { + const named = asRecord(unit.owner["flags"])?.["leaseId"]; + if (present(named) && named !== check.leaseId) { + throw refuse("refused: a batch step cannot name another lease"); + } + } + rulePlatform(check, unit); + if (unit.kind === "install") return; + ruleDeviceSet(unit); + await ruleSelectors(check, unit); + await ruleSharding(check, unit); + ruleInstall(check, unit); + if (unit.isStep && unit.command === "devices") throw refuse("refused: run devices on its own"); + await ruleLeaseFree(check, unit); +} + +function unitFor(name: string, params: Fields): Unit | undefined { + if (name === "command") { + return { + command: commandName(params["command"]), + isStep: false, + kind: "command", + owner: params, + }; + } + if (name === "lease.allocate") { + return { command: "", isStep: false, kind: "allocate", owner: params }; + } + if (name === "install_from_source") { + return { command: "", isStep: false, kind: "install", owner: params }; + } + return undefined; +} + +function buildCheck( + context: FrontContext, + identity: TokenIdentity, + platforms: readonly string[], + params: Fields, + kind: Unit["kind"], +): Check { + const leaseId = kind === "command" ? commandLeaseId(params) : undefined; + const held = leaseId === undefined ? undefined : context.map.get(leaseId); + let devices: Promise | undefined; + const meta = asRecord(params["meta"]) ?? {}; + return { + changed: false, + context, + identity, + leaseId, + leased: + leaseId !== undefined && held?.identity.requesterId === identity.requesterId + ? { ...held, leaseId } + : undefined, + meta, + platforms, + tokenDevices: () => (devices ??= tokenDevices(context, identity)), + }; +} + +export async function checkRequest( + context: FrontContext, + identity: TokenIdentity, + read: RpcRequest, + platforms: readonly string[], +): Promise { + try { + return await run(context, identity, read, platforms); + } catch (error) { + if (error instanceof Refused) return { kind: "refused", reply: error.reply }; + if (error instanceof LeaseCheckFailed) { + return { kind: "refused", reply: failure(error.message) }; + } + throw error; + } +} + +function checkMeta(check: Check): void { + const key = check.meta["deviceKey"]; + if (present(key) && typeof key !== "string") throw refuse("refused: malformed deviceKey"); +} + +async function run( + context: FrontContext, + identity: TokenIdentity, + read: RpcRequest, + platforms: readonly string[], +): Promise { + if (!isKnownRpcMethod(read.method)) throw refuse(`refused: unknown method ${read.method}`); + const body = structuredClone(read.body); + const params = asRecord(body["params"]) ?? {}; + body["params"] = params; + const main = unitFor(methodName(read.method) ?? "", params); + if (main === undefined) return { kind: "accepted", read }; + const units = [main, ...stepsOf(main)]; + const check = buildCheck(context, identity, platforms, params, main.kind); + checkMeta(check); + for (const unit of units) checkTypes(unit); + for (const unit of units) await applyRules(check, unit); + ruleDevicesAnswer(check, main); + return accepted(read, check, body); +} + +function ruleDevicesAnswer(check: Check, main: Unit): void { + if (main.command === "devices" && Boolean(check.meta["requestProgress"])) { + throw refuse("refused: devices does not stream through simlock"); + } +} + +function accepted(read: RpcRequest, check: Check, body: Fields): RulesOutcome { + if (!check.changed) return { kind: "accepted", read }; + const params = asRecord(body["params"]) ?? {}; + return { kind: "accepted", read: { ...read, body, params, text: JSON.stringify(body) } }; +} diff --git a/src/agent-device/front/token-devices.ts b/src/agent-device/front/token-devices.ts new file mode 100644 index 000000000..57703c043 --- /dev/null +++ b/src/agent-device/front/token-devices.ts @@ -0,0 +1,29 @@ +import type { TokenIdentity } from "../../http/token-store.js"; +import { listLeases, type FrontContext } from "./context.js"; +import type { HeldView } from "./front-map.js"; + +export type TokenDevice = HeldView & { readonly leaseId: string }; + +export class LeaseCheckFailed extends Error { + constructor() { + super("could not check your leases; try again"); + } +} + +export async function tokenDevices( + context: FrontContext, + identity: TokenIdentity, +): Promise { + const held = context.map.liveOf(identity.requesterId); + if (held.length === 0) return held; + let listed: Awaited>; + try { + listed = await listLeases(context, identity); + } catch { + throw new LeaseCheckFailed(); + } + for (const entry of held) { + if (!listed.some((lease) => lease.id === entry.leaseId)) context.map.markEnded(entry.leaseId); + } + return context.map.liveOf(identity.requesterId); +} diff --git a/src/agent-device/host/host.test.ts b/src/agent-device/host/host.test.ts index a3497f9c5..9b2abae13 100644 --- a/src/agent-device/host/host.test.ts +++ b/src/agent-device/host/host.test.ts @@ -21,7 +21,7 @@ describe("the agent-device host", () => { current: () => running, fetch: async () => new Response(), } as unknown as AgentDeviceUpstream; - const host = new AgentDeviceHost(upstream); + const host = new AgentDeviceHost(upstream, ["ios"]); expect(await host.status()).toEqual({ reason: expect.stringMatching(/^could not load @agent-device\/proxy: ./), @@ -35,7 +35,7 @@ describe("the agent-device host", () => { fetch: async () => new Response(), } as unknown as AgentDeviceUpstream; - expect(await new AgentDeviceHost(upstream).status()).toEqual({ + expect(await new AgentDeviceHost(upstream, ["ios"]).status()).toEqual({ reason: "agent-device is stopped", state: "unavailable", }); diff --git a/src/agent-device/host/host.ts b/src/agent-device/host/host.ts index 5375744a1..e8b68ced8 100644 --- a/src/agent-device/host/host.ts +++ b/src/agent-device/host/host.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto"; import type { TokenIdentity } from "../../http/token-store.js"; +import type { AgentDevicePlatform } from "./agent-device-supervisor.js"; import { FRONT_PREFIX, PROXY_BASE_PATH } from "../shared/paths.js"; import { recordingFetch, ReleaseScopeRecord } from "./lease-end.js"; import type { AgentDeviceUpstream } from "./upstream.js"; @@ -13,7 +14,11 @@ const TAG_HEADER = "x-simlock-front-tag"; const PREFLIGHT_PATH = `${PROXY_BASE_PATH}/upload/preflight`; export type HostStatus = - | { readonly state: "running"; readonly leaseMaxTtlMs: number } + | { + readonly state: "running"; + readonly leaseMaxTtlMs: number; + readonly platforms: readonly AgentDevicePlatform[]; + } | { readonly state: "unavailable"; readonly reason: string }; function stripBodyHeaders(headers: Headers): Headers { @@ -33,6 +38,7 @@ export class AgentDeviceHost { constructor( readonly upstream: AgentDeviceUpstream, + readonly platforms: readonly AgentDevicePlatform[], record: ReleaseScopeRecord = new ReleaseScopeRecord(), ) { this.#upstreamFetch = recordingFetch(upstream, record); @@ -43,7 +49,11 @@ export class AgentDeviceHost { if (current.state === "unavailable") return current; await this.#load(); if (this.#loadError !== undefined) return { reason: this.#loadError, state: "unavailable" }; - return { leaseMaxTtlMs: current.leaseMaxTtlMs, state: "running" }; + return { + leaseMaxTtlMs: current.leaseMaxTtlMs, + platforms: this.platforms, + state: "running", + }; } tag(request: Request, identity: TokenIdentity): string { diff --git a/src/agent-device/host/upstream.test.ts b/src/agent-device/host/upstream.test.ts index 0363f8e83..f258bc63c 100644 --- a/src/agent-device/host/upstream.test.ts +++ b/src/agent-device/host/upstream.test.ts @@ -144,7 +144,7 @@ describe("the agent-device host's authenticate", () => { }; it("returns the tagged identity's principal as the tenant, and null for a request the front did not tag", () => { - const host = new AgentDeviceHost(upstream); + const host = new AgentDeviceHost(upstream, ["ios"]); const tagged = new Request("http://worker/v1/agent-device/rpc"); host.tag(tagged, { requesterId: "tok_agent", role: "agent" }); diff --git a/src/agent-device/index.ts b/src/agent-device/index.ts index 2a95a29d1..36340cb70 100644 --- a/src/agent-device/index.ts +++ b/src/agent-device/index.ts @@ -5,6 +5,7 @@ import { FrontMap } from "./front/front-map.js"; import { createFront } from "./front/front.js"; import { InProcessHostLink, type HostLink } from "./front/host-link.js"; import { Renewals } from "./front/renewals.js"; +import type { AgentDevicePlatform } from "./host/agent-device-supervisor.js"; import { AgentDeviceHost } from "./host/host.js"; import { AgentDeviceLeaseEnd, ReleaseScopeRecord } from "./host/lease-end.js"; import type { AgentDeviceUpstream } from "./host/upstream.js"; @@ -27,11 +28,12 @@ export interface AgentDeviceEdgeParts { export function createAgentDeviceEdgeParts( upstream: AgentDeviceUpstream, clock: Clock, + platforms: readonly AgentDevicePlatform[], ): AgentDeviceEdgeParts { const record = new ReleaseScopeRecord(); return { leaseEnd: new AgentDeviceLeaseEnd(upstream, record), - link: new InProcessHostLink(new AgentDeviceHost(upstream, record)), + link: new InProcessHostLink(new AgentDeviceHost(upstream, platforms, record)), map: new FrontMap(clock), renewals: new Renewals(clock), }; diff --git a/src/agent-device/shared/release-scope.ts b/src/agent-device/shared/release-scope.ts index 451b845fd..974bf1bb4 100644 --- a/src/agent-device/shared/release-scope.ts +++ b/src/agent-device/shared/release-scope.ts @@ -9,12 +9,12 @@ export interface ReleaseScope { const SCOPE_VALUE = /^[A-Za-z0-9._-]{1,128}$/; const OPTIONAL_KEYS = ["leaseProvider", "clientId", "deviceKey"] as const; -function valid(value: unknown): value is string { +function validScopeValue(value: unknown): value is string { return typeof value === "string" && SCOPE_VALUE.test(value); } // why: agent-device's own device keys look like `ios:mobile:`, so only the length is bounded. -function validDeviceKey(value: unknown): value is string { +export function validDeviceKey(value: unknown): value is string { return typeof value === "string" && value.length >= 1 && value.length <= 128; } @@ -23,13 +23,16 @@ export function readReleaseScope(lease: unknown): ReleaseScope | undefined { const fields = lease as Record; const tenantId = fields["tenantId"]; const runId = fields["runId"]; - if (!valid(tenantId) || !valid(runId)) return undefined; + if (!validScopeValue(tenantId) || !validScopeValue(runId)) return undefined; const optional: { -readonly [K in (typeof OPTIONAL_KEYS)[number]]?: string } = {}; for (const key of OPTIONAL_KEYS) { const value = fields[key]; + if (key === "deviceKey") { + if (validDeviceKey(value)) optional[key] = value; + continue; + } if (value === undefined) continue; - if (typeof value !== "string") return undefined; - if (!(key === "deviceKey" ? validDeviceKey(value) : valid(value))) return undefined; + if (!validScopeValue(value)) return undefined; optional[key] = value; } return { ...optional, runId, tenantId }; diff --git a/src/agent-device/shared/routes.ts b/src/agent-device/shared/routes.ts new file mode 100644 index 000000000..53ad22b82 --- /dev/null +++ b/src/agent-device/shared/routes.ts @@ -0,0 +1,47 @@ +import { methodName } from "./rpc.js"; + +const RPC_METHODS: ReadonlySet = new Set([ + "command", + "lease.allocate", + "lease.heartbeat", + "lease.release", + "install_from_source", + "release_materialized_paths", +]); + +export function isKnownRpcMethod(method: string): boolean { + const name = methodName(method); + return name !== undefined && RPC_METHODS.has(name); +} + +const FIXED_ROUTES: ReadonlyMap = new Map([ + ["/health", "GET"], + ["/rpc", "POST"], + ["/upload", "POST"], + ["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/upload/preflight", "POST"], + ["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/upload/finalize", "POST"], + ["/artifacts", "GET"], + ["/artifacts/", "GET"], +]); + +export function isKnownRoute(method: string, path: string): boolean { + if (FIXED_ROUTES.get(path) === method) return true; + const segments = path.split("/").slice(1); + if (segments.some((segment, index) => segment === "" && index < segments.length - 1)) { + return false; + } + const [first, second, third, fourth, fifth] = segments; + if (method === "PUT") { + return first === "upload" && second === "direct" && segments.length === 3 && third !== ""; + } + if (method !== "GET") return false; + if (first === "artifacts") return segments.length >= 2 && segments.every((s) => s !== ""); + return ( + first === "sessions" && + segments.length === 5 && + second !== "" && + third === "requests" && + fourth !== "" && + fifth === "diagnostics" + ); +} diff --git a/src/agent-device/shared/rpc.ts b/src/agent-device/shared/rpc.ts index bc83eb457..cae92747c 100644 --- a/src/agent-device/shared/rpc.ts +++ b/src/agent-device/shared/rpc.ts @@ -25,7 +25,9 @@ export type RpcRead = | { readonly kind: "too-large" } | { readonly kind: "malformed" }; -async function readBounded(body: ReadableStream | null): Promise { +export async function readBounded( + body: ReadableStream | null, +): Promise { if (body === null) return ""; const reader = body.getReader(); const chunks: Uint8Array[] = []; @@ -66,10 +68,15 @@ export async function readRpcBody(request: Request): Promise { export type CallClass = "allocate" | "heartbeat" | "release" | "wrapped-lease" | "command"; +const METHOD_SPELLING = /^agent[_-]device\./; const LEASE_METHOD = /^agent[_-]device\.lease\.(allocate|heartbeat|release)$/; const COMMAND_METHOD = /^agent[_-]device\.command$/; const WRAPPED_LEASE = /^lease_(allocate|heartbeat|release)$/; +export function methodName(method: string): string | undefined { + return METHOD_SPELLING.test(method) ? method.replace(METHOD_SPELLING, "") : undefined; +} + export function classifyCall(method: string, params: Record): CallClass { const lease = LEASE_METHOD.exec(method)?.[1]; if (lease !== undefined) return lease as "allocate" | "heartbeat" | "release"; diff --git a/src/agent-device/shared/selectors.ts b/src/agent-device/shared/selectors.ts new file mode 100644 index 000000000..c95c55405 --- /dev/null +++ b/src/agent-device/shared/selectors.ts @@ -0,0 +1,42 @@ +export type Fields = Record; + +export function asRecord(value: unknown): Fields | undefined { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Fields) + : undefined; +} + +export const present = (value: unknown): boolean => value !== undefined && value !== null; + +const STRING_FIELDS = ["platform", "target", "udid", "serial", "device", "deviceKey"] as const; +const INTEGER_FIELDS = ["shardAll", "shardSplit"] as const; + +export function malformedField(source: Fields): string | undefined { + for (const field of STRING_FIELDS) { + if (present(source[field]) && typeof source[field] !== "string") return field; + } + for (const field of INTEGER_FIELDS) { + if (present(source[field]) && !Number.isInteger(source[field])) return field; + } + return undefined; +} + +export function normalizeDeviceName(name: string): string { + return name.toLowerCase().replaceAll("_", " ").replace(/ +/g, " ").trim(); +} + +export function deviceList(value: unknown): readonly string[] { + if (typeof value !== "string") return []; + return value + .split(",") + .map((entry) => entry.trim()) + .filter((entry) => entry !== ""); +} + +export function commandName(value: unknown): string { + return typeof value === "string" ? value.trim().toLowerCase() : ""; +} + +// why: iOS devices are addressed by `udid` and Android ones by `serial`; the front names the address in both its allocate and its rewrites. +export const addressField = (platform: string | undefined): "udid" | "serial" => + platform === "android" ? "serial" : "udid"; diff --git a/src/agent-device/testing.ts b/src/agent-device/testing.ts index b0b7463da..19a949453 100644 --- a/src/agent-device/testing.ts +++ b/src/agent-device/testing.ts @@ -60,6 +60,18 @@ interface RunningCommand { readonly ended: Promise; } +export interface FakeReplyDevice { + readonly name?: string; + readonly target?: string; +} + +export interface FakeInventoryDevice { + readonly id: string; + readonly name?: string; + readonly platform?: string; + readonly target?: string; +} + export interface FakeAllocateReplyEdit { readonly runId?: string; readonly clientId?: string; @@ -162,6 +174,11 @@ export class FakeAgentDevice implements AgentDeviceUpstream { #hangRelease = false; #releaseBody: string | undefined; #replyEdit: FakeAllocateReplyEdit | undefined; + #replyDevice: FakeReplyDevice | "none" | undefined; + #devicesAnswer: + | { readonly body: string } + | { readonly list: readonly FakeInventoryDevice[] } + | undefined; constructor(options: { readonly leaseMaxTtlMs?: number } = {}) { this.leaseMaxTtlMs = options.leaseMaxTtlMs ?? 4 * 60 * 60_000 + 10_000; @@ -257,6 +274,20 @@ export class FakeAgentDevice implements AgentDeviceUpstream { this.#replyEdit = edit; } + // why: agent-device names the device it picked beside the lease in its allocate reply; `"none"` is a reply that names no device. + nameDeviceInNextReply(device: FakeReplyDevice | "none"): void { + this.#replyDevice = device; + } + + // why: the `devices` command answers the daemon's whole inventory, which the front must cut down to the token's own devices. + listDevices(devices: readonly FakeInventoryDevice[]): void { + this.#devicesAnswer = { list: devices }; + } + + answerDevicesWith(body: string): void { + this.#devicesAnswer = { body }; + } + streamNextCommand(chunks: readonly string[]): void { this.#streamChunks = chunks; } @@ -314,7 +345,10 @@ export class FakeAgentDevice implements AgentDeviceUpstream { this.uploads.push(await request.text()); return Response.json({ ok: true }); } - if (url.pathname !== "/rpc") return new Response("Not found", { status: 404 }); + if (url.pathname !== "/rpc") { + this.requests.push({ method: request.method, path: url.pathname, tenant: tenantHeader }); + return new Response("Not found", { status: 404 }); + } return this.#rpc(request, tenantHeader); } @@ -373,6 +407,8 @@ export class FakeAgentDevice implements AgentDeviceUpstream { this.#replyDeviceKey = undefined; const edit = this.#replyEdit; this.#replyEdit = undefined; + const picked = this.#replyDevice; + this.#replyDevice = undefined; this.leases.set(leaseId, { address, ended: false, @@ -382,6 +418,9 @@ export class FakeAgentDevice implements AgentDeviceUpstream { ttlMs: params["ttlMs"], }); return envelope(id, { + ...(picked === "none" || address === undefined + ? {} + : { device: { id: address, name: `simlock-${address}`, ...picked } }), lease: { ...scope, ...edit, leaseId, tenantId: tenant, ttlMs: params["ttlMs"] }, ok: true, }); @@ -510,6 +549,11 @@ export class FakeAgentDevice implements AgentDeviceUpstream { const failure = this.#failCommand; this.#failCommand = undefined; if (failure !== undefined) return errorEnvelope(id, failure); + const inventory = this.#devicesAnswer; + if (command === "devices" && inventory !== undefined) { + if ("body" in inventory) return new Response(inventory.body, { status: 200 }); + return envelope(id, { data: { devices: inventory.list }, ok: true }); + } if (command === "close" && typeof leaseId === "string") { const lease = this.leases.get(leaseId); if (lease !== undefined) lease.ended = true; diff --git a/src/daemon/main.ts b/src/daemon/main.ts index da2d0095b..344ea41b0 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -322,6 +322,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise driver.platform), ) : undefined; // Builds leasing on top of core (ADR 0018 ยง2).