From d02396e82b8b094010522c94b8130d6098b0c3e7 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 20:57:18 +0000 Subject: [PATCH 01/10] [hooks] Cover secret writes across file tools and redirects --- src/audit/findings.ts | 2 +- src/hooks/builtin-policies.ts | 140 ++++++++++++++++++++++++++++++---- src/hooks/policy-catalog.ts | 15 ++-- 3 files changed, 133 insertions(+), 24 deletions(-) diff --git a/src/audit/findings.ts b/src/audit/findings.ts index 0fa442426..d9381efcc 100644 --- a/src/audit/findings.ts +++ b/src/audit/findings.ts @@ -235,7 +235,7 @@ const POLICY_META: Record = { }, "block-secrets-write": { displayTitle: "Tried to write a secret-key file", - impact: "blocks writes to .pem, id_rsa, credentials.json, and similar.", + impact: "blocks writes to SSH private keys, certificate/key stores, credentials files, and shell redirects into them.", }, "warn-background-process": { displayTitle: "Started a long-lived background process", diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 717bd18c7..eea2b82b5 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -453,9 +453,41 @@ const SHORT_FLAG_BUNDLE_RE = /^-[a-zA-Z]*f[a-zA-Z]*$/; const SAFE_FORCE_PREFIXES = ["--force-with-lease", "--force-if-includes"] as const; // blockSecretsWrite -const SECRET_FILE_RE = /\.(?:pem|key)$/; -const SECRET_FILE_ID_RSA_RE = /id_rsa/; -const SECRET_FILE_CREDENTIALS_RE = /credentials/; +const SECRET_FILE_EXTENSIONS = [".pem", ".p12", ".pfx", ".keystore"] as const; +const SECRET_FILE_BASENAMES = new Set([ + ".netrc", + ".npmrc", + ".pypirc", + "credentials", + "credentials.json", + "service-account.json", + "service_account.json", + "serviceaccountkey.json", +]); + +function secretPathBasename(filePath: string): string { + const trimmed = filePath.replace(/[\\/]+$/, ""); + const slash = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\")); + return trimmed.slice(slash + 1).toLowerCase(); +} + +/** + * True when a path names a credential or private-key file by its basename. + * + * `.key` is deliberately absent: Keynote presentations use the same extension, + * so an extension-only matcher cannot separate them from private keys. Users + * who accept that tradeoff can add it back through `additionalPatterns`. + * Service-account JSON has no required filename, so only the conventional + * exact basenames above are covered; arbitrary names remain a job for + * `additionalPatterns` rather than a heuristic over every `*.json` file. + */ +function isSecretFilePath(filePath: string): boolean { + const basename = secretPathBasename(filePath); + if (!basename) return false; + if (basename.startsWith("id_") && !basename.endsWith(".pub")) return true; + if (SECRET_FILE_BASENAMES.has(basename)) return true; + return SECRET_FILE_EXTENSIONS.some((extension) => basename.endsWith(extension)); +} // blockWorkOnMain const GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/; @@ -2040,14 +2072,22 @@ function blockEnvFiles(ctx: PolicyContext): PolicyResult { * are. Quoted tokens are returned separately so a caller can decide whether * their CONTENTS deserve a second look — see `EVAL_FLAG_RE`. */ -function quoteAwareSegments(command: string): Array { - const segments: Array = []; - let tokens: string[] = []; +interface ShellLexedToken { + text: string; + /** Indexes of unquoted, unescaped `<` and `>` characters in `text`. */ + redirectOperators: number[]; +} + +function lexShellSegments(command: string): ShellLexedToken[][] { + const segments: ShellLexedToken[][] = []; + let tokens: ShellLexedToken[] = []; let token = ""; + let redirectOperators: number[] = []; let quote: '"' | "'" | null = null; const endToken = () => { - if (token) tokens.push(token); + if (token) tokens.push({ text: token, redirectOperators }); token = ""; + redirectOperators = []; }; const endSegment = () => { endToken(); @@ -2083,16 +2123,64 @@ function quoteAwareSegments(command: string): Array { endToken(); continue; } - if (/[;&|\n\r(){}`]/.test(c)) { + // `>|` is one redirection operator (noclobber override), not a redirect + // followed by a pipe. Every other pipe keeps its ordinary separator role. + const noClobberPipe = + c === "|" && token.endsWith(">") && redirectOperators[redirectOperators.length - 1] === token.length - 1; + if (/[;&|\n\r(){}`]/.test(c) && !noClobberPipe) { endSegment(); continue; } + if (c === "<" || c === ">") redirectOperators.push(token.length); token += c; } endSegment(); return segments; } +function quoteAwareSegments(command: string): Array { + return lexShellSegments(command).map((segment) => segment.map((token) => token.text)); +} + +/** + * Extract output redirect targets using the same quote-aware lexing as + * `block-sudo`. Redirections are shell syntax even when glued to a word + * (`cat>file`), while quoted or escaped `>` characters are data. + */ +function outputRedirectTargets(command: string): string[] { + const targets: string[] = []; + for (const segment of lexShellSegments(command)) { + for (let index = 0; index < segment.length; index++) { + const token = segment[index]; + for (let operatorPosition = 0; operatorPosition < token.redirectOperators.length; operatorPosition++) { + const operatorIndex = token.redirectOperators[operatorPosition]; + if (token.text[operatorIndex] !== ">") continue; + // The second half of `>>`, and the `>` in the read-write operator + // `<>`, are not separate output redirections. + if ( + operatorIndex > 0 && + (token.text[operatorIndex - 1] === ">" || token.text[operatorIndex - 1] === "<") && + token.redirectOperators[operatorPosition - 1] === operatorIndex - 1 + ) { + continue; + } + + let targetStart = operatorIndex + 1; + if (token.text[targetStart] === ">") targetStart++; + if (token.text[targetStart] === "|") targetStart++; + + const nextOperator = token.redirectOperators[operatorPosition + 1]; + const targetEnd = nextOperator !== undefined && nextOperator > targetStart ? nextOperator : token.text.length; + let target = token.text.slice(targetStart, targetEnd); + if (!target && index + 1 < segment.length) target = segment[index + 1].text; + // `>&2` duplicates a descriptor; it does not open a file named `2`. + if (target && !target.startsWith("&")) targets.push(target); + } + } + } + return targets; +} + /** `-c` and friends: the flags whose ARGUMENT is a command, not data. */ const EVAL_FLAG_RE = /^-{1,2}c$/; @@ -2441,16 +2529,36 @@ function isForcePushFlag(token: string): boolean { return SHORT_FLAG_BUNDLE_RE.test(token); } +const SECRET_WRITE_FILE_TOOLS = new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]); + function blockSecretsWrite(ctx: PolicyContext): PolicyResult { - if (ctx.toolName !== "Write") return allow(); - const filePath = getFilePath(ctx); - if (SECRET_FILE_RE.test(filePath) || SECRET_FILE_ID_RSA_RE.test(filePath) || SECRET_FILE_CREDENTIALS_RE.test(filePath)) { - return deny("Writing secret key files is blocked"); - } const additionalPatterns = ((ctx.params?.additionalPatterns ?? []) as string[]); - for (const pattern of additionalPatterns) { - if (filePath.includes(pattern)) { - return deny(`Writing blocked file pattern: ${pattern}`); + const blockedPath = (filePath: string): PolicyResult | null => { + if (!filePath) return null; + if (isSecretFilePath(filePath)) { + return deny("Writing secret key files is blocked"); + } + for (const pattern of additionalPatterns) { + if (filePath.includes(pattern)) { + return deny(`Writing blocked file pattern: ${pattern}`); + } + } + return null; + }; + + if (ctx.toolName && SECRET_WRITE_FILE_TOOLS.has(ctx.toolName)) { + const filePath = + getFilePath(ctx) || + ((ctx.toolInput?.notebook_path as string) ?? "") || + ((ctx.toolInput?.path as string) ?? ""); + const blocked = blockedPath(filePath); + if (blocked) return blocked; + } + + if (ctx.toolName === "Bash") { + for (const target of outputRedirectTargets(getCommand(ctx))) { + const blocked = blockedPath(target); + if (blocked) return blocked; } } return allow(); diff --git a/src/hooks/policy-catalog.ts b/src/hooks/policy-catalog.ts index ad4300c5e..35beb4483 100644 --- a/src/hooks/policy-catalog.ts +++ b/src/hooks/policy-catalog.ts @@ -391,14 +391,15 @@ export const POLICY_CATALOG: PolicyCatalogEntry[] = [ { name: "block-secrets-write", displayTitle: "Tried to write a secret-key file", - impact: "Stops the agent from creating `.pem`, `id_rsa`, `credentials.json`, etc.", - description: "Block writing secret key files", - match: { events: ["PreToolUse"], toolNames: ["Write"] }, + impact: "Stops the agent from creating SSH private keys, certificate/key stores, credential files, and shell redirects into them.", + description: "Block writing secret key and credential files", + match: { events: ["PreToolUse"], toolNames: ["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit"] }, // Reviewable: `secret-exposure` is deny-mode and `write` is in its `appliesTo`, so a - // real private key still comes back deny. What clears is this matcher's substring - // problem — `/credentials/` and `id_rsa` unanchored against a whole path, which - // catches `src/auth/credentials.ts`. `credential-exfiltration` would have been a - // dead name here: it applies to shell and network, and a file write is neither. + // real private key still comes back deny. The basename matcher can still catch a + // same-named non-secret file, which is what the review clears. `.key` is not in + // the builtin list because it is also Keynote's extension. `credential-exfiltration` + // would have been a dead name here: it applies to shell and network, and a file + // write is neither. authority: "reviewable", reviewedBy: ["secret-exposure"], defaultEnabled: false, From 9751b540019f857f9063dfc79efab70921b1b088 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 20:57:19 +0000 Subject: [PATCH 02/10] [hooks] Test secret-write coverage and false positives --- __tests__/e2e/helpers/payloads.ts | 12 +++ .../e2e/hooks/builtin-policies.e2e.test.ts | 30 ++++++ __tests__/hooks/builtin-policies.test.ts | 92 ++++++++++++++++--- __tests__/hooks/two-tier/corpus.ts | 14 ++- 4 files changed, 136 insertions(+), 12 deletions(-) diff --git a/__tests__/e2e/helpers/payloads.ts b/__tests__/e2e/helpers/payloads.ts index 42b47e738..587ac921c 100644 --- a/__tests__/e2e/helpers/payloads.ts +++ b/__tests__/e2e/helpers/payloads.ts @@ -39,6 +39,18 @@ export const Payloads = { }; }, + edit(filePath: string, cwd: string): Record { + return { + session_id: SESSION_ID, + transcript_path: TRANSCRIPT_PATH, + cwd, + permission_mode: "default", + hook_event_name: "PreToolUse", + tool_name: "Edit", + tool_input: { file_path: filePath, old_string: "before", new_string: "after" }, + }; + }, + read(filePath: string, cwd: string): Record { return { session_id: SESSION_ID, diff --git a/__tests__/e2e/hooks/builtin-policies.e2e.test.ts b/__tests__/e2e/hooks/builtin-policies.e2e.test.ts index 249edf0cb..4dab2ed7d 100644 --- a/__tests__/e2e/hooks/builtin-policies.e2e.test.ts +++ b/__tests__/e2e/hooks/builtin-policies.e2e.test.ts @@ -110,12 +110,42 @@ describe("block-secrets-write", () => { assertPreToolUseDeny(result); }); + it("blocks editing a secret key file", () => { + const env = createFixtureEnv(); + env.writeConfig({ enabledPolicies: ["block-secrets-write"] }); + const result = runHook("PreToolUse", Payloads.preToolUse.edit(`${env.cwd}/id_ed25519`, env.cwd), { homeDir: env.home }); + assertPreToolUseDeny(result); + }); + + it("blocks a Bash redirect into a secret key file", () => { + const env = createFixtureEnv(); + env.writeConfig({ enabledPolicies: ["block-secrets-write"] }); + const result = runHook("PreToolUse", Payloads.preToolUse.bash("cat > ~/.ssh/id_rsa < { const env = createFixtureEnv(); env.writeConfig({ enabledPolicies: ["block-secrets-write"] }); const result = runHook("PreToolUse", Payloads.preToolUse.write(`${env.cwd}/config.json`, "{}", env.cwd), { homeDir: env.home }); assertAllow(result); }); + + it("allows source and document paths that merely contain credentials", () => { + const env = createFixtureEnv(); + env.writeConfig({ enabledPolicies: ["block-secrets-write"] }); + for (const filePath of [`${env.cwd}/src/auth/credentials.ts`, `${env.cwd}/docs/credentials/setup.md`]) { + const result = runHook("PreToolUse", Payloads.preToolUse.write(filePath, "content", env.cwd), { homeDir: env.home }); + assertAllow(result); + } + }); + + it("allows a Keynote .key file", () => { + const env = createFixtureEnv(); + env.writeConfig({ enabledPolicies: ["block-secrets-write"] }); + const result = runHook("PreToolUse", Payloads.preToolUse.write(`${env.cwd}/slides/Roadmap.key`, "content", env.cwd), { homeDir: env.home }); + assertAllow(result); + }); }); describe("warn-large-file-write", () => { diff --git a/__tests__/hooks/builtin-policies.test.ts b/__tests__/hooks/builtin-policies.test.ts index f08026f62..fdd6ed5be 100644 --- a/__tests__/hooks/builtin-policies.test.ts +++ b/__tests__/hooks/builtin-policies.test.ts @@ -1181,32 +1181,102 @@ describe("hooks/builtin-policies", () => { describe("block-secrets-write", () => { const policy = BUILTIN_POLICIES.find((p) => p.name === "block-secrets-write")!; - it("blocks writing .pem files", async () => { - const ctx = makeCtx({ toolName: "Write", toolInput: { file_path: "/home/user/cert.pem" } }); + it("matches file-writing tools and Bash", () => { + expect(policy.match.toolNames).toEqual(["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit"]); + }); + + it.each([ + "/home/user/.ssh/id_rsa", + "/home/user/.ssh/id_ed25519", + "/home/user/.ssh/id_ecdsa", + "/home/user/.ssh/id_dsa", + "/home/user/.ssh/id_xmss", + "/home/user/cert.pem", + "/home/user/cert.p12", + "/home/user/cert.pfx", + "/home/user/store.keystore", + "/home/user/.netrc", + "/home/user/.npmrc", + "/home/user/.pypirc", + "/home/user/.aws/credentials", + "/home/user/.config/credentials.json", + "/home/user/service-account.json", + "/home/user/service_account.json", + "/home/user/serviceAccountKey.json", + ])("blocks Write to credential file %s", async (filePath) => { + const ctx = makeCtx({ toolName: "Write", toolInput: { file_path: filePath } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + + it.each(["Edit", "MultiEdit"])("blocks %s to a credential file", async (toolName) => { + const ctx = makeCtx({ toolName, toolInput: { file_path: "/home/user/.ssh/id_ed25519" } }); expect((await policy.fn(ctx)).decision).toBe("deny"); }); - it("blocks writing .key files", async () => { - const ctx = makeCtx({ toolName: "Write", toolInput: { file_path: "/etc/ssl/private.key" } }); + it("blocks NotebookEdit to a credential file", async () => { + const ctx = makeCtx({ toolName: "NotebookEdit", toolInput: { notebook_path: "/home/user/.ssh/id_rsa" } }); expect((await policy.fn(ctx)).decision).toBe("deny"); }); - it("blocks writing id_rsa", async () => { - const ctx = makeCtx({ toolName: "Write", toolInput: { file_path: "/home/user/.ssh/id_rsa" } }); + it.each([ + ["heredoc target", "cat > ~/.ssh/id_rsa <./id_ed25519"], + ["append redirect", "printf key >> ./cert.pem"], + ["append redirect glued to its target", "printf key>>./cert.p12"], + ["operator glued to its target", "cat >~/.ssh/id_ecdsa </home/user/.netrc"], + ["combined stdout and stderr", "printf key &>./credentials.json"], + ["quoted target", 'cat > "~/x/.npmrc" <|./credentials.json"], + ])("blocks a Bash output redirect using %s", async (_label, command) => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); expect((await policy.fn(ctx)).decision).toBe("deny"); }); - it("blocks writing credentials files", async () => { - const ctx = makeCtx({ toolName: "Write", toolInput: { file_path: "/home/user/.aws/credentials" } }); + it("blocks a Bash redirect target matching additionalPatterns", async () => { + const ctx = makeCtx({ + toolName: "Bash", + toolInput: { command: "printf token > ./secrets/vault-token.txt" }, + params: { additionalPatterns: ["secrets/"] }, + }); expect((await policy.fn(ctx)).decision).toBe("deny"); }); - it("allows writing normal files", async () => { - const ctx = makeCtx({ toolName: "Write", toolInput: { file_path: "/app/src/index.ts" } }); + it.each([ + "src/auth/credentials.ts", + "docs/credentials/setup.md", + "slides/Roadmap.key", + "slides/private.key", + "/home/user/.ssh/id_rsa.pub", + "/home/user/mycredentials", + "/home/user/credentials.txt", + "/home/user/service-account-details.json", + ])("allows writing non-secret file %s", async (filePath) => { + const ctx = makeCtx({ toolName: "Write", toolInput: { file_path: filePath } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it("allows a Bash redirect to a non-secret file", async () => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command: "cat ~/.ssh/id_rsa > ./backup.txt" } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it("does not treat a quoted greater-than sign as a redirect", async () => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command: 'echo "literal > ~/.ssh/id_rsa"' } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it("does not treat an escaped greater-than sign as a redirect", async () => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command: "echo literal\\>~/.ssh/id_rsa" } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it("ignores descriptor duplication", async () => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command: "echo hi 2>&1" } }); expect((await policy.fn(ctx)).decision).toBe("allow"); }); - it("allows non-Write tools", async () => { + it("allows non-writing tools", async () => { const ctx = makeCtx({ toolName: "Read", toolInput: { file_path: "/home/user/cert.pem" } }); expect((await policy.fn(ctx)).decision).toBe("allow"); }); diff --git a/__tests__/hooks/two-tier/corpus.ts b/__tests__/hooks/two-tier/corpus.ts index 2bbaf7eca..ca1514253 100644 --- a/__tests__/hooks/two-tier/corpus.ts +++ b/__tests__/hooks/two-tier/corpus.ts @@ -319,11 +319,22 @@ export function comparableHandlerOutcome( outcome: { exitCode: number; stdout: string; stderr: string; evaluation?: Record }, activity: Record | null, ): ComparableHandlerOutcome { + // `block-secrets-write` intentionally widened from Write to the other write + // surfaces in #1078. That catalog widening is pinned by its own unit and e2e + // tests; normalizing it here keeps this golden measuring the evaluation path + // rather than rejecting every Bash and Edit row over one expected extra name. + const withoutWidenedSecretsWrite = (value: unknown): unknown => { + if (!Array.isArray(value)) return value; + const toolName = String(outcome.evaluation?.toolName ?? activity?.toolName ?? ""); + if (!["Bash", "Edit", "MultiEdit", "NotebookEdit"].includes(toolName)) return value; + return value.filter((name) => name !== "failproofai/block-secrets-write"); + }; + let evaluation: Record | null = null; if (outcome.evaluation) { evaluation = { ...outcome.evaluation }; delete evaluation.durationMs; - evaluation.matchedPolicies = digest(evaluation.matchedPolicies); + evaluation.matchedPolicies = digest(withoutWidenedSecretsWrite(evaluation.matchedPolicies)); } let row: Record | null = null; if (activity) { @@ -332,6 +343,7 @@ export function comparableHandlerOutcome( delete row.durationMs; // Timing as well: `timestamp - durationMs`. delete row.startedAt; + row.matchedPolicies = withoutWidenedSecretsWrite(row.matchedPolicies); } return { out: { exitCode: outcome.exitCode, stdout: outcome.stdout, stderr: outcome.stderr, evaluation }, From b4f294194b1f3f3d8ee39cb83ad3d05c030c1db3 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 20:57:25 +0000 Subject: [PATCH 03/10] [hooks] Document secret-write path matching --- CHANGELOG.md | 1 + docs/policies/authority.mdx | 2 +- docs/policies/local-configuration.mdx | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 144f6a7ad..1eeaa9f1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Fixes +- `block-secrets-write` covers Edit, MultiEdit, NotebookEdit and Bash output redirects, and matches credential/key files by basename or extension rather than substring so source paths containing `credentials` and Keynote `.key` files are allowed (#1078). - Preserve bracketed units in Cloud CLI query results, so column labels like `latency [ms]` keep their units in the terminal (#1031). - Copilot: map the `task` tool to `Task` and `web_search` to `WebSearch`, so policies matching them fire on Copilot sessions instead of silently never running. The subagent tool reaches the PascalCase hooks as `Agent` (verified against Copilot CLI 1.0.117) and Copilot's session log as `task`, so both names map (#1101, from #693, #792, #844, fixes #690) - The Codex session cache (`state/codex-session-paths.json`) is written to a temp file and renamed into place. A write cut short by a full disk or a killed hook used to leave a torn file, and the next read discarded every cached session (#1102, from #692, #847, fixes #689) diff --git a/docs/policies/authority.mdx b/docs/policies/authority.mdx index bfdd33707..ca740c4dc 100644 --- a/docs/policies/authority.mdx +++ b/docs/policies/authority.mdx @@ -90,7 +90,7 @@ An instruct-mode semantic policy can never answer deny, but it can still keep a | `block-push-master` | hard | | Pushes directly to a protected branch. | | `block-work-on-main` | hard | | `commit-on-protected-branch` covers exactly this concern but is instruct-mode, so it can never answer deny, and no other check covers it. | | `block-force-push` | reviewable | `git-history-rewrite` | Jev's probe is a superset of the matcher and counts `--force-with-lease`; what clears is force-pushing your own branch. | -| `block-secrets-write` | reviewable | `secret-exposure` | The path match is unanchored, so `src/auth/credentials.ts` is caught; Jev asks whether real key material is being written. | +| `block-secrets-write` | reviewable | `secret-exposure` | The path match is basename- and extension-based; Jev asks whether real key material is being written. `.key` is not matched because Keynote uses the same extension. | | `block-kubectl` | reviewable | `production-infra-change` | Denies the whole CLI, read-only subcommands included; Jev asks whether the call mutates and whether the target is production. | | `block-terraform` | reviewable | `production-infra-change` | Same: clears `terraform plan` and `validate`. | | `block-aws-cli` | reviewable | `production-infra-change` | Same: clears `aws s3 ls`, `aws sts get-caller-identity`. | diff --git a/docs/policies/local-configuration.mdx b/docs/policies/local-configuration.mdx index 46fcbace5..b48007cd0 100644 --- a/docs/policies/local-configuration.mdx +++ b/docs/policies/local-configuration.mdx @@ -78,6 +78,8 @@ Each policy validates its own parameter types. | `require-pr-before-stop` | `baseBranch` | `string`, `"main"` | | `require-no-conflicts-before-stop` | `baseBranch` | `string`, `"main"` | +`block-secrets-write` matches SSH private-key and credential basenames plus key-store extensions. It deliberately does not match `.key`, because Keynote presentations use that extension too; add `.key` to `additionalPatterns` only where that false positive is acceptable. + An allow pattern broadens what an agent may do. Test the exact tokenization and command variants on the target harness before deploying it across a fleet. From 111ad015e65edb945c8410faed50a8d61b658074 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 21:02:13 +0000 Subject: [PATCH 04/10] [hooks] Link secret-write changelog entry --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1eeaa9f1f..1238711f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Fixes -- `block-secrets-write` covers Edit, MultiEdit, NotebookEdit and Bash output redirects, and matches credential/key files by basename or extension rather than substring so source paths containing `credentials` and Keynote `.key` files are allowed (#1078). +- `block-secrets-write` covers Edit, MultiEdit, NotebookEdit and Bash output redirects, and matches credential/key files by basename or extension rather than substring so source paths containing `credentials` and Keynote `.key` files are allowed (#1112, fixes #1078). - Preserve bracketed units in Cloud CLI query results, so column labels like `latency [ms]` keep their units in the terminal (#1031). - Copilot: map the `task` tool to `Task` and `web_search` to `WebSearch`, so policies matching them fire on Copilot sessions instead of silently never running. The subagent tool reaches the PascalCase hooks as `Agent` (verified against Copilot CLI 1.0.117) and Copilot's session log as `task`, so both names map (#1101, from #693, #792, #844, fixes #690) - The Codex session cache (`state/codex-session-paths.json`) is written to a temp file and renamed into place. A write cut short by a full disk or a killed hook used to leave a torn file, and the next read discarded every cached session (#1102, from #692, #847, fixes #689) From 741017c59bdeb70559772baf07db37c50c5a0ede Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 21:50:20 +0000 Subject: [PATCH 05/10] [hooks] Parse additional secret-write redirect forms --- src/hooks/builtin-policies.ts | 94 +++++++++++++++++++++++++++++------ 1 file changed, 80 insertions(+), 14 deletions(-) diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index eea2b82b5..8a956c86b 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2123,11 +2123,16 @@ function lexShellSegments(command: string): ShellLexedToken[][] { endToken(); continue; } - // `>|` is one redirection operator (noclobber override), not a redirect - // followed by a pipe. Every other pipe keeps its ordinary separator role. + // `>|`, `>&`, and `&>` are redirection operators rather than a redirect + // followed by a pipe or a command separator. Every other pipe or + // ampersand keeps its ordinary separator role. const noClobberPipe = c === "|" && token.endsWith(">") && redirectOperators[redirectOperators.length - 1] === token.length - 1; - if (/[;&|\n\r(){}`]/.test(c) && !noClobberPipe) { + const redirectAmpersand = + c === "&" && + ((token.endsWith(">") && redirectOperators[redirectOperators.length - 1] === token.length - 1) || + command[i + 1] === ">"); + if (/[;&|\n\r(){}`]/.test(c) && !noClobberPipe && !redirectAmpersand) { endSegment(); continue; } @@ -2142,6 +2147,61 @@ function quoteAwareSegments(command: string): Array { return lexShellSegments(command).map((segment) => segment.map((token) => token.text)); } +/** + * Extract output redirect targets using the same quote-aware lexing as + * `block-sudo`. Redirections are shell syntax even when glued to a word + * (`cat>file`), while quoted or escaped `>` characters are data. + */ +function heredocDelimitersInLine(line: string): Array<{ delimiter: string; stripTabs: boolean }> { + const delimiters: Array<{ delimiter: string; stripTabs: boolean }> = []; + for (const segment of lexShellSegments(line)) { + for (let index = 0; index < segment.length; index++) { + const token = segment[index]; + for (let operatorPosition = 0; operatorPosition < token.redirectOperators.length; operatorPosition++) { + const operatorIndex = token.redirectOperators[operatorPosition]; + if (token.text[operatorIndex] !== "<" || token.text[operatorIndex + 1] !== "<") continue; + if ( + operatorIndex > 0 && + token.text[operatorIndex - 1] === "<" && + token.redirectOperators[operatorPosition - 1] === operatorIndex - 1 + ) { + continue; + } + + let delimiterStart = operatorIndex + 2; + if (token.text[delimiterStart] === "<") continue; // `<<<` is a here-string, not a heredoc. + const stripTabs = token.text[delimiterStart] === "-"; + if (stripTabs) delimiterStart++; + const boundary = token.redirectOperators.find((position) => position >= delimiterStart); + let delimiter = token.text.slice(delimiterStart, boundary ?? token.text.length); + if (!delimiter && index + 1 < segment.length) { + const nextToken = segment[index + 1]; + delimiter = nextToken.text.slice(0, nextToken.redirectOperators[0] ?? nextToken.text.length); + } + if (delimiter) delimiters.push({ delimiter, stripTabs }); + } + } + } + return delimiters; +} + +function stripHeredocBodies(command: string): string { + const keptLines: string[] = []; + const pending: Array<{ delimiter: string; stripTabs: boolean }> = []; + for (const line of command.split("\n")) { + if (pending.length) { + const terminator = pending.findIndex(({ delimiter, stripTabs }) => + (stripTabs ? line.replace(/^\t+/, "") : line) === delimiter, + ); + if (terminator >= 0) pending.splice(terminator, 1); + continue; + } + keptLines.push(line); + pending.push(...heredocDelimitersInLine(line)); + } + return keptLines.join("\n"); +} + /** * Extract output redirect targets using the same quote-aware lexing as * `block-sudo`. Redirections are shell syntax even when glued to a word @@ -2149,17 +2209,18 @@ function quoteAwareSegments(command: string): Array { */ function outputRedirectTargets(command: string): string[] { const targets: string[] = []; - for (const segment of lexShellSegments(command)) { + for (const segment of lexShellSegments(stripHeredocBodies(command))) { for (let index = 0; index < segment.length; index++) { const token = segment[index]; for (let operatorPosition = 0; operatorPosition < token.redirectOperators.length; operatorPosition++) { const operatorIndex = token.redirectOperators[operatorPosition]; if (token.text[operatorIndex] !== ">") continue; - // The second half of `>>`, and the `>` in the read-write operator - // `<>`, are not separate output redirections. + // The second half of `>>` is part of the append operator, not a + // separate output redirection. `<>` is a read-write redirection, so + // its target is writable and must be checked. if ( operatorIndex > 0 && - (token.text[operatorIndex - 1] === ">" || token.text[operatorIndex - 1] === "<") && + token.text[operatorIndex - 1] === ">" && token.redirectOperators[operatorPosition - 1] === operatorIndex - 1 ) { continue; @@ -2168,13 +2229,18 @@ function outputRedirectTargets(command: string): string[] { let targetStart = operatorIndex + 1; if (token.text[targetStart] === ">") targetStart++; if (token.text[targetStart] === "|") targetStart++; - - const nextOperator = token.redirectOperators[operatorPosition + 1]; - const targetEnd = nextOperator !== undefined && nextOperator > targetStart ? nextOperator : token.text.length; - let target = token.text.slice(targetStart, targetEnd); - if (!target && index + 1 < segment.length) target = segment[index + 1].text; - // `>&2` duplicates a descriptor; it does not open a file named `2`. - if (target && !target.startsWith("&")) targets.push(target); + const duplicatesDescriptor = token.text[targetStart] === "&"; + if (duplicatesDescriptor) targetStart++; + + const boundary = token.redirectOperators.find((position) => position >= targetStart); + let target = token.text.slice(targetStart, boundary ?? token.text.length); + if (!target && index + 1 < segment.length) { + const nextToken = segment[index + 1]; + target = nextToken.text.slice(0, nextToken.redirectOperators[0] ?? nextToken.text.length); + } + // `>&1` duplicates a descriptor and `>&-` closes it; neither opens a + // file. A non-numeric word after `>&` is a combined-output filename. + if (target && (!duplicatesDescriptor || !/^(?:\d+|-)$/.test(target))) targets.push(target); } } } From 12d676e73efc5307fcfcc842daf9ac7de5157b96 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 21:50:20 +0000 Subject: [PATCH 06/10] [hooks] Test redirect parsing edge cases --- __tests__/hooks/builtin-policies.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/__tests__/hooks/builtin-policies.test.ts b/__tests__/hooks/builtin-policies.test.ts index fdd6ed5be..8c5ba95e1 100644 --- a/__tests__/hooks/builtin-policies.test.ts +++ b/__tests__/hooks/builtin-policies.test.ts @@ -1226,6 +1226,10 @@ describe("hooks/builtin-policies", () => { ["operator glued to its target", "cat >~/.ssh/id_ecdsa </home/user/.netrc"], ["combined stdout and stderr", "printf key &>./credentials.json"], + ["combined stdout and stderr after the output operator", "printf key >&./credentials.json"], + ["read-write target", "printf token 1<>./credentials.json"], + ["append target before an input redirect", "printf token >>./credentials.json ./credentials.json "~/x/.npmrc" <|./credentials.json"], ])("blocks a Bash output redirect using %s", async (_label, command) => { @@ -1261,6 +1265,18 @@ describe("hooks/builtin-policies", () => { expect((await policy.fn(ctx)).decision).toBe("allow"); }); + it("does not treat heredoc body lines as redirects", async () => { + const command = "cat > README.md <<'EOF'\nExample: cat > ~/.ssh/id_rsa\nEOF"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it("still checks redirects after a heredoc body", async () => { + const command = "cat > README.md <<'EOF'\ntext\nEOF\ncat > ~/.ssh/id_rsa"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + it("does not treat a quoted greater-than sign as a redirect", async () => { const ctx = makeCtx({ toolName: "Bash", toolInput: { command: 'echo "literal > ~/.ssh/id_rsa"' } }); expect((await policy.fn(ctx)).decision).toBe("allow"); From a8cf41430c28a553ed5022189fbe92cf2c4d1357 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 22:15:34 +0000 Subject: [PATCH 07/10] [hooks] Harden heredoc and redirect parsing --- src/hooks/builtin-policies.ts | 221 ++++++++++++++++++++++++++++------ 1 file changed, 184 insertions(+), 37 deletions(-) diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index 8a956c86b..adbdd5569 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2152,53 +2152,172 @@ function quoteAwareSegments(command: string): Array { * `block-sudo`. Redirections are shell syntax even when glued to a word * (`cat>file`), while quoted or escaped `>` characters are data. */ -function heredocDelimitersInLine(line: string): Array<{ delimiter: string; stripTabs: boolean }> { - const delimiters: Array<{ delimiter: string; stripTabs: boolean }> = []; - for (const segment of lexShellSegments(line)) { - for (let index = 0; index < segment.length; index++) { - const token = segment[index]; - for (let operatorPosition = 0; operatorPosition < token.redirectOperators.length; operatorPosition++) { - const operatorIndex = token.redirectOperators[operatorPosition]; - if (token.text[operatorIndex] !== "<" || token.text[operatorIndex + 1] !== "<") continue; - if ( - operatorIndex > 0 && - token.text[operatorIndex - 1] === "<" && - token.redirectOperators[operatorPosition - 1] === operatorIndex - 1 - ) { - continue; - } +interface HeredocDelimiter { + delimiter: string; + stripTabs: boolean; + quoted: boolean; + line: number; +} + +function parseHeredocDelimiter( + command: string, + start: number, + line: number, +): (HeredocDelimiter & { end: number }) | null { + let index = start; + const stripTabs = command[index] === "-"; + if (stripTabs) index++; + while (command[index] === " " || command[index] === "\t") index++; + + let delimiter = ""; + let quoted = false; + let quote: '"' | "'" | null = null; + while (index < command.length) { + const c = command[index]; + if (quote) { + if (c === quote) quote = null; + else delimiter += c; + index++; + continue; + } + if (c === "\\" && index + 1 < command.length) { + quoted = true; + delimiter += command[index + 1]; + index += 2; + continue; + } + if (c === '"' || c === "'") { + quoted = true; + quote = c; + index++; + continue; + } + if (/\s/.test(c) || /[;&|<>(){}`]/.test(c)) break; + delimiter += c; + index++; + } + return delimiter ? { delimiter, stripTabs, quoted, line, end: index } : null; +} - let delimiterStart = operatorIndex + 2; - if (token.text[delimiterStart] === "<") continue; // `<<<` is a here-string, not a heredoc. - const stripTabs = token.text[delimiterStart] === "-"; - if (stripTabs) delimiterStart++; - const boundary = token.redirectOperators.find((position) => position >= delimiterStart); - let delimiter = token.text.slice(delimiterStart, boundary ?? token.text.length); - if (!delimiter && index + 1 < segment.length) { - const nextToken = segment[index + 1]; - delimiter = nextToken.text.slice(0, nextToken.redirectOperators[0] ?? nextToken.text.length); +/** + * Find heredoc declarations in one pass over the whole command. Tracking quote + * and comment state here matters because both can span physical lines, and a + * `<<` inside either one is data rather than a redirection operator. + */ +function heredocDeclarations(command: string): HeredocDelimiter[] { + const declarations: HeredocDelimiter[] = []; + let quote: '"' | "'" | null = null; + let comment = false; + let word = false; + let line = 0; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + if (c === "\n") { + line++; + comment = false; + word = false; + continue; + } + if (comment) continue; + if (quote) { + if (c === "\\" && quote === '"' && i + 1 < command.length) i++; + else if (c === quote) quote = null; + word = true; + continue; + } + if (c === "\\" && i + 1 < command.length) { + word = true; + i++; + continue; + } + if (c === '"' || c === "'") { + quote = c; + word = true; + continue; + } + if (c === "#" && !word) { + comment = true; + continue; + } + if (/\s/.test(c) || /[;&|<>(){}`]/.test(c)) { + if (c === "<" && command[i + 1] === "<" && command[i + 2] !== "<") { + const declaration = parseHeredocDelimiter(command, i + 2, line); + if (declaration) { + declarations.push(declaration); + i = Math.max(i, declaration.end - 1); } - if (delimiter) delimiters.push({ delimiter, stripTabs }); } + word = false; + continue; + } + word = true; + } + return declarations; +} + +function commandSubstitutions(text: string): string[] { + const substitutions: string[] = []; + for (let i = 0; i < text.length; i++) { + if (text[i] === "\\") { + i++; + continue; + } + if (text[i] === "$" && text[i + 1] === "(") { + const start = i + 2; + let depth = 1; + let end = start; + while (end < text.length && depth) { + if (text[end] === "\\") end++; + else if (text[end] === "(") depth++; + else if (text[end] === ")") depth--; + end++; + } + if (!depth) substitutions.push(text.slice(start, end - 1)); + i = end; + continue; + } + if (text[i] === "`") { + const start = i + 1; + let end = start; + while (end < text.length && text[end] !== "`") { + if (text[end] === "\\") end++; + end++; + } + if (end < text.length) substitutions.push(text.slice(start, end)); + i = end; } } - return delimiters; + return substitutions; } function stripHeredocBodies(command: string): string { + const declarationsByLine = new Map(); + for (const declaration of heredocDeclarations(command)) { + const declarations = declarationsByLine.get(declaration.line) ?? []; + declarations.push(declaration); + declarationsByLine.set(declaration.line, declarations); + } + const keptLines: string[] = []; - const pending: Array<{ delimiter: string; stripTabs: boolean }> = []; - for (const line of command.split("\n")) { - if (pending.length) { - const terminator = pending.findIndex(({ delimiter, stripTabs }) => - (stripTabs ? line.replace(/^\t+/, "") : line) === delimiter, - ); - if (terminator >= 0) pending.splice(terminator, 1); - continue; + const pending: Array = []; + let current: (HeredocDelimiter & { body: string }) | null = null; + command.split("\n").forEach((line, lineNumber) => { + if (!current && pending.length) current = pending.shift() ?? null; + if (current) { + const terminator = current.stripTabs ? line.replace(/^\t+/, "") : line; + if (terminator === current.delimiter) { + if (!current.quoted) keptLines.push(...commandSubstitutions(current.body)); + current = null; + } else { + current.body += `${line}\n`; + } + return; } keptLines.push(line); - pending.push(...heredocDelimitersInLine(line)); - } + for (const declaration of declarationsByLine.get(lineNumber) ?? []) { + pending.push({ ...declaration, body: "" }); + } + }); return keptLines.join("\n"); } @@ -2233,7 +2352,13 @@ function outputRedirectTargets(command: string): string[] { if (duplicatesDescriptor) targetStart++; const boundary = token.redirectOperators.find((position) => position >= targetStart); - let target = token.text.slice(targetStart, boundary ?? token.text.length); + // `&>` begins at its ampersand. Without backing the boundary up by + // one, a glued target such as `file&>/dev/null` keeps that operator's + // leading `&` in the filename and misses the write to `file`. + const targetEnd = boundary !== undefined && boundary > targetStart && token.text[boundary - 1] === "&" + ? boundary - 1 + : (boundary ?? token.text.length); + let target = token.text.slice(targetStart, targetEnd); if (!target && index + 1 < segment.length) { const nextToken = segment[index + 1]; target = nextToken.text.slice(0, nextToken.redirectOperators[0] ?? nextToken.text.length); @@ -2275,11 +2400,33 @@ const EVAL_FLAG_RE = /^-{1,2}c$/; * because static inspection of one command string cannot follow them. Closing * that properly needs enforcement below the shell, not a better matcher. */ +function shellRedirectOperatorEnd(token: string): number { + let index = 0; + while (/\d/.test(token[index] ?? "")) index++; + if (token.startsWith("&>", index)) return index + 2; + if (token[index] !== "<" && token[index] !== ">") return -1; + index++; + while (["<", ">", "|", "&", "-"].includes(token[index] ?? "")) index++; + return index; +} + function namesElevation(command: string, depth = 0): boolean { for (const tokens of quoteAwareSegments(command)) { let i = 0; + let skipRedirectOperand = false; while (i < tokens.length) { const token = tokens[i]; + if (skipRedirectOperand) { + skipRedirectOperand = false; + i++; + continue; + } + const redirectEnd = shellRedirectOperatorEnd(token); + if (redirectEnd >= 0) { + if (redirectEnd === token.length) skipRedirectOperand = true; + i++; + continue; + } const base = token.slice(token.lastIndexOf("/") + 1); // `sudo`/`doas` are themselves in COMMAND_PREFIX_TOKENS (they legitimately // stand in front of another binary), so they must be tested BEFORE the From 39e77579059504fad052f59101e7717d57548a30 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 22:15:34 +0000 Subject: [PATCH 08/10] [hooks] Test shell parsing bypasses --- __tests__/hooks/builtin-policies.test.ts | 36 ++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/__tests__/hooks/builtin-policies.test.ts b/__tests__/hooks/builtin-policies.test.ts index 8c5ba95e1..7c89672cf 100644 --- a/__tests__/hooks/builtin-policies.test.ts +++ b/__tests__/hooks/builtin-policies.test.ts @@ -567,6 +567,11 @@ describe("hooks/builtin-policies", () => { expect((await policy.fn(ctx)).decision).toBe("deny"); }); + it.each(["&>/dev/null sudo id", "&> /dev/null sudo id"])("blocks sudo after combined redirect %s", async (command) => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + it("allows non-sudo commands", async () => { const ctx = makeCtx({ toolName: "Bash", toolInput: { command: "ls -la" } }); expect((await policy.fn(ctx)).decision).toBe("allow"); @@ -1230,6 +1235,7 @@ describe("hooks/builtin-policies", () => { ["read-write target", "printf token 1<>./credentials.json"], ["append target before an input redirect", "printf token >>./credentials.json ./credentials.json./credentials.json&>/dev/null"], ["quoted target", 'cat > "~/x/.npmrc" <|./credentials.json"], ])("blocks a Bash output redirect using %s", async (_label, command) => { @@ -1277,6 +1283,36 @@ describe("hooks/builtin-policies", () => { expect((await policy.fn(ctx)).decision).toBe("deny"); }); + it("does not treat a heredoc operator in a comment as a delimiter", async () => { + const command = "# < ./credentials.json"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + + it("does not treat heredoc text inside a multiline quote as a delimiter", async () => { + const command = "printf '%s' '\n< ./credentials.json"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + + it("checks command substitutions in an unquoted heredoc body", async () => { + const command = "cat < ./credentials.json)\nEOF"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + + it("does not execute-looking literal text in an unquoted heredoc body", async () => { + const command = "cat > README.md < ~/.ssh/id_rsa\nEOF"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it("does not treat a quoted hash as the start of a comment", async () => { + const command = "printf '# < ./credentials.json"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + it("does not treat a quoted greater-than sign as a redirect", async () => { const ctx = makeCtx({ toolName: "Bash", toolInput: { command: 'echo "literal > ~/.ssh/id_rsa"' } }); expect((await policy.fn(ctx)).decision).toBe("allow"); From 86f24b12d893e6cf10f5cdbca9610b3f28850136 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 23:16:23 +0000 Subject: [PATCH 09/10] [hooks] Harden shell operator and heredoc lexing --- src/hooks/builtin-policies.ts | 209 ++++++++++++++++++++++------------ 1 file changed, 136 insertions(+), 73 deletions(-) diff --git a/src/hooks/builtin-policies.ts b/src/hooks/builtin-policies.ts index adbdd5569..b91064292 100644 --- a/src/hooks/builtin-policies.ts +++ b/src/hooks/builtin-policies.ts @@ -2076,18 +2076,24 @@ interface ShellLexedToken { text: string; /** Indexes of unquoted, unescaped `<` and `>` characters in `text`. */ redirectOperators: number[]; + /** Indexes of unquoted, unescaped `&` characters that form `>&` or `&>`. */ + redirectAmpersands: number[]; } function lexShellSegments(command: string): ShellLexedToken[][] { const segments: ShellLexedToken[][] = []; let tokens: ShellLexedToken[] = []; let token = ""; + let tokenStarted = false; let redirectOperators: number[] = []; + let redirectAmpersands: number[] = []; let quote: '"' | "'" | null = null; const endToken = () => { - if (token) tokens.push({ text: token, redirectOperators }); + if (tokenStarted) tokens.push({ text: token, redirectOperators, redirectAmpersands }); token = ""; + tokenStarted = false; redirectOperators = []; + redirectAmpersands = []; }; const endSegment = () => { endToken(); @@ -2099,6 +2105,7 @@ function lexShellSegments(command: string): ShellLexedToken[][] { if (quote) { // Inside single quotes a backslash is literal; inside double quotes it escapes. if (c === "\\" && quote === '"' && i + 1 < command.length) { + tokenStarted = true; token += command[++i]; continue; } @@ -2106,16 +2113,19 @@ function lexShellSegments(command: string): ShellLexedToken[][] { quote = null; continue; } + tokenStarted = true; token += c; continue; } if (c === "\\" && i + 1 < command.length) { // An escaped character is literal — `\sudo` is still sudo, and `\|` is a // pipe CHARACTER rather than a separator. + tokenStarted = true; token += command[++i]; continue; } if (c === '"' || c === "'") { + tokenStarted = true; quote = c; continue; } @@ -2123,6 +2133,12 @@ function lexShellSegments(command: string): ShellLexedToken[][] { endToken(); continue; } + // `#` starts a comment only where it starts a word. Quoted and escaped + // hashes never reach this branch, and `foo#bar` has already started one. + if (c === "#" && !tokenStarted) { + while (i + 1 < command.length && command[i + 1] !== "\n" && command[i + 1] !== "\r") i++; + continue; + } // `>|`, `>&`, and `&>` are redirection operators rather than a redirect // followed by a pipe or a command separator. Every other pipe or // ampersand keeps its ordinary separator role. @@ -2136,17 +2152,15 @@ function lexShellSegments(command: string): ShellLexedToken[][] { endSegment(); continue; } + if (redirectAmpersand) redirectAmpersands.push(token.length); if (c === "<" || c === ">") redirectOperators.push(token.length); + tokenStarted = true; token += c; } endSegment(); return segments; } -function quoteAwareSegments(command: string): Array { - return lexShellSegments(command).map((segment) => segment.map((token) => token.text)); -} - /** * Extract output redirect targets using the same quote-aware lexing as * `block-sudo`. Redirections are shell syntax even when glued to a word @@ -2170,6 +2184,7 @@ function parseHeredocDelimiter( while (command[index] === " " || command[index] === "\t") index++; let delimiter = ""; + let consumed = false; let quoted = false; let quote: '"' | "'" | null = null; while (index < command.length) { @@ -2181,80 +2196,106 @@ function parseHeredocDelimiter( continue; } if (c === "\\" && index + 1 < command.length) { + consumed = true; quoted = true; delimiter += command[index + 1]; index += 2; continue; } if (c === '"' || c === "'") { + consumed = true; quoted = true; quote = c; index++; continue; } if (/\s/.test(c) || /[;&|<>(){}`]/.test(c)) break; + consumed = true; delimiter += c; index++; } - return delimiter ? { delimiter, stripTabs, quoted, line, end: index } : null; + return consumed ? { delimiter, stripTabs, quoted, line, end: index } : null; +} + +interface ShellSyntaxScanState { + quote: '"' | "'" | null; + word: boolean; } /** - * Find heredoc declarations in one pass over the whole command. Tracking quote - * and comment state here matters because both can span physical lines, and a - * `<<` inside either one is data rather than a redirection operator. + * Scan one physical line of shell syntax for heredoc declarations. The caller + * invokes this only outside heredoc bodies, so quotes inside those literal + * bodies cannot corrupt the quote state used for later shell syntax. */ -function heredocDeclarations(command: string): HeredocDelimiter[] { +function heredocDeclarationsInLine( + lineText: string, + line: number, + state: ShellSyntaxScanState, +): HeredocDelimiter[] { const declarations: HeredocDelimiter[] = []; - let quote: '"' | "'" | null = null; - let comment = false; - let word = false; - let line = 0; - for (let i = 0; i < command.length; i++) { - const c = command[i]; - if (c === "\n") { - line++; - comment = false; - word = false; + for (let i = 0; i < lineText.length; i++) { + const c = lineText[i]; + if (state.quote) { + if (c === "\\" && state.quote === '"' && i + 1 < lineText.length) i++; + else if (c === state.quote) state.quote = null; + state.word = true; continue; } - if (comment) continue; - if (quote) { - if (c === "\\" && quote === '"' && i + 1 < command.length) i++; - else if (c === quote) quote = null; - word = true; - continue; - } - if (c === "\\" && i + 1 < command.length) { - word = true; + if (c === "\\" && i + 1 < lineText.length) { + state.word = true; i++; continue; } if (c === '"' || c === "'") { - quote = c; - word = true; - continue; - } - if (c === "#" && !word) { - comment = true; + state.quote = c; + state.word = true; continue; } + if (c === "#" && !state.word) break; if (/\s/.test(c) || /[;&|<>(){}`]/.test(c)) { - if (c === "<" && command[i + 1] === "<" && command[i + 2] !== "<") { - const declaration = parseHeredocDelimiter(command, i + 2, line); + if (c === "<" && lineText[i + 1] === "<" && lineText[i + 2] !== "<") { + const declaration = parseHeredocDelimiter(lineText, i + 2, line); if (declaration) { declarations.push(declaration); i = Math.max(i, declaration.end - 1); } } - word = false; + state.word = false; continue; } - word = true; + state.word = true; } + if (!state.quote) state.word = false; return declarations; } +function parenthesizedSubstitutionEnd(text: string, start: number): number { + let depth = 1; + let quote: '"' | "'" | null = null; + for (let index = start; index < text.length; index++) { + const c = text[index]; + if (quote) { + if (c === "\\" && quote === '"' && index + 1 < text.length) index++; + else if (c === quote) quote = null; + continue; + } + if (c === "\\" && index + 1 < text.length) { + index++; + continue; + } + if (c === '"' || c === "'") { + quote = c; + continue; + } + if (c === "(") depth++; + else if (c === ")") { + depth--; + if (!depth) return index + 1; + } + } + return -1; +} + function commandSubstitutions(text: string): string[] { const substitutions: string[] = []; for (let i = 0; i < text.length; i++) { @@ -2264,16 +2305,9 @@ function commandSubstitutions(text: string): string[] { } if (text[i] === "$" && text[i + 1] === "(") { const start = i + 2; - let depth = 1; - let end = start; - while (end < text.length && depth) { - if (text[end] === "\\") end++; - else if (text[end] === "(") depth++; - else if (text[end] === ")") depth--; - end++; - } - if (!depth) substitutions.push(text.slice(start, end - 1)); - i = end; + const end = parenthesizedSubstitutionEnd(text, start); + if (end >= 0) substitutions.push(text.slice(start, end - 1)); + i = (end >= 0 ? end : text.length) - 1; continue; } if (text[i] === "`") { @@ -2284,23 +2318,18 @@ function commandSubstitutions(text: string): string[] { end++; } if (end < text.length) substitutions.push(text.slice(start, end)); - i = end; + i = end - 1; } } return substitutions; } function stripHeredocBodies(command: string): string { - const declarationsByLine = new Map(); - for (const declaration of heredocDeclarations(command)) { - const declarations = declarationsByLine.get(declaration.line) ?? []; - declarations.push(declaration); - declarationsByLine.set(declaration.line, declarations); - } - const keptLines: string[] = []; const pending: Array = []; let current: (HeredocDelimiter & { body: string }) | null = null; + const scanState: ShellSyntaxScanState = { quote: null, word: false }; + command.split("\n").forEach((line, lineNumber) => { if (!current && pending.length) current = pending.shift() ?? null; if (current) { @@ -2313,8 +2342,9 @@ function stripHeredocBodies(command: string): string { } return; } + keptLines.push(line); - for (const declaration of declarationsByLine.get(lineNumber) ?? []) { + for (const declaration of heredocDeclarationsInLine(line, lineNumber, scanState)) { pending.push({ ...declaration, body: "" }); } }); @@ -2355,13 +2385,19 @@ function outputRedirectTargets(command: string): string[] { // `&>` begins at its ampersand. Without backing the boundary up by // one, a glued target such as `file&>/dev/null` keeps that operator's // leading `&` in the filename and misses the write to `file`. - const targetEnd = boundary !== undefined && boundary > targetStart && token.text[boundary - 1] === "&" - ? boundary - 1 - : (boundary ?? token.text.length); + const targetEnd = + boundary !== undefined && boundary > targetStart && token.redirectAmpersands.includes(boundary - 1) + ? boundary - 1 + : (boundary ?? token.text.length); let target = token.text.slice(targetStart, targetEnd); if (!target && index + 1 < segment.length) { const nextToken = segment[index + 1]; - target = nextToken.text.slice(0, nextToken.redirectOperators[0] ?? nextToken.text.length); + const firstOperator = nextToken.redirectOperators[0]; + const nextTargetEnd = + firstOperator !== undefined && nextToken.redirectAmpersands.includes(firstOperator - 1) + ? firstOperator - 1 + : (firstOperator ?? nextToken.text.length); + target = nextToken.text.slice(0, nextTargetEnd); } // `>&1` duplicates a descriptor and `>&-` closes it; neither opens a // file. A non-numeric word after `>&` is a combined-output filename. @@ -2400,28 +2436,55 @@ const EVAL_FLAG_RE = /^-{1,2}c$/; * because static inspection of one command string cannot follow them. Closing * that properly needs enforcement below the shell, not a better matcher. */ -function shellRedirectOperatorEnd(token: string): number { +function shellRedirectOperatorEnd(token: ShellLexedToken): number { let index = 0; - while (/\d/.test(token[index] ?? "")) index++; - if (token.startsWith("&>", index)) return index + 2; - if (token[index] !== "<" && token[index] !== ">") return -1; - index++; - while (["<", ">", "|", "&", "-"].includes(token[index] ?? "")) index++; - return index; + while (/\d/.test(token.text[index] ?? "")) index++; + + if ( + token.text[index] === "&" && + token.redirectAmpersands.includes(index) && + token.text[index + 1] === ">" && + token.redirectOperators.includes(index + 1) + ) { + let end = index + 2; + if (token.text[end] === ">" && token.redirectOperators.includes(end)) end++; + return end; + } + + const operator = token.text[index]; + if ((operator !== "<" && operator !== ">") || !token.redirectOperators.includes(index)) return -1; + let end = index + 1; + if (operator === "<") { + if (token.text[end] === "<" && token.redirectOperators.includes(end)) { + end++; + if (token.text[end] === "<" && token.redirectOperators.includes(end)) end++; + else if (token.text[end] === "-") end++; + } else if (token.text[end] === ">" && token.redirectOperators.includes(end)) { + end++; + } else if (token.text[end] === "&" && token.redirectAmpersands.includes(end)) { + end++; + } + } else { + if (token.text[end] === ">" && token.redirectOperators.includes(end)) end++; + else if (token.text[end] === "|") end++; + else if (token.text[end] === "&" && token.redirectAmpersands.includes(end)) end++; + } + return end; } function namesElevation(command: string, depth = 0): boolean { - for (const tokens of quoteAwareSegments(command)) { + for (const tokens of lexShellSegments(command)) { let i = 0; let skipRedirectOperand = false; while (i < tokens.length) { - const token = tokens[i]; + const lexedToken = tokens[i]; + const token = lexedToken.text; if (skipRedirectOperand) { skipRedirectOperand = false; i++; continue; } - const redirectEnd = shellRedirectOperatorEnd(token); + const redirectEnd = shellRedirectOperatorEnd(lexedToken); if (redirectEnd >= 0) { if (redirectEnd === token.length) skipRedirectOperand = true; i++; @@ -2443,7 +2506,7 @@ function namesElevation(command: string, depth = 0): boolean { // `sh -c "…"` / `bash -c "…"`: the next token is a COMMAND. Bounded // recursion so a nested `bash -c "bash -c …"` cannot spin. if (EVAL_FLAG_RE.test(token) && depth < 3 && i + 1 < tokens.length) { - if (namesElevation(tokens[i + 1], depth + 1)) return true; + if (namesElevation(tokens[i + 1].text, depth + 1)) return true; } i++; } From 3a034fee0f413333d73e5bc17b9d8bbfeb7ed0b4 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Mon, 30 Nov 2026 23:16:24 +0000 Subject: [PATCH 10/10] [hooks] Add shell lexer regression coverage --- __tests__/hooks/builtin-policies.test.ts | 70 +++++++++++++++++++++++- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/__tests__/hooks/builtin-policies.test.ts b/__tests__/hooks/builtin-policies.test.ts index 7c89672cf..c9d9501f3 100644 --- a/__tests__/hooks/builtin-policies.test.ts +++ b/__tests__/hooks/builtin-policies.test.ts @@ -567,11 +567,24 @@ describe("hooks/builtin-policies", () => { expect((await policy.fn(ctx)).decision).toBe("deny"); }); - it.each(["&>/dev/null sudo id", "&> /dev/null sudo id"])("blocks sudo after combined redirect %s", async (command) => { - const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + it.each(["&>/dev/null sudo id", "&> /dev/null sudo id", "&>> /dev/null sudo id"])( + "blocks sudo after combined redirect %s", + async (command) => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }, + ); + + it("does not skip the command after an attached dash redirect target", async () => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command: ">- sudo id" } }); expect((await policy.fn(ctx)).decision).toBe("deny"); }); + it("does not treat a quoted combined-redirect-shaped command as a redirect", async () => { + const ctx = makeCtx({ toolName: "Bash", toolInput: { command: "'&>helper' sudo" } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + it("allows non-sudo commands", async () => { const ctx = makeCtx({ toolName: "Bash", toolInput: { command: "ls -la" } }); expect((await policy.fn(ctx)).decision).toBe("allow"); @@ -1236,6 +1249,7 @@ describe("hooks/builtin-policies", () => { ["append target before an input redirect", "printf token >>./credentials.json ./credentials.json./credentials.json&>/dev/null"], + ["separate target before a combined redirect", "printf token > ./credentials.json&>/dev/null"], ["quoted target", 'cat > "~/x/.npmrc" <|./credentials.json"], ])("blocks a Bash output redirect using %s", async (_label, command) => { @@ -1277,6 +1291,18 @@ describe("hooks/builtin-policies", () => { expect((await policy.fn(ctx)).decision).toBe("allow"); }); + it("accepts a quoted empty heredoc delimiter", async () => { + const command = "cat <<''\nExample: cat > credentials.json\n\nprintf done"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it("does not let quotes in one literal heredoc body hide the next declaration", async () => { + const command = "cat <<'A'\ndon't\nA\ncat <<'B'\nExample: cat > credentials.json\nB"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + it("still checks redirects after a heredoc body", async () => { const command = "cat > README.md <<'EOF'\ntext\nEOF\ncat > ~/.ssh/id_rsa"; const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); @@ -1301,6 +1327,24 @@ describe("hooks/builtin-policies", () => { expect((await policy.fn(ctx)).decision).toBe("deny"); }); + it("checks adjacent command substitutions in an unquoted heredoc body", async () => { + const command = "cat < ./credentials.json)\nEOF"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + + it("does not end a command substitution at a quoted parenthesis", async () => { + const command = "cat < ./credentials.json)\nEOF"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + + it("checks adjacent backtick substitutions in an unquoted heredoc body", async () => { + const command = "cat < ./credentials.json`\nEOF"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("deny"); + }); + it("does not execute-looking literal text in an unquoted heredoc body", async () => { const command = "cat > README.md < ~/.ssh/id_rsa\nEOF"; const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); @@ -1308,11 +1352,31 @@ describe("hooks/builtin-policies", () => { }); it("does not treat a quoted hash as the start of a comment", async () => { - const command = "printf '# < ./credentials.json"; + const command = "printf '# harmless' <<'EOF'\nExample: cat > credentials.json\nEOF"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it("does not treat redirect examples in comments as redirects", async () => { + const command = "printf ok # Example: cat > credentials.json"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + + it.each([ + ["outside quotes", "true \\\ncat < ./credentials.json"], + ["inside double quotes", "printf \"start\\\nend\"\ncat < ./credentials.json"], + ])("keeps heredoc lines aligned after a backslash-newline continuation %s", async (_label, command) => { const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); expect((await policy.fn(ctx)).decision).toBe("deny"); }); + it("preserves an escaped ampersand in a redirect target", async () => { + const command = "printf token >./credentials.json\\&>/dev/null"; + const ctx = makeCtx({ toolName: "Bash", toolInput: { command } }); + expect((await policy.fn(ctx)).decision).toBe("allow"); + }); + it("does not treat a quoted greater-than sign as a redirect", async () => { const ctx = makeCtx({ toolName: "Bash", toolInput: { command: 'echo "literal > ~/.ssh/id_rsa"' } }); expect((await policy.fn(ctx)).decision).toBe("allow");