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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
Expand Down
54 changes: 54 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,60 @@ 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/<user>` is the
daemon's): a root-owned `sh` script with one `case` arm per uid that set the hooks up,
`<uid>) exec '<that account's failproofai>' "$@"`, 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 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`), 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).
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
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, 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
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**
Expand Down
98 changes: 93 additions & 5 deletions __tests__/e2e/cli/codex-system-hooks.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -22,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");
Expand All @@ -38,7 +45,7 @@ function run(args: string[], env: Record<string, string> = {}) {
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}`,
Expand All @@ -52,19 +59,35 @@ function run(args: string[], env: Record<string, string> = {}) {
}

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<string, Array<{ hooks: unknown[] }>> }).hooks ?? {};
return Object.values(hooks).flat().reduce((n, group) => n + group.hooks.length, 0);
};

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");
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");
});

Expand All @@ -74,9 +97,13 @@ 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 });
// 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);
// 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(
Expand Down Expand Up @@ -106,6 +133,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(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 '${cliPath}' "$@" ;;`);
Comment thread
NiveditJain marked this conversation as resolved.
Resolved
// 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);
Expand All @@ -114,14 +156,60 @@ 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", () => {
// 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`);
Comment thread
NiveditJain marked this conversation as resolved.
Resolved
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"),
);
chmodSync(systemConfig, 0o644);
expect(hookPrograms()).toEqual([cliPath, cliPath]);

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 '${cliPath}' "$@" ;;`);

// 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", () => {
Expand Down
Loading