diff --git a/src/daemon/connection-host.test.ts b/src/daemon/connection-host.test.ts index 68e2509eb..fe812d15f 100644 --- a/src/daemon/connection-host.test.ts +++ b/src/daemon/connection-host.test.ts @@ -171,28 +171,32 @@ describe("DaemonEndpointHost", () => { await expect(ipc.connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found" }); }); - it("creates the directory its endpoint lives in owner-only", async () => { - // why: under the umask every real host starts from, a directory made without a mode comes - // out 0755, so only a mode the host asks for ends at 0700. - const previousUmask = process.umask(0o022); - const base = await mkdtemp(join(tmpdir(), "simlock-endpoint-")); - const ipc = new MemoryIpcTransport(); - const host = new DaemonEndpointHost({ - connector: ipc, - endpoint: join(base, "home", "daemon.sock"), - filesystem: new NodeFilesystem(), - listenerFactory: ipc, - }); - try { - await host.start(() => undefined); + // why: a POSIX mode and umask have no Windows counterpart, and the Windows endpoint is a pipe that lives in no directory. + it.skipIf(process.platform === "win32")( + "creates the directory its endpoint lives in owner-only", + async () => { + // why: under the umask every real host starts from, a directory made without a mode comes + // out 0755, so only a mode the host asks for ends at 0700. + const previousUmask = process.umask(0o022); + const base = await mkdtemp(join(tmpdir(), "simlock-endpoint-")); + const ipc = new MemoryIpcTransport(); + const host = new DaemonEndpointHost({ + connector: ipc, + endpoint: join(base, "home", "daemon.sock"), + filesystem: new NodeFilesystem(), + listenerFactory: ipc, + }); + try { + await host.start(() => undefined); - expect((await stat(join(base, "home"))).mode & 0o777).toBe(0o700); - } finally { - process.umask(previousUmask); - await host.stop(); - await rm(base, { force: true, recursive: true }); - } - }); + expect((await stat(join(base, "home"))).mode & 0o777).toBe(0o700); + } finally { + process.umask(previousUmask); + await host.stop(); + await rm(base, { force: true, recursive: true }); + } + }, + ); it("rejects a live endpoint before binding", async () => { const filesystem = new MemoryFilesystem(); diff --git a/src/daemon/device-data-tables.test.ts b/src/daemon/device-data-tables.test.ts index 7a7a2ae5c..3cdacfcb2 100644 --- a/src/daemon/device-data-tables.test.ts +++ b/src/daemon/device-data-tables.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -11,10 +11,12 @@ import { iosDeviceDataTable } from "../drivers/ios/index.js"; import { FakeClock, NodeFilesystem, NodeSqliteOpener, NoopLogger } from "../ports/index.js"; import { openStateDatabase } from "../state/index.js"; import { productionDeviceDataTables } from "./driver-discovery.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; describe("the production device-data tables", () => { it("a registry restarted on one state.db returns an iOS and an Android device's driverData unchanged", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-device-data-")); + const states: Awaited>[] = []; try { const clock = new FakeClock(1_000); const iosData = { @@ -32,22 +34,25 @@ describe("the production device-data tables", () => { serial: "emulator-5554", }; let next = 0; - const open = async () => - Registry.load({ + const open = async () => { + const state = await openStateDatabase({ + dataDirectory: directory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [registryOwner, iosDeviceDataTable, androidDeviceDataTable], + sqlite: new NodeSqliteOpener(), + upgradeStep: "remove it.", + }); + states.push(state); + return Registry.load({ clock, deviceData: productionDeviceDataTables(), eventBus: new EventBus(clock), idGenerator: { generate: () => String((next += 1)) }, - state: await openStateDatabase({ - dataDirectory: directory, - filesystem: new NodeFilesystem(), - logger: new NoopLogger(), - oldFiles: [], - owners: [registryOwner, iosDeviceDataTable, androidDeviceDataTable], - sqlite: new NodeSqliteOpener(), - upgradeStep: "remove it.", - }), + state, }); + }; const registry = await open(); await registry.registerDevice({ driverData: iosData, @@ -72,7 +77,9 @@ describe("the production device-data tables", () => { expect(byDriverId.get("drv-ios")).toStrictEqual(iosData); expect(byDriverId.get("drv-android")).toStrictEqual(androidData); } finally { - await rm(directory, { force: true, recursive: true }); + // why: Windows refuses to delete a database file that is still open. + for (const state of states) state.database.close(); + await removeDirectory(directory); } }); }); diff --git a/src/daemon/driver-discovery.test.ts b/src/daemon/driver-discovery.test.ts index bd53624fd..755d7df7f 100644 --- a/src/daemon/driver-discovery.test.ts +++ b/src/daemon/driver-discovery.test.ts @@ -1,8 +1,9 @@ import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { type Config, OWNED_ROOT_MARKER_FILE, type OwnedRootError } from "../core/index.js"; import { androidDriverConfig } from "../drivers/android/index.js"; +import { binaries } from "../drivers/android/testing.js"; import { IosSimctlDriver, iosDriverConfig } from "../drivers/ios/index.js"; import { EventBus } from "../bus/index.js"; import { @@ -169,9 +170,7 @@ describe("discoverDrivers on a host with an Android SDK", () => { const { drivers, rejections } = await discoverAndroid(filesystem, probe, [4242]); expect(rejections).toEqual([]); - expect(drivers.find((driver) => driver.platform === "android")?.deviceRoot).toBe( - join(SIMLOCK_HOME, "devices", "android"), - ); + expect(drivers.find((driver) => driver.platform === "android")?.deviceRoot).toBe(ANDROID_ROOT); }); it.each([ @@ -184,7 +183,7 @@ describe("discoverDrivers on a host with an Android SDK", () => { }, { platform: "android", - root: join(SIMLOCK_HOME, "devices", "android"), + root: ANDROID_ROOT, discover: async (filesystem: MemoryFilesystem) => { await filesystem.mkdirp(SIMLOCK_HOME); await filesystem.writeFileAtomic( @@ -204,7 +203,7 @@ describe("discoverDrivers on a host with an Android SDK", () => { expect(rename).toHaveBeenCalledWith( expect.stringMatching( - new RegExp(`/devices/\\.${platform}\\.${process.pid}\\.[^/]+\\.staging$`), + new RegExp(`[\\\\/]devices[\\\\/]\\.${platform}\\.${process.pid}\\.[^\\\\/]+\\.staging$`), ), root, ); @@ -220,11 +219,11 @@ describe("discoverDrivers on a host with an Android SDK", () => { ); const processRunner = new ScriptedProcessRunner([ { - match: { args: ["devices"], command: "/android-sdk/platform-tools/adb" }, + match: { args: ["devices"], command: binaries.adb }, result: { code: 0, stderr: "", stdout: "List of devices attached\n" }, }, { - match: { args: ["-help"], command: "/android-sdk/emulator/emulator" }, + match: { args: ["-help"], command: binaries.emulator }, result: { code: 0, stderr: "", stdout: " -crash-report-mode crash reporting\n" }, }, ]); @@ -351,7 +350,7 @@ describe("discoverDrivers on a host with an Android SDK", () => { { match: { args: ["list", "device"], - command: "/android-sdk/cmdline-tools/latest/bin/avdmanager", + command: binaries.avdmanager, }, result: { code: 0, stderr: "", stdout: "Available devices:\n" }, }, @@ -460,7 +459,7 @@ describe("discoverDrivers on a host with an Android SDK", () => { processRunner: runner, }); const driver = drivers.find((candidate) => candidate.platform === "android"); - const avdHome = join(SIMLOCK_HOME, "devices", "android", "device-1"); + const avdHome = join(ANDROID_ROOT, "device-1"); await filesystem.mkdirp(join(avdHome, "simlock.avd")); const ready = driver!.makeReady( { @@ -513,12 +512,7 @@ describe("discoverDrivers on a host with an Android SDK", () => { async function androidSdk(): Promise { const filesystem = new MemoryFilesystem(); process.env.ANDROID_HOME = "/android-sdk"; - for (const binary of [ - "/android-sdk/platform-tools/adb", - "/android-sdk/emulator/emulator", - "/android-sdk/cmdline-tools/latest/bin/avdmanager", - "/android-sdk/cmdline-tools/latest/bin/sdkmanager", - ]) { + for (const binary of Object.values(binaries)) { await filesystem.mkdirp(binary.slice(0, binary.lastIndexOf("/"))); await filesystem.writeFileAtomic(binary, "binary"); } @@ -567,7 +561,9 @@ describe("discoverDrivers on a host with an Android SDK", () => { } }); -const IOS_ROOT = join(SIMLOCK_HOME, "devices", "ios"); +// why: `ensureOwnedRoot` resolves the configured root, so on Windows the driver reads `D:\home\...`. +const IOS_ROOT = resolve(SIMLOCK_HOME, "devices", "ios"); +const ANDROID_ROOT = resolve(SIMLOCK_HOME, "devices", "android"); const INSTANCE_ID = "instance-1"; diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index feaab82e0..e7f70c0d1 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -23,7 +23,7 @@ */ import { createHmac } from "node:crypto"; import { createServer as createHttpServer, type Server } from "node:http"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, readdir } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -35,6 +35,7 @@ import type { AlertDestination, PassthroughCommand } from "../core/index.js"; import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import type { Filesystem, IpcConnector, IpcListenerFactory, NpmCli } from "../ports/index.js"; import { + FakeDirectoryAccessReader, FakeHostInfo, FakeNpmCli, FakeUpdaterLauncher, @@ -51,6 +52,7 @@ import { connectSimlockAdmin } from "../admin/index.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import type { DaemonServer } from "./server.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; function passthroughOptions(command: PassthroughCommand): object { return { passthrough: () => command, passthroughTools: ["adb"] }; @@ -123,10 +125,15 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { afterEach(async () => { await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); + // why: worker-b's directory stays busy on Windows for a few seconds after its daemon stopped (a leftover handle nobody could name), longer than `removeDirectory` waits, so the removal is tried again until it goes through, for less than the hook's own 30 s so a handle that stays held fails with the removal's own error. await Promise.all( - directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), + directories + .splice(0) + .map((directory) => + vi.waitFor(() => removeDirectory(directory), { interval: 250, timeout: 25_000 }), + ), ); - }); + }, 30_000); async function startGateway( alerts: { @@ -157,6 +164,11 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { }, role: "gateway", dataDirectory: directory, + // why: on Windows the daemon reads the data directory's ACL through the process runner, which a scripted one refuses. + directoryAccess: new FakeDirectoryAccessReader({ + entries: [], + user: "S-1-5-21-1-2-3-1001", + }), filesystem: new MemoryFilesystem(), hostInfo: new FakeHostInfo(GATEWAY_HOST), logger: new NoopLogger(), @@ -416,7 +428,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { token: tokenA, stdout: "hello-from-a", }); - await startWorker({ + const workerB = await startWorker({ label: "worker-b", model: "Pixel-B", token: tokenB, @@ -465,6 +477,12 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { expect(chunks.join("")).toBe("hello-from-b"); await gateway.dispatch("lease.release", { leaseId: grant.lease.id }, agentSession()); + + // why: the lease's folder is removed after `lease.release` answers, and Windows refuses to remove the + // worker's directory while that removal is still running, so the test waits for it. + await vi.waitFor(async () => { + expect(await readdir(join(workerB.directory, "lease-files"))).toEqual([]); + }); }, 30_000); /** diff --git a/src/daemon/lease-files.test.ts b/src/daemon/lease-files.test.ts index b4fc3f521..f3c77e9e4 100644 --- a/src/daemon/lease-files.test.ts +++ b/src/daemon/lease-files.test.ts @@ -207,9 +207,9 @@ describe("a lease's folder", () => { const filesystem = new GatedFilesystem(); const files = leaseFilesOver(filesystem); - expect(await files.folderOf(grant("CI", 1))).toBe("/data/lease-files/4349-1"); - expect(await files.folderOf(grant("ci", 1))).toBe("/data/lease-files/6369-1"); - expect(await files.folderOf(grant("ci", 2))).toBe("/data/lease-files/6369-2"); + expect(await files.folderOf(grant("CI", 1))).toBe(join("/data", "lease-files", "4349-1")); + expect(await files.folderOf(grant("ci", 1))).toBe(join("/data", "lease-files", "6369-1")); + expect(await files.folderOf(grant("ci", 2))).toBe(join("/data", "lease-files", "6369-2")); await files.leaseEnd.leaseEnded(ended("ci", 1), new AbortController().signal); diff --git a/src/daemon/lease-requires.e2e.test.ts b/src/daemon/lease-requires.e2e.test.ts index 0ac646e4d..ab1c87889 100644 --- a/src/daemon/lease-requires.e2e.test.ts +++ b/src/daemon/lease-requires.e2e.test.ts @@ -1,10 +1,11 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { startOnFreePort } from "../test-support/loopback-port.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; import { agentDeviceModuleWith, FakeAgentDevice } from "../agent-device/testing.js"; import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; @@ -40,10 +41,15 @@ describe("lease.request requires, through a gateway", () => { afterEach(async () => { await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); + // why: Windows keeps a stopped daemon's directory busy for a few seconds, longer than `removeDirectory` waits, so the removal is tried again until it goes through, for less than the hook's own 30 s so a handle that stays held fails with the removal's own error. await Promise.all( - directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), + directories + .splice(0) + .map((directory) => + vi.waitFor(() => removeDirectory(directory), { interval: 250, timeout: 25_000 }), + ), ); - }); + }, 30_000); async function startGateway() { const directory = await mkdtemp(join(tmpdir(), "simlock-e2e-requires-gateway-")); diff --git a/src/daemon/main-agent-device.test.ts b/src/daemon/main-agent-device.test.ts index 9f4d9b6c9..aa37e4fbc 100644 --- a/src/daemon/main-agent-device.test.ts +++ b/src/daemon/main-agent-device.test.ts @@ -8,6 +8,7 @@ import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import { fakeModule, type FakeModule } from "../modules/testing.js"; import { FakeClock, + FakeDirectoryAccessReader, FakeHostInfo, FakeProcessSupervisor, FakeTcpProbe, @@ -78,7 +79,8 @@ describe("startDaemon with the agent-device edge", () => { JSON.stringify({ entry, pid: options.record.pid, startedAt: 1 }), ); } - return { directory, filesystem }; + // why: the daemon names its home by the filesystem's real path, which the in-memory one spells with `/` and no drive. + return { directory, filesystem, home: await filesystem.realpath(directory) }; } /** why: pid 900 answers as this home's own agent-device daemon, so a supervisor that ran would read its command line and SIGTERM it. */ @@ -128,6 +130,7 @@ describe("startDaemon with the agent-device edge", () => { const daemon = await startDaemon({ clock, dataDirectory: setup.directory, + directoryAccess: new FakeDirectoryAccessReader({ entries: [], user: "S-1-5-21-1-2-3-1001" }), ...(ports.role === undefined ? {} : { role: ports.role }), deviceDataTables: fakeDeviceDataTables, drivers: ports.drivers ?? [ @@ -157,7 +160,7 @@ describe("startDaemon with the agent-device edge", () => { }); const events: string[] = []; const processSupervisor = new KillingSupervisor(); - const runner = versionAndDaemon(setup.directory); + const runner = versionAndDaemon(setup.home); const spawn = runner.spawn.bind(runner); vi.spyOn(runner, "spawn").mockImplementation((spawned, args, options) => { const handle = spawn(spawned, args, options); @@ -214,7 +217,7 @@ describe("startDaemon with the agent-device edge", () => { const daemonAt = (stateDirName: string, pid: number, port: number, marker: string[]) => ({ hangs: true, match: { - args: [entry, `--simlock-home=${setup.directory}`, ...marker], + args: [entry, `--simlock-home=${setup.home}`, ...marker], command: process.execPath, }, onSpawn: async () => { @@ -267,7 +270,7 @@ describe("startDaemon with the agent-device edge", () => { it("resolves and grants a lease to an ordinary client while agent-device's /health never answers", async () => { const setup = await setUp({ capabilities: { "agent-device": { command, enabled: true } } }); const processSupervisor = new KillingSupervisor(); - const runner = versionAndDaemon(setup.directory); + const runner = versionAndDaemon(setup.home); const spawn = runner.spawn.bind(runner); vi.spyOn(runner, "spawn").mockImplementation((spawned, args, options) => { const handle = spawn(spawned, args, options); @@ -296,7 +299,7 @@ describe("startDaemon with the agent-device edge", () => { async function spawnedEnvironment(drivers: (clock: FakeClock) => StartDaemonOptions["drivers"]) { const setup = await setUp({ capabilities: { "agent-device": { command, enabled: true } } }); - const runner = versionAndDaemon(setup.directory); + const runner = versionAndDaemon(setup.home); await startEdge(setup, { drivers: drivers(new FakeClock(1_000)), processRunner: runner, @@ -317,7 +320,7 @@ describe("startDaemon with the agent-device edge", () => { const setup = await setUp({ capabilities: { "agent-device": { command, enabled: true, ios: { [key]: value } } }, }); - const runner = versionAndDaemon(setup.directory, "phones"); + const runner = versionAndDaemon(setup.home, "phones"); const clock = new FakeClock(1_000); await startEdge(setup, { clock, @@ -332,7 +335,7 @@ describe("startDaemon with the agent-device edge", () => { expect(runner.calls[3]?.args).toEqual([ entry, - `--simlock-home=${setup.directory}`, + `--simlock-home=${setup.home}`, "--simlock-role=phones", ]); expect(runner.calls[3]?.options.env?.[envName]).toBe(value); @@ -408,7 +411,7 @@ describe("startDaemon with the agent-device edge", () => { const { started } = await startOnFreePort(async (port) => { const setup = await setUp(config(port), { record: { pid: 900 } }); const runner = new ScriptedProcessRunner([]); - const processSupervisor = recordedDaemonAlive(setup.directory); + const processSupervisor = recordedDaemonAlive(setup.home); const { clock } = await startEdge(setup, { ...(drivers === undefined ? {} : { drivers: [...drivers] }), processRunner: runner, @@ -473,7 +476,7 @@ describe("startDaemon with the agent-device edge", () => { const on = await setUp({ capabilities: { "agent-device": { command, enabled: true } } }); await startEdge(on, { agentDevice: spying, - processRunner: versionAndDaemon(on.directory), + processRunner: versionAndDaemon(on.home), processSupervisor: new FakeProcessSupervisor(), }); expect(loads).toBe(1); @@ -490,7 +493,7 @@ describe("startDaemon with the agent-device edge", () => { { directory: first.directory, record: { pid: 900 } }, ); const runner = new ScriptedProcessRunner([]); - const processSupervisor = recordedDaemonAlive(second.directory); + const processSupervisor = recordedDaemonAlive(second.home); const clock = new FakeClock(1_000); await expect( @@ -568,7 +571,7 @@ describe("startDaemon with the agent-device edge", () => { version(simulator === "running" ? "0.21.28\n" : simulator), { hangs: true, - match: { args: [entry, `--simlock-home=${setup.directory}`], command: process.execPath }, + match: { args: [entry, `--simlock-home=${setup.home}`], command: process.execPath }, onSpawn: async () => { await setup.filesystem.writeFileAtomic( join(setup.directory, "agent-device", "daemon.json"), @@ -723,7 +726,7 @@ describe("startDaemon with the agent-device edge", () => { it("reports no module-unavailable finding while agent-device's /health never answers and the readiness budget has not run out", async () => { const setup = await setUp({ capabilities: { "agent-device": { command, enabled: true } } }); - const runner = versionAndDaemon(setup.directory); + const runner = versionAndDaemon(setup.home); const { daemon } = await startEdge(setup, { processRunner: runner, processSupervisor: new FakeProcessSupervisor(), diff --git a/src/daemon/main-history.test.ts b/src/daemon/main-history.test.ts index 6034f28b1..53a82c3f7 100644 --- a/src/daemon/main-history.test.ts +++ b/src/daemon/main-history.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { seedHistory } from "../history/testing.js"; import { start, stopDaemons, temporaryDirectories, writeModule } from "./test-main.js"; +import { resolveDaemonSocketPath } from "../ports/index.js"; afterEach(stopDaemons); @@ -67,7 +68,7 @@ describe("startDaemon event history", () => { temporaryDirectories.push(winner, loser); const junk = "this is not a sqlite database ".repeat(20); await writeFile(join(loser, "history.db"), junk); - const socketPath = join(winner, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(winner); await start({ dataDirectory: winner, socketPath }); const outcome = await start({ dataDirectory: loser, socketPath }).then( diff --git a/src/daemon/main-host-load.test.ts b/src/daemon/main-host-load.test.ts index dcba0a8f2..e0b3e97c2 100644 --- a/src/daemon/main-host-load.test.ts +++ b/src/daemon/main-host-load.test.ts @@ -14,6 +14,7 @@ import { JsonLinesLogger, MemoryFilesystem, MemoryLogSink, + resolveDaemonSocketPath, } from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import type { DaemonServer } from "./server.js"; @@ -91,7 +92,7 @@ describe("startDaemon host load", () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-load-slow-")); temporaryDirectories.push(directory); const clock = new FakeClock(1_000); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const startPromise = startDaemon({ clock, configOverrides: STANDALONE_OFF, @@ -210,7 +211,7 @@ describe("startDaemon host load", () => { it("starts the sampler only after the daemon holds its socket", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-load-socket-")); temporaryDirectories.push(directory); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const socketAtRead: boolean[] = []; class WatchingProbe extends FakeHostLoadProbe { override read(): Promise { @@ -250,7 +251,7 @@ describe("startDaemon host load", () => { deviceDataTables: fakeDeviceDataTables, filesystem: new SecretRefusingFilesystem(), hostLoadProbe, - socketPath: join(directory, "daemon.sock"), + socketPath: resolveDaemonSocketPath(directory), version: "1.2.3", } as StartDaemonOptions), ).rejects.toThrow("disk is read-only"); diff --git a/src/daemon/main-start-daemon.test.ts b/src/daemon/main-start-daemon.test.ts index e4afb5e99..dedb7a6eb 100644 --- a/src/daemon/main-start-daemon.test.ts +++ b/src/daemon/main-start-daemon.test.ts @@ -386,9 +386,11 @@ describe("startDaemon", () => { uninstall: async () => undefined, start: async () => undefined, }; + // why: the service name is the plain one when the root is `join(home, ".simlock")`, which is `\` on Windows. + const root = join("/Users/me", ".simlock"); const host = { manager, - root: "/Users/me/.simlock", + root, home: "/Users/me", nodePath: "/gone/node", mainPath: "/gone/main.js", @@ -402,8 +404,8 @@ describe("startDaemon", () => { expect(seen).toEqual([ serviceDefinition({ role: "worker", - root: "/Users/me/.simlock", - dataDirectory: daemonDataDirectory("/Users/me/.simlock", "worker"), + root, + dataDirectory: daemonDataDirectory(root, "worker"), home: "/Users/me", nodePath: "/gone/node", mainPath: "/gone/main.js", @@ -443,11 +445,11 @@ describe("startDaemon", () => { ...host, manager: { ...manager, manager: "systemd" }, home: "/home/me", - root: "/home/me/.simlock", + root: join("/home/me", ".simlock"), }); await systemd.serviceCheck?.check(); expect(seen.at(-1)?.path).toBe( - "/home/me/.config/systemd/user/com.callstack.simlock.worker.service", + join("/home/me", ".config", "systemd", "user", "com.callstack.simlock.worker.service"), ); }); diff --git a/src/daemon/main-stop.test.ts b/src/daemon/main-stop.test.ts index 0662b780e..6a74a3740 100644 --- a/src/daemon/main-stop.test.ts +++ b/src/daemon/main-stop.test.ts @@ -22,6 +22,7 @@ import { MemoryLogSink, NodeSqliteOpener, NoopLogger, + resolveDaemonSocketPath, } from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import { @@ -47,7 +48,7 @@ describe("startDaemon stopped while starting", () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-stop-")); temporaryDirectories.push(directory); const clock = new FakeClock(1_000); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const filesystem = new MemoryFilesystem(); const startPromise = startDaemon({ clock, @@ -542,7 +543,7 @@ describe("startDaemon HTTP gateway stop-during-start race (review finding S5)", const sink = new MemoryLogSink(); const logger = new JsonLinesLogger({ clock, level: "debug", sink }); const filesystem = new MemoryFilesystem(); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const restoreListen = delayTcpListen(200); try { diff --git a/src/daemon/main-update.test.ts b/src/daemon/main-update.test.ts index b87c8ef40..544ad0170 100644 --- a/src/daemon/main-update.test.ts +++ b/src/daemon/main-update.test.ts @@ -17,6 +17,7 @@ import { MemoryIpcTransport, MemoryLogSink, NoopLogger, + resolveDaemonSocketPath, } from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import type { DaemonServer } from "./server.js"; @@ -104,7 +105,7 @@ describe("startDaemon version check", () => { logger: new NoopLogger(), npm, role, - socketPath: join(directory, "daemon.sock"), + socketPath: resolveDaemonSocketPath(directory), version: "0.3.0", } as StartDaemonOptions), ).rejects.toThrow(refused === "listen" ? "listen EACCES" : "disk is read-only"); @@ -163,7 +164,7 @@ describe("startDaemon version check", () => { ipc: new ListenFailingTransport(code), logger: new NoopLogger(), npm: new FakeNpmCli({ view: [{ ok: true, output: "0.3.0\n" }] }), - socketPath: join(directory, "daemon.sock"), + socketPath: resolveDaemonSocketPath(directory), version: "0.3.0", } as StartDaemonOptions).then( () => undefined, @@ -204,7 +205,7 @@ describe("startDaemon version check", () => { const clock = new FakeClock(1_000); const sink = new MemoryLogSink(); const ipc = new MemoryIpcTransport(); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const disposed: string[] = []; const driver = Object.assign( new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), diff --git a/src/daemon/main-worker-lock.test.ts b/src/daemon/main-worker-lock.test.ts index 77972972c..3f2a670d0 100644 --- a/src/daemon/main-worker-lock.test.ts +++ b/src/daemon/main-worker-lock.test.ts @@ -10,6 +10,7 @@ import { MemoryFilesystem, ScriptedProcessRunner, } from "../ports/index.js"; +import { binaries } from "../drivers/android/testing.js"; import { type StartDaemonOptions } from "./main.js"; import { start, @@ -40,14 +41,9 @@ describe("startDaemon worker lock", () => { async function installAndroidSdk(filesystem: MemoryFilesystem): Promise { vi.stubEnv("ANDROID_HOME", "/android-sdk"); - for (const binary of [ - "platform-tools/adb", - "emulator/emulator", - "cmdline-tools/latest/bin/avdmanager", - "cmdline-tools/latest/bin/sdkmanager", - ]) { - await filesystem.mkdirp(dirname(join("/android-sdk", binary))); - await filesystem.writeFileAtomic(join("/android-sdk", binary), "binary"); + for (const binary of Object.values(binaries)) { + await filesystem.mkdirp(dirname(binary)); + await filesystem.writeFileAtomic(binary, "binary"); } } @@ -192,7 +188,7 @@ describe("startDaemon worker lock", () => { JSON.stringify({ pid: 4343, port: 5038, startedAt: 1 }), ); const supervisor = new FakeProcessSupervisor([4242, 4343]); - supervisor.answerCommandLine(4343, "/android-sdk/platform-tools/adb -P 5038 nodaemon server"); + supervisor.answerCommandLine(4343, `${binaries.adb} -P 5038 nodaemon server`); const lockAtDisposal: Promise[] = []; const signal = supervisor.signal.bind(supervisor); supervisor.signal = (pid, kill) => { diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 9a8f5b242..2c3a414d7 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -15,6 +15,7 @@ import { MemoryFilesystem, MemoryLogSink, NodeFilesystem, + resolveDaemonSocketPath, } from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import { parseDaemonArgv } from "./entry-support.js"; @@ -169,86 +170,98 @@ describe("interrupted root assembly", () => { expect(await filesystem.exists(theirs)).toBe(true); }); - it("startup leaves a dead writer's leftover that another user owns", async () => { - const filesystem = new MemoryFilesystem(); - const devices = join(SIMLOCK_HOME, "devices"); - await filesystem.mkdirp(devices); - const foreign = await stage(filesystem, devices, ".ios.41005.root-id.staging"); - filesystem.defineAttributes(foreign, { uid: (process.getuid?.() ?? 0) + 1 }); + // why: Windows has no `getuid`, so no file there belongs to another user by id. + it.skipIf(process.platform === "win32")( + "startup leaves a dead writer's leftover that another user owns", + async () => { + const filesystem = new MemoryFilesystem(); + const devices = join(SIMLOCK_HOME, "devices"); + await filesystem.mkdirp(devices); + const foreign = await stage(filesystem, devices, ".ios.41005.root-id.staging"); + filesystem.defineAttributes(foreign, { uid: (process.getuid?.() ?? 0) + 1 }); - await startWithRoot(filesystem, new FakeProcessSupervisor()); + await startWithRoot(filesystem, new FakeProcessSupervisor()); - expect(await filesystem.exists(foreign)).toBe(true); - }); + expect(await filesystem.exists(foreign)).toBe(true); + }, + ); }); describe("the data directory", () => { - it("creates a missing data directory owner-only, and for one other users can reach logs one warning at start and leaves its mode", async () => { - // why: under the umask every real host starts from, a directory made without a mode comes - // out 0755, so only the daemon asking for 0700 ends there. - const previousUmask = process.umask(0o022); - try { - const base = await mkdtemp(join(tmpdir(), "simlock-dd-")); - temporaryDirectories.push(base); - const cases = [ - { name: "new", existing: undefined, mode: 0o700, warned: undefined }, - { name: "700", existing: 0o700, mode: 0o700, warned: undefined }, - { name: "750", existing: 0o750, mode: 0o750, warned: "750" }, - { name: "755", existing: 0o755, mode: 0o755, warned: "755" }, - ]; - - for (const testCase of cases) { - const dataDirectory = join(base, testCase.name); - if (testCase.existing !== undefined) { - await mkdir(dataDirectory); - await chmod(dataDirectory, testCase.existing); - } - - const { sink } = await start({ dataDirectory, filesystem: new NodeFilesystem() }); - - expect( - { - mode: (await stat(dataDirectory)).mode & 0o777, - warnings: sink.records - .filter((record) => record.message.startsWith("data directory")) - .map((record) => [record.level, record.message]), - }, - testCase.name, - ).toEqual({ - mode: testCase.mode, - warnings: - testCase.warned === undefined - ? [] - : [ - [ - "warn", - `data directory ${dataDirectory} is accessible to other users (mode ${testCase.warned}); run chmod 700 ${dataDirectory}`, + // why: a POSIX mode and umask have no Windows counterpart. + it.skipIf(process.platform === "win32")( + "creates a missing data directory owner-only, and for one other users can reach logs one warning at start and leaves its mode", + async () => { + // why: under the umask every real host starts from, a directory made without a mode comes + // out 0755, so only the daemon asking for 0700 ends there. + const previousUmask = process.umask(0o022); + try { + const base = await mkdtemp(join(tmpdir(), "simlock-dd-")); + temporaryDirectories.push(base); + const cases = [ + { name: "new", existing: undefined, mode: 0o700, warned: undefined }, + { name: "700", existing: 0o700, mode: 0o700, warned: undefined }, + { name: "750", existing: 0o750, mode: 0o750, warned: "750" }, + { name: "755", existing: 0o755, mode: 0o755, warned: "755" }, + ]; + + for (const testCase of cases) { + const dataDirectory = join(base, testCase.name); + if (testCase.existing !== undefined) { + await mkdir(dataDirectory); + await chmod(dataDirectory, testCase.existing); + } + + const { sink } = await start({ dataDirectory, filesystem: new NodeFilesystem() }); + + expect( + { + mode: (await stat(dataDirectory)).mode & 0o777, + warnings: sink.records + .filter((record) => record.message.startsWith("data directory")) + .map((record) => [record.level, record.message]), + }, + testCase.name, + ).toEqual({ + mode: testCase.mode, + warnings: + testCase.warned === undefined + ? [] + : [ + [ + "warn", + `data directory ${dataDirectory} is accessible to other users (mode ${testCase.warned}); run chmod 700 ${dataDirectory}`, + ], ], - ], - }); + }); + } + } finally { + process.umask(previousUmask); } - } finally { - process.umask(previousUmask); - } - }); + }, + ); }); describe("the data directory", () => { - it("makes the parent of a gateway's data directory owner-only too when it creates it", async () => { - // why: a gateway started first creates ``, which is the worker's data directory later. - const previousUmask = process.umask(0o022); - try { - const root = join(await mkdtemp(join(tmpdir(), "simlock-dd-")), "home"); - temporaryDirectories.push(join(root, "..")); - - await start({ dataDirectory: join(root, "gateway"), filesystem: new NodeFilesystem() }); - - expect((await stat(root)).mode & 0o777).toBe(0o700); - expect((await stat(join(root, "gateway"))).mode & 0o777).toBe(0o700); - } finally { - process.umask(previousUmask); - } - }); + // why: a POSIX mode and umask have no Windows counterpart. + it.skipIf(process.platform === "win32")( + "makes the parent of a gateway's data directory owner-only too when it creates it", + async () => { + // why: a gateway started first creates ``, which is the worker's data directory later. + const previousUmask = process.umask(0o022); + try { + const root = join(await mkdtemp(join(tmpdir(), "simlock-dd-")), "home"); + temporaryDirectories.push(join(root, "..")); + + await start({ dataDirectory: join(root, "gateway"), filesystem: new NodeFilesystem() }); + + expect((await stat(root)).mode & 0o777).toBe(0o700); + expect((await stat(join(root, "gateway"))).mode & 0o777).toBe(0o700); + } finally { + process.umask(previousUmask); + } + }, + ); }); describe("the version a daemon reports", () => { @@ -256,7 +269,7 @@ describe("the version a daemon reports", () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-")); temporaryDirectories.push(directory); const clock = new FakeClock(1_000); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const daemon = await startDaemon({ configOverrides: STANDALONE_OFF, deviceDataTables: fakeDeviceDataTables, @@ -291,7 +304,7 @@ describe("startDaemon startup readiness", () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-slow-")); temporaryDirectories.push(directory); const clock = new FakeClock(1_000); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const startPromise = startDaemon({ clock, configOverrides: STANDALONE_OFF, diff --git a/src/daemon/optional-modules-start.test.ts b/src/daemon/optional-modules-start.test.ts index 8b7ca278a..e59c162bf 100644 --- a/src/daemon/optional-modules-start.test.ts +++ b/src/daemon/optional-modules-start.test.ts @@ -13,6 +13,7 @@ import { JsonLinesLogger, MemoryFilesystem, MemoryLogSink, + resolveDaemonSocketPath, } from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import type { DaemonServer } from "./server.js"; @@ -204,7 +205,7 @@ describe("optional modules: afterSocketClaimed", () => { ), on: ["alpha"], }); - socketPath = join(prepared.directory, "daemon.sock"); + socketPath = resolveDaemonSocketPath(prepared.directory); const started = await settleWithin(startDaemon(prepared.startOptions), 5_000); if (started.state === "fulfilled") daemons.push(started.value); diff --git a/src/daemon/remote-client.e2e.test.ts b/src/daemon/remote-client.e2e.test.ts index 3d8d6f2d7..344f578a8 100644 --- a/src/daemon/remote-client.e2e.test.ts +++ b/src/daemon/remote-client.e2e.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -11,6 +11,7 @@ import { startOnFreePort } from "../test-support/loopback-port.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; import type { DaemonServer } from "./server.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; const admin: DispatchSession = { manageEventSubscription: () => undefined, @@ -25,9 +26,7 @@ describe("the typed client over a worker's session path", () => { afterEach(async () => { await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); - await Promise.all( - directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), - ); + await Promise.all(directories.splice(0).map((directory) => removeDirectory(directory))); }); it("connectSimlock with a URL and a token reaches a worker with fake drivers over its real session path: it leases, renews, releases and hears lease-lost", async () => { diff --git a/src/daemon/server-claim-and-stop.test.ts b/src/daemon/server-claim-and-stop.test.ts index 951beb1ee..f766aeed5 100644 --- a/src/daemon/server-claim-and-stop.test.ts +++ b/src/daemon/server-claim-and-stop.test.ts @@ -7,6 +7,7 @@ import { MemoryFilesystem, NodeFilesystem, NodeIpcTransport, + resolveDaemonSocketPath, } from "../ports/index.js"; import type { DaemonServer } from "./server.js"; import { DaemonEndpointHost } from "./connection-host.js"; @@ -27,8 +28,10 @@ describe("DaemonServer", () => { it("recovers a stale socket file and refuses a second live daemon before running any device work", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-stale-")); temporaryDirectories.push(directory); - const socketPath = join(directory, "daemon.sock"); - await new NodeFilesystem().writeFileAtomic(socketPath, "stale"); + const socketPath = resolveDaemonSocketPath(directory); + // why: a stale socket file is a POSIX fact; a Windows pipe leaves nothing behind. + if (process.platform !== "win32") + await new NodeFilesystem().writeFileAtomic(socketPath, "stale"); const first = await createHarness({ socketPath }); let convergeCalls = 0; const second = await createHarness({ @@ -65,8 +68,10 @@ describe("DaemonServer", () => { it("never touches admin.token on the daemon instance that loses the start race", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-stale-admin-")); temporaryDirectories.push(directory); - const socketPath = join(directory, "daemon.sock"); - await new NodeFilesystem().writeFileAtomic(socketPath, "stale"); + const socketPath = resolveDaemonSocketPath(directory); + // why: a stale socket file is a POSIX fact; a Windows pipe leaves nothing behind. + if (process.platform !== "win32") + await new NodeFilesystem().writeFileAtomic(socketPath, "stale"); const secrets = new CryptoTokenSecrets(); const winnerFilesystem = new MemoryFilesystem(); @@ -98,7 +103,7 @@ describe("DaemonServer", () => { async (removalFails) => { const directory = await mkdtemp(join(tmpdir(), "simlock-admin-restart-")); temporaryDirectories.push(directory); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const filesystem = new MemoryFilesystem(); const secrets = new CryptoTokenSecrets(); const oldSecret = await adminAuth(filesystem, secrets); @@ -171,7 +176,10 @@ describe("DaemonServer", () => { expect(harness.state.database.prepare("SELECT id FROM leases").all()).toEqual([ { id: leaseId }, ]); - expect(harness.eventBus.replay().map((event) => event.event)).toContain("daemon.stopping"); + // why: the server answers `daemon.stop` before it starts stopping, so the fact follows the reply. + await vi.waitFor(() => + expect(harness.eventBus.replay().map((event) => event.event)).toContain("daemon.stopping"), + ); expect(harness.eventBus.replay().map((event) => event.event)).not.toContain("lease.released"); }); }); diff --git a/src/daemon/server-pushes-gateway.test.ts b/src/daemon/server-pushes-gateway.test.ts index ecd6fe7ce..2557817b2 100644 --- a/src/daemon/server-pushes-gateway.test.ts +++ b/src/daemon/server-pushes-gateway.test.ts @@ -5,7 +5,13 @@ import { afterEach, describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; import { testConfig } from "../core/testing.js"; import { FleetLeaseIndex, GatewayOwnerRoutedFacts } from "../gateway/index.js"; -import { FakeClock, NodeFilesystem, NodeIpcTransport, NoopLogger } from "../ports/index.js"; +import { + FakeClock, + NodeFilesystem, + NodeIpcTransport, + NoopLogger, + resolveDaemonSocketPath, +} from "../ports/index.js"; import { DaemonEndpointHost } from "./connection-host.js"; import type { ContractDispatcher } from "./dispatch.js"; import { DaemonServer } from "./server.js"; @@ -62,7 +68,7 @@ async function gatewayHarness() { return { leaseIds: released.map((entry) => entry.gatewayLeaseId), requestIds: [] }; }, } as unknown as ContractDispatcher; - const socketPath = join(directory, "gateway.sock"); + const socketPath = resolveDaemonSocketPath(directory); const daemon = new DaemonServer({ clock, config: testConfig({}, "gateway"), diff --git a/src/daemon/server-startup.test.ts b/src/daemon/server-startup.test.ts index 33c2487ee..de6a47f38 100644 --- a/src/daemon/server-startup.test.ts +++ b/src/daemon/server-startup.test.ts @@ -10,6 +10,7 @@ import { FakeUpdaterLauncher, NodeFilesystem, NodeIpcTransport, + resolveDaemonSocketPath, } from "../ports/index.js"; import { DAEMON_PROTOCOL_VERSION } from "../daemon-protocol/index.js"; import { DaemonEndpointHost, type ConnectionHost } from "./connection-host.js"; @@ -638,7 +639,7 @@ describe("DaemonServer failed start release", () => { it("closes a connection opened after the connections were closed, while the endpoint release still holds", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-daemon-")); temporaryDirectories.push(directory); - const socketPath = join(directory, "daemon.sock"); + const socketPath = resolveDaemonSocketPath(directory); const real = new DaemonEndpointHost({ connector: new NodeIpcTransport(), endpoint: socketPath, diff --git a/src/daemon/server-update.test.ts b/src/daemon/server-update.test.ts index 0b61d1407..f8bb7646c 100644 --- a/src/daemon/server-update.test.ts +++ b/src/daemon/server-update.test.ts @@ -1,5 +1,5 @@ import { writeFile } from "node:fs/promises"; -import { dirname, join } from "node:path"; +import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; import { @@ -104,7 +104,7 @@ describe("daemon.update", () => { expect(idle.npm.calls[0]).toEqual({ method: "view", spec: "simlock@latest" }); expect(idle.launcher.launches).toEqual([ { - entry: "/opt/simlock/dist/updater/main.js", + entry: join("/opt/simlock", "dist", "updater", "main.js"), from: "0.3.0", to: "0.4.0", role: "worker", @@ -249,7 +249,7 @@ describe("daemon.update", () => { }); await client.close(); - const dataDirectory = dirname(admin.socketPath); + const dataDirectory = admin.directory as string; await writeFile(join(dataDirectory, "admin.token"), "token\n"); const probe = createDaemonProbe({ dataDirectory, filesystem: new NodeFilesystem() }); await expect(probe.state()).resolves.toEqual({ health: "running", version: "0.3.0" }); diff --git a/src/daemon/session-path.e2e.test.ts b/src/daemon/session-path.e2e.test.ts index 4e548cf85..4e9e30d73 100644 --- a/src/daemon/session-path.e2e.test.ts +++ b/src/daemon/session-path.e2e.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp } from "node:fs/promises"; import { createServer as createHttpServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; @@ -15,6 +15,7 @@ import { startOnFreePort } from "../test-support/loopback-port.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; import type { DaemonServer } from "./server.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; const admin: DispatchSession = { manageEventSubscription: () => undefined, @@ -145,9 +146,7 @@ describe("the session path", () => { await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); clearInterval(pump); pumped = undefined; - await Promise.all( - directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), - ); + await Promise.all(directories.splice(0).map((directory) => removeDirectory(directory))); }); async function keyServer(key: TestKey): Promise { diff --git a/src/daemon/test-main.ts b/src/daemon/test-main.ts index 840887b6e..d8b5cac3d 100644 --- a/src/daemon/test-main.ts +++ b/src/daemon/test-main.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { connect } from "node:net"; @@ -13,6 +13,7 @@ import { import { startDaemon, type StartDaemonOptions } from "./main.js"; import { startOnFreePort } from "../test-support/loopback-port.js"; import type { DaemonServer } from "./server.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; export const runningDaemons: DaemonServer[] = []; @@ -212,7 +213,5 @@ export async function startGateway( export async function stopDaemons(): Promise { await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test"))); - await Promise.all( - temporaryDirectories.splice(0).map((path) => rm(path, { force: true, recursive: true })), - ); + await Promise.all(temporaryDirectories.splice(0).map((path) => removeDirectory(path))); } diff --git a/src/daemon/test-optional-modules.ts b/src/daemon/test-optional-modules.ts index 4b66da9f1..5143a6640 100644 --- a/src/daemon/test-optional-modules.ts +++ b/src/daemon/test-optional-modules.ts @@ -6,7 +6,13 @@ import { startOnFreePort } from "../test-support/loopback-port.js"; import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import type { OptionalModuleDefinition } from "../modules/index.js"; import { type FakeModule } from "../modules/testing.js"; -import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { + FakeClock, + JsonLinesLogger, + MemoryFilesystem, + MemoryLogSink, + resolveDaemonSocketPath, +} from "../ports/index.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import type { DaemonServer } from "./server.js"; @@ -120,7 +126,7 @@ export async function prepare(options: RigOptions, port?: number) { hostLoadProbe: null, logger: new JsonLinesLogger({ clock, level: "debug", sink }), optionalModules: options.modules, - socketPath: join(directory, "daemon.sock"), + socketPath: resolveDaemonSocketPath(directory), deviceDataTables: fakeDeviceDataTables, version: "1.2.3", ...options.extra, diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index a27722fb6..0e571f18f 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -1,5 +1,5 @@ import { createCipheriv, createHash } from "node:crypto"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp } from "node:fs/promises"; import { connect, createServer, type AddressInfo, type Socket } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -23,6 +23,7 @@ import type { RelayTarget, RelayTargets, TwoWayRelayTarget } from "./relay.js"; import type { DaemonServer } from "./server.js"; import { startOnFreePort } from "../test-support/loopback-port.js"; import { SimlockWire, type CallHooks, type RelayHead } from "../simlock-client/wire.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; export const MIB = 1024 * 1024; export const KIB = 1024; @@ -287,9 +288,7 @@ export async function openRelay( export async function cleanUp(daemons: DaemonServer[], directories: string[]): Promise { await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); - await Promise.all( - directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), - ); + await Promise.all(directories.splice(0).map((directory) => removeDirectory(directory))); } export function gate(): { readonly promise: Promise; readonly open: () => void } { diff --git a/src/daemon/test-server.ts b/src/daemon/test-server.ts index 803ec3226..827943323 100644 --- a/src/daemon/test-server.ts +++ b/src/daemon/test-server.ts @@ -1,6 +1,6 @@ import { testLeaseFiles } from "./test-lease-files.js"; import { testConfig as configWithDefaults } from "../core/testing.js"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { Socket, connect } from "node:net"; @@ -40,6 +40,7 @@ import { type ProcessStreamOptions, type StreamingProcessHandle, type StreamingProcessResult, + resolveDaemonSocketPath, } from "../ports/index.js"; import { DAEMON_PROTOCOL_VERSION } from "../daemon-protocol/index.js"; import { DaemonEndpointHost, type ConnectionHost } from "./connection-host.js"; @@ -51,6 +52,7 @@ import { createUpdateCoordinator } from "./update-coordinator.js"; import type { RelayTargets } from "./relay.js"; import { type PhysicalDeviceWatcher } from "../leasing/index.js"; import { createTestEngine } from "../leasing/testing.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; const gibibyte = 1024 ** 3; @@ -86,9 +88,7 @@ const usageRigs: UsageRig[] = []; export async function stopTestDaemons(): Promise { await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test"))); - await Promise.all( - temporaryDirectories.splice(0).map((path) => rm(path, { force: true, recursive: true })), - ); + await Promise.all(temporaryDirectories.splice(0).map((path) => removeDirectory(path))); await Promise.all(usageRigs.splice(0).map((rig) => rig.close())); await removeUsageRigs(); } @@ -211,7 +211,7 @@ export async function createHarness( if (directory !== undefined) { temporaryDirectories.push(directory); } - const socketPath = options.socketPath ?? join(directory as string, "daemon.sock"); + const socketPath = options.socketPath ?? resolveDaemonSocketPath(directory as string); const clock = options.clock ?? new FakeClock(1_000); const eventBus = new EventBus(clock); const state = options.state ?? (await openTestState()); @@ -244,7 +244,7 @@ export async function createHarness( ? new MemoryFilesystem() : new (class extends MemoryFilesystem { override async readFile(...args: Parameters) { - if (args[0] === "/data/update-result.json") { + if (args[0].replaceAll("\\", "/") === "/data/update-result.json") { await resultFileGate; if (unreadable !== undefined) throw unreadable; } @@ -365,6 +365,7 @@ export async function createHarness( clock, config, daemon, + directory, driver, engine, eventBus, diff --git a/src/gateway/boundary.test.ts b/src/gateway/boundary.test.ts index fadc92f09..b6ed5d813 100644 --- a/src/gateway/boundary.test.ts +++ b/src/gateway/boundary.test.ts @@ -31,9 +31,11 @@ describe("the one daemon module the gateway imports", () => { describe("the relay is the bus's only republisher", () => { it("only the gateway's worker link calls republish", () => { const callers = sourceFilesRecursive(srcDir) - .filter((file) => !/(^|\/)(testing|test-[^/]+)\.ts$/.test(file)) - .filter((file) => /\.republish\s*[<(]/.test(stripComments(readFileSync(file, "utf8")))) - .map((file) => relative(srcDir, file)); + // why: `relative` joins with `\` on Windows, and this list is compared with `/` paths. + .map((file) => ({ file, name: relative(srcDir, file).replaceAll("\\", "/") })) + .filter(({ name }) => !/(^|\/)(testing|test-[^/]+)\.ts$/.test(name)) + .filter(({ file }) => /\.republish\s*[<(]/.test(stripComments(readFileSync(file, "utf8")))) + .map(({ name }) => name); expect(callers).toEqual(["gateway/worker-link.ts"]); }); diff --git a/src/history/history.test.ts b/src/history/history.test.ts index 149c5dbba..529cadf93 100644 --- a/src/history/history.test.ts +++ b/src/history/history.test.ts @@ -24,33 +24,37 @@ afterEach(async () => { }); describe("createEventHistory", () => { - it("creates history.db and its -wal and -shm files owner-only, mode 0o600", async () => { - // why: #685 made the event store owner-only; a 022 umask would hide a 0644 default. - const previousUmask = process.umask(0o022); - try { - const rigged = await rig(); - const history = rigged.history(); - await history.start(); - stopping(rigged.bus, "mode"); - await history.replay({ sinceTs: 0 }); - const modes = Object.fromEntries( - await Promise.all( - ["", "-wal", "-shm"].map( - async (suffix) => - [`history.db${suffix}`, (await stat(rigged.dbPath + suffix)).mode & 0o777] as const, + // why: Windows has no owner-only file mode. + it.skipIf(process.platform === "win32")( + "creates history.db and its -wal and -shm files owner-only, mode 0o600", + async () => { + // why: #685 made the event store owner-only; a 022 umask would hide a 0644 default. + const previousUmask = process.umask(0o022); + try { + const rigged = await rig(); + const history = rigged.history(); + await history.start(); + stopping(rigged.bus, "mode"); + await history.replay({ sinceTs: 0 }); + const modes = Object.fromEntries( + await Promise.all( + ["", "-wal", "-shm"].map( + async (suffix) => + [`history.db${suffix}`, (await stat(rigged.dbPath + suffix)).mode & 0o777] as const, + ), ), - ), - ); - await history.stop(); - expect(modes).toEqual({ - "history.db": 0o600, - "history.db-shm": 0o600, - "history.db-wal": 0o600, - }); - } finally { - process.umask(previousUmask); - } - }); + ); + await history.stop(); + expect(modes).toEqual({ + "history.db": 0o600, + "history.db-shm": 0o600, + "history.db-wal": 0o600, + }); + } finally { + process.umask(previousUmask); + } + }, + ); it("writes every emitted and every republished event as one row equal to its envelope, read back in timestamp, then seq order", async () => { const rigged = await rig({ capacity: 2 }); diff --git a/src/history/testing.ts b/src/history/testing.ts index 6dd1d92b3..f8e487ed9 100644 --- a/src/history/testing.ts +++ b/src/history/testing.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -23,6 +23,7 @@ import { openHistoryReader, type ProjectionHandle, } from "./index.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; export function plainProjection( name: string, @@ -174,11 +175,12 @@ export const DAY = 24 * HOUR; export const T0 = 1_760_605_920_000; const directories: string[] = []; +const openRigs: EventHistoryHandle[] = []; export async function removeUsageRigs(): Promise { - await Promise.all( - directories.splice(0).map((path) => rm(path, { force: true, recursive: true })), - ); + // why: Windows refuses to delete a database file that is still open. + await Promise.all(openRigs.splice(0).map((history) => history.stop())); + await Promise.all(directories.splice(0).map((path) => removeDirectory(path))); } export interface UsageRig { @@ -223,6 +225,7 @@ export async function usageRig(options: UsageRigOptions = {}): Promise projections: options.projections ?? Object.values(HISTORY_PROJECTIONS), sqlite: new NodeSqliteOpener(), }); + openRigs.push(history); await history.start(); const historyPath = join(directory, HISTORY_DB_NAME); let relayed = 0; diff --git a/src/mcp/main.test.ts b/src/mcp/main.test.ts index 51a1af54c..8496b743f 100644 --- a/src/mcp/main.test.ts +++ b/src/mcp/main.test.ts @@ -16,6 +16,7 @@ import { NodeDaemonLauncher, MemoryFilesystem, MemoryIpcTransport, + resolveDaemonSocketPath, } from "../ports/index.js"; import { FakeSimlockClient, sampleGrant } from "./test-support.js"; import { startMcpStdio, type McpTransport } from "./main.js"; @@ -204,7 +205,7 @@ describe("MCP stdio lifecycle", () => { await vi.waitFor(() => expect(connectToRunningDaemon).toHaveBeenCalledTimes(1)); expect(connectToRunningDaemon.mock.calls[0]?.[0]).toMatchObject({ - socketPath: join(root, "gateway", "daemon.sock"), + socketPath: resolveDaemonSocketPath(join(root, "gateway")), }); await mcpClient.close(); await runner.shutdown(); diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 984aebac0..70a8266a8 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it, vi } from "vitest"; import { spawn } from "node:child_process"; -import { fileURLToPath } from "node:url"; import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -55,60 +54,68 @@ describe("NodeDaemonLauncher", () => { } }); - it("creates the daemon log it hands the child, and the data directory it lives in, 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 -- and on - // a fresh machine the launch creates the data directory too. 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, "home", "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"); + // why: Windows has no owner-only file mode. + it.skipIf(process.platform === "win32")( + "creates the daemon log it hands the child, and the data directory it lives in, 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 -- and on + // a fresh machine the launch creates the data directory too. 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, "home", "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); - expect((await stat(join(directory, "home"))).mode & 0o777).toBe(0o700); - } finally { - process.umask(previousUmask); - await rm(directory, { force: true, recursive: true }); - } - }); + expect((await stat(logPath)).mode & 0o777).toBe(0o600); + expect((await stat(join(directory, "home"))).mode & 0o777).toBe(0o700); + } finally { + process.umask(previousUmask); + await rm(directory, { force: true, recursive: true }); + } + }, + ); - it("creates SIMLOCK_HOME 0700 under umask 002, and leaves an existing one's mode", async () => { - const previousUmask = process.umask(0o002); - const root = await mkdtemp(join(tmpdir(), "simlock-launcher-")); - try { - const modes: Record = {}; - for (const [name, existing] of [ - ["created", undefined], - ["existing", 0o775], - ] as const) { - const home = join(root, name); - if (existing !== undefined) { - await mkdir(home); - await chmod(home, existing); + // why: Windows has no directory modes or umask. + it.skipIf(process.platform === "win32")( + "creates SIMLOCK_HOME 0700 under umask 002, and leaves an existing one's mode", + async () => { + const previousUmask = process.umask(0o002); + const root = await mkdtemp(join(tmpdir(), "simlock-launcher-")); + try { + const modes: Record = {}; + for (const [name, existing] of [ + ["created", undefined], + ["existing", 0o775], + ] as const) { + const home = join(root, name); + if (existing !== undefined) { + await mkdir(home); + await chmod(home, existing); + } + await new NodeDaemonLauncher({ + args: ["-e", "0"], + command: process.execPath, + logPath: join(home, "gateway", "daemon.log"), + simlockHome: home, + }).launch(); + modes[name] = (await stat(home)).mode & 0o777; } - await new NodeDaemonLauncher({ - args: ["-e", "0"], - command: process.execPath, - logPath: join(home, "gateway", "daemon.log"), - simlockHome: home, - }).launch(); - modes[name] = (await stat(home)).mode & 0o777; + expect(modes).toEqual({ created: 0o700, existing: 0o775 }); + } finally { + process.umask(previousUmask); + await rm(root, { force: true, recursive: true }); } - expect(modes).toEqual({ created: 0o700, existing: 0o775 }); - } finally { - process.umask(previousUmask); - await rm(root, { force: true, recursive: true }); - } - }); + }, + ); it("starts the daemon when the folder holding SIMLOCK_HOME exists but refuses mkdir", async () => { // why: #1663: on Windows `mkdir('D:\\')`, recursive or not, rejects EPERM though the root exists @@ -221,7 +228,8 @@ describe("NodeDaemonLauncher's LaunchedDaemon", () => { describe("NodeDaemonLauncher in a parent that awaits nothing", () => { it("lets the parent process exit while the launched daemon keeps running", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); - const launcherModule = fileURLToPath(new URL("./daemon-launcher.ts", import.meta.url)); + // why: a `file:` URL imports on Windows, where a drive path is read as a URL scheme. + const launcherModule = new URL("./daemon-launcher.ts", import.meta.url).href; const parentScript = ` const { NodeDaemonLauncher } = await import(${JSON.stringify(launcherModule)}); const launcher = new NodeDaemonLauncher({ @@ -349,8 +357,8 @@ describe("launcherFor's fallback to spawning", () => { const notices: string[] = []; const launcher = launcherFor({ role: "worker", - root: "/Users/me/.simlock", - dataDirectory: "/Users/me/.simlock", + root: join("/Users/me", ".simlock"), + dataDirectory: join("/Users/me", ".simlock"), mainPath: "/opt/simlock/dist/daemon/main.js", nodePath: "/opt/node/bin/node", home: "/Users/me", @@ -383,8 +391,8 @@ describe("launcherFor with an installed service", () => { const spawner = new FakeDaemonLauncher(); const launcher = launcherFor({ role: "worker", - root: "/home/me/.simlock", - dataDirectory: "/home/me/.simlock", + root: join("/home/me", ".simlock"), + dataDirectory: join("/home/me", ".simlock"), mainPath: "/opt/simlock/dist/daemon/main.js", nodePath: "/opt/node/bin/node", home: "/home/me", @@ -401,7 +409,10 @@ describe("launcherFor with an installed service", () => { serviceManager.starts.map((definition) => definition.path), testCase.manager, ).toEqual([ - `${testCase.path}com.callstack.simlock.worker.${testCase.manager === "systemd" ? "service" : "plist"}`, + join( + testCase.path, + `com.callstack.simlock.worker.${testCase.manager === "systemd" ? "service" : "plist"}`, + ), ]); } }); diff --git a/src/ports/filesystem.test.ts b/src/ports/filesystem.test.ts index 4d2e6e6c9..bfaccfc0d 100644 --- a/src/ports/filesystem.test.ts +++ b/src/ports/filesystem.test.ts @@ -44,7 +44,13 @@ afterEach(async () => { await new NodeFilesystem().rm(temporaryDirectory); }); -describe.each(implementations)("Filesystem contract: $name", ({ create, link }) => { +// why: the real filesystem on Windows has no mode bits, no owner ids and a different errno for some failures, so a test of those facts runs on the memory filesystem only there. +const posixOnly = (name: string) => name === "node filesystem" && process.platform === "win32"; + +// why: the memory filesystem keeps a link target as a `/` path without a drive, and the real one as the host spells it. +const targetOf = (path: string) => path.replace(/^[A-Za-z]:/, "").replaceAll("\\", "/"); + +describe.each(implementations)("Filesystem contract: $name", ({ name, create, link }) => { it("atomically writes and overwrites a complete file", async () => { const filesystem = create(); const file = `${temporaryDirectory}/devices/registry.json`; @@ -70,7 +76,7 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) await expect(filesystem.readFile(file)).resolves.toBe(""); expect((await filesystem.stat(file)).identity).toBe(before); - expect((await filesystem.stat(file)).mode).toBe(0o600); + if (!posixOnly(name)) expect((await filesystem.stat(file)).mode).toBe(0o600); await filesystem.writeFileInPlace(`${temporaryDirectory}/new.log`, "text", { mode: 0o600 }); await expect(filesystem.readFile(`${temporaryDirectory}/new.log`)).resolves.toBe("text"); @@ -140,9 +146,14 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) await filesystem.mkdirp(directory, { mode: 0o750 }); await filesystem.mkdirp(existing, { mode: 0o750 }); - expect((await filesystem.stat(directory)).mode).toBe(0o750); - expect((await filesystem.stat(`${temporaryDirectory}/home`)).mode).toBe(0o750); - expect((await filesystem.stat(existing)).mode).toBe(0o755); + expect((await filesystem.stat(directory)).kind).toBe("directory"); + expect((await filesystem.stat(`${temporaryDirectory}/home`)).kind).toBe("directory"); + // why: the real filesystem on Windows has no mode bits, so only the memory one can show them. + if (!posixOnly(name)) { + expect((await filesystem.stat(directory)).mode).toBe(0o750); + expect((await filesystem.stat(`${temporaryDirectory}/home`)).mode).toBe(0o750); + expect((await filesystem.stat(existing)).mode).toBe(0o755); + } } finally { process.umask(previousUmask); } @@ -176,8 +187,13 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) 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); + await expect(filesystem.readFile(asked)).resolves.toBe("{}"); + await expect(filesystem.readFile(unasked)).resolves.toBe("{}"); + // why: the real filesystem on Windows has no mode bits, so only the memory one can show them. + if (!posixOnly(name)) { + expect((await filesystem.stat(asked)).mode).toBe(0o600); + expect((await filesystem.stat(unasked)).mode).toBe(0o644); + } } finally { process.umask(previousUmask); } @@ -206,9 +222,10 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) await filesystem.mkdirp(occupied); await filesystem.writeFileAtomic(`${occupied}/someone-elses-work.txt`, ""); - await expect(filesystem.rename(staging, occupied)).rejects.toMatchObject({ - code: "ENOTEMPTY", - }); + const refused = expect(filesystem.rename(staging, occupied)).rejects; + // why: Windows refuses with EPERM where POSIX says ENOTEMPTY, so only the refusal is common. + await (posixOnly(name) ? refused.toThrow() : refused.toMatchObject({ code: "ENOTEMPTY" })); + await expect(filesystem.exists(`${occupied}/someone-elses-work.txt`)).resolves.toBe(true); }); it("reports whether a path is there", async () => { @@ -262,9 +279,9 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) const modifiedBefore = (await filesystem.stat(`${dir}/file`)).modifiedAtMs; await link(filesystem, `${dir}/link`, `${dir}/old`); - await expect(filesystem.readlink(`${dir}/link`)).resolves.toBe(`${dir}/old`); + expect(targetOf(await filesystem.readlink(`${dir}/link`))).toBe(targetOf(`${dir}/old`)); await filesystem.replaceSymlink(`${dir}/link`, `${dir}/new`); - await expect(filesystem.readlink(`${dir}/link`)).resolves.toBe(`${dir}/new`); + expect(targetOf(await filesystem.readlink(`${dir}/link`))).toBe(targetOf(`${dir}/new`)); await filesystem.writeAt(`${dir}/file`, 2, new TextEncoder().encode("XY")); await expect(filesystem.readFile(`${dir}/file`)).resolves.toBe("abXYef"); expect((await filesystem.stat(`${dir}/file`)).modifiedAtMs).toBe(modifiedBefore); @@ -281,6 +298,9 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) await filesystem.mkdirp(temporaryDirectory); await filesystem.writeFileAtomic(`${temporaryDirectory}/notes.txt`, ""); + // why: Windows reports a path that runs through a file as ENOENT, the same errno as a missing + // one, so the claim cannot hold there. + if (posixOnly(name)) return; await expect(filesystem.exists(`${temporaryDirectory}/notes.txt/ios`)).rejects.toMatchObject({ code: "ENOTDIR", }); @@ -308,7 +328,7 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) }); }); -describe.each(implementations)("Filesystem ownership contract: $name", ({ create }) => { +describe.each(implementations)("Filesystem ownership contract: $name", ({ name, create }) => { it("reports what a path is, who owns it, and how exposed it is", async () => { const filesystem = create(); const root = `${temporaryDirectory}/devices/ios`; @@ -316,11 +336,15 @@ describe.each(implementations)("Filesystem ownership contract: $name", ({ create await filesystem.mkdirp(root); await filesystem.chmod(root, 0o700); - await expect(filesystem.lstat(root)).resolves.toEqual({ - kind: "directory", - mode: 0o700, - uid: process.getuid?.() ?? 0, - }); + // why: the real filesystem on Windows has no mode bits or owner ids, so only its kind is common. + if (posixOnly(name)) + await expect(filesystem.lstat(root)).resolves.toMatchObject({ kind: "directory" }); + else + await expect(filesystem.lstat(root)).resolves.toEqual({ + kind: "directory", + mode: 0o700, + uid: process.getuid?.() ?? 0, + }); }); it("reports the permission bits a path was last given, not the ones it was created with", async () => { @@ -331,7 +355,10 @@ describe.each(implementations)("Filesystem ownership contract: $name", ({ create await filesystem.mkdir(root, { mode: 0o777 }); await filesystem.chmod(root, 0o700); - await expect(filesystem.lstat(root)).resolves.toMatchObject({ mode: 0o700 }); + // why: the real filesystem on Windows has no mode bits, so only its kind is common. + await expect(filesystem.lstat(root)).resolves.toMatchObject( + posixOnly(name) ? { kind: "directory" } : { mode: 0o700 }, + ); }); it("refuses to create a directory that already exists", async () => { @@ -358,7 +385,7 @@ describe.each(implementations)("Filesystem ownership contract: $name", ({ create await filesystem.mkdirp(root); const resolved = await filesystem.realpath(root); - expect(resolved.endsWith("/devices/ios")).toBe(true); + expect(targetOf(resolved).endsWith("/devices/ios")).toBe(true); await expect(filesystem.realpath(resolved)).resolves.toBe(resolved); }); }); @@ -475,7 +502,7 @@ describe("Filesystem.copyTree", () => { await real.mkdirp(source); await writeFile(`${source}/disk.img`, "image"); await utimes(`${source}/disk.img`, modifiedAt, modifiedAt); - for (const platform of ["win32", process.platform] as const) { + for (const platform of new Set(["win32", process.platform] as const)) { const target = `${temporaryDirectory}/copy-tree/${platform}`; await new NodeFilesystem({ platform }).copyTree(source, target, { timeoutMs: 600_000 }); await expect(real.readFile(`${target}/disk.img`)).resolves.toBe("image"); diff --git a/src/ports/ipc.test.ts b/src/ports/ipc.test.ts index 8bcb7d1ab..1dac95497 100644 --- a/src/ports/ipc.test.ts +++ b/src/ports/ipc.test.ts @@ -18,7 +18,7 @@ describe.each(implementations)("IpcTransport contract: $name", ({ create }) => { beforeEach(async () => { directory = await mkdtemp(join(tmpdir(), "simlock-ipc-")); - endpoint = join(directory, "daemon.sock"); + endpoint = resolveDaemonSocketPath(directory); }); afterEach(async () => { diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index fdfccaa1c..20a4de124 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -122,28 +122,32 @@ async function tempDir(): Promise { } describe("NodeFileLogSink", () => { - it("creates the file it holds owner-only, the current file and the rotated generation alike", async () => { - // why: #685: 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(); - const path = join(directory, "daemon.log"); - // why: the second write passes the 12-byte cap — that rotation is part of what this asserts. - const sink = new NodeFileLogSink({ maxBytes: 12, path }); - sink.write("first"); - sink.write("second"); - sink.close(); - - expect({ - current: (await stat(path)).mode & 0o777, - rotated: (await stat(`${path}.1`)).mode & 0o777, - }).toEqual({ current: 0o600, rotated: 0o600 }); - } finally { - process.umask(previousUmask); - } - }); + // why: Windows has no owner-only file mode. + it.skipIf(process.platform === "win32")( + "creates the file it holds owner-only, the current file and the rotated generation alike", + async () => { + // why: #685: 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(); + const path = join(directory, "daemon.log"); + // why: the second write passes the 12-byte cap — that rotation is part of what this asserts. + const sink = new NodeFileLogSink({ maxBytes: 12, path }); + sink.write("first"); + sink.write("second"); + sink.close(); + + expect({ + current: (await stat(path)).mode & 0o777, + rotated: (await stat(`${path}.1`)).mode & 0o777, + }).toEqual({ current: 0o600, rotated: 0o600 }); + } finally { + process.umask(previousUmask); + } + }, + ); it("appends one line per write to the target file", async () => { const directory = await tempDir(); diff --git a/src/ports/npm-cli.test.ts b/src/ports/npm-cli.test.ts index 4ef64420e..2ea52c958 100644 --- a/src/ports/npm-cli.test.ts +++ b/src/ports/npm-cli.test.ts @@ -17,6 +17,9 @@ if (rest.includes("simlock@noisy")) { process.stdout.write(JSON.stringify({ argv: process.argv.slice(2), script: process.argv[1], cwd: process.cwd() }) + "\\n"); `; +// why: Windows runs a program only by a name that ends in `.exe`. +const NODE = process.platform === "win32" ? "node.exe" : "node"; + const trees: string[] = []; afterEach(async () => { @@ -32,7 +35,7 @@ async function stubNpm( await mkdir(dataDirectory); await mkdir(join(tree, "bin")); await mkdir(join(tree, "lib")); - await symlink(process.execPath, join(tree, "bin", "node")); + await symlink(process.execPath, join(tree, "bin", NODE)); const script = join(tree, "lib", "npm-cli.js"); await writeFile(script, STUB_NPM); await chmod(script, 0o755); @@ -41,7 +44,7 @@ async function stubNpm( runner, filesystem: new NodeFilesystem(), dataDirectory, - execPath: join(tree, "bin", "node"), + execPath: join(tree, "bin", NODE), }); return { npm, dataDirectory, script }; } @@ -68,7 +71,7 @@ async function windowsLayoutNpm(): Promise<{ await mkdir(dataDirectory); const nodejs = join(tree, "nodejs"); await mkdir(join(nodejs, "node_modules", "npm", "bin"), { recursive: true }); - await symlink(process.execPath, join(nodejs, "node")); + await symlink(process.execPath, join(nodejs, NODE)); await writeFile(join(nodejs, "npm"), WINDOWS_NPM_WRAPPER); const script = join(nodejs, "node_modules", "npm", "bin", "npm-cli.js"); await writeFile(script, STUB_NPM); @@ -76,7 +79,7 @@ async function windowsLayoutNpm(): Promise<{ runner: new NodeProcessRunner(), filesystem: new NodeFilesystem(), dataDirectory, - execPath: join(nodejs, "node"), + execPath: join(nodejs, NODE), }); return { npm, dataDirectory, script }; } @@ -132,7 +135,7 @@ describe("NodeNpmCli", () => { ["i", "-g", "simlock@0.4.0"], ["root", "-g"], ].map((args) => ({ - match: { command: /node$/, args: [/npm-cli\.js$/, ...args] }, + match: { command: /node(\.exe)?$/, args: [/npm-cli\.js$/, ...args] }, result: hung, })), ); diff --git a/src/ports/paths.test.ts b/src/ports/paths.test.ts index e9ebf1c12..4679ab4ec 100644 --- a/src/ports/paths.test.ts +++ b/src/ports/paths.test.ts @@ -1,5 +1,5 @@ import { homedir } from "node:os"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { describe, expect, it } from "vitest"; import { MemoryFilesystem } from "./filesystem.js"; @@ -110,7 +110,9 @@ describe("resolveSimlockHome", () => { }); it("uses SIMLOCK_HOME when set", () => { - expect(resolveSimlockHome({ SIMLOCK_HOME: "/tmp/custom-home" })).toBe("/tmp/custom-home"); + expect(resolveSimlockHome({ SIMLOCK_HOME: "/tmp/custom-home" })).toBe( + resolve("/tmp/custom-home"), + ); }); it("makes a relative SIMLOCK_HOME absolute, since device roots derived from it must be", () => { @@ -121,7 +123,7 @@ describe("resolveSimlockHome", () => { it("normalises a SIMLOCK_HOME that is absolute but not canonical", () => { expect(resolveSimlockHome({ SIMLOCK_HOME: "/tmp/custom-home/../other-home" })).toBe( - "/tmp/other-home", + resolve("/tmp/other-home"), ); }); }); @@ -130,7 +132,7 @@ describe("resolveDaemonHome", () => { const root = "/home/me/.simlock"; it.each([ - ["gateway", "gateway", `${root}/gateway`], + ["gateway", "gateway", join(root, "gateway")], [undefined, "worker", root], ] as const)( "sends the gateway flag to /gateway and everything else to (flag %s)", @@ -240,7 +242,7 @@ describe("resolveDaemonHome", () => { await inner.writeFileAtomic(`${root}/gateway/config.json`, "{}"); const filesystem = { exists: (path: string) => - path === `${root}/instance.json` + path === join(root, "instance.json") ? Promise.reject(Object.assign(new Error("EACCES"), { code: "EACCES" })) : inner.exists(path), }; diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index e6c57082a..f123b5773 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -724,10 +724,6 @@ describe("NodeProcessRunner", () => { }), answer: await runner.run(process.execPath, ["-e", echo], { input: '{"a":1}\n' }), exit1: await runner.run(process.execPath, ["-e", "process.exit(1)"], { input: "{}\n" }), - killedFromOutside: await runner.run(process.execPath, [ - "-e", - "process.kill(process.pid, 'SIGKILL')", - ]), timeout: await runner.run(process.execPath, ["-e", lingers], { timeoutMs: 100 }), tooMuchOutput: await runner.run( process.execPath, @@ -742,8 +738,15 @@ describe("NodeProcessRunner", () => { expect(outcomes.timeout).toMatchObject({ code: null, endedBy: "timeout" }); expect(outcomes.tooMuchOutput).toMatchObject({ code: null, endedBy: "output-limit" }); expect(outcomes.aborted).toMatchObject({ code: null, endedBy: "aborted" }); - expect(outcomes.killedFromOutside).toMatchObject({ code: null, signal: "SIGKILL" }); - expect(outcomes.killedFromOutside.endedBy).toBeUndefined(); + // why: Windows has no signals, so a process that kills itself there exits with code 1. + if (process.platform !== "win32") { + const killedFromOutside = await runner.run(process.execPath, [ + "-e", + "process.kill(process.pid, 'SIGKILL')", + ]); + expect(killedFromOutside).toMatchObject({ code: null, signal: "SIGKILL" }); + expect(killedFromOutside.endedBy).toBeUndefined(); + } await expect( runner.run("/nonexistent/simlock-policy", [], { input: "{}\n" }), ).rejects.toBeInstanceOf(ProcessSpawnError); diff --git a/src/ports/service-manager.test.ts b/src/ports/service-manager.test.ts index a1e4d564a..ab280e12d 100644 --- a/src/ports/service-manager.test.ts +++ b/src/ports/service-manager.test.ts @@ -107,84 +107,92 @@ async function installed( } describe("LaunchdServiceManager (#830)", () => { - it("launchd reads the plist install wrote: arguments, saved variables, service keys and log paths", async () => { - const saved = { - SIMLOCK_DRIVERS_MODULE: "/x/drivers.js", - PATH: "/usr/bin:/opt/bin&sbin:/odd", - ANDROID_HOME: "/sdk", - ANDROID_SDK_ROOT: "/sdk", - ANDROID_AVD_HOME: "/avd", - ANDROID_USER_HOME: "/auser", - ANDROID_PREFS_ROOT: "/aprefs", - ANDROID_SDK_HOME: "/ahome", - JAVA_HOME: "/jdk", - DEVELOPER_DIR: "/Xcode/Developer", - }; - const cases = [ - { - label: "worker, every saved variable set, secrets present in the shell", - role: "worker" as const, - env: { ...saved, SIMLOCK_ADMIN_TOKEN: "secret", SIMLOCK_AGENT_ID: "agent" }, - arguments: ["/opt/node/bin/node", "/opt/simlock/dist/daemon/main.js"], - variables: { SIMLOCK_HOME: root, ...saved }, - logPath: `${root}/daemon.log`, - }, - { - label: "gateway, no variable set", - role: "gateway" as const, - env: {}, - arguments: ["/opt/node/bin/node", "/opt/simlock/dist/daemon/main.js", "--gateway"], - variables: { SIMLOCK_HOME: root }, - logPath: `${root}/gateway/daemon.log`, - }, - ]; - - for (const testCase of cases) { - const definition = definitionFor(testCase.role, testCase.env); - const { plist, filesystem } = await installed(definition); - const raw = await filesystem.readFile(definition.path); - if (testCase.role === "worker") { - expect(raw, `${testCase.label}: XML-escaped`).toContain( - "/usr/bin:/opt/bin&sbin:/odd<dir>", - ); + // why: launchd and systemd are not on Windows, and these files are read back by `/` path. + it.skipIf(process.platform === "win32")( + "launchd reads the plist install wrote: arguments, saved variables, service keys and log paths", + async () => { + const saved = { + SIMLOCK_DRIVERS_MODULE: "/x/drivers.js", + PATH: "/usr/bin:/opt/bin&sbin:/odd", + ANDROID_HOME: "/sdk", + ANDROID_SDK_ROOT: "/sdk", + ANDROID_AVD_HOME: "/avd", + ANDROID_USER_HOME: "/auser", + ANDROID_PREFS_ROOT: "/aprefs", + ANDROID_SDK_HOME: "/ahome", + JAVA_HOME: "/jdk", + DEVELOPER_DIR: "/Xcode/Developer", + }; + const cases = [ + { + label: "worker, every saved variable set, secrets present in the shell", + role: "worker" as const, + env: { ...saved, SIMLOCK_ADMIN_TOKEN: "secret", SIMLOCK_AGENT_ID: "agent" }, + arguments: ["/opt/node/bin/node", "/opt/simlock/dist/daemon/main.js"], + variables: { SIMLOCK_HOME: root, ...saved }, + logPath: `${root}/daemon.log`, + }, + { + label: "gateway, no variable set", + role: "gateway" as const, + env: {}, + arguments: ["/opt/node/bin/node", "/opt/simlock/dist/daemon/main.js", "--gateway"], + variables: { SIMLOCK_HOME: root }, + logPath: `${root}/gateway/daemon.log`, + }, + ]; + + for (const testCase of cases) { + const definition = definitionFor(testCase.role, testCase.env); + const { plist, filesystem } = await installed(definition); + const raw = await filesystem.readFile(definition.path); + if (testCase.role === "worker") { + expect(raw, `${testCase.label}: XML-escaped`).toContain( + "/usr/bin:/opt/bin&sbin:/odd<dir>", + ); + } + expect(plist, testCase.label).toEqual({ + Label: definition.name, + ProgramArguments: testCase.arguments, + EnvironmentVariables: testCase.variables, + RunAtLoad: true, + KeepAlive: { SuccessfulExit: false }, + AbandonProcessGroup: true, + ExitTimeOut: 300, + StandardOutPath: testCase.logPath, + StandardErrorPath: testCase.logPath, + }); } - expect(plist, testCase.label).toEqual({ - Label: definition.name, - ProgramArguments: testCase.arguments, - EnvironmentVariables: testCase.variables, - RunAtLoad: true, - KeepAlive: { SuccessfulExit: false }, - AbandonProcessGroup: true, - ExitTimeOut: 300, - StandardOutPath: testCase.logPath, - StandardErrorPath: testCase.logPath, - }); - } - }); + }, + ); - it("install creates daemon.log at 0600 in a data directory it creates owner-only when they are missing, and keeps a log that exists", async () => { - // why: a directory the memory filesystem creates without a mode is already 0700, so the - // mode install asks for is read from the call it makes, not from the directory. - class RecordingFilesystem extends MemoryFilesystem { - readonly directories: Array<{ path: string; mode: number | undefined }> = []; - override async mkdirp(path: string, options?: { readonly mode?: number }): Promise { - this.directories.push({ path, mode: options?.mode }); - await super.mkdirp(path, options); + // why: launchd and systemd are not on Windows, and these files are read back by `/` path. + it.skipIf(process.platform === "win32")( + "install creates daemon.log at 0600 in a data directory it creates owner-only when they are missing, and keeps a log that exists", + async () => { + // why: a directory the memory filesystem creates without a mode is already 0700, so the + // mode install asks for is read from the call it makes, not from the directory. + class RecordingFilesystem extends MemoryFilesystem { + readonly directories: Array<{ path: string; mode: number | undefined }> = []; + override async mkdirp(path: string, options?: { readonly mode?: number }): Promise { + this.directories.push({ path, mode: options?.mode }); + await super.mkdirp(path, options); + } } - } - const definition = definitionFor("worker"); - const recording = new RecordingFilesystem(); - const created = await installed(definition, recording); - expect((await created.filesystem.stat(definition.logPath)).mode).toBe(0o600); - expect(recording.directories).toContainEqual({ path: root, mode: 0o700 }); - - const existing = new MemoryFilesystem(); - await existing.mkdirp(root); - await existing.writeFileAtomic(definition.logPath, "earlier line\n", { mode: 0o640 }); - await installed(definition, existing); - expect(await existing.readFile(definition.logPath)).toBe("earlier line\n"); - expect((await existing.stat(definition.logPath)).mode).toBe(0o640); - }); + const definition = definitionFor("worker"); + const recording = new RecordingFilesystem(); + const created = await installed(definition, recording); + expect((await created.filesystem.stat(definition.logPath)).mode).toBe(0o600); + expect(recording.directories).toContainEqual({ path: root, mode: 0o700 }); + + const existing = new MemoryFilesystem(); + await existing.mkdirp(root); + await existing.writeFileAtomic(definition.logPath, "earlier line\n", { mode: 0o640 }); + await installed(definition, existing); + expect(await existing.readFile(definition.logPath)).toBe("earlier line\n"); + expect((await existing.stat(definition.logPath)).mode).toBe(0o640); + }, + ); it("daemon install on an installed service rewrites the plist and loads it again", async () => { const cases = [ @@ -714,12 +722,16 @@ describe("SystemdServiceManager (#832)", () => { expect(await stuck.exists(definition.path)).toBe(true); } - it("an operator on Linux installs, starts and removes a systemd user unit", async () => { - await checkUnitText(); - checkUnitPath(); - await checkStart(); - await checkInstallFailures(); - await checkStates(); - await checkUninstall(); - }); + // why: launchd and systemd are not on Windows, and these files are read back by `/` path. + it.skipIf(process.platform === "win32")( + "an operator on Linux installs, starts and removes a systemd user unit", + async () => { + await checkUnitText(); + checkUnitPath(); + await checkStart(); + await checkInstallFailures(); + await checkStates(); + await checkUninstall(); + }, + ); }); diff --git a/src/ports/sqlite.test.ts b/src/ports/sqlite.test.ts index 68772821e..ac3323a34 100644 --- a/src/ports/sqlite.test.ts +++ b/src/ports/sqlite.test.ts @@ -1,5 +1,5 @@ import { readdirSync, readFileSync } from "node:fs"; -import { join, posix } from "node:path"; +import { join, relative } from "node:path"; import { describe, expect, it } from "vitest"; @@ -23,7 +23,8 @@ describe("the sqlite port", () => { ) || SQLITE_LOADERS.test(source) ); }) - .map((file) => posix.relative(srcDir, file)); + // why: `join` and `srcDir` use `\` on Windows, so the names are joined with `/` before they are compared. + .map((file) => relative(srcDir, file).replaceAll("\\", "/")); expect(naming).toEqual(["ports/sqlite.ts"]); }); diff --git a/src/ports/updater-launcher.test.ts b/src/ports/updater-launcher.test.ts index 71e8a9fc7..14d02ac77 100644 --- a/src/ports/updater-launcher.test.ts +++ b/src/ports/updater-launcher.test.ts @@ -20,8 +20,9 @@ describe("NodeUpdaterLauncher", () => { await writeFile( entry, `const { execFileSync } = require("node:child_process"); -const group = Number(execFileSync("ps", ["-o", "pgid=", "-p", String(process.pid)])); -console.log(JSON.stringify({ argv: process.argv.slice(2), home: process.env.SIMLOCK_HOME, leader: group === process.pid })); +// why: Windows has no process groups, so there the entry reports no leader. +const leader = process.platform === "win32" ? null : Number(execFileSync("ps", ["-o", "pgid=", "-p", String(process.pid)])) === process.pid; +console.log(JSON.stringify({ argv: process.argv.slice(2), home: process.env.SIMLOCK_HOME, leader })); console.log("second"); console.error("to the log"); process.exit(3);`, @@ -45,7 +46,7 @@ process.exit(3);`, JSON.stringify({ argv: ["--from", "0.3.0", "--to", "0.4.0", "--pid", "4242", "--gateway"], home: "/home/.simlock", - leader: true, + leader: process.platform === "win32" ? null : true, }), "second", ]); diff --git a/src/ports/uplink-websocket.test.ts b/src/ports/uplink-websocket.test.ts index 84a30d9bd..06e9e0944 100644 --- a/src/ports/uplink-websocket.test.ts +++ b/src/ports/uplink-websocket.test.ts @@ -292,7 +292,7 @@ describe("WebSocketUplinkConnection binary messages", () => { await vi.waitFor(() => expect(received).toEqual([[2]])); }); - it("unsentBytes follows the socket's buffered amount with onSent firing when a send completes", async () => { + it("unsentBytes is 0 again and onSent has fired once a send completes", async () => { const { accepted, url } = await startAcceptingGateway(); const worker = await new WebSocketUplinkConnector().connect(dialOptions(url)); await accepted; @@ -300,15 +300,28 @@ describe("WebSocketUplinkConnection binary messages", () => { worker.onSent(onSent); expect(worker.unsentBytes).toBe(0); - const write = worker.writeBinary(new Uint8Array(16 * 1024 * 1024)); - const buffered = worker.unsentBytes; - await write; + await worker.writeBinary(new Uint8Array(16 * 1024 * 1024)); - expect(buffered).toBeGreaterThan(0); expect(worker.unsentBytes).toBe(0); expect(onSent).toHaveBeenCalled(); }); + // why: on the Windows CI runner the loopback socket takes the whole 16 MiB write at once, so the buffered amount reads 0 right after it and there is nothing to follow. + it.skipIf(process.platform === "win32")( + "unsentBytes counts what the socket still buffers while a send is in flight", + async () => { + const { accepted, url } = await startAcceptingGateway(); + const worker = await new WebSocketUplinkConnector().connect(dialOptions(url)); + await accepted; + + const write = worker.writeBinary(new Uint8Array(16 * 1024 * 1024)); + const buffered = worker.unsentBytes; + await write; + + expect(buffered).toBeGreaterThan(0); + }, + ); + it("onSent fires when a text send completes", async () => { const { accepted, url } = await startAcceptingGateway(); const worker = await new WebSocketUplinkConnector().connect(dialOptions(url)); @@ -386,8 +399,11 @@ describe("WebSocketUplinkConnector liveness", () => { ]); expect(firstOutcome).toBe("closed"); - clock.advance(1_000); - await vi.waitFor(() => expect(accepted).toBe(2)); + // why: the redial's backoff timer is armed when the worker's end sees the close, which can come after the gateway's end on Windows, and an earlier timer (the stable-connection one) is already pending; advancing again on each try reaches the backoff timer whenever it is armed. + await vi.waitFor(() => { + clock.advance(1_000); + expect(accepted).toBe(2); + }); expect(gateway.peers).toHaveLength(2); await uplink.stop(); }); diff --git a/src/ports/worker-lock.test.ts b/src/ports/worker-lock.test.ts index 6b413b70c..839459cd9 100644 --- a/src/ports/worker-lock.test.ts +++ b/src/ports/worker-lock.test.ts @@ -99,20 +99,24 @@ describe("NodeWorkerLock", () => { expect(JSON.parse(await readFile(join(path, "owner.json"), "utf8"))).toEqual(holder); }); - it("refuses a parent folder owned by another user and tightens one of its own to 0700", async () => { - const { path } = await lockInTemporaryFolder(); - const parent = dirname(path); - await mkdir(parent, { mode: 0o755, recursive: true }); - await chmod(parent, 0o755); - const uid = process.getuid?.() ?? 0; + // why: Windows has no owner ids and no directory modes. + it.skipIf(process.platform === "win32")( + "refuses a parent folder owned by another user and tightens one of its own to 0700", + async () => { + const { path } = await lockInTemporaryFolder(); + const parent = dirname(path); + await mkdir(parent, { mode: 0o755, recursive: true }); + await chmod(parent, 0o755); + const uid = process.getuid?.() ?? 0; - await expect(adapter(path, [], uid + 1).take(ME)).rejects.toThrow( - `${parent} cannot be used as the worker lock folder: owned by another user`, - ); - await adapter(path, [], uid).take(ME); + await expect(adapter(path, [], uid + 1).take(ME)).rejects.toThrow( + `${parent} cannot be used as the worker lock folder: owned by another user`, + ); + await adapter(path, [], uid).take(ME); - expect((await stat(parent)).mode & 0o777).toBe(0o700); - }); + expect((await stat(parent)).mode & 0o777).toBe(0o700); + }, + ); it("a worker that wins the socket claim makes the lock again when it is missing and refuses when a live pid in another folder holds it", async () => { const { path } = await lockInTemporaryFolder(); diff --git a/src/state/state.test.ts b/src/state/state.test.ts index c6bde5e24..ff69d22c0 100644 --- a/src/state/state.test.ts +++ b/src/state/state.test.ts @@ -1,5 +1,5 @@ import { existsSync, statSync } from "node:fs"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -13,13 +13,12 @@ import { type SqliteSchemaOwner, } from "../ports/index.js"; import { openStateDatabase, STATE_DB_NAME } from "./index.js"; +import { removeDirectory } from "../test-support/remove-directory.js"; const directories: string[] = []; afterEach(async () => { - await Promise.all( - directories.splice(0).map((path) => rm(path, { force: true, recursive: true })), - ); + await Promise.all(directories.splice(0).map((path) => removeDirectory(path))); }); const sqlite = new NodeSqliteOpener(); @@ -65,7 +64,8 @@ describe("openStateDatabase", () => { const first = await open(directory); expect(existsSync(path)).toBe(true); - expect(statSync(path).mode & 0o777).toBe(0o600); + // why: Windows has no owner-only file mode. + if (process.platform !== "win32") expect(statSync(path).mode & 0o777).toBe(0o600); expect( first.database.prepare("SELECT owner, version FROM schema_versions ORDER BY owner").all(), ).toEqual([ diff --git a/src/test-support/imports.test.ts b/src/test-support/imports.test.ts index 3246bc401..897d60d78 100644 --- a/src/test-support/imports.test.ts +++ b/src/test-support/imports.test.ts @@ -28,7 +28,7 @@ describe("sourceFilesRecursive", () => { writeFileSync(join(dir, "nested", "deep.test.ts"), "export {};"); const found = sourceFilesRecursive(dir) - .map((path) => path.slice(dir.length + 1)) + .map((path) => path.slice(dir.length + 1).replaceAll("\\", "/")) .sort(); expect(found).toEqual(["nested/deep.ts", "top.ts"]); diff --git a/src/test-support/imports.ts b/src/test-support/imports.ts index 7ee8b4175..552d2ea73 100644 --- a/src/test-support/imports.ts +++ b/src/test-support/imports.ts @@ -55,7 +55,12 @@ export function importSpecifiers(contents: string): string[] { */ export function normalizeSpecifier(fileDir: string, specifier: string, root = srcDir): string { if (!specifier.startsWith(".")) return specifier; - return posix.relative(root, posix.normalize(posix.join(fileDir, specifier))); + return posix.relative(slashed(root), posix.normalize(posix.join(slashed(fileDir), specifier))); +} + +// why: a path from `node:path` has `\` on Windows, and the `posix` calls here read only `/`. +function slashed(path: string): string { + return path.replaceAll("\\", "/"); } /** Whether a normalized specifier names a module inside the top-level directory `dir` of the @@ -87,7 +92,7 @@ export interface ModuleImport { export function importsOf(files: readonly string[], root = srcDir): ModuleImport[] { return files.flatMap((filePath) => importSpecifiers(stripComments(readFileSync(filePath, "utf8"))).map((specifier) => ({ - file: posix.relative(root, filePath), + file: posix.relative(slashed(root), slashed(filePath)), normalized: normalizeSpecifier(dirname(filePath), specifier, root), specifier, })), diff --git a/src/test-support/remove-directory.ts b/src/test-support/remove-directory.ts new file mode 100644 index 000000000..fce0e00c4 --- /dev/null +++ b/src/test-support/remove-directory.ts @@ -0,0 +1,7 @@ +import { rm } from "node:fs/promises"; + +// why: Windows keeps a deleted file's folder busy until the last handle on it is released, which can +// trail a stopped daemon by a few ms, so the removal retries `EBUSY` and `EPERM` for about 3 s (Node waits longer after each try). +export function removeDirectory(path: string): Promise { + return rm(path, { force: true, maxRetries: 10, recursive: true, retryDelay: 50 }); +} diff --git a/src/test-support/windows-skipped.ts b/src/test-support/windows-skipped.ts index ccb6e3240..2f783f3af 100644 --- a/src/test-support/windows-skipped.ts +++ b/src/test-support/windows-skipped.ts @@ -22,44 +22,6 @@ const WINDOWS_SKIPPED: readonly string[] = [ "src/core/device-root.test.ts", "src/core/instance-identity.test.ts", "src/core/registry.test.ts", - "src/daemon/connection-host.test.ts", - "src/daemon/device-data-tables.test.ts", - "src/daemon/dispatcher-events.test.ts", - "src/daemon/dispatcher-usage.test.ts", - "src/daemon/driver-discovery.test.ts", - "src/daemon/gateway-fleet.e2e.test.ts", - "src/daemon/identity-uplink.e2e.test.ts", - "src/daemon/lease-files.test.ts", - "src/daemon/main-agent-device.test.ts", - "src/daemon/main-history.test.ts", - "src/daemon/main-host-load.test.ts", - "src/daemon/main-start-daemon.test.ts", - "src/daemon/main-state-db.test.ts", - "src/daemon/main-stop.test.ts", - "src/daemon/main-update.test.ts", - "src/daemon/main-worker-lock.test.ts", - "src/daemon/main.test.ts", - "src/daemon/optional-modules-start.test.ts", - "src/daemon/optional-modules-stop.test.ts", - "src/daemon/optional-modules.test.ts", - "src/daemon/relay-gateway-bodies.e2e.test.ts", - "src/daemon/relay-gateway-cancel.e2e.test.ts", - "src/daemon/relay-gateway-capacity.e2e.test.ts", - "src/daemon/relay-gateway-files.e2e.test.ts", - "src/daemon/relay-gateway.e2e.test.ts", - "src/daemon/relay-worker.e2e.test.ts", - "src/daemon/remote-client.e2e.test.ts", - "src/daemon/server-claim-and-stop.test.ts", - "src/daemon/server-drivers.test.ts", - "src/daemon/server-leases.test.ts", - "src/daemon/server-pushes-gateway.test.ts", - "src/daemon/server-pushes.test.ts", - "src/daemon/server-requests.test.ts", - "src/daemon/server-roles.test.ts", - "src/daemon/server-startup.test.ts", - "src/daemon/server-update.test.ts", - "src/daemon/server.test.ts", - "src/daemon/session-path.e2e.test.ts", "src/delivery-stats.test.ts", "src/docs-surface-check.test.ts", "src/drivers/ios/boot-courtesies.test.ts", @@ -87,28 +49,11 @@ const WINDOWS_SKIPPED: readonly string[] = [ "src/drivers/ios/slim-except.test.ts", "src/drivers/ios/slim-named-services.test.ts", "src/fast-track.test.ts", - "src/gateway/boundary.test.ts", - "src/gateway/dispatcher-reads.test.ts", - "src/history/history.test.ts", "src/instructions/setup.test.ts", "src/lint-rules.test.ts", "src/manual-hook.test.ts", - "src/mcp/main.test.ts", "src/merge-pr.test.ts", "src/mutate.test.ts", - "src/ports/daemon-launcher.test.ts", - "src/ports/filesystem.test.ts", - "src/ports/host-load.test.ts", - "src/ports/ipc.test.ts", - "src/ports/logger.test.ts", - "src/ports/npm-cli.test.ts", - "src/ports/paths.test.ts", - "src/ports/process-runner.test.ts", - "src/ports/service-manager.test.ts", - "src/ports/sqlite.test.ts", - "src/ports/updater-launcher.test.ts", - "src/ports/uplink-websocket.test.ts", - "src/ports/worker-lock.test.ts", "src/pr-body-check.test.ts", "src/recurring-findings.test.ts", "src/refactor-check.test.ts", @@ -116,8 +61,6 @@ const WINDOWS_SKIPPED: readonly string[] = [ "src/review-inputs.test.ts", "src/simlock-client/no-core-leak.test.ts", "src/slow-e2e.test.ts", - "src/state/state.test.ts", - "src/test-support/imports.test.ts", "src/tool-guard.test.ts", "src/updater/index.test.ts", "src/worktree-script.test.ts",