From d6a7f5f7f3924c63da782569a83c163fb84978ad Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 19:10:00 +0530 Subject: [PATCH 1/6] [hooks] Harden the privileged service install Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the /opt copy of the daemon) now reaches root as bytes on stdin. Root writes them to a hidden mktemp file beside the destination, checks their SHA-256 against the digest on its command line, and only then sets the mode and renames the file into place. The daemon binary is read by the CLI, as the user, with O_NOFOLLOW and O_NONBLOCK; a symbolic link there is refused. sudo and every program it runs are named by absolute path from /usr/bin, /bin, /usr/sbin and /sbin (src/hooks/system-command.ts) and start with a minimal environment, the credential prompt included. The needs_root recipe runs every write through the same script with each file's digest and names sudo and its programs the same way. Files it carries inline go through a single-quoted printf rather than a here-document, so an interactive shell's history expansion cannot touch them, and the macOS recipe carries the plist itself instead of a placeholder. The printed uninstall, status and restart commands use the same absolute paths. FAILPROOFAI_LAUNCHD_DIR redirects the LaunchDaemons directory for tests, like FAILPROOFAI_SYSTEMD_DIR. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 12 + .../hooks/daemon-privileged-install.test.ts | 565 ++++++++++++++++++ __tests__/hooks/daemon-service.test.ts | 27 +- __tests__/hooks/system-command.test.ts | 87 +++ __tests__/hooks/uninstall-cli.test.ts | 16 +- src/hooks/cloud-enrollment-cli.ts | 3 +- src/hooks/daemon-service.ts | 380 +++++++++--- src/hooks/manager.ts | 3 +- src/hooks/system-command.ts | 76 +++ src/hooks/uninstall-cli.ts | 18 +- 10 files changed, 1067 insertions(+), 120 deletions(-) create mode 100644 __tests__/hooks/daemon-privileged-install.test.ts create mode 100644 __tests__/hooks/system-command.test.ts create mode 100644 src/hooks/system-command.ts diff --git a/CLAUDE.md b/CLAUDE.md index 18a2e9a89..db6684311 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -956,6 +956,18 @@ Three consequences, all handled explicitly rather than assumed: anything; when it fails, the install writes nothing and returns the exact commands to run, classified as `needs_root`. `sudo -n`, never interactive — a password prompt fired from under the wizard's TUI is unreadable. +- **Root is never handed a path the user can write.** Every file written as root (unit, + plist, Codex's `/etc/codex/config.toml`, the `/opt` binary) goes through + `writePrivilegedFile()`: the bytes go to `PRIVILEGED_INSTALL_SCRIPT` on stdin with their + SHA-256 as an argument, and root checks them in a hidden `mktemp` file beside the + destination before it sets the mode and renames. The binary is read by the CLI, as the + user, with `O_NOFOLLOW`. No `sudo install `: root installs + only bytes it has verified. The printed `needs_root` recipe carries the same digests. +- **Nor a program found through PATH.** `sudo` and everything it runs come from + `src/hooks/system-command.ts`, which looks only in `/usr/bin`, `/bin`, `/usr/sbin` and + `/sbin` and starts them with `privilegedEnv()` (root's PATH, the caller's locale). PATH + is the user's, and macOS sudoers sets no `secure_path`. Printed commands use + `sudoCommandLine()` for the same reason. - **A system unit has no login environment.** `resolveWorkerCommand()` uses `process.execPath`, not a bare `node`: the single most common Node install is nvm, whose binary lives under `~/.nvm/versions/node/*/bin` and is on no system PATH. A bare `node` diff --git a/__tests__/hooks/daemon-privileged-install.test.ts b/__tests__/hooks/daemon-privileged-install.test.ts new file mode 100644 index 000000000..988f0d785 --- /dev/null +++ b/__tests__/hooks/daemon-privileged-install.test.ts @@ -0,0 +1,565 @@ +// @vitest-environment node +/** + * Everything root writes for the daemon service (the systemd unit, the launchd + * plist, the copy of the binary under /opt) must reach root as bytes, never as + * a path the user can write, and must land exactly as failproofai produced it; + * and sudo, and every program it runs, must be named by absolute path rather + * than found through PATH. + * + * The install tests stand in for sudo with a mock that runs each privileged + * command as this (unprivileged) user, after changing any file under the + * user's home or temp directory that the command names: root must be handed + * none, so none of those changes may reach what is installed. No real sudo + * runs anywhere in this file, and nothing outside its scratch directory is + * written. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { execFileSync as realExecFileSync, type ExecFileSyncOptions } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir, userInfo } from "node:os"; +import { basename, dirname, resolve } from "node:path"; +import { installedBinaryPath } from "../../src/hooks/daemon-download"; +import { logsDir } from "../../src/hooks/fp-home"; +import { shellQuote } from "../../src/hooks/shell-quote"; + +vi.mock("../../src/hooks/hook-logger", () => ({ + hookLogWarn: vi.fn(), + hookLogInfo: vi.fn(), +})); + +type DaemonService = typeof import("../../src/hooks/daemon-service"); +type SystemCommand = typeof import("../../src/hooks/system-command"); + +const isRoot = typeof process.getuid === "function" && process.getuid() === 0; +const sha256 = (bytes: Buffer | string) => createHash("sha256").update(bytes).digest("hex"); + +/** What the managed daemon binary holds. */ +const BINARY = "#!/bin/sh\nexec sleep infinity\n"; +/** Some file other than the ones failproofai wrote. */ +const OTHER = "the content of some other file\n"; +/** What a file failproofai wrote is changed to. */ +const CHANGED = "changed after failproofai wrote it\n"; +const WORKER = "'/usr/bin/node' '/pkg/dist/worker.mjs'"; +const CLI = "'/usr/bin/node' '/pkg/dist/cli.mjs'"; + +const ENV_KEYS = [ + "PATH", + "HOME", + "TMPDIR", + "SUDO_ASKPASS", + "FAILPROOFAI_HOME", + "FAILPROOFAI_SYSTEMD_DIR", + "FAILPROOFAI_SYSTEM_BIN_DIR", + "FAILPROOFAI_LAUNCHD_DIR", + "FAILPROOFAI_DAEMON_BINARY", + "FAILPROOFAI_PACKAGE_ROOT", + "FAILPROOFAI_WORKER_CMD", + "FAILPROOFAI_CLI_CMD", + "FAILPROOFAI_NO_DOWNLOAD", +] as const; + +/** Every regular file under `dir`, recursively. */ +function filesUnder(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const path = resolve(dir, entry.name); + if (entry.isDirectory()) return filesUnder(path); + return entry.isFile() ? [path] : []; + }); +} + +/** Imported where used, so a test that does not need it still runs on its own. */ +async function systemCommand(): Promise { + return import("../../src/hooks/system-command"); +} + +// Meaningless as root, where nothing goes through sudo. +describe.skipIf(isRoot)("privileged service install: root is handed bytes, never a user path", () => { + const originalPlatform = process.platform; + const saved = new Map(); + let scratch: string; + /** The user's home and temp directory: anything running as the user can change them. */ + let home: string; + let userTmp: string; + /** Stands in for the directories only root can write. */ + let rootDir: string; + let otherPath: string; + + function setPlatform(platform: NodeJS.Platform) { + Object.defineProperty(process, "platform", { value: platform }); + } + + beforeEach(() => { + for (const key of ENV_KEYS) saved.set(key, process.env[key]); + scratch = mkdtempSync(resolve(tmpdir(), "fpai-priv-install-")); + // A space in the home, as on many Macs: every path in a recipe is quoted. + home = resolve(scratch, "first last"); + userTmp = resolve(scratch, "user-tmp"); + rootDir = resolve(scratch, "root"); + for (const dir of [home, userTmp, resolve(rootDir, "systemd"), resolve(rootDir, "LaunchDaemons")]) { + mkdirSync(dir, { recursive: true }); + } + otherPath = resolve(rootDir, "other"); + writeFileSync(otherPath, OTHER); + + process.env.HOME = home; + process.env.TMPDIR = userTmp; + process.env.FAILPROOFAI_HOME = resolve(home, ".failproofai"); + process.env.FAILPROOFAI_SYSTEMD_DIR = resolve(rootDir, "systemd"); + process.env.FAILPROOFAI_SYSTEM_BIN_DIR = resolve(rootDir, "opt"); + process.env.FAILPROOFAI_LAUNCHD_DIR = resolve(rootDir, "LaunchDaemons"); + process.env.FAILPROOFAI_WORKER_CMD = WORKER; + process.env.FAILPROOFAI_CLI_CMD = CLI; + // Nothing here may reach the network. + process.env.FAILPROOFAI_NO_DOWNLOAD = "1"; + delete process.env.FAILPROOFAI_DAEMON_BINARY; + delete process.env.FAILPROOFAI_PACKAGE_ROOT; + vi.resetModules(); + }); + + afterEach(() => { + vi.doUnmock("node:child_process"); + vi.doUnmock("../../src/hooks/system-command"); + vi.resetModules(); + setPlatform(originalPlatform); + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(scratch, { recursive: true, force: true }); + }); + + /** The binary failproofai installed for this version, under the user's home. */ + function writeManagedBinary(): string { + const path = installedBinaryPath(); + expect(path.startsWith(`${home}/`)).toBe(true); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, BINARY, { mode: 0o755 }); + return path; + } + + /** The arguments of a privileged command that name something under the user's home or temp directory. */ + function userWritable(argv: readonly string[]): string[] { + return argv.filter((arg) => arg.startsWith(`${home}/`) || arg.startsWith(`${userTmp}/`)); + } + + interface RootCall { + /** How sudo itself was named. */ + sudo: string; + /** What it was asked to run, `-n` taken off. */ + argv: string[]; + input?: Buffer; + env?: NodeJS.ProcessEnv; + } + type BeforeRoot = (call: RootCall, options: ExecFileSyncOptions) => void; + + /** + * Stands in for sudo: runs each privileged command as this user, after + * `beforeRoot` has had its turn. `elevate: false` is a machine where sudo + * cannot run anything; `warmUp: true` one where it can only after `sudo -v`. + */ + function mockSudo(opts: { beforeRoot?: BeforeRoot; elevate?: boolean; warmUp?: boolean } = {}): RootCall[] { + const calls: RootCall[] = []; + let warm = !opts.warmUp; + vi.doMock("node:child_process", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + execFileSync: (cmd: string, args: readonly string[] = [], options: ExecFileSyncOptions = {}) => { + if (basename(cmd) === "sudo") { + const argv = args[0] === "-n" ? args.slice(1) : [...args]; + const call: RootCall = { + sudo: cmd, + argv, + input: Buffer.isBuffer(options.input) ? options.input : undefined, + env: options.env, + }; + calls.push(call); + if (opts.elevate === false) throw new Error("sudo: a password is required"); + if (argv[0] === "-v") { + warm = true; + return Buffer.alloc(0); + } + if (!warm) throw new Error("sudo: a password is required"); + if (argv.length === 1 && basename(argv[0]) === "true") return Buffer.alloc(0); + opts.beforeRoot?.(call, options); + switch (basename(argv[0])) { + case "install": + case "mv": + case "rm": + case "sh": + return actual.execFileSync(argv[0], argv.slice(1), options); + case "systemctl": + case "restorecon": + return Buffer.alloc(0); + case "launchctl": + return Buffer.from(argv[1] === "print" ? "state = running\n" : ""); + default: + throw new Error(`unexpected privileged command: ${argv.join(" ")}`); + } + } + if (basename(cmd) === "systemctl" && args[0] === "is-active") return Buffer.from("active\n"); + throw new Error(`unexpected command: ${cmd} ${args.join(" ")}`); + }, + }; + }); + return calls; + } + + /** + * A Linux runner has no launchctl, and the install looks for it only in + * root's own directories: stand one in at its macOS path. It never runs — + * the sudo mock answers for it. + */ + function standInLaunchctl(): void { + vi.doMock("../../src/hooks/system-command", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + requireSystemCommand: (name: string) => + name === "launchctl" ? (actual.systemCommandPath(name) ?? "/bin/launchctl") : actual.requireSystemCommand(name), + }; + }); + } + + /** + * Before each privileged command, every file under the user's home or temp + * directory that the command names is changed: replaced by a link to OTHER, + * or rewritten. + */ + function changeUserFiles(how: "link" | "rewrite"): BeforeRoot { + return (call) => { + for (const path of userWritable(call.argv)) { + if (!existsSync(path) || !lstatSync(path).isFile()) continue; + if (how === "link") { + unlinkSync(path); + symlinkSync(otherPath, path); + } else { + writeFileSync(path, CHANGED); + } + } + }; + } + + async function loadService(): Promise { + return import("../../src/hooks/daemon-service"); + } + + const changes: ("link" | "rewrite")[] = ["link", "rewrite"]; + describe.each(changes)("while user files are changed (%s)", (how) => { + it("linux: the unit and the /opt binary are exactly what failproofai produced", async () => { + setPlatform("linux"); + const managed = writeManagedBinary(); + const calls = mockSudo({ beforeRoot: changeUserFiles(how) }); + const svc = await loadService(); + const target = svc.systemBinaryTarget(managed)!; + expect(target.startsWith(`${rootDir}/`)).toBe(true); + + expect(await svc.installDaemonService()).toEqual({ installed: true }); + + // Root was handed nothing under the user's home or temp directory. + expect(calls.flatMap((call) => userWritable(call.argv))).toEqual([]); + expect(readFileSync(target, "utf8")).toBe(BINARY); + expect(statSync(target).mode & 0o777).toBe(0o755); + const unitPath = svc.daemonServiceFilePath()!; + expect(readFileSync(unitPath, "utf8")).toBe(svc.systemdUnitContents(target, WORKER, CLI)); + expect(statSync(unitPath).mode & 0o777).toBe(0o644); + // Nothing staged is left beside either. + expect(readdirSync(dirname(unitPath))).toEqual([basename(unitPath)]); + expect(readdirSync(dirname(target))).toEqual([basename(target)]); + expect(filesUnder(rootDir).filter((p) => p !== otherPath).map((p) => readFileSync(p, "utf8"))).not.toContain( + OTHER, + ); + }, 20_000); + + it("macOS: the plist is exactly what failproofai rendered, and launchd loads it after it is in place", async () => { + setPlatform("darwin"); + const managed = writeManagedBinary(); + standInLaunchctl(); + const calls = mockSudo({ beforeRoot: changeUserFiles(how) }); + const svc = await loadService(); + + expect(await svc.installDaemonService()).toEqual({ installed: true }); + + expect(calls.flatMap((call) => userWritable(call.argv))).toEqual([]); + const plistPath = svc.daemonServiceFilePath()!; + expect(plistPath).toBe( + resolve(rootDir, "LaunchDaemons", `ai.failproof.failproofaid.${userInfo().username}.plist`), + ); + expect(readFileSync(plistPath, "utf8")).toBe(svc.launchdPlistContents(managed, logsDir(), WORKER, CLI)); + expect(statSync(plistPath).mode & 0o777).toBe(0o644); + expect(readdirSync(dirname(plistPath))).toEqual([basename(plistPath)]); + const write = calls.findIndex((call) => basename(call.argv[0]) === "sh" && call.argv.includes(plistPath)); + const load = calls.findIndex((call) => basename(call.argv[0]) === "launchctl" && call.argv[1] === "load"); + expect(write).toBeGreaterThanOrEqual(0); + expect(load).toBeGreaterThan(write); + }, 20_000); + }); + + it("linux: refuses a daemon binary that is a symbolic link, and copies nothing", async () => { + setPlatform("linux"); + const managed = installedBinaryPath(); + mkdirSync(dirname(managed), { recursive: true }); + symlinkSync(otherPath, managed); + mockSudo(); + const svc = await loadService(); + + const result = await svc.installDaemonService(); + + expect(result.installed).toBe(false); + expect(result.reason).toMatch(/symbolic link/); + expect(filesUnder(rootDir).filter((p) => p !== otherPath).map((p) => readFileSync(p, "utf8"))).not.toContain( + OTHER, + ); + expect(existsSync(svc.daemonServiceFilePath()!)).toBe(false); + }); + + it("never runs a sudo or a program that PATH finds first, credential warm-up included, and gives sudo root's PATH", async () => { + setPlatform("linux"); + writeManagedBinary(); + // Programs of the same names first on PATH, in a directory the user owns. + // Each leaves a mark if it ever runs. + const planted = resolve(home, ".local", "bin"); + const marks = resolve(scratch, "marks"); + mkdirSync(planted, { recursive: true }); + mkdirSync(marks); + const names = ["sudo", "install", "mv", "rm", "sh", "systemctl", "restorecon", "true", "mktemp", "cat", "chmod", "sha256sum"]; + for (const name of names) { + writeFileSync(resolve(planted, name), `#!/bin/sh\n: > '${resolve(marks, name)}'\nexit 1\n`, { mode: 0o755 }); + } + process.env.PATH = `${planted}:${process.env.PATH ?? ""}`; + process.env.SUDO_ASKPASS = resolve(planted, "sudo"); + const calls = mockSudo({ warmUp: true }); + const sys = await systemCommand(); + const svc = await loadService(); + + // The wizard's warm-up: the one place the user types their password. + expect(svc.primeElevation()).toBe(true); + expect(calls.some((call) => call.argv[0] === "-v")).toBe(true); + expect(await svc.installDaemonService()).toEqual({ installed: true }); + + expect(readdirSync(marks)).toEqual([]); + for (const call of calls) { + expect(call.sudo).toBe(sys.systemCommandPath("sudo")); + if (call.argv[0] !== "-v") expect(sys.SYSTEM_BIN_DIRS).toContain(dirname(call.argv[0])); + expect(call.env?.PATH).toBe(sys.SYSTEM_PATH); + expect(call.env).not.toHaveProperty("SUDO_ASKPASS"); + } + }, 20_000); + + const alterations: [string, (bytes: Buffer) => Buffer][] = [ + ["appended to", (bytes) => Buffer.concat([bytes, Buffer.from(CHANGED)])], + ["substituted for", () => Buffer.from(CHANGED)], + ]; + describe.each(alterations)("bytes %s what failproofai sent on the way to root", (_what, alter) => { + it("are refused, and the destination keeps what it had", async () => { + const dest = resolve(rootDir, "systemd", "x.service"); + writeFileSync(dest, "previous\n"); + mockSudo({ + beforeRoot: (_call, options) => { + if (Buffer.isBuffer(options.input)) options.input = alter(options.input); + }, + }); + const { writePrivilegedFile } = await loadService(); + + expect(() => writePrivilegedFile(dest, "[Unit]\nDescription=x\n")).toThrow(/do not match sha256/); + expect(readFileSync(dest, "utf8")).toBe("previous\n"); + expect(readdirSync(dirname(dest))).toEqual(["x.service"]); + }); + }); + + it("refuses a relative destination or a mode that is not octal, before anything runs", async () => { + const calls = mockSudo(); + const { writePrivilegedFile } = await loadService(); + expect(() => writePrivilegedFile("etc/x.service", "x\n")).toThrow(/relative path/); + expect(() => writePrivilegedFile(resolve(rootDir, "x"), "x\n", "u+s")).toThrow(/mode/); + expect(calls).toEqual([]); + }); + + describe("the manual recipe printed when sudo is not available", () => { + /** + * A stand-in sudo, at a path of its own: it runs the command as this user, + * and does nothing for the service managers. + */ + function fakeSudo(): string { + const dir = resolve(scratch, "fake-bin"); + mkdirSync(dir, { recursive: true }); + const path = resolve(dir, "sudo"); + writeFileSync( + path, + [ + "#!/bin/sh", + "while [ $# -gt 0 ]; do case $1 in -*) shift ;; *) break ;; esac; done", + 'case "${1##*/}" in systemctl|launchctl|restorecon) exit 0 ;; esac', + 'exec "$@"', + "", + ].join("\n"), + { mode: 0o755 }, + ); + return path; + } + + async function printedRecipe(platform: NodeJS.Platform): Promise<{ recipe: string; svc: DaemonService }> { + setPlatform(platform); + mockSudo({ elevate: false }); + const svc = await loadService(); + const result = await svc.installDaemonService(); + expect(result.installed).toBe(false); + expect(result.reason).toMatch(/root privileges are required/); + const marker = "To install by hand, run:\n"; + expect(result.reason).toContain(marker); + return { recipe: result.reason!.slice(result.reason!.indexOf(marker) + marker.length), svc }; + } + + /** + * Runs the recipe as pasted, with the stand-in in place of every sudo it + * names. Refuses to run one that still names a real sudo. + */ + async function runRecipe(recipe: string): Promise<{ status: number; stderr: string }> { + const sudo = (await systemCommand()).sudoPath(); + const stand = fakeSudo(); + const runnable = sudo.startsWith("/") ? recipe.split(`${sudo} `).join(`${stand} `) : recipe; + if (sudo.startsWith("/")) expect(runnable).not.toContain(sudo); + try { + realExecFileSync("/bin/sh", ["-c", runnable], { + env: { ...process.env, PATH: `${dirname(stand)}:/usr/bin:/bin` }, + stdio: ["ignore", "ignore", "pipe"], + timeout: 30_000, + }); + return { status: 0, stderr: "" }; + } catch (err) { + const e = err as { status?: number | null; stderr?: Buffer }; + return { status: e.status ?? -1, stderr: e.stderr?.toString() ?? "" }; + } + } + + it("linux: installs exactly the binary and unit the install would, run as printed", async () => { + const managed = writeManagedBinary(); + const { recipe, svc } = await printedRecipe("linux"); + const sys = await systemCommand(); + const target = svc.systemBinaryTarget(managed)!; + // Rendered before the recipe runs, as the recipe's own copy was. + const unit = svc.systemdUnitContents(target, WORKER, CLI); + + // Root reads the binary from stdin; the user's shell opens it. + expect(recipe).toContain(`< '${managed}'`); + expect(recipe).not.toMatch(/sudo (install -m|tee|cp) /); + // sudo and the programs it runs, by absolute path. + expect(recipe).toContain(sys.sudoCommandLine("systemctl", "daemon-reload")); + + expect(await runRecipe(recipe)).toEqual({ status: 0, stderr: "" }); + expect(readFileSync(target, "utf8")).toBe(BINARY); + expect(statSync(target).mode & 0o777).toBe(0o755); + expect(readFileSync(svc.daemonServiceFilePath()!, "utf8")).toBe(unit); + }); + + it("linux: stops before any unit is written when the binary changed after it was printed", async () => { + const managed = writeManagedBinary(); + const { recipe, svc } = await printedRecipe("linux"); + + writeFileSync(managed, CHANGED); + const { status, stderr } = await runRecipe(recipe); + + expect(status).not.toBe(0); + expect(stderr).toMatch(/do not match sha256/); + expect(existsSync(svc.systemBinaryTarget(managed)!)).toBe(false); + expect(existsSync(svc.daemonServiceFilePath()!)).toBe(false); + }); + + it("macOS: carries the plist inline and installs exactly it, run as printed", async () => { + const managed = writeManagedBinary(); + const { recipe, svc } = await printedRecipe("darwin"); + const plist = svc.launchdPlistContents(managed, logsDir(), WORKER, CLI); + + // Single-quoted, never a here-document: zsh (the macOS default) expands + // `!` in a here-document's body, and the plist has ` { + /** Whether root's fixed PATH has `tool`. */ + function has(tool: string): boolean { + try { + realExecFileSync("/bin/sh", ["-c", `PATH=/usr/bin:/bin:/usr/sbin:/sbin; command -v ${tool}`], { + stdio: "ignore", + }); + return true; + } catch { + return false; + } + } + + // Each later branch is forced by naming the tools before it as ones no + // system has: Linux runners have all three, macOS has the last two. + const NONE = "command -v failproofai-no-such-tool"; + const variants: [string, (script: string) => string][] = [ + ["sha256sum", (s) => s], + ["shasum", (s) => s.replace("command -v sha256sum", NONE)], + ["openssl", (s) => s.replace("command -v sha256sum", NONE).replace("command -v shasum", NONE)], + ]; + + let dir: string; + beforeEach(() => { + dir = mkdtempSync(resolve(tmpdir(), "fpai-priv-script-")); + }); + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + function run(script: string, dest: string, digest: string, mode: string, input: Buffer): void { + realExecFileSync("/bin/sh", ["-c", script, "failproofai-install", dest, digest, mode], { + input, + stdio: ["pipe", "ignore", "pipe"], + }); + } + + for (const [tool, edit] of variants) { + it.skipIf(!has(tool))(`with ${tool}: installs exactly the bytes, with the mode, and refuses any others`, async () => { + const { PRIVILEGED_INSTALL_SCRIPT } = await import("../../src/hooks/daemon-service"); + const script = edit(PRIVILEGED_INSTALL_SCRIPT); + if (tool !== "sha256sum") expect(script).not.toContain("command -v sha256sum"); + // Binary-safe: a NUL, a lone CR, no trailing newline. + const bytes = Buffer.from([0, 1, 2, 255, 13, 10, 65]); + const dest = resolve(dir, "file"); + + run(script, dest, sha256(bytes), "0640", bytes); + expect(readFileSync(dest).equals(bytes)).toBe(true); + expect(statSync(dest).mode & 0o777).toBe(0o640); + + expect(() => + run(script, resolve(dir, "other"), sha256(bytes), "0640", Buffer.concat([bytes, Buffer.from("x")])), + ).toThrow(); + expect(() => run(script, dest, sha256(bytes), "0640", Buffer.from("x"))).toThrow(); + // The refused writes left nothing behind, and the earlier file as it was. + expect(readdirSync(dir)).toEqual(["file"]); + expect(readFileSync(dest).equals(bytes)).toBe(true); + }); + } + + it("never contains a single quote, so a recipe can quote it verbatim", async () => { + const { PRIVILEGED_INSTALL_SCRIPT } = await import("../../src/hooks/daemon-service"); + expect(PRIVILEGED_INSTALL_SCRIPT).not.toContain("'"); + }); +}); diff --git a/__tests__/hooks/daemon-service.test.ts b/__tests__/hooks/daemon-service.test.ts index 6dd7c5967..931b16dba 100644 --- a/__tests__/hooks/daemon-service.test.ts +++ b/__tests__/hooks/daemon-service.test.ts @@ -1,10 +1,12 @@ // @vitest-environment node import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir, userInfo } from "node:os"; -import { dirname, resolve } from "node:path"; +import { basename, dirname, resolve } from "node:path"; import { binDir } from "../../src/hooks/fp-home"; +import { sudoCommandLine, sudoPath, systemCommandPath } from "../../src/hooks/system-command"; import { startedAtFromMonotonic, waitForDaemonRunning } from "../../src/hooks/daemon-service"; import * as svc from "../../src/hooks/daemon-service"; import { version as pkgVersion } from "../../package.json"; @@ -415,7 +417,8 @@ describe("hooks/daemon-service", () => { vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string) => { - if (cmd === "sudo") throw new Error("sudo: a password is required"); + // By absolute path now (system-command.ts), never a bare `sudo`. + if (basename(cmd) === "sudo") throw new Error("sudo: a password is required"); throw new Error(`nothing else should run before elevation succeeds, but got: ${cmd}`); }, })); @@ -466,7 +469,8 @@ describe("hooks/daemon-service", () => { vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string, args: string[] = []) => { - const line = (cmd === "sudo" ? args.slice(1) : [cmd, ...args]).join(" "); + const [program, ...rest] = basename(cmd) === "sudo" ? args.slice(1) : [cmd, ...args]; + const line = [basename(program), ...rest].join(" "); ran.push(line); if (opts.failOn && line.startsWith(opts.failOn)) throw new Error("sudo: a password is required"); return ""; @@ -593,7 +597,8 @@ describe("hooks/daemon-service", () => { vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string) => { - if (cmd === "sudo") throw new Error("sudo: a password is required"); + // By absolute path now (system-command.ts), never a bare `sudo`. + if (basename(cmd) === "sudo") throw new Error("sudo: a password is required"); throw new Error(`nothing else should run before elevation succeeds, but got: ${cmd}`); }, })); @@ -607,9 +612,15 @@ describe("hooks/daemon-service", () => { expect(result.installed).toBe(false); expect(path).toContain(" "); - expect(result.reason).toContain(`sudo install -d -m 0755 '${dirname(target)}'`); - expect(result.reason).toContain(`sudo install -m 0755 '${path}' '${target}'`); - expect(result.reason).toContain(`sudo restorecon -R '${daemonSystemBinaryDir()}'`); + expect(result.reason).toContain(sudoCommandLine("install", "-d", "-m", "0755", `'${dirname(target)}'`)); + // The binary reaches root on stdin, from a `<` the user's own shell + // opens, with the digest root checks it against. + const digest = createHash("sha256").update("#!/bin/sh\n").digest("hex"); + expect(result.reason).toContain(`failproofai_install '${target}' ${digest} 0755 < '${path}'`); + // Only where root's own directories have restorecon (every SELinux system). + if (systemCommandPath("restorecon")) { + expect(result.reason).toContain(sudoCommandLine("restorecon", "-R", `'${daemonSystemBinaryDir()}'`)); + } } finally { vi.doUnmock("node:child_process"); vi.resetModules(); @@ -1523,7 +1534,7 @@ describe("refreshDaemonToCliVersion", () => { expect(result.lines).toEqual([ `✕ failproofaid ${version} was not installed: root privileges are required. The previous daemon is untouched.`, - " Run `sudo -v` and then `failproofai update` again.", + ` Run \`${sudoPath()} -v\` and then \`failproofai update\` again.`, ]); expect(result.lines.join("\n")).not.toMatch(/failproofai config|\[Unit\]|sudo tee/); }); diff --git a/__tests__/hooks/system-command.test.ts b/__tests__/hooks/system-command.test.ts new file mode 100644 index 000000000..ac09f3e61 --- /dev/null +++ b/__tests__/hooks/system-command.test.ts @@ -0,0 +1,87 @@ +// @vitest-environment node +/** + * Programs failproofai runs as root are found in root's own directories, never + * through PATH, and start with root's PATH rather than the caller's + * environment. + */ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { + SYSTEM_BIN_DIRS, + SYSTEM_PATH, + privilegedEnv, + requireSystemCommand, + sudoCommandLine, + sudoPath, + systemCommandPath, +} from "../../src/hooks/system-command"; + +const KEYS = ["PATH", "SUDO_ASKPASS", "BASH_ENV", "LANG", "TERM"] as const; + +describe("system-command", () => { + const saved = new Map(); + let planted: string; + + beforeEach(() => { + for (const key of KEYS) saved.set(key, process.env[key]); + // Programs a process running as the user put first on PATH. + planted = mkdtempSync(resolve(tmpdir(), "fpai-planted-")); + for (const name of ["sudo", "sh", "failproofai-only-on-path"]) { + writeFileSync(resolve(planted, name), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + } + process.env.PATH = `${planted}:${process.env.PATH ?? ""}`; + }); + + afterEach(() => { + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(planted, { recursive: true, force: true }); + }); + + it("finds a program only in root's own directories, never through PATH", () => { + expect(SYSTEM_BIN_DIRS).toEqual(["/usr/bin", "/bin", "/usr/sbin", "/sbin"]); + expect(SYSTEM_PATH).toBe("/usr/bin:/bin:/usr/sbin:/sbin"); + + const sh = systemCommandPath("sh"); + expect(sh).not.toBeNull(); + expect(SYSTEM_BIN_DIRS).toContain(dirname(sh!)); + const sudo = systemCommandPath("sudo"); + if (sudo) expect(SYSTEM_BIN_DIRS).toContain(dirname(sudo)); + expect(sudo).not.toBe(resolve(planted, "sudo")); + + // Only on PATH: not found at all, rather than found there. + expect(systemCommandPath("failproofai-only-on-path")).toBeNull(); + expect(() => requireSystemCommand("failproofai-only-on-path")).toThrow(/not found in \/usr\/bin, \/bin/); + // A name, never a path. + expect(systemCommandPath("../bin/sh")).toBeNull(); + expect(systemCommandPath(`${planted}/sudo`)).toBeNull(); + }); + + it("starts privileged commands with root's PATH and the caller's locale, nothing else", () => { + process.env.SUDO_ASKPASS = resolve(planted, "sudo"); + process.env.BASH_ENV = resolve(planted, "sh"); + process.env.LANG = "C.UTF-8"; + process.env.TERM = "xterm-256color"; + + const env = privilegedEnv(); + + expect(env.PATH).toBe(SYSTEM_PATH); + expect(env.LANG).toBe("C.UTF-8"); + expect(env.TERM).toBe("xterm-256color"); + expect(env).not.toHaveProperty("SUDO_ASKPASS"); + expect(env).not.toHaveProperty("BASH_ENV"); + expect(Object.keys(env).every((key) => ["PATH", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES"].includes(key))).toBe( + true, + ); + }); + + it("prints sudo and the program by absolute path, and the bare name where root has none", () => { + expect(sudoCommandLine("sh", "-c", "'true'")).toBe(`${sudoPath()} ${systemCommandPath("sh")} -c 'true'`); + expect(sudoCommandLine("failproofai-only-on-path", "-x")).toBe(`${sudoPath()} failproofai-only-on-path -x`); + expect(sudoPath()).toBe(systemCommandPath("sudo") ?? "sudo"); + }); +}); diff --git a/__tests__/hooks/uninstall-cli.test.ts b/__tests__/hooks/uninstall-cli.test.ts index 795d0808e..b161e3520 100644 --- a/__tests__/hooks/uninstall-cli.test.ts +++ b/__tests__/hooks/uninstall-cli.test.ts @@ -15,6 +15,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { sudoCommandLine } from "../../src/hooks/system-command"; /** Call order across the mocked modules, which is the actual thing under test. */ const calls: string[] = []; @@ -224,8 +225,9 @@ describe("hooks/uninstall-cli", () => { expect(res.exitCode).toBe(1); const out = res.lines.join("\n"); expect(out).toMatch(/still there/); - expect(out).toMatch(/sudo systemctl disable --now failproofaid@tester\.service/); - expect(out).toMatch(/sudo rm -f/); + // sudo and each program by absolute path, as failproofai runs them itself. + expect(out).toContain(sudoCommandLine("systemctl", "disable", "--now", "failproofaid@tester.service")); + expect(out).toContain(sudoCommandLine("rm", "-f")); // Enforcement is still off even though cleanup was incomplete. expect(calls[0]).toBe("setDaemonConfigured(false)"); }); @@ -417,11 +419,11 @@ describe("hooks/uninstall-cli — who decides the daemon's fate", () => { expect(at).toBeGreaterThanOrEqual(0); expect(res.lines.slice(at + 1, at + 7)).toEqual([ " Remove it as root:", - " sudo systemctl disable --now failproofaid@tester.service", - ` sudo rm -f '${servicePath}'`, - " sudo systemctl daemon-reload", + ` ${sudoCommandLine("systemctl", "disable", "--now", "failproofaid@tester.service")}`, + ` ${sudoCommandLine("rm", "-f", `'${servicePath}'`)}`, + ` ${sudoCommandLine("systemctl", "daemon-reload")}`, // The root-owned copy the unit ran, outside HOME for SELinux. - ` sudo rm -rf '${stagedDir}'`, + ` ${sudoCommandLine("rm", "-rf", `'${stagedDir}'`)}`, " Check it with systemctl status failproofaid@tester", ]); }); @@ -480,7 +482,7 @@ describe("hooks/uninstall-cli — a staged daemon binary with no unit", () => { const res = await runUninstallCommand({ yes: true }); expect(res.exitCode).toBe(1); - expect(res.lines.join("\n")).toContain(`sudo rm -rf '${stagedDir}'`); + expect(res.lines.join("\n")).toContain(sudoCommandLine("rm", "-rf", `'${stagedDir}'`)); expect(res.lines.join("\n")).not.toContain("Removed the failproofaid binary"); }); }); diff --git a/src/hooks/cloud-enrollment-cli.ts b/src/hooks/cloud-enrollment-cli.ts index 61f9039c1..8b83ed3ff 100644 --- a/src/hooks/cloud-enrollment-cli.ts +++ b/src/hooks/cloud-enrollment-cli.ts @@ -138,7 +138,8 @@ function daemonWarning(status: ReturnType): string[] ? [" A daemon is running and policy is being pulled."] : ["! No daemon is answering, so nothing is being pulled right now."]), " Its service state needs elevation to read, so it is not shown above.", - ...(check ? [` Check it with: sudo ${check}`] : []), + // The command carries its own sudo: a LaunchDaemon cannot be read without it. + ...(check ? [` Check it with: ${check}`] : []), ]; } // A daemon started by hand is invisible to the service manager but is diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index d977676a5..abbb85362 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -8,25 +8,35 @@ * relationship it already has with `manager.ts`'s `installHooks()`. */ import { HEALTH_PROBE_SOURCE } from "./health-probe"; +import { createHash } from "node:crypto"; import { + closeSync, + constants as fsConstants, existsSync, + fstatSync, mkdirSync, - mkdtempSync, + openSync, readFileSync, readdirSync, realpathSync, statSync, - writeFileSync, unlinkSync, - rmSync, } from "node:fs"; -import { homedir, tmpdir, userInfo } from "node:os"; +import { homedir, userInfo } from "node:os"; import { dirname, resolve } from "node:path"; import { execFileSync } from "node:child_process"; import { hookLogWarn } from "./hook-logger"; import { downloadFailproofaidBinary, installFromNpmPackage, installedBinaryPath } from "./daemon-download"; import { logsDir } from "./fp-home"; import { shellQuote, shellQuotedWords } from "./shell-quote"; +import { + SYSTEM_PATH, + privilegedEnv, + requireSystemCommand, + sudoCommandLine, + sudoPath, + systemCommandPath, +} from "./system-command"; import { version } from "../../package.json"; import { readVersionFile, updateConfig, writeVersionFile } from "./fp-config"; @@ -564,8 +574,16 @@ function selinuxEnabled(): boolean { * unit should start. Privileged; throws when the copy fails, which the caller * reports as a failed install before any unit is written. * - * Staged under a temp name and renamed into place, so a reinstall of the same - * version never writes into the file a running daemon was started from. + * The bytes are read here, as the user, and handed to root on stdin by + * {@link writePrivilegedFile}; root is never given the binary's path, which is + * in a directory the user owns. Root installs exactly the bytes read here, and + * reading them as the user reaches nothing the user could not read anyway. + * O_NOFOLLOW refuses a link outright: the managed binary is a regular file + * failproofai wrote itself. + * + * Staged under a temp name and renamed into place by the privileged write, so + * a reinstall of the same version never writes into the file a running daemon + * was started from. * * `restorecon` afterwards, because a new file inherits the label of the * directory it is created in, not the one the policy assigns to its path: the @@ -575,20 +593,9 @@ function selinuxEnabled(): boolean { function stageSystemBinary(binaryPath: string): string { const target = systemBinaryTarget(binaryPath); if (!target) return binaryPath; - const dir = systemBinaryDir(); - const staging = `${target}.${process.pid}.tmp`; - runPrivileged("install", ["-d", "-m", "0755", dir]); - try { - runPrivileged("install", ["-m", "0755", binaryPath, staging]); - runPrivileged("mv", ["-f", staging, target]); - } catch (err) { - try { - runPrivileged("rm", ["-f", staging]); - } catch { - /* best-effort */ - } - throw err; - } + const bytes = readRegularFileNoFollow(binaryPath); + runPrivileged("install", ["-d", "-m", "0755", systemBinaryDir()]); + writePrivilegedFile(target, bytes, "0755"); if (selinuxEnabled()) { const root = systemBinaryRoot(); try { @@ -645,8 +652,17 @@ function launchdLabel(user: string = serviceUser()): string { return `ai.failproof.failproofaid.${user}`; } +/** + * `/Library/LaunchDaemons`, redirectable for tests ONLY, like the systemd unit + * directory: it lets a Linux runner drive the macOS install end to end against + * a scratch directory, with launchctl stubbed, instead of not at all. + */ +function launchdDaemonDir(): string { + return process.env.FAILPROOFAI_LAUNCHD_DIR || "/Library/LaunchDaemons"; +} + function launchdPlistPath(user: string = serviceUser()): string { - return `/Library/LaunchDaemons/${launchdLabel(user)}.plist`; + return resolve(launchdDaemonDir(), `${launchdLabel(user)}.plist`); } /** The pre-1.0.0-beta.1 LaunchAgent. */ @@ -660,7 +676,7 @@ function legacyLaunchAgentPlistPath(): string { * leaving it would leave two daemons racing for one socket. */ function legacySharedLaunchDaemonPath(): string { - return "/Library/LaunchDaemons/ai.failproof.failproofaid.plist"; + return resolve(launchdDaemonDir(), "ai.failproof.failproofaid.plist"); } /** @@ -683,7 +699,7 @@ export function daemonStatusCommand(): string | null { if (!isDaemonSupportedPlatform()) return null; return process.platform === "linux" ? `systemctl status ${systemdUnitName()}` - : `sudo launchctl print system/${launchdLabel()}`; + : sudoCommandLine("launchctl", "print", `system/${launchdLabel()}`); } /** @@ -698,8 +714,8 @@ export function daemonStatusCommand(): string | null { export function daemonRestartCommand(): string | null { if (!isDaemonSupportedPlatform()) return null; return process.platform === "linux" - ? `sudo systemctl restart ${systemdUnitName()}` - : `sudo launchctl kickstart -k system/${launchdLabel()}`; + ? sudoCommandLine("systemctl", "restart", systemdUnitName()) + : sudoCommandLine("launchctl", "kickstart", "-k", `system/${launchdLabel()}`); } /** @@ -719,12 +735,20 @@ export function daemonRestartCommand(): string | null { * * `stdio: "inherit"` so the prompt and the typed password go straight to the * real terminal. The timeout is generous because a human is typing. + * + * sudo by absolute path, like every privileged command here (see + * `system-command.ts`): this is where the user types their password, so it is + * the system's own sudo, whatever PATH says. */ export function primeElevation(): boolean { if (typeof process.getuid === "function" && process.getuid() === 0) return true; if (canElevate()) return true; // NOPASSWD, or already primed try { - execFileSync("sudo", ["-v"], { stdio: "inherit", timeout: SUDO_PROMPT_TIMEOUT_MS }); + execFileSync(requireSystemCommand("sudo"), ["-v"], { + stdio: "inherit", + timeout: SUDO_PROMPT_TIMEOUT_MS, + env: privilegedEnv(), + }); return canElevate(); } catch { // Wrong password, no sudo rights, or the user pressed ctrl-C. All of them @@ -745,13 +769,29 @@ export function primeElevation(): boolean { export function canElevate(): boolean { if (typeof process.getuid === "function" && process.getuid() === 0) return true; try { - execFileSync("sudo", ["-n", "true"], { stdio: "ignore", timeout: SERVICE_CMD_TIMEOUT_MS }); + execFileSync(requireSystemCommand("sudo"), ["-n", requireSystemCommand("true")], { + stdio: "ignore", + timeout: SERVICE_CMD_TIMEOUT_MS, + env: privilegedEnv(), + }); return true; } catch { return false; } } +/** + * The command and arguments that run `command args` as root: the program + * itself when this process already is root, through `sudo -n` otherwise. Both + * by absolute path from root's own directories, never through PATH (see + * `system-command.ts`). Throws when either cannot be found there. + */ +function elevatedCommand(command: string, args: string[]): [string, string[]] { + const program = command.startsWith("/") ? command : requireSystemCommand(command); + if (typeof process.getuid === "function" && process.getuid() === 0) return [program, args]; + return [requireSystemCommand("sudo"), ["-n", program, ...args]]; +} + /** * Runs one privileged command, non-interactively. * @@ -761,36 +801,133 @@ export function canElevate(): boolean { * instead — it keeps working exactly as it did, on the in-process path. */ export function runPrivileged(command: string, args: string[]): void { - const root = typeof process.getuid === "function" && process.getuid() === 0; - const [cmd, argv] = root ? [command, args] : ["sudo", ["-n", command, ...args]]; - execFileSync(cmd, argv, { stdio: "ignore", timeout: SERVICE_CMD_TIMEOUT_MS }); + const [cmd, argv] = elevatedCommand(command, args); + execFileSync(cmd, argv, { stdio: "ignore", timeout: SERVICE_CMD_TIMEOUT_MS, env: privilegedEnv() }); +} + +/** The shell root runs the install script with. Absolute: no PATH lookup picks it. */ +const SYSTEM_SH = "/bin/sh"; + +/** + * How long one privileged write may take. Bounded like every other privileged + * call, but well above SERVICE_CMD_TIMEOUT_MS: the daemon binary is tens of + * megabytes, streamed through sudo. + */ +const PRIVILEGED_WRITE_TIMEOUT_MS = 60_000; + +/** + * What root runs to put a file in place: + * `sh -c SCRIPT failproofai-install `, with the + * file's bytes on stdin. Exported so tests can run it. + * + * The rules it exists for: root installs only bytes it has verified, and never + * opens a path the user can write. The bytes arrive on stdin, not as a file + * staged where the user could reach it. A pipe is not a private channel either, + * so root hashes what it received, in a file only root can reach, against the + * digest on its own command line, and only then sets the mode and renames the + * file over the destination. + * + * - PATH is fixed, like every privileged command's (see `system-command.ts`): + * the programs root runs here are root's own. + * - The temp file comes from `mktemp`, which creates it exclusively and never + * through an existing link, beside the destination in a directory only root + * can write, so the rename that publishes it is atomic. It is hidden, so a + * leftover is never read as a unit by systemd or as a job by launchd. + * - The digest tool is whichever the OS has: coreutils `sha256sum` on Linux, + * `shasum -a 256` on macOS, `openssl` as a last resort. + * - There is no single quote in it, so the manual recipe quotes it verbatim. + */ +export const PRIVILEGED_INSTALL_SCRIPT = [ + "set -eu", + `PATH=${SYSTEM_PATH}`, + "export PATH", + "umask 077", + "dest=$1 want=$2 mode=$3 tmp=", + 'cleanup() { [ -z "$tmp" ] || rm -f "$tmp"; }', + "trap cleanup EXIT", + 'trap "exit 1" HUP INT TERM', + 'tmp=$(mktemp "${dest%/*}/.${dest##*/}.XXXXXX")', + 'cat >"$tmp"', + 'if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum <"$tmp")', + 'elif command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 <"$tmp")', + 'else got=$(openssl dgst -sha256 -r <"$tmp")', + "fi", + 'if [ "${got%% *}" != "$want" ]; then', + ' echo "refusing to install $dest: the bytes received do not match sha256 $want" >&2', + " exit 1", + "fi", + 'chmod "$mode" "$tmp"', + 'mv -f "$tmp" "$dest"', + "tmp=", + "", +].join("\n"); + +function sha256Hex(bytes: Buffer): string { + return createHash("sha256").update(bytes).digest("hex"); +} + +/** + * Installs a file into a root-owned location with `mode`, because the caller + * is not root and cannot write there directly. The bytes go to root on stdin + * and are checked against their digest before they land; see + * {@link PRIVILEGED_INSTALL_SCRIPT}. The file is renamed over `destination` + * only once its mode is set, so it is never briefly world-writable and never + * half-written: a failed write leaves the previous file in place. + */ +export function writePrivilegedFile(destination: string, contents: string | Buffer, mode = "0644"): void { + // Both are command-line words for root, never shell text, but a relative + // path would land somewhere unintended and chmod also takes symbolic modes. + if (!destination.startsWith("/")) throw new Error(`refusing to write a relative path as root: ${destination}`); + if (!/^[0-7]{3,4}$/.test(mode)) throw new Error(`refusing to write ${destination} with mode ${JSON.stringify(mode)}`); + const bytes = typeof contents === "string" ? Buffer.from(contents, "utf8") : contents; + const args = ["-c", PRIVILEGED_INSTALL_SCRIPT, "failproofai-install", destination, sha256Hex(bytes), mode]; + try { + const [cmd, argv] = elevatedCommand(SYSTEM_SH, args); + execFileSync(cmd, argv, { + input: bytes, + stdio: ["pipe", "ignore", "pipe"], + timeout: PRIVILEGED_WRITE_TIMEOUT_MS, + env: privilegedEnv(), + }); + } catch (err) { + // The script's own refusal, or sudo's, is on stderr. The error's message + // would otherwise lead with the whole script. + const e = err as { stderr?: Buffer | string; code?: string; status?: number | null }; + const why = + e.stderr?.toString().trim() || + e.code || + (typeof e.status === "number" ? `exit status ${e.status}` : err instanceof Error ? err.message : String(err)); + throw new Error(`could not write ${destination} as root: ${why}`); + } } /** - * Installs a file into a root-owned location via a temp file, because the - * caller is not root and cannot write there directly. `install -m` sets the - * mode in the same step, so the file is never briefly world-writable. + * Reads a regular file, refusing a symbolic link or anything else in its + * place. Used for the one file whose bytes go to root: what root installs is + * then exactly what this process read, as the user. */ -export function writePrivilegedFile(destination: string, contents: string, mode = "0644"): void { - // mkdtempSync, not a name built from pid + timestamp in the shared tmpdir. - // That name is guessable, and `writeFileSync` follows a symlink already - // sitting at the path — so on a multi-user box another local user could - // pre-create it and have `install` copy content they control into - // /etc/systemd/system as root. mkdtemp gives a 0700 directory with a name - // they cannot predict, so there is nothing to pre-create. - const stagingDir = mkdtempSync(resolve(tmpdir(), "failproofaid-stage-")); - const staging = resolve(stagingDir, "service-definition"); +function readRegularFileNoFollow(path: string): Buffer { + let fd: number; + try { + // O_NONBLOCK so that a FIFO in its place is opened and refused below, + // rather than blocking this process until something writes to it. + fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + // ELOOP is how O_NOFOLLOW reports a link (EMLINK on FreeBSD). + if (code === "ELOOP" || code === "EMLINK") { + throw new Error( + `refusing to copy ${path}: it is a symbolic link. To run a binary of your own, ` + + "set FAILPROOFAI_DAEMON_BINARY to its real path", + ); + } + throw err; + } try { - writeFileSync(staging, contents, "utf8"); - // Installed beside the destination and renamed over it: `install` onto - // the destination unlinks the old file before copying, so a copy that - // failed part-way left no definition (launchd then cannot load the job - // at boot). A rename within one directory is atomic. - const sibling = `${destination}.failproofai-new`; - runPrivileged("install", ["-m", mode, staging, sibling]); - runPrivileged("mv", ["-f", sibling, destination]); + if (!fstatSync(fd).isFile()) throw new Error(`refusing to copy ${path}: it is not a regular file`); + return readFileSync(fd); } finally { - rmSync(stagingDir, { recursive: true, force: true }); + closeSync(fd); } } @@ -1009,45 +1146,98 @@ export interface DaemonInstallResult { reason?: string; } +/** The shell function the manual recipe defines once and sends every root write through. */ +const RECIPE_WRITE_FN = "failproofai_install"; + +/** + * The recipe step that writes `contents` to `destination` as root, carried + * inline and checked against its digest by the same script the automatic + * install runs. + * + * A single-quoted `printf`, not a here-document: an interactive shell expands + * history (`!`) in a here-document's body (zsh, the macOS default, does) but + * never inside single quotes, and the plist's `/dev/null || true; }`, - ] - : []; - return [ - ...stage, - `sudo tee ${systemdUnitPath()} <<'EOF'\n${systemdUnitContents(target ?? binaryPath, workerCmd, cliCmd)}EOF`, - "sudo systemctl daemon-reload", - `sudo systemctl enable ${systemdUnitName()}`, + const steps: string[] = []; + if (target) { + const digest = sha256Hex(readRegularFileNoFollow(binaryPath)); + steps.push( + // Quoted: a home directory may hold a space, and an unquoted path + // splits into words that stop this `&&`-chained recipe before the + // unit is ever written. + sudoCommandLine("install", "-d", "-m", "0755", shellQuote(systemBinaryDir())), + `${RECIPE_WRITE_FN} ${shellQuote(target)} ${digest} 0755 < ${shellQuote(binaryPath)}`, + ); + // Only where root's directories have it: SELinux systems always do, and a + // bare name would leave sudo to find one. + if (systemCommandPath("restorecon")) { + steps.push(`{ ${sudoCommandLine("restorecon", "-R", shellQuote(systemBinaryRoot()))} 2>/dev/null || true; }`); + } + } + steps.push( + recipeWriteInline(systemdUnitPath(), systemdUnitContents(target ?? binaryPath, workerCmd, cliCmd), "0644"), + sudoCommandLine("systemctl", "daemon-reload"), + sudoCommandLine("systemctl", "enable", systemdUnitName()), // `restart`, not `enable --now`, for the reason the install path gives: // `--now` does nothing to an already-active unit, and these commands are // handed to someone whose daemon may well be running — an upgrade is the // most likely reason they are reading them. - `sudo systemctl restart ${systemdUnitName()}`, - ]; + sudoCommandLine("systemctl", "restart", systemdUnitName()), + ); + return renderRecipe(steps); + } + // The same order as the install: the log directory the plist names, the + // plist, then unload and load, since a plain `load` of a label launchd + // already has is a no-op. + const plistPath = launchdPlistPath(); + const logDir = logsDir(); + return renderRecipe([ + `mkdir -p ${shellQuote(logDir)}`, + recipeWriteInline(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd), "0644"), + `{ ${sudoCommandLine("launchctl", "unload", shellQuote(plistPath))} 2>/dev/null || true; }`, + sudoCommandLine("launchctl", "load", "-w", shellQuote(plistPath)), + ]); +} + +/** The manual-install half of the needs-root reason. Never throws. */ +function manualInstallSteps(binaryPath: string, workerCmd: string | null, cliCmd: string | null): string { + try { + return `To install by hand, run:\n${daemonInstallRecipe(binaryPath, workerCmd, cliCmd)}`; + } catch (err) { + return `No manual steps could be prepared: ${err instanceof Error ? err.message : String(err)}.`; } - return [ - `sudo tee ${launchdPlistPath()} < the plist failproofai config would write`, - `sudo launchctl load -w ${launchdPlistPath()}`, - ]; } /** @@ -1106,8 +1296,8 @@ export async function installDaemonService(): Promise { reason: "root privileges are required to install the failproofaid system service, and sudo credentials were not available. " + "Re-run `failproofai config` and approve the sudo prompt — do NOT run the CLI itself under sudo, which would " + - "configure root's account instead of yours. To install by hand: " + - daemonInstallCommands(binaryPath, workerCmd, cliCmd).join(" && "), + "configure root's account instead of yours. " + + manualInstallSteps(binaryPath, workerCmd, cliCmd), }; } @@ -1750,9 +1940,9 @@ export async function ensureDaemonServiceCurrent(): Promise // What to put back if this goes wrong, and from which point. Set BEFORE the // step that can leave the machine changed, not after it succeeds: on Linux - // `writePrivilegedFile` is an `install` copy straight onto the unit path, so - // a failure part-way through leaves a truncated unit behind, and on macOS - // the unload has already stopped the daemon before anything is written. + // the new unit is in place the moment `writePrivilegedFile` renames it there, + // whatever happens to the reload after it, and on macOS the unload has + // already stopped the daemon before anything is written. let previous: string | null = null; try { @@ -1929,7 +2119,7 @@ export async function refreshDaemonToCliVersion( lines: needsRoot ? [ `✕ failproofaid ${version} was not installed: root privileges are required. The previous daemon is untouched.`, - " Run `sudo -v` and then `failproofai update` again.", + ` Run \`${sudoPath()} -v\` and then \`failproofai update\` again.`, ] : [ `✕ failproofaid ${version} could not be installed: ${(result.reason ?? "unknown reason").replace(/\.$/, "")}. ` + @@ -2149,16 +2339,12 @@ export function daemonServiceStatus(): DaemonServiceStatus { // running daemon read as dead, and the wizard then demanded a password to // unload and reload a service that was fine. if (!root && !canElevate()) return "unknown"; - const args = ["print", `system/${launchdLabel()}`]; - const out = root - ? execFileSync("launchctl", args, { - stdio: ["ignore", "pipe", "ignore"], - timeout: SERVICE_CMD_TIMEOUT_MS, - }).toString() - : execFileSync("sudo", ["-n", "launchctl", ...args], { - stdio: ["ignore", "pipe", "ignore"], - timeout: SERVICE_CMD_TIMEOUT_MS, - }).toString(); + const [cmd, argv] = elevatedCommand("launchctl", ["print", `system/${launchdLabel()}`]); + const out = execFileSync(cmd, argv, { + stdio: ["ignore", "pipe", "ignore"], + timeout: SERVICE_CMD_TIMEOUT_MS, + env: privilegedEnv(), + }).toString(); // `state = running` is launchd's own wording; a loaded-but-dead job // prints `state = not running` and must not read as healthy. return /state\s*=\s*running/.test(out) ? "running" : "stopped"; diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index f147f3df5..1d2573f52 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -41,6 +41,7 @@ import type { ResolvedPack } from "./pack-manifest"; import { hasInstalledRegexPacks, readInstalledPacks } from "./pack-manifest"; import { packPolicyParamKey } from "./policy-evaluator"; import { probeDaemonPolicyEvaluation } from "./daemon-service"; +import { sudoPath } from "./system-command"; import { keepAgentSelectionTrue } from "./agent-selection"; import { INDENT, colorsEnabled, optsFor, printBlock, screenKit, type ScreenKitOpts } from "./tui"; @@ -1144,7 +1145,7 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al for (const line of screenKit(optsFor(process.stdout)).notice( "caution", `failproofai's Codex hooks are still in ${system.path}: ${system.reason}.\n` + - "Run `sudo -v`, then this command again.", + `Run \`${sudoPath()} -v\`, then this command again.`, )) { say(line); } diff --git a/src/hooks/system-command.ts b/src/hooks/system-command.ts new file mode 100644 index 000000000..9d411ec2f --- /dev/null +++ b/src/hooks/system-command.ts @@ -0,0 +1,76 @@ +/** + * How failproofai names the programs it runs as root: by absolute path, from + * root's own directories, with a minimal environment. Never through PATH. + * + * PATH and the rest of the caller's environment belong to the user: PATH + * routinely starts with directories the user can write (`~/.local/bin`, nvm's + * bin, Homebrew's prefix), and where sudoers sets no `secure_path` (macOS by + * default) sudo looks programs up in it too. Root's programs, and the sudo the + * user types their password into, come from root's own directories instead. + */ +import { accessSync, constants as fsConstants, statSync } from "node:fs"; + +/** Root's own program directories, in lookup order. */ +export const SYSTEM_BIN_DIRS: readonly string[] = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"]; + +/** The PATH every privileged command runs with. */ +export const SYSTEM_PATH = SYSTEM_BIN_DIRS.join(":"); + +/** + * The absolute path of a system program such as `sudo`, `systemctl`, + * `launchctl` or `install`, from {@link SYSTEM_BIN_DIRS} only, or null when + * none of them has it. + */ +export function systemCommandPath(name: string): string | null { + if (!/^[A-Za-z0-9._-]+$/.test(name)) return null; + for (const dir of SYSTEM_BIN_DIRS) { + const candidate = `${dir}/${name}`; + try { + if (!statSync(candidate).isFile()) continue; + accessSync(candidate, fsConstants.X_OK); + return candidate; + } catch { + // Not in this directory: try the next. + } + } + return null; +} + +/** {@link systemCommandPath}, or an error that says where it looked. */ +export function requireSystemCommand(name: string): string { + const path = systemCommandPath(name); + if (!path) throw new Error(`${name} was not found in ${SYSTEM_BIN_DIRS.join(", ")}`); + return path; +} + +/** The caller's settings that only shape how sudo's prompt and messages look. */ +const PASSED_THROUGH = ["TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES"] as const; + +/** + * The environment every privileged command starts with: root's PATH, plus the + * caller's terminal type and locale for sudo's own prompt. Nothing else of the + * caller's reaches sudo or what it runs: no PATH, no loader or shell variables, + * no `SUDO_ASKPASS` or `SUDO_PROMPT`. + */ +export function privilegedEnv(): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { PATH: SYSTEM_PATH }; + for (const key of PASSED_THROUGH) { + const value = process.env[key]; + if (value) env[key] = value; + } + return env; +} + +/** `sudo` as printed for someone to run: its absolute path, or the bare name where there is none. */ +export function sudoPath(): string { + return systemCommandPath("sudo") ?? "sudo"; +} + +/** + * A privileged command as printed for someone to run: `sudo` and the program + * by absolute path where root's directories have them, the bare names where + * they do not. `args` are pasted as given, so the caller quotes them. + */ +export function sudoCommandLine(command: string, ...args: string[]): string { + return [sudoPath(), systemCommandPath(command) ?? command, ...args].join(" "); +} diff --git a/src/hooks/uninstall-cli.ts b/src/hooks/uninstall-cli.ts index 9e58dc97d..011414203 100644 --- a/src/hooks/uninstall-cli.ts +++ b/src/hooks/uninstall-cli.ts @@ -49,6 +49,7 @@ import { listInstallableIds, getIntegration } from "./integrations"; import type { IntegrationType } from "./types"; import { removeHooks } from "./manager"; import { shellQuote } from "./shell-quote"; +import { sudoCommandLine } from "./system-command"; import { installedAgentSkillDirs, removeAgentSkill } from "./agent-skill"; import { CODEX_MANAGED_BEGIN, CODEX_MANAGED_END, codexSystemConfigPath, codexSystemHooksPresent } from "./codex-system-hooks"; import { optsFor, screenKit, type RenderOpts } from "./tui"; @@ -377,7 +378,7 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< } else if (found.stagedBinaryDir && existsSync(found.stagedBinaryDir)) { failures.push( `The failproofaid binary in ${found.stagedBinaryDir} is still there, most often because sudo was not available.` + - `\nRemove it as root:\n \`sudo rm -rf ${shellQuote(found.stagedBinaryDir)}\``, + `\nRemove it as root:\n \`${sudoCommandLine("rm", "-rf", shellQuote(found.stagedBinaryDir))}\``, ); } else if (found.serviceInstalled) { lines.push(kit.ok("Stopped and removed the failproofaid service.")); @@ -433,16 +434,21 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< * paths are quoted: these are pasted into a root shell, and an unquoted path * holding a space would make `rm -rf` remove something else. */ function manualServiceRemoval(servicePath: string): string[] { + // sudo and each program by absolute path, as failproofai runs them itself: + // see system-command.ts. if (process.platform === "darwin") { - return [`sudo launchctl unload -w ${shellQuote(servicePath)}`, `sudo rm -f ${shellQuote(servicePath)}`]; + return [ + sudoCommandLine("launchctl", "unload", "-w", shellQuote(servicePath)), + sudoCommandLine("rm", "-f", shellQuote(servicePath)), + ]; } const unit = servicePath.split("/").pop() ?? servicePath; const binDir = daemonSystemBinaryDir(); return [ - `sudo systemctl disable --now ${unit}`, - `sudo rm -f ${shellQuote(servicePath)}`, - `sudo systemctl daemon-reload`, - ...(binDir ? [`sudo rm -rf ${shellQuote(binDir)}`] : []), + sudoCommandLine("systemctl", "disable", "--now", unit), + sudoCommandLine("rm", "-f", shellQuote(servicePath)), + sudoCommandLine("systemctl", "daemon-reload"), + ...(binDir ? [sudoCommandLine("rm", "-rf", shellQuote(binDir))] : []), ]; } From 07f8b88137ef8a5a30d4583c2b38252e6b42648b Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 19:22:15 +0530 Subject: [PATCH 2/6] [hooks] Hold the staged daemon binary to its recorded digest The bytes root installs under /opt are now checked against the digest the build recorded for the managed binary (when it carries one), on the same read that hands them to root, and the needs_root recipe prints that digest. sudo keeps the caller's SSH agent socket and Kerberos credential cache, which some PAM setups authenticate with. Tests stand in for any of sudo, systemctl, launchctl or restorecon the test machine lacks. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +- .../hooks/daemon-privileged-install.test.ts | 48 +++++++++++++++---- __tests__/hooks/system-command.test.ts | 16 ++++--- src/hooks/daemon-service.ts | 23 ++++++++- src/hooks/system-command.ts | 23 +++++---- 5 files changed, 85 insertions(+), 29 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5fb27a4e8..24821a2f2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -965,8 +965,8 @@ Three consequences, all handled explicitly rather than assumed: only bytes it has verified. The printed `needs_root` recipe carries the same digests. - **Nor a program found through PATH.** `sudo` and everything it runs come from `src/hooks/system-command.ts`, which looks only in `/usr/bin`, `/bin`, `/usr/sbin` and - `/sbin` and starts them with `privilegedEnv()` (root's PATH, the caller's locale). PATH - is the user's, and macOS sudoers sets no `secure_path`. Printed commands use + `/sbin` and starts them with `privilegedEnv()` (root's PATH, the caller's locale and the + settings sudo authenticates with). PATH is the user's to change. Printed commands use `sudoCommandLine()` for the same reason. - **A system unit has no login environment.** `resolveWorkerCommand()` uses `process.execPath`, not a bare `node`: the single most common Node install is nvm, whose diff --git a/__tests__/hooks/daemon-privileged-install.test.ts b/__tests__/hooks/daemon-privileged-install.test.ts index 988f0d785..cd6bdb525 100644 --- a/__tests__/hooks/daemon-privileged-install.test.ts +++ b/__tests__/hooks/daemon-privileged-install.test.ts @@ -34,6 +34,7 @@ import { basename, dirname, resolve } from "node:path"; import { installedBinaryPath } from "../../src/hooks/daemon-download"; import { logsDir } from "../../src/hooks/fp-home"; import { shellQuote } from "../../src/hooks/shell-quote"; +import packageJson from "../../package.json"; vi.mock("../../src/hooks/hook-logger", () => ({ hookLogWarn: vi.fn(), @@ -132,6 +133,7 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never afterEach(() => { vi.doUnmock("node:child_process"); vi.doUnmock("../../src/hooks/system-command"); + vi.doUnmock("../../package.json"); vi.resetModules(); setPlatform(originalPlatform); for (const [key, value] of saved) { @@ -169,10 +171,15 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never * Stands in for sudo: runs each privileged command as this user, after * `beforeRoot` has had its turn. `elevate: false` is a machine where sudo * cannot run anything; `warmUp: true` one where it can only after `sudo -v`. + * `onElevate` runs at each `sudo -n true`, the check made just before the + * install starts copying. */ - function mockSudo(opts: { beforeRoot?: BeforeRoot; elevate?: boolean; warmUp?: boolean } = {}): RootCall[] { + function mockSudo( + opts: { beforeRoot?: BeforeRoot; elevate?: boolean; warmUp?: boolean; onElevate?: () => void } = {}, + ): RootCall[] { const calls: RootCall[] = []; let warm = !opts.warmUp; + standInSystemPrograms(); vi.doMock("node:child_process", async (importOriginal) => { const actual = await importOriginal(); return { @@ -193,7 +200,10 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never return Buffer.alloc(0); } if (!warm) throw new Error("sudo: a password is required"); - if (argv.length === 1 && basename(argv[0]) === "true") return Buffer.alloc(0); + if (argv.length === 1 && basename(argv[0]) === "true") { + opts.onElevate?.(); + return Buffer.alloc(0); + } opts.beforeRoot?.(call, options); switch (basename(argv[0])) { case "install": @@ -219,17 +229,20 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never } /** - * A Linux runner has no launchctl, and the install looks for it only in - * root's own directories: stand one in at its macOS path. It never runs — - * the sudo mock answers for it. + * The install looks programs up only in root's own directories, and a test + * machine may lack some: launchctl on Linux, systemctl on a Mac or in a + * container, sudo itself. Each of these the sudo mock answers for without + * running it, so where one is missing a path stands in for it. Programs the + * mock does run (install, mv, rm, sh) are always the machine's own. */ - function standInLaunchctl(): void { + function standInSystemPrograms(): void { + const answered = new Set(["sudo", "true", "systemctl", "launchctl", "restorecon"]); vi.doMock("../../src/hooks/system-command", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, requireSystemCommand: (name: string) => - name === "launchctl" ? (actual.systemCommandPath(name) ?? "/bin/launchctl") : actual.requireSystemCommand(name), + actual.systemCommandPath(name) ?? (answered.has(name) ? `/usr/bin/${name}` : actual.requireSystemCommand(name)), }; }); } @@ -287,7 +300,6 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never it("macOS: the plist is exactly what failproofai rendered, and launchd loads it after it is in place", async () => { setPlatform("darwin"); const managed = writeManagedBinary(); - standInLaunchctl(); const calls = mockSudo({ beforeRoot: changeUserFiles(how) }); const svc = await loadService(); @@ -326,6 +338,24 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never expect(existsSync(svc.daemonServiceFilePath()!)).toBe(false); }); + it("linux: installs under /opt only the binary bytes this build recorded, even if the file changes once checked", async () => { + setPlatform("linux"); + writeManagedBinary(); + // The digest a published build records for its own platform binary. + const arch = process.arch === "arm64" ? "arm64" : "x64"; + const manifest = { ...packageJson, failproofaidBinaries: { [`linux-${arch}`]: sha256(BINARY) } }; + vi.doMock("../../package.json", () => ({ ...manifest, default: manifest })); + // Checked once before the install starts copying, then changed. + mockSudo({ onElevate: () => writeFileSync(installedBinaryPath(), CHANGED) }); + const svc = await loadService(); + + const result = await svc.installDaemonService(); + + expect(result.installed).toBe(false); + expect(result.reason).toMatch(/expects [0-9a-f]{64}/); + expect(filesUnder(rootDir).filter((p) => p !== otherPath)).toEqual([]); + }); + it("never runs a sudo or a program that PATH finds first, credential warm-up included, and gives sudo root's PATH", async () => { setPlatform("linux"); writeManagedBinary(); @@ -352,7 +382,7 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never expect(readdirSync(marks)).toEqual([]); for (const call of calls) { - expect(call.sudo).toBe(sys.systemCommandPath("sudo")); + expect(call.sudo).toBe(sys.requireSystemCommand("sudo")); if (call.argv[0] !== "-v") expect(sys.SYSTEM_BIN_DIRS).toContain(dirname(call.argv[0])); expect(call.env?.PATH).toBe(sys.SYSTEM_PATH); expect(call.env).not.toHaveProperty("SUDO_ASKPASS"); diff --git a/__tests__/hooks/system-command.test.ts b/__tests__/hooks/system-command.test.ts index ac09f3e61..9b725d67c 100644 --- a/__tests__/hooks/system-command.test.ts +++ b/__tests__/hooks/system-command.test.ts @@ -18,7 +18,7 @@ import { systemCommandPath, } from "../../src/hooks/system-command"; -const KEYS = ["PATH", "SUDO_ASKPASS", "BASH_ENV", "LANG", "TERM"] as const; +const KEYS = ["PATH", "SUDO_ASKPASS", "BASH_ENV", "LANG", "TERM", "SSH_AUTH_SOCK", "KRB5CCNAME"] as const; describe("system-command", () => { const saved = new Map(); @@ -26,7 +26,7 @@ describe("system-command", () => { beforeEach(() => { for (const key of KEYS) saved.set(key, process.env[key]); - // Programs a process running as the user put first on PATH. + // Programs of the same names first on PATH. planted = mkdtempSync(resolve(tmpdir(), "fpai-planted-")); for (const name of ["sudo", "sh", "failproofai-only-on-path"]) { writeFileSync(resolve(planted, name), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); @@ -61,22 +61,26 @@ describe("system-command", () => { expect(systemCommandPath(`${planted}/sudo`)).toBeNull(); }); - it("starts privileged commands with root's PATH and the caller's locale, nothing else", () => { + it("starts privileged commands with root's PATH and what sudo itself uses, nothing else", () => { process.env.SUDO_ASKPASS = resolve(planted, "sudo"); process.env.BASH_ENV = resolve(planted, "sh"); process.env.LANG = "C.UTF-8"; process.env.TERM = "xterm-256color"; + // What PAM modules authenticate sudo with on some fleets. + process.env.SSH_AUTH_SOCK = "/run/user/1000/ssh-agent.socket"; + process.env.KRB5CCNAME = "KCM:"; const env = privilegedEnv(); expect(env.PATH).toBe(SYSTEM_PATH); expect(env.LANG).toBe("C.UTF-8"); expect(env.TERM).toBe("xterm-256color"); + expect(env.SSH_AUTH_SOCK).toBe("/run/user/1000/ssh-agent.socket"); + expect(env.KRB5CCNAME).toBe("KCM:"); expect(env).not.toHaveProperty("SUDO_ASKPASS"); expect(env).not.toHaveProperty("BASH_ENV"); - expect(Object.keys(env).every((key) => ["PATH", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES"].includes(key))).toBe( - true, - ); + const allowed = ["PATH", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "SSH_AUTH_SOCK", "KRB5CCNAME"]; + expect(Object.keys(env).every((key) => allowed.includes(key))).toBe(true); }); it("prints sudo and the program by absolute path, and the bare name where root has none", () => { diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index ecbf8b920..df70316f7 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -27,7 +27,9 @@ import { dirname, resolve } from "node:path"; import { execFileSync } from "node:child_process"; import { hookLogWarn } from "./hook-logger"; import { + binaryDigestMismatch, downloadFailproofaidBinary, + expectedNpmBinaryDigest, installFromNpmPackage, installedBinaryMismatch, installedBinaryPath, @@ -607,7 +609,7 @@ function selinuxEnabled(): boolean { function stageSystemBinary(binaryPath: string): string { const target = systemBinaryTarget(binaryPath); if (!target) return binaryPath; - const bytes = readRegularFileNoFollow(binaryPath); + const bytes = readDaemonBinaryForRoot(binaryPath); runPrivileged("install", ["-d", "-m", "0755", systemBinaryDir()]); writePrivilegedFile(target, bytes, "0755"); if (selinuxEnabled()) { @@ -915,6 +917,23 @@ export function writePrivilegedFile(destination: string, contents: string | Buff } } +/** + * The daemon binary's bytes as root will install them: read once, and held to + * the digest this build recorded for the managed copy when it carries one + * (`expectedNpmBinaryDigest`). `ensureFailproofaidBinary` checks the file + * before the install starts, but what reaches root is this read, so the check + * is made again on these very bytes. + */ +function readDaemonBinaryForRoot(binaryPath: string): Buffer { + const bytes = readRegularFileNoFollow(binaryPath); + const key = platformKey(); + if (key && binaryPath === installedBinaryPath()) { + const mismatch = binaryDigestMismatch(expectedNpmBinaryDigest(key), bytes, binaryPath); + if (mismatch) throw new Error(mismatch); + } + return bytes; +} + /** * Reads a regular file, refusing a symbolic link or anything else in its * place. Used for the one file whose bytes go to root: what root installs is @@ -1206,7 +1225,7 @@ function daemonInstallRecipe(binaryPath: string, workerCmd: string | null, cliCm const target = systemBinaryTarget(binaryPath); const steps: string[] = []; if (target) { - const digest = sha256Hex(readRegularFileNoFollow(binaryPath)); + const digest = sha256Hex(readDaemonBinaryForRoot(binaryPath)); steps.push( // Quoted: a home directory may hold a space, and an unquoted path // splits into words that stop this `&&`-chained recipe before the diff --git a/src/hooks/system-command.ts b/src/hooks/system-command.ts index 9d411ec2f..2bf4400de 100644 --- a/src/hooks/system-command.ts +++ b/src/hooks/system-command.ts @@ -2,11 +2,9 @@ * How failproofai names the programs it runs as root: by absolute path, from * root's own directories, with a minimal environment. Never through PATH. * - * PATH and the rest of the caller's environment belong to the user: PATH - * routinely starts with directories the user can write (`~/.local/bin`, nvm's - * bin, Homebrew's prefix), and where sudoers sets no `secure_path` (macOS by - * default) sudo looks programs up in it too. Root's programs, and the sudo the - * user types their password into, come from root's own directories instead. + * PATH and the rest of the caller's environment belong to the user, and sudo + * may look programs up in that PATH too. Root's programs, and the sudo the user + * types their password into, come from root's own directories instead. */ import { accessSync, constants as fsConstants, statSync } from "node:fs"; @@ -43,14 +41,19 @@ export function requireSystemCommand(name: string): string { return path; } -/** The caller's settings that only shape how sudo's prompt and messages look. */ -const PASSED_THROUGH = ["TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES"] as const; +/** + * The caller's settings sudo itself may need: the terminal type and locale for + * its prompt, and the SSH agent socket and Kerberos credential cache that PAM + * modules such as pam_ssh_agent_auth and pam_sss_gss authenticate with. None of + * them names code to run. + */ +const PASSED_THROUGH = ["TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "SSH_AUTH_SOCK", "KRB5CCNAME"] as const; /** * The environment every privileged command starts with: root's PATH, plus the - * caller's terminal type and locale for sudo's own prompt. Nothing else of the - * caller's reaches sudo or what it runs: no PATH, no loader or shell variables, - * no `SUDO_ASKPASS` or `SUDO_PROMPT`. + * few settings above that sudo's own prompt and authentication use. Nothing + * else of the caller's reaches sudo or what it runs: no PATH, no loader or + * shell variables, no `SUDO_ASKPASS` or `SUDO_PROMPT`. */ export function privilegedEnv(): NodeJS.ProcessEnv { const env: NodeJS.ProcessEnv = { PATH: SYSTEM_PATH }; From ba66ef7bf10348d5d5957e11c73200351059ca74 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 19:23:47 +0530 Subject: [PATCH 3/6] [hooks] Add the CHANGELOG entry for the privileged service install hardening Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 201c85c11..025f6270d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - `FAILPROOFAI_DAEMON_BASE_URL` must be https, and so must every hop a redirect sends the download to. Plain http is accepted only for a loopback address, because over http the checksum manifest arrives on the same unauthenticated connection as the binary (#1056) - CI: bun is pinned to 1.4.5 in every workflow and in the integration-suite images instead of `latest`, the `pull_request_target` workflow pins `actions/github-script` by commit, and translate-docs reads its `languages` input from `env:` and accepts only supported codes. The input used to run as shell, including in the job holding the translation credentials. The ts-sdk release preflight reads `github.ref` from `env:` too, where a crafted branch name could skip its branch check (#1056) - An install of failproofai fetches one third-party package, `sql.js`, pinned to an exact version with no dependencies or install script of its own; everything else it uses is compiled into its bundles at build time from `bun.lock`. It used to declare six caret ranges, so each `npm install -g failproofai` or `npx failproofai` resolved them, and posthog-node's own ranges under them, afresh: a malicious in-range release (posthog-node was hit by Shai-Hulud 2.0 in November 2025) reached every install made after it was published, and its install script ran there. posthog-node, yaml, smol-toml, jsonc-parser and html-to-image are devDependencies now, since nothing loaded them from `node_modules` at run time, so the pin holds whichever package manager installs failproofai, and an install downloads about 1.2 MB less. `bun run build` now fails first if a runtime dependency is a range, has dependencies of its own or an install script, if a bundle leaves a package external that the install would not carry, or if the package itself gains an install script, a peer dependency or an optional dependency other than the daemon packages (#1059) +- Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) ### Docs From 96c4f3e85a40c6ac325bd71eb010c96181ca99ad Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 19:31:01 +0530 Subject: [PATCH 4/6] [hooks] Type the privileged command environment as a plain record This project's ambient types (Next.js) declare NODE_ENV required on every NodeJS.ProcessEnv, so the minimal environment is built as a record and cast. Co-Authored-By: Claude Opus 5.5 --- src/hooks/system-command.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/hooks/system-command.ts b/src/hooks/system-command.ts index 2bf4400de..07bfd39f2 100644 --- a/src/hooks/system-command.ts +++ b/src/hooks/system-command.ts @@ -56,12 +56,14 @@ const PASSED_THROUGH = ["TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "SS * shell variables, no `SUDO_ASKPASS` or `SUDO_PROMPT`. */ export function privilegedEnv(): NodeJS.ProcessEnv { - const env: NodeJS.ProcessEnv = { PATH: SYSTEM_PATH }; + const env: Record = { PATH: SYSTEM_PATH }; for (const key of PASSED_THROUGH) { const value = process.env[key]; if (value) env[key] = value; } - return env; + // Cast rather than padded: this project's ambient types (Next.js) declare + // NODE_ENV required on every ProcessEnv, and a privileged command needs none. + return env as NodeJS.ProcessEnv; } /** `sudo` as printed for someone to run: its absolute path, or the bare name where there is none. */ From 205e7678cbef4137a47fe7502dbd5e4de620053c Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 19:48:28 +0530 Subject: [PATCH 5/6] [hooks] Check the daemon binary before retiring the legacy user service The install now reads and checks the bytes it will stage under /opt before removing a pre-1.0.0-beta.1 user-scope daemon, so a refused binary leaves the running daemon alone. The uninstall unit tests stand in for elevation tools the test machine lacks, and CLAUDE.md scopes the O_NOFOLLOW read to Linux (macOS root writes only the plist). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 ++++--- .../hooks/daemon-privileged-install.test.ts | 8 ++++++- __tests__/hooks/daemon-service.test.ts | 8 +++++++ src/hooks/daemon-service.ts | 22 +++++++++++++++---- 4 files changed, 38 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 24821a2f2..5a3f00090 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -960,9 +960,11 @@ Three consequences, all handled explicitly rather than assumed: plist, Codex's `/etc/codex/config.toml`, the `/opt` binary) goes through `writePrivilegedFile()`: the bytes go to `PRIVILEGED_INSTALL_SCRIPT` on stdin with their SHA-256 as an argument, and root checks them in a hidden `mktemp` file beside the - destination before it sets the mode and renames. The binary is read by the CLI, as the - user, with `O_NOFOLLOW`. No `sudo install `: root installs - only bytes it has verified. The printed `needs_root` recipe carries the same digests. + destination before it sets the mode and renames. On Linux the `/opt` binary is read by + the CLI, as the user, with `O_NOFOLLOW`, and checked before the install tears anything + down; on macOS root writes only the plist, which runs the user's own copy as that user. + No `sudo install `: root installs only bytes it has + verified. The printed `needs_root` recipe carries the same digests. - **Nor a program found through PATH.** `sudo` and everything it runs come from `src/hooks/system-command.ts`, which looks only in `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and starts them with `privilegedEnv()` (root's PATH, the caller's locale and the diff --git a/__tests__/hooks/daemon-privileged-install.test.ts b/__tests__/hooks/daemon-privileged-install.test.ts index cd6bdb525..7ec74efa1 100644 --- a/__tests__/hooks/daemon-privileged-install.test.ts +++ b/__tests__/hooks/daemon-privileged-install.test.ts @@ -320,11 +320,15 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never }, 20_000); }); - it("linux: refuses a daemon binary that is a symbolic link, and copies nothing", async () => { + it("linux: refuses a daemon binary that is a symbolic link, copies nothing and stops nothing", async () => { setPlatform("linux"); const managed = installedBinaryPath(); mkdirSync(dirname(managed), { recursive: true }); symlinkSync(otherPath, managed); + // A daemon from an older install that a successful install would retire. + const legacyUnit = resolve(home, ".config", "systemd", "user", "failproofaid.service"); + mkdirSync(dirname(legacyUnit), { recursive: true }); + writeFileSync(legacyUnit, "[Unit]\n"); mockSudo(); const svc = await loadService(); @@ -332,6 +336,8 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never expect(result.installed).toBe(false); expect(result.reason).toMatch(/symbolic link/); + // Refused before anything was torn down. + expect(existsSync(legacyUnit)).toBe(true); expect(filesUnder(rootDir).filter((p) => p !== otherPath).map((p) => readFileSync(p, "utf8"))).not.toContain( OTHER, ); diff --git a/__tests__/hooks/daemon-service.test.ts b/__tests__/hooks/daemon-service.test.ts index 931b16dba..210112457 100644 --- a/__tests__/hooks/daemon-service.test.ts +++ b/__tests__/hooks/daemon-service.test.ts @@ -466,6 +466,13 @@ describe("hooks/daemon-service", () => { // read the same as root or not. async function runUninstall(opts: { failOn?: string } = {}): Promise<{ ran: string[]; root: string; unit: string }> { const ran: string[] = []; + // The install names sudo and each program by absolute path, looked up + // on this machine; none of them runs here, so any the machine lacks + // gets a stand-in path rather than failing the lookup. + vi.doMock("../../src/hooks/system-command", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, requireSystemCommand: (name: string) => actual.systemCommandPath(name) ?? `/usr/bin/${name}` }; + }); vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string, args: string[] = []) => { @@ -484,6 +491,7 @@ describe("hooks/daemon-service", () => { await uninstallDaemonService(); return { ran, root: daemonSystemBinaryDir()!, unit: daemonServiceFilePath()! }; } finally { + vi.doUnmock("../../src/hooks/system-command"); vi.doUnmock("node:child_process"); vi.resetModules(); } diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index df70316f7..ebc98a214 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -606,12 +606,12 @@ function selinuxEnabled(): boolean { * directories `install -d` creates under `/opt` (`usr_t`) come out `usr_t` * too, never the `bin_t` the policy names for them. */ -function stageSystemBinary(binaryPath: string): string { +function stageSystemBinary(binaryPath: string, bytes?: Buffer): string { const target = systemBinaryTarget(binaryPath); if (!target) return binaryPath; - const bytes = readDaemonBinaryForRoot(binaryPath); + const data = bytes ?? readDaemonBinaryForRoot(binaryPath); runPrivileged("install", ["-d", "-m", "0755", systemBinaryDir()]); - writePrivilegedFile(target, bytes, "0755"); + writePrivilegedFile(target, data, "0755"); if (selinuxEnabled()) { const root = systemBinaryRoot(); try { @@ -1334,6 +1334,20 @@ export async function installDaemonService(): Promise { }; } + // The bytes root will install under /opt, read and checked BEFORE anything + // is torn down below: a binary that is refused must leave whatever daemon + // runs now still running. + let stagedBytes: Buffer | undefined; + if (process.platform === "linux" && systemBinaryTarget(binaryPath)) { + try { + stagedBytes = readDaemonBinaryForRoot(binaryPath); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + hookLogWarn(`daemon service install failed: ${msg}`); + return { installed: false, reason: msg }; + } + } + // A daemon left over from a pre-1.0.0-beta.1 install holds the same // singleton lock the new one needs, so the system unit would start, lose // the flock race, and leave the machine fail-closed against a daemon that @@ -1345,7 +1359,7 @@ export async function installDaemonService(): Promise { if (process.platform === "linux") { // Before the unit is written, so a copy that fails leaves the previous // unit and the daemon it runs untouched. See `systemBinaryDir()`. - execPath = stageSystemBinary(binaryPath); + execPath = stageSystemBinary(binaryPath, stagedBytes); writePrivilegedFile(systemdUnitPath(), systemdUnitContents(execPath, workerCmd, cliCmd)); runPrivileged("systemctl", ["daemon-reload"]); // `enable` for boot persistence, then `restart` — NOT `enable --now`. From 9d01a9f4ff0e87e6eb309a624ecf10ae8412ba12 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 21:12:39 +0530 Subject: [PATCH 6/6] [hooks] Print no privileged command without vetted absolute paths sudoCommandLine and sudoPath return null, rather than a bare name, where /usr/bin, /bin, /usr/sbin and /sbin lack sudo or the program. The install recipe, the uninstall fallback, the restart and status hints and the sudo -v hints then say what to do instead of printing a command whose names the pasting shell would look up through its own PATH. Tests share a stand-in for system programs the test machine lacks, and can hide one. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 +- __tests__/helpers/system-command-stand-in.ts | 49 ++++++++++ .../hooks/daemon-privileged-install.test.ts | 93 ++++++++++++++----- __tests__/hooks/daemon-service.test.ts | 55 ++++++++--- __tests__/hooks/system-command.test.ts | 14 ++- __tests__/hooks/uninstall-cli.test.ts | 29 +++++- src/hooks/daemon-service.ts | 38 ++++++-- src/hooks/manager.ts | 10 +- src/hooks/system-command.ts | 23 +++-- src/hooks/uninstall-cli.ts | 53 ++++++----- 10 files changed, 280 insertions(+), 87 deletions(-) create mode 100644 __tests__/helpers/system-command-stand-in.ts diff --git a/CLAUDE.md b/CLAUDE.md index 5a3f00090..1e2d887d8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -969,7 +969,8 @@ Three consequences, all handled explicitly rather than assumed: `src/hooks/system-command.ts`, which looks only in `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and starts them with `privilegedEnv()` (root's PATH, the caller's locale and the settings sudo authenticates with). PATH is the user's to change. Printed commands use - `sudoCommandLine()` for the same reason. + `sudoCommandLine()`, which returns null rather than a bare name where root's directories + lack sudo or the program; callers then print what to do instead of a command. - **A system unit has no login environment.** `resolveWorkerCommand()` uses `process.execPath`, not a bare `node`: the single most common Node install is nvm, whose binary lives under `~/.nvm/versions/node/*/bin` and is on no system PATH. A bare `node` diff --git a/__tests__/helpers/system-command-stand-in.ts b/__tests__/helpers/system-command-stand-in.ts new file mode 100644 index 000000000..87dfa3a0d --- /dev/null +++ b/__tests__/helpers/system-command-stand-in.ts @@ -0,0 +1,49 @@ +/** + * A stand-in for `src/hooks/system-command` in tests that drive the privileged + * service install with `node:child_process` mocked. + * + * The install looks sudo and the programs it runs up in root's own directories + * on the machine running the tests, before any mocked command is called. A + * machine may lack some of them (launchctl on Linux, systemctl on a Mac or in a + * container, sudo itself), so where one is missing a path stands in for it; + * these tests never run them. Everything else is the real module. A test can + * also hide a program, to see what the install does where root has none. + * + * vi.doMock("../../src/hooks/system-command", async (importOriginal) => + * standInSystemCommand(await importOriginal())); + */ +import type * as SystemCommandModule from "../../src/hooks/system-command"; + +type SystemCommand = typeof SystemCommandModule; + +/** Programs the tests' sudo mocks answer for without running them. */ +const STOOD_IN = new Set(["sudo", "systemctl", "launchctl"]); + +/** On globalThis, because `vi.resetModules` evaluates this file afresh for each importer. */ +const HIDDEN_KEY = "__failproofaiHiddenSystemPrograms"; + +/** Programs to report as absent from root's directories, for the current test. */ +export function hiddenSystemPrograms(): Set { + const store = globalThis as Record; + if (!(store[HIDDEN_KEY] instanceof Set)) store[HIDDEN_KEY] = new Set(); + return store[HIDDEN_KEY] as Set; +} + +export function standInSystemCommand(actual: SystemCommand): SystemCommand { + const systemCommandPath = (name: string): string | null => { + if (hiddenSystemPrograms().has(name)) return null; + return actual.systemCommandPath(name) ?? (STOOD_IN.has(name) ? `/usr/bin/${name}` : null); + }; + const requireSystemCommand = (name: string): string => { + const path = systemCommandPath(name); + if (!path) throw new Error(`${name} was not found in ${actual.SYSTEM_BIN_DIRS.join(", ")}`); + return path; + }; + const sudoPath = (): string | null => systemCommandPath("sudo"); + const sudoCommandLine = (command: string, ...args: string[]): string | null => { + const sudo = sudoPath(); + const program = systemCommandPath(command); + return sudo && program ? [sudo, program, ...args].join(" ") : null; + }; + return { ...actual, systemCommandPath, requireSystemCommand, sudoPath, sudoCommandLine }; +} diff --git a/__tests__/hooks/daemon-privileged-install.test.ts b/__tests__/hooks/daemon-privileged-install.test.ts index 7ec74efa1..0388dcc27 100644 --- a/__tests__/hooks/daemon-privileged-install.test.ts +++ b/__tests__/hooks/daemon-privileged-install.test.ts @@ -35,6 +35,7 @@ import { installedBinaryPath } from "../../src/hooks/daemon-download"; import { logsDir } from "../../src/hooks/fp-home"; import { shellQuote } from "../../src/hooks/shell-quote"; import packageJson from "../../package.json"; +import { hiddenSystemPrograms, standInSystemCommand } from "../helpers/system-command-stand-in"; vi.mock("../../src/hooks/hook-logger", () => ({ hookLogWarn: vi.fn(), @@ -131,6 +132,7 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never }); afterEach(() => { + hiddenSystemPrograms().clear(); vi.doUnmock("node:child_process"); vi.doUnmock("../../src/hooks/system-command"); vi.doUnmock("../../package.json"); @@ -172,14 +174,24 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never * `beforeRoot` has had its turn. `elevate: false` is a machine where sudo * cannot run anything; `warmUp: true` one where it can only after `sudo -v`. * `onElevate` runs at each `sudo -n true`, the check made just before the - * install starts copying. + * install starts copying. `hide` names programs root's directories are to + * lack. Programs the machine lacks are stood in for (see the helper). */ function mockSudo( - opts: { beforeRoot?: BeforeRoot; elevate?: boolean; warmUp?: boolean; onElevate?: () => void } = {}, + opts: { + beforeRoot?: BeforeRoot; + elevate?: boolean; + warmUp?: boolean; + onElevate?: () => void; + hide?: string[]; + } = {}, ): RootCall[] { const calls: RootCall[] = []; let warm = !opts.warmUp; - standInSystemPrograms(); + for (const name of opts.hide ?? []) hiddenSystemPrograms().add(name); + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), + ); vi.doMock("node:child_process", async (importOriginal) => { const actual = await importOriginal(); return { @@ -228,25 +240,6 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never return calls; } - /** - * The install looks programs up only in root's own directories, and a test - * machine may lack some: launchctl on Linux, systemctl on a Mac or in a - * container, sudo itself. Each of these the sudo mock answers for without - * running it, so where one is missing a path stands in for it. Programs the - * mock does run (install, mv, rm, sh) are always the machine's own. - */ - function standInSystemPrograms(): void { - const answered = new Set(["sudo", "true", "systemctl", "launchctl", "restorecon"]); - vi.doMock("../../src/hooks/system-command", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - requireSystemCommand: (name: string) => - actual.systemCommandPath(name) ?? (answered.has(name) ? `/usr/bin/${name}` : actual.requireSystemCommand(name)), - }; - }); - } - /** * Before each privileged command, every file under the user's home or temp * directory that the command names is changed: replaced by a link to OTHER, @@ -465,9 +458,10 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never */ async function runRecipe(recipe: string): Promise<{ status: number; stderr: string }> { const sudo = (await systemCommand()).sudoPath(); + if (!sudo) throw new Error("no sudo to stand in for: the recipe would not have been printed"); const stand = fakeSudo(); - const runnable = sudo.startsWith("/") ? recipe.split(`${sudo} `).join(`${stand} `) : recipe; - if (sudo.startsWith("/")) expect(runnable).not.toContain(sudo); + const runnable = recipe.split(`${sudo} `).join(`${stand} `); + expect(runnable).not.toContain(sudo); try { realExecFileSync("/bin/sh", ["-c", runnable], { env: { ...process.env, PATH: `${dirname(stand)}:/usr/bin:/bin` }, @@ -493,7 +487,7 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never expect(recipe).toContain(`< '${managed}'`); expect(recipe).not.toMatch(/sudo (install -m|tee|cp) /); // sudo and the programs it runs, by absolute path. - expect(recipe).toContain(sys.sudoCommandLine("systemctl", "daemon-reload")); + expect(recipe).toContain(sys.sudoCommandLine("systemctl", "daemon-reload")!); expect(await runRecipe(recipe)).toEqual({ status: 0, stderr: "" }); expect(readFileSync(target, "utf8")).toBe(BINARY); @@ -514,6 +508,55 @@ describe.skipIf(isRoot)("privileged service install: root is handed bytes, never expect(existsSync(svc.daemonServiceFilePath()!)).toBe(false); }); + // Never a bare name: whoever pastes a printed command would look it up + // through their own PATH. + const missing: [NodeJS.Platform, string][] = [ + ["linux", "sudo"], + ["darwin", "sudo"], + ["linux", "systemctl"], + ]; + it.each(missing)("%s, without %s in root's directories: prints no command to run as root", async (platform, hide) => { + writeManagedBinary(); + setPlatform(platform); + mockSudo({ elevate: false, hide: [hide] }); + const svc = await loadService(); + const sys = await systemCommand(); + + const result = await svc.installDaemonService(); + + expect(result.installed).toBe(false); + expect(result.reason).toMatch(/root privileges are required/); + expect(result.reason).toContain(`No manual steps could be prepared: ${sys.NO_PRINTED_COMMAND_REASON}`); + expect(result.reason).not.toContain("failproofai_install"); + expect(svc.daemonRestartCommand()).toBeNull(); + if (platform === "darwin") expect(svc.daemonStatusCommand()).toBeNull(); + }); + + const updateHints: [string, string[]][] = [ + ["with sudo in root's directories", []], + ["without", ["sudo"]], + ]; + it.each(updateHints)("update's needs-root hint %s names no bare sudo", async (_label, hide) => { + setPlatform("linux"); + mockSudo({ hide }); + const svc = await loadService(); + const sys = await systemCommand(); + + const result = await svc.refreshDaemonToCliVersion({ + status: () => "running", + interactive: () => false, + install: async () => ({ installed: false, reason: "root privileges are required to install it" }), + }); + + const sudo = sys.sudoPath(); + expect(result.lines[1]).toBe( + sudo + ? ` Run \`${sudo} -v\` and then \`failproofai update\` again.` + : ` No sudo was found in ${sys.SYSTEM_BIN_DIRS.join(", ")}, so failproofai cannot install its service here.`, + ); + expect(Boolean(sudo)).toBe(hide.length === 0); + }); + it("macOS: carries the plist inline and installs exactly it, run as printed", async () => { const managed = writeManagedBinary(); const { recipe, svc } = await printedRecipe("darwin"); diff --git a/__tests__/hooks/daemon-service.test.ts b/__tests__/hooks/daemon-service.test.ts index 210112457..5988b9dd0 100644 --- a/__tests__/hooks/daemon-service.test.ts +++ b/__tests__/hooks/daemon-service.test.ts @@ -6,7 +6,8 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, wri import { tmpdir, userInfo } from "node:os"; import { basename, dirname, resolve } from "node:path"; import { binDir } from "../../src/hooks/fp-home"; -import { sudoCommandLine, sudoPath, systemCommandPath } from "../../src/hooks/system-command"; +import { SYSTEM_BIN_DIRS, sudoPath } from "../../src/hooks/system-command"; +import { standInSystemCommand } from "../helpers/system-command-stand-in"; import { startedAtFromMonotonic, waitForDaemonRunning } from "../../src/hooks/daemon-service"; import * as svc from "../../src/hooks/daemon-service"; import { version as pkgVersion } from "../../package.json"; @@ -242,13 +243,22 @@ describe("hooks/daemon-service", () => { // first's daemon (UserName, ExecStart under their ~/.failproofai/bin, // their log paths) and their uninstall deleted it. setPlatform("darwin"); - const { daemonServiceFilePath, daemonStatusCommand } = await import("../../src/hooks/daemon-service"); - const user = userInfo().username; - - expect(daemonServiceFilePath()).toBe( - `/Library/LaunchDaemons/ai.failproof.failproofaid.${user}.plist`, + // The status hint names launchctl by absolute path, and a Linux runner + // has none: stand one in. + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), ); - expect(daemonStatusCommand()).toContain(`system/ai.failproof.failproofaid.${user}`); + try { + const { daemonServiceFilePath, daemonStatusCommand } = await import("../../src/hooks/daemon-service"); + const user = userInfo().username; + + expect(daemonServiceFilePath()).toBe( + `/Library/LaunchDaemons/ai.failproof.failproofaid.${user}.plist`, + ); + expect(daemonStatusCommand()).toContain(`system/ai.failproof.failproofaid.${user}`); + } finally { + vi.doUnmock("../../src/hooks/system-command"); + } }); it("writes a unit that runs as the user, starts at boot, and knows where HOME is", async () => { @@ -414,6 +424,11 @@ describe("hooks/daemon-service", () => { // Every privileged command fails the way a machine without // passwordless sudo fails. Nothing may be written, and the reason // has to be actionable rather than an errno. + // sudo and the programs it runs are looked up on this machine; any it + // lacks (systemctl on a Mac) gets a stand-in path. None of them runs. + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), + ); vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string) => { @@ -439,6 +454,7 @@ describe("hooks/daemon-service", () => { existsSync(resolve(process.env.FAILPROOFAI_SYSTEMD_DIR!, `failproofaid@${userInfo().username}.service`)), ).toBe(false); } finally { + vi.doUnmock("../../src/hooks/system-command"); vi.doUnmock("node:child_process"); vi.resetModules(); } @@ -469,10 +485,9 @@ describe("hooks/daemon-service", () => { // The install names sudo and each program by absolute path, looked up // on this machine; none of them runs here, so any the machine lacks // gets a stand-in path rather than failing the lookup. - vi.doMock("../../src/hooks/system-command", async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, requireSystemCommand: (name: string) => actual.systemCommandPath(name) ?? `/usr/bin/${name}` }; - }); + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), + ); vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string, args: string[] = []) => { @@ -602,6 +617,11 @@ describe("hooks/daemon-service", () => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, "#!/bin/sh\n", { mode: 0o755 }); setPlatform("linux"); + // sudo and the programs it runs are looked up on this machine; any it + // lacks (systemctl on a Mac) gets a stand-in path. None of them runs. + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), + ); vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string) => { @@ -615,21 +635,24 @@ describe("hooks/daemon-service", () => { const { installDaemonService, systemBinaryTarget, daemonSystemBinaryDir } = await import( "../../src/hooks/daemon-service" ); + // The same lookups the install used (stand-ins included). + const sys = await import("../../src/hooks/system-command"); const target = systemBinaryTarget(path)!; const result = await installDaemonService(); expect(result.installed).toBe(false); expect(path).toContain(" "); - expect(result.reason).toContain(sudoCommandLine("install", "-d", "-m", "0755", `'${dirname(target)}'`)); + expect(result.reason).toContain(sys.sudoCommandLine("install", "-d", "-m", "0755", `'${dirname(target)}'`)!); // The binary reaches root on stdin, from a `<` the user's own shell // opens, with the digest root checks it against. const digest = createHash("sha256").update("#!/bin/sh\n").digest("hex"); expect(result.reason).toContain(`failproofai_install '${target}' ${digest} 0755 < '${path}'`); // Only where root's own directories have restorecon (every SELinux system). - if (systemCommandPath("restorecon")) { - expect(result.reason).toContain(sudoCommandLine("restorecon", "-R", `'${daemonSystemBinaryDir()}'`)); + if (sys.systemCommandPath("restorecon")) { + expect(result.reason).toContain(sys.sudoCommandLine("restorecon", "-R", `'${daemonSystemBinaryDir()}'`)!); } } finally { + vi.doUnmock("../../src/hooks/system-command"); vi.doUnmock("node:child_process"); vi.resetModules(); } @@ -1542,7 +1565,9 @@ describe("refreshDaemonToCliVersion", () => { expect(result.lines).toEqual([ `✕ failproofaid ${version} was not installed: root privileges are required. The previous daemon is untouched.`, - ` Run \`${sudoPath()} -v\` and then \`failproofai update\` again.`, + sudoPath() + ? ` Run \`${sudoPath()} -v\` and then \`failproofai update\` again.` + : ` No sudo was found in ${SYSTEM_BIN_DIRS.join(", ")}, so failproofai cannot install its service here.`, ]); expect(result.lines.join("\n")).not.toMatch(/failproofai config|\[Unit\]|sudo tee/); }); diff --git a/__tests__/hooks/system-command.test.ts b/__tests__/hooks/system-command.test.ts index 9b725d67c..806cf4913 100644 --- a/__tests__/hooks/system-command.test.ts +++ b/__tests__/hooks/system-command.test.ts @@ -9,6 +9,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, resolve } from "node:path"; import { + NO_PRINTED_COMMAND_REASON, SYSTEM_BIN_DIRS, SYSTEM_PATH, privilegedEnv, @@ -83,9 +84,14 @@ describe("system-command", () => { expect(Object.keys(env).every((key) => allowed.includes(key))).toBe(true); }); - it("prints sudo and the program by absolute path, and the bare name where root has none", () => { - expect(sudoCommandLine("sh", "-c", "'true'")).toBe(`${sudoPath()} ${systemCommandPath("sh")} -c 'true'`); - expect(sudoCommandLine("failproofai-only-on-path", "-x")).toBe(`${sudoPath()} failproofai-only-on-path -x`); - expect(sudoPath()).toBe(systemCommandPath("sudo") ?? "sudo"); + it("prints sudo and the program by absolute path, and nothing where root's directories lack either", () => { + const sudo = sudoPath(); + expect(sudo).toBe(systemCommandPath("sudo")); + expect(sudoCommandLine("sh", "-c", "'true'")).toBe(sudo ? `${sudo} ${systemCommandPath("sh")} -c 'true'` : null); + // Never a bare name: the program below is only on PATH. + expect(sudoCommandLine("failproofai-only-on-path", "-x")).toBeNull(); + expect(NO_PRINTED_COMMAND_REASON).toBe( + "sudo or the program it would run is not in /usr/bin, /bin, /usr/sbin, /sbin, so no command to run as root is printed", + ); }); }); diff --git a/__tests__/hooks/uninstall-cli.test.ts b/__tests__/hooks/uninstall-cli.test.ts index b161e3520..7d9b1dcaa 100644 --- a/__tests__/hooks/uninstall-cli.test.ts +++ b/__tests__/hooks/uninstall-cli.test.ts @@ -15,7 +15,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { sudoCommandLine } from "../../src/hooks/system-command"; +import { NO_PRINTED_COMMAND_REASON, sudoCommandLine } from "../../src/hooks/system-command"; +import { hiddenSystemPrograms } from "../helpers/system-command-stand-in"; /** Call order across the mocked modules, which is the actual thing under test. */ const calls: string[] = []; @@ -47,6 +48,14 @@ vi.mock("../../src/hooks/agent-skill", () => ({ }), })); +// sudo and the programs it runs are named by absolute path, looked up on this +// machine; any it lacks (systemctl on a Mac) gets a stand-in path. See the helper. +vi.mock("../../src/hooks/system-command", async (importOriginal) => + (await import("../helpers/system-command-stand-in")).standInSystemCommand( + await importOriginal(), + ), +); + vi.mock("../../src/hooks/daemon-service", () => ({ isDaemonSupportedPlatform: () => true, daemonServiceFilePath: () => servicePath, @@ -427,6 +436,24 @@ describe("hooks/uninstall-cli — who decides the daemon's fate", () => { " Check it with systemctl status failproofaid@tester", ]); }); + + it("prints no command, only what to remove, where root's directories have no sudo", async () => { + // A bare `sudo` would be whatever the PATH of whoever pastes it finds first. + hiddenSystemPrograms().add("sudo"); + try { + serviceExists = false; + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + const res = await runUninstallCommand({ yes: true }); + + const out = res.lines.join("\n"); + expect(res.exitCode).toBe(1); + expect(out).toContain(`Remove ${servicePath} as root (${NO_PRINTED_COMMAND_REASON}).`); + expect(out).not.toContain("Remove it as root:"); + expect(out).not.toMatch(/`sudo /); + } finally { + hiddenSystemPrograms().clear(); + } + }); }); describe("hooks/uninstall-cli — a staged daemon binary with no unit", () => { diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index ebc98a214..4fb780b15 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -37,6 +37,8 @@ import { import { logsDir } from "./fp-home"; import { shellQuote, shellQuotedWords } from "./shell-quote"; import { + NO_PRINTED_COMMAND_REASON, + SYSTEM_BIN_DIRS, SYSTEM_PATH, privilegedEnv, requireSystemCommand, @@ -1204,10 +1206,23 @@ function recipeWriteInline(destination: string, contents: string, mode: string): * before any service is started. */ function renderRecipe(steps: string[]): string { - const define = `${RECIPE_WRITE_FN}() { ${sudoPath()} ${SYSTEM_SH} -c ${shellQuote(PRIVILEGED_INSTALL_SCRIPT)} failproofai-install "$@"; }`; + const sudo = sudoPath(); + if (!sudo) throw new Error(NO_PRINTED_COMMAND_REASON); + const define = `${RECIPE_WRITE_FN}() { ${sudo} ${SYSTEM_SH} -c ${shellQuote(PRIVILEGED_INSTALL_SCRIPT)} failproofai-install "$@"; }`; return [define, steps.join(" &&\n")].join("\n"); } +/** + * One privileged step of the recipe. Throws where root's directories lack sudo + * or the program: the recipe is then not printed at all, rather than printed + * with a name that whoever pastes it would look up through their own PATH. + */ +function recipeCommand(command: string, ...args: string[]): string { + const line = sudoCommandLine(command, ...args); + if (!line) throw new Error(NO_PRINTED_COMMAND_REASON); + return line; +} + /** * The privileged steps an install performs, as a recipe to paste, so a * machine that cannot elevate can be told exactly what to run rather than just @@ -1230,24 +1245,24 @@ function daemonInstallRecipe(binaryPath: string, workerCmd: string | null, cliCm // Quoted: a home directory may hold a space, and an unquoted path // splits into words that stop this `&&`-chained recipe before the // unit is ever written. - sudoCommandLine("install", "-d", "-m", "0755", shellQuote(systemBinaryDir())), + recipeCommand("install", "-d", "-m", "0755", shellQuote(systemBinaryDir())), `${RECIPE_WRITE_FN} ${shellQuote(target)} ${digest} 0755 < ${shellQuote(binaryPath)}`, ); // Only where root's directories have it: SELinux systems always do, and a // bare name would leave sudo to find one. if (systemCommandPath("restorecon")) { - steps.push(`{ ${sudoCommandLine("restorecon", "-R", shellQuote(systemBinaryRoot()))} 2>/dev/null || true; }`); + steps.push(`{ ${recipeCommand("restorecon", "-R", shellQuote(systemBinaryRoot()))} 2>/dev/null || true; }`); } } steps.push( recipeWriteInline(systemdUnitPath(), systemdUnitContents(target ?? binaryPath, workerCmd, cliCmd), "0644"), - sudoCommandLine("systemctl", "daemon-reload"), - sudoCommandLine("systemctl", "enable", systemdUnitName()), + recipeCommand("systemctl", "daemon-reload"), + recipeCommand("systemctl", "enable", systemdUnitName()), // `restart`, not `enable --now`, for the reason the install path gives: // `--now` does nothing to an already-active unit, and these commands are // handed to someone whose daemon may well be running — an upgrade is the // most likely reason they are reading them. - sudoCommandLine("systemctl", "restart", systemdUnitName()), + recipeCommand("systemctl", "restart", systemdUnitName()), ); return renderRecipe(steps); } @@ -1259,8 +1274,8 @@ function daemonInstallRecipe(binaryPath: string, workerCmd: string | null, cliCm return renderRecipe([ `mkdir -p ${shellQuote(logDir)}`, recipeWriteInline(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd), "0644"), - `{ ${sudoCommandLine("launchctl", "unload", shellQuote(plistPath))} 2>/dev/null || true; }`, - sudoCommandLine("launchctl", "load", "-w", shellQuote(plistPath)), + `{ ${recipeCommand("launchctl", "unload", shellQuote(plistPath))} 2>/dev/null || true; }`, + recipeCommand("launchctl", "load", "-w", shellQuote(plistPath)), ]); } @@ -2161,12 +2176,17 @@ export async function refreshDaemonToCliVersion( // and names this command: get sudo, then run it again. Never "run the CLI // under sudo" — that would configure root's account instead of this one. const needsRoot = /root privileges are required/.test(result.reason ?? ""); + // Only a sudo from root's own directories is named; with none there, a + // bare `sudo` would be whatever the user's PATH finds first. + const sudo = sudoPath(); return { ok: false, lines: needsRoot ? [ `✕ failproofaid ${version} was not installed: root privileges are required. The previous daemon is untouched.`, - ` Run \`${sudoPath()} -v\` and then \`failproofai update\` again.`, + sudo + ? ` Run \`${sudo} -v\` and then \`failproofai update\` again.` + : ` No sudo was found in ${SYSTEM_BIN_DIRS.join(", ")}, so failproofai cannot install its service here.`, ] : [ `✕ failproofaid ${version} could not be installed: ${(result.reason ?? "unknown reason").replace(/\.$/, "")}. ` + diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index 1d2573f52..83ded00dc 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -41,7 +41,7 @@ import type { ResolvedPack } from "./pack-manifest"; import { hasInstalledRegexPacks, readInstalledPacks } from "./pack-manifest"; import { packPolicyParamKey } from "./policy-evaluator"; import { probeDaemonPolicyEvaluation } from "./daemon-service"; -import { sudoPath } from "./system-command"; +import { NO_PRINTED_COMMAND_REASON, sudoPath } from "./system-command"; import { keepAgentSelectionTrue } from "./agent-selection"; import { INDENT, colorsEnabled, optsFor, printBlock, screenKit, type ScreenKitOpts } from "./tui"; @@ -1141,11 +1141,15 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al } } else if (system.status === "failed") { // Non-interactive by design (this also runs from the dashboard), so - // the fix is to prime sudo and come back. + // the fix is to prime sudo and come back. Only a sudo from root's own + // directories is named: a bare one is whatever PATH finds first. + const sudo = sudoPath(); for (const line of screenKit(optsFor(process.stdout)).notice( "caution", `failproofai's Codex hooks are still in ${system.path}: ${system.reason}.\n` + - `Run \`${sudoPath()} -v\`, then this command again.`, + (sudo + ? `Run \`${sudo} -v\`, then this command again.` + : `Remove failproofai's block from ${system.path} as root (${NO_PRINTED_COMMAND_REASON}).`), )) { say(line); } diff --git a/src/hooks/system-command.ts b/src/hooks/system-command.ts index 07bfd39f2..71937a0a6 100644 --- a/src/hooks/system-command.ts +++ b/src/hooks/system-command.ts @@ -66,16 +66,25 @@ export function privilegedEnv(): NodeJS.ProcessEnv { return env as NodeJS.ProcessEnv; } -/** `sudo` as printed for someone to run: its absolute path, or the bare name where there is none. */ -export function sudoPath(): string { - return systemCommandPath("sudo") ?? "sudo"; +/** + * Why no command to run as root is printed, where a caller would have printed + * one: a printed bare name is looked up by whoever runs it (their shell's PATH, + * or sudo's), which is the lookup this module exists to avoid. + */ +export const NO_PRINTED_COMMAND_REASON = `sudo or the program it would run is not in ${SYSTEM_BIN_DIRS.join(", ")}, so no command to run as root is printed`; + +/** `sudo` as printed for someone to run: its absolute path, or null where root's directories have none. */ +export function sudoPath(): string | null { + return systemCommandPath("sudo"); } /** * A privileged command as printed for someone to run: `sudo` and the program - * by absolute path where root's directories have them, the bare names where - * they do not. `args` are pasted as given, so the caller quotes them. + * by absolute path, or null where root's directories lack either; never a bare + * name. `args` are pasted as given, so the caller quotes them. */ -export function sudoCommandLine(command: string, ...args: string[]): string { - return [sudoPath(), systemCommandPath(command) ?? command, ...args].join(" "); +export function sudoCommandLine(command: string, ...args: string[]): string | null { + const sudo = sudoPath(); + const program = systemCommandPath(command); + return sudo && program ? [sudo, program, ...args].join(" ") : null; } diff --git a/src/hooks/uninstall-cli.ts b/src/hooks/uninstall-cli.ts index 011414203..158e4225f 100644 --- a/src/hooks/uninstall-cli.ts +++ b/src/hooks/uninstall-cli.ts @@ -49,7 +49,7 @@ import { listInstallableIds, getIntegration } from "./integrations"; import type { IntegrationType } from "./types"; import { removeHooks } from "./manager"; import { shellQuote } from "./shell-quote"; -import { sudoCommandLine } from "./system-command"; +import { NO_PRINTED_COMMAND_REASON, sudoCommandLine } from "./system-command"; import { installedAgentSkillDirs, removeAgentSkill } from "./agent-skill"; import { CODEX_MANAGED_BEGIN, CODEX_MANAGED_END, codexSystemConfigPath, codexSystemHooksPresent } from "./codex-system-hooks"; import { optsFor, screenKit, type RenderOpts } from "./tui"; @@ -361,10 +361,15 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< // "still there, here is what to run as root" path below. elevateOnce(); // What to run as root when the removal could not elevate, and where to look. - const byHand = (servicePath: string): string => - "\nRemove it as root:\n" + - manualServiceRemoval(servicePath).map((step) => ` \`${step}\``).join("\n") + - (daemonStatusCommand() ? `\nCheck it with \`${daemonStatusCommand()}\`` : ""); + const byHand = (servicePath: string): string => { + const steps = manualServiceRemoval(servicePath); + return ( + (steps + ? "\nRemove it as root:\n" + steps.map((step) => ` \`${step}\``).join("\n") + : `\nRemove ${servicePath} as root (${NO_PRINTED_COMMAND_REASON}).`) + + (daemonStatusCommand() ? `\nCheck it with \`${daemonStatusCommand()}\`` : "") + ); + }; try { await uninstallDaemonService(); // uninstallDaemonService is best-effort by contract — it warns and @@ -376,9 +381,10 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< byHand(found.servicePath), ); } else if (found.stagedBinaryDir && existsSync(found.stagedBinaryDir)) { + const removal = sudoCommandLine("rm", "-rf", shellQuote(found.stagedBinaryDir)); failures.push( `The failproofaid binary in ${found.stagedBinaryDir} is still there, most often because sudo was not available.` + - `\nRemove it as root:\n \`${sudoCommandLine("rm", "-rf", shellQuote(found.stagedBinaryDir))}\``, + (removal ? `\nRemove it as root:\n \`${removal}\`` : `\nRemove it as root (${NO_PRINTED_COMMAND_REASON}).`), ); } else if (found.serviceInstalled) { lines.push(kit.ok("Stopped and removed the failproofaid service.")); @@ -430,26 +436,29 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< return { exitCode: 0, lines, planLines, purged }; } -/** The exact commands to finish a service removal that could not elevate. The - * paths are quoted: these are pasted into a root shell, and an unquoted path - * holding a space would make `rm -rf` remove something else. */ -function manualServiceRemoval(servicePath: string): string[] { - // sudo and each program by absolute path, as failproofai runs them itself: - // see system-command.ts. +/** The exact commands to finish a service removal that could not elevate, or + * null where root's directories lack sudo or a program they name (see + * system-command.ts: a printed bare name is looked up through the user's + * PATH). The paths are quoted: these are pasted into a root shell, and an + * unquoted path holding a space would make `rm -rf` remove something else. */ +function manualServiceRemoval(servicePath: string): string[] | null { + const steps: (string | null)[] = []; if (process.platform === "darwin") { - return [ + steps.push( sudoCommandLine("launchctl", "unload", "-w", shellQuote(servicePath)), sudoCommandLine("rm", "-f", shellQuote(servicePath)), - ]; + ); + } else { + const unit = servicePath.split("/").pop() ?? servicePath; + const binDir = daemonSystemBinaryDir(); + steps.push( + sudoCommandLine("systemctl", "disable", "--now", unit), + sudoCommandLine("rm", "-f", shellQuote(servicePath)), + sudoCommandLine("systemctl", "daemon-reload"), + ...(binDir ? [sudoCommandLine("rm", "-rf", shellQuote(binDir))] : []), + ); } - const unit = servicePath.split("/").pop() ?? servicePath; - const binDir = daemonSystemBinaryDir(); - return [ - sudoCommandLine("systemctl", "disable", "--now", unit), - sudoCommandLine("rm", "-f", shellQuote(servicePath)), - sudoCommandLine("systemctl", "daemon-reload"), - ...(binDir ? [sudoCommandLine("rm", "-rf", shellQuote(binDir))] : []), - ]; + return steps.every((step): step is string => step !== null) ? steps : null; } /** What `daemonServiceStatus()` says, for the status line the CLI prints. */