From e7c1bdfa13b55856cfeffeb939932b8f00532eb8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 22:56:40 +0200 Subject: [PATCH 1/5] test: devices, uploads, artifacts and diagnostics through a gateway (#516) --- src/agent-device/edge.test.ts | 23 ++ src/agent-device/gateway-front.test.ts | 352 +++++++++++++++++++++++++ src/agent-device/testing.ts | 3 + 3 files changed, 378 insertions(+) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 4fd685e44..1df351cb2 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -1325,6 +1325,29 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(rig.fake.uploads).toEqual(["artifact bytes"]); }); + it("on a worker, an `x-agent-device-lease-id` header naming another token's lease, a malformed one and no header are each forwarded, as today", async () => { + const rig = await setUp(); + await granted(rig, 1); + const other = { "x-agent-device-lease-id": hex(1) }; + const malformed = { "x-agent-device-lease-id": "NOT-A-LEASE-ID".repeat(4) }; + const preflights = () => + rig.fake.requests.filter((request) => request.path === "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/upload/preflight").length; + + const answers: Response[] = []; + for (const headers of [other, malformed, {}]) { + const before = preflights(); + const answer = await send(rig, "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/upload/preflight", { + body: "{}", + headers, + token: secrets.two, + }); + answers.push(answer); + expect(preflights()).toBe(before + 1); + } + + expect(answers.map((answer) => answer.status)).toEqual([200, 200, 200]); + }); + it("an `/rpc` body over 1 MiB, one that is not JSON, a JSON array, and an object with no `method` are each refused with their message and `id: null`, also while agent-device is unavailable, and neither simlock nor the agent-device daemon sees them", async () => { const rig = await setUp(); expect((await command(rig, "snapshot", undefined)).status).toBe(200); diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index a43a333a4..04b72f1a3 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -1265,3 +1265,355 @@ describe("the agent-device front, through a gateway", { timeout: 60_000 }, () => expect((await fleetLeases(rig)).map((lease) => lease.id)).toContain(hex(2)); }); }); + +const LEASE_HEADER = "x-agent-device-lease-id"; +const notYoursOnGateway = (n: number): string => + `refused: lease ${hex(n)} is not one of yours on this gateway`; +const notALeaseId = "refused: the x-agent-device-lease-id header is not a lease id"; + +function leased(n: number): Record { + return { [LEASE_HEADER]: hex(n) }; +} + +function holderOf(rig: Rig, n: number): Member { + const member = rig.members.find((candidate) => candidate.fake.leases.has(hex(n))); + if (member === undefined) throw new Error(`no worker holds the agent-device lease ${hex(n)}`); + return member; +} + +// why: a worker with room for one lease each puts two leases on two workers. +async function twoLeasesOnTwoWorkers(): Promise { + const rig = await setUp({ + workers: [ + { label: "w1", maxRunning: 1 }, + { label: "w2", maxRunning: 1 }, + ], + }); + await granted(rig, 1); + await granted(rig, 2); + expect(holderOf(rig, 1)).not.toBe(holderOf(rig, 2)); + return rig; +} + +function addressOfLease(rig: Rig, n: number): string { + const address = holderOf(rig, n).fake.leases.get(hex(n))?.address; + expect(address).toBeDefined(); + return address as string; +} + +function pathsReceived(member: Member): string[] { + return member.fake.requests.map((request) => request.path); +} + +async function listedNames(response: Response): Promise { + const answer = await envelopeOf(response); + const data = answer.result?.["data"] as { devices?: { name?: string }[] } | undefined; + expect(Array.isArray(data?.devices), "expected a devices list in result.data").toBe(true); + return (data?.devices ?? []).map((device) => String(device.name)).sort(); +} + +describe("the agent-device front, through a gateway: the lease header", { timeout: 60_000 }, () => { + it("through the gateway, an upload preflight with the header naming the token's lease on W2 reaches W2's agent-device daemon and not W1's", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const target = holderOf(rig, 2); + const other = holderOf(rig, 1); + const before = pathsReceived(other); + + const preflight = await send(rig, "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/upload/preflight", { body: "{}", headers: leased(2) }); + + expect(preflight.status).toBe(200); + expect(pathsReceived(target)).toContain("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/upload/preflight"); + expect(pathsReceived(other)).toEqual(before); + }); + + it("the preflight's ticket URL names the gateway's origin, its `upload.headers` carry the caller's own `authorization`, W2 received no `authorization` or `x-agent-device-token`, and a `PUT` to it with the lease header and those headers reaches W2", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const target = holderOf(rig, 2); + + const preflight = await send(rig, "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/upload/preflight", { + body: "{}", + headers: { ...leased(2), "x-agent-device-token": "caller-token" }, + }); + + const ticket = ( + (await preflight.json()) as { upload: { url: string; headers: Record } } + ).upload; + expect(ticket.url.startsWith(`${rig.origin}/v1/agent-device/upload/direct/`)).toBe(true); + const named = (name: string) => + Object.entries(ticket.headers).find(([key]) => key.toLowerCase() === name)?.[1]; + expect(named("authorization")).toBe(`Bearer ${secrets.one}`); + expect(named("x-agent-device-token")).toBe("caller-token"); + const seen = target.fake.preflightHeaders[0] ?? {}; + expect(seen["authorization"]).toBe(`Bearer ${target.fake.token}`); + expect(seen["x-agent-device-token"]).toBeUndefined(); + + const put = await fetch(ticket.url, { + body: "artifact bytes", + headers: { ...ticket.headers, ...leased(2) }, + method: "PUT", + }); + + expect(put.status).toBe(200); + expect(target.fake.uploads).toEqual(["artifact bytes"]); + expect(holderOf(rig, 1).fake.uploads).toEqual([]); + }); + + it("a finalize, a `POST /upload`, a `GET artifacts/` and a diagnostics `GET`, each with the header, reach the lease's worker", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const target = holderOf(rig, 2); + const other = holderOf(rig, 1); + const before = pathsReceived(other); + const diagnostics = `/sessions/${principals.one}:s1/requests/r1/diagnostics`; + + await send(rig, "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/upload/finalize", { body: "{}", headers: leased(2) }); + await send(rig, "/upload", { body: "{}", headers: leased(2) }); + await send(rig, "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/artifacts/a.png", { headers: leased(2) }); + await send(rig, diagnostics, { headers: leased(2) }); + + const paths = pathsReceived(target); + expect(paths).toContain("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/upload/finalize"); + expect(paths).toContain("/upload"); + expect(paths).toContain("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/artifacts/a.png"); + expect(paths).toContain(diagnostics); + expect(pathsReceived(other)).toEqual(before); + }); + + it("through the gateway, the same requests without the header, or with an empty one, and a `GET artifacts` list, are refused with `refused: this agent-device is too old to use through a gateway; update it`", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const diagnostics = `/sessions/${principals.one}:s1/requests/r1/diagnostics`; + const calls: readonly { path: string; body?: string }[] = [ + { body: "{}", path: "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/upload/preflight" }, + { body: "{}", path: "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/upload/finalize" }, + { body: "{}", path: "/upload" }, + { path: "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/artifacts/a.png" }, + { path: diagnostics }, + ]; + for (const call of calls) { + const accepted = await send(rig, call.path, { + ...(call.body === undefined ? {} : { body: call.body }), + headers: leased(2), + }); + expect(await accepted.text()).not.toContain(tooOld); + } + const before = rig.members.map((member) => member.fake.requests.length); + + for (const call of calls) { + for (const headers of [{}, { [LEASE_HEADER]: "" }]) { + const answer = await send(rig, call.path, { + ...(call.body === undefined ? {} : { body: call.body }), + headers, + }); + expect(await answer.text()).toContain(tooOld); + } + } + const list = await send(rig, "/artifacts"); + expect(await list.text()).toContain(tooOld); + + expect(rig.members.map((member) => member.fake.requests.length)).toEqual(before); + }); + + it("through the gateway, a header naming another token's lease is refused `refused: lease is not one of yours on this gateway` with status 403, and no agent-device daemon receives it", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const own = await send(rig, "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/upload/preflight", { body: "{}", headers: leased(2) }); + expect(own.status).toBe(200); + const before = rig.members.map((member) => member.fake.requests.length); + + const other = await send(rig, "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/upload/preflight", { + body: "{}", + headers: leased(2), + token: secrets.two, + }); + + expect(other.status).toBe(403); + expect(await other.text()).toContain(notYoursOnGateway(2)); + expect(rig.members.map((member) => member.fake.requests.length)).toEqual(before); + }); + + it("through the gateway, a header of 40 characters, and one with upper-case hex, are refused `refused: the x-agent-device-lease-id header is not a lease id` with status 400, and the reply does not contain the value", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const accepted = await send(rig, "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/upload/preflight", { body: "{}", headers: leased(2) }); + expect(accepted.status).toBe(200); + const before = rig.members.map((member) => member.fake.requests.length); + + for (const value of ["a".repeat(40), `ABCDEF${"0".repeat(26)}`]) { + const answer = await send(rig, "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/upload/preflight", { + body: "{}", + headers: { [LEASE_HEADER]: value }, + }); + const text = await answer.text(); + expect(answer.status).toBe(400); + expect(text).toContain(notALeaseId); + expect(text).not.toContain(value); + } + + expect(rig.members.map((member) => member.fake.requests.length)).toEqual(before); + }); + + it("through the gateway, a header naming the token's lease whose worker stopped being capable answers the notAvailable reply naming that reason", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const accepted = await send(rig, "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/upload/preflight", { body: "{}", headers: leased(2) }); + expect(accepted.status).toBe(200); + const target = holderOf(rig, 2); + await turn(rig, target, "unavailable"); + const before = pathsReceived(target); + + const answer = await send(rig, "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/upload/preflight", { body: "{}", headers: leased(2) }); + + expect(await answer.text()).toContain(`${notAvailable}${holderCannot}`); + expect(pathsReceived(target)).toEqual(before); + }); + + it("through the gateway, `/health` with a header naming another token's lease answers the proxy's health", async () => { + const rig = await twoLeasesOnTwoWorkers(); + + const health = await send(rig, "/health", { headers: leased(2), token: secrets.two }); + + expect(health.status).toBe(200); + expect(await health.json()).toMatchObject({ service: "agent-device-proxy" }); + }); + + it("through the gateway, an upload naming the token's lease after `simlock release --all` reaches that lease's worker", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const target = holderOf(rig, 2); + await rig.gateway.dispatch("lease.release-all", {}, adminSession); + await expect.poll(async () => (await fleetLeases(rig)).length).toBe(0); + const before = pathsReceived(target).filter((path) => path === "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/upload/preflight").length; + + const preflight = await send(rig, "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/upload/preflight", { body: "{}", headers: leased(2) }); + + expect(await preflight.text()).not.toContain(notYoursOnGateway(2)); + expect(pathsReceived(target).filter((path) => path === "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/upload/preflight").length).toBe( + before + 1, + ); + }); + + it("through the gateway, `devices` with no lease held answers an empty list and no agent-device daemon receives it", async () => { + const rig = await setUp({ workers: [{ label: "w1" }, { label: "w2" }] }); + for (const member of rig.members) member.fake.listDevices([{ id: "stray", name: "stray" }]); + + const answer = await envelopeOf(await command(rig, "devices", undefined)); + + expect(answer.result).toMatchObject({ data: { devices: [] }, ok: true }); + for (const member of rig.members) { + expect(member.fake.rpcRequests("agent_device.command")).toEqual([]); + } + }); + + it("through the gateway, `devices` with leases on W1 and W2 answers both devices, each once, and no device of another token", async () => { + const rig = await twoLeasesOnTwoWorkers(); + for (const [index, n] of [1, 2].entries()) { + holderOf(rig, n).fake.listDevices([ + { id: addressOfLease(rig, n), name: `mine-${String(index)}` }, + { id: "another-token-device", name: "foreign" }, + ]); + } + + expect(await listedNames(await command(rig, "devices", undefined))).toEqual([ + "mine-0", + "mine-1", + ]); + }); + + it("through the gateway, `devices` with leases on W1 and W2 whose emulators are both `emulator-5554` answers both, each from its own worker", async () => { + const rig = await twoLeasesOnTwoWorkers(); + expect(addressOfLease(rig, 1)).toBe(addressOfLease(rig, 2)); + holderOf(rig, 1).fake.listDevices([{ id: addressOfLease(rig, 1), name: "from-first" }]); + holderOf(rig, 2).fake.listDevices([{ id: addressOfLease(rig, 2), name: "from-second" }]); + + expect(await listedNames(await command(rig, "devices", undefined))).toEqual([ + "from-first", + "from-second", + ]); + }); + + it("through the gateway, `devices` with two leases on one worker answers both devices, each once", async () => { + const rig = await setUp({ workers: [{ label: "w1", maxRunning: 2 }] }); + await granted(rig, 1); + await granted(rig, 2); + const member = first(rig); + member.fake.listDevices([ + { id: addressOfLease(rig, 1), name: "first" }, + { id: addressOfLease(rig, 2), name: "second" }, + { id: "another-token-device", name: "foreign" }, + ]); + + expect(await listedNames(await command(rig, "devices", undefined))).toEqual([ + "first", + "second", + ]); + }); + + it("through the gateway, `devices` when W2's agent-device answers an error passes that error on; when W2 answers a body with no list, it answers `could not read the device list from the worker holding lease ` with status 502", async () => { + const rig = await twoLeasesOnTwoWorkers(); + holderOf(rig, 1).fake.listDevices([{ id: addressOfLease(rig, 1), name: "first" }]); + const second = holderOf(rig, 2).fake; + second.answerDevicesWith( + JSON.stringify({ + error: { + code: -32000, + data: { code: "COMMAND_FAILED", message: "inventory down" }, + message: "inventory down", + }, + id: 1, + jsonrpc: "2.0", + }), + ); + + const failed = await envelopeOf(await command(rig, "devices", undefined)); + + expect(failed.error?.message).toBe("inventory down"); + + second.answerDevicesWith( + JSON.stringify({ id: 1, jsonrpc: "2.0", result: { data: {}, ok: true } }), + ); + const unreadable = await command(rig, "devices", undefined); + + expect(unreadable.status).toBe(502); + expect((await envelopeOf(unreadable)).error?.message).toBe( + `could not read the device list from the worker holding lease ${hex(2)}`, + ); + }); + + it("through the gateway, a CLI that hangs up during `devices` aborts every forward", async () => { + const rig = await twoLeasesOnTwoWorkers(); + for (const member of rig.members) member.fake.holdCommand(); + const hangUp = new AbortController(); + const held = track(command(rig, "devices", undefined, { signal: hangUp.signal })); + await expect + .poll(() => + rig.members.map((member) => member.fake.rpcRequests("agent_device.command").length), + ) + .toEqual([1, 1]); + + hangUp.abort(); + await held.promise.catch(() => undefined); + + await expect + .poll(() => rig.members.map((member) => member.fake.abortedCommands)) + .toEqual([["devices"], ["devices"]]); + }); + + it("through the gateway, `release_materialized_paths` is refused `refused: this agent-device is too old to use through a gateway; update it`, and an `install_from_source` naming the token's lease reaches its worker", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const target = holderOf(rig, 2); + const before = rig.members.map((member) => member.fake.requests.length); + + const released = await envelopeOf( + await rpc(rig, "agent_device.release_materialized_paths", { + materializationId: "m-1", + }), + ); + + expect(released.error?.message).toBe(tooOld); + expect(rig.members.map((member) => member.fake.requests.length)).toEqual(before); + + await rpc(rig, "agent_device.install_from_source", { + meta: { leaseId: hex(2) }, + platform: "ios", + source: { kind: "url", url: "https://example.com/App.zip" }, + }); + + expect(target.fake.rpcRequests("agent_device.install_from_source")).toHaveLength(1); + expect(holderOf(rig, 1).fake.rpcRequests("agent_device.install_from_source")).toHaveLength(0); + }); +}); diff --git a/src/agent-device/testing.ts b/src/agent-device/testing.ts index 19dee13ca..4255f2014 100644 --- a/src/agent-device/testing.ts +++ b/src/agent-device/testing.ts @@ -146,6 +146,8 @@ export class FakeAgentDevice implements AgentDeviceUpstream { readonly hungUpReleases: string[] = []; readonly refused: string[] = []; readonly uploads: string[] = []; + // why: the headers the proxy sent the daemon with each upload preflight, so a test can see which of the caller's credentials reached it. + readonly preflightHeaders: Record[] = []; baseUrl = "http://127.0.0.1:47001"; token = "daemon-token-1"; generation = 1; @@ -339,6 +341,7 @@ export class FakeAgentDevice implements AgentDeviceUpstream { return Response.json({ ok: true, rpcProtocolVersion: 2, service: "agent-device-daemon" }); } if (url.pathname === "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/upload/preflight") { + this.preflightHeaders.push(Object.fromEntries(request.headers)); this.requests.push({ method: request.method, path: url.pathname, tenant: tenantHeader }); return Response.json({ ok: true, From 8ca801fadc55f02c4c8818174c353251e74bca10 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 22:59:54 +0200 Subject: [PATCH 2/5] feat(agent-device): uploads, artifacts, diagnostics and devices through a gateway (#516) 2 failing -> 0 failing --- docs/HTTP-API.md | 17 +++- src/agent-device/dispose.test.ts | 1 + src/agent-device/front/devices-filter.ts | 102 ++++++++++++++++++++++ src/agent-device/front/front.ts | 68 +++++++++++++-- src/agent-device/front/host-link.ts | 4 + src/agent-device/front/relay-host-link.ts | 1 + src/agent-device/gateway-front.test.ts | 8 +- src/agent-device/shared/paths.ts | 3 + 8 files changed, 195 insertions(+), 9 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index cb62dd649..c5bb0afe3 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1504,9 +1504,22 @@ agent-device session with an agent on a worker's own tokens. Through a gateway: with status 200. - A worker that is draining takes no new `open`, and keeps serving the leases it holds. -- A request that names no lease, other than `/health`, is refused with +- Uploads, artifact downloads and diagnostics name their lease in the + `x-agent-device-lease-id: ` header, which agent-device sends once + it holds a lease. The request goes to the worker holding that lease. An + upload ticket works through the gateway: it carries your own `authorization` + and `x-agent-device-token`, so the `PUT` that follows reaches the gateway + with them, and the worker never sees your token. A header that is not 32 + lower-case hex characters is refused with `refused: the + x-agent-device-lease-id header is not a lease id` (status 400). `/health` + does not read the header. +- A request that names no lease, or sends the header empty, other than + `/health`, is refused with `refused: this agent-device is too old to use through a gateway; update it`. - That includes `devices`, uploads, artifact downloads and diagnostics. + That includes an upload, an artifact download or a diagnostics request with + no header, and the artifact list. +- `devices` lists your devices across every worker that holds one of your + leases, and answers an empty list when you hold none. - A request that names a lease the token does not hold, or the gateway does not know, is refused with `refused: lease is not one of yours on this gateway` (status 403). A lease `simlock release --all` ended stays known for diff --git a/src/agent-device/dispose.test.ts b/src/agent-device/dispose.test.ts index 18df538df..fcf5432d9 100644 --- a/src/agent-device/dispose.test.ts +++ b/src/agent-device/dispose.test.ts @@ -16,6 +16,7 @@ describe("disposeAgentDeviceEdge", () => { }, forward: () => Promise.reject(new Error("unused")), leaseRequires: [], + readsLeaseHeader: false, status: () => Promise.resolve({ reason: "unused", state: "unavailable" }), }; const parts: AgentDeviceFrontParts = { link, map: new FrontMap(clock), renewals }; diff --git a/src/agent-device/front/devices-filter.ts b/src/agent-device/front/devices-filter.ts index 7ab11033a..ee1aa9a12 100644 --- a/src/agent-device/front/devices-filter.ts +++ b/src/agent-device/front/devices-filter.ts @@ -40,3 +40,105 @@ export async function filterDevices( body.result.data["devices"] = kept; return relay({ response, text: JSON.stringify(body) }); } + +interface GatewayDevices { + readonly request: Request; + readonly identity: TokenIdentity; + readonly read: { readonly id: unknown; readonly text: string }; + readonly forward: (request: Request, leaseId: string) => Promise; +} + +type Piece = + | { + readonly kind: "list"; + readonly response: Response; + readonly text: string; + readonly devices: unknown[]; + } + | { readonly kind: "failed"; readonly response: Response }; + +function unreadable(leaseId: string, rpc: { readonly id: unknown }): Response { + return frontReply( + failure(`could not read the device list from the worker holding lease ${leaseId}`), + rpc, + ); +} + +async function readPiece( + response: Response, + address: string, + leaseId: string, + rpc: { readonly id: unknown }, +): Promise { + const text = await readBounded(response.body); + if (text === undefined) return { kind: "failed", response: unreadable(leaseId, rpc) }; + const reading = readReply(text); + if (reading.kind === "error") return { kind: "failed", response: relay({ response, text }) }; + const devices = asRecord(reading.kind === "success" ? reading.result["data"] : undefined)?.[ + "devices" + ]; + if ( + reading.kind !== "success" || + !Array.isArray(devices) || + !devices.every((device) => asRecord(device) !== undefined) + ) { + return { kind: "failed", response: unreadable(leaseId, rpc) }; + } + const own = devices.filter((device) => String(asRecord(device)?.["id"]) === address); + return { devices: own, kind: "list", response, text }; +} + +// why: each worker answers with everything its daemon sees; cutting each answer to its own lease's device before joining keeps two workers' equal ids apart and other tokens' devices out. +export async function devicesThroughGateway( + context: FrontContext, + { forward, identity, read, request }: GatewayDevices, +): Promise { + let held: Awaited>; + try { + held = await tokenDevices(context, identity); + } catch (error) { + if (!(error instanceof LeaseCheckFailed)) throw error; + return frontReply(failure(error.message), read); + } + if (held.length === 0) return emptyList(read); + const cancel = new AbortController(); + const signal = AbortSignal.any([request.signal, cancel.signal]); + const pieces = await Promise.all( + held.map(async (lease) => { + const forwarded = new Request(request.url, { + body: read.text, + headers: withoutLength(request.headers), + method: request.method, + signal, + }); + let piece: Piece; + try { + piece = await readPiece( + await forward(forwarded, lease.leaseId), + lease.address, + lease.leaseId, + read, + ); + } catch { + piece = { kind: "failed", response: unreadable(lease.leaseId, read) }; + } + const cancelledByUs = piece.kind === "failed" && cancel.signal.aborted; + if (piece.kind === "failed") cancel.abort(); + return { cancelledByUs, piece }; + }), + ); + const failed = pieces.find((entry) => entry.piece.kind === "failed" && !entry.cancelledByUs); + if (failed !== undefined) return (failed.piece as { response: Response }).response; + const lists = pieces.flatMap((entry) => (entry.piece.kind === "list" ? [entry.piece] : [])); + const [firstList] = lists; + if (firstList === undefined) return emptyList(read); + const body = JSON.parse(firstList.text) as { result: { data: Record } }; + body.result.data["devices"] = lists.flatMap((entry) => entry.devices); + return relay({ response: firstList.response, text: JSON.stringify(body) }); +} + +function withoutLength(source: Headers): Headers { + const headers = new Headers(source); + headers.delete("content-length"); + return headers; +} diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index 925522f18..e6cc90e3f 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -1,6 +1,6 @@ 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 { FRONT_MOUNT, FRONT_PREFIX, LEASE_HEADER } 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"; @@ -15,8 +15,8 @@ import { type RpcRead, } from "../shared/rpc.js"; import { allocate } from "./allocate.js"; -import type { FrontContext } from "./context.js"; -import { filterDevices } from "./devices-filter.js"; +import { relay, type FrontContext } from "./context.js"; +import { devicesThroughGateway, filterDevices } from "./devices-filter.js"; import { heartbeat } from "./heartbeat.js"; import { release } from "./release.js"; import { checkRequest } from "./request-rules.js"; @@ -181,10 +181,18 @@ async function forwardCommand( read: RpcRequest, leaseId: string | undefined, ): Promise { - const response = await passThrough(context, request, identity, read, leaseId); const isDevices = methodName(read.method) === "command" && commandName(asRecord(read.params)?.["command"]) === "devices"; + if (isDevices && context.link.readsLeaseHeader) { + return devicesThroughGateway(context, { + forward: (forwarded, held) => passThrough(context, forwarded, identity, read, held), + identity, + read, + request, + }); + } + const response = await passThrough(context, request, identity, read, leaseId); return isDevices ? filterDevices(context, identity, response, read) : response; } @@ -232,6 +240,53 @@ async function passThrough( } } +const TICKET_HEADERS = ["authorization", "x-agent-device-token"] as const; + +// why: the relay drops the caller's credentials, so the worker's ticket has none; the CLI sends the ticket's headers with its PUT, which reaches the gateway. +async function withCallerCredentials(request: Request, response: Response): Promise { + const text = await response.text(); + try { + const body: unknown = JSON.parse(text); + const upload = asRecord(asRecord(body)?.["upload"]); + if (upload === undefined) return relay({ response, text }); + const headers = { ...asRecord(upload["headers"]) }; + for (const name of TICKET_HEADERS) { + const value = request.headers.get(name); + if (value !== null) headers[name] = value; + } + upload["headers"] = headers; + return relay({ response, text: JSON.stringify(body) }); + } catch { + return relay({ response, text }); + } +} + +async function routeByHeader( + context: FrontContext, + request: Request, + identity: TokenIdentity, +): Promise { + const header = request.headers.get(LEASE_HEADER); + const value = header === null || header === "" ? undefined : header; + const leaseId = value === undefined ? undefined : leaseIdOf(value); + if (value !== undefined && leaseId === undefined) { + return frontReply( + refusal("refused: the x-agent-device-lease-id header is not a lease id"), + undefined, + ); + } + if (leaseId !== undefined) { + const status = await context.link.status(leaseId, identity); + if (status.state === "unavailable") return frontReply(notAvailable(status.reason), undefined); + } + const response = await passThrough(context, request, identity, undefined, leaseId); + const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); + const preflight = request.method === "POST" && path === "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/upload/preflight"; + return leaseId !== undefined && preflight && response.ok + ? withCallerCredentials(request, response) + : response; +} + export function createFront(context: FrontContext): HttpMount { return { handle: async (request, identity) => { @@ -254,7 +309,10 @@ export function createFront(context: FrontContext): HttpMount { undefined, ); } - return passThrough(context, request, identity, undefined, undefined, probe); + if (probe || !context.link.readsLeaseHeader) { + return passThrough(context, request, identity, undefined, undefined, probe); + } + return routeByHeader(context, request, identity); }, prefix: FRONT_MOUNT, }; diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index 2f3f729d2..a28eae9e1 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -12,6 +12,8 @@ export type LinkStatus = | { readonly state: "unavailable"; readonly reason: string }; export interface HostLink { + // why: only a link that serves many hosts routes non-RPC requests by the lease header and fans out `devices`; a worker never reads the header. + readonly readsLeaseHeader: boolean; // why: capabilities a lease request must require so it lands on a host that can serve agent-device; none means any worker. readonly leaseRequires?: readonly string[]; status(leaseId?: string, identity?: TokenIdentity): Promise; @@ -20,6 +22,8 @@ export interface HostLink { } export class InProcessHostLink implements HostLink { + readonly readsLeaseHeader = false; + constructor(private readonly host: AgentDeviceHost) {} status(): ReturnType { diff --git a/src/agent-device/front/relay-host-link.ts b/src/agent-device/front/relay-host-link.ts index bcac03a08..fe7d71366 100644 --- a/src/agent-device/front/relay-host-link.ts +++ b/src/agent-device/front/relay-host-link.ts @@ -76,6 +76,7 @@ function refuseRequest(request: Request, message: string, status?: number): Prom export class RelayHostLink implements HostLink { readonly leaseRequires: readonly string[] = ["agent-device"]; + readonly readsLeaseHeader = true; readonly #kept = new Map(); #sweep: TimerHandle | undefined; #disposed = false; diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index 04b72f1a3..581b36107 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -1345,7 +1345,8 @@ describe("the agent-device front, through a gateway: the lease header", { timeou expect(named("x-agent-device-token")).toBe("caller-token"); const seen = target.fake.preflightHeaders[0] ?? {}; expect(seen["authorization"]).toBe(`Bearer ${target.fake.token}`); - expect(seen["x-agent-device-token"]).toBeUndefined(); + // why: the proxy sends its own daemon token in both headers, never the caller's. + expect(seen["x-agent-device-token"]).toBe(target.fake.token); const put = await fetch(ticket.url, { body: "artifact bytes", @@ -1363,9 +1364,12 @@ describe("the agent-device front, through a gateway: the lease header", { timeou const target = holderOf(rig, 2); const other = holderOf(rig, 1); const before = pathsReceived(other); - const diagnostics = `/sessions/${principals.one}:s1/requests/r1/diagnostics`; await send(rig, "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/upload/finalize", { body: "{}", headers: leased(2) }); + // why: the proxy confines diagnostics to sessions under the caller's tenant, which the gateway names. + const tenant = target.fake.requests.at(-1)?.tenant; + expect(tenant).toBeDefined(); + const diagnostics = `/sessions/${String(tenant)}:s1/requests/r1/diagnostics`; await send(rig, "/upload", { body: "{}", headers: leased(2) }); await send(rig, "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/artifacts/a.png", { headers: leased(2) }); await send(rig, diagnostics, { headers: leased(2) }); diff --git a/src/agent-device/shared/paths.ts b/src/agent-device/shared/paths.ts index 18a61fc15..c1cd74239 100644 --- a/src/agent-device/shared/paths.ts +++ b/src/agent-device/shared/paths.ts @@ -3,3 +3,6 @@ export const FRONT_MOUNT = "agent-device"; export const FRONT_PREFIX = `/v1/${FRONT_MOUNT}`; export const PROXY_BASE_PATH = "/agent-device"; + +// why: agent-device sends this header on every upload, artifact download and diagnostics request once it holds a lease; a gateway routes by it. +export const LEASE_HEADER = "x-agent-device-lease-id"; From f393092d9c3d153fba12798f89b4efa5bb3310f6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 23:00:40 +0200 Subject: [PATCH 3/5] refactor(agent-device): split the front's plain-route handling (#516) --- src/agent-device/front/front.ts | 77 +++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 33 deletions(-) diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index e6cc90e3f..e7fa7bfbf 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -261,30 +261,57 @@ async function withCallerCredentials(request: Request, response: Response): Prom } } +type HeaderLease = { readonly leaseId: string | undefined } | { readonly refused: Response }; + +function readLeaseHeader(request: Request): HeaderLease { + const header = request.headers.get(LEASE_HEADER); + if (header === null || header === "") return { leaseId: undefined }; + const leaseId = leaseIdOf(header); + if (leaseId !== undefined) return { leaseId }; + return { + refused: frontReply( + refusal("refused: the x-agent-device-lease-id header is not a lease id"), + undefined, + ), + }; +} + async function routeByHeader( context: FrontContext, request: Request, identity: TokenIdentity, ): Promise { - const header = request.headers.get(LEASE_HEADER); - const value = header === null || header === "" ? undefined : header; - const leaseId = value === undefined ? undefined : leaseIdOf(value); - if (value !== undefined && leaseId === undefined) { - return frontReply( - refusal("refused: the x-agent-device-lease-id header is not a lease id"), - undefined, - ); - } - if (leaseId !== undefined) { - const status = await context.link.status(leaseId, identity); - if (status.state === "unavailable") return frontReply(notAvailable(status.reason), undefined); - } + const read = readLeaseHeader(request); + if ("refused" in read) return read.refused; + const { leaseId } = read; + if (leaseId === undefined) return passThrough(context, request, identity, undefined); + const status = await context.link.status(leaseId, identity); + if (status.state === "unavailable") return frontReply(notAvailable(status.reason), undefined); const response = await passThrough(context, request, identity, undefined, leaseId); const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); const preflight = request.method === "POST" && path === "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/upload/preflight"; - return leaseId !== undefined && preflight && response.ok - ? withCallerCredentials(request, response) - : response; + return preflight && response.ok ? withCallerCredentials(request, response) : response; +} + +async function handlePlain( + context: FrontContext, + request: Request, + identity: TokenIdentity, +): Promise { + const status = await context.link.status(); + const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); + const probe = request.method === "GET" && path === "/health"; + if (status.state === "unavailable") { + const reply = notAvailable(status.reason); + return frontReply(probe ? { ...reply, status: HEALTH_STATUS } : reply, undefined); + } + if (!isKnownRoute(request.method, path)) { + return frontReply(refusal(`refused: unknown route ${request.method} ${path}`, 404), undefined); + } + if (probe || !context.link.readsLeaseHeader) { + return passThrough(context, request, identity, undefined, undefined, probe); + } + return routeByHeader(context, request, identity); } export function createFront(context: FrontContext): HttpMount { @@ -296,23 +323,7 @@ export function createFront(context: FrontContext): HttpMount { return frontReply(refusal(AGENT_TOKEN_ONLY, 403), isRpc ? { id: null } : undefined); } if (isRpc) return handleRpc(context, request, identity); - const status = await context.link.status(); - const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); - const probe = request.method === "GET" && path === "/health"; - if (status.state === "unavailable") { - const reply = notAvailable(status.reason); - return frontReply(probe ? { ...reply, status: HEALTH_STATUS } : reply, undefined); - } - if (!isKnownRoute(request.method, path)) { - return frontReply( - refusal(`refused: unknown route ${request.method} ${path}`, 404), - undefined, - ); - } - if (probe || !context.link.readsLeaseHeader) { - return passThrough(context, request, identity, undefined, undefined, probe); - } - return routeByHeader(context, request, identity); + return handlePlain(context, request, identity); }, prefix: FRONT_MOUNT, }; From c6ef3cc9bfede203a1731b15b12062ea638ba9c6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 23:14:11 +0200 Subject: [PATCH 4/5] test(agent-device): wait for the gateway to list both leases before asking for devices (#516) --- src/agent-device/gateway-front.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index 581b36107..8f81f50cb 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -1281,6 +1281,11 @@ function holderOf(rig: Rig, n: number): Member { return member; } +// why: the gateway lists a lease only once its worker's next view reaches it, which can trail the grant. +async function listedByGateway(rig: Rig, count: number): Promise { + await expect.poll(async () => (await fleetLeases(rig)).length).toBe(count); +} + // why: a worker with room for one lease each puts two leases on two workers. async function twoLeasesOnTwoWorkers(): Promise { const rig = await setUp({ @@ -1291,6 +1296,7 @@ async function twoLeasesOnTwoWorkers(): Promise { }); await granted(rig, 1); await granted(rig, 2); + await listedByGateway(rig, 2); expect(holderOf(rig, 1)).not.toBe(holderOf(rig, 2)); return rig; } @@ -1534,6 +1540,7 @@ describe("the agent-device front, through a gateway: the lease header", { timeou const rig = await setUp({ workers: [{ label: "w1", maxRunning: 2 }] }); await granted(rig, 1); await granted(rig, 2); + await listedByGateway(rig, 2); const member = first(rig); member.fake.listDevices([ { id: addressOfLease(rig, 1), name: "first" }, From 89e9993ee731aff855ccdf06795defe814944a75 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 23:22:05 +0200 Subject: [PATCH 5/5] test(agent-device): gateway devices lease-check failure, sibling cancel, and credential leak proven (#516) --- src/agent-device/gateway-front.test.ts | 52 +++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index 8f81f50cb..b7b004de0 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -555,6 +555,7 @@ interface DispatchTap { readonly operations: string[]; readonly inputs: { readonly operation: string; readonly input: Record }[]; afterNext(operation: string, run: () => Promise): void; + rejectNext(operation: string): void; } // why: the front reaches simlock through `daemon.dispatch` looked up at call time, so a wrapper on the daemon object sits between the front and leasing. @@ -564,8 +565,10 @@ function tapDispatch(daemon: DaemonServer): DispatchTap { const operations: string[] = []; const inputs: { operation: string; input: Record }[] = []; const afters = new Map Promise>(); + const rejections = new Set(); target.dispatch = async (operation, input, session) => { operations.push(operation); + if (rejections.delete(operation)) throw new Error(`${operation} failed`); inputs.push({ input: (input ?? {}) as Record, operation }); const result = await original(operation, input, session); const after = afters.get(operation); @@ -573,7 +576,12 @@ function tapDispatch(daemon: DaemonServer): DispatchTap { await after?.(); return result; }; - return { afterNext: (operation, run) => afters.set(operation, run), inputs, operations }; + return { + afterNext: (operation, run) => afters.set(operation, run), + inputs, + operations, + rejectNext: (operation) => rejections.add(operation), + }; } type RelayFn = (workerId: string, call: unknown) => Promise; @@ -1332,7 +1340,7 @@ describe("the agent-device front, through a gateway: the lease header", { timeou expect(pathsReceived(other)).toEqual(before); }); - it("the preflight's ticket URL names the gateway's origin, its `upload.headers` carry the caller's own `authorization`, W2 received no `authorization` or `x-agent-device-token`, and a `PUT` to it with the lease header and those headers reaches W2", async () => { + it("the preflight's ticket URL names the gateway's origin, its `upload.headers` carry the caller's own `authorization`, W2 received its own daemon's token in `authorization` and `x-agent-device-token` and none of the caller's credentials, and a `PUT` to it with the lease header and those headers reaches W2", async () => { const rig = await twoLeasesOnTwoWorkers(); const target = holderOf(rig, 2); @@ -1353,6 +1361,8 @@ describe("the agent-device front, through a gateway: the lease header", { timeou expect(seen["authorization"]).toBe(`Bearer ${target.fake.token}`); // why: the proxy sends its own daemon token in both headers, never the caller's. expect(seen["x-agent-device-token"]).toBe(target.fake.token); + expect(Object.values(seen).join("\n")).not.toContain(secrets.one); + expect(Object.values(seen).join("\n")).not.toContain("caller-token"); const put = await fetch(ticket.url, { body: "artifact bytes", @@ -1585,6 +1595,44 @@ describe("the agent-device front, through a gateway: the lease header", { timeou ); }); + it("through the gateway, `devices` whose lease check fails answers `could not check your leases; try again`, not an empty list, and no daemon receives the command", async () => { + const rig = await twoLeasesOnTwoWorkers(); + for (const n of [1, 2]) { + holderOf(rig, n).fake.listDevices([ + { id: addressOfLease(rig, n), name: `mine-${String(n)}` }, + ]); + } + const tap = tapDispatch(rig.gateway); + tap.rejectNext("lease.list"); + const before = rig.members.map( + (member) => member.fake.rpcRequests("agent_device.command").length, + ); + + const answer = await envelopeOf(await command(rig, "devices", undefined)); + + expect(answer.error?.message).toBe("could not check your leases; try again"); + expect( + rig.members.map((member) => member.fake.rpcRequests("agent_device.command").length), + ).toEqual(before); + }); + + it("through the gateway, `devices` when W2 answers a body with no list aborts the forward still waiting on W1", async () => { + const rig = await twoLeasesOnTwoWorkers(); + const slow = holderOf(rig, 1).fake; + slow.holdCommand(); + holderOf(rig, 2).fake.answerDevicesWith( + JSON.stringify({ id: 1, jsonrpc: "2.0", result: { data: {}, ok: true } }), + ); + + const answer = await command(rig, "devices", undefined); + + expect(answer.status).toBe(502); + expect((await envelopeOf(answer)).error?.message).toBe( + `could not read the device list from the worker holding lease ${hex(2)}`, + ); + await expect.poll(() => slow.abortedCommands).toEqual(["devices"]); + }); + it("through the gateway, a CLI that hangs up during `devices` aborts every forward", async () => { const rig = await twoLeasesOnTwoWorkers(); for (const member of rig.members) member.fake.holdCommand();