diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index c583cfc36..e0fead921 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -164,7 +164,7 @@ because it owns no devices. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| | `worker.connected` | worker id, label, worker's daemon version | a worker's uplink opened and its `hello` completed, so the gateway can drive it. A worker whose `hello` found no overlapping protocol range emits nothing: it is in the registry as `incompatible`, which is where an operator finds it | WorkerRegistry | implemented | -| `worker.rejected` | reason (`unauthenticated`/`forbidden`), worker id, label, occasionally a count | an uplink was turned away at the door, before any session existed: `unauthenticated` (`401`) for a missing or unrecognized join token — a revoked or mistyped one lands here — and `forbidden` (`403`) for a real token whose role is not `worker`. Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing (see the note below the table). A refused peer proves no identity, so `workerId` and `label` are only what the connection claimed and may be absent. `count`, present only above one, is how many identical (reason, claimed id) refusals the *previous* coalescing window absorbed — `GatewayService` computes it before calling into the registry, so a flood of refused dials collapses to one event per window rather than one per attempt, since the ring buffer they land in is bounded by count, not bytes | WorkerRegistry | implemented | +| `worker.rejected` | reason (`unauthenticated`/`forbidden`/`worker-mismatch`), worker id, label, occasionally a count | an uplink was turned away at the door, before any session existed: `unauthenticated` (`401`) for a missing or unrecognized join token — a revoked or mistyped one lands here — `forbidden` (`403`) for a real token whose role is not `worker`, and `worker-mismatch` (`403`) for a join token pinned to another worker id, a worker id another token is pinned to, or an empty claimed id (a token is pinned to the first worker id that joins with it; `token revoke` frees both). Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing (see the note below the table). A refused peer proves no identity, so `workerId` and `label` are only what the connection claimed and may be absent. `count`, present only above one, is how many identical (reason, claimed id) refusals the *previous* coalescing window absorbed — `GatewayService` computes it before calling into the registry, so a flood of refused dials collapses to one event per window rather than one per attempt, since the ring buffer they land in is bounded by count, not bytes | WorkerRegistry | implemented | | `worker.disconnected` | worker id, label, lease count | a worker's uplink closed. `leaseCount` is what its view still shows it holding — how much is stranded, and why the view is kept rather than dropped, not ended: the gateway never guesses a lease is gone before the worker says so | WorkerRegistry | implemented | | `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every gateway-issued lease on it had expired and `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker (`WORKER_CONNECTED` refuses that) | WorkerRegistry | implemented | | `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented | diff --git a/docs/internal/adr/0005-gateway-and-worker-modes.md b/docs/internal/adr/0005-gateway-and-worker-modes.md index c30919256..8744e751b 100644 --- a/docs/internal/adr/0005-gateway-and-worker-modes.md +++ b/docs/internal/adr/0005-gateway-and-worker-modes.md @@ -5,6 +5,10 @@ - **Issue:** [#115](https://github.com/callstackincubator/simlock/issues/115) (sub-issues #116–#120, one per sequenced PR) - **Supersedes:** nothing +- **Amended:** §4 and requirement 22 by the maintainer's decision on the + join-token pin (PR #894): a join token is pinned to the first worker id + that uses it, and a mismatch is a third `worker.rejected` reason, + `worker-mismatch` (`403`). - **Depends on:** [ADR 0004](0004-ttl-first-leases-on-every-transport.md) > This record is a PRD and an ADR in one file: the first half says what the @@ -139,7 +143,10 @@ physical machine. its token store. The two ways that can fail are different facts and get different answers, as everywhere else in the API: a **missing or unrecognized token is `401`**, and a **valid token whose role is not - `worker` is `403`**. Either way nothing enters the worker registry and + `worker` is `403`**. A join token is pinned to the first worker id that + uses it: another claimed id, an id another token is pinned to, or no id + at all is `403` too, as `worker-mismatch`. Either way nothing enters the + worker registry and the gateway emits `worker.rejected` (requirement 22), which is the only trace an uplink refused at the door leaves. 5. Over the uplink the **gateway is the protocol client**: it sends `hello` @@ -445,8 +452,8 @@ drive the device it leased. (documented in `EVENTS.md` in the same change). `worker.rejected` covers an uplink refused at the door (requirement 4): payload `{ reason, workerId?, label?, protocol? }` with `reason` either - `unauthenticated` (`401`) or `forbidden` (`403`), everything else - optional because a dial that fails authentication proves no identity. + `unauthenticated` (`401`), `forbidden` (`403`) or `worker-mismatch` + (`403`), everything else optional because a dial that fails authentication proves no identity. Without it a refused uplink leaves no trace at all, and "why did that machine never appear" is exactly what an operator comes to the event stream to answer. `device.exec` deliberately emits **no** event: running diff --git a/e2e/console/activity.spec.ts b/e2e/console/activity.spec.ts index 922279806..5699176e8 100644 --- a/e2e/console/activity.spec.ts +++ b/e2e/console/activity.spec.ts @@ -703,7 +703,7 @@ test.describe("the Activity page", () => { }) => { const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]); try { - const joinToken = fleet.gateway.tokens.worker; + const [joinToken = ""] = fleet.joinTokens; await openEvents(page, fleet.gateway); await expect(rows(page).filter({ hasText: "worker.connected" })).not.toHaveCount(0); const events = await cliEvents(fleet.gateway); diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 3b5d64108..8b2bf0522 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -421,6 +421,14 @@ export async function startDaemon( export interface Fleet { readonly gateway: RunningDaemon; readonly workers: readonly RunningDaemon[]; + readonly joinTokens: readonly string[]; +} + +/** why: a gateway pins a join token to the first worker that joins with it, so each worker needs its own. */ +export async function mintJoinToken(gateway: RunningDaemon): Promise { + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + expect(minted.code, minted.stderr).toBe(0); + return (minted.json as { secret: string }).secret; } /** @@ -442,15 +450,18 @@ export async function startFleet( options.gatewayConfig === undefined ? {} : { config: options.gatewayConfig }, ); const started: RunningDaemon[] = []; + const joinTokens: string[] = []; try { for (const worker of workers) { + const token = await mintJoinToken(gateway); + joinTokens.push(token); started.push( await startDaemon("worker", { config: { ...worker.config, gateway: { label: worker.label, - token: gateway.tokens.worker, + token, url: `ws://127.0.0.1:${gateway.port}`, }, }, @@ -478,7 +489,7 @@ export async function startFleet( }, { label: "every worker connected to the gateway and read by it" }, ); - return { gateway, workers: started }; + return { gateway, joinTokens, workers: started }; } catch (error: unknown) { await disposeFleet({ gateway, workers: started }); throw error; @@ -486,7 +497,7 @@ export async function startFleet( } export async function disposeFleet( - fleet: Fleet, + fleet: Pick, options: { readonly preservePages?: readonly Page[] } = {}, ): Promise { await Promise.all(fleet.workers.map((worker) => worker.dispose(options))); @@ -506,9 +517,10 @@ export async function joinOldWorker( gateway: RunningDaemon, identity: { readonly id: string; readonly label: string }, ): Promise<() => void> { + const token = await mintJoinToken(gateway); const socket = new WebSocket(`ws://127.0.0.1:${gateway.port}/v1/uplink`, { headers: { - authorization: `Bearer ${gateway.tokens.worker}`, + authorization: `Bearer ${token}`, "x-simlock-worker-id": identity.id, "x-simlock-worker-label": encodeURIComponent(identity.label), }, diff --git a/e2e/console/usage.spec.ts b/e2e/console/usage.spec.ts index e674e6fbc..09f39e6fc 100644 --- a/e2e/console/usage.spec.ts +++ b/e2e/console/usage.spec.ts @@ -1,7 +1,15 @@ import type { Page } from "@playwright/test"; import { waitFor } from "../helpers/wait.js"; -import { expect, type RunningDaemon, settled, signIn, startDaemon, test } from "./fixtures.js"; +import { + expect, + mintJoinToken, + type RunningDaemon, + settled, + signIn, + startDaemon, + test, +} from "./fixtures.js"; import { returnToTab } from "./tab.js"; const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; @@ -240,7 +248,7 @@ test.describe("the Usage page", () => { ...ONE_DEVICE, gateway: { label, - token: gateway.tokens.worker, + token: await mintJoinToken(gateway), url: `ws://127.0.0.1:${String(gateway.port)}`, }, }, diff --git a/e2e/gateway-component-install.test.ts b/e2e/gateway-component-install.test.ts index aad32f20e..795deb1c0 100644 --- a/e2e/gateway-component-install.test.ts +++ b/e2e/gateway-component-install.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from "vitest"; -import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; +import { + mintJoinToken, + type TestEnv, + waitFor, + withDaemon, + withHttpDaemon, +} from "./helpers/index.js"; interface WorkerView { readonly id: string; @@ -49,10 +55,7 @@ describe("simlock component install through a gateway", () => { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - expect(minted.code, minted.stderr).toBe(0); - const { secret } = minted.json as { secret: string }; - const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; + const url = `ws://127.0.0.1:${port}`; const androidScript = { android: { availableOsVersions: ["34"], @@ -63,11 +66,14 @@ describe("simlock component install through a gateway", () => { }, }; await withDaemon({ - configOverrides: { gateway: { ...uplink, label: "open" } }, + configOverrides: { gateway: { label: "open", token: await mintJoinToken(gateway), url } }, driverScript: androidScript, }); await withDaemon({ - configOverrides: { downloads: { policy: "never" }, gateway: { ...uplink, label: "locked" } }, + configOverrides: { + downloads: { policy: "never" }, + gateway: { label: "locked", token: await mintJoinToken(gateway), url }, + }, driverScript: androidScript, }); let workers: readonly WorkerView[] = []; diff --git a/e2e/gateway-event-relay.test.ts b/e2e/gateway-event-relay.test.ts index 138f3c1be..24acf102d 100644 --- a/e2e/gateway-event-relay.test.ts +++ b/e2e/gateway-event-relay.test.ts @@ -7,7 +7,7 @@ import { describe, expect, it } from "vitest"; import { NodeIpcTransport } from "../src/ports/index.js"; import { SimlockWire } from "../src/simlock-client/wire.js"; -import { waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; +import { mintJoinToken, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; import type { RecordedEvent } from "./helpers/events.js"; /** @@ -198,7 +198,7 @@ describe("gateway event relay", () => { }); it("a gateway pages its events by worker through GET /v1/events, and a worker answers its own id only", async () => { - const { first, gateway, port, read, second, secret } = await gatewayWithTwoWorkers(); + const { first, gateway, port, read, second } = await gatewayWithTwoWorkers(); const holders = [ first.env.cliBackground(leaseArgs("by-worker-one-a")), first.env.cliBackground(leaseArgs("by-worker-one-b")), @@ -265,7 +265,6 @@ describe("gateway event relay", () => { } finally { await wire.close(); } - expect(secret).toBeDefined(); for (const holder of holders) { holder.kill("SIGTERM"); await holder.waitForExit(15_000); @@ -331,11 +330,10 @@ async function gatewayWithTwoWorkers() { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - const { secret } = minted.json as { secret: string }; const join = async (label: string): Promise => { + const token = await mintJoinToken(gateway); const env = await withDaemon({ - configOverrides: { gateway: { label, token: secret, url: `ws://127.0.0.1:${port}` } }, + configOverrides: { gateway: { label, token, url: `ws://127.0.0.1:${port}` } }, driverScript: { ios: { knownModels: ["iPhone 17"], availableOsVersions: ["18.4"] } }, }); let id: string | undefined; @@ -361,7 +359,7 @@ async function gatewayWithTwoWorkers() { expect(response.status, query).toBe(200); return ((await response.json()) as { events: RecordedEvent[] }).events; }; - return { first, gateway, operator, port, read, second, secret }; + return { first, gateway, operator, port, read, second }; } const idsOf = (events: readonly RecordedEvent[]) => events.map((event) => event.id); diff --git a/e2e/gateway-fast-fail.test.ts b/e2e/gateway-fast-fail.test.ts index 814fa5df3..789150814 100644 --- a/e2e/gateway-fast-fail.test.ts +++ b/e2e/gateway-fast-fail.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; +import { mintJoinToken, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; import type { CliResult, TestEnv } from "./helpers/index.js"; import type { FakeDriverScript } from "./fake-driver/types.js"; @@ -32,17 +32,20 @@ async function startGateway() { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - expect(minted.code, minted.stderr).toBe(0); - const { secret } = minted.json as { secret: string }; - const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; return { baseUrl: `http://127.0.0.1:${port}`, gateway, - join: (label: string, script: FakeDriverScript, extraConfig: Record = {}) => + join: async ( + label: string, + script: FakeDriverScript, + extraConfig: Record = {}, + ) => // Seeded before the daemon starts: a worker reports its catalog as its uplink opens. withDaemon({ - configOverrides: { gateway: { ...uplink, label }, ...extraConfig }, + configOverrides: { + gateway: { label, token: await mintJoinToken(gateway), url: `ws://127.0.0.1:${port}` }, + ...extraConfig, + }, driverScript: script, fakeDriverPlatforms: ["ios"], }), diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index 76509ba93..4d58c4bc4 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from "vitest"; -import { waitFor, waitForDeviceState, withDaemon, withHttpDaemon } from "./helpers/index.js"; +import { + mintJoinToken, + waitFor, + waitForDeviceState, + withDaemon, + withHttpDaemon, +} from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; /** @@ -147,17 +153,17 @@ describe("gateway fleet", () => { const { secret, token } = minted.json as { secret: string; token: { role: string } }; expect(token.role).toBe("worker"); - // 2. Two workers, each with its own SIMLOCK_HOME (and therefore its own instance identity), - // join with the same token and the gateway's base URL. - const fleetConfig = { gateway: { token: secret, url: `ws://127.0.0.1:${port}` } }; + // why: two workers, each with its own SIMLOCK_HOME (so its own instance identity) and its + // own join token, because a gateway pins a token to the first worker that joins with it. + const url = `ws://127.0.0.1:${port}`; const workerA = await withDaemon({ - configOverrides: { gateway: { ...fleetConfig.gateway, label: "worker-a" } }, + configOverrides: { gateway: { label: "worker-a", token: secret, url } }, // Seeded before the daemon starts: the worker reports its catalog as its uplink opens, and // a script written afterwards would only reach the gateway on its 30s periodic refresh. driverScript: { ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] } }, }); const workerB = await withDaemon({ - configOverrides: { gateway: { ...fleetConfig.gateway, label: "worker-b" } }, + configOverrides: { gateway: { label: "worker-b", token: await mintJoinToken(gateway), url } }, driverScript: { ios: { knownModels: ["iPhone 17"], availableOsVersions: ["18.4"] } }, }); @@ -285,15 +291,13 @@ describe("gateway fleet", () => { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - const { secret } = minted.json as { secret: string }; - const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; + const url = `ws://127.0.0.1:${port}`; // Both workers have the same model and the same two runtimes installed, and pair the model // with a different one of them. Each also accepts its own other name for it and reports its // own image of one shared runtime. const installed = ["18.4", "26.0"]; await withDaemon({ - configOverrides: { gateway: { ...uplink, label: "worker-a" } }, + configOverrides: { gateway: { label: "worker-a", token: await mintJoinToken(gateway), url } }, driverScript: { ios: { availableOsVersions: installed, @@ -307,7 +311,7 @@ describe("gateway fleet", () => { }, }); await withDaemon({ - configOverrides: { gateway: { ...uplink, label: "worker-b" } }, + configOverrides: { gateway: { label: "worker-b", token: await mintJoinToken(gateway), url } }, driverScript: { ios: { availableOsVersions: installed, @@ -402,12 +406,10 @@ describe("gateway fleet", () => { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - const { secret } = minted.json as { secret: string }; - const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; + const url = `ws://127.0.0.1:${port}`; // Both workers list My Tablet; only worker-a has it as a custom profile. await withDaemon({ - configOverrides: { gateway: { ...uplink, label: "worker-a" } }, + configOverrides: { gateway: { label: "worker-a", token: await mintJoinToken(gateway), url } }, driverScript: { android: { availableOsVersions: ["35"], @@ -417,7 +419,7 @@ describe("gateway fleet", () => { }, }); await withDaemon({ - configOverrides: { gateway: { ...uplink, label: "worker-b" } }, + configOverrides: { gateway: { label: "worker-b", token: await mintJoinToken(gateway), url } }, driverScript: { android: { availableOsVersions: ["35"], knownModels: ["Pixel 8", "My Tablet"] }, }, @@ -457,14 +459,12 @@ describe("gateway fleet", () => { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - const { secret } = minted.json as { secret: string }; - const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; + const url = `ws://127.0.0.1:${port}`; // One model per worker, so the model alone decides where a request lands. Both workers can // slim the one runtime they have. await withDaemon({ configOverrides: { - gateway: { ...uplink, label: "default-full" }, + gateway: { label: "default-full", token: await mintJoinToken(gateway), url }, ios: { defaultMode: "full" }, }, driverScript: { @@ -477,7 +477,7 @@ describe("gateway fleet", () => { }); await withDaemon({ configOverrides: { - gateway: { ...uplink, label: "default-slim" }, + gateway: { label: "default-slim", token: await mintJoinToken(gateway), url }, ios: { defaultMode: "slim" }, }, driverScript: { @@ -582,8 +582,6 @@ describe("gateway fleet", () => { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - const { secret } = minted.json as { secret: string }; const pixels = { android: { availableOsVersions: ["34"], @@ -592,9 +590,11 @@ describe("gateway fleet", () => { modelClasses: { "Pixel 8": "phone" }, }, } as const; - const join = (label: string) => + const join = async (label: string) => withDaemon({ - configOverrides: { gateway: { label, token: secret, url: `ws://127.0.0.1:${port}` } }, + configOverrides: { + gateway: { label, token: await mintJoinToken(gateway), url: `ws://127.0.0.1:${port}` }, + }, driverScript: pixels, fakeDriverPlatforms: ["android"], }); @@ -659,12 +659,10 @@ describe("gateway fleet", () => { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - const { secret } = minted.json as { secret: string }; - const join = (label: string, osVersion: string) => + const join = async (label: string, osVersion: string) => withDaemon({ configOverrides: { - gateway: { label, token: secret, url: `ws://127.0.0.1:${port}` }, + gateway: { label, token: await mintJoinToken(gateway), url: `ws://127.0.0.1:${port}` }, }, driverScript: { ios: { @@ -735,6 +733,49 @@ describe("gateway fleet", () => { expect(await listWorkers(gateway)).toEqual([]); }); + it("pins a join token to the first worker that joins with it, refuses a second worker with it as worker-mismatch, and lists the token with the first worker's id", async () => { + const { env: gateway, port } = await withHttpDaemon((port) => ({ + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", + driver: "none", + })); + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + const { secret, token } = minted.json as { secret: string; token: { id: string } }; + const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; + await withDaemon({ configOverrides: { gateway: { ...uplink, label: "first" } } }); + const [first] = await waitForWorkers( + gateway, + (workers) => workers.length === 1 && workers[0]?.connection === "connected", + "the first worker joined", + ); + + await withDaemon({ configOverrides: { gateway: { ...uplink, label: "second" } } }); + + let rejected: { reason?: string; workerId?: string; label?: string } | undefined; + await waitFor( + async () => { + rejected = (await gateway.events()).find((event) => event.event === "worker.rejected") + ?.payload as typeof rejected; + return rejected !== undefined; + }, + { label: "the gateway reported the second worker's refused uplink", timeout: 20_000 }, + ); + expect(rejected).toMatchObject({ + label: "second", + reason: "worker-mismatch", + workerId: expect.any(String), + }); + expect(rejected?.workerId).not.toBe(first?.id); + const listed = await gateway.cli(["token", "list"]); + expect(listed.code, listed.stderr).toBe(0); + expect((listed.json as { tokens: unknown[] }).tokens).toEqual([ + expect.objectContaining({ id: token.id, workerId: first?.id }), + ]); + expect((await listWorkers(gateway)).map((worker) => [worker.label, worker.connection])).toEqual( + [["first", "connected"]], + ); + }); + it("through a gateway, a caller-chosen lease ID comes back with no worker prefix, renews and releases by that ID, and a second request for it is LEASE_ID_TAKEN", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port } }, diff --git a/e2e/gateway-physical-routing.test.ts b/e2e/gateway-physical-routing.test.ts index de3aa288d..0b3c0e0f3 100644 --- a/e2e/gateway-physical-routing.test.ts +++ b/e2e/gateway-physical-routing.test.ts @@ -4,6 +4,7 @@ import type { CliBackgroundHandle } from "./helpers/cli.js"; import type { FakeDriverPlatformScript, ScriptedPhysicalDevice } from "./fake-driver/types.js"; import { type CliResult, + mintJoinToken, type TestEnv, waitFor, waitForDeviceState, @@ -76,16 +77,17 @@ async function startFleet(specs: readonly WorkerSpec[]): Promise { role: "gateway", driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - expect(minted.code, minted.stderr).toBe(0); - const { secret } = minted.json as { secret: string }; const workers: Record = {}; let enrolled = 0; for (const spec of specs) { const worker = await withDaemon({ configOverrides: { - gateway: { label: spec.label, token: secret, url: `ws://127.0.0.1:${String(port)}` }, + gateway: { + label: spec.label, + token: await mintJoinToken(gateway), + url: `ws://127.0.0.1:${String(port)}`, + }, ...spec.config, }, driverScript: { diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index 4efa8d5f7..7a3aae25f 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from "vitest"; -import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; +import { + mintJoinToken, + type TestEnv, + waitFor, + withDaemon, + withHttpDaemon, +} from "./helpers/index.js"; /** * ADR 0005's happy path, over real transports: a real gateway process, real worker processes @@ -68,16 +74,16 @@ async function startFleet(specs: readonly WorkerSpec[], agentId: string): Promis driver: "none", })); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - expect(minted.code).toBe(0); - const { secret } = minted.json as { secret: string }; - const workers: TestEnv[] = []; for (const spec of specs) { const worker = await withDaemon({ agentId, configOverrides: { - gateway: { label: spec.label, token: secret, url: `ws://127.0.0.1:${port}` }, + gateway: { + label: spec.label, + token: await mintJoinToken(gateway), + url: `ws://127.0.0.1:${port}`, + }, ...(spec.limits === undefined ? {} : { limits: spec.limits }), }, // Before the daemon starts, not after: the worker reports its catalog as its uplink diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index 39f2b6391..2e8c73228 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -15,6 +15,7 @@ export type { Agent, AgentDeviceResult } from "./agent-device.js"; export { freeLoopbackPort } from "./port.js"; export { deviceStreamUrl } from "./device-stream.js"; export { withHttpDaemon } from "./http-daemon.js"; +export { mintJoinToken } from "./join-token.js"; // A flow that factors its own setup out of a test body needs to name what `withDaemon` hands // back; every other flow keeps it inferred. export type { SharedTestEnv, TestEnv } from "./env.js"; diff --git a/e2e/helpers/join-token.ts b/e2e/helpers/join-token.ts new file mode 100644 index 000000000..14b653c0a --- /dev/null +++ b/e2e/helpers/join-token.ts @@ -0,0 +1,10 @@ +import { expect } from "vitest"; + +import type { TestEnv } from "./env.js"; + +/** why: a gateway pins a join token to the first worker that joins with it, so each worker in a test needs its own. */ +export async function mintJoinToken(gateway: Pick): Promise { + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + expect(minted.code, minted.stderr).toBe(0); + return (minted.json as { secret: string }).secret; +} diff --git a/e2e/usage-stats.test.ts b/e2e/usage-stats.test.ts index c5f781f71..71d096fdd 100644 --- a/e2e/usage-stats.test.ts +++ b/e2e/usage-stats.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon } from "./helpers/index.js"; +import { freeLoopbackPort, mintJoinToken, waitFor, withDaemon } from "./helpers/index.js"; import type { RecordedEvent } from "./helpers/events.js"; const LEASE_ARGS = ["lease", "--platform", "ios", "--device", "iPhone 16", "--os", "18.4"] as const; @@ -128,14 +128,12 @@ describe("simlock stats", () => { role: "gateway", driver: "none", }); - const minted = await gateway.cli(["token", "create", "--role", "worker"]); - const { secret } = minted.json as { secret: string }; const oneAtATime = { limits: { maxRunning: 1, ios: { maxDevices: 1, maxRunning: 1 } } }; - const joinWith = (label: string) => + const joinWith = async (label: string) => withDaemon({ configOverrides: { ...oneAtATime, - gateway: { label, token: secret, url: `ws://127.0.0.1:${port}` }, + gateway: { label, token: await mintJoinToken(gateway), url: `ws://127.0.0.1:${port}` }, }, driverScript: { ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] } }, }); diff --git a/src/auth/AGENTS.md b/src/auth/AGENTS.md index c7358e58f..cf9d56cd5 100644 --- a/src/auth/AGENTS.md +++ b/src/auth/AGENTS.md @@ -9,30 +9,30 @@ Decision: [ADR 0033](../../docs/internal/adr/0033-a-sign-in-proxy-is-a-second-wa ## Files -| File | Role | -| ----------------------------------- | -------------------------------------------------------------------------------------------------------- | -| `index.ts` | `createAuth`, `Auth`, `AuthError`, `AdminAuthenticationFailedError` | -| `identity.ts` | `Identity`: principal, name, role, via, expiry, ambient, sign-out URL | -| `strategy.ts` | `AuthStrategyDefinition`, `AuthStrategy`, `StrategyAnswer`, `AuthConfig` | -| `strategies/index.ts` | The registry: ordered definitions (`token`, then `proxy`) | -| `strategies/token/index.ts` | The Simlock token strategy: `Authorization: Bearer slk_…` | -| `strategies/proxy-jwt/index.ts` | The proxy strategy: a sign-in proxy's JWT in `http.proxyAuth.header`; owns the `proxyAuth` config schema | -| `strategies/proxy-jwt/key-cache.ts` | `KeyCache`: the proxy's published keys, on the `Clock` | -| `strategies/conformance.test.ts` | Every registered strategy: `not-mine` without its credential, `via` = name | -| `token-store.ts` | `TokenStore`: hashed tokens in the `tokens` table of `state.db`; one read per verify; `tokensOwner` | -| `admin-secret.ts` | `AdminSecretManager`: per-start secret, `admin.token` | -| `hello.ts` | `SessionRoleResolver`, `resolveAgentRole`, `AdminAuthenticationFailedError` | -| `tokens.ts` | `TokenRole`, `TokenRecord`, `TokenOperations` | +| File | Role | +| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `index.ts` | `createAuth`, `Auth`, `AuthError`, `AdminAuthenticationFailedError` | +| `identity.ts` | `Identity`: principal, name, role, via, expiry, ambient, sign-out URL | +| `strategy.ts` | `AuthStrategyDefinition`, `AuthStrategy`, `StrategyAnswer`, `AuthConfig` | +| `strategies/index.ts` | The registry: ordered definitions (`token`, then `proxy`) | +| `strategies/token/index.ts` | The Simlock token strategy: `Authorization: Bearer slk_…` | +| `strategies/proxy-jwt/index.ts` | The proxy strategy: a sign-in proxy's JWT in `http.proxyAuth.header`; owns the `proxyAuth` config schema | +| `strategies/proxy-jwt/key-cache.ts` | `KeyCache`: the proxy's published keys, on the `Clock` | +| `strategies/conformance.test.ts` | Every registered strategy: `not-mine` without its credential, `via` = name | +| `token-store.ts` | `TokenStore`: hashed tokens in the `tokens` table of `state.db`; one read per verify; `pinWorker`; `tokensOwner` | +| `admin-secret.ts` | `AdminSecretManager`: per-start secret, `admin.token` | +| `hello.ts` | `SessionRoleResolver`, `resolveAgentRole`, `AdminAuthenticationFailedError` | +| `tokens.ts` | `TokenRole`, `TokenRecord`, `TokenOperations` | ## Auth -| Member | Does | -| --------------------- | -------------------------------------------------------------------------------------------------------- | -| `authenticateRequest` | Asks the enabled strategies in registry order; returns `Identity` or throws `AuthError` | -| `resolveHelloRole` | No credential → `agent`; operator token or admin secret → `admin`; else `AdminAuthenticationFailedError` | -| `authenticateUplink` | None or unknown → `unauthenticated`; not a `worker` token → `forbidden`; else accept with the token id | -| `tokens` | `create`, `list`, `revoke` (both dispatchers); `verify` (the module host, for a local profile) | -| `adminSecret` | `persist`, `remove` (`DaemonServer`) | +| Member | Does | +| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `authenticateRequest` | Asks the enabled strategies in registry order; returns `Identity` or throws `AuthError` | +| `resolveHelloRole` | No credential → `agent`; operator token or admin secret → `admin`; else `AdminAuthenticationFailedError` | +| `authenticateUplink` | None or unknown → `unauthenticated`; not a `worker` token → `forbidden`; claimed worker id empty, or not the one the token is pinned to (an unpinned token pins it now, unless another token holds it) → `worker-mismatch`; else accept with the token id | +| `tokens` | `create`, `list`, `revoke` (both dispatchers); `verify` (the module host, for a local profile) | +| `adminSecret` | `persist`, `remove` (`DaemonServer`) | ## Strategies @@ -66,5 +66,6 @@ the `KeySetFetcher` port, which never follows a redirect and caps the body at 64 ## Facts - A worker join token is `forbidden` on HTTP and accepted only by `authenticateUplink`. +- A join token is pinned to the first worker id it is accepted with (`tokens.worker_id`, unique): `pinWorker` is one transaction (`UPDATE OR IGNORE ... WHERE worker_id IS NULL`, then a re-read), so of two first joins at once one wins. Re-pairing is `token revoke` + `token create`; `token.list` shows `workerId`. - Every verify reads the `tokens` table, so a `token revoke` takes effect at once. `create` and `revoke` are each one transaction, so two at once never lose one another. `createAuth` takes the daemon's `SqliteDatabase`, never the state module. - The admin secret's hash lives in memory from construction; the plaintext is written to `admin.token` (0600, atomic) only by `persist`, after the socket claim. diff --git a/src/auth/auth.test.ts b/src/auth/auth.test.ts index 850ac669a..4bf05aa89 100644 --- a/src/auth/auth.test.ts +++ b/src/auth/auth.test.ts @@ -302,13 +302,54 @@ describe("authenticateUplink", () => { it("answers unauthenticated for none and unknown, forbidden for a token that is not a worker's, accept with the token id for a worker token", async () => { const auth = createAuth(await options()); - await expect(auth.authenticateUplink(undefined)).resolves.toBe("unauthenticated"); - await expect(auth.authenticateUplink("slk_unknown")).resolves.toBe("unauthenticated"); - await expect(auth.authenticateUplink("slk_operator")).resolves.toBe("forbidden"); - await expect(auth.authenticateUplink("slk_agent")).resolves.toBe("forbidden"); - await expect(auth.authenticateUplink("slk_worker")).resolves.toEqual({ + await expect(auth.authenticateUplink(undefined, "wrk_a")).resolves.toBe("unauthenticated"); + await expect(auth.authenticateUplink("slk_unknown", "wrk_a")).resolves.toBe("unauthenticated"); + await expect(auth.authenticateUplink("slk_operator", "wrk_a")).resolves.toBe("forbidden"); + await expect(auth.authenticateUplink("slk_agent", "wrk_a")).resolves.toBe("forbidden"); + await expect(auth.authenticateUplink("slk_worker", "wrk_a")).resolves.toEqual({ outcome: "accept", tokenId: "tok_worker", }); }); + + it("pins a worker token to the first worker id that joins with it: that id is accepted again, another or an empty one is worker-mismatch", async () => { + const auth = createAuth(await options()); + const accepted = { outcome: "accept", tokenId: "tok_worker" }; + + await expect(auth.authenticateUplink("slk_worker", "")).resolves.toBe("worker-mismatch"); + await expect(auth.authenticateUplink("slk_worker", undefined)).resolves.toBe("worker-mismatch"); + await expect(auth.authenticateUplink("slk_worker", "wrk_a")).resolves.toEqual(accepted); + await expect(auth.authenticateUplink("slk_worker", "wrk_a")).resolves.toEqual(accepted); + await expect(auth.authenticateUplink("slk_worker", "wrk_b")).resolves.toBe("worker-mismatch"); + expect((await auth.tokens.list()).find((token) => token.id === "tok_worker")?.workerId).toBe( + "wrk_a", + ); + }); + + it("accepts exactly one of two first joins with one worker token at once, and refuses the other as worker-mismatch", async () => { + const auth = createAuth(await options()); + + const answers = await Promise.all([ + auth.authenticateUplink("slk_worker", "wrk_a"), + auth.authenticateUplink("slk_worker", "wrk_b"), + ]); + + expect(answers).toEqual([{ outcome: "accept", tokenId: "tok_worker" }, "worker-mismatch"]); + }); + + it("refuses a worker id another worker token is pinned to as worker-mismatch, until that token is revoked", async () => { + const auth = createAuth(await options()); + const { record, secret } = await auth.tokens.create("worker", "replacement"); + await expect(auth.authenticateUplink("slk_worker", "wrk_a")).resolves.toMatchObject({ + outcome: "accept", + }); + + await expect(auth.authenticateUplink(secret, "wrk_a")).resolves.toBe("worker-mismatch"); + await auth.tokens.revoke("tok_worker"); + + await expect(auth.authenticateUplink(secret, "wrk_a")).resolves.toEqual({ + outcome: "accept", + tokenId: record.id, + }); + }); }); diff --git a/src/auth/index.ts b/src/auth/index.ts index 3b5cc2830..6077665fb 100644 --- a/src/auth/index.ts +++ b/src/auth/index.ts @@ -41,6 +41,7 @@ export interface AuthOptions { export type UplinkAnswer = | "unauthenticated" | "forbidden" + | "worker-mismatch" | { readonly outcome: "accept"; readonly tokenId: string }; export interface Auth { @@ -49,7 +50,10 @@ export interface Auth { readonly principal?: string; readonly credential?: string; }): Promise; - authenticateUplink(credential: string | undefined): Promise; + authenticateUplink( + credential: string | undefined, + claimedWorkerId: string | undefined, + ): Promise; readonly tokens: TokenOperations; readonly adminSecret: { persist(): Promise; remove(): Promise }; } @@ -99,12 +103,17 @@ export function createAuthFrom( if (adminSecret.verify(hello.credential)) return "admin"; throw new AdminAuthenticationFailedError(); }, - authenticateUplink: async (credential) => { + authenticateUplink: async (credential, claimedWorkerId) => { if (credential === undefined) return "unauthenticated"; const record = await store.verify(credential); if (record === undefined) return "unauthenticated"; if (record.role !== "worker") return "forbidden"; - return { outcome: "accept", tokenId: record.id }; + if (claimedWorkerId === undefined || claimedWorkerId === "") return "worker-mismatch"; + const pinned = + record.workerId === undefined + ? await store.pinWorker(record.id, claimedWorkerId) + : record.workerId === claimedWorkerId; + return pinned ? { outcome: "accept", tokenId: record.id } : "worker-mismatch"; }, tokens: { create: (role, label) => store.create(role, label), diff --git a/src/auth/token-store.test.ts b/src/auth/token-store.test.ts index 67b4d6494..ac6e964a5 100644 --- a/src/auth/token-store.test.ts +++ b/src/auth/token-store.test.ts @@ -1,8 +1,13 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import { describe, expect, it, vi } from "vitest"; -import { FakeClock } from "../ports/index.js"; +import { FakeClock, NodeFilesystem, NodeSqliteOpener, NoopLogger } from "../ports/index.js"; import type { SqliteDatabase } from "../ports/index.js"; import type { TokenSecrets } from "../ports/token-secrets.js"; +import { openStateDatabase } from "../state/index.js"; import { openMemoryStateDatabase } from "./testing.js"; import { TokenStore, tokensOwner } from "./token-store.js"; @@ -67,6 +72,7 @@ describe("TokenStore", () => { role: "agent", label: "ci-runner", created_at: 1_000, + worker_id: null, }, ]); expect(JSON.stringify(rows)).not.toContain("fake-secret"); @@ -223,4 +229,56 @@ describe("TokenStore", () => { await expect(store.verify("slk_anything")).resolves.toBeUndefined(); await expect(store.revoke("tok_anything")).resolves.toBe(false); }); + + it("pins a token to a worker id once, and lists the token with it", async () => { + const { store, database } = await tokenStore(); + const { record } = await store.create("worker", "mac-mini"); + + await expect(store.pinWorker(record.id, "wrk_a")).resolves.toBe(true); + await expect(store.pinWorker(record.id, "wrk_b")).resolves.toBe(false); + + await expect(store.list()).resolves.toEqual([{ ...record, workerId: "wrk_a" }]); + expect(storedRows(database)[0]?.worker_id).toBe("wrk_a"); + }); + + it("moves a version 1 tokens table up, keeping its tokens unpinned until their first pin", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-tokens-v1-")); + const open = (owner: typeof tokensOwner) => + openStateDatabase({ + dataDirectory: directory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [owner], + sqlite: new NodeSqliteOpener(), + upgradeStep: "", + }); + try { + const old = await open({ + ...tokensOwner, + migrations: tokensOwner.migrations.slice(0, 1), + version: 1, + }); + old.database + .prepare("INSERT INTO tokens (id, hash, role, label, created_at) VALUES (?, ?, ?, NULL, 5)") + .run("tok_old", "hash-old", "worker"); + old.close(); + + const state = await open(tokensOwner); + try { + const { store } = await tokenStore({ database: state.database }); + await expect(store.list()).resolves.toEqual([ + { id: "tok_old", hash: "hash-old", role: "worker", createdAt: 5 }, + ]); + await expect(store.pinWorker("tok_old", "wrk_a")).resolves.toBe(true); + await expect(store.list()).resolves.toEqual([ + { id: "tok_old", hash: "hash-old", role: "worker", createdAt: 5, workerId: "wrk_a" }, + ]); + } finally { + state.close(); + } + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); }); diff --git a/src/auth/token-store.ts b/src/auth/token-store.ts index 6733c9a36..48b6a1aa6 100644 --- a/src/auth/token-store.ts +++ b/src/auth/token-store.ts @@ -18,10 +18,16 @@ CREATE TABLE tokens ( ) STRICT; `; +// why: the unique index keeps a worker id pinned to one live token, so a second token cannot take over a paired worker. +const TOKENS_V2 = ` +ALTER TABLE tokens ADD COLUMN worker_id TEXT; +CREATE UNIQUE INDEX tokens_worker_id ON tokens (worker_id); +`; + export const tokensOwner: SqliteSchemaOwner = { - migrations: [TOKENS_V1], + migrations: [TOKENS_V1, TOKENS_V2], name: "tokens", - version: 1, + version: 2, }; export interface TokenStoreOptions { @@ -73,6 +79,17 @@ export class TokenStore { ); } + // why: OR IGNORE leaves the row unpinned when another token holds the id, and the re-read in the same transaction decides, so two first joins at once cannot both win. + async pinWorker(id: string, workerId: string): Promise { + return inTransaction(this.#database, () => { + this.#database + .prepare("UPDATE OR IGNORE tokens SET worker_id = ? WHERE id = ? AND worker_id IS NULL") + .run(workerId, id); + const row = this.#database.prepare("SELECT worker_id FROM tokens WHERE id = ?").get(id); + return row?.worker_id === workerId; + }); + } + async verify(secret: string): Promise { const row = this.#database .prepare("SELECT * FROM tokens WHERE hash = ?") @@ -88,5 +105,6 @@ function toRecord(row: Record): TokenRecord { role: row.role as TokenRole, ...(row.label === null ? {} : { label: row.label as string }), createdAt: Number(row.created_at), + ...(row.worker_id === null ? {} : { workerId: row.worker_id as string }), }; } diff --git a/src/auth/tokens.ts b/src/auth/tokens.ts index ad2de7d6a..ca9b07ffb 100644 --- a/src/auth/tokens.ts +++ b/src/auth/tokens.ts @@ -6,6 +6,7 @@ export interface TokenRecord { readonly role: TokenRole; readonly label?: string; readonly createdAt: number; + readonly workerId?: string; } export interface TokenOperations { diff --git a/src/bus/index.ts b/src/bus/index.ts index 0c4ae8812..ecec9799c 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -8,6 +8,9 @@ export interface CapacityFiguresPayload { readonly warm: number; } +/** why: each reason points an operator at a different fix: the token, its role, or the worker it is pinned to. */ +export type WorkerRejectedReason = "unauthenticated" | "forbidden" | "worker-mismatch"; + export interface EventMap { "lease.requested": { /** The stored request's id, so an observer can correlate this event with its record. */ @@ -330,10 +333,11 @@ export interface EventMap { readonly version?: string; }; /** - * An uplink was turned away at the door, before any session existed (ADR 0005 §4/§22). - * Two reasons, and they are the same two the rest of the API tells apart: + * why: an uplink turned away at the door leaves no other trace (ADR 0005 §4/§22). * `unauthenticated` (`401`) is a missing or unrecognized join token -- a revoked or mistyped - * one lands here -- and `forbidden` (`403`) is a real token whose role is not `worker`. + * one lands here; `forbidden` (`403`) is a real token whose role is not `worker`; and + * `worker-mismatch` (`403`) is a join token pinned to another worker id, or a worker id + * another token is pinned to. * * Version skew is deliberately *not* one of these: a worker whose `hello` finds no * overlapping protocol range authenticated fine, so it enters the registry as @@ -354,7 +358,7 @@ export interface EventMap { * debugging. */ "worker.rejected": { - readonly reason: "forbidden" | "unauthenticated"; + readonly reason: WorkerRejectedReason; readonly workerId?: string; readonly label?: string; readonly count?: number; diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 86783d79b..92509ecf5 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -57,7 +57,7 @@ Three identities: ## Protocol version -- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 62, max: 62 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. +- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 63, max: 63 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. - Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless a compatibility path stays side by side. `.agents/scripts/protocol-bump-check.mjs` checks it on push and in CI; it counts every file here as a shape but tests, `index.ts` and the diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 127d07e0e..54aa285c7 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 62, max: 62 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 63, max: 63 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index c62bfc7b7..54c7a1b5c 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -1222,6 +1222,8 @@ export const tokenRecordSchema = z.object({ role: tokenRoleSchema, label: z.string().optional(), createdAt: z.number(), + // why: the uplink cuts a claimed worker id to 128 characters before the token is pinned to it. + workerId: z.string().max(128).optional(), }); // ---- modes and worker views (ADR 0005) -------------------------------------------------------- diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 7f5fe5a9d..e85a8c8be 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(62); + expect(DAEMON_PROTOCOL_VERSION).toBe(63); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 0b300c071..6d8b9f07b 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -59,7 +59,7 @@ Its stdout lines move the state; a failed line, a non-zero exit or a failed laun 2. **Hello** — first frame must be `hello`, else `HANDSHAKE_REQUIRED` and close. Role: the uplink connection is `admin` by acceptance; otherwise the resolver. Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid. Both are fixed for the connection's life. 3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE` - is `{ min: 62, max: 62 }` (`src/contract/protocol.ts`). No overlap → the + is `{ min: 63, max: 63 }` (`src/contract/protocol.ts`). No overlap → the connection stays open, and every request but `daemon.stop` gets `PROTOCOL_VERSION_UNSUPPORTED`. 4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`. diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 36bcf68ad..61fc3738e 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -924,11 +924,10 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise auth.authenticateUplink(credential), + authenticate: (credential, workerId) => auth.authenticateUplink(credential, workerId), clock, drainStore: new StateDrainStore({ database: state.database, logger: logger.child("gateway") }), eventBus, diff --git a/src/gateway/AGENTS.md b/src/gateway/AGENTS.md index 151c8f9b0..b66f2f5f7 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -46,9 +46,9 @@ Flows: [device selection](../../docs/internal/flows/device-selection.md), [devic **Uplink, gateway side.** 1. `GatewayService.start`: `registry.load()` (drained ids) before the listener opens. -2. Upgrade auth (`../daemon/main.ts`): unknown token `401`, non-`worker` role `403`. Refusals emit - `worker.rejected`, coalesced per reason and claimed id over 1 s. -3. A new uplink under a live worker id closes and replaces the old link. +2. Upgrade auth (`../daemon/main.ts`, `authenticateUplink` with the claimed id, cut to `MAX_CLAIMED_FIELD_LENGTH`): + unknown token `401`, non-`worker` role or `worker-mismatch` `403`. Refusals emit `worker.rejected`, coalesced per reason and claimed id over 1 s. +3. A new uplink under a live worker id (so with the token pinned to it) closes and replaces the old link. 4. `WorkerLink.start`: `hello` as `gw:`, `status.get`. Protocol mismatch → view `incompatible`; role not `admin` → close. Then `worker.connected`, `events.subscribe`, first refresh with catalog. Each of these reads waits at most 10 s (`WORKER_CALL_TIMEOUT_MS`). @@ -141,8 +141,6 @@ Persisted: the `drained_workers` and `tokens` tables of `state.db`, `instance.js release and exec fail meanwhile; past the TTL it expires. Knob: `lease.defaultTtlMs`/`--ttl`. - **Local agents and the gateway share a worker's capacity.** A busy machine answers `NO_CAPACITY`; the request waits elsewhere. `worker drain` leaves it to the owner. -- **A worker's claimed id is never verified against its join token.** Any `worker`-token holder can - claim any id and take over its link, view, drain flag and calls. Ids cut to 128 chars. - **`device.exec` backpressure through a gateway does not slow the worker's own process.** Output is relayed with `void session.onOutput(...)`; a slow fleet client is buffered in the gateway. - **Three gaps in gateway warm hits.** A slim-pool device that failed its slim pass reports `full` and counts for `full`; a default-slim worker's full device on an unslimmable runtime is no hit for a diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 359d3df8c..cfb74ae5c 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -54,6 +54,7 @@ function fleet( options: { readonly authenticate?: ( credential: string | undefined, + workerId: string | undefined, ) => UplinkAuthOutcome | UplinkAuthResult; readonly leaseMaxTtlMs?: number; readonly logger?: Logger; @@ -68,7 +69,8 @@ function fleet( const clients: ScriptedWorkerClient[] = []; const connectState = { hangNext: false }; const service = new GatewayService({ - authenticate: async (credential) => options.authenticate?.(credential) ?? "accept", + authenticate: async (credential, workerId) => + options.authenticate?.(credential, workerId) ?? "accept", clock, connect: async () => { if (connectState.hangNext) { @@ -1683,7 +1685,7 @@ describe("GatewayService", () => { await harness.service.stop(); }); - it.each(["unauthenticated", "forbidden"] as const)( + it.each(["unauthenticated", "forbidden", "worker-mismatch"] as const)( "reports a %s uplink it turned away, without inventing a worker for it", async (reason) => { const harness = fleet({ authenticate: () => reason }); @@ -1705,6 +1707,42 @@ describe("GatewayService", () => { }, ); + it("refuses a second worker id on a token pinned to another worker as worker-mismatch, leaving that worker's link alone, while the pinned worker's own redial replaces its link", async () => { + const pins = new Map(); + const harness = fleet({ + authenticate: (credential, workerId) => { + if (!pins.has(credential)) pins.set(credential, workerId); + return pins.get(credential) === workerId + ? { outcome: "accept" as const, tokenId: "tok_a" } + : "worker-mismatch"; + }, + }); + await harness.service.start(); + const workerEndA = await harness.join("wrk_a", new ScriptedWorkerClient("admin", "1.0.0")); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_a")?.connection).toBe("connected"), + ); + + await expect( + harness.join("wrk_b", new ScriptedWorkerClient(), "intruder"), + ).rejects.toMatchObject({ code: "rejected" }); + + expect(harness.events.filter((event) => event.event === "worker.rejected")).toMatchObject([ + { payload: { label: "intruder", reason: "worker-mismatch", workerId: "wrk_b" } }, + ]); + expect(harness.service.workers.view("wrk_b")).toBeUndefined(); + expect(workerEndA.closed).toBe(false); + expect(harness.service.workers.view("wrk_a")?.connection).toBe("connected"); + + await harness.join("wrk_a", new ScriptedWorkerClient("admin", "2.0.0")); + + await vi.waitFor(() => expect(workerEndA.closed).toBe(true)); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_a")?.version).toBe("2.0.0")); + expect(harness.service.workers.view("wrk_a")?.connection).toBe("connected"); + + await harness.service.stop(); + }); + it("coalesces a flood of identical refusals into one event per window, with a count only above one (P-2)", async () => { const harness = fleet({ authenticate: () => "unauthenticated" }); await harness.service.start(); diff --git a/src/gateway/service.ts b/src/gateway/service.ts index ce4f6925e..b32ce803c 100644 --- a/src/gateway/service.ts +++ b/src/gateway/service.ts @@ -6,7 +6,7 @@ * Everything here is lifecycle. What an operation *answers* lives in `GatewayDispatcher`, and * what a view *is* lives in `WorkerRegistry`; this class only makes sure both are fed. */ -import type { EventBus } from "../bus/index.js"; +import type { EventBus, WorkerRejectedReason } from "../bus/index.js"; import type { AcceptedUplink, Clock, @@ -61,13 +61,15 @@ export interface GatewayServiceOptions { readonly eventBus: EventBus; readonly uplinks: UplinkListenerFactory; /** - * Verifies a join token presented at upgrade (ADR 0005 §4/§25): `accept` only for a token the - * gateway's own store holds with role `worker`; `forbidden` for a real token of another role; - * `unauthenticated` for anything else. Injected rather than taking a token store, so this - * module never learns what a token *is* -- except its id, which an `accept` may optionally - * carry (`UplinkAuthResult`) so `closeLinksForToken` (C-2) can later find the link it opened. + * why: injected rather than taking a token store, so this module never learns what a token + * *is* -- except its id, which an `accept` may carry (`UplinkAuthResult`) so + * `closeLinksForToken` (C-2) can later find the link it opened. Gets the claimed worker id, + * because a join token is pinned to one worker (`worker-mismatch` otherwise). */ - readonly authenticate: (credential: string | undefined) => Promise; + readonly authenticate: ( + credential: string | undefined, + workerId: string | undefined, + ) => Promise; /** `gateway.disconnectedRetentionMs` (§6). */ readonly retentionMs: number; /** This gateway's own `lease.maxTtlMs` (§15) -- threaded straight into the registry, which @@ -148,15 +150,13 @@ export class GatewayService { this.#listener = await this.options.uplinks.listen({ accept: (uplink) => this.#accept(uplink), authenticate: async (credential, claimed) => { - const result = await this.options.authenticate(credential); + const result = await this.options.authenticate(credential, claimed.workerId); const outcome = uplinkOutcome(result); - // ADR 0005 §22's fleet audit trail includes the joins that failed: a revoked token - // retrying at its backoff cap is invisible on the gateway otherwise, and "why is that - // machine not in the fleet" is exactly the question an operator brings to - // `simlock events`. Which of the two refusals it was travels with the fact -- the - // event carries the same 401/403 distinction the upgrade answered with. `workerId` and - // `label` are only what the dial *claimed* in its headers, never verified -- a refused - // uplink proves no identity, but the claim is still worth an operator's while. + // why: ADR 0005 §22's fleet audit trail includes the joins that failed: a revoked token + // retrying at its backoff cap is invisible on the gateway otherwise. Which refusal it + // was travels with the fact. `workerId` and `label` are only what the dial *claimed* in + // its headers -- a refused uplink proves no identity, but the claim is still worth an + // operator's while. // P-2: coalesced rather than emitted one-per-dial -- see `#recordRejection`. if (outcome !== "accept") this.#recordRejection(outcome, claimed.workerId, claimed.label); return result; @@ -175,7 +175,7 @@ export class GatewayService { * was -- just not once per attempt. */ #recordRejection( - reason: "forbidden" | "unauthenticated", + reason: WorkerRejectedReason, workerId: string | undefined, label: string | undefined, ): void { diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index 657fef32e..7242530cd 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -11,7 +11,7 @@ */ import type { z } from "zod"; -import type { EventBus } from "../bus/index.js"; +import type { EventBus, WorkerRejectedReason } from "../bus/index.js"; import { type grantedDeviceSchema, type ProtocolRange, @@ -309,11 +309,9 @@ export class WorkerRegistry { } /** - * An uplink the gateway turned away at the upgrade (ADR 0005 §4/§22). The reason is the - * outcome the token check produced, kept apart here for the same reason it is kept apart on - * the wire: `unauthenticated` (`401`) is "no token, or one I do not know" and points at the - * join token, while `forbidden` (`403`) is "a real credential without this authority" and - * points at its role -- two different things for an operator to go and fix. + * why: the reason is the outcome the token check produced, kept apart so an operator knows + * what to fix: `unauthenticated` (`401`) points at the join token, `forbidden` (`403`) at its + * role, `worker-mismatch` (`403`) at the worker the token is pinned to (ADR 0005 §4/§22). * * There is no view to build: the peer never became a worker, so this is a fact and nothing * else, and `workerId` is only ever what the connection claimed in its header. @@ -328,7 +326,7 @@ export class WorkerRegistry { * in the overwhelmingly common case of an isolated refusal. */ rejected( - reason: "forbidden" | "unauthenticated", + reason: WorkerRejectedReason, workerId: string | undefined, label: string | undefined, count?: number, diff --git a/src/ports/uplink-websocket.test.ts b/src/ports/uplink-websocket.test.ts index a899ded35..a3e76fc3a 100644 --- a/src/ports/uplink-websocket.test.ts +++ b/src/ports/uplink-websocket.test.ts @@ -46,7 +46,9 @@ afterEach(async () => { /** Starts a real gateway-side listener whose `authenticate` always refuses (recording every * `claimed` it was handed) and returns the base URL to dial it at. */ -async function startRefusingGateway(): Promise<{ +async function startRefusingGateway( + outcome: Exclude = "unauthenticated", +): Promise<{ url: string; claims: ClaimedUplinkIdentity[]; }> { @@ -55,7 +57,7 @@ async function startRefusingGateway(): Promise<{ await factory.listen({ authenticate: (_credential, claimed): Promise => { claims.push(claimed); - return Promise.resolve("unauthenticated"); + return Promise.resolve(outcome); }, accept: () => { throw new Error("this gateway never accepts"); @@ -121,6 +123,29 @@ describe("WebSocketUplinkListenerFactory / P3", () => { }); }); +describe("WebSocketUplinkListenerFactory refusals", () => { + it("answers 401 for an unauthenticated join, and 403 for a forbidden one or a worker-mismatch", async () => { + for (const [outcome, status] of [ + ["unauthenticated", 401], + ["forbidden", 403], + ["worker-mismatch", 403], + ] as const) { + const { url } = await startRefusingGateway(outcome); + + await expect( + new WebSocketUplinkConnector().connect({ token: "slk_x", url, workerId: "wrk_1" }), + outcome, + ).rejects.toMatchObject({ + code: "rejected", + message: `The gateway refused the uplink with HTTP ${String(status)}`, + }); + + await new Promise((resolve) => server?.close(() => resolve())); + server = undefined; + } + }); +}); + async function startAcceptingGateway(): Promise<{ url: string; accepted: Promise; diff --git a/src/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts index acaeaa2c5..5ca015571 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -255,11 +255,10 @@ export class WebSocketUplinkListenerFactory implements UplinkListenerFactory { } const outcome = uplinkOutcome(result); if (outcome !== "accept") { - // 403 for a real token of the wrong role, 401 for one the gateway does not know - // (ADR 0005 §25) -- the same distinction the HTTP frontend draws for a `worker` token on - // an ordinary `/v1` route, in the opposite direction. - if (outcome === "forbidden") respondAndDestroy(socket, 403, "Forbidden"); - else respondAndDestroy(socket, 401, "Unauthorized"); + // why: 401 for a token the gateway does not know, 403 for a real token that may not open + // this uplink: the wrong role, or pinned to another worker (ADR 0005 §25). + if (outcome === "unauthenticated") respondAndDestroy(socket, 401, "Unauthorized"); + else respondAndDestroy(socket, 403, "Forbidden"); return; } // C-2: the token record id that authorized this uplink, carried onto `AcceptedUplink` so a diff --git a/src/ports/uplink.ts b/src/ports/uplink.ts index ef936191b..5f683c0f7 100644 --- a/src/ports/uplink.ts +++ b/src/ports/uplink.ts @@ -90,18 +90,18 @@ export interface UplinkListener { } /** - * What the gateway makes of the credential presented at upgrade (ADR 0005 §4/§25). Three - * outcomes, not two, because the difference is the difference between "who are you" and "you - * are not allowed here": + * why: the refusals differ in what an operator must fix (ADR 0005 §4/§25): * - * - `accept` -- a token the gateway holds with role `worker`. + * - `accept` -- a `worker` token pinned to the worker id the dial claimed (or pinned to it now). * - `unauthenticated` (`401`) -- no token, or one the gateway does not know. A revoked join * token lands here, which is what closes an uplink after `simlock token revoke`. * - `forbidden` (`403`) -- a real token of the wrong role. An `agent` or `operator` token is * valid elsewhere and carries no authority here, exactly as a `worker` token carries none on * any other `/v1` route. + * - `worker-mismatch` (`403`) -- a `worker` token pinned to another worker id, a worker id + * another token is pinned to, or no worker id at all. */ -export type UplinkAuthOutcome = "accept" | "unauthenticated" | "forbidden"; +export type UplinkAuthOutcome = "accept" | "unauthenticated" | "forbidden" | "worker-mismatch"; /** * `authenticate`'s actual return type: the bare outcome, or -- only on acceptance -- an object @@ -137,11 +137,9 @@ export interface ClaimedUplinkIdentity { export interface UplinkHandlers { /** - * Verifies the join token presented in the `Authorization: Bearer` header at upgrade time. - * Anything but `accept` answers its HTTP status and destroys the socket without ever - * completing the upgrade -- an unauthorized peer never reaches the daemon protocol at all. - * `claimed` is never itself trusted for anything but attribution on a refusal: a rejected - * dial proves no identity, so this is only what it *said*, not what it is. + * why: checked at upgrade, so anything but `accept` answers its HTTP status and destroys the + * socket before an unauthorized peer reaches the daemon protocol. `claimed.workerId` is checked + * against the worker the join token is pinned to; on a refusal it is only what the dial said. */ authenticate( credential: string | undefined, diff --git a/website/src/content/docs/docs/gateway/access-control.mdx b/website/src/content/docs/docs/gateway/access-control.mdx index bafe5f7a1..f9b684722 100644 --- a/website/src/content/docs/docs/gateway/access-control.mdx +++ b/website/src/content/docs/docs/gateway/access-control.mdx @@ -15,7 +15,7 @@ This page uses the gateway in its examples. Tokens work the same way on a worker | --- | --- | --- | | `agent` | A coding agent that leases devices over HTTP. | Read the catalog and status (only its own leases and waiting requests), list installed runtimes, request, renew and release its own leases, cancel its own waiting requests, and run commands on the devices it leases. | | `operator` | A person, or a script that manages the fleet. | Everything an agent may, for every requester's leases, plus the console, events, usage figures, tokens, worker commands and component installs. | -| `worker` | A worker machine joining a gateway. | Open the worker's connection to the gateway, and nothing else. Any other request with it is refused with `403`. | +| `worker` | A worker machine joining a gateway. | Open one worker's connection to the gateway, and nothing else. The first worker that joins with it is paired with it; another worker with the same token, and any other request with it, is refused with `403`. | A valid token used for something its role may not do gets `403 FORBIDDEN`. An unknown or revoked token gets `401 UNAUTHENTICATED`. @@ -45,7 +45,7 @@ simlock --gateway token create --role agent --label ci-ios-runner-3 The `secret` is printed once. Simlock keeps only a hash of it, so a lost secret cannot be shown again: make a new token and revoke the old one. -List tokens. The list shows ids, roles and labels, never secrets: +List tokens. The list shows ids, roles and labels, never secrets. A worker token that a worker has joined with also shows `workerId`, the id of the worker it is paired with: ```sh simlock --gateway token list @@ -65,7 +65,7 @@ simlock --gateway token revoke tok_5e2b8d1c-4a7f-4c9e-b3d6-0f1a2c8e7b45 {"revoked":true} ``` -A revoked token stops working at once, on its next request. Revoking a worker token also closes that worker's connection. Leases made with a revoked agent token stay until their time to live runs out or an operator releases them: the agent can no longer renew or release them. An id that names no token answers `"revoked":false`. +A revoked token stops working at once, on its next request. Revoking a worker token also closes that worker's connection, and frees the worker to join with a new token. Leases made with a revoked agent token stay until their time to live runs out or an operator releases them: the agent can no longer renew or release them. An id that names no token answers `"revoked":false`. ## Admin commands on the CLI diff --git a/website/src/content/docs/docs/gateway/alerts.mdx b/website/src/content/docs/docs/gateway/alerts.mdx index cc0b99e42..3fd2a4862 100644 --- a/website/src/content/docs/docs/gateway/alerts.mdx +++ b/website/src/content/docs/docs/gateway/alerts.mdx @@ -15,7 +15,7 @@ Alerts are sent only by a gateway. A worker on its own sends none; to watch a si | --- | --- | | `worker.connected` | A worker connected to the gateway. | | `worker.disconnected` | A worker's connection closed. The message says how many leases it held. | -| `worker.rejected` | The gateway refused a worker's connection: its token is unknown, revoked, or not a worker token. Refusals within one second for the same reason and worker are sent as one. | +| `worker.rejected` | The gateway refused a worker's connection: its token is unknown, revoked, not a worker token, or already used by another worker. Refusals within one second for the same reason and worker are sent as one. | | `worker.drain-started` | A worker was drained: it takes no new leases from the gateway. | | `worker.drain-ended` | A drained worker takes new leases again. | | `device.quarantine-abandoned` | A worker gave up cleaning a device after repeated failures and retired it. | diff --git a/website/src/content/docs/docs/gateway/joining-workers.mdx b/website/src/content/docs/docs/gateway/joining-workers.mdx index 5873f54aa..9530d4d57 100644 --- a/website/src/content/docs/docs/gateway/joining-workers.mdx +++ b/website/src/content/docs/docs/gateway/joining-workers.mdx @@ -31,7 +31,7 @@ A joined worker gives its gateway the same rights as an operator on that worker. {"secret":"slk_7mQ2xVb9Lr4pK0sZt8YcN1dHf6WjE3uAoG5iRk2Pq-s","token":{"id":"tok_9c1d4e7a-2b6f-4f3a-8d0e-5a7b3c9e1f24","role":"worker","label":"mac-mini-2","createdAt":1792569600000}} ``` - Copy the `secret`. It is printed once. Make one token per worker, so that you can revoke one machine without touching the others. + Copy the `secret`. It is printed once. Make one token per worker: the first worker that joins with a token is paired with it, and the gateway refuses any other worker that tries the same token. See [Pair a token with its worker](#pair-a-token-with-its-worker). 2. On the worker, set the gateway's address, the token and a display name, all in one command: @@ -83,11 +83,34 @@ simlock daemon logs | --- | --- | --- | | `Uplink to gateway established` | The worker joined. | Nothing. | | `Uplink to gateway failed; retrying` with reason `rejected` and `The gateway refused the uplink with HTTP 401` | The gateway does not know the token: it is mistyped, revoked, or made on another daemon. | Make a new join token on the gateway and set it on the worker. | -| The same, with `HTTP 403` | The token is real but is not a worker token. | Make one with `--role worker`. | +| The same, with `HTTP 403` | The token is real but is not a worker token, or it is paired with another worker. | Make a new join token for this worker with `--role worker`. On the gateway, `simlock events` shows `worker.rejected` with the reason: `forbidden` or `worker-mismatch`. | | `Uplink to gateway failed; retrying` with any other reason | The worker cannot reach the gateway. | Check the address, DNS, and that the reverse proxy passes WebSocket upgrades. | A worker shown as `incompatible` is connected, but it and the gateway run Simlock versions that cannot talk to each other. The gateway sends it no requests. Update the older one. +## Pair a token with its worker + +The first time a worker joins with a join token, the gateway pairs the token with that worker's id. From then on: + +- The worker can reconnect and restart with the token as often as it needs. +- Another machine that tries the same token is refused with `HTTP 403`, and the gateway records `worker.rejected` with reason `worker-mismatch`. The paired worker stays connected. +- The worker cannot join with a second token while the first one is still valid. + +`simlock --gateway token list` shows the pairing: a join token that has been used has a `workerId`, the same id `worker list` shows. + +```json +{"tokens":[{"id":"tok_9c1d4e7a-2b6f-4f3a-8d0e-5a7b3c9e1f24","role":"worker","label":"mac-mini-2","createdAt":1792569600000,"workerId":"4b1e9c2a-6d3f-4a8e-9b2c-7f1d0e5a3c68"}]} +``` + +A worker's id lives in its Simlock folder. If you move the token to another machine, or the worker gets a new id (a new Simlock folder, or a reinstalled machine), pair it again: revoke the old token, make a new one, and set it on the worker. + +```sh +simlock --gateway token revoke tok_9c1d4e7a-2b6f-4f3a-8d0e-5a7b3c9e1f24 +simlock --gateway token create --role worker --label mac-mini-2 +``` + +Then set the new `secret` on the worker as in step 2 above, and restart it. + ## What changes on a joined worker - **Local agents keep working.** Agents on the worker machine still lease devices from it directly. They share the worker's devices with requests from the gateway: a device a local agent holds is not free for the fleet, and the other way round. diff --git a/website/src/content/docs/docs/gateway/managing-workers.mdx b/website/src/content/docs/docs/gateway/managing-workers.mdx index 03ba6906e..d39f2b85a 100644 --- a/website/src/content/docs/docs/gateway/managing-workers.mdx +++ b/website/src/content/docs/docs/gateway/managing-workers.mdx @@ -161,7 +161,7 @@ simlock --gateway token revoke tok_9c1d4e7a-2b6f-4f3a-8d0e-5a7b3c9e1f24 {"revoked":true} ``` -Revoking closes the worker's connection at once. The worker keeps trying to reconnect, and the gateway refuses every try. Its leases keep running on the worker until their time to live runs out, but agents can no longer reach them through the gateway. +`token list` shows each used join token's `workerId`: the id of the worker it is paired with, as `worker list` shows it. Revoking closes the worker's connection at once. The worker keeps trying to reconnect, and the gateway refuses every try. Its leases keep running on the worker until their time to live runs out, but agents can no longer reach them through the gateway.