From 70f1bbaef62711183869b576f45f02c9d4e26fb5 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 21:27:59 +0530 Subject: [PATCH 1/7] [hooks] Harden the Codex system hooks The hooks failproofai writes into Codex's system config now run a root-owned hook runner, /opt/failproofai-codex/codex-hook, which hands each event to the failproofai of the account that set the hooks up, one line per account. - installCodexSystemHooks adds this account's line and keeps the others'. removeCodexSystemHooks takes out only this account, and the block and runner once none is left. - untrustedPathReason checks that the runner, the directories above it, the sh, id and cat it runs, and each account's own failproofai can be changed only by root or that account. It runs on install and on every failproofai update (refreshCodexSystemHooks). A runner that fails takes the block out; a line that fails is taken out of the runner. What root writes is read back before the block goes in. - failproofai update rewrites a block in an earlier format to run the runner. It asks for root only as an account the block runs for, and any other account gets a notice instead of a failed update. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + CLAUDE.md | 37 + .../e2e/cli/codex-system-hooks.e2e.test.ts | 79 +- .../codex-system-hooks-privileged.test.ts | 104 ++ __tests__/hooks/codex-system-hooks.test.ts | 663 ++++++++++- __tests__/hooks/update-run.test.ts | 69 ++ docs/reference/harnesses.mdx | 8 +- src/hooks/codex-system-hooks.ts | 1042 +++++++++++++++-- src/hooks/integrations.ts | 10 +- src/hooks/manager.ts | 26 +- src/hooks/update-run.ts | 22 +- 11 files changed, 1916 insertions(+), 145 deletions(-) create mode 100644 __tests__/hooks/codex-system-hooks-privileged.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 201c85c11..433e83cdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - The daemon download is checked against the digest recorded in the npm package as well as the release's `SHA256SUMS`, which comes from the same release as the binary and so cannot catch a replaced asset (#1056) - `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) +- Harden the Codex system hooks. The hooks failproofai writes into `/etc/codex/config.toml` now run `/opt/failproofai-codex/codex-hook`, a short root-owned script that hands each event to the failproofai of the account that set the hooks up, one line per account. Install and every `failproofai update` check that the script, the directories above it, the `sh`, `id` and `cat` it runs, and each account's own failproofai can be changed only by root or that account; a block that fails is taken out, and an account that fails is taken out of the script. `update` rewrites a block from an earlier version to use the script, which needs sudo; an account the block does not run for gets a notice instead of a failed update. Uninstalling takes out only your account (#PR_NUMBER) - 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) ### Docs diff --git a/CLAUDE.md b/CLAUDE.md index a1836c44c..41287e9c9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,6 +29,43 @@ failproofai policies --install --cli codex --scope project ``` which writes a portable `npx -y failproofai --hook ... --cli codex` command. +**User scope with sudo: Codex's system config, through the hook runner.** Codex ≥0.129 +runs a `~/.codex/hooks.json` hook only once a person trusts it, but runs hooks from its +system config (`/etc/codex/config.toml`) as managed, with no trust. So with root, +`src/hooks/codex-system-hooks.ts` puts the user-scope hooks there, in one marked block that +serves every account on the machine. Every hook in it runs the **hook runner**, +`/opt/failproofai-codex/codex-hook` (its own directory: `/opt/failproofai/` is the +daemon's): a root-owned `sh` script with one `case` arm per uid that set the hooks up, +`) exec '' "$@"`, which for any other uid drains stdin with +`cat` and exits 0 (no decision). It names `sh`, `id` and `cat` by absolute path from `/bin` +or `/usr/bin`. Rules that keep it safe: +- **Check what it runs, every time.** `untrustedPathReason()` walks a path the way the + kernel resolves it, following each symlink, and requires every directory, link and the + final file to be owned by a trusted uid and writable by no one else (a sticky directory, + like `/tmp`, is allowed). For `/etc/codex/config.toml` the trusted uid is root alone + (`codexTrustedOwners`); only a test's config path (`FAILPROOFAI_CODEX_SYSTEM_CONFIG`) + also trusts that path's owner. The runner's directory, the runner, `sh`, `id`, `cat` + and each account's line are checked on install (`installCodexSystemHooks`) and on every + `failproofai update` (`refreshCodexSystemHooks`, a step in `update-run.ts`). A runner + that fails takes the block out; a line that fails is taken out of the runner. +- **Each line runs only that account's own install.** An account's line must resolve + through files owned by root or that account (its group may write them: a umask of 002). + Root's line must be root's alone, group included, and names its interpreter by absolute + path, so nothing on it goes through PATH. Another account's line that this process + cannot read (a 0750 home) is kept as it is. +- **One block, many accounts.** Install adds this uid and keeps the others. Uninstall + removes only this uid, and the block and runner once none is left. + `codexSystemHooksPresent()` / `codexHookTrust()` answer for **this** uid. A runner with + no block is stale: its lines are never merged back. +- **Earlier blocks.** A block in the format earlier versions wrote is rewritten to run the + runner for the account that owns the program it ran; one whose program is root's alone + is left as it is. `update` asks for root (`sudo -n`) only when this account is one the + block runs for or owns what it runs; any other account gets a notice and its update + does not fail. +- **Tests never reach `/opt`.** The runner sits beside the system config whenever + `FAILPROOFAI_CODEX_SYSTEM_CONFIG` points anywhere but `/etc/codex/config.toml` + (`codexHookRunnerPath`). Both vitest configs set that variable to `off`. + ### Copilot hooks (`.github/hooks/failproofai.json`) Copilot's project-scope hook config lives under `.github/hooks/`, **not** diff --git a/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts b/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts index 562dd95b6..b94582302 100644 --- a/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts +++ b/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts @@ -5,11 +5,12 @@ * but runs hooks from its system config as managed. Each test gets its own * HOME, FAILPROOFAI_HOME and a temp "system config" (FAILPROOFAI_CODEX_SYSTEM_CONFIG), * plus a fake `codex` on PATH that reports a version, so nothing here reaches - * /etc or needs sudo or a real Codex. + * /etc or needs sudo or a real Codex. The hook runner goes beside that temp + * config, never to /opt. */ import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { spawnSync } from "node:child_process"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -52,6 +53,18 @@ function run(args: string[], env: Record = {}) { } const hooksJson = () => join(home, ".codex", "hooks.json"); +/** Where the hooks in a temp system config point: the runner beside it. */ +const runnerPath = () => join(dirname(systemConfig), "failproofai-codex-hook"); +/** The program each hook in the system config runs: the double-quoted path its command starts with. */ +const hookPrograms = (): string[] => + [...readFileSync(systemConfig, "utf8").matchAll(/^command = (".*")$/gm)].map( + (m) => /^"([^"]*)"/.exec(JSON.parse(m[1]) as string)?.[1] ?? "", + ); +/** A directory as the system's own are made: 0755 whatever the umask, which the runner's check needs. */ +const mkdir755 = (dir: string) => { + mkdirSync(dir, { recursive: true }); + for (let d = dir; d.startsWith(root) && d !== root; d = dirname(d)) chmodSync(d, 0o755); +}; const codexHooksInUserFile = (): number => { if (!existsSync(hooksJson())) return 0; const hooks = (JSON.parse(readFileSync(hooksJson(), "utf8")) as { hooks?: Record> }).hooks ?? {}; @@ -59,7 +72,7 @@ const codexHooksInUserFile = (): number => { }; beforeEach(() => { - root = mkdtempSync(join(tmpdir(), "fp-e2e-codex-system-")); + root = realpathSync(mkdtempSync(join(tmpdir(), "fp-e2e-codex-system-"))); home = join(root, "home"); fakeBin = join(root, "bin"); systemConfig = join(root, "etc", "codex", "config.toml"); @@ -74,7 +87,7 @@ afterEach(() => { describe("E2E: Codex hooks in the system config", () => { it("installs into the system config, keeps what was there, and moves hooks out of hooks.json", () => { - mkdirSync(dirname(systemConfig), { recursive: true }); + mkdir755(dirname(systemConfig)); const original = '# set by the admin\napproval_policy = "never"\n'; writeFileSync(systemConfig, original); // An older install's entries in hooks.json, next to someone else's hook. @@ -106,6 +119,21 @@ describe("E2E: Codex hooks in the system config", () => { expect(codexHooksInUserFile()).toBe(1); expect(readFileSync(hooksJson(), "utf8")).toContain("my-own-hook"); + // Codex runs these hooks for every account, so each runs the hook runner, + // never this account's failproofai, which the runner runs for this uid only. + const programs = hookPrograms(); + expect(programs.length).toBeGreaterThan(0); + expect(new Set(programs)).toEqual(new Set([runnerPath()])); + expect(written).not.toContain(BINARY_PATH); + const runner = readFileSync(runnerPath(), "utf8"); + const arms = runner.split("\n").filter((line) => /^ {2}\d+\) exec /.test(line)); + expect(arms).toHaveLength(1); + expect(arms[0]).toContain(` ${process.getuid!()}) exec '${BINARY_PATH}' "$@" ;;`); + // For this account, the runner is this account's failproofai. + const viaRunner = spawnSync(runnerPath(), ["--version"], { encoding: "utf8", timeout: 20_000 }); + expect(viaRunner.status, viaRunner.stderr).toBe(0); + expect(viaRunner.stdout).toMatch(/\d+\.\d+\.\d+/); + // Idempotent. expect(run(["policies", "--install", "--cli", "codex"]).exitCode).toBe(0); expect(readFileSync(systemConfig, "utf8")).toBe(written); @@ -114,14 +142,57 @@ describe("E2E: Codex hooks in the system config", () => { expect(removed.exitCode, removed.stderr).toBe(0); expect(removed.stdout).toContain("from Codex's system config"); expect(readFileSync(systemConfig, "utf8")).toBe(original); + expect(existsSync(runnerPath())).toBe(false); }); it("deletes a system config it created when the hooks are removed", () => { expect(run(["policies", "--install", "--cli", "codex"]).exitCode).toBe(0); expect(existsSync(systemConfig)).toBe(true); + expect(existsSync(runnerPath())).toBe(true); expect(codexHooksInUserFile()).toBe(0); expect(run(["policies", "--uninstall", "--cli", "codex"]).exitCode).toBe(0); expect(existsSync(systemConfig)).toBe(false); + expect(existsSync(runnerPath())).toBe(false); + }); + + it("update rewrites hooks that run failproofai itself to run the hook runner", () => { + // A block in the format earlier versions wrote: every hook runs failproofai itself. + mkdir755(dirname(systemConfig)); + const command = (event: string) => JSON.stringify(`"${BINARY_PATH}" --hook ${event} --cli codex --agent-scope user`); + writeFileSync( + systemConfig, + [ + BEGIN, + "", + "[[hooks.PreToolUse]]", + "[[hooks.PreToolUse.hooks]]", + 'type = "command"', + `command = ${command("pre_tool_use")}`, + "timeout = 60", + "", + "[[hooks.Stop]]", + "[[hooks.Stop.hooks]]", + 'type = "command"', + `command = ${command("stop")}`, + "timeout = 60", + "# <<< failproofai managed hooks <<<", + "", + ].join("\n"), + ); + expect(hookPrograms()).toEqual([BINARY_PATH, BINARY_PATH]); + + const updated = run(["update", "--no-daemon"]); + expect(updated.exitCode, updated.stdout + updated.stderr).toBe(0); + // The report wraps to the terminal's width. + expect(updated.stdout.replace(/\s+/g, " ")).toContain(`now go through ${runnerPath()},`); + expect(hookPrograms()).toEqual([runnerPath(), runnerPath()]); + expect(readFileSync(systemConfig, "utf8")).toContain("--hook stop --cli codex --agent-scope user"); + expect(readFileSync(runnerPath(), "utf8")).toContain(` ${process.getuid!()}) exec '${BINARY_PATH}' "$@" ;;`); + + // Checked again on the next update, with nothing to say. + const again = run(["update", "--no-daemon"]); + expect(again.exitCode, again.stdout + again.stderr).toBe(0); + expect(again.stdout).not.toContain("Codex"); }); it("without a system config, keeps hooks.json and warns that Codex won't run them untrusted", () => { diff --git a/__tests__/hooks/codex-system-hooks-privileged.test.ts b/__tests__/hooks/codex-system-hooks-privileged.test.ts new file mode 100644 index 000000000..8344eb977 --- /dev/null +++ b/__tests__/hooks/codex-system-hooks-privileged.test.ts @@ -0,0 +1,104 @@ +/** + * The Codex hook runner and system config as they are written on a real + * machine: through `sudo -n` (`runPrivileged`, `writePrivilegedFile` in + * ./daemon-service), not by this process. No real sudo: the privileged helpers + * are stand-ins that do what root would, as the test user, and record each call. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +const root = vi.hoisted(() => ({ + calls: [] as Array<{ op: string; args: unknown[] }>, + /** Bytes a write delivers instead of what it was asked to write, per destination. */ + tamper: new Map(), +})); +vi.mock("../../src/hooks/daemon-service", () => ({ + canElevate: () => true, + runPrivileged: (command: string, args: string[]) => { + root.calls.push({ op: command, args }); + if (command === "install" && args[0] === "-d") { + mkdirSync(args[3], { recursive: true, mode: 0o755 }); + chmodSync(args[3], 0o755); + } else if (command === "rm") rmSync(args[1], { force: true }); + else if (command === "rmdir") rmdirSync(args[0]); + else throw new Error(`unexpected privileged command ${command}`); + }, + writePrivilegedFile: (destination: string, contents: string, mode: string) => { + root.calls.push({ op: "write", args: [destination, mode] }); + writeFileSync(destination, root.tamper.get(destination) ?? contents); + chmodSync(destination, parseInt(mode, 8)); + }, +})); + +import { + CODEX_MANAGED_BEGIN, + codexHookRunnerPath, + installCodexSystemHooks, + parseCodexHookRunner, + removeCodexSystemHooks, +} from "../../src/hooks/codex-system-hooks"; +import { codexSystemHookEntries } from "../../src/hooks/integrations"; + +let dir: string; +beforeEach(() => { + dir = realpathSync(mkdtempSync(join(tmpdir(), "fp-codex-privileged-"))); + root.calls.length = 0; + root.tamper.clear(); +}); +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); +}); + +const path = () => join(dir, "etc", "codex", "config.toml"); +const runner = () => codexHookRunnerPath(path())!; +const cli = () => { + const file = join(dir, "home", "failproofai"); + mkdirSync(dirname(file), { recursive: true, mode: 0o755 }); + chmodSync(dirname(file), 0o755); + writeFileSync(file, "#!/bin/sh\ntrue\n"); + chmodSync(file, 0o755); + return file; +}; +const deps = () => ({ path: path(), codexVersion: () => "0.162.1", direct: false }); +const install = () => installCodexSystemHooks(cli(), codexSystemHookEntries, deps()); + +describe("the Codex system hooks, written as root", () => { + it("makes the runner's directory, then writes the runner 0755 and the config 0644, all through root", () => { + expect(install()).toMatchObject({ ok: true, changed: true }); + expect(root.calls).toEqual([ + { op: "install", args: ["-d", "-m", "0755", dirname(runner())] }, + { op: "install", args: ["-d", "-m", "0755", dirname(runner())] }, + { op: "write", args: [runner(), "0755"] }, + { op: "install", args: ["-d", "-m", "0755", dirname(path())] }, + { op: "write", args: [path(), "0644"] }, + ]); + expect(readFileSync(path(), "utf8")).toContain(CODEX_MANAGED_BEGIN); + expect(parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts).toHaveLength(1); + }); + + it("takes the block out again when the runner root wrote does not hold what was meant", () => { + root.tamper.set(runner(), "#!/bin/sh\n# failproofai Codex hook runner\nexec /bin/true\n"); + expect(install()).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${runner()} does not hold what failproofai wrote`, + }); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + expect(root.calls.at(-1)).toEqual({ op: "rm", args: ["-f", runner()] }); + }); + + it("removes the config it created, then the runner, through root", () => { + expect(install()).toMatchObject({ ok: true }); + root.calls.length = 0; + expect(removeCodexSystemHooks(deps())).toMatchObject({ status: "removed", remaining: 0 }); + expect(root.calls).toEqual([ + { op: "rm", args: ["-f", path()] }, + { op: "rm", args: ["-f", runner()] }, + ]); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); +}); diff --git a/__tests__/hooks/codex-system-hooks.test.ts b/__tests__/hooks/codex-system-hooks.test.ts index 9983a3a76..9998840f4 100644 --- a/__tests__/hooks/codex-system-hooks.test.ts +++ b/__tests__/hooks/codex-system-hooks.test.ts @@ -8,26 +8,47 @@ * `trustStatus: "managed"`. */ import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { CODEX_MANAGED_BEGIN, CODEX_MANAGED_END, codexGatesHookTrust, codexHookHash, + codexHookRunnerPath, codexHookTrust, + codexRefreshLines, codexSystemBackupPath, codexSystemConfigPath, + codexSystemHooksPresent, conflictingHooksDefinition, failproofaiCodexHookIdentities, hasCodexManagedBlock, installCodexSystemHooks, mergeCodexManagedBlock, + parseCodexHookRunner, + parseCodexManagedBlock, parseCodexTrustedHashes, + refreshCodexSystemHooks, removeCodexSystemHooks, + renderCodexHookRunner, renderCodexManagedBlock, + codexTrustedOwners, + untrustedPathReason, } from "../../src/hooks/codex-system-hooks"; import { codex, codexSystemHookEntries } from "../../src/hooks/integrations"; @@ -38,7 +59,8 @@ const CURRENT = () => "0.162.1"; let dir: string; beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), "fp-codex-system-")); + // Resolved: the ownership check reports paths as the kernel resolves them. + dir = realpathSync(mkdtempSync(join(tmpdir(), "fp-codex-system-"))); }); afterEach(() => { rmSync(dir, { recursive: true, force: true }); @@ -104,95 +126,230 @@ describe("conflictingHooksDefinition", () => { }); }); +/** Directories as the tests make them: 0755 whatever the umask, as the runner's check needs. */ +function mkdirs(path: string): void { + const missing: string[] = []; + for (let d = path; !existsSync(d); d = dirname(d)) missing.unshift(d); + for (const d of missing) { + mkdirSync(d); + chmodSync(d, 0o755); + } +} + +/** An executable shell script at `path`, 0755. */ +function script(path: string, body: string): string { + mkdirs(dirname(path)); + writeFileSync(path, `#!/bin/sh\n${body}\n`); + chmodSync(path, 0o755); + return path; +} + +/** The program each hook in the system config's block runs. */ +function blockPrograms(configPath: string): string[] { + const text = readFileSync(configPath, "utf8"); + const entries = parseCodexManagedBlock(text.slice(text.indexOf(CODEX_MANAGED_BEGIN))); + return (entries ?? []).map((e) => /^"([^"]*)"/.exec(e.command)?.[1] ?? e.command); +} + +const ME = process.getuid?.() ?? 0; + +/** This account's own failproofai, as a real file: the runner's per-account check reads it. */ +const myCli = () => script(join(dir, "home", "me", "failproofai"), "true"); + describe("installCodexSystemHooks", () => { const path = () => join(dir, "etc", "codex", "config.toml"); + const runner = () => codexHookRunnerPath(path())!; + const install = (over: Record = {}, cli = myCli()) => + installCodexSystemHooks(cli, codexSystemHookEntries, { path: path(), codexVersion: CURRENT, ...over }); + const block = () => renderCodexManagedBlock(codexSystemHookEntries(runner())); it("creates the file (and its directory) with mode 0644 when there is none, and backs nothing up", () => { - const result = installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: CURRENT }); - expect(result).toEqual({ ok: true, path: path(), changed: true }); - expect(readFileSync(path(), "utf8")).toBe(BLOCK); + const result = install(); + expect(result).toEqual({ ok: true, path: path(), changed: true, dropped: [] }); + expect(readFileSync(path(), "utf8")).toBe(block()); expect(statSync(path()).mode & 0o777).toBe(0o644); expect(existsSync(codexSystemBackupPath(path()))).toBe(false); }); + it("runs every hook through the hook runner, never through the account's own failproofai", () => { + expect(install()).toMatchObject({ ok: true }); + const programs = blockPrograms(path()); + expect(programs).toHaveLength(codex.eventTypes.length); + expect(new Set(programs)).toEqual(new Set([runner()])); + expect(readFileSync(path(), "utf8")).not.toContain(myCli()); + // The runner: 0755, failproofai's, naming this account's failproofai for this uid alone. + expect(statSync(runner()).mode & 0o777).toBe(0o755); + expect(parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts).toEqual([ + expect.objectContaining({ uid: ME, cli: myCli() }), + ]); + }); + it("merges into an existing file, backs it up once, and is a no-op the second time", () => { - mkdirSync(join(dir, "etc", "codex"), { recursive: true }); + mkdirs(join(dir, "etc", "codex")); const original = '# admin\napproval_policy = "never"\n'; writeFileSync(path(), original); chmodSync(path(), 0o640); - expect(installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: CURRENT })).toMatchObject({ ok: true, changed: true }); - expect(readFileSync(path(), "utf8")).toBe(`${original}\n${BLOCK}`); + expect(install()).toMatchObject({ ok: true, changed: true }); + expect(readFileSync(path(), "utf8")).toBe(`${original}\n${block()}`); expect(readFileSync(codexSystemBackupPath(path()), "utf8")).toBe(original); expect(statSync(path()).mode & 0o777).toBe(0o640); - expect(installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: CURRENT })).toMatchObject({ ok: true, changed: false }); - // A new binary path replaces the block and leaves the first backup alone. - const moved = codexSystemHookEntries("/opt/failproofai/cli.mjs"); - expect(installCodexSystemHooks(moved, { path: path(), codexVersion: CURRENT })).toMatchObject({ ok: true, changed: true }); - expect(readFileSync(path(), "utf8")).toBe(`${original}\n${renderCodexManagedBlock(moved)}`); + const runnerBefore = readFileSync(runner(), "utf8"); + expect(install()).toMatchObject({ ok: true, changed: false }); + expect(readFileSync(runner(), "utf8")).toBe(runnerBefore); + // A new failproofai path changes the runner, not the block or the backup. + const elsewhere = script(join(dir, "elsewhere", "failproofai"), "true"); + expect(install({}, elsewhere)).toMatchObject({ ok: true, changed: true }); + expect(readFileSync(path(), "utf8")).toBe(`${original}\n${block()}`); + expect(parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts).toEqual([ + expect.objectContaining({ uid: ME, cli: elsewhere }), + ]); expect(readFileSync(codexSystemBackupPath(path()), "utf8")).toBe(original); }); it("falls back, writing nothing, where the system layer cannot be used", () => { - expect(installCodexSystemHooks(ENTRIES, { path: null, codexVersion: CURRENT })).toMatchObject({ - ok: false, - reason: "unsupported-platform", - }); - expect(installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: () => null })).toMatchObject({ - ok: false, - reason: "codex-not-found", - }); - expect(installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: () => "0.128.0" })).toMatchObject({ - ok: false, - reason: "codex-too-old", - }); + expect(install({ path: null })).toMatchObject({ ok: false, reason: "unsupported-platform" }); + expect(install({ codexVersion: () => null })).toMatchObject({ ok: false, reason: "codex-not-found" }); + expect(install({ codexVersion: () => "0.128.0" })).toMatchObject({ ok: false, reason: "codex-too-old" }); expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); }); it("needs root for a file it cannot write itself, and leaves it untouched without", () => { - if (process.getuid?.() === 0) return; // root can write anything + if (ME === 0) return; // root can write anything const etc = join(dir, "etc", "codex"); - mkdirSync(etc, { recursive: true }); + mkdirs(etc); writeFileSync(path(), "x = 1\n"); chmodSync(path(), 0o444); chmodSync(etc, 0o555); try { - expect(installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: CURRENT, canElevate: () => false })).toEqual({ - ok: false, - reason: "no-root", - path: path(), - }); + expect(install({ canElevate: () => false })).toEqual({ ok: false, reason: "no-root", path: path() }); expect(readFileSync(path(), "utf8")).toBe("x = 1\n"); + expect(existsSync(runner())).toBe(false); } finally { chmodSync(etc, 0o755); } }); it("will not write a block that would break the file's TOML", () => { - mkdirSync(join(dir, "etc", "codex"), { recursive: true }); + mkdirs(join(dir, "etc", "codex")); writeFileSync(path(), "hooks = {}\n"); - expect(installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: CURRENT })).toMatchObject({ + expect(install()).toMatchObject({ ok: false, reason: "conflict", detail: "hooks = {}" }); + expect(readFileSync(path(), "utf8")).toBe("hooks = {}\n"); + expect(existsSync(runner())).toBe(false); + }); + + it("will not replace a file at the runner's path that failproofai did not write", () => { + script(runner(), "echo mine"); + expect(install()).toMatchObject({ ok: false, reason: "conflict", detail: expect.stringContaining(runner()) }); + expect(readFileSync(runner(), "utf8")).toBe("#!/bin/sh\necho mine\n"); + expect(existsSync(path())).toBe(false); + }); + + it("refuses hooks that would run anything else", () => { + const direct = () => codexSystemHookEntries(BIN); + expect(installCodexSystemHooks(myCli(), direct, { path: path(), codexVersion: CURRENT })).toMatchObject({ ok: false, - reason: "conflict", - detail: "hooks = {}", + reason: "write-failed", }); - expect(readFileSync(path(), "utf8")).toBe("hooks = {}\n"); + expect(existsSync(path())).toBe(false); + }); +}); + +describe("the hook runner, run", () => { + const path = () => join(dir, "etc", "codex", "config.toml"); + const runner = () => codexHookRunnerPath(path())!; + // `id` stands in for the account Codex runs as; the rest is the real system's. + const programs = () => ({ sh: "/bin/sh", id: script(join(dir, "fake", "id"), 'echo "$FAKE_UID"'), cat: "/bin/cat" }); + /** An account's own failproofai: writes who it is, its arguments and the event to $MARKER. */ + const fakeCli = (home: string, label = home) => + script(join(dir, "accounts", home, "failproofai"), `printf "%s %s\\n" ${label} "$*" >"$MARKER"; cat >>"$MARKER"`); + const marker = () => join(dir, "ran"); + const payload = '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"ls"}}'; + + /** Every hook in the block, run as `uid` the way Codex runs one: through a shell, the event on stdin. */ + function runHooksAs(uid: number): Array<{ status: number | null; stdout: string }> { + const text = readFileSync(path(), "utf8"); + const entries = parseCodexManagedBlock(text.slice(text.indexOf(CODEX_MANAGED_BEGIN))) ?? []; + expect(entries.length).toBeGreaterThan(0); + return entries.map((entry) => { + const result = spawnSync("/bin/sh", ["-c", entry.command], { + input: payload, + env: { ...process.env, FAKE_UID: String(uid), MARKER: marker() }, + encoding: "utf8", + timeout: 10_000, + }); + return { status: result.status, stdout: result.stdout }; + }); + } + + it("hands the event to the account's own failproofai for that account, and runs nothing for root or anyone else", () => { + const cli = fakeCli("alice"); + expect( + installCodexSystemHooks(cli, codexSystemHookEntries, { + path: path(), + codexVersion: CURRENT, + uid: 4242, + userName: "alice", + programs: programs(), + }), + ).toMatchObject({ ok: true }); + + for (const uid of [0, 4243]) { + const results = runHooksAs(uid); + expect(results.every((r) => r.status === 0 && r.stdout === "")).toBe(true); + expect(existsSync(marker())).toBe(false); + } + + const [first] = runHooksAs(4242); + expect(first.status).toBe(0); + const ran = readFileSync(marker(), "utf8"); + expect(ran).toMatch(/^alice --hook \w+ --cli codex --agent-scope user\n/); + expect(ran).toContain(payload); + }); + + it("runs each account that set it up its own failproofai", () => { + const alice = fakeCli("alice"); + const bob = fakeCli("bob"); + const deps = { path: path(), codexVersion: CURRENT, programs: programs() }; + expect(installCodexSystemHooks(alice, codexSystemHookEntries, { ...deps, uid: 4242 })).toMatchObject({ ok: true }); + expect(installCodexSystemHooks(bob, codexSystemHookEntries, { ...deps, uid: 4243 })).toMatchObject({ ok: true }); + runHooksAs(4243); + expect(readFileSync(marker(), "utf8")).toMatch(/^bob --hook /); + runHooksAs(4242); + expect(readFileSync(marker(), "utf8")).toMatch(/^alice --hook /); + expect(parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts.map((a) => [a.uid, a.cli])).toEqual([ + [4242, alice], + [4243, bob], + ]); + }); + + it("quotes a failproofai path that holds a quote", () => { + const cli = fakeCli("o'brien", "obrien"); + installCodexSystemHooks(cli, codexSystemHookEntries, { path: path(), codexVersion: CURRENT, uid: 4242, programs: programs() }); + expect(parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts[0].cli).toBe(cli); + runHooksAs(4242); + expect(existsSync(marker())).toBe(true); }); }); describe("removeCodexSystemHooks", () => { const path = () => join(dir, "config.toml"); + const runner = () => codexHookRunnerPath(path())!; + const install = (over: Record = {}) => + installCodexSystemHooks(myCli(), codexSystemHookEntries, { path: path(), codexVersion: CURRENT, ...over }); - it("deletes a file failproofai created and nobody else added to", () => { - installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: CURRENT }); - expect(removeCodexSystemHooks({ path: path() })).toEqual({ status: "removed", path: path(), hooks: ENTRIES.length }); + it("deletes a file failproofai created and nobody else added to, and the runner with it", () => { + install(); + expect(removeCodexSystemHooks({ path: path() })).toEqual({ status: "removed", path: path(), hooks: ENTRIES.length, remaining: 0 }); expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); }); it("restores the exact original from the backup, even one with no final newline", () => { const original = 'model = "o3"'; // no trailing newline writeFileSync(path(), original); - installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: CURRENT }); + install(); expect(removeCodexSystemHooks({ path: path() }).status).toBe("removed"); expect(readFileSync(path(), "utf8")).toBe(original); expect(existsSync(codexSystemBackupPath(path()))).toBe(false); @@ -200,7 +357,7 @@ describe("removeCodexSystemHooks", () => { it("keeps edits made since, and the backup, when the rest of the file changed", () => { writeFileSync(path(), "a = 1\n"); - installCodexSystemHooks(ENTRIES, { path: path(), codexVersion: CURRENT }); + install(); writeFileSync(path(), `${readFileSync(path(), "utf8")}b = 2\n`); expect(removeCodexSystemHooks({ path: path() }).status).toBe("removed"); expect(readFileSync(path(), "utf8")).toBe("a = 1\n\nb = 2\n"); @@ -213,6 +370,253 @@ describe("removeCodexSystemHooks", () => { expect(removeCodexSystemHooks({ path: path() })).toEqual({ status: "absent" }); expect(readFileSync(path(), "utf8")).toBe("a = 1\n"); }); + + it("takes out only this account while another still has its hooks there", () => { + install({ uid: 4242 }); + install({ uid: 4243 }); + const config = readFileSync(path(), "utf8"); + expect(removeCodexSystemHooks({ path: path(), uid: 4242 })).toMatchObject({ status: "removed", remaining: 1 }); + expect(readFileSync(path(), "utf8")).toBe(config); + expect(parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts.map((a) => a.uid)).toEqual([4243]); + expect(codexSystemHooksPresent({ path: path(), uid: 4242 })).toBe(false); + expect(codexSystemHooksPresent({ path: path(), uid: 4243 })).toBe(true); + // An account with nothing there removes nothing. + expect(removeCodexSystemHooks({ path: path(), uid: 4244 })).toEqual({ status: "absent" }); + expect(removeCodexSystemHooks({ path: path(), uid: 4243 })).toMatchObject({ status: "removed" }); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); +}); + +describe("what the runner may run before it knows the account", () => { + const path = () => join(dir, "etc", "codex", "config.toml"); + const runner = () => codexHookRunnerPath(path())!; + const install = (over: Record = {}) => + installCodexSystemHooks(myCli(), codexSystemHookEntries, { path: path(), codexVersion: CURRENT, ...over }); + + it("is root's alone when the system config is: the runner of an account is refused and the hooks stay out", () => { + if (ME === 0) return; // root's own files are root's + // As on a real machine, where /etc/codex is root's: this test's files are an account's. + const result = install({ trustedUids: [0] }); + expect(result).toMatchObject({ ok: false, reason: "unsafe", detail: expect.stringMatching(/is owned by uid \d+/) }); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); + + it("refuses a directory others can write, and takes out the block that was there", () => { + expect(install()).toMatchObject({ ok: true }); + chmodSync(dirname(runner()), 0o775); + expect(install()).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${dirname(runner())} can be written by accounts other than its owner`, + }); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); + + it("refuses an `id` or `cat` another account could replace", () => { + const loose = join(dir, "loose"); + const id = script(join(loose, "id"), "echo 0"); + chmodSync(loose, 0o777); + expect(install({ programs: { sh: "/bin/sh", id, cat: "/bin/cat" } })).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${loose} can be written by accounts other than its owner`, + }); + expect(existsSync(path())).toBe(false); + }); + + describe("untrustedPathReason", () => { + const trusted = new Set([0, ME]); + + it("accepts a file only its owner can write, under directories only their owners can", () => { + const file = script(join(dir, "a", "b", "f"), "true"); + expect(untrustedPathReason(file, trusted)).toBeNull(); + expect(untrustedPathReason(join(dir, "a"), trusted, { dir: true })).toBeNull(); + expect(untrustedPathReason("/bin/sh", new Set([0]), { link: true })).toBeNull(); + }); + + it("names the first entry that belongs to someone else, or that others can write", () => { + const file = script(join(dir, "a", "f"), "true"); + if (ME !== 0) expect(untrustedPathReason(file, new Set([0]))).toMatch(/is owned by uid \d+$/); + chmodSync(file, 0o775); + expect(untrustedPathReason(file, trusted)).toBe(`${file} can be written by accounts other than its owner`); + chmodSync(file, 0o755); + chmodSync(join(dir, "a"), 0o757); + expect(untrustedPathReason(file, trusted)).toBe(`${join(dir, "a")} can be written by accounts other than its owner`); + }); + + it("accepts a sticky directory everyone can write, as /tmp is", () => { + const file = script(join(dir, "sticky", "own", "f"), "true"); + chmodSync(join(dir, "sticky"), 0o1777); + expect(untrustedPathReason(file, trusted)).toBeNull(); + }); + + it("refuses a link as the runner, and checks every directory a link passes through", () => { + const file = script(join(dir, "y", "f"), "true"); + // a/l -> x/l2 -> y/f, with x writable by others: resolving a/l reads x. + mkdirs(join(dir, "x")); + symlinkSync(file, join(dir, "x", "l2")); + chmodSync(join(dir, "x"), 0o777); + mkdirs(join(dir, "a")); + symlinkSync(join(dir, "x", "l2"), join(dir, "a", "l")); + expect(untrustedPathReason(join(dir, "a", "l"), trusted)).toBe(`${join(dir, "a", "l")} is a symbolic link`); + expect(untrustedPathReason(join(dir, "a", "l"), trusted, { link: true })).toBe( + `${join(dir, "x")} can be written by accounts other than its owner`, + ); + chmodSync(join(dir, "x"), 0o755); + expect(untrustedPathReason(join(dir, "a", "l"), trusted, { link: true })).toBeNull(); + }); + + it("refuses a relative path and one that is not there", () => { + expect(untrustedPathReason("bin/sh", trusted)).toBe("bin/sh is not an absolute path"); + expect(untrustedPathReason(join(dir, "nope"), trusted)).toBe(`${join(dir, "nope")} does not exist`); + }); + }); +}); + +describe("refreshCodexSystemHooks (failproofai update)", () => { + const path = () => join(dir, "etc", "codex", "config.toml"); + const runner = () => codexHookRunnerPath(path())!; + /** A block in the format earlier versions wrote: every hook runs `cli` itself. */ + const writeOlderBlock = (cli: string, before = "") => { + mkdirs(dirname(path())); + writeFileSync(path(), mergeCodexManagedBlock(before, renderCodexManagedBlock(codexSystemHookEntries(cli)))); + }; + + it("rewrites a block from before the runner to run it, for the account whose failproofai it ran", () => { + if (ME === 0) return; // root owns every file here, so the block would be the running account's + const cli = script(join(dir, "home", "failproofai"), "true"); + writeOlderBlock(cli, 'model = "o3"\n'); + expect(codexSystemHooksPresent({ path: path(), uid: 4242 })).toBe(true); // it runs for every account + expect(refreshCodexSystemHooks({ path: path(), uid: 4242 })).toEqual({ + status: "rewritten", + path: path(), + runner: runner(), + migrated: true, + dropped: [], + }); + expect(new Set(blockPrograms(path()))).toEqual(new Set([runner()])); + expect(readFileSync(path(), "utf8").startsWith('model = "o3"\n')).toBe(true); + // The failproofai it ran is this test's, so it runs for this test's uid and no other. + expect(parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts).toEqual([{ uid: ME, cli }]); + expect(codexSystemHooksPresent({ path: path(), uid: 4242 })).toBe(false); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ status: "current", path: path() }); + }); + + it("keeps the same events, arguments and timeouts", () => { + const cli = script(join(dir, "home", "failproofai"), "true"); + writeOlderBlock(cli); + refreshCodexSystemHooks({ path: path() }); + const text = readFileSync(path(), "utf8"); + expect(parseCodexManagedBlock(text)).toEqual( + codexSystemHookEntries(cli).map((e) => ({ ...e, command: e.command.replace(`"${cli}"`, `"${runner()}"`) })), + ); + }); + + it("takes out a block from before the runner rather than replace a file failproofai did not write", () => { + const cli = script(join(dir, "home", "failproofai"), "true"); + writeOlderBlock(cli); + script(runner(), "echo mine"); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ + status: "removed", + path: path(), + reason: `${runner()} is there, and failproofai did not write it`, + }); + expect(existsSync(path())).toBe(false); + expect(readFileSync(runner(), "utf8")).toBe("#!/bin/sh\necho mine\n"); + }); + + it("takes out a block from before the runner whose failproofai is gone", () => { + writeOlderBlock(join(dir, "gone", "failproofai")); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ + status: "removed", + path: path(), + reason: "the failproofai they ran is gone", + }); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); + + it("changes nothing without root, and says so", () => { + if (ME === 0) return; + const cli = script(join(dir, "home", "failproofai"), "true"); + writeOlderBlock(cli); + const before = readFileSync(path(), "utf8"); + chmodSync(dirname(path()), 0o555); + try { + expect(refreshCodexSystemHooks({ path: path(), canElevate: () => false })).toMatchObject({ status: "needs-root", path: path() }); + expect(readFileSync(path(), "utf8")).toBe(before); + } finally { + chmodSync(dirname(path()), 0o755); + } + }); + + it("takes the block out when the runner stops passing the check", () => { + expect(installCodexSystemHooks(myCli(), codexSystemHookEntries, { path: path(), codexVersion: CURRENT })).toMatchObject({ ok: true }); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ status: "current", path: path() }); + chmodSync(runner(), 0o777); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ + status: "removed", + path: path(), + reason: `${runner()} can be written by accounts other than its owner`, + }); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); + + it("takes the block out when its runner is missing or replaced", () => { + const install = () => installCodexSystemHooks(myCli(), codexSystemHookEntries, { path: path(), codexVersion: CURRENT }); + install(); + rmSync(runner()); + expect(refreshCodexSystemHooks({ path: path() })).toMatchObject({ status: "removed", reason: `${runner()} is missing` }); + install(); + rmSync(runner()); + symlinkSync("/bin/true", runner()); + expect(refreshCodexSystemHooks({ path: path() })).toMatchObject({ + status: "removed", + reason: `${runner()} was not written by failproofai`, + }); + expect(existsSync(path())).toBe(false); + }); + + it("says what changed, and how to finish when it needs root", () => { + expect(codexRefreshLines({ status: "current", path: path() })).toEqual([]); + expect(codexRefreshLines({ status: "rewritten", path: path(), runner: runner(), migrated: true, dropped: [] })[0]).toMatch(/^✓ Codex: /); + expect(codexRefreshLines({ status: "rewritten", path: path(), runner: runner(), migrated: false, dropped: [{ uid: 7, reason: "x" }] })).toEqual([ + `▲ Codex: took uid 7 out of failproofai's hooks in ${path()}: x.`, + " That account can run `failproofai config` to set them up again.", + ]); + expect(codexRefreshLines({ status: "others", path: path(), reason: "x" })).toEqual([ + `▲ Codex: failproofai's hooks in ${path()} need updating by an account that set them up, or by root: x.`, + ]); + expect(codexRefreshLines({ status: "removed", path: path(), reason: "x" })[0]).toMatch(/^▲ Codex: took/); + expect(codexRefreshLines({ status: "needs-root", path: path(), reason: "x" })).toEqual([ + `✕ Codex: failproofai's hooks in ${path()} need updating, which needs root: x.`, + " Run `sudo -v` and then `failproofai update` again.", + ]); + }); +}); + +describe("installing over a block from before the runner", () => { + const path = () => join(dir, "etc", "codex", "config.toml"); + const runner = () => codexHookRunnerPath(path())!; + + it("keeps it for the account whose failproofai it ran, and adds this one", () => { + if (ME === 0) return; // root owns every file here, so the block would be the running account's + const theirs = script(join(dir, "home", "failproofai"), "true"); + mkdirs(dirname(path())); + writeFileSync(path(), renderCodexManagedBlock(codexSystemHookEntries(theirs))); + // This account is not the one that owns `theirs`. + expect( + installCodexSystemHooks(myCli(), codexSystemHookEntries, { path: path(), codexVersion: CURRENT, uid: 4242 }), + ).toMatchObject({ ok: true, changed: true }); + expect(new Set(blockPrograms(path()))).toEqual(new Set([runner()])); + expect(parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts.map((a) => [a.uid, a.cli])).toEqual( + [[ME, theirs], [4242, myCli()]].sort((a, b) => Number(a[0]) - Number(b[0])), + ); + }); }); describe("trust", () => { @@ -304,13 +708,21 @@ describe("trust", () => { expect(codexHookTrust(deps())).toMatchObject({ kind: "untrusted", untrusted: 1 }); }); - it("is system (managed) whenever failproofai's block is in the system config", () => { + it("is system (managed) for every account while the block runs failproofai itself, as before the runner", () => { writeHooksJson(); mkdirSync(join(dir, "etc"), { recursive: true }); writeFileSync(systemPath(), BLOCK); expect(codexHookTrust(deps())).toEqual({ kind: "system", path: systemPath() }); }); + it("is system (managed) only for an account the hook runner runs failproofai for", () => { + writeHooksJson(); + writeFileSync(userConfig(), 'model = "o3"\n'); + expect(installCodexSystemHooks(myCli(), codexSystemHookEntries, deps({ uid: 4242 }))).toMatchObject({ ok: true }); + expect(codexHookTrust(deps({ uid: 4242 }))).toEqual({ kind: "system", path: systemPath() }); + expect(codexHookTrust(deps({ uid: 4243 }))).toMatchObject({ kind: "untrusted" }); + }); + it("is ungated on a Codex older than the trust gate", () => { writeHooksJson(); expect(codexHookTrust(deps({ codexVersion: () => "0.128.0" }))).toMatchObject({ kind: "ungated", version: "0.128.0" }); @@ -336,6 +748,169 @@ describe("trust", () => { }); }); +describe("the lines the runner keeps", () => { + const path = () => join(dir, "etc", "codex", "config.toml"); + const runner = () => codexHookRunnerPath(path())!; + const install = (over: Record = {}, cli = myCli()) => + installCodexSystemHooks(cli, codexSystemHookEntries, { path: path(), codexVersion: CURRENT, ...over }); + const accounts = () => parseCodexHookRunner(readFileSync(runner(), "utf8"))?.accounts; + + it("never gives root a line that runs anything another account can change", () => { + if (ME === 0) return; // root's own files are root's + // As on a real machine: root's line must be root's alone, and this test's file is an account's. + expect(install({ uid: 0, interpreter: "/bin/sh", trustedUids: [0] })).toMatchObject({ + ok: false, + reason: "unsafe", + detail: expect.stringMatching(/is owned by uid \d+$/), + }); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); + + it("runs root's own install through the interpreter it names, by absolute path", () => { + expect(install({ uid: 0, interpreter: "/bin/sh", trustedUids: [0, ME] }, "/bin/true")).toMatchObject({ ok: true }); + expect(readFileSync(runner(), "utf8")).toContain(` 0) exec '/bin/sh' '/bin/true' "$@" ;;`); + expect(accounts()).toEqual([expect.objectContaining({ uid: 0, interpreter: "/bin/sh", cli: "/bin/true" })]); + }); + + it("takes out a root line that names no interpreter", () => { + expect(install()).toMatchObject({ ok: true }); + const programs = parseCodexHookRunner(readFileSync(runner(), "utf8"))!.programs; + writeFileSync(runner(), renderCodexHookRunner([...accounts()!, { uid: 0, cli: "/bin/true" }], programs)); + expect(refreshCodexSystemHooks({ path: path() })).toMatchObject({ + status: "rewritten", + migrated: false, + dropped: [{ uid: 0, reason: "root's line must name the program that runs failproofai" }], + }); + expect(accounts()?.map((a) => a.uid)).toEqual([ME]); + }); + + it("refuses an account's line that runs another account's install", () => { + // This test's file, put forward as uid 4242's own failproofai. + expect(install({ uid: 4242, trustedUids: [0] })).toMatchObject({ + ok: false, + reason: "unsafe", + detail: expect.stringMatching(/is owned by uid \d+$/), + }); + expect(existsSync(path())).toBe(false); + }); + + it("accepts an install its own group can write, as a umask of 002 leaves it, but not one everyone can", () => { + const home = dirname(myCli()); + chmodSync(home, 0o775); + expect(install()).toMatchObject({ ok: true }); + chmodSync(home, 0o777); + expect(install()).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${home} can be written by accounts other than its owner`, + }); + // This account's old line goes too: its hooks are not in the system config now. + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); + + it("keeps another account's line that this account cannot read", () => { + if (ME === 0) return; // root reads everything + const locked = join(dir, "locked"); + const theirs = script(join(locked, "failproofai"), "true"); + expect(install({ uid: 4243 }, theirs)).toMatchObject({ ok: true }); + chmodSync(locked, 0o000); + try { + expect(install({ uid: 4242 })).toMatchObject({ ok: true, dropped: [] }); + expect(accounts()?.map((a) => a.uid)).toEqual([4242, 4243]); + expect(refreshCodexSystemHooks({ path: path(), uid: 4242 })).toEqual({ status: "current", path: path() }); + } finally { + chmodSync(locked, 0o755); + } + }); + + it("does not bring back accounts from a runner whose block was taken out", () => { + install({ uid: 4242 }); + install({ uid: 4243 }); + // Taken out by hand, or by an earlier version's uninstall: the runner stays. + writeFileSync(path(), mergeCodexManagedBlock(readFileSync(path(), "utf8"), null)); + expect(install({ uid: 4242 })).toMatchObject({ ok: true }); + expect(accounts()?.map((a) => a.uid)).toEqual([4242]); + }); + + it("tidies away a runner no block runs, on update", () => { + install(); + writeFileSync(path(), mergeCodexManagedBlock(readFileSync(path(), "utf8"), null)); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ status: "absent" }); + expect(existsSync(runner())).toBe(false); + }); + + it("drains an event larger than a pipe holds for an account it does not run, rather than leave Codex writing", () => { + install({ uid: 4242, programs: { sh: "/bin/sh", id: script(join(dir, "fake", "id"), 'echo "$FAKE_UID"'), cat: "/bin/cat" } }); + const text = readFileSync(path(), "utf8"); + const command = parseCodexManagedBlock(text.slice(text.indexOf(CODEX_MANAGED_BEGIN)))![0].command; + const big = JSON.stringify({ hook_event_name: "PostToolUse", tool_response: "x".repeat(256 * 1024) }); + const result = spawnSync("/bin/sh", ["-c", command], { + input: big, + env: { ...process.env, FAKE_UID: "0" }, + encoding: "utf8", + timeout: 10_000, + }); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(0); + expect(result.stdout).toBe(""); + }); +}); + +describe("a block in the earlier format", () => { + const path = () => join(dir, "etc", "codex", "config.toml"); + const runner = () => codexHookRunnerPath(path())!; + const writeOlderBlock = (cli: string) => { + mkdirs(dirname(path())); + writeFileSync(path(), renderCodexManagedBlock(codexSystemHookEntries(cli))); + }; + + it("is left as it is when everything it runs is root's alone", () => { + writeOlderBlock("/bin/true"); + const before = readFileSync(path(), "utf8"); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ status: "current", path: path() }); + expect(readFileSync(path(), "utf8")).toBe(before); + expect(existsSync(runner())).toBe(false); + }); + + it("asks no one for root, and fails no update, when it is not this account's", () => { + writeOlderBlock(myCli()); // this test's install, seen from uid 4242 + const before = readFileSync(path(), "utf8"); + let asked = 0; + const canElevate = () => { + asked++; + return true; + }; + expect(refreshCodexSystemHooks({ path: path(), uid: 4242, direct: false, canElevate })).toEqual({ + status: "others", + path: path(), + reason: "they predate the hook runner", + }); + expect(asked).toBe(0); + expect(readFileSync(path(), "utf8")).toBe(before); + // The account whose install it runs is asked, and told when root is not there. + expect(refreshCodexSystemHooks({ path: path(), direct: false, canElevate: () => false })).toMatchObject({ + status: "needs-root", + }); + }); +}); + +describe("codexHookRunnerPath and codexTrustedOwners", () => { + it("puts the runner in its own directory under /opt for Codex's config, and beside any other", () => { + expect(codexHookRunnerPath("/etc/codex/config.toml")).toBe("/opt/failproofai-codex/codex-hook"); + expect(codexHookRunnerPath("/tmp/x/config.toml")).toBe("/tmp/x/failproofai-codex-hook"); + expect(codexHookRunnerPath(null)).toBeNull(); + }); + + it("trusts root alone for Codex's config, and the directory's owner too for any other", () => { + expect([...codexTrustedOwners("/etc/codex/config.toml")]).toEqual([0]); + expect([...codexTrustedOwners(join(dir, "etc", "config.toml"))].sort()).toEqual([...new Set([0, ME])].sort()); + // A directory that does not exist yet: its nearest parent decides. + expect([...codexTrustedOwners("/usr/share/fp-codex-nonexistent/config.toml")]).toEqual([0]); + }); +}); + describe("codexSystemConfigPath", () => { it("honours the override, and `off` means none", () => { const saved = process.env.FAILPROOFAI_CODEX_SYSTEM_CONFIG; diff --git a/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts index 744d6121d..36f2077bf 100644 --- a/__tests__/hooks/update-run.test.ts +++ b/__tests__/hooks/update-run.test.ts @@ -20,9 +20,25 @@ const gateways = vi.hoisted(() => ({ restartOpenClawGateways: vi.fn(() => [] as unknown[]), openclawRestartLines: vi.fn((r: unknown[]) => (r.length > 0 ? ["OpenClaw:", " openclaw/default gateway restarting"] : [])), })); +const codexHooks = vi.hoisted(() => ({ + refreshCodexSystemHooks: vi.fn( + (): { + status: string; + path?: string; + runner?: string; + reason?: string; + migrated?: boolean; + dropped?: Array<{ uid: number; reason: string }>; + } => ({ status: "absent" }), + ), +})); vi.mock("../../src/hooks/daemon-service", () => svc); vi.mock("../../src/hooks/hermes-update", () => hermes); vi.mock("../../src/hooks/gateway-restart", () => gateways); +vi.mock("../../src/hooks/codex-system-hooks", async (importOriginal) => ({ + ...(await importOriginal()), + refreshCodexSystemHooks: codexHooks.refreshCodexSystemHooks, +})); import { markUpdated, @@ -134,6 +150,59 @@ describe("runUpdateSteps as update runs it", () => { }); }); +describe("Codex's system config, on every update", () => { + const AS_UPDATE = { layout: false, daemon: false, restart: false } as const; + + it("is checked, and a block rewritten to run through the hook runner is reported", async () => { + hermesWith("untouched"); + codexHooks.refreshCodexSystemHooks.mockReturnValueOnce({ + status: "rewritten", + path: "/etc/codex/config.toml", + runner: "/opt/failproofai-codex/codex-hook", + migrated: true, + dropped: [], + }); + const run = await runUpdateSteps(AS_UPDATE); + expect(codexHooks.refreshCodexSystemHooks).toHaveBeenCalledTimes(1); + expect(run).toMatchObject({ ok: true, changed: true }); + expect(run.lines).toContain( + "✓ Codex: failproofai's hooks in /etc/codex/config.toml now go through /opt/failproofai-codex/codex-hook,", + ); + }); + + it("fails the update when the hooks have to change and root was not available", async () => { + hermesWith("untouched"); + codexHooks.refreshCodexSystemHooks.mockReturnValueOnce({ + status: "needs-root", + path: "/etc/codex/config.toml", + reason: "they predate the hook runner", + }); + const run = await runUpdateSteps(AS_UPDATE); + expect(run.ok).toBe(false); + expect(run.lines).toContain(" Run `sudo -v` and then `failproofai update` again."); + }); + + it("tells an account the hooks are not for to ask one that set them up, without failing its update", async () => { + hermesWith("untouched"); + codexHooks.refreshCodexSystemHooks.mockReturnValueOnce({ + status: "others", + path: "/etc/codex/config.toml", + reason: "they predate the hook runner", + }); + const run = await runUpdateSteps(AS_UPDATE); + expect(run.ok).toBe(true); + expect(run.lines).toContain( + "▲ Codex: failproofai's hooks in /etc/codex/config.toml need updating by an account that set them up, or by root: they predate the hook runner.", + ); + }); + + it("says nothing when the hooks are current", async () => { + hermesWith("untouched"); + codexHooks.refreshCodexSystemHooks.mockReturnValueOnce({ status: "current", path: "/etc/codex/config.toml" }); + expect(await runUpdateSteps(AS_UPDATE)).toMatchObject({ ok: true, changed: false, lines: [] }); + }); +}); + describe("what config prints about it", () => { const r = (host: "hermes" | "openclaw", profile: string, status: string) => ({ host, profile, status }) as never; diff --git a/docs/reference/harnesses.mdx b/docs/reference/harnesses.mdx index e18706d84..1fde0e1ef 100644 --- a/docs/reference/harnesses.mdx +++ b/docs/reference/harnesses.mdx @@ -102,7 +102,13 @@ loads the updated plugin. Codex 0.129 and later runs a hook from `~/.codex/hooks.json` only after you approve it in interactive `codex` ("Review hooks"); until then, every Codex session — headless `codex exec` included — skips it. Hooks in Codex's system config, `/etc/codex/config.toml` on Linux and macOS, run without that approval. -So when `failproofai config` (or `policies --install --cli codex` at user scope) can use sudo, it writes the Codex hooks into `/etc/codex/config.toml`, between `# >>> failproofai managed hooks >>>` and `# <<< failproofai managed hooks <<<`, and leaves the rest of that file as it was. The file applies to every account on the machine. `failproofai uninstall` and unticking Codex in `failproofai config` take the block out again. +So when `failproofai config` (or `policies --install --cli codex` at user scope) can use sudo, it writes the Codex hooks into `/etc/codex/config.toml`, between `# >>> failproofai managed hooks >>>` and `# <<< failproofai managed hooks <<<`, and leaves the rest of that file as it was. + +That file applies to every account on the machine, so each hook in it runs `/opt/failproofai-codex/codex-hook`, a short script that root owns. The script hands the event to an account's own failproofai for each account that set the hooks up there, and does nothing for any other account. Another account that wants failproofai's Codex hooks sets them up for itself. + +Before writing the block, and again on every `failproofai update`, failproofai checks that the script, every directory above it, and the `sh`, `id` and `cat` it runs belong to root and can be written by no one else, and that each account's failproofai belongs to that account or root. On install, when that check fails, your hooks stay in `~/.codex/hooks.json`. On update, a script that fails it takes the block out, and an account whose failproofai fails it is taken out of the script; run `failproofai config` again once it is fixed. `failproofai update` also rewrites a block written by an earlier version to use the script, which needs sudo. + +`failproofai uninstall` and unticking Codex in `failproofai config` take your account out again, and the block with it once no account is left. Without sudo, and on Windows, the hooks stay in `~/.codex/hooks.json`. `failproofai config` and `failproofai config --status` then do not count Codex as enforcing until the hooks are approved, and say how to fix it: re-run `failproofai config` and allow sudo, or open `codex` once and approve the hooks. diff --git a/src/hooks/codex-system-hooks.ts b/src/hooks/codex-system-hooks.ts index 81693d321..13666cc2a 100644 --- a/src/hooks/codex-system-hooks.ts +++ b/src/hooks/codex-system-hooks.ts @@ -22,22 +22,47 @@ * de-duplicating, so leaving both would evaluate every tool call twice once the * user file is trusted. * + * One block serves every account on the machine, so its hooks run the hook + * runner (`/opt/failproofai-codex/codex-hook`), a short script root owns that + * runs an account's own failproofai for each account that set the hooks up, + * one line per uid, and decides nothing for any other. What it runs before it + * knows the account (the script, every directory above it, `sh`, `id` and + * `cat`), and what each line runs, is checked with {@link untrustedPathReason} + * on every install and every `failproofai update` ({@link refreshCodexSystemHooks}); + * a block that fails is taken out rather than kept. A block in the format + * earlier versions wrote is rewritten to use the runner. + * * Without root (or on Windows, whose system config lives elsewhere and is not * handled here) the hooks stay in `hooks.json`, and {@link codexHookTrust} * reads the user's `[hooks.state]` so `failproofai config` and * `config --status` stop counting Codex as enforcing until they are trusted. * - * Everything that touches `/etc` goes through the same non-interactive - * `sudo -n` the daemon install uses; `failproofai config` primes it first. + * Everything that touches `/etc` or `/opt` goes through the same + * non-interactive `sudo -n` the daemon install uses; `failproofai config` + * primes it first. */ import { execSync } from "node:child_process"; import { createHash } from "node:crypto"; -import { accessSync, chmodSync, constants as fsConstants, existsSync, readFileSync, rmSync, statSync } from "node:fs"; -import { homedir } from "node:os"; -import { dirname, resolve } from "node:path"; +import { + accessSync, + chmodSync, + constants as fsConstants, + existsSync, + lstatSync, + mkdirSync, + readFileSync, + readlinkSync, + rmSync, + rmdirSync, + statSync, + type Stats, +} from "node:fs"; +import { homedir, userInfo } from "node:os"; +import { dirname, isAbsolute, resolve } from "node:path"; import { canElevate, runPrivileged, writePrivilegedFile } from "./daemon-service"; import { writeConfigFileAtomic } from "./safe-config-write"; import { compareVersions } from "./semver-precedence"; +import { shellQuote } from "./shell-quote"; import { FAILPROOFAI_HOOK_MARKER } from "./types"; export const CODEX_MANAGED_BEGIN = "# >>> failproofai managed hooks >>>"; @@ -97,6 +122,19 @@ export function codexSystemBackupPath(path: string): string { return `${path}.failproofai-backup`; } +const RUNNER_UNIX = "/opt/failproofai-codex/codex-hook"; + +/** + * The hook runner every hook in the system config runs, for the system config + * at `configPath`: `/opt/failproofai-codex/codex-hook` for Codex's own (its own + * directory: `/opt/failproofai/` is the daemon's, per account), and a + * file beside any other config (a test's), so that no test reaches `/opt`. + */ +export function codexHookRunnerPath(configPath: string | null = codexSystemConfigPath()): string | null { + if (!configPath) return null; + return configPath === SYSTEM_CONFIG_UNIX ? RUNNER_UNIX : resolve(dirname(configPath), "failproofai-codex-hook"); +} + /** `codex --version`, as a bare semver, or null when there is no codex to ask. */ export function detectCodexVersion(): string | null { try { @@ -122,8 +160,10 @@ export function renderCodexManagedBlock(entries: readonly CodexSystemHookEntry[] const lines = [ CODEX_MANAGED_BEGIN, "# Written by failproofai. Codex runs hooks from its system config without", - "# asking to trust them. `failproofai uninstall` removes this block; edit", - "# outside the markers only, everything between them is replaced.", + "# asking to trust them. Each hook runs failproofai's hook runner, which runs", + "# failproofai for the accounts that set it up. `failproofai uninstall` takes", + "# an account out, and this block once none is left. Edit outside the markers", + "# only: everything between them is replaced.", ]; for (const entry of entries) { lines.push( @@ -227,22 +267,337 @@ export function conflictingHooksDefinition(text: string): string | null { return null; } -// ── Reading and writing the root-owned file ───────────────────────────────── +// ── The hook runner ───────────────────────────────────────────────────────── + +/** The line after the shebang that marks a hook runner as failproofai's. */ +export const CODEX_RUNNER_MARKER = "# failproofai Codex hook runner"; + +/** + * An account the hook runner runs failproofai for: its uid and its own + * failproofai. Root's line also names the program that runs failproofai + * (`interpreter`), so that nothing on it is looked up through PATH. + */ +export interface CodexRunnerAccount { + uid: number; + cli: string; + interpreter?: string; + /** The account's name, for whoever reads the file. */ + name?: string; +} + +/** + * The programs the hook runner uses before it knows whose hook it is running, + * by absolute path: its interpreter, `id` and `cat`. + */ +export interface CodexRunnerPrograms { + sh: string; + id: string; + cat: string; +} + +/** Root's own directories, the only ones the runner's programs come from. */ +const RUNNER_PROGRAM_DIRS = ["/bin", "/usr/bin"] as const; + +/** `sh`, `id` and `cat` from {@link RUNNER_PROGRAM_DIRS}, never through PATH; null when one is missing. */ +export function codexRunnerPrograms(): CodexRunnerPrograms | null { + const find = (name: string): string | null => { + for (const dir of RUNNER_PROGRAM_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; + }; + const sh = find("sh"); + const id = find("id"); + const cat = find("cat"); + return sh && id && cat ? { sh, id, cat } : null; +} + +const PROGRAM_PATH = /^\/[A-Za-z0-9._/-]+$/; + +/** + * The hook runner for `accounts`. Codex runs it with the event on stdin; it + * compares the uid it runs as with each account's and hands the event to that + * account's failproofai, or reads it and exits 0 (no decision) for an account + * that is not listed. Everything before that comparison is named by absolute + * path, and every path in a line is single-quoted. + */ +export function renderCodexHookRunner(accounts: readonly CodexRunnerAccount[], programs: CodexRunnerPrograms): string { + for (const program of [programs.sh, programs.id, programs.cat]) { + if (!PROGRAM_PATH.test(program)) throw new Error(`refusing to name ${JSON.stringify(program)} in the Codex hook runner`); + } + const arms = [...accounts] + .sort((a, b) => a.uid - b.uid) + .map((a) => { + const run = a.interpreter ? `${shellQuote(a.interpreter)} ${shellQuote(a.cli)}` : shellQuote(a.cli); + return ` ${a.uid}) exec ${run} "$@" ;;${a.name ? ` # ${a.name}` : ""}`; + }); + return [ + `#!${programs.sh}`, + CODEX_RUNNER_MARKER, + "# Codex runs every hook in its system config for every account. This runs", + "# an account's own failproofai only for the accounts listed below, each of", + "# which set it up, and for any other account reads the event and decides", + "# nothing. failproofai rewrites this file; `failproofai policies", + "# --uninstall --cli codex` takes an account out.", + `case "$(${programs.id} -u)" in`, + ...arms, + "esac", + `exec ${programs.cat} >/dev/null`, + "", + ].join("\n"); +} + +const RUNNER_ARM = /^ {2}(\d+)\) exec '((?:[^']|'\\'')*)'(?: '((?:[^']|'\\'')*)')? "\$@" ;;(?: # ([A-Za-z0-9._-]+))?$/; +const unquote = (word: string): string => word.replace(/'\\''/g, "'"); + +/** The accounts and programs in a hook runner failproofai wrote, or null for any other file. */ +export function parseCodexHookRunner( + text: string, +): { accounts: CodexRunnerAccount[]; programs: CodexRunnerPrograms } | null { + const lines = text.split("\n"); + if (lines[1] !== CODEX_RUNNER_MARKER) return null; + const sh = /^#!(\/\S+)$/.exec(lines[0])?.[1]; + const id = lines.map((line) => /^case "\$\((\/\S+) -u\)" in$/.exec(line)?.[1]).find(Boolean); + const cat = lines.map((line) => /^exec (\/\S+) >\/dev\/null$/.exec(line)?.[1]).find(Boolean); + if (!sh || !id || !cat) return null; + const accounts: CodexRunnerAccount[] = []; + for (const line of lines) { + const arm = RUNNER_ARM.exec(line); + if (!arm) continue; + const [, uid, first, second, name] = arm; + accounts.push({ + uid: Number(uid), + ...(second === undefined ? { cli: unquote(first) } : { interpreter: unquote(first), cli: unquote(second) }), + ...(name ? { name } : {}), + }); + } + return { accounts, programs: { sh, id, cat } }; +} + +// ── Who may change what the runner runs ───────────────────────────────────── + +/** Every name looked at while resolving a path, with its lstat; where it ends; whether its own last name is a link. */ +type Chain = { seen: Array<{ name: string; st: Stats }>; last: string; finalLink: boolean }; + +function resolveChain(path: string): Chain | { error: string; code?: string } { + if (!isAbsolute(path)) return { error: `${path} is not an absolute path` }; + const seen: Array<{ name: string; st: Stats }> = []; + let current = "/"; + let finalLink: boolean | null = null; + try { + seen.push({ name: "/", st: lstatSync("/") }); + const todo = path.split("/").filter((part) => part !== "" && part !== "."); + let links = 0; + while (todo.length > 0) { + const part = todo.shift()!; + if (part === "..") { + current = dirname(current); + continue; + } + const next = current === "/" ? `/${part}` : `${current}/${part}`; + const st = lstatSync(next); + seen.push({ name: next, st }); + // The first time nothing is left to resolve, this is the path's own last name. + if (todo.length === 0 && finalLink === null) finalLink = st.isSymbolicLink(); + if (st.isSymbolicLink()) { + if (++links > 40) return { error: `${path} goes through too many symbolic links` }; + const target = readlinkSync(next); + todo.unshift(...target.split("/").filter((p) => p !== "" && p !== ".")); + if (target.startsWith("/")) current = "/"; + continue; + } + current = next; + } + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + return { + error: code === "ENOENT" || code === "ENOTDIR" ? `${path} does not exist` : `${path} cannot be read (${code ?? err})`, + ...(code ? { code } : {}), + }; + } + return { seen, last: current, finalLink: finalLink ?? false }; +} + +/** + * Why an account outside `trusted` could change what `path` names, or null + * when none can. + * + * Walks the path the way the kernel resolves it, from `/`, following every + * symbolic link, and requires each directory, link and the final entry to be + * owned by a trusted uid. A directory others can write is allowed only with + * the sticky bit (`/tmp`), where no one renames or removes an entry another + * account owns; the final file must be writable by its owner alone. + * `groupWritable` lets a directory or file be writable by its group (an + * account's own install, which a umask of 002 leaves that way). `dir` expects + * a directory at the end; `link` accepts a symbolic link as the last name + * (`/bin/sh`), whose target is checked the same way. + */ +export function untrustedPathReason( + path: string, + trusted: ReadonlySet, + opts: { dir?: boolean; link?: boolean; groupWritable?: boolean } = {}, +): string | null { + const chain = resolveChain(path); + if ("error" in chain) return chain.error; + const { seen, last } = chain; + const others = opts.groupWritable ? 0o002 : 0o022; + if (!opts.link && chain.finalLink) return `${resolve(path)} is a symbolic link`; + for (const { name, st } of seen) { + if (!trusted.has(st.uid)) return `${name} is owned by uid ${st.uid}`; + if (st.isDirectory() && (st.mode & others) !== 0 && (st.mode & 0o1000) === 0) { + return `${name} can be written by accounts other than its owner`; + } + } + const end = seen[seen.length - 1].st; + if (opts.dir) return end.isDirectory() ? null : `${last} is not a directory`; + if (!end.isFile()) return `${last} is not a regular file`; + if ((end.mode & others) !== 0) return `${last} can be written by accounts other than its owner`; + return null; +} + +/** The uids that own anything resolving `path` goes through, root's left out; or why it does not resolve. */ +function pathOwners(path: string): Set | { error: string; code?: string } { + const chain = resolveChain(path); + if ("error" in chain) return chain; + const owners = new Set(chain.seen.map((e) => e.st.uid)); + owners.delete(0); + return owners; +} + +/** Another account's files that this process may not read: nothing can be judged about them from here. */ +function unreadableHere(path: string): boolean { + const chain = resolveChain(path); + return "error" in chain && (chain.code === "EACCES" || chain.code === "EPERM"); +} + +/** + * The uids whose files may sit where the runner and its programs are: root, + * and for a config path other than Codex's own (a test's), the owner of that + * path's directory, who can rewrite that config anyway. Root alone for + * `/etc/codex/config.toml`. + */ +export function codexTrustedOwners(configPath: string, deps: CodexSystemDeps = {}): ReadonlySet { + if (deps.trustedUids) return new Set(deps.trustedUids); + const owners = new Set([0]); + if (resolve(configPath) === SYSTEM_CONFIG_UNIX) return owners; + for (let dir = dirname(configPath); ; dir = dirname(dir)) { + try { + owners.add(statSync(dir).uid); + return owners; + } catch { + if (dirname(dir) === dir) return owners; + } + } +} + +/** Why the runner at `runner`, with `programs`, could run anything but root's before it knows the account. */ +function runnerProblem( + runner: string, + programs: CodexRunnerPrograms, + trusted: ReadonlySet, + written: boolean, +): string | null { + return ( + untrustedPathReason(dirname(runner), trusted, { dir: true }) ?? + (written ? untrustedPathReason(runner, trusted) : null) ?? + untrustedPathReason(programs.sh, trusted, { link: true }) ?? + untrustedPathReason(programs.id, trusted, { link: true }) ?? + untrustedPathReason(programs.cat, trusted, { link: true }) + ); +} + +/** + * Why the runner must not keep `account`'s line: what the line runs can be + * changed by an account other than that one or root. Root's line names its + * interpreter, and everything it runs must be root's alone, group included; + * another account's own install may be writable by its group. + */ +function accountProblem(account: CodexRunnerAccount, trusted: ReadonlySet): string | null { + if (!usableCliPath(account.cli)) return `${JSON.stringify(account.cli)} cannot go into the hook runner`; + // Another account's install under a home this process cannot enter (0750) + // is kept as it is: only what can be seen to fail is taken out. + if (unreadableHere(account.cli) || (account.interpreter && unreadableHere(account.interpreter))) return null; + if (account.uid === 0) { + if (!account.interpreter || !usableCliPath(account.interpreter)) { + return "root's line must name the program that runs failproofai"; + } + return ( + untrustedPathReason(account.interpreter, trusted, { link: true }) ?? + untrustedPathReason(account.cli, trusted, { link: true }) + ); + } + const own = new Set([...trusted, account.uid]); + return ( + (account.interpreter ? untrustedPathReason(account.interpreter, own, { link: true, groupWritable: true }) : null) ?? + untrustedPathReason(account.cli, own, { link: true, groupWritable: true }) + ); +} -/** Seams for tests: the file, the Codex version and the privileges. */ +// ── Reading and writing the root-owned files ──────────────────────────────── + +/** Seams for tests: the files, the Codex version, the privileges and the account. */ export interface CodexSystemDeps { /** The system config path; `null` = none on this machine. Default {@link codexSystemConfigPath}. */ path?: string | null; codexVersion?: () => string | null; canElevate?: () => boolean; + /** The hook runner. Default {@link codexHookRunnerPath} for the config. */ + runnerPath?: string; + /** The runner's `sh`, `id` and `cat`. Default {@link codexRunnerPrograms}. */ + programs?: CodexRunnerPrograms; + /** The uids whose files the runner may run. Default {@link codexTrustedOwners}. */ + trustedUids?: readonly number[]; + /** This account's uid. Default the process's. */ + uid?: number; + /** This account's name. Default the process's user. */ + userName?: string; + /** What runs failproofai on root's line. Default `process.execPath`. */ + interpreter?: string; + /** Write as this process (true) or through `sudo -n` (false). Default: whichever the files allow. */ + direct?: boolean; } function resolvedPath(deps: CodexSystemDeps): string | null { return deps.path !== undefined ? deps.path : codexSystemConfigPath(); } -/** True when this process can write `path` itself (root, or a test's temp dir). */ -function writableDirectly(path: string): boolean { +function resolvedRunner(deps: CodexSystemDeps, configPath: string): string { + return deps.runnerPath ?? codexHookRunnerPath(configPath)!; +} + +/** This account, or null where there are no uids (Windows). */ +function selfAccount(deps: CodexSystemDeps): { uid: number; name?: string } | null { + const uid = deps.uid ?? (typeof process.getuid === "function" ? process.getuid() : undefined); + if (uid === undefined) return null; + let name = deps.userName; + if (name === undefined) { + try { + name = userInfo().username; + } catch { + name = undefined; + } + } + return name && /^[A-Za-z0-9._-]+$/.test(name) ? { uid, name } : { uid }; +} + +/** A path the runner can name: absolute, on one line. */ +function usableCliPath(cli: string): boolean { + return isAbsolute(cli) && !/[\x00-\x1f\x7f]/.test(cli); +} + +/** + * True when this process can write `path` itself (root, or a test's temp dir). + * `replaced`: the file is only ever renamed over or removed, never written in + * place (the runner), so only its directory counts, whatever sits at `path`. + */ +function writableDirectly(path: string, replaced = false): boolean { let dir = dirname(path); while (!existsSync(dir)) { const parent = dirname(dir); @@ -251,7 +606,7 @@ function writableDirectly(path: string): boolean { } try { accessSync(dir, fsConstants.W_OK); - if (existsSync(path)) accessSync(path, fsConstants.W_OK); + if (!replaced && existsSync(path)) accessSync(path, fsConstants.W_OK); return true; } catch { return false; @@ -266,9 +621,18 @@ function fileMode(path: string): string { } } -function writeSystemFile(path: string, contents: string, mode: string, direct: boolean): void { +/** + * `replaceLink` replaces a symbolic link at `path` rather than writing through + * it: the runner must be the file failproofai wrote, wherever a link pointed. + * The mode is set when the file is created, not after, whatever the umask. + */ +function writeSystemFile(path: string, contents: string, mode: string, direct: boolean, replaceLink = false): void { if (direct) { - writeConfigFileAtomic(path, contents, { backup: false }); + writeConfigFileAtomic(path, contents, { + backup: false, + mode: parseInt(mode, 8), + ...(replaceLink ? { symlinks: "replace" as const } : {}), + }); chmodSync(path, parseInt(mode, 8)); return; } @@ -281,132 +645,634 @@ function removeSystemFile(path: string, direct: boolean): void { else runPrivileged("rm", ["-f", path]); } -/** Whether failproofai's block is in Codex's system config. Read-only, never throws. */ +/** Makes `dir` exist, each directory made here 0755 from the moment it is made. */ +function ensureSystemDir(dir: string, direct: boolean): void { + if (!direct) { + runPrivileged("install", ["-d", "-m", "0755", dir]); + return; + } + const missing: string[] = []; + for (let d = dir; !existsSync(d); d = dirname(d)) { + missing.unshift(d); + if (dirname(d) === d) break; + } + for (const d of missing) { + mkdirSync(d, { mode: 0o755 }); + chmodSync(d, 0o755); + } +} + +/** The program a hook command runs: the double-quoted path `buildHookEntry` puts first. */ +function commandProgram(command: string): string | null { + return /^"([^"]*)"(?= |$)/.exec(command)?.[1] ?? null; +} + +/** The hooks in a block of ours, read back as {@link renderCodexManagedBlock} wrote them, or null. */ +export function parseCodexManagedBlock(block: string): CodexSystemHookEntry[] | null { + const tables = block.match(/^\[\[hooks\.[A-Za-z]+\.hooks\]\]$/gm) ?? []; + const entries: CodexSystemHookEntry[] = []; + for (const m of block.matchAll(/^\[\[hooks\.([A-Za-z]+)\.hooks\]\]\ntype = "command"\ncommand = (".*")\ntimeout = (\d+)$/gm)) { + let command: unknown; + try { + command = JSON.parse(m[2]); + } catch { + return null; + } + if (typeof command !== "string") return null; + entries.push({ event: m[1], command, timeout: Number(m[3]) }); + } + return entries.length > 0 && entries.length === tables.length ? entries : null; +} + +/** What a block of ours runs: the runner, or (an earlier format) one program for every account. */ +type BlockForm = + | { kind: "runner"; entries: CodexSystemHookEntry[] } + | { kind: "direct"; entries: CodexSystemHookEntry[] | null; program: string | null }; + +function blockForm(block: string, runner: string): BlockForm { + const entries = parseCodexManagedBlock(block); + const programs = new Set((entries ?? []).map((e) => commandProgram(e.command))); + if (entries && programs.size === 1 && programs.has(runner)) return { kind: "runner", entries }; + const [program] = programs; + return { kind: "direct", entries, program: programs.size === 1 && program ? program : null }; +} + +/** + * Whose a block in the earlier format is, judged by the program it runs: + * - `root`: everything resolving it is root's alone, so it can stay as it is; + * - `account`: one account owns it (its own install), and keeps it through the runner; + * - `none`: it is gone, unreadable, or more than one account can change it. + * `owners` are the uids that own any part of it. + */ +type EarlierBlock = + | { kind: "root" } + | { kind: "account"; account: CodexRunnerAccount; owners: Set } + | { kind: "none"; reason: string; owners: Set } + /** Its program is under a directory this process cannot enter: nothing can be judged from here. */ + | { kind: "unknown"; owners: Set }; + +function earlierBlock(form: BlockForm, trusted: ReadonlySet, self: { uid: number; name?: string }): EarlierBlock { + if (form.kind !== "direct" || !form.program || !usableCliPath(form.program)) { + return { kind: "none", reason: "they could not be read back", owners: new Set() }; + } + const program = form.program; + const owners = pathOwners(program); + if (!(owners instanceof Set)) { + return owners.code === "EACCES" || owners.code === "EPERM" + ? { kind: "unknown", owners: new Set() } + : { kind: "none", reason: "the failproofai they ran is gone", owners: new Set() }; + } + if (owners.size === 0) { + const problem = untrustedPathReason(program, new Set([0]), { link: true }); + return problem ? { kind: "none", reason: problem, owners } : { kind: "root" }; + } + if (owners.size > 1) return { kind: "none", reason: `more than one account can change ${program}`, owners }; + const [uid] = owners; + const account: CodexRunnerAccount = { uid, cli: program, ...(uid === self.uid && self.name ? { name: self.name } : {}) }; + const problem = accountProblem(account, trusted); + return problem ? { kind: "none", reason: problem, owners } : { kind: "account", account, owners }; +} + +/** `lists`, one entry per uid, the later list winning. */ +function mergeAccounts(...lists: ReadonlyArray): CodexRunnerAccount[] { + const byUid = new Map(); + for (const list of lists) for (const account of list) byUid.set(account.uid, account); + return [...byUid.values()].sort((a, b) => a.uid - b.uid); +} + +type RunnerState = + | { kind: "absent" } + | { kind: "ours"; text: string; accounts: CodexRunnerAccount[]; programs: CodexRunnerPrograms } + | { kind: "foreign" }; + +function readRunner(runner: string): RunnerState { + let text: string; + try { + text = readFileSync(runner, "utf8"); + } catch (err) { + return (err as NodeJS.ErrnoException).code === "ENOENT" ? { kind: "absent" } : { kind: "foreign" }; + } + const parsed = parseCodexHookRunner(text); + return parsed ? { kind: "ours", text, ...parsed } : { kind: "foreign" }; +} + +/** The system config, failproofai's block in it, and the hook runner, as they are now. */ +interface SystemState { + path: string; + current: string; + existed: boolean; + span: { start: number; end: number } | null; + form: BlockForm | null; + runner: string; + runnerState: RunnerState; + trusted: ReadonlySet; +} + +function readSystemState(path: string, deps: CodexSystemDeps): SystemState | { error: string } { + let current = ""; + const existed = existsSync(path); + if (existed) { + try { + current = readFileSync(path, "utf8"); + } catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } + } + const span = findBlock(current); + if (span === "malformed") return { error: "failproofai's block has lost one of its markers" }; + const runner = resolvedRunner(deps, path); + return { + path, + current, + existed, + span, + form: span ? blockForm(current.slice(span.start, span.end), runner) : null, + runner, + runnerState: readRunner(runner), + trusted: codexTrustedOwners(path, deps), + }; +} + +/** + * The accounts the runner on disk names. Only while a block of ours is there: + * a runner left behind by a block taken out (by hand, or by an earlier + * version's uninstall) names accounts nothing runs any more. + */ +function runnerAccounts(state: SystemState): CodexRunnerAccount[] { + return state.span && state.runnerState.kind === "ours" ? state.runnerState.accounts : []; +} + +/** A block's hooks, each running `runner` instead of its program; null when they cannot be read back. */ +function retargetedBlock(form: BlockForm, runner: string): string | null { + if (!form.entries) return null; + const entries: CodexSystemHookEntry[] = []; + for (const entry of form.entries) { + const program = commandProgram(entry.command); + if (program === null) return null; + entries.push({ ...entry, command: `"${runner}"${entry.command.slice(program.length + 2)}` }); + } + return renderCodexManagedBlock(entries); +} + +/** An account taken out of the runner, and why. */ +export interface CodexDroppedAccount { + uid: number; + reason: string; +} + +type Applied = + | { ok: true; changed: boolean; dropped: CodexDroppedAccount[] } + | { ok: false; reason: "no-root" | "unsafe" | "write-failed"; detail?: string }; + +/** + * Puts the system config and the runner in the state that runs `accounts`' + * failproofai through `block` (null: the block already there), or takes both + * out when no account is left. An account whose line fails + * {@link accountProblem} is left out; the runner and its programs are checked + * before the block is written, and what was written is read back. When any of + * that fails, the block is taken out instead. + * + * `probe`: whether to ask `sudo -n` when this process cannot write the files + * itself. Without it, a change that needs root is reported as "no-root". + */ +function applySystemState( + state: SystemState, + want: { accounts: CodexRunnerAccount[]; block: string | null; programs: CodexRunnerPrograms | null; probe: boolean }, + deps: CodexSystemDeps, +): Applied { + const { path, current, span, runner, runnerState, trusted } = state; + const runnerOurs = runnerState.kind === "ours"; + const direct = deps.direct ?? (writableDirectly(path) && writableDirectly(runner, true)); + const elevate = (): boolean => direct || (want.probe && (deps.canElevate ?? canElevate)()); + const takeOut = (): void => { + if (span) { + const stripped = mergeCodexManagedBlock(current, null); + const backupPath = codexSystemBackupPath(path); + let backup: string | null = null; + try { + if (existsSync(backupPath)) backup = readFileSync(backupPath, "utf8"); + } catch { + backup = null; + } + if (backup !== null && (stripped === backup || stripped === `${backup}\n`)) { + // Nothing else changed since: put back the exact bytes. + writeSystemFile(path, backup, fileMode(path), direct); + removeSystemFile(backupPath, direct); + } else if (backup === null && stripped.trim() === "") { + // failproofai created this file, and it holds nothing of anyone else's. + removeSystemFile(path, direct); + } else { + writeSystemFile(path, stripped, fileMode(path), direct); + } + } + // After the block: Codex stops running the runner before it goes. + if (runnerOurs) removeSystemFile(runner, direct); + }; + const unsafe = (detail: string): Applied => { + takeOut(); + return { ok: false, reason: "unsafe", detail }; + }; + + const dropped: CodexDroppedAccount[] = []; + const kept = want.accounts.filter((account) => { + const problem = accountProblem(account, trusted); + if (problem) dropped.push({ uid: account.uid, reason: problem }); + return !problem; + }); + + try { + if (kept.length === 0) { + if (!span && !runnerOurs) return { ok: true, changed: false, dropped }; + if (!elevate()) return { ok: false, reason: "no-root" }; + takeOut(); + return { ok: true, changed: true, dropped }; + } + const programs = want.programs; + // A file failproofai did not write is never replaced: the block goes instead. + const refusal = + runnerState.kind === "foreign" + ? `${runner} is there, and failproofai did not write it` + : !programs + ? `no sh, id or cat in ${RUNNER_PROGRAM_DIRS.join(" or ")} for the hook runner` + : null; + if (refusal !== null || !programs) { + const detail = refusal ?? ""; + if (!span && !runnerOurs) return { ok: false, reason: "unsafe", detail }; + return elevate() ? unsafe(detail) : { ok: false, reason: "no-root", detail }; + } + const runnerText = renderCodexHookRunner(kept, programs); + const next = want.block === null ? current : mergeCodexManagedBlock(current, want.block); + const runnerChanged = runnerState.kind !== "ours" || runnerState.text !== runnerText; + if (!runnerChanged && next === current) { + const problem = runnerProblem(runner, programs, trusted, true); + if (!problem) return { ok: true, changed: false, dropped }; + return elevate() ? unsafe(problem) : { ok: false, reason: "no-root", detail: problem }; + } + if (!elevate()) return { ok: false, reason: "no-root" }; + + ensureSystemDir(dirname(runner), direct); + const before = runnerProblem(runner, programs, trusted, false); + if (before) return unsafe(before); + if (runnerChanged) writeSystemFile(runner, runnerText, "0755", direct, true); + // Read back: what Codex will run is what was meant, and only root can change it. + const after = untrustedPathReason(runner, trusted) ?? (readFileOr(runner) === runnerText ? null : `${runner} does not hold what failproofai wrote`); + if (after) { + takeOut(); + // Written by this call, so it is ours to remove even when it was not before. + if (!runnerOurs) removeSystemFile(runner, direct); + return { ok: false, reason: "unsafe", detail: after }; + } + if (next !== current) { + // Once: the file as it was before failproofai ever touched it. A file + // that already holds our block is not that, and an existing backup is kept. + const mode = state.existed ? fileMode(path) : "0644"; + const backup = codexSystemBackupPath(path); + if (state.existed && !span && !existsSync(backup)) writeSystemFile(backup, current, mode, direct); + writeSystemFile(path, next, mode, direct); + if (readFileOr(path) !== next) { + return unsafe(`${path} does not hold what failproofai wrote`); + } + } + return { ok: true, changed: true, dropped }; + } catch (err) { + return { ok: false, reason: "write-failed", detail: err instanceof Error ? err.message : String(err) }; + } +} + +function readFileOr(path: string): string | null { + try { + return readFileSync(path, "utf8"); + } catch { + return null; + } +} + +/** Removes the runner's own directory once it is empty; best effort. Never the system config's. */ +function tidyRunnerDir(state: SystemState, direct: boolean): void { + const dir = dirname(state.runner); + if (dir === dirname(state.path) || !existsSync(dir)) return; + try { + if (direct) rmdirSync(dir); + else runPrivileged("rmdir", [dir]); + } catch { + // Not empty, or not ours to remove: left as it is. + } +} + +/** + * Whether failproofai's Codex hooks in the system config run for this account: + * a block that runs the runner and a runner that lists this uid, or a block in + * the earlier format, which runs for every account. Read-only, never throws. + */ export function codexSystemHooksPresent(deps: CodexSystemDeps = {}): boolean { const path = resolvedPath(deps); if (!path) return false; try { - return hasCodexManagedBlock(readFileSync(path, "utf8")); + const text = readFileSync(path, "utf8"); + const span = findBlock(text); + if (span === null || span === "malformed") return false; + const runner = resolvedRunner(deps, path); + if (blockForm(text.slice(span.start, span.end), runner).kind === "direct") return true; + const self = selfAccount(deps); + const runnerState = readRunner(runner); + return !!self && runnerState.kind === "ours" && runnerState.accounts.some((a) => a.uid === self.uid); } catch { return false; } } export type CodexSystemInstall = - | { ok: true; path: string; changed: boolean } + | { ok: true; path: string; changed: boolean; dropped: CodexDroppedAccount[] } | { ok: false; - reason: "unsupported-platform" | "codex-not-found" | "codex-too-old" | "no-root" | "conflict" | "unreadable" | "write-failed"; + reason: + | "unsupported-platform" + | "codex-not-found" + | "codex-too-old" + | "no-root" + | "conflict" + | "unreadable" + | "unsafe" + | "write-failed"; detail?: string; path?: string; }; /** - * Write failproofai's Codex hooks into the system config, replacing only our - * block. Never prompts: it uses root, or a `sudo -n` that `failproofai config` - * primed. Every refusal leaves the file exactly as it was. + * Set this account's Codex hooks up in the system config: this account's uid + * and its failproofai, `cliPath`, go into the hook runner (with the accounts + * already there), and the block holds `entriesFor(runner)`, which must all run + * the runner. Replaces only our block. Never prompts: it uses root, or a + * `sudo -n` that `failproofai config` primed. + * + * Refused ("unsafe") when this account's line, the runner or its programs fail + * the ownership check; this account's hooks are then not in the system config. */ export function installCodexSystemHooks( - entries: readonly CodexSystemHookEntry[], + cliPath: string, + entriesFor: (runner: string) => readonly CodexSystemHookEntry[], deps: CodexSystemDeps = {}, ): CodexSystemInstall { const path = resolvedPath(deps); if (!path) return { ok: false, reason: "unsupported-platform" }; + const self = selfAccount(deps); + if (!self) return { ok: false, reason: "unsupported-platform" }; const version = (deps.codexVersion ?? detectCodexVersion)(); if (!version) return { ok: false, reason: "codex-not-found", path }; const cmp = compareVersions(version, CODEX_TRUST_GATE_VERSION); if (cmp !== null && cmp < 0) return { ok: false, reason: "codex-too-old", detail: version, path }; - let current = ""; - const existed = existsSync(path); - if (existed) { - try { - current = readFileSync(path, "utf8"); - } catch (err) { - return { ok: false, reason: "unreadable", detail: err instanceof Error ? err.message : String(err), path }; - } - } - const span = findBlock(current); - if (span === "malformed") { - return { ok: false, reason: "unreadable", detail: "failproofai's block has lost one of its markers", path }; - } + const state = readSystemState(path, deps); + if ("error" in state) return { ok: false, reason: "unreadable", detail: state.error, path }; + const { current, span, runner, runnerState, trusted } = state; const outside = span ? current.slice(0, span.start) + current.slice(span.end) : current; const conflict = conflictingHooksDefinition(outside); if (conflict) return { ok: false, reason: "conflict", detail: conflict, path }; + const entries = entriesFor(runner); + if (entries.length === 0 || entries.some((e) => commandProgram(e.command) !== runner)) { + return { ok: false, reason: "write-failed", detail: `every Codex system hook must run ${runner}`, path }; + } + const programs = codexRunnerProgramsFor(deps); + if (runnerState.kind === "foreign") { + // Our block must not run a file failproofai did not write: it is taken out, the file is left. + if (state.form?.kind === "runner") applySystemState(state, { accounts: [], block: null, programs: null, probe: true }, deps); + return { ok: false, reason: "conflict", detail: `${runner} is there, and failproofai did not write it`, path }; + } - const next = mergeCodexManagedBlock(current, renderCodexManagedBlock(entries)); - if (next === current) return { ok: true, path, changed: false }; + const mine: CodexRunnerAccount = { + ...self, + cli: cliPath, + ...(self.uid === 0 ? { interpreter: deps.interpreter ?? process.execPath } : {}), + }; + const earlier = state.form ? earlierAccounts(earlierBlock(state.form, trusted, self)) : []; + const others = mergeAccounts(earlier, runnerAccounts(state)).filter((a) => a.uid !== self.uid); + const problem = accountProblem(mine, trusted); + if (problem) { + // This account's hooks are not in the system config now: an old line of its own goes too. + if (runnerAccounts(state).some((a) => a.uid === self.uid)) { + applySystemState(state, { accounts: others, block: null, programs, probe: true }, deps); + } + return { ok: false, reason: "unsafe", detail: problem, path }; + } + const applied = applySystemState( + state, + { accounts: mergeAccounts(others, [mine]), block: renderCodexManagedBlock(entries), programs, probe: true }, + deps, + ); + if (!applied.ok) return { ok: false, reason: applied.reason, ...(applied.detail ? { detail: applied.detail } : {}), path }; + return { ok: true, path, changed: applied.changed, dropped: applied.dropped }; +} - const direct = writableDirectly(path); - if (!direct && !(deps.canElevate ?? canElevate)()) return { ok: false, reason: "no-root", path }; +function codexRunnerProgramsFor(deps: CodexSystemDeps): CodexRunnerPrograms | null { + return deps.programs ?? codexRunnerPrograms(); +} - try { - const mode = existed ? fileMode(path) : "0644"; - // Once: the file as it was before failproofai ever touched it. A file that - // already holds our block is not that, and an existing backup is kept. - const backup = codexSystemBackupPath(path); - if (existed && !span && !existsSync(backup)) writeSystemFile(backup, current, mode, direct); - writeSystemFile(path, next, mode, direct); - } catch (err) { - return { ok: false, reason: "write-failed", detail: err instanceof Error ? err.message : String(err), path }; - } - return { ok: true, path, changed: true }; +/** The account an earlier block keeps through the runner, if any. */ +function earlierAccounts(earlier: EarlierBlock): CodexRunnerAccount[] { + return earlier.kind === "account" ? [earlier.account] : []; } export type CodexSystemRemoval = | { status: "absent" } - | { status: "removed"; path: string; hooks: number } + | { status: "removed"; path: string; hooks: number; remaining: number } | { status: "failed"; path: string; reason: string }; /** - * Take failproofai's block out of the system config. The file is restored from - * its backup when what is left is exactly what was backed up, and deleted when - * failproofai created it and nothing else was ever added. + * Take this account out of failproofai's Codex hooks in the system config: + * out of the runner, and the block and runner out entirely when no account is + * left. The file is then restored from its backup when what is left is + * exactly what was backed up, and deleted when failproofai created it and + * nothing else was ever added. A block in the earlier format that another + * account's install ran is rewritten to run the runner, for that account only. */ export function removeCodexSystemHooks(deps: CodexSystemDeps = {}): CodexSystemRemoval { const path = resolvedPath(deps); if (!path || !existsSync(path)) return { status: "absent" }; - let current: string; - try { - current = readFileSync(path, "utf8"); - } catch (err) { - return { status: "failed", path, reason: err instanceof Error ? err.message : String(err) }; + const state = readSystemState(path, deps); + if ("error" in state) { + return { + status: "failed", + path, + reason: /marker/.test(state.error) ? "one of failproofai's markers is missing; remove the block by hand" : state.error, + }; } - const span = findBlock(current); - if (span === null) return { status: "absent" }; - if (span === "malformed") { - return { status: "failed", path, reason: `one of failproofai's markers is missing; remove the block by hand` }; + const { span, form } = state; + const self = selfAccount(deps); + if (!span || !form || !self) return { status: "absent" }; + + const earlier = form.kind === "direct" ? earlierBlock(form, state.trusted, self) : null; + const before = mergeAccounts(earlier ? earlierAccounts(earlier) : [], runnerAccounts(state)); + const programs = codexRunnerProgramsFor(deps); + // An earlier block runs for every account. It is another account's when that + // account's own install is what it runs, or when this account cannot read + // what it runs; otherwise it is this account's to remove. + const theirs = earlier?.kind === "unknown" || (earlier?.kind === "account" && earlier.account.uid !== self.uid); + const mine = before.some((a) => a.uid === self.uid) || (earlier !== null && !theirs); + if (!mine) { + // Another account's earlier block now runs only for that account, where + // root allows; nothing of this account's was there either way. + const block = earlier?.kind === "account" ? retargetedBlock(form, state.runner) : null; + if (block !== null) applySystemState(state, { accounts: before, block, programs, probe: true }, deps); + return { status: "absent" }; + } + let accounts = before.filter((a) => a.uid !== self.uid); + let block: string | null = null; + if (form.kind === "direct" && accounts.length > 0) { + block = retargetedBlock(form, state.runner); + // A block that cannot be read back is taken out rather than guessed at. + if (block === null) accounts = []; + } + const applied = applySystemState(state, { accounts, block, programs, probe: true }, deps); + if (applied.ok && accounts.length === 0) tidyRunnerDir(state, deps.direct ?? writableDirectly(state.runner, true)); + if (applied.ok || applied.reason === "unsafe") { + const hooks = (state.current.slice(span.start, span.end).match(/^\[\[hooks\.[A-Za-z]+\.hooks\]\]/gm) ?? []).length; + return { status: "removed", path, hooks, remaining: applied.ok ? accounts.length - applied.dropped.length : 0 }; } - const hooks = (current.slice(span.start, span.end).match(/^\[\[hooks\.[A-Za-z]+\.hooks\]\]/gm) ?? []).length; - const stripped = mergeCodexManagedBlock(current, null); + if (applied.reason === "no-root") return { status: "failed", path, reason: "removing it needs root, and sudo is not available" }; + return { status: "failed", path, reason: applied.detail ?? applied.reason }; +} - const backupPath = codexSystemBackupPath(path); - let backup: string | null = null; - try { - if (existsSync(backupPath)) backup = readFileSync(backupPath, "utf8"); - } catch { - backup = null; +export type CodexSystemRefresh = + /** No block of ours: nothing to check. */ + | { status: "absent" } + /** Nothing to change. */ + | { status: "current"; path: string } + /** Rewritten: an earlier block now runs the runner, or accounts were taken out of it. */ + | { status: "rewritten"; path: string; runner: string; migrated: boolean; dropped: CodexDroppedAccount[] } + /** The block failed the check, or had nothing left to run, and was taken out. */ + | { status: "removed"; path: string; reason: string } + /** It has to change, this account set it up, and changing it needs root, which was not available. */ + | { status: "needs-root"; path: string; reason: string } + /** It has to change, and only an account that set it up, or root, can do that. */ + | { status: "others"; path: string; reason: string } + | { status: "failed"; path: string; reason: string }; + +/** + * `failproofai update`'s check of the Codex hooks in the system config. A block + * that runs the runner keeps running only while the runner and each account's + * line pass the ownership check; a block in the earlier format is rewritten to + * run the runner, for the account whose own install it ran. Root is asked for + * (`sudo -n`) only when something has to change and this account is one of + * those it runs for, or owns what it runs: anyone else is told, and nothing + * is changed or asked for. + */ +export function refreshCodexSystemHooks(deps: CodexSystemDeps = {}): CodexSystemRefresh { + const path = resolvedPath(deps); + if (!path) return { status: "absent" }; + const state = existsSync(path) ? readSystemState(path, deps) : null; + if (state && "error" in state) return { status: "failed", path, reason: state.error }; + const self = selfAccount(deps); + if (!self) return { status: "absent" }; + if (!state || !state.form) { + // A runner with no block runs nothing; tidy it away where that needs no one. + const runner = resolvedRunner(deps, path); + if (readRunner(runner).kind === "ours" && (deps.direct ?? writableDirectly(runner, true))) { + try { + removeSystemFile(runner, true); + } catch { + // Best effort. + } + } + return { status: "absent" }; } + const { form, runner, runnerState } = state; + const listed = runnerAccounts(state).some((a) => a.uid === self.uid); - const direct = writableDirectly(path); - if (!direct && !(deps.canElevate ?? canElevate)()) { - return { status: "failed", path, reason: "removing it needs root, and sudo is not available" }; + const settle = ( + applied: Applied, + involved: boolean, + reason: string, + done: (a: Extract) => CodexSystemRefresh, + ): CodexSystemRefresh => { + if (applied.ok) return done(applied); + if (applied.reason === "no-root") { + return { status: involved ? "needs-root" : "others", path, reason: applied.detail ?? reason }; + } + if (applied.reason === "unsafe") return { status: "removed", path, reason: applied.detail ?? reason }; + return { status: "failed", path, reason: applied.detail ?? reason }; + }; + const programs = codexRunnerProgramsFor(deps); + + if (form.kind === "runner") { + const problem = + runnerState.kind === "ours" + ? runnerProblem(runner, runnerState.programs, state.trusted, true) + : runnerState.kind === "absent" + ? `${runner} is missing` + : `${runner} was not written by failproofai`; + if (problem) { + const applied = applySystemState(state, { accounts: [], block: null, programs: null, probe: listed }, deps); + return settle(applied, listed, problem, () => ({ status: "removed", path, reason: problem })); + } + const accounts = runnerAccounts(state); + if (accounts.every((a) => accountProblem(a, state.trusted) === null)) return { status: "current", path }; + const applied = applySystemState(state, { accounts, block: null, programs: runnerState.kind === "ours" ? runnerState.programs : programs, probe: listed }, deps); + const reason = "an account's failproofai can be changed by another account"; + return settle(applied, listed, reason, (a) => + a.changed ? { status: "rewritten", path, runner, migrated: false, dropped: a.dropped } : { status: "current", path }, + ); } - try { - if (backup !== null && (stripped === backup || stripped === `${backup}\n`)) { - // Nothing else changed since: put back the exact bytes. - writeSystemFile(path, backup, fileMode(path), direct); - removeSystemFile(backupPath, direct); - } else if (backup === null && stripped.trim() === "") { - // failproofai created this file, and it holds nothing of anyone else's. - removeSystemFile(path, direct); - } else { - writeSystemFile(path, stripped, fileMode(path), direct); + + // The earlier format: every hook runs one program, for every account. + const earlier = earlierBlock(form, state.trusted, self); + if (earlier.kind === "root") return { status: "current", path }; + if (earlier.kind === "unknown") { + return { status: "others", path, reason: "they run a failproofai this account cannot read" }; + } + const involved = listed || earlier.owners.has(self.uid); + const accounts = mergeAccounts(earlierAccounts(earlier), runnerAccounts(state)); + const block = retargetedBlock(form, runner); + if (accounts.length === 0 || block === null) { + const reason = earlier.kind === "none" ? earlier.reason : "they could not be read back"; + const applied = applySystemState(state, { accounts: [], block: null, programs: null, probe: involved }, deps); + return settle(applied, involved, reason, () => ({ status: "removed", path, reason })); + } + const applied = applySystemState(state, { accounts, block, programs, probe: involved }, deps); + return settle(applied, involved, "they predate the hook runner", (a) => ({ + status: "rewritten", + path, + runner, + migrated: true, + dropped: a.dropped, + })); +} + +/** What `failproofai update` says about {@link refreshCodexSystemHooks}' result; nothing when nothing changed. */ +export function codexRefreshLines(result: CodexSystemRefresh): string[] { + switch (result.status) { + case "absent": + case "current": + return []; + case "rewritten": { + const lines = result.migrated + ? [ + `✓ Codex: failproofai's hooks in ${result.path} now go through ${result.runner},`, + " which runs failproofai only for the accounts that set it up.", + ] + : []; + for (const { uid, reason } of result.dropped) { + lines.push(`▲ Codex: took uid ${uid} out of failproofai's hooks in ${result.path}: ${reason}.`); + } + if (result.dropped.length > 0) lines.push(" That account can run `failproofai config` to set them up again."); + return lines; } - } catch (err) { - return { status: "failed", path, reason: err instanceof Error ? err.message : String(err) }; + case "removed": + return [ + `▲ Codex: took failproofai's hooks out of ${result.path}: ${result.reason}.`, + " Run `failproofai config` to set them up again.", + ]; + case "needs-root": + return [ + `✕ Codex: failproofai's hooks in ${result.path} need updating, which needs root: ${result.reason}.`, + " Run `sudo -v` and then `failproofai update` again.", + ]; + case "others": + return [ + `▲ Codex: failproofai's hooks in ${result.path} need updating by an account that set them up, or by root: ${result.reason}.`, + ]; + case "failed": + return [`✕ Codex: could not check failproofai's hooks in ${result.path}: ${result.reason}.`]; } - return { status: "removed", path, hooks }; } // ── Trust ─────────────────────────────────────────────────────────────────── @@ -456,7 +1322,7 @@ export interface CodexTrustDeps extends CodexSystemDeps { */ export function codexHookTrust(deps: CodexTrustDeps = {}): CodexHookTrust { const systemPath = resolvedPath(deps); - if (systemPath && codexSystemHooksPresent({ path: systemPath })) return { kind: "system", path: systemPath }; + if (systemPath && codexSystemHooksPresent({ ...deps, path: systemPath })) return { kind: "system", path: systemPath }; const hooksJsonPath = deps.hooksJsonPath ?? resolve(codexHome(), "hooks.json"); const ours = failproofaiCodexHookIdentities(hooksJsonPath); diff --git a/src/hooks/integrations.ts b/src/hooks/integrations.ts index d055102c0..4dcda2b6c 100644 --- a/src/hooks/integrations.ts +++ b/src/hooks/integrations.ts @@ -577,12 +577,14 @@ export const codex: Integration = { /** * failproofai's user-scope Codex hooks, as the system config holds them: the - * same events, commands and timeouts `codex.buildHookEntry` writes to - * `~/.codex/hooks.json`. + * same events, arguments and timeouts `codex.buildHookEntry` writes to + * `~/.codex/hooks.json`, each running `runner`. That is Codex's hook runner + * (see ./codex-system-hooks), never an account's own failproofai: Codex runs + * the system config for every account on the machine. */ -export function codexSystemHookEntries(binaryPath: string): CodexSystemHookEntry[] { +export function codexSystemHookEntries(runner: string): CodexSystemHookEntry[] { return CODEX_HOOK_EVENT_TYPES.map((eventType) => { - const entry = codex.buildHookEntry(binaryPath, eventType, "user") as { command: string; timeout: number }; + const entry = codex.buildHookEntry(runner, eventType, "user") as { command: string; timeout: number }; return { event: CODEX_EVENT_MAP[eventType as CodexHookEventType], command: entry.command, timeout: entry.timeout }; }); } diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index f147f3df5..d75810bcf 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -856,18 +856,23 @@ async function installHooksImpl( const writtenSettingsPaths: { cli: IntegrationType; path: string }[] = []; // Why Codex's user-scope hooks went to hooks.json rather than its system config. let codexFallback: CodexSystemInstall | null = null; + // Other accounts the system config's hook runner stopped running failproofai for. + let codexDropped: string[] = []; for (const cliId of selectedClis) { const integration = getIntegration(cliId); // Codex runs a hooks.json hook only once a person has trusted it, so a // headless `codex exec` skips every one of ours. Its system config is // trusted as managed: put user-scope hooks there whenever root allows, and // take them out of hooks.json so a trusted copy does not run them twice. + // The system config applies to every account, so its hooks run the hook + // runner, which runs this binary for this account only. if (cliId === "codex" && scope === "user") { - const placed = installCodexSystemHooks(codexSystemHookEntries(binaryPath)); + const placed = installCodexSystemHooks(binaryPath, codexSystemHookEntries); if (placed.ok) { const userPath = integration.getSettingsPath("user", cwd); if (existsSync(userPath)) integration.removeHooksFromFile(userPath); writtenSettingsPaths.push({ cli: cliId, path: placed.path }); + codexDropped = placed.dropped.map((d) => `uid ${d.uid}: ${d.reason}`); continue; } codexFallback = placed; @@ -962,9 +967,18 @@ async function installHooksImpl( } if (scope === "project") console.log(`${INDENT}This file can be committed to git: it has no machine-specific paths.`); + for (const dropped of codexDropped) { + console.log(kit.caution(`Took an account out of failproofai's Codex hooks in Codex's system config (${dropped}).`)); + } + // Codex on hooks.json: say so when Codex will not run them yet. if (codexFallback && !codexFallback.ok) { - if (codexFallback.reason === "conflict" || codexFallback.reason === "unreadable" || codexFallback.reason === "write-failed") { + if ( + codexFallback.reason === "conflict" || + codexFallback.reason === "unreadable" || + codexFallback.reason === "unsafe" || + codexFallback.reason === "write-failed" + ) { console.log( kit.caution(`Couldn't add the Codex hooks to ${codexFallback.path}: ${codexFallback.detail ?? codexFallback.reason}.`), ); @@ -1135,7 +1149,13 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al if (system.status === "removed") { removedFromSystem = system.hooks; if (scope !== "all") { - say(screenKit(optsFor(process.stdout)).ok(`Removed ${system.hooks} failproofai ${system.hooks === 1 ? "hook" : "hooks"} from Codex's system config.`)); + say( + screenKit(optsFor(process.stdout)).ok( + system.remaining > 0 + ? `Took this account out of failproofai's Codex hooks in Codex's system config; ${system.remaining} other ${system.remaining === 1 ? "account keeps" : "accounts keep"} them.` + : `Removed ${system.hooks} failproofai ${system.hooks === 1 ? "hook" : "hooks"} from Codex's system config.`, + ), + ); for (const line of screenKit(optsFor(process.stdout)).kv([["settings", system.path]])) say(line); } } else if (system.status === "failed") { diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts index de6daa7a7..64b13fb9c 100644 --- a/src/hooks/update-run.ts +++ b/src/hooks/update-run.ts @@ -111,6 +111,26 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise 0) { + lines.push("", ...codexLines); + changed = true; + } + codexOk = refreshed.status !== "needs-root" && refreshed.status !== "failed"; + } catch (err) { + lines.push("", `✕ Codex: could not check failproofai's hooks: ${err instanceof Error ? err.message : String(err)}`); + codexOk = false; + } + // Hermes is migrated AFTER the daemon, and gated on what the daemon that is // now running can do: the native plugin needs `policyEvaluation`, which // ≤1.0.5 daemons lack, so when the swap above could not happen (a sudo @@ -169,7 +189,7 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise Date: Tue, 24 Nov 2026 21:28:37 +0530 Subject: [PATCH 2/7] [hooks] Name the PR in the CHANGELOG entry for the Codex system hooks Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 433e83cdd..cb3bef888 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ - The daemon download is checked against the digest recorded in the npm package as well as the release's `SHA256SUMS`, which comes from the same release as the binary and so cannot catch a replaced asset (#1056) - `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) -- Harden the Codex system hooks. The hooks failproofai writes into `/etc/codex/config.toml` now run `/opt/failproofai-codex/codex-hook`, a short root-owned script that hands each event to the failproofai of the account that set the hooks up, one line per account. Install and every `failproofai update` check that the script, the directories above it, the `sh`, `id` and `cat` it runs, and each account's own failproofai can be changed only by root or that account; a block that fails is taken out, and an account that fails is taken out of the script. `update` rewrites a block from an earlier version to use the script, which needs sudo; an account the block does not run for gets a notice instead of a failed update. Uninstalling takes out only your account (#PR_NUMBER) +- Harden the Codex system hooks. The hooks failproofai writes into `/etc/codex/config.toml` now run `/opt/failproofai-codex/codex-hook`, a short root-owned script that hands each event to the failproofai of the account that set the hooks up, one line per account. Install and every `failproofai update` check that the script, the directories above it, the `sh`, `id` and `cat` it runs, and each account's own failproofai can be changed only by root or that account; a block that fails is taken out, and an account that fails is taken out of the script. `update` rewrites a block from an earlier version to use the script, which needs sudo; an account the block does not run for gets a notice instead of a failed update. Uninstalling takes out only your account (#1061) - 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) ### Docs From 9074f6ae2e0794d99bd1577493fa82f4e1450c30 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 21:57:04 +0530 Subject: [PATCH 3/7] [hooks] Tighten the Codex hook runner's checks and its writes - An account's line may be group-writable only through the account's own private group, as /etc/passwd and /etc/group describe it. - A runner directory that already exists is checked as it is, never re-moded first by `install -d`. - After the block is written, the config and the runner are read back. A mismatch undoes this call's writes: the config as it was, the runner as it was or removed. - Install fails when this account's own line is dropped while writing, and says so when its earlier line could not be removed. - Update writes a runner again when it was edited by hand or lost its 0755 mode. It removes a runner with no block only once it is 10 minutes old, and tells an account the hooks are not its own what to do. - The managed block parses with CRLF line endings. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 18 +- .../codex-system-hooks-privileged.test.ts | 27 ++- __tests__/hooks/codex-system-hooks.test.ts | 66 +++++- __tests__/hooks/update-run.test.ts | 1 + src/hooks/codex-system-hooks.ts | 205 ++++++++++++++---- 5 files changed, 269 insertions(+), 48 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 41287e9c9..6f383f57c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,14 +49,22 @@ or `/usr/bin`. Rules that keep it safe: `failproofai update` (`refreshCodexSystemHooks`, a step in `update-run.ts`). A runner that fails takes the block out; a line that fails is taken out of the runner. - **Each line runs only that account's own install.** An account's line must resolve - through files owned by root or that account (its group may write them: a umask of 002). - Root's line must be root's alone, group included, and names its interpreter by absolute - path, so nothing on it goes through PATH. Another account's line that this process - cannot read (a 0750 home) is kept as it is. + through files owned by root or that account. Its group may write them only when it is + the account's private group, as a umask of 002 leaves an install: its primary group, + named after it, nobody else's primary group and no other member in `/etc/passwd` and + `/etc/group` (`isPrivateGroup`). Root's line must be root's alone, group included, and + names its interpreter by absolute path, so nothing on it goes through PATH. Another + account's line that this process cannot read (a 0750 home) is kept as it is. +- **What root wrote is read back.** The runner and the config are compared with what was + meant once the block is in; anything else undoes this call's writes. A runner edited by + hand or no longer 0755 is written again on update. A directory that already exists is + never re-moded before it is checked. - **One block, many accounts.** Install adds this uid and keeps the others. Uninstall removes only this uid, and the block and runner once none is left. `codexSystemHooksPresent()` / `codexHookTrust()` answer for **this** uid. A runner with - no block is stale: its lines are never merged back. + no block is stale: its lines are never merged back, and update removes it once it is + 10 minutes old (an install writes the runner before the block). There is no lock: two + accounts installing at the same moment can lose one line. - **Earlier blocks.** A block in the format earlier versions wrote is rewritten to run the runner for the account that owns the program it ran; one whose program is root's alone is left as it is. `update` asks for root (`sudo -n`) only when this account is one the diff --git a/__tests__/hooks/codex-system-hooks-privileged.test.ts b/__tests__/hooks/codex-system-hooks-privileged.test.ts index 8344eb977..35bbf0586 100644 --- a/__tests__/hooks/codex-system-hooks-privileged.test.ts +++ b/__tests__/hooks/codex-system-hooks-privileged.test.ts @@ -68,10 +68,8 @@ describe("the Codex system hooks, written as root", () => { it("makes the runner's directory, then writes the runner 0755 and the config 0644, all through root", () => { expect(install()).toMatchObject({ ok: true, changed: true }); expect(root.calls).toEqual([ - { op: "install", args: ["-d", "-m", "0755", dirname(runner())] }, { op: "install", args: ["-d", "-m", "0755", dirname(runner())] }, { op: "write", args: [runner(), "0755"] }, - { op: "install", args: ["-d", "-m", "0755", dirname(path())] }, { op: "write", args: [path(), "0644"] }, ]); expect(readFileSync(path(), "utf8")).toContain(CODEX_MANAGED_BEGIN); @@ -90,6 +88,31 @@ describe("the Codex system hooks, written as root", () => { expect(root.calls.at(-1)).toEqual({ op: "rm", args: ["-f", runner()] }); }); + it("judges a directory that is already there as it is, never tightening it first", () => { + expect(install()).toMatchObject({ ok: true }); + chmodSync(dirname(runner()), 0o775); + root.calls.length = 0; + expect(install()).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${dirname(runner())} can be written by accounts other than its owner`, + }); + expect(root.calls.some((c) => c.op === "install")).toBe(false); + expect(existsSync(path())).toBe(false); + }); + + it("undoes its own writes when the config root wrote does not hold what was meant", () => { + root.tamper.set(path(), "something else\n"); + expect(install()).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${path()} does not hold what failproofai wrote`, + }); + // A config this call created, and the runner it wrote, are both gone. + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); + it("removes the config it created, then the runner, through root", () => { expect(install()).toMatchObject({ ok: true }); root.calls.length = 0; diff --git a/__tests__/hooks/codex-system-hooks.test.ts b/__tests__/hooks/codex-system-hooks.test.ts index 9998840f4..eca8a4f1d 100644 --- a/__tests__/hooks/codex-system-hooks.test.ts +++ b/__tests__/hooks/codex-system-hooks.test.ts @@ -19,6 +19,7 @@ import { rmSync, statSync, symlinkSync, + utimesSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; @@ -506,6 +507,7 @@ describe("refreshCodexSystemHooks (failproofai update)", () => { }); it("keeps the same events, arguments and timeouts", () => { + if (ME === 0) return; // root owns every file here, so this account's files are root's alone const cli = script(join(dir, "home", "failproofai"), "true"); writeOlderBlock(cli); refreshCodexSystemHooks({ path: path() }); @@ -516,6 +518,7 @@ describe("refreshCodexSystemHooks (failproofai update)", () => { }); it("takes out a block from before the runner rather than replace a file failproofai did not write", () => { + if (ME === 0) return; // root owns every file here, so this account's files are root's alone const cli = script(join(dir, "home", "failproofai"), "true"); writeOlderBlock(cli); script(runner(), "echo mine"); @@ -590,6 +593,10 @@ describe("refreshCodexSystemHooks (failproofai update)", () => { ]); expect(codexRefreshLines({ status: "others", path: path(), reason: "x" })).toEqual([ `▲ Codex: failproofai's hooks in ${path()} need updating by an account that set them up, or by root: x.`, + " If you set them up, run `failproofai config`; otherwise tell whoever administers this machine.", + ]); + expect(codexRefreshLines({ status: "rewritten", path: path(), runner: runner(), migrated: false, dropped: [] })).toEqual([ + `✓ Codex: rewrote failproofai's hook runner, ${runner()}, which had changed since it was written.`, ]); expect(codexRefreshLines({ status: "removed", path: path(), reason: "x" })[0]).toMatch(/^▲ Codex: took/); expect(codexRefreshLines({ status: "needs-root", path: path(), reason: "x" })).toEqual([ @@ -786,6 +793,7 @@ describe("the lines the runner keeps", () => { }); it("refuses an account's line that runs another account's install", () => { + if (ME === 0) return; // root owns every file here, so this account's files are root's alone // This test's file, put forward as uid 4242's own failproofai. expect(install({ uid: 4242, trustedUids: [0] })).toMatchObject({ ok: false, @@ -795,12 +803,28 @@ describe("the lines the runner keeps", () => { expect(existsSync(path())).toBe(false); }); - it("accepts an install its own group can write, as a umask of 002 leaves it, but not one everyone can", () => { + it("accepts an install its own private group can write, as a umask of 002 leaves it, but no other group, nor everyone", () => { + if (ME === 0) return; // root's line takes no group at all const home = dirname(myCli()); + const gid = statSync(home).gid; + const own = { users: [{ name: "me", uid: ME, gid }], groups: [{ name: "me", gid, members: [] }] }; chmodSync(home, 0o775); - expect(install()).toMatchObject({ ok: true }); + expect(install({ accounts: own })).toMatchObject({ ok: true }); + // The same group, shared: another account's primary group, a listed member, or a name not the account's. + for (const shared of [ + { users: [...own.users, { name: "other", uid: ME + 1, gid }], groups: own.groups }, + { users: own.users, groups: [{ name: "me", gid, members: ["other"] }] }, + { users: own.users, groups: [{ name: "staff", gid, members: [] }] }, + ]) { + expect(install({ accounts: shared })).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${home} can be written by accounts other than its owner`, + }); + expect(install({ accounts: own })).toMatchObject({ ok: true }); + } chmodSync(home, 0o777); - expect(install()).toMatchObject({ + expect(install({ accounts: own })).toMatchObject({ ok: false, reason: "unsafe", detail: `${home} can be written by accounts other than its owner`, @@ -834,13 +858,46 @@ describe("the lines the runner keeps", () => { expect(accounts()?.map((a) => a.uid)).toEqual([4242]); }); - it("tidies away a runner no block runs, on update", () => { + it("tidies away a runner no block runs, on update, once no install can be about to add its block", () => { install(); writeFileSync(path(), mergeCodexManagedBlock(readFileSync(path(), "utf8"), null)); + // Just written: an install may be between writing the runner and the block. + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ status: "absent" }); + expect(existsSync(runner())).toBe(true); + const old = new Date(Date.now() - 11 * 60 * 1000); + utimesSync(runner(), old, old); expect(refreshCodexSystemHooks({ path: path() })).toEqual({ status: "absent" }); expect(existsSync(runner())).toBe(false); }); + it("writes the runner again when it was edited by hand or lost its mode", () => { + expect(install()).toMatchObject({ ok: true }); + const written = readFileSync(runner(), "utf8"); + writeFileSync(runner(), written.replace("esac\n", "esac\nexit 0\n")); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ + status: "rewritten", + path: path(), + runner: runner(), + migrated: false, + dropped: [], + }); + expect(readFileSync(runner(), "utf8")).toBe(written); + chmodSync(runner(), 0o644); + expect(refreshCodexSystemHooks({ path: path() })).toMatchObject({ status: "rewritten", dropped: [] }); + expect(statSync(runner()).mode & 0o777).toBe(0o755); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ status: "current", path: path() }); + }); + + it("reads a block whose lines an editor turned into CRLF", () => { + expect(install({ uid: 4242 })).toMatchObject({ ok: true }); + writeFileSync(path(), readFileSync(path(), "utf8").replace(/\n/g, "\r\n")); + const text = readFileSync(path(), "utf8"); + expect(parseCodexManagedBlock(text)).toHaveLength(codex.eventTypes.length); + // Still the runner's block: only the account it lists runs failproofai. + expect(codexSystemHooksPresent({ path: path(), uid: 4242 })).toBe(true); + expect(codexSystemHooksPresent({ path: path(), uid: 4243 })).toBe(false); + }); + it("drains an event larger than a pipe holds for an account it does not run, rather than leave Codex writing", () => { install({ uid: 4242, programs: { sh: "/bin/sh", id: script(join(dir, "fake", "id"), 'echo "$FAKE_UID"'), cat: "/bin/cat" } }); const text = readFileSync(path(), "utf8"); @@ -875,6 +932,7 @@ describe("a block in the earlier format", () => { }); it("asks no one for root, and fails no update, when it is not this account's", () => { + if (ME === 0) return; // root owns every file here, so this account's files are root's alone writeOlderBlock(myCli()); // this test's install, seen from uid 4242 const before = readFileSync(path(), "utf8"); let asked = 0; diff --git a/__tests__/hooks/update-run.test.ts b/__tests__/hooks/update-run.test.ts index 36f2077bf..66b8c2fc4 100644 --- a/__tests__/hooks/update-run.test.ts +++ b/__tests__/hooks/update-run.test.ts @@ -194,6 +194,7 @@ describe("Codex's system config, on every update", () => { expect(run.lines).toContain( "▲ Codex: failproofai's hooks in /etc/codex/config.toml need updating by an account that set them up, or by root: they predate the hook runner.", ); + expect(run.lines).toContain(" If you set them up, run `failproofai config`; otherwise tell whoever administers this machine."); }); it("says nothing when the hooks are current", async () => { diff --git a/src/hooks/codex-system-hooks.ts b/src/hooks/codex-system-hooks.ts index 13666cc2a..c32ab93fd 100644 --- a/src/hooks/codex-system-hooks.ts +++ b/src/hooks/codex-system-hooks.ts @@ -434,34 +434,79 @@ function resolveChain(path: string): Chain | { error: string; code?: string } { * owned by a trusted uid. A directory others can write is allowed only with * the sticky bit (`/tmp`), where no one renames or removes an entry another * account owns; the final file must be writable by its owner alone. - * `groupWritable` lets a directory or file be writable by its group (an - * account's own install, which a umask of 002 leaves that way). `dir` expects - * a directory at the end; `link` accepts a symbolic link as the last name - * (`/bin/sh`), whose target is checked the same way. + * `groupOk` lets a directory or file be writable by its group when that + * group passes it (an account's own private group, which a umask of 002 + * leaves writing its install). `dir` expects a directory at the end; `link` + * accepts a symbolic link as the last name (`/bin/sh`), whose target is + * checked the same way. */ export function untrustedPathReason( path: string, trusted: ReadonlySet, - opts: { dir?: boolean; link?: boolean; groupWritable?: boolean } = {}, + opts: { dir?: boolean; link?: boolean; groupOk?: (gid: number) => boolean } = {}, ): string | null { const chain = resolveChain(path); if ("error" in chain) return chain.error; const { seen, last } = chain; - const others = opts.groupWritable ? 0o002 : 0o022; if (!opts.link && chain.finalLink) return `${resolve(path)} is a symbolic link`; + const othersWrite = (st: Stats): boolean => + (st.mode & 0o002) !== 0 || ((st.mode & 0o020) !== 0 && !(opts.groupOk?.(st.gid) ?? false)); for (const { name, st } of seen) { if (!trusted.has(st.uid)) return `${name} is owned by uid ${st.uid}`; - if (st.isDirectory() && (st.mode & others) !== 0 && (st.mode & 0o1000) === 0) { + if (st.isDirectory() && othersWrite(st) && (st.mode & 0o1000) === 0) { return `${name} can be written by accounts other than its owner`; } } const end = seen[seen.length - 1].st; if (opts.dir) return end.isDirectory() ? null : `${last} is not a directory`; if (!end.isFile()) return `${last} is not a regular file`; - if ((end.mode & others) !== 0) return `${last} can be written by accounts other than its owner`; + if (othersWrite(end)) return `${last} can be written by accounts other than its owner`; return null; } +/** Accounts and groups, as /etc/passwd and /etc/group list them. */ +export interface CodexAccountsDb { + users: Array<{ name: string; uid: number; gid: number }>; + groups: Array<{ name: string; gid: number; members: string[] }>; +} + +function readAccountsDb(deps: CodexSystemDeps): CodexAccountsDb { + if (deps.accounts) return deps.accounts; + const rows = (file: string): string[][] => { + try { + return readFileSync(file, "utf8") + .split("\n") + .filter((line) => line !== "" && !line.startsWith("#")) + .map((line) => line.split(":")); + } catch { + return []; + } + }; + return { + users: rows("/etc/passwd") + .filter((f) => f.length >= 4) + .map((f) => ({ name: f[0], uid: Number(f[2]), gid: Number(f[3]) })), + groups: rows("/etc/group") + .filter((f) => f.length >= 3) + .map((f) => ({ name: f[0], gid: Number(f[2]), members: (f[3] ?? "").split(",").filter(Boolean) })), + }; +} + +/** + * Whether `gid` is `uid`'s own private group, which a umask of 002 makes safe + * to leave writing its files: its primary group, named after it, no other + * account's primary group, and listing no other member. Only what /etc/passwd + * and /etc/group say counts, so a group they cannot vouch for is not private. + */ +function isPrivateGroup(uid: number, gid: number, db: CodexAccountsDb): boolean { + const user = db.users.find((u) => u.uid === uid); + if (!user || user.gid !== gid) return false; + const group = db.groups.find((g) => g.gid === gid); + if (!group || group.name !== user.name) return false; + if (db.users.some((u) => u.gid === gid && u.uid !== uid)) return false; + return group.members.every((member) => member === user.name); +} + /** The uids that own anything resolving `path` goes through, root's left out; or why it does not resolve. */ function pathOwners(path: string): Set | { error: string; code?: string } { const chain = resolveChain(path); @@ -517,9 +562,9 @@ function runnerProblem( * Why the runner must not keep `account`'s line: what the line runs can be * changed by an account other than that one or root. Root's line names its * interpreter, and everything it runs must be root's alone, group included; - * another account's own install may be writable by its group. + * another account's own install may be writable by its private group. */ -function accountProblem(account: CodexRunnerAccount, trusted: ReadonlySet): string | null { +function accountProblem(account: CodexRunnerAccount, trusted: ReadonlySet, db: CodexAccountsDb): string | null { if (!usableCliPath(account.cli)) return `${JSON.stringify(account.cli)} cannot go into the hook runner`; // Another account's install under a home this process cannot enter (0750) // is kept as it is: only what can be seen to fail is taken out. @@ -534,9 +579,10 @@ function accountProblem(account: CodexRunnerAccount, trusted: ReadonlySet isPrivateGroup(account.uid, gid, db); return ( - (account.interpreter ? untrustedPathReason(account.interpreter, own, { link: true, groupWritable: true }) : null) ?? - untrustedPathReason(account.cli, own, { link: true, groupWritable: true }) + (account.interpreter ? untrustedPathReason(account.interpreter, own, { link: true, groupOk }) : null) ?? + untrustedPathReason(account.cli, own, { link: true, groupOk }) ); } @@ -562,6 +608,8 @@ export interface CodexSystemDeps { interpreter?: string; /** Write as this process (true) or through `sudo -n` (false). Default: whichever the files allow. */ direct?: boolean; + /** /etc/passwd and /etc/group, read. Default the files. */ + accounts?: CodexAccountsDb; } function resolvedPath(deps: CodexSystemDeps): string | null { @@ -636,7 +684,7 @@ function writeSystemFile(path: string, contents: string, mode: string, direct: b chmodSync(path, parseInt(mode, 8)); return; } - runPrivileged("install", ["-d", "-m", "0755", dirname(path)]); + if (!existsSync(dirname(path))) runPrivileged("install", ["-d", "-m", "0755", dirname(path)]); writePrivilegedFile(path, contents, mode); } @@ -645,8 +693,13 @@ function removeSystemFile(path: string, direct: boolean): void { else runPrivileged("rm", ["-f", path]); } -/** Makes `dir` exist, each directory made here 0755 from the moment it is made. */ +/** + * Makes `dir` exist, each directory made here 0755 from the moment it is made. + * One that is already there keeps its mode: the ownership check judges it as + * it is, rather than after root has quietly tightened it. + */ function ensureSystemDir(dir: string, direct: boolean): void { + if (existsSync(dir)) return; if (!direct) { runPrivileged("install", ["-d", "-m", "0755", dir]); return; @@ -669,9 +722,11 @@ function commandProgram(command: string): string | null { /** The hooks in a block of ours, read back as {@link renderCodexManagedBlock} wrote them, or null. */ export function parseCodexManagedBlock(block: string): CodexSystemHookEntry[] | null { - const tables = block.match(/^\[\[hooks\.[A-Za-z]+\.hooks\]\]$/gm) ?? []; + // Line endings an editor may have changed; the bytes themselves are left as they are. + const text = block.replace(/\r\n/g, "\n"); + const tables = text.match(/^\[\[hooks\.[A-Za-z]+\.hooks\]\]$/gm) ?? []; const entries: CodexSystemHookEntry[] = []; - for (const m of block.matchAll(/^\[\[hooks\.([A-Za-z]+)\.hooks\]\]\ntype = "command"\ncommand = (".*")\ntimeout = (\d+)$/gm)) { + for (const m of text.matchAll(/^\[\[hooks\.([A-Za-z]+)\.hooks\]\]\ntype = "command"\ncommand = (".*")\ntimeout = (\d+)$/gm)) { let command: unknown; try { command = JSON.parse(m[2]); @@ -711,7 +766,12 @@ type EarlierBlock = /** Its program is under a directory this process cannot enter: nothing can be judged from here. */ | { kind: "unknown"; owners: Set }; -function earlierBlock(form: BlockForm, trusted: ReadonlySet, self: { uid: number; name?: string }): EarlierBlock { +function earlierBlock( + form: BlockForm, + trusted: ReadonlySet, + self: { uid: number; name?: string }, + db: CodexAccountsDb, +): EarlierBlock { if (form.kind !== "direct" || !form.program || !usableCliPath(form.program)) { return { kind: "none", reason: "they could not be read back", owners: new Set() }; } @@ -729,7 +789,7 @@ function earlierBlock(form: BlockForm, trusted: ReadonlySet, self: { uid if (owners.size > 1) return { kind: "none", reason: `more than one account can change ${program}`, owners }; const [uid] = owners; const account: CodexRunnerAccount = { uid, cli: program, ...(uid === self.uid && self.name ? { name: self.name } : {}) }; - const problem = accountProblem(account, trusted); + const problem = accountProblem(account, trusted, db); return problem ? { kind: "none", reason: problem, owners } : { kind: "account", account, owners }; } @@ -742,18 +802,35 @@ function mergeAccounts(...lists: ReadonlyArray): type RunnerState = | { kind: "absent" } - | { kind: "ours"; text: string; accounts: CodexRunnerAccount[]; programs: CodexRunnerPrograms } + | { + kind: "ours"; + text: string; + accounts: CodexRunnerAccount[]; + programs: CodexRunnerPrograms; + /** Exactly what {@link renderCodexHookRunner} writes for these accounts: nothing added by hand. */ + canonical: boolean; + mode: number; + } | { kind: "foreign" }; function readRunner(runner: string): RunnerState { let text: string; + let mode: number; try { text = readFileSync(runner, "utf8"); + mode = statSync(runner).mode & 0o7777; } catch (err) { return (err as NodeJS.ErrnoException).code === "ENOENT" ? { kind: "absent" } : { kind: "foreign" }; } const parsed = parseCodexHookRunner(text); - return parsed ? { kind: "ours", text, ...parsed } : { kind: "foreign" }; + if (!parsed) return { kind: "foreign" }; + let canonical = false; + try { + canonical = renderCodexHookRunner(parsed.accounts, parsed.programs) === text; + } catch { + canonical = false; + } + return { kind: "ours", text, ...parsed, canonical, mode }; } /** The system config, failproofai's block in it, and the hook runner, as they are now. */ @@ -766,6 +843,7 @@ interface SystemState { runner: string; runnerState: RunnerState; trusted: ReadonlySet; + accounts: CodexAccountsDb; } function readSystemState(path: string, deps: CodexSystemDeps): SystemState | { error: string } { @@ -790,6 +868,7 @@ function readSystemState(path: string, deps: CodexSystemDeps): SystemState | { e runner, runnerState: readRunner(runner), trusted: codexTrustedOwners(path, deps), + accounts: readAccountsDb(deps), }; } @@ -875,7 +954,7 @@ function applySystemState( const dropped: CodexDroppedAccount[] = []; const kept = want.accounts.filter((account) => { - const problem = accountProblem(account, trusted); + const problem = accountProblem(account, trusted, state.accounts); if (problem) dropped.push({ uid: account.uid, reason: problem }); return !problem; }); @@ -902,7 +981,7 @@ function applySystemState( } const runnerText = renderCodexHookRunner(kept, programs); const next = want.block === null ? current : mergeCodexManagedBlock(current, want.block); - const runnerChanged = runnerState.kind !== "ours" || runnerState.text !== runnerText; + const runnerChanged = runnerState.kind !== "ours" || runnerState.text !== runnerText || runnerState.mode !== 0o755; if (!runnerChanged && next === current) { const problem = runnerProblem(runner, programs, trusted, true); if (!problem) return { ok: true, changed: false, dropped }; @@ -927,10 +1006,25 @@ function applySystemState( // that already holds our block is not that, and an existing backup is kept. const mode = state.existed ? fileMode(path) : "0644"; const backup = codexSystemBackupPath(path); - if (state.existed && !span && !existsSync(backup)) writeSystemFile(backup, current, mode, direct); + const wroteBackup = state.existed && !span && !existsSync(backup); + if (wroteBackup) writeSystemFile(backup, current, mode, direct); writeSystemFile(path, next, mode, direct); - if (readFileOr(path) !== next) { - return unsafe(`${path} does not hold what failproofai wrote`); + // Read back both, now the block names the runner: anything else, and + // this call's writes are undone (the config as it was, the runner as it + // was or gone), so nothing unverified is left for Codex to run. + const failed = + readFileOr(path) !== next + ? `${path} does not hold what failproofai wrote` + : readFileOr(runner) !== runnerText + ? `${runner} changed while failproofai was writing the block` + : null; + if (failed) { + if (state.existed) writeSystemFile(path, current, mode, direct); + else removeSystemFile(path, direct); + if (wroteBackup) removeSystemFile(backup, direct); + if (runnerState.kind === "ours") writeSystemFile(runner, runnerState.text, "0755", direct, true); + else removeSystemFile(runner, direct); + return { ok: false, reason: "unsafe", detail: failed }; } } return { ok: true, changed: true, dropped }; @@ -939,6 +1033,17 @@ function applySystemState( } } +/** How old a runner with no block must be before update tidies it away: an install writes the runner first. */ +const STALE_RUNNER_MS = 10 * 60 * 1000; + +function statSafe(path: string): Stats | null { + try { + return statSync(path); + } catch { + return null; + } +} + function readFileOr(path: string): string | null { try { return readFileSync(path, "utf8"); @@ -1044,13 +1149,17 @@ export function installCodexSystemHooks( cli: cliPath, ...(self.uid === 0 ? { interpreter: deps.interpreter ?? process.execPath } : {}), }; - const earlier = state.form ? earlierAccounts(earlierBlock(state.form, trusted, self)) : []; + const earlier = state.form ? earlierAccounts(earlierBlock(state.form, trusted, self, state.accounts)) : []; const others = mergeAccounts(earlier, runnerAccounts(state)).filter((a) => a.uid !== self.uid); - const problem = accountProblem(mine, trusted); + const problem = accountProblem(mine, trusted, state.accounts); if (problem) { // This account's hooks are not in the system config now: an old line of its own goes too. if (runnerAccounts(state).some((a) => a.uid === self.uid)) { - applySystemState(state, { accounts: others, block: null, programs, probe: true }, deps); + const cleaned = applySystemState(state, { accounts: others, block: null, programs, probe: true }, deps); + if (!cleaned.ok && cleaned.reason !== "unsafe") { + const stale = `${problem}; this account's earlier line is still in ${runner} (run \`sudo -v\`, then this again)`; + return { ok: false, reason: "unsafe", detail: stale, path }; + } } return { ok: false, reason: "unsafe", detail: problem, path }; } @@ -1060,6 +1169,9 @@ export function installCodexSystemHooks( deps, ); if (!applied.ok) return { ok: false, reason: applied.reason, ...(applied.detail ? { detail: applied.detail } : {}), path }; + // Its own failproofai changed between the check and the write (a package being replaced). + const lost = applied.dropped.find((d) => d.uid === self.uid); + if (lost) return { ok: false, reason: "unsafe", detail: lost.reason, path }; return { ok: true, path, changed: applied.changed, dropped: applied.dropped }; } @@ -1100,7 +1212,7 @@ export function removeCodexSystemHooks(deps: CodexSystemDeps = {}): CodexSystemR const self = selfAccount(deps); if (!span || !form || !self) return { status: "absent" }; - const earlier = form.kind === "direct" ? earlierBlock(form, state.trusted, self) : null; + const earlier = form.kind === "direct" ? earlierBlock(form, state.trusted, self, state.accounts) : null; const before = mergeAccounts(earlier ? earlierAccounts(earlier) : [], runnerAccounts(state)); const programs = codexRunnerProgramsFor(deps); // An earlier block runs for every account. It is another account's when that @@ -1164,9 +1276,14 @@ export function refreshCodexSystemHooks(deps: CodexSystemDeps = {}): CodexSystem const self = selfAccount(deps); if (!self) return { status: "absent" }; if (!state || !state.form) { - // A runner with no block runs nothing; tidy it away where that needs no one. + // A runner with no block runs nothing; tidy it away where that needs no + // one, once it is old enough that no install can be about to add its block. const runner = resolvedRunner(deps, path); - if (readRunner(runner).kind === "ours" && (deps.direct ?? writableDirectly(runner, true))) { + if ( + readRunner(runner).kind === "ours" && + (deps.direct ?? writableDirectly(runner, true)) && + Date.now() - (statSafe(runner)?.mtimeMs ?? Date.now()) > STALE_RUNNER_MS + ) { try { removeSystemFile(runner, true); } catch { @@ -1205,16 +1322,27 @@ export function refreshCodexSystemHooks(deps: CodexSystemDeps = {}): CodexSystem return settle(applied, listed, problem, () => ({ status: "removed", path, reason: problem })); } const accounts = runnerAccounts(state); - if (accounts.every((a) => accountProblem(a, state.trusted) === null)) return { status: "current", path }; - const applied = applySystemState(state, { accounts, block: null, programs: runnerState.kind === "ours" ? runnerState.programs : programs, probe: listed }, deps); - const reason = "an account's failproofai can be changed by another account"; + const linesOk = accounts.every((a) => accountProblem(a, state.trusted, state.accounts) === null); + // Edited by hand, or no longer 0755 (an account Codex runs it for could not run it): written again. + const runnerOk = runnerState.kind === "ours" && runnerState.canonical && runnerState.mode === 0o755; + if (linesOk && runnerOk) return { status: "current", path }; + const applied = applySystemState( + state, + { accounts, block: null, programs: runnerState.kind === "ours" ? runnerState.programs : programs, probe: listed }, + deps, + ); + const reason = runnerOk + ? "an account's failproofai can be changed by another account" + : `${runner} changed since failproofai wrote it`; return settle(applied, listed, reason, (a) => - a.changed ? { status: "rewritten", path, runner, migrated: false, dropped: a.dropped } : { status: "current", path }, + a.changed + ? { status: "rewritten", path, runner, migrated: false, dropped: a.dropped } + : { status: "current", path }, ); } // The earlier format: every hook runs one program, for every account. - const earlier = earlierBlock(form, state.trusted, self); + const earlier = earlierBlock(form, state.trusted, self, state.accounts); if (earlier.kind === "root") return { status: "current", path }; if (earlier.kind === "unknown") { return { status: "others", path, reason: "they run a failproofai this account cannot read" }; @@ -1249,7 +1377,9 @@ export function codexRefreshLines(result: CodexSystemRefresh): string[] { `✓ Codex: failproofai's hooks in ${result.path} now go through ${result.runner},`, " which runs failproofai only for the accounts that set it up.", ] - : []; + : result.dropped.length === 0 + ? [`✓ Codex: rewrote failproofai's hook runner, ${result.runner}, which had changed since it was written.`] + : []; for (const { uid, reason } of result.dropped) { lines.push(`▲ Codex: took uid ${uid} out of failproofai's hooks in ${result.path}: ${reason}.`); } @@ -1269,6 +1399,7 @@ export function codexRefreshLines(result: CodexSystemRefresh): string[] { case "others": return [ `▲ Codex: failproofai's hooks in ${result.path} need updating by an account that set them up, or by root: ${result.reason}.`, + " If you set them up, run `failproofai config`; otherwise tell whoever administers this machine.", ]; case "failed": return [`✕ Codex: could not check failproofai's hooks in ${result.path}: ${result.reason}.`]; From 9bd5d82c41cfbd87207ca8079ab975853b56facd Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 22:09:28 +0530 Subject: [PATCH 4/7] [hooks] Take out this account's earlier Codex block when install refuses it When install refuses this account's failproofai, it now also takes out a block in the earlier format that runs that install for every account. Before, it did so only when the runner listed the account. A block that is another account's, or that this account cannot read, is still left to that account. Co-Authored-By: Claude Opus 5.5 --- __tests__/hooks/codex-system-hooks.test.ts | 22 ++++++++++++++++++++++ src/hooks/codex-system-hooks.ts | 20 +++++++++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/__tests__/hooks/codex-system-hooks.test.ts b/__tests__/hooks/codex-system-hooks.test.ts index eca8a4f1d..4a5cd58f7 100644 --- a/__tests__/hooks/codex-system-hooks.test.ts +++ b/__tests__/hooks/codex-system-hooks.test.ts @@ -834,6 +834,28 @@ describe("the lines the runner keeps", () => { expect(existsSync(runner())).toBe(false); }); + it("takes out an earlier block that runs this account's install when it refuses that install", () => { + if (ME === 0) return; // root's line takes no group at all + const cli = myCli(); + const home = dirname(cli); + const gid = statSync(home).gid; + // The install's directory is writable by a group other accounts are in. + const shared = { + users: [{ name: "me", uid: ME, gid }, { name: "other", uid: ME + 1, gid }], + groups: [{ name: "me", gid, members: [] }], + }; + chmodSync(home, 0o775); + mkdirs(dirname(path())); + writeFileSync(path(), renderCodexManagedBlock(codexSystemHookEntries(cli))); + expect(install({ accounts: shared })).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${home} can be written by accounts other than its owner`, + }); + expect(existsSync(path())).toBe(false); + expect(existsSync(runner())).toBe(false); + }); + it("keeps another account's line that this account cannot read", () => { if (ME === 0) return; // root reads everything const locked = join(dir, "locked"); diff --git a/src/hooks/codex-system-hooks.ts b/src/hooks/codex-system-hooks.ts index c32ab93fd..22267d2d3 100644 --- a/src/hooks/codex-system-hooks.ts +++ b/src/hooks/codex-system-hooks.ts @@ -1149,13 +1149,23 @@ export function installCodexSystemHooks( cli: cliPath, ...(self.uid === 0 ? { interpreter: deps.interpreter ?? process.execPath } : {}), }; - const earlier = state.form ? earlierAccounts(earlierBlock(state.form, trusted, self, state.accounts)) : []; - const others = mergeAccounts(earlier, runnerAccounts(state)).filter((a) => a.uid !== self.uid); + const earlierInfo = state.form?.kind === "direct" ? earlierBlock(state.form, trusted, self, state.accounts) : null; + const others = mergeAccounts(earlierInfo ? earlierAccounts(earlierInfo) : [], runnerAccounts(state)).filter( + (a) => a.uid !== self.uid, + ); const problem = accountProblem(mine, trusted, state.accounts); if (problem) { - // This account's hooks are not in the system config now: an old line of its own goes too. - if (runnerAccounts(state).some((a) => a.uid === self.uid)) { - const cleaned = applySystemState(state, { accounts: others, block: null, programs, probe: true }, deps); + // This account's hooks are not in the system config now: an old line of + // its own goes too, and so does an earlier block that runs this account's + // install for every account. Another account's earlier block, or one this + // account cannot read, is left to that account. + const earlierMine = + (earlierInfo?.kind === "account" || earlierInfo?.kind === "none") && earlierInfo.owners.has(self.uid); + if (runnerAccounts(state).some((a) => a.uid === self.uid) || earlierMine) { + const form = state.form!; + const block = form.kind === "direct" && others.length > 0 ? retargetedBlock(form, runner) : null; + const keep = form.kind === "direct" && block === null ? [] : others; + const cleaned = applySystemState(state, { accounts: keep, block, programs, probe: true }, deps); if (!cleaned.ok && cleaned.reason !== "unsafe") { const stale = `${problem}; this account's earlier line is still in ${runner} (run \`sudo -v\`, then this again)`; return { ok: false, reason: "unsafe", detail: stale, path }; From 278257e6d5458d1d4cf741d875542a897d02c608 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 22:19:53 +0530 Subject: [PATCH 5/7] [hooks] Accept a private group only where local files list every account /etc/passwd and /etc/group can prove a group is an account's own only when /etc/nsswitch.conf takes accounts and groups from files, compat (no +/- entries) or systemd alone. With LDAP, SSSD, NIS or winbind configured, a group-writable install is refused, and that account keeps hooks.json. When install refuses this account's failproofai, it also takes out an earlier block that no account owns: a program that is root's but that others can change, or one that is gone. The e2e test runs the in-tree CLI through a wrapper in its own 0755 directory, so a checkout made with umask 002 does not decide the test. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 ++- .../e2e/cli/codex-system-hooks.e2e.test.ts | 22 ++++++--- __tests__/hooks/codex-system-hooks.test.ts | 26 ++++++++--- src/hooks/codex-system-hooks.ts | 45 ++++++++++++++++++- 4 files changed, 84 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6f383f57c..bf53606da 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,7 +52,10 @@ or `/usr/bin`. Rules that keep it safe: through files owned by root or that account. Its group may write them only when it is the account's private group, as a umask of 002 leaves an install: its primary group, named after it, nobody else's primary group and no other member in `/etc/passwd` and - `/etc/group` (`isPrivateGroup`). Root's line must be root's alone, group included, and + `/etc/group` (`isPrivateGroup`), and only where `/etc/nsswitch.conf` takes accounts + and groups from `files`, `compat` (no `+`/`-` entries) or `systemd` alone. With LDAP, + SSSD, NIS or winbind in it, those files cannot prove a group private, so such an + install is refused and that account keeps `hooks.json` (or runs `chmod -R g-w` on it). Root's line must be root's alone, group included, and names its interpreter by absolute path, so nothing on it goes through PATH. Another account's line that this process cannot read (a 0750 home) is kept as it is. - **What root wrote is read back.** The runner and the config are compared with what was diff --git a/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts b/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts index b94582302..e19df774b 100644 --- a/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts +++ b/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts @@ -23,6 +23,12 @@ let root: string; let home: string; let fakeBin: string; let systemConfig: string; +/** + * This account's failproofai as the hooks name it: a wrapper in the test's own + * 0755 directory that runs the in-tree CLI. A checkout made with umask 002 is + * group-writable, which the runner accepts only for a provably private group. + */ +let cliPath: string; function fakeCodex(version: string): void { const script = join(fakeBin, "codex"); @@ -39,7 +45,7 @@ function run(args: string[], env: Record = {}) { USERPROFILE: home, FAILPROOFAI_HOME: join(home, ".failproofai"), FAILPROOFAI_PACK_DIR: join(root, "packs"), - FAILPROOFAI_BINARY_OVERRIDE: BINARY_PATH, + FAILPROOFAI_BINARY_OVERRIDE: cliPath, FAILPROOFAI_TELEMETRY_DISABLED: "1", FAILPROOFAI_CODEX_SYSTEM_CONFIG: systemConfig, PATH: `${fakeBin}:${process.env.PATH}`, @@ -78,6 +84,10 @@ beforeEach(() => { systemConfig = join(root, "etc", "codex", "config.toml"); mkdirSync(home, { recursive: true }); mkdirSync(fakeBin, { recursive: true }); + chmodSync(fakeBin, 0o755); + cliPath = join(fakeBin, "failproofai"); + writeFileSync(cliPath, `#!/bin/sh\nexec bun ${JSON.stringify(BINARY_PATH)} "$@"\n`); + chmodSync(cliPath, 0o755); fakeCodex("0.162.1"); }); @@ -124,11 +134,11 @@ describe("E2E: Codex hooks in the system config", () => { const programs = hookPrograms(); expect(programs.length).toBeGreaterThan(0); expect(new Set(programs)).toEqual(new Set([runnerPath()])); - expect(written).not.toContain(BINARY_PATH); + expect(written).not.toContain(cliPath); const runner = readFileSync(runnerPath(), "utf8"); const arms = runner.split("\n").filter((line) => /^ {2}\d+\) exec /.test(line)); expect(arms).toHaveLength(1); - expect(arms[0]).toContain(` ${process.getuid!()}) exec '${BINARY_PATH}' "$@" ;;`); + expect(arms[0]).toContain(` ${process.getuid!()}) exec '${cliPath}' "$@" ;;`); // For this account, the runner is this account's failproofai. const viaRunner = spawnSync(runnerPath(), ["--version"], { encoding: "utf8", timeout: 20_000 }); expect(viaRunner.status, viaRunner.stderr).toBe(0); @@ -158,7 +168,7 @@ describe("E2E: Codex hooks in the system config", () => { it("update rewrites hooks that run failproofai itself to run the hook runner", () => { // A block in the format earlier versions wrote: every hook runs failproofai itself. mkdir755(dirname(systemConfig)); - const command = (event: string) => JSON.stringify(`"${BINARY_PATH}" --hook ${event} --cli codex --agent-scope user`); + const command = (event: string) => JSON.stringify(`"${cliPath}" --hook ${event} --cli codex --agent-scope user`); writeFileSync( systemConfig, [ @@ -179,7 +189,7 @@ describe("E2E: Codex hooks in the system config", () => { "", ].join("\n"), ); - expect(hookPrograms()).toEqual([BINARY_PATH, BINARY_PATH]); + expect(hookPrograms()).toEqual([cliPath, cliPath]); const updated = run(["update", "--no-daemon"]); expect(updated.exitCode, updated.stdout + updated.stderr).toBe(0); @@ -187,7 +197,7 @@ describe("E2E: Codex hooks in the system config", () => { expect(updated.stdout.replace(/\s+/g, " ")).toContain(`now go through ${runnerPath()},`); expect(hookPrograms()).toEqual([runnerPath(), runnerPath()]); expect(readFileSync(systemConfig, "utf8")).toContain("--hook stop --cli codex --agent-scope user"); - expect(readFileSync(runnerPath(), "utf8")).toContain(` ${process.getuid!()}) exec '${BINARY_PATH}' "$@" ;;`); + expect(readFileSync(runnerPath(), "utf8")).toContain(` ${process.getuid!()}) exec '${cliPath}' "$@" ;;`); // Checked again on the next update, with nothing to say. const again = run(["update", "--no-daemon"]); diff --git a/__tests__/hooks/codex-system-hooks.test.ts b/__tests__/hooks/codex-system-hooks.test.ts index 4a5cd58f7..9ea4a8b82 100644 --- a/__tests__/hooks/codex-system-hooks.test.ts +++ b/__tests__/hooks/codex-system-hooks.test.ts @@ -807,14 +807,16 @@ describe("the lines the runner keeps", () => { if (ME === 0) return; // root's line takes no group at all const home = dirname(myCli()); const gid = statSync(home).gid; - const own = { users: [{ name: "me", uid: ME, gid }], groups: [{ name: "me", gid, members: [] }] }; + const own = { users: [{ name: "me", uid: ME, gid }], groups: [{ name: "me", gid, members: [] }], local: true }; chmodSync(home, 0o775); expect(install({ accounts: own })).toMatchObject({ ok: true }); - // The same group, shared: another account's primary group, a listed member, or a name not the account's. + // The same group, shared: another account's primary group, a listed member, a name not the + // account's, or accounts that may come from a directory service the files do not show. for (const shared of [ - { users: [...own.users, { name: "other", uid: ME + 1, gid }], groups: own.groups }, - { users: own.users, groups: [{ name: "me", gid, members: ["other"] }] }, - { users: own.users, groups: [{ name: "staff", gid, members: [] }] }, + { ...own, users: [...own.users, { name: "other", uid: ME + 1, gid }] }, + { ...own, groups: [{ name: "me", gid, members: ["other"] }] }, + { ...own, groups: [{ name: "staff", gid, members: [] }] }, + { ...own, local: false }, ]) { expect(install({ accounts: shared })).toMatchObject({ ok: false, @@ -843,6 +845,7 @@ describe("the lines the runner keeps", () => { const shared = { users: [{ name: "me", uid: ME, gid }, { name: "other", uid: ME + 1, gid }], groups: [{ name: "me", gid, members: [] }], + local: true, }; chmodSync(home, 0o775); mkdirs(dirname(path())); @@ -856,6 +859,19 @@ describe("the lines the runner keeps", () => { expect(existsSync(runner())).toBe(false); }); + it("takes out an earlier block no account can keep when it refuses this account's install", () => { + if (ME === 0) return; // root's line takes no group at all + const home = dirname(myCli()); + const gid = statSync(home).gid; + chmodSync(home, 0o775); + // The program it ran is gone: no account owns it, and it is not another account's to keep. + mkdirs(dirname(path())); + writeFileSync(path(), renderCodexManagedBlock(codexSystemHookEntries(join(dir, "gone", "failproofai")))); + const notPrivate = { users: [{ name: "me", uid: ME, gid }], groups: [{ name: "me", gid, members: [] }], local: false }; + expect(install({ accounts: notPrivate })).toMatchObject({ ok: false, reason: "unsafe" }); + expect(existsSync(path())).toBe(false); + }); + it("keeps another account's line that this account cannot read", () => { if (ME === 0) return; // root reads everything const locked = join(dir, "locked"); diff --git a/src/hooks/codex-system-hooks.ts b/src/hooks/codex-system-hooks.ts index 22267d2d3..b60083265 100644 --- a/src/hooks/codex-system-hooks.ts +++ b/src/hooks/codex-system-hooks.ts @@ -468,6 +468,40 @@ export function untrustedPathReason( export interface CodexAccountsDb { users: Array<{ name: string; uid: number; gid: number }>; groups: Array<{ name: string; gid: number; members: string[] }>; + /** + * Whether those files are the whole story: no other source (LDAP, SSSD, + * NIS, winbind) can add an account to a group without appearing in them. + */ + local: boolean; +} + +/** NSS sources whose accounts are all in the files, or created by root alone (systemd's userdb). */ +const LOCAL_NSS_SOURCES = new Set(["files", "compat", "systemd"]); + +/** + * Whether /etc/nsswitch.conf resolves accounts and groups only from local + * sources. No file, or any other source, is not local: a directory service + * can then give an account this group without /etc/passwd or /etc/group + * knowing. + */ +function identityIsLocal(): boolean { + let conf: string; + try { + conf = readFileSync("/etc/nsswitch.conf", "utf8"); + } catch { + return false; + } + for (const db of ["passwd", "group"]) { + const line = conf.split("\n").find((l) => new RegExp(`^\\s*${db}\\s*:`).test(l)); + if (!line) return false; + const sources = line + .slice(line.indexOf(":") + 1) + .replace(/\[[^\]]*\]/g, " ") + .split(/\s+/) + .filter(Boolean); + if (sources.length === 0 || sources.some((source) => !LOCAL_NSS_SOURCES.has(source))) return false; + } + return true; } function readAccountsDb(deps: CodexSystemDeps): CodexAccountsDb { @@ -482,7 +516,10 @@ function readAccountsDb(deps: CodexSystemDeps): CodexAccountsDb { return []; } }; + // `compat`'s +/- lines pull accounts in from NIS. + const nis = [...rows("/etc/passwd"), ...rows("/etc/group")].some((f) => /^[+-]/.test(f[0] ?? "")); return { + local: identityIsLocal() && !nis, users: rows("/etc/passwd") .filter((f) => f.length >= 4) .map((f) => ({ name: f[0], uid: Number(f[2]), gid: Number(f[3]) })), @@ -496,9 +533,11 @@ function readAccountsDb(deps: CodexSystemDeps): CodexAccountsDb { * Whether `gid` is `uid`'s own private group, which a umask of 002 makes safe * to leave writing its files: its primary group, named after it, no other * account's primary group, and listing no other member. Only what /etc/passwd - * and /etc/group say counts, so a group they cannot vouch for is not private. + * and /etc/group say counts, and only on a machine whose accounts all come + * from them: a group they cannot vouch for is not private. */ function isPrivateGroup(uid: number, gid: number, db: CodexAccountsDb): boolean { + if (!db.local) return false; const user = db.users.find((u) => u.uid === uid); if (!user || user.gid !== gid) return false; const group = db.groups.find((g) => g.gid === gid); @@ -1159,8 +1198,10 @@ export function installCodexSystemHooks( // its own goes too, and so does an earlier block that runs this account's // install for every account. Another account's earlier block, or one this // account cannot read, is left to that account. + // Its program is this account's, or no account's (root's, or gone): not another account's to keep. const earlierMine = - (earlierInfo?.kind === "account" || earlierInfo?.kind === "none") && earlierInfo.owners.has(self.uid); + (earlierInfo?.kind === "account" || earlierInfo?.kind === "none") && + (earlierInfo.owners.has(self.uid) || (earlierInfo.kind === "none" && earlierInfo.owners.size === 0)); if (runnerAccounts(state).some((a) => a.uid === self.uid) || earlierMine) { const form = state.form!; const block = form.kind === "direct" && others.length > 0 ? retargetedBlock(form, runner) : null; From 4c7034c80a402a576bbc629ac3101d5f7baf8612 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 22:33:02 +0530 Subject: [PATCH 6/7] [hooks] Check initgroups and the runner's mode; guard the e2e cases for root - A private group also needs `initgroups` (supplementary groups) to come from local sources, when nsswitch.conf names it. The parser is now `nsswitchIsLocal`, so it can be tested on its own. - Install's read-back requires the runner to be mode 0755, as well as root's and holding what was written. - The two e2e cases that assume a non-root account return early under uid 0; unit tests cover root's line and a root-owned earlier block. Co-Authored-By: Claude Opus 5.5 --- .../e2e/cli/codex-system-hooks.e2e.test.ts | 4 +++ __tests__/hooks/codex-system-hooks.test.ts | 13 +++++++++ src/hooks/codex-system-hooks.ts | 28 ++++++++++++++----- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts b/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts index e19df774b..2628eb0d3 100644 --- a/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts +++ b/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts @@ -97,6 +97,8 @@ afterEach(() => { describe("E2E: Codex hooks in the system config", () => { it("installs into the system config, keeps what was there, and moves hooks out of hooks.json", () => { + // As root, the line also names its interpreter, and the files here are root's: unit tests cover that. + if (process.getuid?.() === 0) return; mkdir755(dirname(systemConfig)); const original = '# set by the admin\napproval_policy = "never"\n'; writeFileSync(systemConfig, original); @@ -166,6 +168,8 @@ describe("E2E: Codex hooks in the system config", () => { }); it("update rewrites hooks that run failproofai itself to run the hook runner", () => { + // As root, every file here is root's, so the earlier block is root's alone and stays as it is. + if (process.getuid?.() === 0) return; // A block in the format earlier versions wrote: every hook runs failproofai itself. mkdir755(dirname(systemConfig)); const command = (event: string) => JSON.stringify(`"${cliPath}" --hook ${event} --cli codex --agent-scope user`); diff --git a/__tests__/hooks/codex-system-hooks.test.ts b/__tests__/hooks/codex-system-hooks.test.ts index 9ea4a8b82..75d1eb05f 100644 --- a/__tests__/hooks/codex-system-hooks.test.ts +++ b/__tests__/hooks/codex-system-hooks.test.ts @@ -49,6 +49,7 @@ import { renderCodexHookRunner, renderCodexManagedBlock, codexTrustedOwners, + nsswitchIsLocal, untrustedPathReason, } from "../../src/hooks/codex-system-hooks"; import { codex, codexSystemHookEntries } from "../../src/hooks/integrations"; @@ -992,6 +993,18 @@ describe("a block in the earlier format", () => { }); }); +describe("nsswitchIsLocal", () => { + it("is local only when accounts, groups and supplementary groups come from local sources", () => { + expect(nsswitchIsLocal("passwd: files systemd\ngroup: files systemd\n")).toBe(true); + expect(nsswitchIsLocal("passwd: compat [NOTFOUND=return] files # comment\ngroup: files\n")).toBe(true); + expect(nsswitchIsLocal("passwd: files systemd sss\ngroup: files systemd sss\n")).toBe(false); + expect(nsswitchIsLocal("passwd: files\ngroup: files ldap\n")).toBe(false); + expect(nsswitchIsLocal("passwd: files\ngroup: files\ninitgroups: files sss\n")).toBe(false); + expect(nsswitchIsLocal("group: files\n")).toBe(false); + expect(nsswitchIsLocal("")).toBe(false); + }); +}); + describe("codexHookRunnerPath and codexTrustedOwners", () => { it("puts the runner in its own directory under /opt for Codex's config, and beside any other", () => { expect(codexHookRunnerPath("/etc/codex/config.toml")).toBe("/opt/failproofai-codex/codex-hook"); diff --git a/src/hooks/codex-system-hooks.ts b/src/hooks/codex-system-hooks.ts index b60083265..a2db99641 100644 --- a/src/hooks/codex-system-hooks.ts +++ b/src/hooks/codex-system-hooks.ts @@ -482,20 +482,28 @@ const LOCAL_NSS_SOURCES = new Set(["files", "compat", "systemd"]); * Whether /etc/nsswitch.conf resolves accounts and groups only from local * sources. No file, or any other source, is not local: a directory service * can then give an account this group without /etc/passwd or /etc/group - * knowing. + * knowing. `initgroups` (supplementary groups) falls back to `group` when it + * has no line of its own. */ function identityIsLocal(): boolean { - let conf: string; try { - conf = readFileSync("/etc/nsswitch.conf", "utf8"); + return nsswitchIsLocal(readFileSync("/etc/nsswitch.conf", "utf8")); } catch { return false; } - for (const db of ["passwd", "group"]) { +} + +/** {@link identityIsLocal} for the text of an nsswitch.conf. */ +export function nsswitchIsLocal(conf: string): boolean { + for (const db of ["passwd", "group", "initgroups"]) { const line = conf.split("\n").find((l) => new RegExp(`^\\s*${db}\\s*:`).test(l)); - if (!line) return false; + if (!line) { + if (db === "initgroups") continue; + return false; + } const sources = line .slice(line.indexOf(":") + 1) + .replace(/#.*$/, "") .replace(/\[[^\]]*\]/g, " ") .split(/\s+/) .filter(Boolean); @@ -1032,8 +1040,14 @@ function applySystemState( const before = runnerProblem(runner, programs, trusted, false); if (before) return unsafe(before); if (runnerChanged) writeSystemFile(runner, runnerText, "0755", direct, true); - // Read back: what Codex will run is what was meant, and only root can change it. - const after = untrustedPathReason(runner, trusted) ?? (readFileOr(runner) === runnerText ? null : `${runner} does not hold what failproofai wrote`); + // Read back: what Codex will run is what was meant, every account can run it, and only root can change it. + const after = + untrustedPathReason(runner, trusted) ?? + (readFileOr(runner) !== runnerText + ? `${runner} does not hold what failproofai wrote` + : ((statSafe(runner)?.mode ?? 0) & 0o7777) !== 0o755 + ? `${runner} is not mode 0755` + : null); if (after) { takeOut(); // Written by this call, so it is ours to remove even when it was not before. From fee22d1599a73dea5aa835ea92a55da22f037ee5 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Tue, 24 Nov 2026 23:39:09 +0530 Subject: [PATCH 7/7] [hooks] Check the Codex system config itself, and look for extended ACLs - Install and update check /etc/codex/config.toml, followed through any link, and the directories above it, against the trusted owners, as they check the runner. Codex runs whatever hooks the config names, so a config another account can change cannot be vouched for. Install refuses it and writes nothing. Update reports it (unsafe-config) and never calls it current. Direct-mode writes make the config's directories 0755, as root's `install -d` does. - A private group may write an entry only when the entry has no extended ACL (`getfacl -s`, else `ls -ld`; when neither can tell, it is taken to have one). On Linux an ACL's mask is what the group bits show, so a named outsider's write would otherwise pass as the group's. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- CLAUDE.md | 8 +- .../e2e/cli/codex-system-hooks.e2e.test.ts | 3 + .../codex-system-hooks-privileged.test.ts | 11 +- __tests__/hooks/codex-system-hooks.test.ts | 103 ++++++++++++++++-- docs/reference/harnesses.mdx | 2 +- src/hooks/codex-system-hooks.ts | 96 ++++++++++++++-- src/hooks/update-run.ts | 2 +- 8 files changed, 199 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb3bef888..d3dff0a4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ - The daemon download is checked against the digest recorded in the npm package as well as the release's `SHA256SUMS`, which comes from the same release as the binary and so cannot catch a replaced asset (#1056) - `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) -- Harden the Codex system hooks. The hooks failproofai writes into `/etc/codex/config.toml` now run `/opt/failproofai-codex/codex-hook`, a short root-owned script that hands each event to the failproofai of the account that set the hooks up, one line per account. Install and every `failproofai update` check that the script, the directories above it, the `sh`, `id` and `cat` it runs, and each account's own failproofai can be changed only by root or that account; a block that fails is taken out, and an account that fails is taken out of the script. `update` rewrites a block from an earlier version to use the script, which needs sudo; an account the block does not run for gets a notice instead of a failed update. Uninstalling takes out only your account (#1061) +- Harden the Codex system hooks. The hooks failproofai writes into `/etc/codex/config.toml` now run `/opt/failproofai-codex/codex-hook`, a short root-owned script that hands each event to the failproofai of the account that set the hooks up, one line per account. Install and every `failproofai update` check that the config itself, the script, the directories above them, the `sh`, `id` and `cat` it runs, and each account's own failproofai can be changed only by root or that account; a block that fails is taken out, and an account that fails is taken out of the script. `update` rewrites a block from an earlier version to use the script, which needs sudo; an account the block does not run for gets a notice instead of a failed update. Uninstalling takes out only your account (#1061) - 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) ### Docs diff --git a/CLAUDE.md b/CLAUDE.md index bf53606da..f1b02bc83 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,7 +55,13 @@ or `/usr/bin`. Rules that keep it safe: `/etc/group` (`isPrivateGroup`), and only where `/etc/nsswitch.conf` takes accounts and groups from `files`, `compat` (no `+`/`-` entries) or `systemd` alone. With LDAP, SSSD, NIS or winbind in it, those files cannot prove a group private, so such an - install is refused and that account keeps `hooks.json` (or runs `chmod -R g-w` on it). Root's line must be root's alone, group included, and + install is refused and that account keeps `hooks.json` (or runs `chmod -R g-w` on it). + An entry with an extended ACL never counts as group-only (`getfacl -s`, else `ls -ld` + `+`): on Linux its group bits are the ACL mask, which a named outsider's write sets. +- **The config itself must be root's.** `configProblem()` walks `/etc/codex/config.toml` + (through any link) and its directories the same way. Install refuses an unsafe config + and writes nothing to it; update reports it (`unsafe-config`) and never calls it + current, because whoever can change it can replace every managed command. Root's line must be root's alone, group included, and names its interpreter by absolute path, so nothing on it goes through PATH. Another account's line that this process cannot read (a 0750 home) is kept as it is. - **What root wrote is read back.** The runner and the config are compared with what was diff --git a/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts b/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts index 2628eb0d3..2403792a0 100644 --- a/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts +++ b/__tests__/e2e/cli/codex-system-hooks.e2e.test.ts @@ -102,6 +102,8 @@ describe("E2E: Codex hooks in the system config", () => { mkdir755(dirname(systemConfig)); const original = '# set by the admin\napproval_policy = "never"\n'; writeFileSync(systemConfig, original); + // As an admin's config is: 0644 whatever this run's umask, or failproofai refuses it. + chmodSync(systemConfig, 0o644); // An older install's entries in hooks.json, next to someone else's hook. mkdirSync(join(home, ".codex"), { recursive: true }); writeFileSync( @@ -193,6 +195,7 @@ describe("E2E: Codex hooks in the system config", () => { "", ].join("\n"), ); + chmodSync(systemConfig, 0o644); expect(hookPrograms()).toEqual([cliPath, cliPath]); const updated = run(["update", "--no-daemon"]); diff --git a/__tests__/hooks/codex-system-hooks-privileged.test.ts b/__tests__/hooks/codex-system-hooks-privileged.test.ts index 35bbf0586..83771b653 100644 --- a/__tests__/hooks/codex-system-hooks-privileged.test.ts +++ b/__tests__/hooks/codex-system-hooks-privileged.test.ts @@ -89,13 +89,16 @@ describe("the Codex system hooks, written as root", () => { }); it("judges a directory that is already there as it is, never tightening it first", () => { - expect(install()).toMatchObject({ ok: true }); - chmodSync(dirname(runner()), 0o775); + // The runner in its own directory, as /opt/failproofai-codex is: the config's stays trusted. + const runnerPath = join(dir, "opt", "failproofai-codex", "codex-hook"); + const withRunner = () => installCodexSystemHooks(cli(), codexSystemHookEntries, { ...deps(), runnerPath }); + expect(withRunner()).toMatchObject({ ok: true }); + chmodSync(dirname(runnerPath), 0o775); root.calls.length = 0; - expect(install()).toMatchObject({ + expect(withRunner()).toMatchObject({ ok: false, reason: "unsafe", - detail: `${dirname(runner())} can be written by accounts other than its owner`, + detail: `${dirname(runnerPath)} can be written by accounts other than its owner`, }); expect(root.calls.some((c) => c.op === "install")).toBe(false); expect(existsSync(path())).toBe(false); diff --git a/__tests__/hooks/codex-system-hooks.test.ts b/__tests__/hooks/codex-system-hooks.test.ts index 75d1eb05f..46a796c20 100644 --- a/__tests__/hooks/codex-system-hooks.test.ts +++ b/__tests__/hooks/codex-system-hooks.test.ts @@ -138,6 +138,12 @@ function mkdirs(path: string): void { } } +/** A system-config fixture: 0644 whatever the umask, as the config's own trust check needs. */ +function writeConfig(path: string, text: string): void { + writeFileSync(path, text); + chmodSync(path, 0o644); +} + /** An executable shell script at `path`, 0755. */ function script(path: string, body: string): string { mkdirs(dirname(path)); @@ -350,7 +356,7 @@ describe("removeCodexSystemHooks", () => { it("restores the exact original from the backup, even one with no final newline", () => { const original = 'model = "o3"'; // no trailing newline - writeFileSync(path(), original); + writeConfig(path(), original); install(); expect(removeCodexSystemHooks({ path: path() }).status).toBe("removed"); expect(readFileSync(path(), "utf8")).toBe(original); @@ -358,7 +364,7 @@ describe("removeCodexSystemHooks", () => { }); it("keeps edits made since, and the backup, when the rest of the file changed", () => { - writeFileSync(path(), "a = 1\n"); + writeConfig(path(), "a = 1\n"); install(); writeFileSync(path(), `${readFileSync(path(), "utf8")}b = 2\n`); expect(removeCodexSystemHooks({ path: path() }).status).toBe("removed"); @@ -405,18 +411,44 @@ describe("what the runner may run before it knows the account", () => { expect(existsSync(runner())).toBe(false); }); - it("refuses a directory others can write, and takes out the block that was there", () => { - expect(install()).toMatchObject({ ok: true }); - chmodSync(dirname(runner()), 0o775); - expect(install()).toMatchObject({ + it("refuses a runner directory others can write, and takes out the block that was there", () => { + // In its own directory, as /opt/failproofai-codex is: the config's stays trusted. + const runnerPath = join(dir, "opt", "failproofai-codex", "codex-hook"); + expect(install({ runnerPath })).toMatchObject({ ok: true }); + chmodSync(dirname(runnerPath), 0o775); + expect(install({ runnerPath })).toMatchObject({ ok: false, reason: "unsafe", - detail: `${dirname(runner())} can be written by accounts other than its owner`, + detail: `${dirname(runnerPath)} can be written by accounts other than its owner`, }); expect(existsSync(path())).toBe(false); + expect(existsSync(runnerPath)).toBe(false); + }); + + it("refuses a system config another account can change, and writes nothing to it", () => { + mkdirs(dirname(path())); + writeConfig(path(), "a = 1\n"); + chmodSync(path(), 0o666); + expect(install()).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${path()} can be written by accounts other than its owner`, + }); + expect(readFileSync(path(), "utf8")).toBe("a = 1\n"); expect(existsSync(runner())).toBe(false); }); + it("refuses a system config reached through a directory everyone can write", () => { + const loose = join(dir, "loose"); + mkdirs(loose); + chmodSync(loose, 0o777); + writeConfig(join(loose, "config.toml"), "a = 1\n"); + mkdirs(dirname(path())); + symlinkSync(join(loose, "config.toml"), path()); + expect(install()).toMatchObject({ ok: false, reason: "unsafe", detail: `${loose} can be written by accounts other than its owner` }); + expect(readFileSync(path(), "utf8")).toBe("a = 1\n"); + }); + it("refuses an `id` or `cat` another account could replace", () => { const loose = join(dir, "loose"); const id = script(join(loose, "id"), "echo 0"); @@ -484,7 +516,7 @@ describe("refreshCodexSystemHooks (failproofai update)", () => { /** A block in the format earlier versions wrote: every hook runs `cli` itself. */ const writeOlderBlock = (cli: string, before = "") => { mkdirs(dirname(path())); - writeFileSync(path(), mergeCodexManagedBlock(before, renderCodexManagedBlock(codexSystemHookEntries(cli)))); + writeConfig(path(), mergeCodexManagedBlock(before, renderCodexManagedBlock(codexSystemHookEntries(cli)))); }; it("rewrites a block from before the runner to run it, for the account whose failproofai it ran", () => { @@ -557,6 +589,21 @@ describe("refreshCodexSystemHooks (failproofai update)", () => { } }); + it("reports a system config another account can change, never calling it current", () => { + expect(installCodexSystemHooks(myCli(), codexSystemHookEntries, { path: path(), codexVersion: CURRENT })).toMatchObject({ ok: true }); + chmodSync(path(), 0o666); + const before = readFileSync(path(), "utf8"); + expect(refreshCodexSystemHooks({ path: path() })).toEqual({ + status: "unsafe-config", + path: path(), + reason: `${path()} can be written by accounts other than its owner`, + }); + // An account the hooks do not run for is told, and its update does not fail. + expect(refreshCodexSystemHooks({ path: path(), uid: 4242 })).toMatchObject({ status: "others" }); + expect(readFileSync(path(), "utf8")).toBe(before); + expect(codexRefreshLines({ status: "unsafe-config", path: path(), reason: "x" })[0]).toMatch(/^✕ Codex: /); + }); + it("takes the block out when the runner stops passing the check", () => { expect(installCodexSystemHooks(myCli(), codexSystemHookEntries, { path: path(), codexVersion: CURRENT })).toMatchObject({ ok: true }); expect(refreshCodexSystemHooks({ path: path() })).toEqual({ status: "current", path: path() }); @@ -615,7 +662,7 @@ describe("installing over a block from before the runner", () => { if (ME === 0) return; // root owns every file here, so the block would be the running account's const theirs = script(join(dir, "home", "failproofai"), "true"); mkdirs(dirname(path())); - writeFileSync(path(), renderCodexManagedBlock(codexSystemHookEntries(theirs))); + writeConfig(path(), renderCodexManagedBlock(codexSystemHookEntries(theirs))); // This account is not the one that owns `theirs`. expect( installCodexSystemHooks(myCli(), codexSystemHookEntries, { path: path(), codexVersion: CURRENT, uid: 4242 }), @@ -837,6 +884,38 @@ describe("the lines the runner keeps", () => { expect(existsSync(runner())).toBe(false); }); + it("does not let an extended ACL pass as the private group", () => { + if (ME === 0) return; // root's line takes no group at all + const home = dirname(myCli()); + const gid = statSync(home).gid; + const own = { users: [{ name: "me", uid: ME, gid }], groups: [{ name: "me", gid, members: [] }], local: true }; + chmodSync(home, 0o775); + expect(install({ accounts: { ...own, hasAcl: () => false } })).toMatchObject({ ok: true }); + expect(install({ accounts: { ...own, hasAcl: () => true } })).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${home} can be written by accounts other than its owner`, + }); + }); + + it("finds a real named-user ACL that grants write, as Linux shows it through the group bits", () => { + if (ME === 0 || process.platform !== "linux") return; + const setfacl = ["/usr/bin/setfacl", "/bin/setfacl"].find((p) => existsSync(p)); + if (!setfacl) return; // no acl tools on this machine + const home = dirname(myCli()); + const gid = statSync(home).gid; + const own = { users: [{ name: "me", uid: ME, gid }], groups: [{ name: "me", gid, members: [] }], local: true }; + chmodSync(home, 0o755); + spawnSync(setfacl, ["-m", `u:${ME + 1}:rwx`, home]); + // The ACL's mask now reads as the group's write bit. + expect(statSync(home).mode & 0o020).toBe(0o020); + expect(install({ accounts: own })).toMatchObject({ + ok: false, + reason: "unsafe", + detail: `${home} can be written by accounts other than its owner`, + }); + }); + it("takes out an earlier block that runs this account's install when it refuses that install", () => { if (ME === 0) return; // root's line takes no group at all const cli = myCli(); @@ -850,7 +929,7 @@ describe("the lines the runner keeps", () => { }; chmodSync(home, 0o775); mkdirs(dirname(path())); - writeFileSync(path(), renderCodexManagedBlock(codexSystemHookEntries(cli))); + writeConfig(path(), renderCodexManagedBlock(codexSystemHookEntries(cli))); expect(install({ accounts: shared })).toMatchObject({ ok: false, reason: "unsafe", @@ -867,7 +946,7 @@ describe("the lines the runner keeps", () => { chmodSync(home, 0o775); // The program it ran is gone: no account owns it, and it is not another account's to keep. mkdirs(dirname(path())); - writeFileSync(path(), renderCodexManagedBlock(codexSystemHookEntries(join(dir, "gone", "failproofai")))); + writeConfig(path(), renderCodexManagedBlock(codexSystemHookEntries(join(dir, "gone", "failproofai")))); const notPrivate = { users: [{ name: "me", uid: ME, gid }], groups: [{ name: "me", gid, members: [] }], local: false }; expect(install({ accounts: notPrivate })).toMatchObject({ ok: false, reason: "unsafe" }); expect(existsSync(path())).toBe(false); @@ -959,7 +1038,7 @@ describe("a block in the earlier format", () => { const runner = () => codexHookRunnerPath(path())!; const writeOlderBlock = (cli: string) => { mkdirs(dirname(path())); - writeFileSync(path(), renderCodexManagedBlock(codexSystemHookEntries(cli))); + writeConfig(path(), renderCodexManagedBlock(codexSystemHookEntries(cli))); }; it("is left as it is when everything it runs is root's alone", () => { diff --git a/docs/reference/harnesses.mdx b/docs/reference/harnesses.mdx index 1fde0e1ef..f0eb93c9d 100644 --- a/docs/reference/harnesses.mdx +++ b/docs/reference/harnesses.mdx @@ -106,7 +106,7 @@ So when `failproofai config` (or `policies --install --cli codex` at user scope) That file applies to every account on the machine, so each hook in it runs `/opt/failproofai-codex/codex-hook`, a short script that root owns. The script hands the event to an account's own failproofai for each account that set the hooks up there, and does nothing for any other account. Another account that wants failproofai's Codex hooks sets them up for itself. -Before writing the block, and again on every `failproofai update`, failproofai checks that the script, every directory above it, and the `sh`, `id` and `cat` it runs belong to root and can be written by no one else, and that each account's failproofai belongs to that account or root. On install, when that check fails, your hooks stay in `~/.codex/hooks.json`. On update, a script that fails it takes the block out, and an account whose failproofai fails it is taken out of the script; run `failproofai config` again once it is fixed. `failproofai update` also rewrites a block written by an earlier version to use the script, which needs sudo. +Before writing the block, and again on every `failproofai update`, failproofai checks that `/etc/codex/config.toml` itself, the script, every directory above them, and the `sh`, `id` and `cat` it runs belong to root and can be written by no one else, and that each account's failproofai belongs to that account or root. On install, when that check fails, your hooks stay in `~/.codex/hooks.json`. On update, a script that fails it takes the block out, and an account whose failproofai fails it is taken out of the script; run `failproofai config` again once it is fixed. `failproofai update` also rewrites a block written by an earlier version to use the script, which needs sudo. `failproofai uninstall` and unticking Codex in `failproofai config` take your account out again, and the block with it once no account is left. diff --git a/src/hooks/codex-system-hooks.ts b/src/hooks/codex-system-hooks.ts index a2db99641..4e6729c27 100644 --- a/src/hooks/codex-system-hooks.ts +++ b/src/hooks/codex-system-hooks.ts @@ -41,7 +41,7 @@ * non-interactive `sudo -n` the daemon install uses; `failproofai config` * primes it first. */ -import { execSync } from "node:child_process"; +import { execFileSync, execSync } from "node:child_process"; import { createHash } from "node:crypto"; import { accessSync, @@ -436,34 +436,68 @@ function resolveChain(path: string): Chain | { error: string; code?: string } { * account owns; the final file must be writable by its owner alone. * `groupOk` lets a directory or file be writable by its group when that * group passes it (an account's own private group, which a umask of 002 - * leaves writing its install). `dir` expects a directory at the end; `link` + * leaves writing its install), given the group and the entry's path. `dir` expects a directory at the end; `link` * accepts a symbolic link as the last name (`/bin/sh`), whose target is * checked the same way. */ export function untrustedPathReason( path: string, trusted: ReadonlySet, - opts: { dir?: boolean; link?: boolean; groupOk?: (gid: number) => boolean } = {}, + opts: { dir?: boolean; link?: boolean; groupOk?: (gid: number, path: string) => boolean } = {}, ): string | null { const chain = resolveChain(path); if ("error" in chain) return chain.error; const { seen, last } = chain; if (!opts.link && chain.finalLink) return `${resolve(path)} is a symbolic link`; - const othersWrite = (st: Stats): boolean => - (st.mode & 0o002) !== 0 || ((st.mode & 0o020) !== 0 && !(opts.groupOk?.(st.gid) ?? false)); + const othersWrite = (st: Stats, name: string): boolean => + (st.mode & 0o002) !== 0 || ((st.mode & 0o020) !== 0 && !(opts.groupOk?.(st.gid, name) ?? false)); for (const { name, st } of seen) { if (!trusted.has(st.uid)) return `${name} is owned by uid ${st.uid}`; - if (st.isDirectory() && othersWrite(st) && (st.mode & 0o1000) === 0) { + if (st.isDirectory() && othersWrite(st, name) && (st.mode & 0o1000) === 0) { return `${name} can be written by accounts other than its owner`; } } const end = seen[seen.length - 1].st; if (opts.dir) return end.isDirectory() ? null : `${last} is not a directory`; if (!end.isFile()) return `${last} is not a regular file`; - if (othersWrite(end)) return `${last} can be written by accounts other than its owner`; + if (othersWrite(end, last)) return `${last} can be written by accounts other than its owner`; return null; } +/** + * Whether `path` has an extended ACL (named users or groups). On Linux the + * group bits of such an entry are the ACL's mask, so a group-writable mode + * may be write access for a named outsider rather than for the group. + * Asked of `getfacl -s` (which prints only entries with an extended ACL), or + * failing that `ls -ld` (a `+` after the mode), by absolute path; when + * neither can say, it is taken to have one. + */ +function hasExtendedAcl(path: string): boolean { + const run = (program: string, args: string[]): string | null => { + for (const dir of RUNNER_PROGRAM_DIRS) { + const candidate = `${dir}/${program}`; + if (!existsSync(candidate)) continue; + try { + return execFileSync(candidate, args, { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + timeout: 5000, + // Cast, not padded: the ambient types require NODE_ENV on every ProcessEnv. + env: { PATH: RUNNER_PROGRAM_DIRS.join(":"), LC_ALL: "C" } as Record as NodeJS.ProcessEnv, + }); + } catch { + return null; + } + } + return null; + }; + const acl = run("getfacl", ["-s", "--absolute-names", "--", path]); + if (acl !== null) return acl.trim() !== ""; + const listing = run("ls", ["-ld", "--", path]); + if (listing === null) return true; + return /^\S{10}\+/.test(listing); +} + /** Accounts and groups, as /etc/passwd and /etc/group list them. */ export interface CodexAccountsDb { users: Array<{ name: string; uid: number; gid: number }>; @@ -473,6 +507,8 @@ export interface CodexAccountsDb { * NIS, winbind) can add an account to a group without appearing in them. */ local: boolean; + /** Whether a path has an extended ACL. Default {@link hasExtendedAcl}. */ + hasAcl?: (path: string) => boolean; } /** NSS sources whose accounts are all in the files, or created by root alone (systemd's userdb). */ @@ -589,6 +625,30 @@ export function codexTrustedOwners(configPath: string, deps: CodexSystemDeps = { } } +/** + * Why an account outside `trusted` could change the system config at `path`: + * the file (followed through any link), or the directories above it. Codex + * runs whatever hooks it names for every account, so failproofai's hooks in + * it are only as safe as it is. + */ +function configProblem(path: string, trusted: ReadonlySet): string | null { + let dir = dirname(path); + while (!existsSync(dir) && dirname(dir) !== dir) dir = dirname(dir); + return ( + untrustedPathReason(dir, trusted, { dir: true }) ?? + // There, or a link to nothing: either way it is what Codex will read. + (existsSync(path) || lstatSafe(path) !== null ? untrustedPathReason(path, trusted, { link: true }) : null) + ); +} + +function lstatSafe(path: string): Stats | null { + try { + return lstatSync(path); + } catch { + return null; + } +} + /** Why the runner at `runner`, with `programs`, could run anything but root's before it knows the account. */ function runnerProblem( runner: string, @@ -626,7 +686,8 @@ function accountProblem(account: CodexRunnerAccount, trusted: ReadonlySet isPrivateGroup(account.uid, gid, db); + const groupOk = (gid: number, path: string): boolean => + isPrivateGroup(account.uid, gid, db) && !(db.hasAcl ?? hasExtendedAcl)(path); return ( (account.interpreter ? untrustedPathReason(account.interpreter, own, { link: true, groupOk }) : null) ?? untrustedPathReason(account.cli, own, { link: true, groupOk }) @@ -723,6 +784,8 @@ function fileMode(path: string): string { */ function writeSystemFile(path: string, contents: string, mode: string, direct: boolean, replaceLink = false): void { if (direct) { + // Its directories 0755 whatever the umask, as root's `install -d` makes them. + ensureSystemDir(dirname(path), true); writeConfigFileAtomic(path, contents, { backup: false, mode: parseInt(mode, 8), @@ -1190,6 +1253,10 @@ export function installCodexSystemHooks( if (entries.length === 0 || entries.some((e) => commandProgram(e.command) !== runner)) { return { ok: false, reason: "write-failed", detail: `every Codex system hook must run ${runner}`, path }; } + // Codex runs every hook the config names, for every account: a config + // another account can change makes no hook in it failproofai's to vouch for. + const unsafeConfig = configProblem(path, trusted); + if (unsafeConfig) return { ok: false, reason: "unsafe", detail: unsafeConfig, path }; const programs = codexRunnerProgramsFor(deps); if (runnerState.kind === "foreign") { // Our block must not run a file failproofai did not write: it is taken out, the file is left. @@ -1322,6 +1389,8 @@ export type CodexSystemRefresh = | { status: "needs-root"; path: string; reason: string } /** It has to change, and only an account that set it up, or root, can do that. */ | { status: "others"; path: string; reason: string } + /** The config itself can be changed by an account other than root: nothing in it can be vouched for. */ + | { status: "unsafe-config"; path: string; reason: string } | { status: "failed"; path: string; reason: string }; /** @@ -1359,6 +1428,12 @@ export function refreshCodexSystemHooks(deps: CodexSystemDeps = {}): CodexSystem } const { form, runner, runnerState } = state; const listed = runnerAccounts(state).some((a) => a.uid === self.uid); + const unsafeConfig = configProblem(path, state.trusted); + if (unsafeConfig) { + const earlier = form.kind === "direct" ? earlierBlock(form, state.trusted, self, state.accounts) : null; + const owner = earlier !== null && earlier.kind !== "root" && earlier.owners.has(self.uid); + return { status: listed || owner ? "unsafe-config" : "others", path, reason: unsafeConfig }; + } const settle = ( applied: Applied, @@ -1466,6 +1541,11 @@ export function codexRefreshLines(result: CodexSystemRefresh): string[] { `▲ Codex: failproofai's hooks in ${result.path} need updating by an account that set them up, or by root: ${result.reason}.`, " If you set them up, run `failproofai config`; otherwise tell whoever administers this machine.", ]; + case "unsafe-config": + return [ + `✕ Codex: ${result.path} can be changed by an account other than root (${result.reason}),`, + " so failproofai's hooks in it cannot be relied on. Make it, and every directory above it, root's alone.", + ]; case "failed": return [`✕ Codex: could not check failproofai's hooks in ${result.path}: ${result.reason}.`]; } diff --git a/src/hooks/update-run.ts b/src/hooks/update-run.ts index 64b13fb9c..320ca6135 100644 --- a/src/hooks/update-run.ts +++ b/src/hooks/update-run.ts @@ -125,7 +125,7 @@ export async function runUpdateSteps(opts: UpdateStepsOptions): Promise