Refuse recursive reads of the closed env files and cf commands hidden behind unknown options
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Review fixes for the hook policy (Spec and Standards axes against issue 104). - cf: yargs gives an option it doesn't declare the next word as its value, so `cf --account-id x --env y deploy` reached deploy. Every word such an option could have taken is now judged as the command (cfCommandWords). - cf: cf's package installs its bin twice, as `cf` and `cloudflare`; both are judged. - cf: the last of `--dry-run`, `--dry-run=…` and `--no-dry-run` decides, and `false` or `0` after `--dry-run` turns it off, as yargs reads it. - cf: AGENTS.md's discovery steps only read, so `cli`, `schema` and `<command> --help` no longer count as deletes (`bun run ops -- schema artifacts namespaces repos delete` was refused). - Closed env files: `grep -r TOKEN .` printed the closed files' lines. A recursive grep (-r, -R, --recursive, -d recurse) is refused unless --include leaves the files out or --exclude covers them, matched as grep does (fnmatch, where `*` matches a leading dot). rg is refused only when it searches hidden and ignored files together (-uu, --hidden with --no-ignore*), since the files are both. grep's -e value and its include and exclude globs are patterns, not files read. - The closed-env-read reason now says rg and git grep skip the files, so a refused recursive grep says what to do instead. - pi: the bash input is decoded with Schema (principle 2) instead of a typeof check; .pi/** is outside lint. Reloaded through pi 1.0.4's jiti with a stand-in API: git push, cat .env.local and grep -rn blocked, git status and other tools pass. - shell.ts: the exported Simple is readonly to callers; the scan builds a mutable Building. - vcs-policy.ts: the header no longer claims a hook that cannot start blocks Claude Code (it exits 1, which Claude Code reports without blocking). - Tests: 26 rows in vcs-policy.test.ts (cf unknown options, cloudflare, dry-run settings, discovery commands, recursive grep and rg with and without include/exclude, grep -e). 21 were red by assertion first. - Gaps left advisory are listed in the issue's Comments.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+252 added−48 removed
- tests:+38 added−1 removed
- other:+214 added−47 removed
Provenance
- Commit
a3e552a- Tree
7462b58- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
db67c5b
5 files changed+252 added−48 removed
modified:.pi/extensions/vcs-policy/index.ts+23 added-19 removed
4 unmodified lines56789101112131414 unmodified lines293031323334353637383940413738394041424344434546474849505152454647484950515253545556575354555657585960616263644 unmodified lines * `decide`, and block a refused command with its reason. The types below are * the slice of pi's extension API this file uses, checked against pi 1.0.4's * `dist/core/extensions/types.d.ts`; pi itself is not a dependency here. */import { Option, Schema } from "effect";
import { Decision, decide } from "../../../scripts/hooks/lib/policy.ts";
/** pi's `ToolCallEvent`, as far as this extension reads it. */interface ToolCall {14 unmodified lines handler: (event: ToolCall) => Block | undefined ): unknown;}
/** pi's `BashToolInput`, as far as the policy reads it. */const BashInput = Schema.Struct({ command: Schema.String });
const UNREADABLE: Block = { block: true, reason: "vcs-policy could not read a shell command from this bash call, so it refuses it.",};
const vcsPolicy = (pi: PiApi) => { pi.on("tool_call", (event) => { if (event.toolName !== "bash") { return undefined; }const blockFor = (command: string): Block | undefined => { const decision = decide(command);
const { command } = event.input; return Decision.$is("Deny")(decision) ? { block: true, reason: `vcs-policy refused this command (${decision.rule}): ${decision.reason}`, } : undefined;};
if (typeof command !== "string") { return UNREADABLE; }
const decision = decide(command);
return Decision.$is("Deny")(decision) ? { block: true, reason: `vcs-policy refused this command (${decision.rule}): ${decision.reason}`, } : undefined; });const vcsPolicy = (pi: PiApi) => { pi.on("tool_call", (event) => event.toolName === "bash" ? Option.match(Schema.decodeUnknownOption(BashInput)(event.input), { onNone: () => UNREADABLE, onSome: ({ command }) => blockFor(command), }) : undefined );};
export default vcsPolicy;modified:packages/config/test/vcs-policy.test.ts+38 added-1 removed
208 unmodified lines209 ["bun run ops -- artifacts namespaces repos delete x --dry-run", "Allow"],210 ["bun run ops -- workers list", "Allow"],211 ["bun run ops -- zones purge-cache x", "delete"],212 ["bun run ops -- workers delete x --dry-run=false", "delete"],213+ // cf parses with yargs, which reads `false` after a boolean flag as its214+ // value, and the last of `--dry-run` and `--no-dry-run` wins.215+ ["bun run ops -- workers delete x --dry-run false", "delete"],216+ ["bun run ops -- workers delete x --dry-run --no-dry-run", "delete"],217+ ["bun run ops -- workers delete x --no-dry-run --dry-run", "Allow"],218+ // AGENTS.md's discovery steps only read: `cli search`, `schema <command>`219+ // and `<command> --help` (the help cf itself points to) delete nothing.220+ ['bun run ops -- cli search "delete"', "Allow"],221+ ["bun run ops -- schema artifacts namespaces repos delete", "Allow"],222+ ["bun run ops -- artifacts namespaces repos delete --help", "Allow"],223+ // cf's package installs its bin under a second name, `cloudflare`.224+ ["./node_modules/.bin/cloudflare deploy", "cf-project-command"],225+ ["bunx cloudflare workers delete x", "delete"],226 // cf's project commands are refused even as dry runs, and through varlock.227 ["cf deploy --dry-run", "cf-project-command"],228 ["cf --profile dev deploy", "cf-project-command"],229+ // An option cf doesn't declare may take the next word as its value, so230+ // any word it could have taken may be the command.231+ ["cf --account-id x --env y deploy", "cf-project-command"],232+ ["cf --account-id x workers list --name deploy", "Allow"],233 ["bunx varlock run --path infra/ -- cf deploy", "cf-project-command"],234 ["bun run verify", "Allow"],235 ["bun infra/deploy.ts --stage demo", "Allow"],236 // The closed env files, by any path, glob or redirect. Their schemas and14 unmodified lines251 ["grep -A 2 TOKEN .env", "closed-env-read"],252 ["grep -f .env other.txt", "closed-env-read"],253 ["cp .env /tmp/x", "closed-env-read"],254 ["set -a; . ./.env; set +a", "closed-env-read"],255+ // A recursive grep reads every file under its paths, the closed ones too,256+ // unless --include or --exclude keeps them out. A pattern is not a file.257+ ["grep -rn TOKEN .", "closed-env-read"],258+ ["grep -R TOKEN apps/platform", "closed-env-read"],259+ ["grep --recursive TOKEN", "closed-env-read"],260+ ["grep -d recurse TOKEN .", "closed-env-read"],261+ ["grep -rn TOKEN . --include='*'", "closed-env-read"],262+ ["grep -rn TOKEN . --exclude='*.local'", "closed-env-read"],263+ ["grep -rn TOKEN . --include='*.ts'", "Allow"],264+ ["grep -rn TOKEN . --exclude='.env*'", "Allow"],265+ ["grep -rn TOKEN . --exclude=.env --exclude='*.local'", "Allow"],266+ ["grep -rn TOKEN . --exclude={.env,.env.local,.env.*.local}", "Allow"],267+ ["grep -n -e .env .gitignore", "Allow"],268+ // rg skips hidden and git-ignored files; the closed files are both, so it269+ // reaches them only when told to search both.270+ ["rg TOKEN", "Allow"],271+ ["rg --hidden TOKEN", "Allow"],272+ ["rg -uu TOKEN", "closed-env-read"],273+ ["rg --hidden --no-ignore-vcs TOKEN", "closed-env-read"],274+ ["rg -. -u TOKEN", "closed-env-read"],275 ["bun run env:check", "Allow"],276 ])("%s → %s", (command, verdict) => {277 expect(verdictOf(command)).toBe(verdict);278 });9 unmodified lines288 expect(reasons).toStrictEqual({289 "cf-project-command":290 "cf's project commands are not our deploy tool; use infra/deploy.ts.",291 "closed-env-read":255- "Never read .env, .env.local or .env.*.local; run bun run env:check.",292+ "Never read .env, .env.local or .env.*.local, even in a recursive search (rg and git grep skip them); run bun run env:check.",293 delete: "Deleting Cloudflare resources needs the user's OK.",294 "hook-bypass":295 "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",296 push: "Pushing is the user's step; commit on the branch and stop.",139 unmodified linesmodified:scripts/hooks/lib/policy.ts+180 added-25 removed
38 unmodified lines39 export const reasons = {40 "cf-project-command":41 "cf's project commands are not our deploy tool; use infra/deploy.ts.",42 "closed-env-read":43- "Never read .env, .env.local or .env.*.local; run bun run env:check.",43+ "Never read .env, .env.local or .env.*.local, even in a recursive search (rg and git grep skip them); run bun run env:check.",44 delete: "Deleting Cloudflare resources needs the user's OK.",45 "hook-bypass":46 "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",47 push: "Pushing is the user's step; commit on the branch and stop.",163 unmodified lines211 const DESTRUCTIVE = /(?:^|-)(?:delete|destroy|purge|remove|revoke)(?:-|$)/u;212 213 // cf-project-command ----------------------------------------------------------214 215-// cf's global options that take a value.215+// cf's global options that take a value (`cf --help`, cf 1.0.0-beta.12).216 const CF = grammar("-m -z --mode --persist-to --profile --zone");217 218 const CF_PROJECT = names("build deploy dev init migrate previews");219 1 unmodified line221 ["workers", "triggers", "deploy"],222 ["workers", "versions", "create"],223 ];224 225+/** cf's commands that only read: AGENTS.md's `cli search` and `schema`. */226+const CF_DISCOVERY = names("cli schema");227+228+/**229+ * The words that may be cf's command. cf parses with yargs, which gives an230+ * option it doesn't declare the next word as its value, so each such word may231+ * be the command too: `cf --account-id x deploy`. The last word is the first232+ * one no option can have taken.233+ */234+const cfCommandWords = (args: readonly string[]): readonly string[] => {235+ const [word, next, ...rest] = args;236+237+ if (word === undefined) {238+ return [];239+ }240+241+ if (word === "--") {242+ return next === undefined ? [] : [next];243+ }244+245+ if (!word.startsWith("-") || word === "-") {246+ return [word];247+ }248+249+ if (word.includes("=") || next === undefined || next.startsWith("-")) {250+ return cfCommandWords(args.slice(1));251+ }252+253+ const after = cfCommandWords(rest);254+255+ return CF.values.has(word) ? after : [next, ...after];256+};257+258+/** Values yargs reads as false for a boolean flag. */259+const OFF = names("0 false");260+261+const DRY_RUN = "--dry-run";262+263+const setsDryRun = (word: string) =>264+ word === DRY_RUN || word === "--no-dry-run" || word.startsWith(`${DRY_RUN}=`);265+266+/** Whether the last `--dry-run`, `--dry-run=…` or `--no-dry-run` turns it on. */267+const dryRun = (args: readonly string[]): boolean => {268+ const end = args.indexOf("--");269+ const flags = end === -1 ? args : args.slice(0, end);270+ const last = flags.findLastIndex(setsDryRun);271+ const word = flags[last] ?? "--no-dry-run";272+273+ if (word === "--no-dry-run") {274+ return false;275+ }276+277+ return !OFF.has(278+ word === DRY_RUN ? (flags[last + 1] ?? "") : word.slice(DRY_RUN.length + 1)279+ );280+};281+282 const judgeCf = (args: readonly string[]): Verdict => {283 const parsed = parse(args, CF, true);227- const [first = "", second = ""] = parsed.operands;228- // An option cf doesn't declare may take the next word as its value.229- const optionFirst = args[0]?.startsWith("-") === true;284+ const commands = cfCommandWords(args);285+ const [command = ""] = commands;286 287+ if (commands.length === 1 && CF_DISCOVERY.has(command)) {288+ return Option.none();289+ }290+291 if (232- CF_PROJECT.has(first) ||233- (optionFirst && CF_PROJECT.has(second)) ||292+ commands.some((word) => CF_PROJECT.has(word)) ||293 CF_PROJECT_SEQUENCES.some((sequence) => contains(parsed.operands, sequence))294 ) {295 return Option.some("cf-project-command");296 }297 239- const dryRun =240- parsed.options.includes("--dry-run") &&241- parsed.values.every(242- ([option, value]) => option !== "--dry-run" || value !== "false"243- );298+ // `<command> --help` prints the command's help, as cf's own help suggests.299+ const executes = !parsed.options.includes("--help") && !dryRun(args);300 301 return breaks(302 "delete",247- !dryRun && parsed.operands.some((word) => DESTRUCTIVE.test(word))303+ executes && parsed.operands.some((word) => DESTRUCTIVE.test(word))304 );305 };306 307 // closed-env-read -------------------------------------------------------------308 253-/** One name for each closed shape, for testing globs against. */254-const CLOSED_SAMPLES = [".env", ".env.local", ".env.development.local"];309+/**310+ * Closed names to test globs against: one of each fixed name and a few of the311+ * `.env.*.local` shape, so a glob covers the shape only if it matches them all.312+ */313+const CLOSED_SAMPLES = [314+ ".env",315+ ".env.local",316+ ".env.development.local",317+ ".env.production.local",318+ ".env.test.local",319+];320 321 const isClosedName = (name: string) =>322 name === ".env" || name === ".env.local" || /^\.env\..+\.local$/u.test(name);323 13 unmodified lines337 return REGEXP_SPECIAL.test(part) ? `\\${part}` : part;338 };339 340 /**276- * Whether a shell glob could match `name`. A bracket matches any one277- * character, which only widens the match; a leading `*` never matches a278- * dotfile, as in a shell without `dotglob`.341+ * Whether a glob could match `name`, as fnmatch does without `FNM_PERIOD`. A342+ * bracket matches any one character, which only widens the match.343 */280-const globMatches = (pattern: string, name: string) =>281- pattern.startsWith(".") &&344+const fnmatch = (pattern: string, name: string) =>345 new RegExp(346 `^${pattern.replaceAll(/\[[^\]]*\]|[\s\S]/gu, globPart)}$`,347 "u"348 ).test(name);349 350+/**351+ * Whether a shell glob could match the dotfile `name`: a leading `*` never352+ * matches one, as in a shell without `dotglob`.353+ */354+const globMatches = (pattern: string, name: string) =>355+ pattern.startsWith(".") && fnmatch(pattern, name);356+357 /** `a{b,c}d` → `abd`, `acd`, as a shell expands braces. */358 const braces = (word: string): readonly string[] => {359 const match = /\{(?<options>[^{}]*,[^{}]*)\}/u.exec(word);360 20 unmodified lines381 : isClosedName(name);382 })383 );384 385+/** The globs one option names, braces expanded: `--include={a,b}`. */386+const globsOf = (parsed: Parsed, option: string) =>387+ parsed.values.flatMap(([name, value]) =>388+ name === option ? braces(value) : []389+ );390+391+const GREP_RECURSIVE = names("-R -r --dereference-recursive --recursive");392+393 /**394+ * `grep -r` reads every file under its paths, the closed ones too, unless395+ * `--include` leaves them out or `--exclude` covers them (grep matches both396+ * against the file's name with fnmatch, so `*` matches a leading dot).397+ */398+const grepReachesClosed = (parsed: Parsed) => {399+ const recursive =400+ parsed.options.some((option) => GREP_RECURSIVE.has(option)) ||401+ parsed.values.some(402+ ([option, value]) =>403+ (option === "-d" || option === "--directories") && value === "recurse"404+ );405+406+ const includes = globsOf(parsed, "--include");407+ const excludes = globsOf(parsed, "--exclude");408+409+ return (410+ recursive &&411+ CLOSED_SAMPLES.some(412+ (sample) =>413+ (includes.length === 0 ||414+ includes.some((glob) => fnmatch(glob, sample))) &&415+ !excludes.some((glob) => fnmatch(glob, sample))416+ )417+ );418+};419+420+const RG_HIDDEN = names("-. --hidden");421+422+const RG_IGNORED = names("--no-ignore --no-ignore-parent --no-ignore-vcs");423+424+/**425+ * rg skips hidden files and the files .gitignore names, and the closed files426+ * are both, so it reaches them only when told to search both: `-uu`, or427+ * `--hidden` with `--no-ignore`.428+ */429+const rgReachesClosed = (parsed: Parsed) => {430+ const unrestricted = parsed.options.filter(431+ (option) => option === "-u" || option === "--unrestricted"432+ ).length;433+434+ return (435+ (unrestricted >= 2 ||436+ parsed.options.some((option) => RG_HIDDEN.has(option))) &&437+ (unrestricted >= 1 ||438+ parsed.options.some((option) => RG_IGNORED.has(option)))439+ );440+};441+442+/**443 * A reader whose first operand is a pattern or a script, not a file, unless444 * one of `instead` supplies it.445 */446 interface PatternFirst {447 readonly grammar: Grammar;448 readonly instead: ReadonlySet<string>;449+ /** Options whose value is a pattern or a glob, never a file it reads. */450+ readonly patterns: ReadonlySet<string>;451+ /** Whether a search of whole directories can reach a closed file. */452+ readonly reachesClosed: (parsed: Parsed) => boolean;453 }454 455 const GREP: PatternFirst = {456 grammar: grammar(457 "-A -B -C -D -d -e -f -m --after-context --before-context --binary-files --context --devices --directories --exclude --exclude-dir --exclude-from --file --include --label --max-count --regexp"458 ),459 instead: names("-e -f --file --regexp"),460+ patterns: names("-e --exclude --exclude-dir --include --regexp"),461+ reachesClosed: grepReachesClosed,462 };463 464 const AWK: PatternFirst = {465 grammar: grammar(466 "-E -F -W -f -i -l -v --assign --exec --field-separator --file --include --load"467 ),468 instead: names("-E -f --exec --file"),469+ patterns: names(""),470+ reachesClosed: () => false,471 };472 473 const RG: PatternFirst = {474 grammar: grammar(475 "-A -B -C -E -M -T -d -e -f -g -j -m -r -t --after-context --before-context --color --colors --context --context-separator --encoding --engine --file --glob --iglob --ignore-file --max-columns --max-count --max-depth --max-filesize --path-separator --pre --pre-glob --regexp --replace --sort --sortr --threads --type --type-add --type-not"476 ),477 instead: names("-e -f --file --files --regexp --type-list"),478+ patterns: names("-e --regexp"),479+ reachesClosed: rgReachesClosed,480 };481 482 const SED: PatternFirst = {483 grammar: grammar("-e -f -l --expression --file --line-length", "-i"),484 instead: names("-e -f --expression --file"),485+ patterns: names(""),486+ reachesClosed: () => false,487 };488 489 const PATTERN_FIRST: ReadonlyMap<string, PatternFirst> = new Map([490 ["awk", AWK],19 unmodified lines510 const judgeRead = (program: string, args: readonly string[]): Verdict => {511 const patternFirst = PATTERN_FIRST.get(program);512 const parsed = parse(args, patternFirst?.grammar ?? NO_OPTIONS, true);513 375- const skipsFirst =376- patternFirst !== undefined &&377- !parsed.options.some((option) => patternFirst.instead.has(option));514+ if (patternFirst === undefined) {515+ return breaks(516+ "closed-env-read",517+ [...parsed.values.map(([, value]) => value), ...parsed.operands].some(518+ namesClosedEnv519+ )520+ );521+ }522 523+ const skipsFirst = !parsed.options.some((option) =>524+ patternFirst.instead.has(option)525+ );526+527 const files = [380- ...parsed.values.map(([, value]) => value),528+ ...parsed.values.flatMap(([option, value]) =>529+ patternFirst.patterns.has(option) ? [] : [value]530+ ),531 ...(skipsFirst ? parsed.operands.slice(1) : parsed.operands),532 ];533 384- return breaks("closed-env-read", files.some(namesClosedEnv));534+ return breaks(535+ "closed-env-read",536+ files.some(namesClosedEnv) || patternFirst.reachesClosed(parsed)537+ );538 };539 540 // ---------------------------------------------------------------------------541 // What actually runs: wrappers, shells and package runners.157 unmodified lines699 700 const PROGRAMS: ReadonlyMap<string, (args: readonly string[]) => Verdict> =701 new Map([702 ["cf", judgeCf],703+ // cf's package installs the same bin as `cloudflare`.704+ ["cloudflare", judgeCf],705 ["git", judgeGit],706 ["jj", judgeJj],707 ["lefthook", judgeLefthook],708 ["wrangler", judgeWrangler],87 unmodified linesmodified:scripts/hooks/lib/shell.ts+8 added-1 removed
14 unmodified lines15 * One simple command: its words after quote removal, the files it reads with16 * `<`, and the heredoc or here-string text on its stdin.17 */18 export interface Simple {19+ readonly words: readonly string[];20+ readonly reads: readonly string[];21+ readonly stdin: readonly string[];22+}23+24+/** A simple command while the scan is still reading it. */25+interface Building {26 readonly words: string[];27 readonly reads: string[];28 readonly stdin: string[];29 }106 unmodified lines136 */137 const scan = (src: string, start: number, nested: boolean): Scanned => {138 const commands: Simple[] = [];139 const heredocs: Heredoc[] = [];133- let simple: Simple = { reads: [], stdin: [], words: [] };140+ let simple: Building = { reads: [], stdin: [], words: [] };141 let word = "";142 let inWord = false;143 let quoted = false;144 let slot: Slot = "argument";306 unmodified linesmodified:scripts/hooks/vcs-policy.ts+3 added-2 removed
8 unmodified lines9 * - Claude Code, or a bare `{"command": …}`: a refusal exits 2 with its reason10 * on stderr; an allowed command exits 0 and prints nothing.11 * - Cursor: prints `{"permission": "allow" | "deny", …}` and exits 0.12 *13- * Input it cannot read, or any failure of its own, is a refusal: it fails14- * closed, so a broken hook never lets a command through.13+ * Input it cannot read, or a failure while it judges, is a refusal: it fails14+ * closed. A hook that cannot start at all (no `bun install` yet) exits 1,15+ * which Cursor's `failClosed` blocks and Claude Code reports without blocking.16 */17 import { BunRuntime, BunServices } from "@effect/platform-bun";18 import {19 Data,120 unmodified lines