From 6ee7351232974f1bf2e309eb8e55f9c1c4443e0a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 18:42:14 +0200 Subject: [PATCH 1/4] =?UTF-8?q?test:=20reproduce=20#170=20=E2=80=94=20gate?= =?UTF-8?q?way.token=20reaches=20the=20daemon=20log,=20events.replay,=20an?= =?UTF-8?q?d=20events.jsonl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/daemon/main.test.ts | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 48adbed81..c49824016 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -140,6 +140,41 @@ describe("startDaemon", () => { expect(record?.fields?.config).toMatchObject({ log: { level: "info" } }); }); + it("keeps gateway.token out of the daemon log, the events.replay answer, and events.jsonl, while config.get still returns it", async () => { + const secret = "secret-join-token-170"; + // Nothing listens on a port just released, so the uplink's one dial fails fast; the fake + // clock never fires its retry. + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, "127.0.0.1", resolve)); + const { port } = probe.address() as { readonly port: number }; + await new Promise((resolve) => probe.close(() => resolve())); + const { daemon, directory, sink } = await start({ + configOverrides: { gateway: { token: secret, url: `ws://127.0.0.1:${port}` } }, + }); + const admin = { + manageEventSubscription: () => undefined, + principal: "operator", + role: "admin", + } as const; + + const replayed = await daemon.dispatch("events.replay", {}, admin); + const eventFile = await readFile(join(directory, "events.jsonl"), "utf8"); + const config = (await daemon.dispatch("config.get", {}, admin)) as { + readonly gateway: { readonly token?: string }; + }; + + // The fixture is real: the daemon did log its start and emit `daemon.started` to both + // the ring and the file, so "absent" below means redacted, not never written. + expect(sink.records.some((record) => record.message === "Daemon started")).toBe(true); + expect(eventFile).toContain('"daemon.started"'); + expect({ + daemonLog: JSON.stringify(sink.records).includes(secret), + eventsReplay: JSON.stringify(replayed).includes(secret), + eventsJsonl: eventFile.includes(secret), + }).toEqual({ daemonLog: false, eventsReplay: false, eventsJsonl: false }); + expect(config.gateway.token).toBe(secret); + }); + it("runs no prerequisite check at startup convergence, and runs every check on each doctor.run", async () => { const runs = { android: 0, ios: 0 }; const missing = { message: "gone", prerequisite: "android-emulator", remedy: "install it" }; From d279902e67b6c3653a0ad273a90ff35420395a6c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 19:05:20 +0200 Subject: [PATCH 2/4] fix(core,daemon,docs): redact gateway.token in the start log line and daemon.started (#170) --- docs/CLI.md | 2 +- docs/CONFIGURATION.md | 2 +- docs/EVENTS.md | 2 +- docs/internal/EVENTS.md | 2 +- src/core/config.test.ts | 37 ++++++++++++++++++++++++++++++++++- src/core/config.ts | 21 ++++++++++++++++++-- src/core/index.ts | 2 ++ src/daemon/main.test.ts | 43 ++++++++++++++++++++++++++++++++++------- src/daemon/server.ts | 9 +++++++-- 9 files changed, 104 insertions(+), 16 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index e6c130681..711ee7707 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1667,7 +1667,7 @@ daemon was asked to do and what went wrong; what happened to leases and devices is in `simlock events`, not here. It records: - **Startup and shutdown**: version, protocol version, socket path, effective - config, socket claim, driver discovery, and why a driver was skipped. + config (with `gateway.token` shown as `[redacted]`), socket claim, driver discovery, and why a driver was skipped. - **Every request that changes something**, on every frontend (CLI, MCP, HTTP, and a gateway's dispatch): one `operation` line when it finishes, with the operation, who asked (`principal`, and `requesterId` or `leaseId` diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 914de1860..267ff756a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -22,7 +22,7 @@ a warning. Inspect the effective, merged configuration at any time with | `lease.requestRetentionMs` | How long a settled lease request stays stored, counted from when it settled. A client that repeats a request with the same `idempotencyKey` inside this window gets the stored result back; after it, the record is removed and the same key starts a new request. | `10 minutes` | | `lease.maxRequestRecords` | The most lease-request records Simlock keeps. When a new request would go over it, the oldest settled record is removed. A request that is still open is never removed. | `10000` | | `gateway.url` | **Worker side.** Base URL of the gateway this worker joins, e.g. `wss://gw.example:4700`; the worker dials `/v1/uplink` and upgrades it to a WebSocket. Joining grants that gateway the `admin` role on this daemon, and `gateway.token` rides on the upgrade request as a bearer credential, so use `wss://` — or plain `ws://` only over loopback or inside your own tunnel. `http://` and `https://` are rejected at load. Unset means "do not join a fleet": the default, and the only thing that changes about a joined worker. | unset | -| `gateway.token` | **Worker side.** The join token (`simlock token create --role worker`, minted on the gateway) this worker presents when it opens its uplink. Required whenever `gateway.url` is set. | unset | +| `gateway.token` | **Worker side.** The join token (`simlock token create --role worker`, minted on the gateway) this worker presents when it opens its uplink. Required whenever `gateway.url` is set. `simlock config` shows it; the daemon log and the `daemon.started` event show `[redacted]`. | unset | | `gateway.label` | **Worker side.** Display name for this worker in `simlock worker list`, `status`, the console, and on the lease's `worker` block. Display-only: nothing routes on it and it need not be unique. | the worker's own id | | `exec.timeoutMs` | **Worker side.** How long one `device.exec` command (`simlock simctl` / `simlock adb` against a gateway or over HTTP) may run before the worker kills it and the operation fails with `EXEC_TIMEOUT`. Authoritative: it bounds the process that actually runs. | `10 minutes` | | `gateway.routing` | **Gateway side.** Which routing policy places a queued request on a worker. `warm-then-free` is the only policy in v1: among workers that can serve the request, warm hit first, then the most free running capacity for the platform. | `warm-then-free` | diff --git a/docs/EVENTS.md b/docs/EVENTS.md index e01bc544a..25330ed9e 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -75,7 +75,7 @@ that fails, emits nothing, and the component stays installed. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `daemon.started` | version, config snapshot | daemon finished startup + reconcile | DaemonServer | implemented | +| `daemon.started` | version, config snapshot (`gateway.token`, when set, reads `[redacted]`) | daemon finished startup + reconcile | DaemonServer | implemented | | `daemon.stopping` | reason | graceful shutdown began | DaemonServer | implemented | | `disk.pressure-detected` | free bytes, threshold | free disk crossed under the configured threshold (edge-triggered: once per crossing, not once per tick while it persists) | CleanupReaper | implemented | | `cleanup.executed` | rule name, action, target, reason | cleanup executor committed a proposed action | CleanupExecutor | implemented | diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 314b2e27d..d4e20a497 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -111,7 +111,7 @@ left behind (#79), each when there is one. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `daemon.started` | version, config snapshot | daemon finished startup + reconcile | DaemonServer | implemented | +| `daemon.started` | version, config snapshot (`gateway.token`, when set, reads `[redacted]`: the payload reaches the ring and `events.jsonl`, which are not guarded like `config.json`; masked rather than dropped so the keys stay the same, #170) | daemon finished startup + reconcile | DaemonServer | implemented | | `daemon.stopping` | reason | graceful shutdown began | DaemonServer | implemented | | `disk.pressure-detected` | free bytes, threshold | free disk crossed under the configured threshold (edge-triggered: once per crossing, not once per tick while it persists) | CleanupReaper | implemented | | `cleanup.executed` | rule name, action, target, reason | cleanup executor committed a proposed action | CleanupExecutor | implemented | diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 9b5985b77..98920591a 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -3,7 +3,13 @@ import { describe, expect, it, vi } from "vitest"; import { MemoryFilesystem, FakeSystemStats } from "../ports/index.js"; import type { ResourceStrategyOptions } from "./capacity/index.js"; import { configSchema } from "../contract/schemas.js"; -import { type Config, effectiveAllowDownload, loadConfig } from "./index.js"; +import { + type Config, + effectiveAllowDownload, + loadConfig, + REDACTED_VALUE, + redactConfig, +} from "./index.js"; /** Narrows the capacity block for assertions on resource-strategy configs. */ function resourceOptions(config: Config): ResourceStrategyOptions { @@ -1430,6 +1436,35 @@ describe("effectiveAllowDownload", () => { }); }); +describe("redactConfig", () => { + async function load(contents: unknown): Promise { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify(contents)); + return loadConfig({ configPath, filesystem, systemStats: createStats() }); + } + + it("replaces a set gateway.token with the marker, keeps every other key, and leaves the input untouched", async () => { + const config = await load({ + gateway: { label: "mac-1", token: "secret-join-token", url: "wss://gw.example:4700" }, + }); + + const redacted = redactConfig(config); + + expect(redacted).toEqual({ ...config, gateway: { ...config.gateway, token: REDACTED_VALUE } }); + expect(config.gateway.token).toBe("secret-join-token"); + }); + + it("adds no gateway.token to a config that has none, so unset still reads as unset", async () => { + const config = await load({}); + + const redacted = redactConfig(config); + + expect(redacted).toEqual(config); + expect(Object.keys(redacted.gateway)).not.toContain("token"); + }); +}); + describe("configSchema agrees with the config the daemon actually loads", () => { /** * `config.get` declares `configSchema` as its output (`contract/operations.ts`), and zod's diff --git a/src/core/config.ts b/src/core/config.ts index 56a668bcf..828b01ad0 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -248,8 +248,9 @@ export interface Config { /** A join token minted on the gateway with `simlock token create --role worker`. * Worker-side. It is a secret, and it sits in the daemon's config file like any other * value there: `config.get` is admin-role and returns the config as written, so this key - * is exactly as sensitive as `config.json`'s file permissions make it. See - * docs/CONFIGURATION.md. */ + * is exactly as sensitive as `config.json`'s file permissions make it. Everywhere else the + * config is written out -- the startup log line, `daemon.started` -- goes through + * `redactConfig`. See docs/CONFIGURATION.md. */ readonly token?: string; /** Display-only name for this worker in the gateway's views (§3a, §13). Worker-side. */ readonly label?: string; @@ -303,6 +304,22 @@ export interface Config { }; } +/** What `redactConfig` puts in place of a secret's value. */ +export const REDACTED_VALUE = "[redacted]"; + +/** + * The config with its secrets masked, for every place that writes the config somewhere other + * than `config.json` and `config.get`: the `Daemon started` log line and the `daemon.started` + * payload, which land in `daemon.log`, the event ring and `events.jsonl`. Masked rather than + * deleted so the copy keeps `Config`'s keys and a reader can still tell "set" from "unset". + * Returns a copy and never touches its input: the live config is what `config.get` answers + * and what the uplink presents, so the masked copy must never be handed to either. + */ +export function redactConfig(config: Config): Config { + if (config.gateway.token === undefined) return config; + return { ...config, gateway: { ...config.gateway, token: REDACTED_VALUE } }; +} + /** * The pre-`capacity` spelling of the resource strategy's options. Still accepted * everywhere the new shape is, and folded into `capacity.config` before anything diff --git a/src/core/index.ts b/src/core/index.ts index 37f0d6d7b..ce5eea98a 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -7,6 +7,8 @@ export { type DownloadPolicy, effectiveAllowDownload, loadConfig, + REDACTED_VALUE, + redactConfig, } from "./config.js"; export { type DeviceMode, diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index c49824016..1d81353ab 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -5,10 +5,12 @@ import { connect, createServer, Server } from "node:net"; import { afterEach, describe, expect, it, vi } from "vitest"; import { + type Config, type DriverToolVersion, FakeDriver, OWNED_ROOT_MARKER_FILE, type OwnedRootError, + REDACTED_VALUE, } from "../core/index.js"; import { IosSimctlDriver } from "../drivers/ios/index.js"; import { EventBus } from "../bus/index.js"; @@ -73,6 +75,16 @@ async function start( return { daemon, directory, sink }; } +/** A gateway URL on a port just released. Nothing listens there, so a worker's uplink dial + * fails fast, and the fake clock never fires its retry. */ +async function unreachableGatewayUrl(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, "127.0.0.1", resolve)); + const { port } = probe.address() as { readonly port: number }; + await new Promise((resolve) => probe.close(() => resolve())); + return `ws://127.0.0.1:${port}`; +} + async function writeModule(contents: string): Promise { const directory = await mkdtemp(join(tmpdir(), "simlock-drivers-module-")); temporaryDirectories.push(directory); @@ -142,14 +154,8 @@ describe("startDaemon", () => { it("keeps gateway.token out of the daemon log, the events.replay answer, and events.jsonl, while config.get still returns it", async () => { const secret = "secret-join-token-170"; - // Nothing listens on a port just released, so the uplink's one dial fails fast; the fake - // clock never fires its retry. - const probe = createServer(); - await new Promise((resolve) => probe.listen(0, "127.0.0.1", resolve)); - const { port } = probe.address() as { readonly port: number }; - await new Promise((resolve) => probe.close(() => resolve())); const { daemon, directory, sink } = await start({ - configOverrides: { gateway: { token: secret, url: `ws://127.0.0.1:${port}` } }, + configOverrides: { gateway: { token: secret, url: await unreachableGatewayUrl() } }, }); const admin = { manageEventSubscription: () => undefined, @@ -175,6 +181,29 @@ describe("startDaemon", () => { expect(config.gateway.token).toBe(secret); }); + it("keeps gateway.token in the daemon.started payload and the Daemon started log line as the redaction marker, so a set token still reads as set", async () => { + const { daemon, sink } = await start({ + configOverrides: { + gateway: { token: "secret-join-token-170", url: await unreachableGatewayUrl() }, + }, + }); + const replayed = (await daemon.dispatch( + "events.replay", + {}, + { manageEventSubscription: () => undefined, principal: "operator", role: "admin" }, + )) as readonly { readonly event: string; readonly payload: unknown }[]; + + const started = replayed.find((envelope) => envelope.event === "daemon.started"); + const logged = sink.records.find((record) => record.message === "Daemon started"); + const snapshot = (started?.payload as { readonly configSnapshot?: Config } | undefined) + ?.configSnapshot; + const loggedConfig = logged?.fields?.config as Config | undefined; + expect({ + eventToken: snapshot?.gateway.token, + logToken: loggedConfig?.gateway.token, + }).toEqual({ eventToken: REDACTED_VALUE, logToken: REDACTED_VALUE }); + }); + it("runs no prerequisite check at startup convergence, and runs every check on each doctor.run", async () => { const runs = { android: 0, ios: 0 }; const missing = { message: "gone", prerequisite: "android-emulator", remedy: "install it" }; diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 8343f3a2a..a8428d487 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -13,6 +13,7 @@ import { type LeaseHealthMonitor, NoDriverError, type Nuke, + redactConfig, UnknownPassthroughToolError, } from "../core/index.js"; import type { @@ -529,9 +530,13 @@ export class DaemonServer { }), ); + // Redacted: the payload lands in the ring and `events.jsonl`, and the log line in + // `daemon.log`, none of which is as guarded as `config.json`. `this.options.config` itself + // stays whole -- `config.get` answers from it. + const configSnapshot = redactConfig(this.options.config); this.options.eventBus.emit( "daemon.started", - { configSnapshot: this.options.config, version: this.options.version }, + { configSnapshot, version: this.options.version }, "daemon", ); // After `daemon.started`, because these are facts about the daemon that just started @@ -543,7 +548,7 @@ export class DaemonServer { this.options.eventBus.emit(rejection.event, rejection.payload, "daemon"); } this.#logger.info("Daemon started", { - config: this.options.config, + config: configSnapshot, protocolVersion: this.#protocolRange.max, protocolRange: this.#protocolRange, socketPath: this.options.host.endpoint, From 15cb9b8b963981432519e87425cf1a34ed693ab0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 19:42:00 +0200 Subject: [PATCH 3/4] test(daemon): prove daemon.started reached the ring before asserting the token is absent from it (#170) --- src/daemon/main.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 1d81353ab..ba2d39fef 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -173,6 +173,7 @@ describe("startDaemon", () => { // the ring and the file, so "absent" below means redacted, not never written. expect(sink.records.some((record) => record.message === "Daemon started")).toBe(true); expect(eventFile).toContain('"daemon.started"'); + expect(JSON.stringify(replayed)).toContain('"daemon.started"'); expect({ daemonLog: JSON.stringify(sink.records).includes(secret), eventsReplay: JSON.stringify(replayed).includes(secret), From acc270c2230b21e4a1dd6c7bfdf13cff35dc5ca9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 19:46:17 +0200 Subject: [PATCH 4/4] test(core): compare redactConfig's input against a copy taken before the call (#170) --- src/core/config.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 98920591a..b533ec74e 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -1449,9 +1449,12 @@ describe("redactConfig", () => { gateway: { label: "mac-1", token: "secret-join-token", url: "wss://gw.example:4700" }, }); + const before = structuredClone(config); + const redacted = redactConfig(config); - expect(redacted).toEqual({ ...config, gateway: { ...config.gateway, token: REDACTED_VALUE } }); + expect(redacted).toEqual({ ...before, gateway: { ...before.gateway, token: REDACTED_VALUE } }); + expect(config).toEqual(before); expect(config.gateway.token).toBe("secret-join-token"); });