From 3a55b3acef676d808dae2766e09fe6b7c46b8b17 Mon Sep 17 00:00:00 2001 From: parsilver Date: Mon, 16 Nov 2026 06:43:22 +0700 Subject: [PATCH 1/3] test: pin doctor, keychain and symlink follow-ups from the #17 review Each test fails on main: doctor quotes the parser's text for a corrupt credentials.json, a tool that cannot start reads as exited timeout, and the credential temp file and service.log are written through a symlink. --- test/cli.test.ts | 21 ++++++++++++++-- test/keychain.test.ts | 34 +++++++++++++++++++++++++- test/service.test.ts | 33 +++++++++++++++++++++++-- test/store.test.ts | 57 +++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 138 insertions(+), 7 deletions(-) diff --git a/test/cli.test.ts b/test/cli.test.ts index 3e1355e..6730434 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -416,12 +416,16 @@ describe.concurrent("tether start", () => { it("warns, with the reason, when the keychain refuses a credential it moves out of the file", async () => { const h = await paired(); - h.keychain = refusingKeychain(); + // A reason that quotes the credential: the warning must print it redacted. + h.keychain = { + ...refusingKeychain(), + set: (_, secret) => `the test keychain is locked: ${secret}`, + }; h.err = ""; startTether(h); await until(() => /claim/.test(h.sent.map((s) => s.path).join(" "))); expect(h.err).toMatch( - /The test keychain refused the credential for .* \(the test keychain is locked\), so it is in .*credentials\.json/, + /The test keychain refused the credential for .* \(the test keychain is locked: \[redacted\]\), so it is in .*credentials\.json/, ); h.expectNoSecrets(); }); @@ -860,6 +864,19 @@ describe.concurrent("tether doctor", () => { /^FAIL {2}The credential for .* is in the keychain, but the test keychain did not answer \(36\)\. Unlock the keychain/m, ); expect(h.err).toBe(""); + h.expectNoSecrets(); + }); + + it("fails, without quoting it, when credentials.json is not valid JSON", async () => { + const h = await paired(); + const file = join(h.home, "credentials.json"); + // The parser's own message quotes the text around the error, here the credential. + writeFileSync(file, `{"apps": [{"credential": ${h.credential()}}]}`); + h.out = ""; + h.err = ""; + expect(await h.run(["doctor"])).toBe(1); + expect(h.out).toMatch(/^FAIL {2}.*credentials\.json could not be read \(invalid JSON\)$/m); + h.expectNoSecrets(); }); it("says when no app is connected, without failing", async () => { diff --git a/test/keychain.test.ts b/test/keychain.test.ts index eca84df..448451a 100644 --- a/test/keychain.test.ts +++ b/test/keychain.test.ts @@ -219,7 +219,7 @@ describe.each([ ? { status: 0, stdout: "", stderr: "" } : { status: 1, stdout: "", stderr: "keyring locked" }; expect(make("tether", writeOnly).set("https://paper.example", SECRET)).toMatch( - /did not answer \(1\)/, + /did not answer \(\S+ exited 1\)/, ); }); @@ -230,6 +230,38 @@ describe.each([ }); }); +describe.each([ + ["macOS", macKeychain, "security"], + ["Secret Service", secretToolKeychain, "secret-tool"], +])("the %s keychain's tool", (_, make, tool) => { + const ended = + (error: string, signal?: string): Run => + () => ({ status: null, stdout: "", stderr: "", error, ...(signal ? { signal } : {}) }); + + it("says it could not run when the tool cannot be started", () => { + const keychain = make("tether", ended("ENOENT")); + expect(keychain.set("https://paper.example", SECRET)).toBe(`${tool} could not run`); + expect(() => keychain.get("https://paper.example")).toThrow(`(${tool} could not run)`); + }); + + it("says it timed out when the tool did not finish in time", () => { + // spawnSync both sets ETIMEDOUT and names the signal it sent. + const keychain = make("tether", ended("ETIMEDOUT", "SIGTERM")); + expect(keychain.set("https://paper.example", SECRET)).toBe(`${tool} timed out`); + expect(() => keychain.get("https://paper.example")).toThrow(`(${tool} timed out)`); + }); + + it("says it was stopped when a signal ended the tool", () => { + const keychain = make("tether", () => ({ + status: null, + stdout: "", + stderr: "", + signal: "SIGKILL", + })); + expect(keychain.set("https://paper.example", SECRET)).toBe(`${tool} was stopped (SIGKILL)`); + }); +}); + describe("the macOS keychain's stdin command", () => { it("refuses a secret it cannot quote rather than send a broken command", () => { const exec = fakeRun(); diff --git a/test/service.test.ts b/test/service.test.ts index ca7c90c..9bc8216 100644 --- a/test/service.test.ts +++ b/test/service.test.ts @@ -1,4 +1,12 @@ -import { chmodSync, existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdtempSync, + readFileSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -258,7 +266,15 @@ describe("tether service on Linux", () => { expect(s.err).toMatch(/enable failed: Unit file is masked\./); s.answers["systemctl --user enable"] = { status: 5, stdout: "", stderr: "" }; expect(await s.exec("install")).toBe(1); - expect(s.err).toMatch(/enable failed: exit 5/); + expect(s.err).toMatch(/enable failed: exited 5/); + s.answers["systemctl --user enable"] = { + status: null, + stdout: "", + stderr: "", + error: "ENOENT", + }; + expect(await s.exec("install")).toBe(1); + expect(s.err).toMatch(/enable failed: could not run/); }); it("warns that an Anthropic key in the shell does not reach the service", async () => { @@ -311,6 +327,19 @@ describe("tether service on macOS, over an agent already loaded", () => { expect(readFileSync(join(s.home, "service.log"), "utf8")).toBe("earlier output\n"); }); + it("refuses a log that is a symbolic link, and leaves what it points at alone", async () => { + const s = new ServiceRun("darwin").connected(); + const elsewhere = join(mkdtempSync(join(tmpdir(), "tether-test-elsewhere-")), "notes.txt"); + writeFileSync(elsewhere, "not Tether's\n", { mode: 0o644 }); + chmodSync(elsewhere, 0o644); + symlinkSync(elsewhere, join(s.home, "service.log")); + expect(await s.exec("install")).toBe(1); + expect(s.err).toMatch(/service\.log is a symbolic link/); + expect(statSync(elsewhere).mode & 0o777).toBe(0o644); + expect(readFileSync(elsewhere, "utf8")).toBe("not Tether's\n"); + expect(s.calls).toEqual([]); + }); + it("waits and bootstraps again while the old agent is still being booted out", async () => { const s = new ServiceRun("darwin").connected(); s.answers["launchctl bootout"] = { diff --git a/test/store.test.ts b/test/store.test.ts index 14b42a1..ebf8214 100644 --- a/test/store.test.ts +++ b/test/store.test.ts @@ -1,8 +1,17 @@ -import { appendFileSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { + appendFileSync, + chmodSync, + lstatSync, + mkdtempSync, + readFileSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { Store, type TaskLogEntry } from "../src/client/store.ts"; +import { type AppRecord, Store, type TaskLogEntry } from "../src/client/store.ts"; function entry(n: number): TaskLogEntry { return { @@ -94,3 +103,47 @@ describe("the service log", () => { expect(statSync(file).size).toBe(5_000_000); }); }); + +function record(): AppRecord { + return { + origin: "https://paper.example", + name: "Paper", + device: { id: "dev_1", name: "Mac (Tether)" }, + account: "Ann", + credential: "tdc_not-a-real-credential", + pairedAt: "2026-11-14T00:00:00.000Z", + }; +} + +describe("files Tether writes", () => { + /** A file outside the home that a symbolic link in the home points at. */ + function elsewhere(): string { + const file = join(mkdtempSync(join(tmpdir(), "tether-store-elsewhere-")), "notes.txt"); + writeFileSync(file, "not Tether's\n", { mode: 0o644 }); + chmodSync(file, 0o644); + return file; + } + + it("never writes credentials through a symbolic link at the temporary file", () => { + const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); + const target = elsewhere(); + symlinkSync(target, join(store.home, `.credentials.json.${process.pid}.tmp`)); + store.saveApp(record()); + expect(readFileSync(target, "utf8")).toBe("not Tether's\n"); + expect(statSync(target).mode & 0o777).toBe(0o644); + const file = join(store.home, "credentials.json"); + expect(lstatSync(file).isSymbolicLink()).toBe(false); + expect(statSync(file).mode & 0o777).toBe(0o600); + expect(store.apps()[0]?.credential).toBe(record().credential); + }); + + it("refuses to cut a service log that is a symbolic link, and leaves what it points at alone", () => { + const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); + const target = elsewhere(); + writeFileSync(target, "x".repeat(5_000_001)); + symlinkSync(target, join(store.home, "service.log")); + expect(() => store.trimServiceLog()).toThrow(/service\.log is a symbolic link/); + expect(statSync(target).size).toBe(5_000_001); + expect(statSync(target).mode & 0o777).toBe(0o644); + }); +}); From a67d05f0374a34528e9c2adaf0dd7acce8669637 Mon Sep 17 00:00:00 2001 From: parsilver Date: Mon, 16 Nov 2026 06:43:22 +0700 Subject: [PATCH 2/3] fix: redact corrupt-JSON reads, name how a tool ended, refuse symlinks doctor now says credentials.json could not be read (invalid JSON) instead of the parser's text, which quotes part of a credential. Ran carries the spawn error and signal, so a keychain or service tool that cannot start says could not run, not exited timeout. Writes of the credential and state temp files, the service files and service.log, and the chmod of an existing service.log, go through one helper that never follows a symlink. --- src/cli/service.ts | 12 ++--- src/client/keychain.ts | 12 ++--- src/client/private-file.ts | 102 +++++++++++++++++++++++++++++++++++++ src/client/run.ts | 25 ++++++++- src/client/store.ts | 31 +++-------- 5 files changed, 144 insertions(+), 38 deletions(-) create mode 100644 src/client/private-file.ts diff --git a/src/cli/service.ts b/src/cli/service.ts index e730b6a..1eb1cc2 100644 --- a/src/cli/service.ts +++ b/src/cli/service.ts @@ -1,6 +1,7 @@ -import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, rmSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; -import type { Ran, Run } from "../client/run.ts"; +import { createPrivate, makePrivate } from "../client/private-file.ts"; +import { ended, type Ran, type Run } from "../client/run.ts"; /** What a background service runs and where its files go; built once from the CLI's context. */ export interface ServiceSpec { @@ -54,7 +55,7 @@ export function thisProgram(execPath: string, argv: string[]): string[] { class ServiceError extends Error {} function failure(done: Ran, what: string): ServiceError { - const detail = done.stderr.trim() || done.stdout.trim() || `exit ${done.status ?? "timeout"}`; + const detail = done.stderr.trim() || done.stdout.trim() || ended(done); return new ServiceError(`${what} failed: ${detail.slice(0, 500)}`); } @@ -68,8 +69,7 @@ const BOOTSTRAP_TRIES = 10; function writePrivate(path: string, content: string | Buffer): void { mkdirSync(dirname(path), { recursive: true }); - writeFileSync(path, content, { mode: 0o600 }); - chmodSync(path, 0o600); + createPrivate(path, content); } // launchd (macOS) @@ -138,7 +138,7 @@ export const launchd: ServiceManager = { // launchd would create the log readable by everyone; create it first, readable by the user, // and take back a log an older install left readable by everyone. const log = join(spec.home, "service.log"); - if (existsSync(log)) chmodSync(log, 0o600); + if (existsSync(log)) makePrivate(log); else writePrivate(log, ""); writePrivate(launchdPlistPath(spec), launchdPlist(spec)); run("launchctl", ["bootout", `${target}/${launchdLabel(spec)}`]); diff --git a/src/client/keychain.ts b/src/client/keychain.ts index 260d7b7..a05f385 100644 --- a/src/client/keychain.ts +++ b/src/client/keychain.ts @@ -1,4 +1,4 @@ -import { type Run, run } from "./run.ts"; +import { ended, type Run, run } from "./run.ts"; /** The keychain could not be asked at all (locked, no session bus, tool missing), as opposed to not holding the item. */ export class KeychainUnavailable extends Error {} @@ -43,9 +43,7 @@ export function macKeychain(service: string, exec: Run = run): Keychain { const done = exec("security", ["find-generic-password", "-s", service, "-a", origin, "-w"]); if (done.status === 0) return done.stdout.replace(/\n$/, ""); if (done.status === MAC_NOT_FOUND) return undefined; - throw new KeychainUnavailable( - `the macOS keychain did not answer (${done.status ?? "timeout"})`, - ); + throw new KeychainUnavailable(`the macOS keychain did not answer (security ${ended(done)})`); }, set: (origin, secret) => { const account = quoted(origin); @@ -57,7 +55,7 @@ export function macKeychain(service: string, exec: Run = run): Keychain { const line = `add-generic-password -U -s ${service} -a ${account} -l ${quoted(`Tether ${origin}`)} -w ${password}\n`; const done = exec("security", ["-i"], line); // Only the status: security may echo the command line, and with it the secret. - if (done.status !== 0) return `security exited ${done.status ?? "timeout"}`; + if (done.status !== 0) return `security ${ended(done)}`; return readBack(keychain, origin, secret); }, delete: (origin) => { @@ -78,7 +76,7 @@ export function secretToolKeychain(service: string, exec: Run = run): Keychain { // secret-tool exits 1 quietly when nothing matches, and says why when it cannot ask. if (done.status === 1 && done.stderr.trim() === "") return undefined; throw new KeychainUnavailable( - `the Secret Service keyring did not answer (${done.status ?? "timeout"})`, + `the Secret Service keyring did not answer (secret-tool ${ended(done)})`, ); }, set: (origin, secret) => { @@ -90,7 +88,7 @@ export function secretToolKeychain(service: string, exec: Run = run): Keychain { .trim() .replace(/\n[\s\S]*/, "") .slice(0, 200); - return `secret-tool exited ${done.status ?? "timeout"}${why ? `: ${why}` : ""}`; + return `secret-tool ${ended(done)}${why ? `: ${why}` : ""}`; } return readBack(keychain, origin, secret); }, diff --git a/src/client/private-file.ts b/src/client/private-file.ts new file mode 100644 index 0000000..979fb41 --- /dev/null +++ b/src/client/private-file.ts @@ -0,0 +1,102 @@ +import { + closeSync, + constants, + fchmodSync, + fstatSync, + ftruncateSync, + lstatSync, + openSync, + readSync, + rmSync, + writeSync, +} from "node:fs"; + +/** Zero on Windows, which has no O_NOFOLLOW; `refuseLink` checks there instead. */ +const NOFOLLOW = constants.O_NOFOLLOW ?? 0; + +/** Throws when `file` is a symbolic link: Tether never writes or chmods through one. */ +function refuseLink(file: string): void { + let link = false; + try { + link = lstatSync(file).isSymbolicLink(); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + if (link) { + throw new Error(`${file} is a symbolic link; Tether does not write through one. Remove it.`); + } +} + +/** + * Opens `file` with `flags` and never through a symbolic link: O_NOFOLLOW makes the open itself + * fail on one, and the lstat check names the file (and stands in on Windows). + */ +function openOwn(file: string, flags: number, mode?: number): number { + refuseLink(file); + try { + return openSync(file, flags | NOFOLLOW, mode); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ELOOP") refuseLink(file); + throw error; + } +} + +function writeAll(fd: number, content: string | Uint8Array): void { + const bytes = typeof content === "string" ? Buffer.from(content, "utf8") : content; + let done = 0; + while (done < bytes.length) done += writeSync(fd, bytes, done, bytes.length - done, done); +} + +/** + * Creates `file` fresh, readable only by the user, and writes `content` to it. Whatever was at the + * path is removed first, a symbolic link as a link, so a stale temporary file cannot block a write + * or redirect it; the exclusive create then refuses anything put there in between. + */ +export function createPrivate(file: string, content: string | Uint8Array): void { + rmSync(file, { force: true }); + const fd = openOwn(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600); + try { + fchmodSync(fd, 0o600); + writeAll(fd, content); + } finally { + closeSync(fd); + } +} + +/** Makes an existing `file` readable only by the user; refuses a symbolic link. */ +export function makePrivate(file: string): void { + const fd = openOwn(file, constants.O_RDONLY); + try { + fchmodSync(fd, 0o600); + } finally { + closeSync(fd); + } +} + +/** + * Keeps the last `keep` bytes of `file`, from the first whole line in them, once it is larger than + * `max` bytes. Cut in place on one descriptor, never through a symbolic link, and left readable + * only by the user. A missing file is left alone. + */ +export function cutToTail(file: string, max: number, keep: number): void { + let fd: number; + try { + fd = openOwn(file, constants.O_RDWR); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + throw error; + } + try { + const size = fstatSync(fd).size; + if (size <= max) return; + const tail = Buffer.alloc(keep); + readSync(fd, tail, 0, keep, size - keep); + // Start on a whole line: the first one in the tail is most likely cut. + const kept = tail.subarray(tail.indexOf(0x0a) + 1); + ftruncateSync(fd, 0); + writeAll(fd, kept); + fchmodSync(fd, 0o600); + } finally { + closeSync(fd); + } +} diff --git a/src/client/run.ts b/src/client/run.ts index 9d3d474..8c43dbd 100644 --- a/src/client/run.ts +++ b/src/client/run.ts @@ -1,10 +1,15 @@ import { spawnSync } from "node:child_process"; -/** What a program did: its exit status (null when it could not start or timed out) and output. */ +/** + * What a program did: its exit status (null when it could not start, timed out or was killed), + * its output, and, when it has no status, the spawn error code and the signal that ended it. + */ export interface Ran { status: number | null; stdout: string; stderr: string; + error?: string; + signal?: string; } /** Runs a program. `input` goes to its stdin: secrets travel there, never in argv, where `ps` shows them. */ @@ -16,5 +21,21 @@ export const run: Run = (command, args, input) => { encoding: "utf8", timeout: 15_000, }); - return { status: done.status, stdout: done.stdout ?? "", stderr: done.stderr ?? "" }; + const error = (done.error as NodeJS.ErrnoException | undefined)?.code; + return { + status: done.status, + stdout: done.stdout ?? "", + stderr: done.stderr ?? "", + ...(error ? { error } : {}), + ...(done.signal ? { signal: done.signal } : {}), + }; }; + +/** How a program ended, for a message: "exited 2", "timed out", "could not run" or "was stopped". */ +export function ended(done: Ran): string { + if (done.status !== null) return `exited ${done.status}`; + // A timeout also names the signal spawnSync sent, so it is checked first. + if (done.error === "ETIMEDOUT") return "timed out"; + if (done.error) return "could not run"; + return done.signal ? `was stopped (${done.signal})` : "was stopped"; +} diff --git a/src/client/store.ts b/src/client/store.ts index c003da8..c010e7c 100644 --- a/src/client/store.ts +++ b/src/client/store.ts @@ -10,12 +10,12 @@ import { renameSync, rmSync, statSync, - writeFileSync, } from "node:fs"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { type Keychain, KeychainUnavailable } from "./keychain.ts"; import { type Cap, DEFAULT_POLICY, type Policy, parsePolicy, type Usage } from "./policy.ts"; +import { createPrivate, cutToTail } from "./private-file.ts"; /** A paired app as stored on disk. `credential` is the device credential: a secret. */ export interface AppRecord { @@ -123,6 +123,10 @@ export class Store { return JSON.parse(readFileSync(this.path(name), "utf8")); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + // The parser's message quotes the text around the error, which can be part of a credential. + if (error instanceof SyntaxError) { + throw new Error(`${this.path(name)} could not be read (invalid JSON)`); + } throw new Error(`${this.path(name)} could not be read: ${(error as Error).message}`); } } @@ -138,8 +142,7 @@ export class Store { private write(name: string, value: unknown): void { this.makeHome(); const temp = this.path(`.${name}.${process.pid}.tmp`); - writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }); - chmodSync(temp, 0o600); + createPrivate(temp, `${JSON.stringify(value, null, 2)}\n`); renameSync(temp, this.path(name)); } @@ -251,7 +254,7 @@ export class Store { if (statSync(file).size > TASK_LOG_TRIM_BYTES) { const kept = this.taskLog(TASK_LOG_KEEP).map((entry) => JSON.stringify(entry)); const temp = this.path(`.tasks.jsonl.${process.pid}.tmp`); - writeFileSync(temp, `${kept.join("\n")}\n`, { mode: 0o600 }); + createPrivate(temp, `${kept.join("\n")}\n`); renameSync(temp, file); } } @@ -262,25 +265,7 @@ export class Store { * writing at the new end of the same file. */ trimServiceLog(): void { - const file = this.path("service.log"); - let size: number; - try { - size = statSync(file).size; - } catch { - return; - } - if (size <= SERVICE_LOG_MAX_BYTES) return; - const tail = Buffer.alloc(SERVICE_LOG_KEEP_BYTES); - const fd = openSync(file, "r"); - try { - readSync(fd, tail, 0, tail.length, size - tail.length); - } finally { - closeSync(fd); - } - // Start on a whole line: the first one in the tail is most likely cut. - const kept = tail.subarray(tail.indexOf(0x0a) + 1); - writeFileSync(file, kept, { mode: 0o600 }); - chmodSync(file, 0o600); + cutToTail(this.path("service.log"), SERVICE_LOG_MAX_BYTES, SERVICE_LOG_KEEP_BYTES); } /** The last `limit` finished tasks, oldest first; a line that does not parse is skipped. */ From bcd9ec97f711710e4193a8c2b8bf2554bbc41db1 Mon Sep 17 00:00:00 2001 From: parsilver Date: Mon, 16 Nov 2026 07:21:54 +0700 Subject: [PATCH 3/3] refactor: write private files whole with writeFileSync, test the edges Mutation testing showed the hand-rolled write loop added nothing over writeFileSync on a descriptor, and that a real spawn failure and a tail with no whole line were untested. AGENTS.md names the new module. --- AGENTS.md | 2 ++ src/client/private-file.ts | 24 +++++++----------------- test/run.test.ts | 8 +++++--- test/store.test.ts | 8 ++++++++ 4 files changed, 22 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c08442e..5c9a5d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,6 +36,8 @@ Guide for anyone (human or agent) changing this repository. The product spec is - `src/cli/`: the `tether` command, `doctor.ts` and the background service (`service.ts`). - `src/client/keychain.ts`: the OS keychain for device credentials; `store.ts` falls back to the 0600 file. +- `src/client/private-file.ts`: every write and chmod of a file only the user may read + (credentials, state, service files, `service.log`); none of them follows a symbolic link. - `src/protocol/schemas.ts` imports each schema: a compiled binary reads nothing from disk, so a new schema file must be imported there too (a test fails until it is). - `test/fake-app/`: an in-memory app server that implements the protocol, for tests. diff --git a/src/client/private-file.ts b/src/client/private-file.ts index 979fb41..e95c755 100644 --- a/src/client/private-file.ts +++ b/src/client/private-file.ts @@ -8,7 +8,7 @@ import { openSync, readSync, rmSync, - writeSync, + writeFileSync, } from "node:fs"; /** Zero on Windows, which has no O_NOFOLLOW; `refuseLink` checks there instead. */ @@ -28,23 +28,12 @@ function refuseLink(file: string): void { } /** - * Opens `file` with `flags` and never through a symbolic link: O_NOFOLLOW makes the open itself - * fail on one, and the lstat check names the file (and stands in on Windows). + * Opens `file` with `flags` and never through a symbolic link: the lstat check names the file + * (and stands in on Windows), and O_NOFOLLOW still fails the open on a link put there since. */ function openOwn(file: string, flags: number, mode?: number): number { refuseLink(file); - try { - return openSync(file, flags | NOFOLLOW, mode); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ELOOP") refuseLink(file); - throw error; - } -} - -function writeAll(fd: number, content: string | Uint8Array): void { - const bytes = typeof content === "string" ? Buffer.from(content, "utf8") : content; - let done = 0; - while (done < bytes.length) done += writeSync(fd, bytes, done, bytes.length - done, done); + return openSync(file, flags | NOFOLLOW, mode); } /** @@ -57,7 +46,7 @@ export function createPrivate(file: string, content: string | Uint8Array): void const fd = openOwn(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600); try { fchmodSync(fd, 0o600); - writeAll(fd, content); + writeFileSync(fd, content); } finally { closeSync(fd); } @@ -94,7 +83,8 @@ export function cutToTail(file: string, max: number, keep: number): void { // Start on a whole line: the first one in the tail is most likely cut. const kept = tail.subarray(tail.indexOf(0x0a) + 1); ftruncateSync(fd, 0); - writeAll(fd, kept); + // Reads at a position leave the descriptor's offset at 0, where this write starts. + writeFileSync(fd, kept); fchmodSync(fd, 0o600); } finally { closeSync(fd); diff --git a/test/run.test.ts b/test/run.test.ts index 46eb336..4483ad6 100644 --- a/test/run.test.ts +++ b/test/run.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { run } from "../src/client/run.ts"; +import { ended, run } from "../src/client/run.ts"; describe("run", () => { it("passes input on stdin and returns the status and both outputs", () => { @@ -12,7 +12,9 @@ describe("run", () => { }); }); - it("reports a program that cannot start with a null status", () => { - expect(run("/no/such/program", []).status).toBeNull(); + it("reports a program that cannot start with a null status, as one that could not run", () => { + const done = run("/no/such/program", []); + expect(done.status).toBeNull(); + expect(ended(done)).toBe("could not run"); }); }); diff --git a/test/store.test.ts b/test/store.test.ts index ebf8214..9937cff 100644 --- a/test/store.test.ts +++ b/test/store.test.ts @@ -90,6 +90,14 @@ describe("the service log", () => { expect(statSync(file).mode & 0o777).toBe(0o600); }); + it("empties a log whose kept part holds no whole line", () => { + const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); + const file = join(store.home, "service.log"); + writeFileSync(file, `${"y".repeat(5_000_001)}\n`); + store.trimServiceLog(); + expect(readFileSync(file, "utf8")).toBe(""); + }); + it("leaves a log at or under the limit, and a missing one, alone", () => { const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); store.trimServiceLog();