Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
2 changes: 1 addition & 1 deletion docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<url>/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` |
Expand Down
2 changes: 1 addition & 1 deletion docs/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion docs/internal/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
40 changes: 39 additions & 1 deletion src/core/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -1430,6 +1436,38 @@ describe("effectiveAllowDownload", () => {
});
});

describe("redactConfig", () => {
async function load(contents: unknown): Promise<Config> {
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 before = structuredClone(config);

const redacted = redactConfig(config);

expect(redacted).toEqual({ ...before, gateway: { ...before.gateway, token: REDACTED_VALUE } });
expect(config).toEqual(before);
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
Expand Down
21 changes: 19 additions & 2 deletions src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export {
type DownloadPolicy,
effectiveAllowDownload,
loadConfig,
REDACTED_VALUE,
redactConfig,
} from "./config.js";
export {
type DeviceMode,
Expand Down
65 changes: 65 additions & 0 deletions src/daemon/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string> {
const probe = createServer();
await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve));
const { port } = probe.address() as { readonly port: number };
await new Promise<void>((resolve) => probe.close(() => resolve()));
return `ws://127.0.0.1:${port}`;
}

async function writeModule(contents: string): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "simlock-drivers-module-"));
temporaryDirectories.push(directory);
Expand Down Expand Up @@ -140,6 +152,59 @@ 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";
const { daemon, directory, sink } = await start({
configOverrides: { gateway: { token: secret, url: await unreachableGatewayUrl() } },
});
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(JSON.stringify(replayed)).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("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" };
Expand Down
9 changes: 7 additions & 2 deletions src/daemon/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
type LeaseHealthMonitor,
NoDriverError,
type Nuke,
redactConfig,
UnknownPassthroughToolError,
} from "../core/index.js";
import type {
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
Loading