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/internal/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ left behind (#79), each when there is one.

| Event | Payload (key fields) | Emitted when | Emitter | Status |
|---|---|---|---|---|
| `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.started` | version, config snapshot (`gateway.token`, when set, reads `[redacted]`: the payload reaches the ring and `events.jsonl`, which are not a token's place the way `config.json` and `config.get` are; 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
2 changes: 1 addition & 1 deletion src/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic
quarantine stalls (age > estimate × `stalledTransition.thresholdMultiplier`, unclaimed).
9. **Physical** — `PhysicalEnrollment.add` refuses Simlock's own devices, reads `inspectPhysical`,
writes `ready` with `enrolledApps`, or re-enrols under `enrollment`; `remove` unenrols. Busy: `DeviceBusyError`.
10. **Ownership** — `loadInstanceId` creates `instance.json` once (exclusive create). `ensureOwnedRoot`
10. **Ownership** — `loadInstanceId` creates `instance.json` once (exclusive create, `0600`). `ensureOwnedRoot`
stages a root with `.simlock-owned.json` (instance id, platform), mode `0700`; doubt is `OwnedRootError`.
11. **Components** — `ComponentInstaller`, the only caller of `installComponent`/`removeComponent`.
One FIFO per platform; a call for the same component joins. At the front: `stillNeeded` →
Expand Down
19 changes: 19 additions & 0 deletions src/core/instance-identity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,25 @@ describe("loadInstanceId on a real filesystem", () => {
// Written once: the two that lost the race read the winner's file instead of writing.
await expect(filesystem.readdir(home)).resolves.toEqual(["instance.json"]);
});

it("creates instance.json owner-only", async () => {
// why: #685: `writeFileExclusive` links a temp file into place, and that temp file is written
// without a mode, so the identity the daemon stamps into every device root lands world-
// readable under the umask every real host starts from. A restrictive umask here would
// mask what the code asks for, so pin 022.
const previousUmask = process.umask(0o022);
try {
const filesystem = new NodeFilesystem();
home = await mkdtemp(join(tmpdir(), "simlock-instance-identity-"));
const instancePath = join(home, "instance.json");

await loadInstanceId({ filesystem, idGenerator: sequence(), path: instancePath });

expect((await filesystem.stat(instancePath)).mode).toBe(0o600);
} finally {
process.umask(previousUmask);
}
});
});

/** Stands in for another daemon whose exclusive create landed first. */
Expand Down
9 changes: 8 additions & 1 deletion src/core/instance-identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import { dirname } from "node:path";

import type { Filesystem, IdGenerator } from "../ports/index.js";

/** why: Owner-only, like the other files that hold secrets or state (`config.json`,
* `state.json`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and the id this
* file holds is what every device root's ownership marker is checked against. */
const INSTANCE_FILE_MODE = 0o600;

