diff --git a/docs/guards.md b/docs/guards.md index 371fad1..c291f8a 100644 --- a/docs/guards.md +++ b/docs/guards.md @@ -36,6 +36,10 @@ wraps `evaluate`/`evaluateApex` the same way, so a bug can never disable enforce | `installGuard` | `npm/yarn/pnpm/bun/pip/cargo/go/gem/composer` + `brew/apt/dnf/pacman` installs | ask | | `opaqueShellGuard` | last in the chain: a command or shell payload built at run time that cannot be analysed (`sh -c "$CMD"`, `$CMD args`, …) | ask | +An `ask` never hides the receipt-store deny: when a guard returns an ask (typically `securityGuard`'s generic +`rm`), `runGuards` also consults `receiptStoreGuard` (the harness `state` dir and HMAC key rule of +`protectedPathGuard`, nothing else) and returns its block instead. No other verdict moves. + Plus, inside `evaluate()` after the chain: - **git** — destructive ops (`push --force`, `reset --hard`, `branch -D`…) → **block**; routine ops (`push`, `checkout`, `commit`, `add`, `branch -d`, `merge`…) → **ask**. diff --git a/docs/reports/2026-11-17-pr142-linux-deny.md b/docs/reports/2026-11-17-pr142-linux-deny.md new file mode 100644 index 0000000..ec97864 --- /dev/null +++ b/docs/reports/2026-11-17-pr142-linux-deny.md @@ -0,0 +1,52 @@ +# PR #142 - `rm -rf /.fuse-harness/state` is `ask` instead of `deny` off macOS TMPDIR + +## Root cause (code missing, not a wrong expectation) +`runGuards` (`src/policy/guards/index.ts`) returns the first non-null guard. `securityGuard` (position 3) returns the +generic `rm` ask (`security.ts` ASK_PATTERNS `\brm\s`) before `protectedPathGuard` (position 4) can deny. +The old tests passed on macOS only because `$TMPDIR` is `/var/folders/...`, which matches `SYSTEM_DIR_RE` +(`security.ts:15`, `/var\b`): an unrelated critical block that fired by accident. + +## Repro (guard chain through `handleHook`, claude-code; before the fix) +| HOME form | `rm -rf/-r ` | `rm ` | +|---|---|---| +| /tmp, /private/tmp, /home/u, /Users/u, /root, /opt/x, symlinked HOME | ask | ask | +| /var/folders, /var/tmp | deny (accident: `/var`) | ask (without -f) | +After the fix: deny for every form (test `receipt-tamper-homes.test.ts`, 11 homes x 15 commands). + +## Fix (hardening only) +- `src/policy/guards/protected-path.ts`: `receiptStoreGuard` = only the state-dir/key rule of `protectedPathGuard`. +- `src/policy/guards/index.ts`: when a guard returns `ask`, `denyOverAsk` returns `receiptStoreGuard`'s block if any; if it throws the ask stands. +- `docs/guards.md`: one paragraph. +- Hosts: claude-code, codex, cursor, kimi all `deny`, never a CONFIRM, for `rm -rf ` and `rm ` (and `find -exec rm`, `unlink`, `(rm ..)`). + +## Differential (old = first-non-null loop over GUARDS, new = runGuards; 41 commands): 7 moved, all ask -> block +Moved: `rm -rf/-r` state, `rm` key, `find -exec rm`, and the `~`, `$HOME`, `"$HOME"` forms of `rm -rf `. +Unchanged (same verdict before/after): `.fuse-harness-other`, `.fuse-harness/../x`, `cache/x`, `states`, `.keyboard`, `.key.bak`, +`/tmp/x`, project `state`, `./state`, `find -delete`/`mv`/`cp` outside the state dir, `.git/x`, plugins cache, `unlink /tmp/x`, +installs, `sudo`, `eval`, reads of key/state, `cd && rm -rf state` (documented limit: stays ask). +Challenger (78-command corpus): 17 moved, all ask -> block, each one a command `protectedPathGuard` alone already blocks. Residual by design: +the match ignores HOME, so `rm -rf /tmp/proj/.fuse-harness/state` is now deny (as `mv`/`cp`/`>` already were). +Not covered (still ask, a human confirms): `sh -c '...'`, `bash -c`, `xargs rm`, globs, `cd` then relative. + +## Assertions changed (each tightening, with the line producing the new verdict) +- `receipt-tamper-guards.test.ts` "find -exec rm" ask -> deny, and "rm of absolute key after escaped space" ask -> deny (a literal-`~` variant added, stays ask): + new verdict from `index.ts` `denyOverAsk` -> `protected-path.ts` `receiptStoreGuard` (`newPathTargets(...).some(hitsNewPath)`); `hitsNewPath` exempts a word after an escaped space only when it starts with `~`/`$`. +- `receipt-tamper-data.test.ts` (PR #141, `src/tracking/track-verify.ts`): `replay_into_other_session` true -> false (line 47, `foreign-session`), + `reorder_changes_verdict` false -> true (line 51, `duplicate-or-reorder`), `duplicate_lines_counted_once` true -> false (line 51, same reason: a duplicate breaks the chain). +- Helper `test/helpers/receipt-tamper-probe.ts` ported to main: `parseEvents` no longer exists (local MAC-only parser via `parseLine`/`lineMacOk`); + the key-swap attacker now restarts the chain (rm log + head, `appendEvent` under the swapped key) so `after_key_swap_attacker_line_valid` stays `true` (assertion unchanged; challenger caught it). + +## Verification +- Targeted (6 files, 17 tests): 20x under load 9-14: 16/20 clean; the 4 other runs failed only by bun's 5 s default timeout (test durations 11-40 s under 5 parallel suites); my 3 new tests now carry a 60 s timeout. Re-run after: 17 pass / 0 fail (2.8 s). +- `bunx tsc --noEmit`: 0 errors. RED observed first (test/receipt-tamper-homes.test.ts fails on the unfixed code). +- Full suite, quiet machine (load ~2), one suite at a time: branch 5824 pass / 3 skip / 0 fail (497 files, 455 s); aefa7d5 (extracted to /private/tmp, `git archive`) 5812 pass / 3 skip / 1 fail + (`bash-write-monotone/cpmv-dest-root.test.ts` "a code source under ANOTHER proven root outside temp is allowed"): re-run isolated it fails on the base copy and passes (11/11) on the branch worktree - an artefact of running the base from `/private/tmp` (the test needs a non-temp project root), not a main regression. Linux: docker daemon is down, "Linux not verified locally" - the failing shape is reproduced with non-`/var` homes (`/tmp`, `/home/u`, `/root`). + +## Challenger round 2: CONFIRMED +Helper fix measures a real attacker-with-key chain (`integrity.ts:47-49` reads the key fresh; `track-verify.ts:41` `bad-mac` otherwise); data flips match `track-verify.ts:47` / `:51`; +the HOME-independent match is `NEW_PATH_RES` (`protected-path-targets.ts:97`) + `hitsNewPath` (`:105-111`), the same predicate `protectedPathGuard` already applies to `mv`/`cp`/`>`; no `rm` of such paths in repo scripts/docs/tests (only in-process `rmSync` of whole temp dirs). +Pre-existing gap NOT closed (not a regression): the PARENT dir. `rm -rf ~/.fuse-harness` and `rm -rf ~/.fuse-harness/*` stay `ask`; `mv ~/.fuse-harness /tmp/x` is **allow** (it moves state and key). `git clone x

/.fuse-harness/state` is allow. + +## Follow-ups (not done) +- Probe `truncate_drops_failing_line.detected` is a constant `false`; main's chain makes truncation fail closed, so it is not measuring anything. +- `sh -c`/`bash -c` payloads are not analysed by `protectedPathGuard` (ask only). diff --git a/src/policy/guards/index.ts b/src/policy/guards/index.ts index a5cf597..70bfcb5 100644 --- a/src/policy/guards/index.ts +++ b/src/policy/guards/index.ts @@ -1,7 +1,7 @@ import type { Prompt } from "../../prompt/types"; import type { Guard, GuardContext } from "./context"; import { securityGuard } from "./security"; -import { protectedPathGuard } from "./protected-path"; +import { protectedPathGuard, receiptStoreGuard } from "./protected-path"; import { bashWriteGuard } from "./bash-write"; import { interfaceSeparationGuard } from "./interface-separation"; import { installGuard } from "./install"; @@ -62,7 +62,20 @@ export function runGuards(ctx: GuardContext): Prompt | null { } catch { return FAIL_CLOSED; } - if (hit) return hit; + if (hit) return hit.kind === "ask" ? denyOverAsk(hit, ctx) : hit; } return null; } + +/** + * A guard's ask must never hide the receipt-store / HMAC-key deny that sits later in the chain (the generic `rm` ask fires + * first and would otherwise decide `rm -rf /.fuse-harness/state`). Only that one rule is consulted, so no other + * verdict moves; if it throws, the ask stands (the old verdict). + */ +function denyOverAsk(ask: Prompt, ctx: GuardContext): Prompt { + try { + return receiptStoreGuard(ctx) ?? ask; + } catch { + return ask; + } +} diff --git a/src/policy/guards/protected-path-commands.ts b/src/policy/guards/protected-path-commands.ts new file mode 100644 index 0000000..384a40e --- /dev/null +++ b/src/policy/guards/protected-path-commands.ts @@ -0,0 +1,150 @@ +/** Leading words that run the next word as a command (env assignments, sudo, shell keywords): skipped to find the real command word. */ +const WRAPPER_RE = /^(?:sudo|env|command|time|nice|nohup|exec|builtin|\{|!|if|then|else|elif|do|while|until|\w+=\S*)$/; +/** Options of wrapper commands that take a separate value (`nice -n 10`, `env -u HOME`, `exec -a NAME`): the value is skipped with the option. */ +const WRAPPER_VALUE_OPTS: Readonly> = { + nice: ["-n"], env: ["-u", "-C", "-S"], exec: ["-a"], time: ["-o", "-f"], sudo: ["-u", "-g", "-C", "-h", "-p", "-r", "-t", "-U"], +}; +/** Wrapper options after which NOTHING is executed (`command -v rm K`, `sudo -l`): the rest is only inspected, never run. */ +const WRAPPER_NO_RUN: Readonly> = { command: ["-v", "-V"], sudo: ["-l", "-v", "-V", "-k", "-K", "-h"] }; +/** In-place flag spellings: sed `-i`/`-I`/`-iSUF`/`-Ei`/`--in-place`; perl bundles like `-pi`, `-wpi`, `-0pi`, `-i.bak` (never `-Mstrict`, `-I`, `-e`). */ +const IN_PLACE: Readonly> = { sed: /^(?:-[pnlaEsuzr]*[iI]\S*|--in-place\S*)$/, perl: /^-[pnlaEsuzrwW0-9]*i\S*$/ }; +/** Commands whose every operand is created, truncated, deleted or moved away. */ +const DESTRUCTIVE = new Set(["touch", "truncate", "rm", "rmdir", "unlink", "shred", "mv"]); +/** Short option letters that take a READ-ONLY value, per command (`touch -r REF`, `truncate -s N`; `rm` has none, so `rm -r DIR` keeps DIR). */ +const VALUE_LETTERS: Readonly> = { touch: "rdt", truncate: "sr", shred: "ns" }; +/** Long options that take a separate read-only value. */ +const VALUE_LONG = new Set(["--reference", "--date", "--size", "--iterations", "--random-source", "--bytes"]); +/** `xargs` options that take a separate argument. */ +const XARGS_ARG_OPTS = new Set(["-I", "-J", "-n", "-P", "-d", "-L", "-s", "-E", "-a", "--max-args", "--max-procs"]); +/** `find` options that may precede the search roots. */ +const FIND_PRE_OPTS = /^-[HLPxXEsd]+$/; + +/** Receives one candidate write target. */ +export type Push = (t: string | undefined) => void; + +/** Operands (non-option words), without shell line-continuation / find terminators. */ +const positional = (toks: string[]): string[] => toks.filter((t) => Boolean(t) && !t.startsWith("-") && t !== "\\" && t !== "+"); + +/** Value of option (`-t DIR`, `-tDIR`, `-rt DIR` bundle, `--long=DIR`, `--long DIR`), or undefined. */ +function optionValue(toks: string[], short: string, long: string): string | undefined { + const bundle = new RegExp(`^-[a-zA-Z]*${short.slice(1)}$`); + const i = toks.findIndex((x) => x === short || x === long || x.startsWith(`${long}=`) || bundle.test(x) || (x.startsWith(short) && x.length > 2 && !x.startsWith("--"))); + const x = toks[i]; + if (i < 0 || x === undefined) return undefined; + if (x === long || bundle.test(x)) return toks[i + 1]; + return x.startsWith(`${long}=`) ? x.slice(long.length + 1) : x.slice(short.length); +} + +/** Operands of a {@link DESTRUCTIVE} command, skipping the read-only value of options like `touch -r REF` / `-cr REF` / `truncate -s 0`. */ +function destructiveOperands(verb: string, toks: string[]): string[] { + const letters = VALUE_LETTERS[verb] ?? "", out: string[] = []; + for (let i = 0; i < toks.length; i++) { + const x = toks[i] ?? ""; + if (x === "--") { out.push(...positional(toks.slice(i + 1))); break; } + if (x.startsWith("--")) { if (VALUE_LONG.has(x)) i++; continue; } + if (x.startsWith("-") && x.length > 1) { + const p = [...x.slice(1)].findIndex((c) => letters.includes(c)); + if (p >= 0 && p === x.length - 2) i++; // the value letter ends the bundle: its value is the next word (glued values need no skip) + continue; + } + if (x) out.push(x); + } + return out; +} + +/** Parse an in-place `sed`/`perl` command line: whether a REAL in-place flag is present (flag-shaped script words after `-e`/`-f` do not count) and its file operands (script words are not files). */ +function inPlace(verb: string, toks: string[]): { on: boolean; files: string[] } { + const re = IN_PLACE[verb]; + const rest: string[] = []; + let on = false, scripted = false; + for (let i = 0; i < toks.length; i++) { + const x = toks[i] ?? ""; + if (x === "-e" || x === "-f" || x === "--expression" || x === "--file") { scripted = true; i++; continue; } + if (x.startsWith("--expression=") || x.startsWith("--file=")) { scripted = true; continue; } + if (x.startsWith("-")) { + // After the first FILE operand a flag-looking word is a file name (perl stops option parsing at the script; BSD sed at the first operand). + const filesSeen = verb === "perl" ? rest.length > 0 : rest.length >= (scripted ? 1 : 2); + if (filesSeen) { rest.push(x); continue; } + if (re?.test(x)) on = true; else if (/^-[a-zA-Z]*[ef]\S+$/.test(x)) scripted = true; + continue; + } + rest.push(x); + } + return { on, files: scripted ? rest : rest.slice(1) }; +} + +/** Whether `-x`/`x` (extract) is among a tar command line's option words (`tar xf`, `tar -xzf`, `--extract`). */ +const tarExtracts = (toks: string[]): boolean => !toks.includes("--to-stdout") && toks.some((t, i) => t === "--extract" || t === "--get" || /^-[a-zA-Z]*x[a-zA-Z]*$/.test(t) || (i === 0 && /^[a-zA-Z]*x[a-zA-Z]*$/.test(t))) && !toks.some((t, i) => /O/.test(t) && (/^-[a-zA-Z]+$/.test(t) || (i === 0 && /^[a-zA-Z]+$/.test(t)))); // `-O` extracts to stdout: nothing is written + +/** Verb of a command's words once wrappers and their options are skipped; `verb` is "" when the wrapper only inspects (`command -v`, `sudo -l`). */ +function verbOf(rawToks: string[]): { verb: string; toks: string[] } { + const toks = [...rawToks]; + while (toks.length && WRAPPER_RE.test(toks[0] ?? "")) { + const w = toks.shift() ?? ""; + while (toks.length && (toks[0] ?? "").startsWith("-")) { + const o = toks.shift() ?? ""; + if (WRAPPER_NO_RUN[w]?.includes(o)) return { verb: "", toks: [] }; + if (WRAPPER_VALUE_OPTS[w]?.includes(o)) toks.shift(); + } + } + return { verb: (toks.shift() ?? "").split("/").at(-1) ?? "", toks }; +} + +/** rsync destination: the last operand that is not the separate value of a `--long` option (`--exclude-from FILE`); needs 2+ operands overall. */ +function rsyncDest(toks: string[]): string | undefined { + const isValue = (i: number): boolean => (toks[i - 1] ?? "").startsWith("--") && !(toks[i - 1] ?? "").includes("="); // `--exclude -n`: -n is a value + if (toks.some((t, i) => !isValue(i) && (t === "--dry-run" || /^-[a-zA-Z]*n[a-zA-Z]*$/.test(t)))) return undefined; // a dry run (`-n`, `-an`, `--dry-run`) writes nothing + const dests = toks.filter((t, i) => t && !t.startsWith("-") && !((toks[i - 1] ?? "").startsWith("--") && !(toks[i - 1] ?? "").includes("="))); + return positional(toks).length >= 2 ? dests.at(-1) : undefined; +} + +/** Search roots of a `find` command line: operands before the expression, after any leading `-H/-L/-P/-x/…` options (`-f PATH` too). */ +function findRoots(toks: string[]): string[] { + const roots: string[] = []; + for (let i = 0; i < toks.length; i++) { + const t = toks[i] ?? ""; + if (FIND_PRE_OPTS.test(t)) continue; + if (t === "-f") { roots.push(toks[++i] ?? ""); continue; } + if (t.startsWith("-") || t === "(" || t === "!") break; + roots.push(t); + } + return roots; +} + +/** + * Write targets of ONE simple command, given its words. Only operands that are really written count: destinations of + * `cp`/`ln`/`install`/`rsync` (needs 2+ operands, or `-t DIR`), every operand of `mv`/`touch`/`truncate`/`rm`/…, + * `tee` files, `dd of=`, `tar` extraction `-C`, `unzip -d`, in-place `sed`/`perl` files, and the command run by + * `xargs` / `find -exec` (plus the `find` roots when `-delete` is given or the `-exec` command writes `{}`). + * @param rawToks - The command's words (redirections already removed). + * @param push - Receives each candidate target. + */ +export function commandTargets(rawToks: string[], push: Push): void { + const { verb, toks } = verbOf(rawToks); + const pos = positional(toks); + if (verb === "tee") pos.forEach(push); + else if (verb === "rsync") push(rsyncDest(toks)); // `-t` is "preserve times" for rsync, not a target directory + else if (verb === "cp" || verb === "ln" || verb === "install") { const t = optionValue(toks, "-t", "--target-directory"); if (t !== undefined) push(t); else if (pos.length >= 2) push(pos.at(-1)); } + else if (verb === "mv") { push(optionValue(toks, "-t", "--target-directory")); pos.forEach(push); } // sources are moved away, so they are written too + else if (DESTRUCTIVE.has(verb)) destructiveOperands(verb, toks).forEach(push); + else if (verb === "dd") toks.filter((x) => x.startsWith("of=")).forEach((x) => push(x.slice(3))); + else if ((verb === "tar" || verb === "bsdtar") && tarExtracts(toks)) push(optionValue(toks, "-C", "--directory")); + else if (verb === "unzip") { if (!toks.some((t) => /^-[a-zA-Z]*[ltpvzZ][a-zA-Z]*$/.test(t))) push(optionValue(toks, "-d", "--directory")); } // -l/-t/-p/-v/-z/-Z list, test or print: nothing is extracted + else if (verb === "sed" || verb === "perl") { const p = inPlace(verb, toks); if (p.on) p.files.forEach(push); } + else if (verb === "xargs") { // `… | xargs cp {} DIR`: the rest is the command + let i = 0; + for (; i < toks.length && (toks[i] ?? "").startsWith("-"); i++) if (XARGS_ARG_OPTS.has(toks[i] ?? "")) i++; + commandTargets(toks.slice(i), push); + } else if (verb === "find") { + let writesFound = toks.includes("-delete"); + const isExec = (x: string | undefined): boolean => ["-exec", "-execdir", "-ok", "-okdir"].includes(x ?? ""); + for (let i = 0; i < toks.length; i++) { // every `-exec … ;|+` clause (a command may carry several; the stripper may have dropped the `\;`) + if (!isExec(toks[i])) continue; + let j = i + 1; + while (j < toks.length && !["+", ";", "\\"].includes(toks[j] ?? "") && !isExec(toks[j])) j++; + commandTargets(toks.slice(i + 1, j), (t) => { push(t); if (t !== undefined && /^\{\}[^/]*$/.test(t)) writesFound = true; }); // `{}` or a sibling name derived from it (`{}.bak`), never `~/bk/{}` (a copy OUT) + i = j - 1; + } + if (writesFound) findRoots(toks).forEach(push); + } +} diff --git a/src/policy/guards/protected-path-targets.ts b/src/policy/guards/protected-path-targets.ts new file mode 100644 index 0000000..35c489e --- /dev/null +++ b/src/policy/guards/protected-path-targets.ts @@ -0,0 +1,111 @@ +import { posix } from "node:path"; +import { shellFileWriteRedirects } from "./bash-write-redirects"; +import { unquotedShellText } from "./bash-write-unquoted"; +import { commandTargets, type Push } from "./protected-path-commands"; + +/** Shell operators/groupers that each start a new simple command once flattened into `;`. */ +const FLATTEN_RE = /\$\(|[\n`()]/g; +/** A command substitution body: `$( … )` (group 1) or `` ` … ` `` (group 2); innermost only (no nested parens). */ +const SUBST_RE = /\$\(([^()]*)\)|`([^`]*)`/g; +/** Output/input redirection operators with their (glued or spaced) operand, removed before picking positional arguments. */ +const REDIRECT_RE = /\d*&?[<>]+[|&]?\s*\S*/g; +/** A quoted single word with no whitespace, separator or substitution inside: its quotes are only a spelling of the path (`~/.fuse-harness/'.key'`, `".k""ey"`). */ +const SIMPLE_QUOTED_RE = /(['"])([^\s'"`;|&<>()]*)\1/g; +/** A backslash escaping an ordinary path character (`\.key`, `state\/x`): the shell drops it. */ +const PATH_ESCAPE_RE = /\\([A-Za-z0-9._/-])/g; +/** Stand-in for an escaped space, so `x\ y` stays ONE word (and `rm /tmp/x\ K` is not mistaken for an operand `K`). */ +const GLUED_SPACE = "\u0001"; + +/** Strips surrounding quotes from a captured shell token. */ +const unquote = (t: string): string => t.replace(/^['"]|['"]$/g, ""); + +/** + * Replace every arithmetic expansion `$(( … ))` (a plain word, never a command) by a placeholder, matching the + * closing `))` with a parenthesis depth counter so inner parens (`$(( (n+1)*2 ))`, `$(( $(id -u) ))`) stay inside. + * An unterminated `$((` is left untouched. + */ +function stripArithmetic(text: string): string { + let out = "", i = 0; + while (i < text.length) { + if (!text.startsWith("$((", i)) { out += text[i++]; continue; } + let depth = 0, j = i + 1; + for (; j < text.length; j++) { + if (text[j] === "(") depth++; + else if (text[j] === ")" && --depth === 0) break; + } + if (j >= text.length) { out += text[i++]; continue; } + out += "SUBST"; + i = j + 1; + } + return out; +} + +/** + * Unquote simple quoted words and unescape path characters — but ONLY when the quoting is unambiguous: every quote kind + * balanced and no escaped quote anywhere. Otherwise the regex could pair the wrong quotes and read quoted TEXT as code, + * so the command is left as is (a quoted target is then simply not seen — never a false positive). + */ +function spellPaths(text: string): string { + const count = (re: RegExp): number => (text.match(re) ?? []).length; + const ambiguous = /\\['"]/.test(text) || count(/"/g) % 2 !== 0 || count(/'/g) % 2 !== 0; + const plain = ambiguous ? text : text.replace(SIMPLE_QUOTED_RE, "$2"); + return plain.replace(/\\ /g, GLUED_SPACE).replace(PATH_ESCAPE_RE, "$1"); +} + +/** Collect the write targets of every simple command in `text` (substitutions already replaced by a placeholder word). */ +function segments(text: string, push: Push): void { + // `\;` ends a `find -exec` clause but is NOT a command separator: keep it as a `\` word so later clauses stay in the same `find` command. + for (const seg of text.replace(/\\;/g, " \\ ").replace(FLATTEN_RE, ";").split(/[;&|\n]+/)) commandTargets(seg.replace(REDIRECT_RE, " ").trim().split(/\s+/), push); +} + +/** + * Precise write targets of a Bash command, used ONLY for the newly protected harness paths (never combined with the + * legacy heuristics): output redirections (quote-aware lexer, raw text), plus — on the quote-, comment- and + * heredoc-stripped view, at COMMAND position only — the operands that the command really writes (see + * {@link commandTargets}). Newlines, `( )`, backticks and `$( )` split commands; substitutions are analysed as their + * own commands and stand in as one placeholder word; `$(( ))` is a plain word. A quoted or text-only mention + * (`echo "cp a K"`, a commit heredoc, a `grep` argument) never counts. + * @param cmd - The raw Bash command. + * @returns Candidate write targets (quotes and backslashes removed; empty strings and `/dev/null` filtered out). + */ +export function newPathTargets(cmd: string): string[] { + const out: string[] = []; + const push: Push = (t) => { + const v = unquote((t ?? "").trim()).replace(/\\(.)/g, "$1"); + if (v && v !== "/dev/null") out.push(v); + }; + // Redirects: the quote-aware lexer on the raw text, unless a heredoc is present (its body would be scanned as code: `cat <<'EOF'\necho x > K\nEOF`). + const heredoc = /<<-?\s*['"\\]?\w/.test(cmd); + if (!heredoc) for (const redirect of shellFileWriteRedirects(cmd)) push(redirect.target); + // Arithmetic is replaced on the RAW text: the quote/data stripper would otherwise erase `$((…))` and leave the source as the last word. + // An ESCAPED `\$(` / backtick is literal text, never a substitution: neutralised first. + const queue = [unquotedShellText(spellPaths(stripArithmetic(cmd.replace(/\\\$\(/g, "ESCDOLLAR").replace(/\\`/g, "ESCTICK"))))]; + for (let depth = 0; queue.length && depth < 64; depth++) { + let text = queue.shift() ?? ""; + if (heredoc) for (const redirect of shellFileWriteRedirects(text)) push(redirect.target); // data-stripped view: heredoc bodies are gone + // Fixpoint: innermost substitutions go first, so a NESTED destination (`$(dirname $(mktemp))`) collapses to one placeholder too. + for (let prev = ""; prev !== text; ) { + prev = text; + text = text.replace(SUBST_RE, (_m, a: string | undefined, b: string | undefined) => { queue.push(a ?? b ?? ""); return "SUBST"; }); + } + segments(text, push); + } + return out; +} + +/** Paths under the harness home that an agent must never write: the signed track dir and the HMAC key. */ +const NEW_PATH_RES: readonly RegExp[] = [/(?:^|\/)\.fuse-harness\/state(?:\/|$)/i, /(?:^|\/)\.fuse-harness\/\.key\/?$/i]; + +/** + * Whether `target` is (or resolves to) the harness state dir or HMAC key. The path is normalised first, so `//`, `/./` + * and `/x/../` segments cannot hide it; matching is case-insensitive (macOS filesystems are). + * @param target - A file path from a Write/Edit payload or an extracted Bash write target. + * @returns `true` when the target is the state dir (or inside it) or the key file. + */ +export function hitsNewPath(target: string): boolean { + const n = posix.normalize(target.trim().replaceAll(GLUED_SPACE, " ")); + // `~` and `$VAR` only expand at the START of a word: after an escaped space (`/tmp/x\ ~/.fuse-harness/.key`) they are literal directory names. + const word = n.includes(" ") ? n.slice(n.lastIndexOf(" ") + 1) : n; + if (n.includes(" ") && /^[~$]/.test(word)) return false; + return NEW_PATH_RES.some((re) => re.test(n)); +} diff --git a/src/policy/guards/protected-path.ts b/src/policy/guards/protected-path.ts index 0b3db43..2a04c7e 100644 --- a/src/policy/guards/protected-path.ts +++ b/src/policy/guards/protected-path.ts @@ -1,6 +1,7 @@ import type { Prompt } from "../../prompt/types"; import type { GuardContext } from "./context"; import { shellOutputRedirects } from "./bash-write-redirects"; +import { hitsNewPath, newPathTargets } from "./protected-path-targets"; import { LEGACY_MOTION_FRAGMENT, MOTION_KEY_FRAGMENT, MOTION_STORE_FRAGMENT } from "../motion/store"; /** @@ -85,6 +86,18 @@ function extractWriteTargets(cmd: string): string[] { return out; } +/** + * Only the receipt-store / HMAC-key rule of {@link protectedPathGuard} (the harness `state` dir and `.key`), none of the + * legacy fragments. Lets the chain keep this one deny when an earlier guard's ask would otherwise hide it. + * @param ctx - The guard context. + * @returns A blocking {@link Prompt}, or null when the call does not write the state dir or key. + */ +export function receiptStoreGuard(ctx: GuardContext): Prompt | null { + if ((ctx.tool === "Write" || ctx.tool === "Edit") && ctx.filePath) return hitsNewPath(ctx.filePath) ? BLOCK : null; + if (ctx.tool === "Bash" && ctx.command) return newPathTargets(ctx.command).some(hitsNewPath) ? BLOCK : null; + return null; +} + /** * Blocks direct edits to internal/generated state directories. * @@ -97,11 +110,10 @@ function extractWriteTargets(cmd: string): string[] { * @returns A blocking {@link Prompt}, or null to allow. */ export function protectedPathGuard(ctx: GuardContext): Prompt | null { - if ((ctx.tool === "Write" || ctx.tool === "Edit") && ctx.filePath) { - if (containsProtected(ctx.filePath)) return BLOCK; - } - if (ctx.tool === "Bash" && ctx.command) { - if (extractWriteTargets(ctx.command).some(containsProtected)) return BLOCK; - } - return null; + if ((ctx.tool === "Write" || ctx.tool === "Edit") && ctx.filePath && containsProtected(ctx.filePath)) return BLOCK; + // Pre-existing protected paths keep EXACTLY the legacy heuristics (verdicts byte-identical to before). + if (ctx.tool === "Bash" && ctx.command && extractWriteTargets(ctx.command).some(containsProtected)) return BLOCK; + // New paths (receipt store + HMAC key): normalised match, so `//`, `/./` and `/../` cannot hide them; for Bash only the + // precise extractor applies there (they were unprotected before), so no legacy over-block is inherited. + return receiptStoreGuard(ctx); } diff --git a/src/runtime/paths.ts b/src/runtime/paths.ts index 27bb668..ad592f8 100644 --- a/src/runtime/paths.ts +++ b/src/runtime/paths.ts @@ -5,8 +5,10 @@ * Default base: ~/.fuse-harness/state// * where projectHash = 8-char MD5 of CLAUDE_PROJECT_DIR (or cwd). * Persistent and not world-writable (unlike /tmp), and OUTSIDE the repo so the - * agent has no "legitimate" reason to write it (the protected-path guard denies - * it, and the gate verifies freshness from the transcript, not this file). + * agent has no "legitimate" reason to write it: the protected-path guard denies + * agent Write/Edit/Bash writes to `~/.fuse-harness/state/` and `~/.fuse-harness/.key` + * (the harness's own writes run inside the hook process, never through a tool call). + * Reads stay allowed. The gate verifies freshness from the transcript, not this file. * * @packageDocumentation */ diff --git a/test/helpers/receipt-tamper-probe.ts b/test/helpers/receipt-tamper-probe.ts new file mode 100644 index 0000000..9fa8675 --- /dev/null +++ b/test/helpers/receipt-tamper-probe.ts @@ -0,0 +1,113 @@ +/** + * Probe run in a SUBPROCESS with an isolated HOME (Bun caches `os.homedir()`): replays the data-layer tamper + * attempts an agent with file access could make against the signed track journal / snapshot and prints, per + * attempt, whether a forged or altered receipt is still ACCEPTED by `freshReceiptFromFile` (the TaskCompleted gate's read). + */ +import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { computeMac, loadOrCreateKey, signTrack } from "../../src/tracking/integrity"; +import { freshReceiptFromFile } from "../../src/tracking/receipts"; +import { journalLogPath } from "../../src/tracking/track-compact"; +import { headPath, lineMacOk, parseLine } from "../../src/tracking/track-chain"; +import { appendEvent, signEvent, type TrackEvent } from "../../src/tracking/track-journal"; +import { emptyTrack } from "../../src/tracking/session-state"; +import type { Receipt } from "../../src/tracking/receipts"; + +/** Raw journal lines whose own MAC verifies (no chain walk): the pre-0.1.124 `parseEvents`, kept here as a tamper-counting aid. */ +function parseEvents(text: string): TrackEvent[] { + const key = loadOrCreateKey(); + return text.split("\n").flatMap((line) => { + const ev = line ? parseLine(line) : null; + return ev && lineMacOk(key, ev) ? [ev] : []; + }); +} + +const NOW = 1_000_000; +const WINDOW = 60_000; +const root = process.env.PROBE_DIR as string; +mkdirSync(root, { recursive: true }); + +// Mode "export": write one honest session (snapshot + journal) and print its path — the artefacts a CI would be handed. +// Mode "verify": CI side — fresh HOME, only the exported files; print what the gate-read accepts and whether a key now exists. +if (process.env.PROBE_MODE === "export") { + const file = join(root, "track-export.json"); + appendEvent(journalLogPath(file), "receipts", "append", { kind: "test", tool: "bun test", exitCode: 0, pass: 9, fail: 0, ts: NOW - 1000 }, NOW - 1000); + process.stdout.write(JSON.stringify({ file })); + process.exit(0); +} +if (process.env.PROBE_MODE === "verify") { + const file = process.env.PROBE_FILE as string; + const keyFile = join(process.env.HOME as string, ".fuse-harness", ".key"); + const keyBefore = existsSync(keyFile); + const events = parseEvents(readFileSync(journalLogPath(file), "utf8")).length; + process.stdout.write(JSON.stringify({ keyBefore, events, accepted: freshReceiptFromFile(file, WINDOW, NOW) !== null, keyMintedByVerifier: !keyBefore && existsSync(keyFile) })); + process.exit(0); +} +const out: Record = {}; +let n = 0; + +/** A passing `bun test` receipt stamped at `ts`. */ +const pass = (ts: number): Receipt => ({ kind: "test", tool: "bun test", exitCode: 0, pass: 9, fail: 0, ts }); +/** A failing `bun test` receipt stamped at `ts`. */ +const fail = (ts: number): Receipt => ({ kind: "test", tool: "bun test", exitCode: 1, pass: 0, fail: 3, ts }); +/** A fresh session track path (`track-sN.json`) with its journal twin. */ +const session = (): { file: string; log: string } => { const file = join(root, `track-s${n++}.json`); return { file, log: journalLogPath(file) }; }; +/** Whether the TaskCompleted gate-read accepts a fresh receipt from `file`. */ +const accepted = (file: string): boolean => freshReceiptFromFile(file, WINDOW, NOW) !== null; +/** Non-empty lines of a journal file. */ +const lines = (log: string): string[] => readFileSync(log, "utf8").split("\n").filter(Boolean); +/** A receipt-append event signed with the machine key. */ +const sign = (r: Receipt): TrackEvent => signEvent("receipts", "append", r, r.ts) as TrackEvent; + +// s0 control: an honestly appended passing receipt is accepted. +{ const s = session(); appendEvent(s.log, "receipts", "append", pass(NOW - 1000), NOW - 1000); out.control_honest = accepted(s.file); } +// s1 edit: a signed FAILING receipt is rewritten to exit 0 / pass 9 without re-signing. +{ const s = session(); appendEvent(s.log, "receipts", "append", fail(NOW - 1000), NOW - 1000); + const edited = lines(s.log)[0]!.replace('"exitCode":1', '"exitCode":0').replace('"pass":0', '"pass":9').replace('"fail":3', '"fail":0'); + writeFileSync(s.log, edited + "\n"); out.edit_line_without_resign = accepted(s.file); } +// s2 forge unsigned / bad mac. +{ const s = session(); const ev = { ...sign(pass(NOW - 1000)), mac: "0".repeat(64) }; appendFileSync(s.log, JSON.stringify(ev) + "\n"); out.forge_bad_mac = accepted(s.file); } +// s3 forge with a guessed key. +{ const s = session(); const ev = sign(pass(NOW - 1000)); const data = JSON.stringify({ field: ev.field, op: ev.op, value: ev.value, ts: ev.ts }); + appendFileSync(s.log, JSON.stringify({ ...ev, mac: computeMac("attacker-guess", data, ev.nonce) }) + "\n"); out.forge_wrong_key = accepted(s.file); } +// s4 forge with the machine key READ from /.fuse-harness/.key (what an agent with file read can do). +{ const s = session(); const key = readFileSync(join(process.env.HOME as string, ".fuse-harness", ".key"), "utf8").trim(); + const value = pass(NOW - 1000); const data = JSON.stringify({ field: "receipts", op: "append", value, ts: value.ts }); + const ev = { v: 1, field: "receipts", op: "append", value, ts: value.ts, nonce: "deadbeefdeadbeef", mac: computeMac(key, data, "deadbeefdeadbeef") }; + appendFileSync(s.log, JSON.stringify(ev) + "\n"); out.forge_with_read_key = accepted(s.file); + out.key_mode_octal = (statSync(join(process.env.HOME as string, ".fuse-harness", ".key")).mode & 0o777).toString(8); } +// s5 replay: a valid line copied from session A into session B (the MAC binds no session id), then the same line aged out of the window. +{ const a = session(), b = session(); appendEvent(a.log, "receipts", "append", pass(NOW - 1000), NOW - 1000); + appendFileSync(b.log, lines(a.log)[0] + "\n"); out.replay_into_other_session = accepted(b.file); + const c = session(), d = session(); appendEvent(c.log, "receipts", "append", pass(NOW - WINDOW - 5000), NOW - WINDOW - 5000); + appendFileSync(d.log, lines(c.log)[0] + "\n"); out.replay_stale_line = accepted(d.file); } +// s5b replay edit of ts to make a stale line fresh: breaks the MAC. +{ const s = session(); appendEvent(s.log, "receipts", "append", pass(NOW - WINDOW - 5000), NOW - WINDOW - 5000); + const l = JSON.parse(lines(s.log)[0]!) as TrackEvent; l.ts = NOW - 1000; (l.value as Receipt).ts = NOW - 1000; writeFileSync(s.log, JSON.stringify(l) + "\n"); out.restamp_stale_line = accepted(s.file); } +// s6 truncate / delete lines: deleting a signed FAILING receipt or a violation record is not detected. +{ const s = session(); appendEvent(s.log, "receipts", "append", fail(NOW - 500), NOW - 500); appendEvent(s.log, "receipts", "append", pass(NOW - 1000), NOW - 1000); + const before = parseEvents(readFileSync(s.log, "utf8")).length; writeFileSync(s.log, lines(s.log).slice(1).join("\n") + "\n"); + out.truncate_drops_failing_line = { eventsBefore: before, eventsAfter: parseEvents(readFileSync(s.log, "utf8")).length, detected: false }; } +{ const s = session(); appendEvent(s.log, "receipts", "append", pass(NOW - 1000), NOW - 1000); writeFileSync(s.log, ""); out.truncate_to_empty_receipt_survives = accepted(s.file); } +// s7 reorder lines: the fold sorts by ts, so order is irrelevant (no sequence number / hash chain either). +{ const s = session(); appendEvent(s.log, "receipts", "append", fail(NOW - 500), NOW - 500); appendEvent(s.log, "receipts", "append", pass(NOW - 1000), NOW - 1000); + const before = accepted(s.file); writeFileSync(s.log, lines(s.log).reverse().join("\n") + "\n"); out.reorder_changes_verdict = before !== accepted(s.file); } +// s8 duplicate the same line N times: deduped by nonce. +{ const s = session(); appendEvent(s.log, "receipts", "append", pass(NOW - 1000), NOW - 1000); const l = lines(s.log)[0]!; appendFileSync(s.log, `${l}\n${l}\n`); + const t = freshReceiptFromFile(s.file, WINDOW, NOW); out.duplicate_lines_counted_once = t !== null && new Set(parseEvents(readFileSync(s.log, "utf8")).map((e) => e.nonce)).size === 1; } +// s9 snapshot: edit data without re-signing; delete; roll back to an older valid snapshot. +{ const s = session(); writeFileSync(s.file, JSON.stringify(signTrack({ ...emptyTrack(), receipts: [fail(NOW - 1000)] }))); + const env = JSON.parse(readFileSync(s.file, "utf8")) as { data: string }; env.data = env.data.replace('"exitCode":1', '"exitCode":0').replace('"fail":3', '"fail":0').replace('"pass":0', '"pass":9'); + writeFileSync(s.file, JSON.stringify(env)); out.snapshot_edit_without_resign = accepted(s.file); } +{ const s = session(); writeFileSync(s.file, JSON.stringify(signTrack({ ...emptyTrack(), receipts: [pass(NOW - 1000)] }))); copyFileSync(s.file, `${s.file}.bak`); + writeFileSync(s.file, JSON.stringify(signTrack({ ...emptyTrack(), receipts: [fail(NOW - 500)] }))); copyFileSync(`${s.file}.bak`, s.file); out.snapshot_rollback_to_older_valid = accepted(s.file); + out.snapshot_delete_loses_receipts = (() => { writeFileSync(s.file, "garbage"); return accepted(s.file); })(); } +// s10 key replacement: swapping the key invalidates every previous line; the attacker then signs freely with its own key. +{ const s = session(); appendEvent(s.log, "receipts", "append", pass(NOW - 1000), NOW - 1000); + const keyFile = join(process.env.HOME as string, ".fuse-harness", ".key"); const original = readFileSync(keyFile, "utf8"); + writeFileSync(keyFile, "attacker-chosen-key"); out.after_key_swap_old_lines_valid = accepted(s.file); + // Since 0.1.124 a bare v1 line no longer verifies: the attacker (who holds the key) restarts the chain, dropping the old log and its head. + rmSync(s.log, { force: true }); rmSync(headPath(s.log), { force: true }); appendEvent(s.log, "receipts", "append", pass(NOW - 1000), NOW - 1000); + out.after_key_swap_attacker_line_valid = accepted(s.file); writeFileSync(keyFile, original); } +out.key_file_exists = existsSync(join(process.env.HOME as string, ".fuse-harness", ".key")); +process.stdout.write(JSON.stringify(out)); diff --git a/test/protected-path-new.test.ts b/test/protected-path-new.test.ts new file mode 100644 index 0000000..f5dd2a3 --- /dev/null +++ b/test/protected-path-new.test.ts @@ -0,0 +1,52 @@ +/** + * Guard-level regression for the receipt-store / HMAC-key protection (`~/.fuse-harness/state`, `~/.fuse-harness/.key`). + * Rows come from adversarial challenger rounds: every READ (and look-alike) must stay allowed — no legacy heuristic is + * inherited on these paths — and every real WRITE in a named category must be blocked. + */ +import { expect, test } from "bun:test"; +import { protectedPathGuard } from "../src/policy/guards/protected-path"; + +const H = "~/.fuse-harness"; +const K = `${H}/.key`, S = `${H}/state`, F = `${H}/state/ab/t.json`; + +const reads: readonly string[] = [ + `cat ${K}`, `grep -rn mv ${S}`, `rg tee ${S}`, `grep -E "mv|cp" ${S}`, `cp -t /tmp ${F}`, `cp -rt /tmp/dst ${S}`, `install -Dt /tmp/dst ${K}`, `ln -st /tmp/dst ${K}`, + `echo "cp a ${K}"`, `cp /tmp/a /tmp/b # ${S}`, `history | grep "cp .* ${K}"`, `touch -r ${K} /tmp/f`, `touch -cr ${K} /tmp/f`, `truncate -cr ${K} /tmp/f`, `ln -s ${K}`, `rsync ${S}/`, + `rsync -a /tmp/src/ /tmp/dst --exclude-from ${S}/excl`, `rsync -a /tmp/src/ /tmp/dst --password-file ${K}`, `tar -C ${S} -czf /tmp/s.tgz .`, `tar -xf ${S}/a.tar -C /tmp/x`, + `find /tmp/x -name a -exec cp ${K} {} \\;`, `find ${S} -name lock -exec rm -f /tmp/marker \\;`, `find ${S} -type f -exec touch -r {} /tmp/stamp \\;`, + `sed -i -f ${S}/s.sed /tmp/out.txt`, `sed -n -e -i ${K}`, `command -v rm ${K}`, `sudo -l rm ${K}`, `echo then rm ${K}`, `[ -f ${K} ] && rm /tmp/x`, `time -p cat ${K}`, + `cat <<'EOF' > /tmp/note\nrun: echo x > ${K}\nEOF`, `git commit -m "$(cat <<'EOF'\nfix: stop writing > ${F}\nEOF\n)"`, `git commit -m "He said \\"hi" -m "; rm ${K}"`, + `truncate -o -r ${K} /tmp/x`, `shred --random-source ${K} /tmp/x`, `cat <<'EOF'\n$(rm ${K})\nEOF`, `find ${K} -newer ${K} -exec cat {} \\;`, + `rsync -n -a /tmp/src/ ${S}/`, `rsync --dry-run -av /tmp/src/ ${S}/`, `find ${S} -type f -exec cp {} ~/bk{} \\;`, `echo \\$(rm ${K})`, `perl -ne print ${K} -i`, `tar -xOf /tmp/a.tar -C ${S}`, + `cat < ${H}/.keyboard`, `echo x > ${H}/.key.bak`, `echo x > ${H}/states/x`, `echo x > ${H}/stateful`, +]; + +const writes: readonly string[] = [ + `echo x > ${K}`, `echo x >> ${F}`, `echo x &> ${K}`, `cp /tmp/a ${K} 2>/dev/null`, `cp /tmp/a ${H}//state/x`, `mv /tmp/x ${H}/./state`, `mv ${S} /tmp/x`, `cp -t ${S} /tmp/a`, `cp -rt ${S} /tmp/a`, + `ln -sf /tmp/x ${K}`, `rsync -a /tmp/x ${S}/`, `install /tmp/x ${K}`, `touch ${K}`, `truncate -s0 ${K}`, `rm -rf ${S}`, `rm -r ${S}`, `echo x | tee out.txt ${K}`, `tar -xf /tmp/t -C ${S}`, + `unzip /tmp/z -d ${S}`, `dd if=/tmp/a of=${K}`, `sed -i s/a/b/ ${K}`, `sed -I .bak s/a/b/ ${K}`, `sed -i --expression=s/a/b/ ${K}`, `perl -pi.bak -e 1 ${K}`, `perl -0pi -e 1 ${K}`, + `find /tmp -exec cp {} ${S} \\;`, `find ${S} -delete`, `find -x ${S} -delete`, `find ${S} -type f -exec rm {} +`, `echo a | xargs cp -t ${S}`, `xargs -J % cp % ${S}/ < /tmp/l`, + `nice -n 10 rm ${K}`, `env -u HOME rm ${K}`, `{ cp /tmp/a ${K}; }`, `if true; then mv /tmp/a ${K}; fi`, `cp /tmp/a ${H}/'.key'`, `cp /tmp/a "${K}"`, `cp /tmp/a ${H}/\\.key`, + `echo $(cp /tmp/a ${K})`, `cp /tmp/a $(dirname $(mktemp))/x ${K}`, `exec 3>${K}`, + `find ${S} -type f -exec cat {} \\; -exec rm {} \\;`, `find ${S} -type f -exec cp {} {}.bak \\;`, `truncate -s 1 -o ${K}`, `rsync -a /tmp/x ${S}/`, +]; + +test("reads and look-alikes of the receipt store stay allowed", () => { + const blocked = reads.filter((c) => protectedPathGuard({ tool: "Bash", command: c }) !== null); + expect(blocked).toEqual([]); +}); + +test("real writes to the receipt store are blocked", () => { + const allowed = writes.filter((c) => protectedPathGuard({ tool: "Bash", command: c }) === null); + expect(allowed).toEqual([]); +}); + +test("Write/Edit: `//`, `/./`, `/../` and case variants cannot hide the store; look-alikes stay allowed", () => { + for (const tool of ["Write", "Edit"]) { + for (const p of [`${H}//state/x`, `${H}/./.key`, `/h//.fuse-harness//.key`, `${H}/state/../.key`, "/Users/u/.FUSE-HARNESS/.KEY", "/Users/John Smith/.fuse-harness/state/x"]) { + expect(protectedPathGuard({ tool, filePath: p })?.kind, `${tool} ${p}`).toBe("block"); + } + for (const p of [`${H}/.keyboard`, `${H}/.key.bak`, `${H}/states/x`, `${H}/cache/x`]) expect(protectedPathGuard({ tool, filePath: p }), `${tool} ${p}`).toBeNull(); + } +}); diff --git a/test/receipt-tamper-data.test.ts b/test/receipt-tamper-data.test.ts new file mode 100644 index 0000000..d9a5c3b --- /dev/null +++ b/test/receipt-tamper-data.test.ts @@ -0,0 +1,60 @@ +/** + * Data-layer tamper attempts on the HMAC-signed track journal / snapshot (the store verification receipts live in). + * Runs `helpers/receipt-tamper-probe.ts` in a subprocess with an isolated HOME and pins, per attempt, whether the + * forged/altered receipt is still accepted by the TaskCompleted gate's read (`freshReceiptFromFile`). + */ +import { expect, test } from "bun:test"; +import { copyFileSync, mkdirSync, mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const probe = join(import.meta.dir, "helpers", "receipt-tamper-probe.ts"); + +/** Run the probe in a subprocess with HOME isolated on its own command line (Bun caches `os.homedir()`). */ +function probe2(home: string, extra: Record): Record { + const r = Bun.spawnSync(["bun", probe], { env: { PATH: process.env.PATH ?? "", HOME: home, PROBE_DIR: join(home, "probe"), ...extra }, stdout: "pipe", stderr: "pipe" }); + if (r.exitCode !== 0) throw new Error(`probe failed: ${r.stderr.toString()}`); + return JSON.parse(r.stdout.toString()) as Record; +} + +test("CI re-verification: exported artefacts alone verify nothing; only the session machine's secret key makes them verify", () => { + const session = mkdtempSync(join(tmpdir(), "fh-rt-ci-session-")); + const file = (probe2(session, { PROBE_MODE: "export" }) as { file: string }).file; + // Fresh HOME, artefacts only (track-export.json + .log): every line fails the MAC under the verifier's own, freshly minted key. + const ci = mkdtempSync(join(tmpdir(), "fh-rt-ci-fresh-")); + expect(probe2(ci, { PROBE_MODE: "verify", PROBE_FILE: file })).toEqual({ keyBefore: false, events: 0, accepted: false, keyMintedByVerifier: true }); + // The same artefacts verify only once the SESSION's .key is copied over: HMAC is symmetric, so the verifier holds forging power too. + const withKey = mkdtempSync(join(tmpdir(), "fh-rt-ci-key-")); + mkdirSync(join(withKey, ".fuse-harness"), { recursive: true }); + copyFileSync(join(session, ".fuse-harness", ".key"), join(withKey, ".fuse-harness", ".key")); + expect(probe2(withKey, { PROBE_MODE: "verify", PROBE_FILE: file })).toEqual({ keyBefore: true, events: 1, accepted: true, keyMintedByVerifier: false }); +}); + +test("signed journal/snapshot: which tamper attempts are rejected, which are not", () => { + const o = probe2(mkdtempSync(join(tmpdir(), "fh-rt-data-home-")), {}); + console.log(JSON.stringify(o, null, 2)); + // control + expect(o.control_honest).toBe(true); + // STOPPED by the per-line / snapshot MAC (integrity.ts computeMac, track-compact.ts:parseEvents "fail-closed per line", integrity.ts verifyTrack) + expect(o.edit_line_without_resign).toBe(false); + expect(o.forge_bad_mac).toBe(false); + expect(o.forge_wrong_key).toBe(false); + expect(o.restamp_stale_line).toBe(false); + expect(o.snapshot_edit_without_resign).toBe(false); + expect(o.snapshot_delete_loses_receipts).toBe(false); + expect(o.after_key_swap_old_lines_valid).toBe(false); + // STOPPED by the freshness window (receipts.ts freshPassingReceipt cutoff) and, since the 0.1.124 hash chain (track-chain/track-verify), by chain breaks + expect(o.replay_stale_line).toBe(false); + expect(o.duplicate_lines_counted_once).toBe(false); // a duplicated line breaks the chain: the whole receipt is rejected (was: deduped by nonce) + expect(o.reorder_changes_verdict).toBe(true); // a reordered journal no longer verifies (was: order-independent) + // NOT STOPPED: documented threat model (integrity.ts header: "the machine key is readable by the same agent process") + expect(o.forge_with_read_key).toBe(true); + expect(o.after_key_swap_attacker_line_valid).toBe(true); + expect(o.key_mode_octal).toBe("600"); + // STOPPED since 0.1.124: the MAC binds the session id, a sequence number and the previous line's MAC (cross-session replay fails closed) + expect(o.replay_into_other_session).toBe(false); + // NOT re-measured by the probe (its `detected` field is a constant) and unchanged by the 0.1.124 fix: + expect(o.snapshot_rollback_to_older_valid).toBe(true); + expect(o.truncate_drops_failing_line).toEqual({ eventsBefore: 2, eventsAfter: 1, detected: false }); + expect(o.truncate_to_empty_receipt_survives).toBe(false); // deleting everything only ever loses proof (fail-closed for the receipt gate) +}); diff --git a/test/receipt-tamper-guards.test.ts b/test/receipt-tamper-guards.test.ts new file mode 100644 index 0000000..ca33982 --- /dev/null +++ b/test/receipt-tamper-guards.test.ts @@ -0,0 +1,126 @@ +/** + * Tamper attempts on the verification-receipt store, made the way an agent would: through the REAL hook + * pipeline (`handleHook`, PreToolUse) with the tool a model has (Write / Edit / Bash). The store is + * `/.fuse-harness/state//track-.{json,log}`; the HMAC key is `/.fuse-harness/.key`. + * Each row pins what the harness does TODAY (characterisation): "deny"/"ask" = stopped, "allow" = nothing stops it. + */ +import { expect, test } from "bun:test"; +import { randomUUID } from "node:crypto"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { handleHook } from "../src/runtime/handle"; +import { fuseHarnessHome } from "../src/runtime/home-state"; +import { projectHash } from "../src/runtime/paths"; + +type Verdict = { decision: string; title: string }; + +/** + * Run one PreToolUse call through the real hook pipeline and reduce its output to a decision. + * @returns `permissionDecision` ("allow" when the hook printed nothing) and the first line of the reason. + */ +async function verdict(tool: string, input: Record, cwd: string, home: string): Promise { + const payload = { hook_event_name: "PreToolUse", session_id: `rt-${randomUUID()}`, tool_use_id: randomUUID(), cwd, tool_name: tool, tool_input: input }; + const { stdout } = await handleHook("claude-code", payload, { now: 1000, cwd, home }); + if (!stdout) return { decision: "allow", title: "" }; + const out = (JSON.parse(stdout) as { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string } }).hookSpecificOutput ?? {}; + return { decision: out.permissionDecision ?? "allow", title: (out.permissionDecisionReason ?? "").split("\n")[0] ?? "" }; +} + +const cwd = mkdtempSync(join(tmpdir(), "fh-rt-cwd-")); +const home = mkdtempSync(join(tmpdir(), "fh-rt-home-")); +const base = join(fuseHarnessHome(home), "state", projectHash(cwd)); +const json = join(base, "track-victim.json"); +const log = join(base, "track-victim.log"); +const key = join(fuseHarnessHome(home), ".key"); +const forged = '{"v":1,"field":"receipts","op":"append","value":{"kind":"test","tool":"bun test","exitCode":0,"pass":9,"fail":0,"ts":1},"ts":1,"nonce":"aa","mac":"00"}'; + +/** [label, tool, input, expected decision]. */ +const attempts: ReadonlyArray, string]> = [ + ["Write: overwrite the track snapshot", "Write", { file_path: json, content: "{}" }, "deny"], + ["Write: overwrite the journal log", "Write", { file_path: log, content: forged }, "deny"], + ["Edit: patch a line of the journal log", "Edit", { file_path: log, old_string: '"exitCode":1', new_string: '"exitCode":0' }, "deny"], + ["Write: replace the HMAC key", "Write", { file_path: key, content: "attackerkey" }, "deny"], + ["Bash: append a line to the journal (>>)", "Bash", { command: `echo '${forged}' >> ${log}` }, "deny"], + ["Bash: truncate the journal (>)", "Bash", { command: `: > ${log}` }, "deny"], + ["Bash: mv a forged dir onto the state dir itself", "Bash", { command: `mv /tmp/forged ${join(fuseHarnessHome(home), "state")}` }, "deny"], + ["control: Write to a look-alike .keyboard path", "Write", { file_path: join(fuseHarnessHome(home), ".keyboard", "x.txt"), content: "x" }, "allow"], + ["control: Write to a look-alike .key.bak path", "Write", { file_path: `${key}.bak`, content: "x" }, "allow"], + ["Bash: tee the key with a glued operator", "Bash", { command: `echo k | tee ${key};true` }, "deny"], + ["Bash: tee the key glued to &&", "Bash", { command: `echo k | tee ${key}&&true` }, "deny"], + ["Bash: mv onto the state dir in a subshell", "Bash", { command: `(mv /tmp/forged ${join(fuseHarnessHome(home), "state")})` }, "deny"], + ["Write: case-variant path (case-insensitive FS)", "Write", { file_path: join(fuseHarnessHome(home), "State", "h", "track-x.log").replace(".fuse-harness", ".FUSE-HARNESS"), content: forged }, "deny"], + ["Bash: cp onto the key with a trailing redirect", "Bash", { command: `cp /tmp/a ${key} 2>/dev/null` }, "deny"], + ["Bash: mv onto the state dir, multi-line", "Bash", { command: `mv /tmp/forged ${join(fuseHarnessHome(home), "state")}\ntrue` }, "deny"], + ["Bash: tee with the protected file as second operand", "Bash", { command: `echo k | tee out.txt ${key}` }, "deny"], + ["Bash: &> onto the journal", "Bash", { command: `echo k &> ${log}` }, "deny"], + ["Bash: cp inside backticks onto the key", "Bash", { command: `echo \`cp /tmp/a ${key}\`` }, "deny"], + ["Bash: cp -t into the state dir", "Bash", { command: `cp -t ${join(fuseHarnessHome(home), "state")} /tmp/a` }, "deny"], + ["control: cp FROM the key to /tmp (read source)", "Bash", { command: `cp ${key} /tmp/copy 2>/dev/null` }, "allow"], + ["control: commit message heredoc that mentions cp onto the key", "Bash", { command: `git commit -m "$(cat <<'EOF'\nfix: deny cp into ${key}\nEOF\n)"` }, "ask"], // "ask" = the generic commit/heredoc confirm; NOT the protected-path deny + ["control: grep tee ", "Bash", { command: `grep tee foo ${key}` }, "allow"], + ["control: cp -t /tmp/bk is only a read of the key", "Bash", { command: `cp -t /tmp/bk ${key}` }, "allow"], + ["control: grep -rn mv ", "Bash", { command: `grep -rn mv ${join(fuseHarnessHome(home), "state")}` }, "allow"], + ["control: rg tee ", "Bash", { command: `rg tee ${join(fuseHarnessHome(home), "state")}` }, "allow"], + ["control: echo text mentioning cp onto the key", "Bash", { command: `echo "cp a ${key}"` }, "allow"], + ["control: history | grep cp .* ", "Bash", { command: `history | grep "cp .* ${key}"` }, "allow"], + ["Write: // inside the path", "Write", { file_path: `${fuseHarnessHome(home)}//state/x`, content: "x" }, "deny"], + ["Write: /./ inside the path", "Write", { file_path: `${fuseHarnessHome(home)}/./.key`, content: "x" }, "deny"], + ["Write: leading // and doubled slash before the key", "Write", { file_path: `/${fuseHarnessHome(home)}//.key`, content: "x" }, "deny"], + ["Bash: cp onto a // path", "Bash", { command: `cp /tmp/a ${fuseHarnessHome(home)}//state/x` }, "deny"], + ["Bash: mv onto a /./ path", "Bash", { command: `mv /tmp/x ${fuseHarnessHome(home)}/./state` }, "deny"], + ["hole: ln -sf onto the key", "Bash", { command: `ln -sf /tmp/x ${key}` }, "deny"], + ["hole: rsync into the state dir", "Bash", { command: `rsync -a /tmp/x ${join(fuseHarnessHome(home), "state")}/` }, "deny"], + ["hole: install onto the key", "Bash", { command: `install /tmp/x ${key}` }, "deny"], + ["hole: touch the key", "Bash", { command: `touch ${key}` }, "deny"], + ["hole: truncate the key", "Bash", { command: `truncate -s0 ${key}` }, "deny"], + ["hole: rm -rf the state dir", "Bash", { command: `rm -rf ${join(fuseHarnessHome(home), "state")}` }, "deny"], + ["hole: mv the state dir away", "Bash", { command: `mv ${join(fuseHarnessHome(home), "state")} /tmp/x` }, "deny"], + ["hole: tar -C into the state dir", "Bash", { command: `tar -xf /tmp/t -C ${join(fuseHarnessHome(home), "state")}` }, "deny"], + ["hole: find -exec cp into the state dir", "Bash", { command: `find /tmp -exec cp {} ${join(fuseHarnessHome(home), "state")} \\;` }, "deny"], + ["hole: xargs cp -t into the state dir", "Bash", { command: `echo a | xargs cp -t ${join(fuseHarnessHome(home), "state")}` }, "deny"], + ["hole: partially quoted key name", "Bash", { command: `cp /tmp/a ${fuseHarnessHome(home)}/'.key'` }, "deny"], + ["control: touch -r (a read of the key)", "Bash", { command: `touch -r ${key} /tmp/f` }, "allow"], + ["control: ln -s /tmp/l (a read of the key)", "Bash", { command: `ln -s ${key} /tmp/l` }, "allow"], + ["control: rsync / out (a read)", "Bash", { command: `rsync -a ${join(fuseHarnessHome(home), "state")}/ /tmp/bk/` }, "allow"], + ["hole: rm -r (flag, not a value option)", "Bash", { command: `rm -r ${join(fuseHarnessHome(home), "state")}` }, "deny"], + ["hole: find -exec rm", "Bash", { command: `find ${join(fuseHarnessHome(home), "state")} -type f -exec rm {} +` }, "deny"], // securityGuard's generic rm ask used to hide this deny (chain order); runGuards now lets the receipt-store deny win over an ask + ["hole: find -delete", "Bash", { command: `find ${join(fuseHarnessHome(home), "state")} -delete` }, "deny"], + ["control: tar -C -czf (a backup, a read)", "Bash", { command: `tar -C ${join(fuseHarnessHome(home), "state")} -czf /tmp/s.tgz .` }, "allow"], + ["control: ln -s with one operand", "Bash", { command: `ln -s ${key}` }, "allow"], + ["control: touch -cr /tmp/f (bundled reference)", "Bash", { command: `touch -cr ${key} /tmp/f` }, "allow"], + ["control: find -exec cp {}", "Bash", { command: `find /tmp/x -name a -exec cp ${key} {} \\;` }, "allow"], + ["control: sed -i -f /s.sed (script file is read; the pipeline's generic sed -i rule denies it, protected-path does not)", "Bash", { command: `sed -i -f ${join(fuseHarnessHome(home), "state")}/s.sed /tmp/out.txt` }, "deny"], + ["control: escaped quotes in a commit message", "Bash", { command: `git commit -m "He said \\"hi" -m "; rm ${key}"` }, "ask"], // "ask" = generic commit confirm, never the protected-path deny + ["hole: rm of an ABSOLUTE key path after an escaped space (a home containing a space; the guard matches it by design)", "Bash", { command: `rm /tmp/x\\ ${key}` }, "deny"], + ["control: rm of a path whose escaped-space prefix ends in a literal ~ (generic rm confirm only, not the protected-path deny)", "Bash", { command: "rm /tmp/x\\ ~/.fuse-harness/.key" }, "ask"], + ["limit: cd into the harness home then a relative redirect (bash-write asks)", "Bash", { command: `cd ${fuseHarnessHome(home)} && echo x > .key` }, "ask"], + ["limit: unresolvable variable path (no new rule)", "Bash", { command: `D=${fuseHarnessHome(home)}; cp /tmp/a $D/.key` }, "allow"], + ["control: perl -M reading the journal is not an in-place edit", "Bash", { command: `perl -Mstrict -e 'print 1' ${log}` }, "allow"], + ["control: cp FROM the key to a $(mktemp) destination", "Bash", { command: `cp ${key} $(mktemp)` }, "allow"], + ["Bash: perl -pi.bak on the journal", "Bash", { command: `perl -pi.bak -e 's/a/b/' ${log}` }, "deny"], + ["control: grep of the journal", "Bash", { command: `grep -rn exitCode ${log}` }, "allow"], + ["Bash: sed -i the key", "Bash", { command: `sed -i '' 's/a/b/' ${key}` }, "deny"], + ["control: Bash read of the journal into another file", "Bash", { command: `cat ${log} > out.txt` }, "ask"], + ["Bash: sed -i the journal", "Bash", { command: `sed -i '' 's/"exitCode":1/"exitCode":0/' ${log}` }, "deny"], + ["Bash: replace the key (>)", "Bash", { command: `echo attackerkey > ${key}` }, "deny"], + ["Bash: READ the HMAC key (cat)", "Bash", { command: `cat ${key}` }, "allow"], + ["Bash: READ the journal (cat)", "Bash", { command: `cat ${log}` }, "allow"], + ["Read tool: the HMAC key", "Read", { file_path: key }, "allow"], + ["Bash: python re-sign with the key", "Bash", { command: `python3 -c "import hmac,hashlib;k=open('${key}').read().strip();print(hmac.new(k.encode(),b'1:x',hashlib.sha256).hexdigest())"` }, "allow"], + ["control: Write to the protected sessions dir", "Write", { file_path: join(fuseHarnessHome(home), "cache", "sessions", "session-x.json"), content: "{}" }, "deny"], + // GAP (read only): SAFE_PREFIXES ("cat ") returns in bash-write.ts before the SESSION_STATE_FRAGMENT block is reached. + ["GAP: Bash cat of the sessions dir", "Bash", { command: `cat ${join(fuseHarnessHome(home), "cache", "sessions", "session-x.json")}` }, "allow"], +]; + +test("receipt-store tamper attempts: what the hook pipeline does today", async () => { + const rows: string[] = [], got: string[] = [], want: string[] = []; + for (const [label, tool, input, expected] of attempts) { + const v = await verdict(tool, input, cwd, home); + rows.push(`${v.decision.padEnd(5)} | ${label} | ${v.title}`); + got.push(`${label}: ${v.decision}`); + want.push(`${label}: ${expected}`); + } + console.log(`\n${rows.join("\n")}`); + expect(got).toEqual(want); +}); diff --git a/test/receipt-tamper-homes.test.ts b/test/receipt-tamper-homes.test.ts new file mode 100644 index 0000000..6683c98 --- /dev/null +++ b/test/receipt-tamper-homes.test.ts @@ -0,0 +1,93 @@ +/** + * The receipt-store / HMAC-key deny must not depend on WHERE the home directory lives. `securityGuard` runs before + * `protectedPathGuard`: its generic `rm` ask used to hide the deny everywhere except under `/var/...` (where the + * unrelated system-directory block fired by accident), so `rm -rf /.fuse-harness/state` was `ask` on Linux + * (`/tmp`, `/home/u`, `/root`) and on macOS under `/private/tmp` or a real `/Users/u`. A guard's ask must never hide + * that deny; and no command outside the state dir / key may change verdict (controls stay `ask`). + */ +import { expect, test } from "bun:test"; +import { randomUUID } from "node:crypto"; +import { mkdtempSync, mkdirSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { handleHook } from "../src/runtime/handle"; + +const ids = ["claude-code", "codex", "cursor", "kimi"] as const; +type Id = (typeof ids)[number]; + +/** Host-shaped hook payload for one Bash command. */ +function payload(id: Id, command: string, cwd: string): Record { + const session_id = `rt-homes-${id}-${randomUUID()}`; + if (id === "cursor") return { hook_event_name: "beforeShellExecution", session_id, command, cwd }; + return { hook_event_name: "PreToolUse", session_id, tool_use_id: randomUUID(), cwd, tool_name: "Bash", tool_input: { command } }; +} + +/** Permission decision from the host-specific hook stdout; empty stdout means allow. */ +async function decide(id: Id, command: string, cwd: string, home: string): Promise { + const { stdout } = await handleHook(id, payload(id, command, cwd), { now: 1000, cwd, home }); + if (!stdout) return "allow"; + const out = JSON.parse(stdout) as { permission?: string; hookSpecificOutput?: { permissionDecision?: string } }; + return id === "cursor" ? out.permission ?? "allow" : out.hookSpecificOutput?.permissionDecision ?? "allow"; +} + +const sandbox = mkdtempSync(join(tmpdir(), "fh-rt-homes-")); +const real = join(sandbox, "real"); +const link = join(sandbox, "link"); +mkdirSync(real); +symlinkSync(real, link); +const cwd = join(sandbox, "proj"); +mkdirSync(cwd); + +/** Home directories: Linux and macOS spellings of a temp or user home, plus a symlinked one. */ +const homes: readonly string[] = [ + "/tmp/fh-x", "/private/tmp/fh-x", "/var/tmp/fh-x", "/var/folders/ab/cd/T/fh-x", "/private/var/folders/ab/cd/T/fh-x", + "/home/u", "/Users/u", "/root", "/opt/x", real, link, +]; +const KEY = ".k" + "ey"; + +/** Commands that destroy or replace the state dir / key, for one home. */ +const hits = (h: string): readonly string[] => [ + `rm -rf ${h}/.fuse-harness/state`, `rm -r ${h}/.fuse-harness/state`, `rm -rf ${h}/.fuse-harness/state/ab/t.json`, + `rm ${h}/.fuse-harness/${KEY}`, `rm -f ${h}/.fuse-harness/${KEY}`, `unlink ${h}/.fuse-harness/${KEY}`, + `find ${h}/.fuse-harness/state -delete`, `find ${h}/.fuse-harness/state -type f -exec rm {} +`, + `mv ${h}/.fuse-harness/state /tmp/gone`, `rm -rf "${h}/.fuse-harness/state"`, `sudo rm -rf ${h}/.fuse-harness/state`, + `cd /tmp && rm -rf ${h}/.fuse-harness/state`, `(rm -rf ${h}/.fuse-harness/state)`, + `rm -rf ${h}//.fuse-harness/./state`, `rm -rf ${h}/.fuse-harness/x/../state`, +]; + +/** Commands near the protected paths that are NOT writes to them: their verdict (the generic rm ask) must not change. */ +const controls = (h: string): readonly string[] => [ + `rm -rf ${h}/.fuse-harness/cache/x`, `rm -rf ${h}/.fuse-harness/states`, `rm ${h}/.fuse-harness/${KEY}board`, + `rm ${h}/.fuse-harness/${KEY}.bak`, `rm -rf ${h}/state`, `rm -rf ${h}/x.fuse-harness/state`, `rm -rf ${h}/.fuse-harnessx/state`, +]; + +test("rm of the state dir / key is denied for every home spelling on claude-code", async () => { + const bad: string[] = []; + for (const h of homes) for (const c of hits(h)) { + const d = await decide("claude-code", c, cwd, h); + if (d !== "deny") bad.push(`${d}: ${c}`); + } + expect(bad).toEqual([]); +}, 60_000); + +test("the same deny holds on codex, cursor and kimi (no CONFIRM code can lift it)", async () => { + const bad: string[] = []; + for (const h of ["/tmp/fh-x", "/home/u", "/Users/u"]) for (const c of hits(h)) for (const id of ids.slice(1)) { + const { stdout } = await handleHook(id, payload(id, c, cwd), { now: 1000, cwd, home: h }); + if (!stdout || /CONFIRM/.test(stdout)) bad.push(`${id}: ${c}`); + } + expect(bad).toEqual([]); +}, 60_000); + +test("limit: a quoted `sh -c` payload is not analysed by the protected-path rule, so the generic rm ask stands (a human still confirms)", async () => { + expect(await decide("claude-code", `sh -c 'rm -rf /home/u/.fuse-harness/state'`, cwd, "/home/u")).toBe("ask"); +}); + +test("controls outside the protected paths keep the generic rm ask (no new false block)", async () => { + const bad: string[] = []; + for (const h of ["/tmp/fh-x", "/private/tmp/fh-x", "/home/u", "/Users/u"]) for (const c of controls(h)) { + const d = await decide("claude-code", c, cwd, h); + if (d !== "ask") bad.push(`${d}: ${c}`); + } + expect(bad).toEqual([]); +}, 60_000); diff --git a/test/receipt-tamper-hosts.test.ts b/test/receipt-tamper-hosts.test.ts new file mode 100644 index 0000000..255ae27 --- /dev/null +++ b/test/receipt-tamper-hosts.test.ts @@ -0,0 +1,49 @@ +/** + * Host parity for the receipt-store / HMAC-key protection: the same Bash write is denied and the same read is allowed on + * Claude Code, Codex, Kimi and Cursor (shared `runGuards` chain). `ask` is downgraded to deny on every host but Claude Code. + */ +import { expect, test } from "bun:test"; +import { randomUUID } from "node:crypto"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { handleHook } from "../src/runtime/handle"; +import { fuseHarnessHome } from "../src/runtime/home-state"; + +const ids = ["claude-code", "codex", "cursor", "kimi"] as const; +type Id = (typeof ids)[number]; + +/** Host-shaped hook payload for one Bash command (Cursor `beforeShellExecution`, others `PreToolUse`). */ +function payload(id: Id, command: string, cwd: string): Record { + const session_id = `rt-hosts-${id}-${randomUUID()}`; + if (id === "cursor") return { hook_event_name: "beforeShellExecution", session_id, command, cwd }; + return { hook_event_name: "PreToolUse", session_id, tool_use_id: randomUUID(), cwd, tool_name: "Bash", tool_input: { command } }; +} + +/** Permission decision from the host-specific hook stdout; empty stdout means allow. */ +function decision(id: Id, stdout: string): string { + if (!stdout) return "allow"; + const parsed = JSON.parse(stdout) as { permission?: string; hookSpecificOutput?: { permissionDecision?: string } }; + return id === "cursor" ? parsed.permission ?? "allow" : parsed.hookSpecificOutput?.permissionDecision ?? "allow"; +} + +test("receipt-store protection gives the same verdict on every host", async () => { + const cwd = mkdtempSync(join(tmpdir(), "fh-rt-hosts-cwd-")); + const home = mkdtempSync(join(tmpdir(), "fh-rt-hosts-home-")); + const h = fuseHarnessHome(home); + const rows: ReadonlyArray = [ + [`echo forged >> ${h}/state/ab/track-s.log`, ["deny", "deny", "deny", "deny"]], + [`cp /tmp/a ${h}//.key 2>/dev/null`, ["deny", "deny", "deny", "deny"]], + [`ln -sf /tmp/x ${h}/.key`, ["deny", "deny", "deny", "deny"]], + [`rm -rf ${h}/state`, ["deny", "deny", "deny", "deny"]], + [`find /tmp -exec cp {} ${h}/state \\;`, ["deny", "deny", "deny", "deny"]], + [`cat ${h}/.key`, ["allow", "allow", "allow", "allow"]], + [`grep -rn mv ${h}/state`, ["allow", "allow", "allow", "allow"]], + [`cp -t /tmp ${h}/state/ab/track-s.json`, ["allow", "allow", "allow", "allow"]], + [`cd ${h} && echo x > .key`, ["ask", "deny", "deny", "deny"]], // not resolved by the protected-path guard: bash-write asks (downgraded to deny off Claude Code) + ]; + for (const [command, expected] of rows) { + const actual = await Promise.all(ids.map(async (id) => decision(id, (await handleHook(id, payload(id, command, cwd), { now: 1000, cwd, home })).stdout))); + expect(actual, command).toEqual([...expected]); + } +});