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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 6 additions & 6 deletions src/cli/service.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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)}`);
}

Expand All @@ -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)
Expand Down Expand Up @@ -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)}`]);
Expand Down
12 changes: 5 additions & 7 deletions src/client/keychain.ts
Original file line number Diff line number Diff line change
@@ -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 {}
Expand Down Expand Up @@ -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);
Expand All @@ -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) => {
Expand All @@ -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) => {
Expand All @@ -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);
},
Expand Down
92 changes: 92 additions & 0 deletions src/client/private-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import {
closeSync,
constants,
fchmodSync,
fstatSync,
ftruncateSync,
lstatSync,
openSync,
readSync,
rmSync,
writeFileSync,
} 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: 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);
return openSync(file, flags | NOFOLLOW, mode);
}

/**
* 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);
writeFileSync(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);
// Reads at a position leave the descriptor's offset at 0, where this write starts.
writeFileSync(fd, kept);
fchmodSync(fd, 0o600);
} finally {
closeSync(fd);
}
}
25 changes: 23 additions & 2 deletions src/client/run.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand All @@ -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";
}
31 changes: 8 additions & 23 deletions src/client/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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}`);
}
}
Expand All @@ -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));
}

Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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. */
Expand Down
21 changes: 19 additions & 2 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down Expand Up @@ -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 () => {
Expand Down
34 changes: 33 additions & 1 deletion test/keychain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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\)/,
);
});

Expand All @@ -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();
Expand Down
Loading
Loading