export interface InstanceIdentityOptions {
readonly filesystem: Filesystem;
readonly idGenerator: IdGenerator;
Expand Down Expand Up @@ -45,7 +50,9 @@ export async function loadInstanceId(options: InstanceIdentityOptions): Promise<
// land on top of an identity the winner had already stamped into its roots, and every
// one of them would read `wrong-instance` from then on. Here the kernel picks the
// winner and the loser is told so.
await options.filesystem.writeFileExclusive(options.path, serializeIdentity(generated));
await options.filesystem.writeFileExclusive(options.path, serializeIdentity(generated), {
mode: INSTANCE_FILE_MODE,
});
} catch (error: unknown) {
if (!isExistingPathError(error)) {
throw new InstanceIdentityError(
Expand Down
3 changes: 2 additions & 1 deletion src/ports/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ Uses: nothing from other components. Imported by: every component that touches t
| Paths | `paths.ts` | `resolveSimlockHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (default `~/.simlock`), socket path length |

`productionHostLoadProbe` picks the Darwin or Linux probe. `NodeFileLogSink` rotates to
`<path>.1`, or keeps numbered generations when given `retentionMs` or `totalMaxBytes`.
`<path>.1`, or keeps numbered generations when given `retentionMs` or `totalMaxBytes`. The
files it opens, and the log `NodeDaemonLauncher` pre-creates, are opened mode `0600`.

## Rules

Expand Down
27 changes: 26 additions & 1 deletion src/ports/daemon-launcher.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { mkdtemp, readFile, readdir, rm } from "node:fs/promises";
import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

Expand Down Expand Up @@ -45,6 +45,31 @@ describe("NodeDaemonLauncher", () => {
}
});

it("creates the daemon log it hands the child owner-only", async () => {
// why: #685: when the CLI or MCP server auto-launches the daemon, this `open(path, "a")` is
// what first creates `daemon.log` -- the daemon's own sink only appends afterwards. A
// restrictive umask in the test environment would mask what the code asks for, so pin
// the one every real host starts from.
const previousUmask = process.umask(0o022);
const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-"));
const logPath = join(directory, "daemon.log");
const launcher = new NodeDaemonLauncher({
args: ["-e", "console.log('out')"],
command: process.execPath,
logPath,
simlockHome: directory,
});
try {
await launcher.launch();
await expect.poll(async () => (await readFile(logPath, "utf8")).trim()).toBe("out");

expect((await stat(logPath)).mode & 0o777).toBe(0o600);
} finally {
process.umask(previousUmask);
await rm(directory, { force: true, recursive: true });
}
});

it("combines stdout and stderr in an append-only log", async () => {
const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-"));
const logPath = join(directory, "daemon.log");
Expand Down
5 changes: 4 additions & 1 deletion src/ports/daemon-launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ export class NodeDaemonLauncher implements DaemonLauncher {

async launch(): Promise<void> {
await mkdir(dirname(this.options.logPath), { recursive: true });
const log = await open(this.options.logPath, "a");
// why: 0600 at creation, like the other files that hold secrets or state under the home:
// this `open` is what first creates `daemon.log` for an auto-launched daemon -- the daemon's
// own sink only appends to the file this one made.
const log = await open(this.options.logPath, "a", 0o600);
try {
const child = spawn(this.options.command, this.options.args, {
detached: true,
Expand Down
22 changes: 22 additions & 0 deletions src/ports/filesystem.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,28 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link })
await expect(filesystem.readFile(file)).resolves.toBe("first writer");
});

it("creates an exclusively written file with the mode it is given, and Node's default without one", async () => {
// why: #685: the exclusive create publishes by hard-linking a temp file, so a mode that
// did not ride on that file's create would leave the winner's file world-readable. A
// restrictive umask here would mask what the code asks for, so pin the one a host starts
// from and pin both halves: the mode a caller asks for, and the default it gets for free.
const previousUmask = process.umask(0o022);
try {
const filesystem = create();
const asked = `${temporaryDirectory}/asked.json`;
const unasked = `${temporaryDirectory}/unasked.json`;

await filesystem.mkdirp(temporaryDirectory);
await filesystem.writeFileExclusive(asked, "{}", { mode: 0o600 });
await filesystem.writeFileExclusive(unasked, "{}");

expect((await filesystem.stat(asked)).mode).toBe(0o600);
expect((await filesystem.stat(unasked)).mode).toBe(0o644);
} finally {
process.umask(previousUmask);
}
});

it("moves a directory and everything under it in one step", async () => {
const filesystem = create();
const staging = `${temporaryDirectory}/.ios.staging`;
Expand Down
45 changes: 38 additions & 7 deletions src/ports/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ export interface WriteFileAtomicOptions {
readonly mode?: number;
}

/** why: Same shape as {@link WriteFileAtomicOptions}: `writeFileExclusive` publishes through a
* hard-linked temp file, so the mode rides on that file's create and the link preserves it. */
export interface WriteFileExclusiveOptions {
readonly mode?: number;
}

/**
* What an un-followed `lstat` reports, narrowed to what ownership validation asks of a
* path: what it really is, who owns it, and how exposed it is. Anything richer would be
Expand All @@ -61,7 +67,11 @@ export interface Filesystem {
* end up agreeing about what it says. The file appears with its full contents, never
* empty, so a loser that reads it straight away reads what the winner wrote.
*/
writeFileExclusive(path: string, contents: string): Promise<void>;
writeFileExclusive(
path: string,
contents: string,
options?: WriteFileExclusiveOptions,
): Promise<void>;
mkdirp(path: string): Promise<void>;
/**
* Moves a path in one step, so what it names becomes visible complete or not at all.
Expand Down Expand Up @@ -136,7 +146,11 @@ export class NodeFilesystem implements Filesystem {
}
}

async writeFileExclusive(path: string, contents: string): Promise<void> {
async writeFileExclusive(
path: string,
contents: string,
options?: WriteFileExclusiveOptions,
): Promise<void> {
// `writeFile` with the `wx` flag creates the file empty and fills it a moment later, so a
// racer that loses the create can read it in between and find nothing. Write the contents
// aside first and hard-link them into place: `link` fails `EEXIST` like `wx` does, but the
Expand All @@ -145,7 +159,16 @@ export class NodeFilesystem implements Filesystem {
dirname(path),
`.${basename(path)}.${process.pid}.${crypto.randomUUID()}.tmp`,
);
await writeFile(temporaryPath, contents, { encoding: "utf8", flag: "wx" });
// why: the mode rides on the temp file's create -- a hard link carries it over, so the
// published file is never world-readable even briefly. A `chmod` after the link is the
// window this port's own doc rules out.
await writeFile(
temporaryPath,
contents,
options?.mode === undefined
? { encoding: "utf8", flag: "wx" }
: { encoding: "utf8", flag: "wx", mode: options.mode },
);
try {
await link(temporaryPath, path);
} finally {
Expand Down Expand Up @@ -267,8 +290,9 @@ const DEFAULT_MEMORY_MODE = 0o700;
// A symlink cycle is a legitimate thing to model; resolving it forever is not.
const MAX_SYMLINK_HOPS = 32;

/** Node's default for a plain file, kept as the default `writeFileAtomic` creates with so a
* caller that says nothing about permissions gets what it got before `mode` was an option. */
/** why: Node's default for a plain file, kept as the default both `writeFileAtomic` and
* `writeFileExclusive` create with so a caller that says nothing about permissions gets what
* it got before `mode` was an option. */
const DEFAULT_FILE_MODE = 0o644;

export class MemoryFilesystem implements Filesystem {
Expand Down Expand Up @@ -314,7 +338,11 @@ export class MemoryFilesystem implements Filesystem {
});
}

async writeFileExclusive(path: string, contents: string): Promise<void> {
async writeFileExclusive(
path: string,
contents: string,
options?: WriteFileExclusiveOptions,
): Promise<void> {
this.#failIfDefined(path);
path = this.#underResolvedParent(path);

Expand All @@ -323,7 +351,10 @@ export class MemoryFilesystem implements Filesystem {
}

this.#requireDirectory(parentPath(path));
this.#entries.set(path, this.#newEntry({ kind: "file", contents }));
this.#entries.set(path, {
...this.#newEntry({ kind: "file", contents }),
mode: options?.mode ?? DEFAULT_FILE_MODE,
});
}

async mkdirp(path: string): Promise<void> {
Expand Down
51 changes: 50 additions & 1 deletion src/ports/logger.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readdirSync } from "node:fs";
import { mkdtemp, readFile, readdir, rename, rm, utimes, writeFile } from "node:fs/promises";
import { mkdtemp, readFile, readdir, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
Expand Down Expand Up @@ -132,6 +132,55 @@ async function tempDir(): Promise<string> {
}

describe("NodeFileLogSink", () => {
it("creates every file it holds owner-only, the current file and every rotated generation alike", async () => {
// why: #685: `daemon.log` and `events.jsonl` are both sinks of this class, and a rotated
// generation is a file this class creates too (`openSync(path, "a")` after each
// rename). A restrictive umask in the test environment would mask what the code
// actually asks for, so pin the one every real host starts from.
const previousUmask = process.umask(0o022);
try {
const directory = await tempDir();
// why: one sink at the daemon's `daemon.log` shape (single generation), one at the
// `events.jsonl` shape (numbered generations under retention) — the two shapes the
// daemon actually opens.
const paths = {
daemonLog: join(directory, "daemon.log"),
events: join(directory, "events.jsonl"),
};
// why: the second write passes the 12-byte cap — that rotation is part of what this asserts.
const logSink = new NodeFileLogSink({ maxBytes: 12, path: paths.daemonLog });
logSink.write("first");
logSink.write("second");
logSink.close();
const eventSink = new NodeFileLogSink({
clock: new FakeClock(1_000),
maxBytes: 12,
path: paths.events,
retentionMs: 1,
totalMaxBytes: 1_000,
});
// why: the second write rotates this sink too, and the rotated generation is a file
// this class creates — its mode is part of the claim.
eventSink.write('{"timestamp":1000}');
eventSink.write('{"timestamp":1000}');
eventSink.close();

expect({
daemonLog: (await stat(paths.daemonLog)).mode & 0o777,
daemonLogRotated: (await stat(`${paths.daemonLog}.1`)).mode & 0o777,
events: (await stat(paths.events)).mode & 0o777,
eventsRotated: (await stat(`${paths.events}.1`)).mode & 0o777,
}).toEqual({
daemonLog: 0o600,
daemonLogRotated: 0o600,
events: 0o600,
eventsRotated: 0o600,
});
} finally {
process.umask(previousUmask);
}
});

it("appends one line per write to the target file", async () => {
const directory = await tempDir();
const path = join(directory, "daemon.log");
Expand Down
10 changes: 8 additions & 2 deletions src/ports/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,12 @@ function readTail(file: string): string {
}
}

// why: Owner-only, like the other files that hold secrets or state (`config.json`,
// `state.json`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and a shared
// runner's other users have no business reading a daemon's log or event stream. Set at each
// `open`, never a later `chmod`, so no generation is ever born world-readable.
const FILE_MODE = 0o600;

export interface NodeFileLogSinkOptions {
/** One generation: the size at which the current file rotates. */
readonly maxBytes?: number;
Expand Down Expand Up @@ -200,7 +206,7 @@ export class NodeFileLogSink implements LogSink {
this.#totalMaxBytes = options.totalMaxBytes;
this.#clock = options.clock ?? new SystemClock();
mkdirSync(dirname(this.#path), { recursive: true });
this.#fd = openSync(this.#path, "a");
this.#fd = openSync(this.#path, "a", FILE_MODE);
this.#bytesWritten = fstatSync(this.#fd).size;
this.#sweep();
}
Expand Down Expand Up @@ -232,7 +238,7 @@ export class NodeFileLogSink implements LogSink {
this.#shiftGenerations();
}
renameSync(this.#path, `${this.#path}.1`);
this.#fd = openSync(this.#path, "a");
this.#fd = openSync(this.#path, "a", FILE_MODE);
this.#bytesWritten = 0;
this.#sweep();
}
Expand Down
Loading