diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 7433fed67..f9cac14e6 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -66,12 +66,12 @@ Front (`createFront`, prefix `agent-device`): 1. Token checked by the http app. Role not `agent` → 403. Gateway: `adoptable` leases rebuilt into the map first. -2. Non-RPC: a fixed route list (`shared/routes.ts`), else 404. `/health` answers 200 even - when unavailable. +2. Non-RPC: a fixed route list (`shared/routes.ts`), else 404. `/health` answers 200 even when unavailable. 3. `/rpc`: body ≤ 1 MiB, one JSON-RPC request; only `command` and `lease.*` methods, as agent-device's proxy takes no other from a tenant; `classifyCall` → allocate, heartbeat, release, command, or refused `wrapped-lease`. 4. `checkRequest`: iOS/Android only; no device selector but the leased one; no device set or allowlist; `install` only from an upload; `devices` alone, not streamed. + A rule that needs a leased device's name (`--device`) reads it once per lease from agent-device's `devices` list (`namedTokenDevices`). 5. Allocate → `lease.request` (`front/allocate.ts`), see flow. 6. Heartbeat → forwarded with `ttlMs` raised to the ceiling; on success `renewLease` (`lease.renew` only if it moves the deadline; a gateway list that trails the grant and omits the lease still relays agent-device's reply). agent-device says gone → `lease.release`, reply "ended by simlock". diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index b12a4e02f..815197b8c 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -779,6 +779,7 @@ describe("the agent-device front, through the whole worker daemon", () => { for (const [n, extra, device] of cases) { rig.fake.nameDeviceKeyInNextReply(`key-${n}`); + rig.fake.nameDeviceInNextReply({}); const result = (await envelopeOf(await allocate(rig, n, extra, {}))).result as { data: { device: unknown; lease: Record }; }; @@ -3376,8 +3377,10 @@ async function forwarded( 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; + // why: the front reads a leased device's name from agent-device's device list the first time a rule needs it, before it forwards the command. + const sent = rig.fake.requests.slice(before).filter((r) => r.params?.["command"] !== "devices"); + expect(sent.length).toBe(1); + return sent[0]?.params as Record; } async function refused(rig: Rig, send: () => Promise, message: string): Promise { @@ -3385,7 +3388,10 @@ async function refused(rig: Rig, send: () => Promise, message: string) const answer = await envelopeOf(await send()); expect(answer.error).toMatchObject(refusal(message)); expect(answer.result).toBeUndefined(); - expect(rig.fake.requests.length).toBe(before); + // why: a refusal can follow the front's one read of a leased device's name from agent-device's device list; no command reaches it. + expect( + rig.fake.requests.slice(before).filter((r) => r.params?.["command"] !== "devices"), + ).toEqual([]); } function flagsOf(params: Record): Record { @@ -3608,11 +3614,14 @@ describe("the agent-device front's request rules", () => { } }); - 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 () => { + it("`--device` with the leased device's own name is forwarded as sent; with the leased model, or a catalog alias of it, 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 byName = await forwarded(rig, () => + runCommand(rig, "snapshot", 1, { flags: { device: nameOf(rig, 1) } }), + ); const ios = flagsOf( await forwarded(rig, () => @@ -3623,6 +3632,7 @@ describe("the agent-device front's request rules", () => { await forwarded(rig, () => runCommand(rig, "snapshot", 2, { flags: { device: "p8" } })), ); + expect(flagsOf(byName)["device"]).toBe(nameOf(rig, 1)); expect(ios["udid"]).toBe(idOf(rig, 1)); expect(ios).not.toHaveProperty("device"); expect(android["serial"]).toBe(idOf(rig, 2)); @@ -3959,11 +3969,11 @@ describe("the agent-device front's request rules", () => { ); }); - it("`test --shard-all 2` names a device by the name agent-device gave it, and by its id when that name holds a comma or the reply named none", async () => { + it("`test --shard-all 2` names a device by the name agent-device gave it, and by its id when that name holds a comma or neither the reply nor the inventory named one", async () => { const rig = await setUp(); rig.fake.nameDeviceInNextReply({ name: "Lab, left" }); await granted(rig, 1); - rig.fake.nameDeviceInNextReply("none"); + rig.fake.listDevices([]); await granted(rig, 2, {}, { token: secrets.two }); const comma = await forwarded(rig, () => shard(rig, 1)); @@ -3971,6 +3981,39 @@ describe("the agent-device front's request rules", () => { expect(flagsOf(comma)["device"]).toBe(idOf(rig, 1)); expect(flagsOf(unnamed)["device"]).toBe(idOf(rig, 2)); + + await forwarded(rig, () => shard(rig, 2, {}, secrets.two)); + const listed = rig.fake.requests + .filter((r) => r.params?.["command"] === "devices") + .map((r) => + String((r.params?.["meta"] as Record | undefined)?.["leaseId"]), + ); + expect(listed.length).toBe(new Set(listed).size); + }); + + // why: agent-device 0.21.28 answers an allocate with `{ lease }` and no device; only its `devices` inventory names a device, and its session check matches `--device` by that name alone (#971). + it("`test --shard-all` with no `--device` names each of the token's leased devices by the name agent-device's inventory gives it when the allocate reply named no device, for an agent holding one device and one holding two", async () => { + const rig = await setUp(); + rig.fake.nameDeviceInNextReply("none"); + await granted(rig, 1); + rig.fake.nameDeviceInNextReply("none"); + await granted(rig, 2, {}, { token: secrets.two }); + rig.fake.nameDeviceInNextReply("none"); + await granted(rig, 3, {}, { token: secrets.two }); + rig.fake.listDevices([ + { id: idOf(rig, 1), name: "simlock-aaaa", platform: "ios" }, + { id: idOf(rig, 2), name: "simlock-bbbb", platform: "ios" }, + { id: idOf(rig, 3), name: "simlock-cccc", platform: "ios" }, + ]); + + const one = await forwarded(rig, () => shard(rig, 1, { shardAll: 1 })); + const two = await forwarded(rig, () => shard(rig, 2, {}, secrets.two)); + + expect(flagsOf(one)["device"]).toBe("simlock-aaaa"); + expect(String(flagsOf(two)["device"]).split(",").sort()).toEqual([ + "simlock-bbbb", + "simlock-cccc", + ]); }); 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 () => { diff --git a/src/agent-device/front/front-map.ts b/src/agent-device/front/front-map.ts index e4a2504c0..087c675b5 100644 --- a/src/agent-device/front/front-map.ts +++ b/src/agent-device/front/front-map.ts @@ -11,6 +11,8 @@ interface DeviceFacts { readonly deviceKey?: string; // why: an adopted entry was rebuilt after a gateway restart and has no device key until a call names one. readonly adopted?: boolean; + // why: agent-device's device list was read for this lease's name, so a device it did not name is not asked about again. + readonly named?: boolean; } export interface FrontMapEntry extends DeviceFacts { @@ -35,8 +37,10 @@ export interface ListedLease { readonly ttlDeadline: number; } -interface Held extends Omit { +interface Held extends Omit { deviceKey?: string; + name?: string; + named?: boolean; readonly identity: Identity; readonly address: string; ttlMs: number; @@ -88,6 +92,13 @@ export class FrontMap { if (held !== undefined && held.deviceKey === undefined) held.deviceKey = deviceKey; } + setName(leaseId: string, name: string | undefined): void { + const held = this.#held.get(leaseId); + if (held === undefined) return; + held.named = true; + if (name !== undefined) held.name = name; + } + 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 a1e13227f..ba14f59fe 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -117,7 +117,7 @@ async function handleRpc( if (kind === "wrapped-lease") { return frontReply(refusal("refused: send lease calls as lease RPCs"), read); } - const checked = await checkRequest(context, identity, read, status.platforms); + const checked = await checkRequest(context, identity, read, status.platforms, request); if (checked.kind === "refused") return frontReply(checked.reply, read); return routeCall(context, { identity, diff --git a/src/agent-device/front/request-rules.ts b/src/agent-device/front/request-rules.ts index f10f0ceb2..6acbc36fa 100644 --- a/src/agent-device/front/request-rules.ts +++ b/src/agent-device/front/request-rules.ts @@ -16,7 +16,7 @@ import { type Fields, } from "../shared/selectors.js"; import type { FrontContext } from "./context.js"; -import { LeaseCheckFailed, tokenDevices, type TokenDevice } from "./token-devices.js"; +import { LeaseCheckFailed, namedTokenDevices, type TokenDevice } from "./token-devices.js"; type RpcRequest = Extract; @@ -186,12 +186,19 @@ async function ruleShardList(check: Check, unit: Unit): Promise { } } +// why: agent-device's allocate reply names no device, so a name the command carries is checked against the name read from its device list, once per lease. +async function withName(check: Check, leased: TokenDevice): Promise { + if (leased.name !== undefined || leased.named === true) return leased; + const read = (await check.tokenDevices()).find((device) => device.leaseId === leased.leaseId); + return read ?? leased; +} + 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); + if (check.leased === undefined) throw refuse(SIMLOCK_PICKS); const name = device as string; + const leased = await withName(check, check.leased); if (namesDevice(leased, name)) return false; if (!(await namesLeasedModel(check, leased, name))) throw refuse(SIMLOCK_PICKS); delete place["device"]; @@ -332,6 +339,7 @@ function buildCheck( platforms: readonly string[], params: Fields, kind: Unit["kind"], + request: Request, ): Check { const leaseId = kind === "command" ? commandLeaseId(params) : undefined; const held = leaseId === undefined ? undefined : context.map.get(leaseId); @@ -348,7 +356,7 @@ function buildCheck( : undefined, meta, platforms, - tokenDevices: () => (devices ??= tokenDevices(context, identity)), + tokenDevices: () => (devices ??= namedTokenDevices(context, identity, request)), }; } @@ -357,9 +365,10 @@ export async function checkRequest( identity: Identity, read: RpcRequest, platforms: readonly string[], + request: Request, ): Promise { try { - return await run(context, identity, read, platforms); + return await run(context, identity, read, platforms, request); } catch (error) { if (error instanceof Refused) return { kind: "refused", reply: error.reply }; if (error instanceof LeaseCheckFailed) { @@ -379,6 +388,7 @@ async function run( identity: Identity, read: RpcRequest, platforms: readonly string[], + request: Request, ): Promise { if (!isKnownRpcMethod(read.method)) throw refuse(`refused: unknown method ${read.method}`); const body = structuredClone(read.body); @@ -387,7 +397,7 @@ async function run( 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); + const check = buildCheck(context, identity, platforms, params, main.kind, request); checkMeta(check); for (const unit of units) checkTypes(unit); for (const unit of units) await applyRules(check, unit); diff --git a/src/agent-device/front/token-devices.ts b/src/agent-device/front/token-devices.ts index e3df32978..c0b280908 100644 --- a/src/agent-device/front/token-devices.ts +++ b/src/agent-device/front/token-devices.ts @@ -1,5 +1,7 @@ import type { Identity } from "../../auth/index.js"; -import { listLeases, type FrontContext } from "./context.js"; +import { LEASE_HEADER } from "../shared/paths.js"; +import { asRecord } from "../shared/selectors.js"; +import { exchange, leaseCall, listLeases, type FrontContext } from "./context.js"; import type { HeldView } from "./front-map.js"; export type TokenDevice = HeldView & { readonly leaseId: string }; @@ -30,3 +32,51 @@ export async function tokenDevices( .liveOf(identity.principal) .filter((entry) => listed.some((lease) => lease.id === entry.leaseId)); } + +// why: agent-device's allocate reply names no device, and it matches `--device` against the session's device by name alone, so each lease's name is read once from its device list, when a rule first needs it. +export async function namedTokenDevices( + context: FrontContext, + identity: Identity, + request: Request, +): Promise { + const held = await tokenDevices(context, identity); + let learned = false; + for (const device of held) { + if (device.name !== undefined || device.named === true) continue; + const reading = await inventoryOf(context, identity, request, device); + if (reading === undefined) continue; + context.map.setName(device.leaseId, reading.name); + learned = true; + } + return learned + ? context.map + .liveOf(identity.principal) + .filter((entry) => held.some((h) => h.leaseId === entry.leaseId)) + : held; +} + +async function inventoryOf( + context: FrontContext, + identity: Identity, + request: Request, + device: TokenDevice, +): Promise<{ readonly name: string | undefined } | undefined> { + const headers = leaseCall(request, "agent_device.lease.allocate", {}, null).headers; + headers.set(LEASE_HEADER, device.leaseId); + const listing = new Request(request.url, { + body: JSON.stringify({ + id: null, + jsonrpc: "2.0", + method: "agent_device.command", + params: { command: "devices", meta: { leaseId: device.leaseId } }, + }), + headers, + method: "POST", + }); + const reply = await exchange(context, listing, identity, "command", device.leaseId); + if (reply.reading.kind !== "success") return undefined; + const devices = asRecord(reply.reading.result["data"])?.["devices"]; + if (!Array.isArray(devices)) return undefined; + const own = devices.map(asRecord).find((entry) => String(entry?.["id"]) === device.address); + return { name: typeof own?.["name"] === "string" ? own["name"] : undefined }; +} diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index db0766243..119c0a198 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -2223,7 +2223,7 @@ describe( expect(answer.error).toBeUndefined(); const sent = member.fake.rpcRequests("agent_device.command").at(-1)?.params; const flags = (sent?.["flags"] ?? {}) as Record; - expect(flags["device"]).toBe(addressOfLease(rig, 1)); + expect(flags["device"]).toBe(`simlock-${addressOfLease(rig, 1)}`); }); it("after a gateway restart, a command naming a `deviceKey` on the adopted lease is accepted and sets it; a later command naming another `deviceKey` is refused `refused: simlock picks the device`", async () => { diff --git a/src/agent-device/testing.ts b/src/agent-device/testing.ts index 6390eb35e..3b36505e6 100644 --- a/src/agent-device/testing.ts +++ b/src/agent-device/testing.ts @@ -308,7 +308,7 @@ 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. + // why: agent-device 0.21.28 names no device in its allocate reply, so a test that needs one in the reply asks for it here; `"none"` is the default. nameDeviceInNextReply(device: FakeReplyDevice | "none"): void { this.#replyDevice = device; } @@ -522,9 +522,7 @@ export class FakeAgentDevice implements AgentDeviceUpstream { }); return envelope(id, { data: { - ...(picked === "none" || address === undefined - ? {} - : { device: { id: address, name: `simlock-${address}`, ...picked } }), + ...replyDevice(picked, address), lease: { ...scope, ...edit, leaseId, tenantId: tenant, ttlMs: params["ttlMs"] }, }, ok: true, @@ -670,6 +668,16 @@ export class FakeAgentDevice implements AgentDeviceUpstream { if ("body" in inventory) return new Response(inventory.body, { status: 200 }); return envelope(id, { data: { devices: inventory.list }, ok: true }); } + // why: agent-device names a leased device `simlock-` in its inventory only, never in the allocate reply. + if (command === "devices" && typeof leaseId === "string" && this.leases.has(leaseId)) { + const address = this.leases.get(leaseId)?.address; + if (address !== undefined) { + return envelope(id, { + data: { devices: [{ id: address, name: `simlock-${address}` }] }, + ok: true, + }); + } + } if (endedLeases.length > 0) { const data = command === "batch" ? { endedLeases, results: [] } : { endedLeases }; return envelope(id, { command, data, ok: true }); @@ -694,6 +702,15 @@ export class FakeAgentDevice implements AgentDeviceUpstream { } } +// why: agent-device's allocate reply names no device; only a test that asks for one gets one. +function replyDevice( + picked: FakeReplyDevice | "none" | undefined, + address: string | undefined, +): { readonly device?: Record } { + if (picked === undefined || picked === "none" || address === undefined) return {}; + return { device: { id: address, name: `simlock-${address}`, ...picked } }; +} + export function agentDeviceModuleWith(fakes: { readonly upstream?: AgentDeviceUpstream; readonly phoneUpstream?: AgentDeviceUpstream;