Skip to content
Open
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (#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)
Expand Down
12 changes: 12 additions & 0 deletions __tests__/e2e/helpers/payloads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,18 @@ export const Payloads = {
};
},

edit(filePath: string, cwd: string): Record<string, unknown> {
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<string, unknown> {
return {
session_id: SESSION_ID,
Expand Down
30 changes: 30 additions & 0 deletions __tests__/e2e/hooks/builtin-policies.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <<EOF", env.cwd), { homeDir: env.home });
assertPreToolUseDeny(result);
});

it("allows writing to normal files", () => {
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", () => {
Expand Down
208 changes: 197 additions & 11 deletions __tests__/hooks/builtin-policies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,24 @@ describe("hooks/builtin-policies", () => {
expect((await policy.fn(ctx)).decision).toBe("deny");
});

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");
Expand Down Expand Up @@ -1181,32 +1199,200 @@ 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 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.each([
["heredoc target", "cat > ~/.ssh/id_rsa <<EOF"],
["redirect glued to a word", "echo key>./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 <<EOF"],
["numbered descriptor", "printf key 2>/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</dev/null"],
["separate target before an input redirect", "printf token > ./credentials.json</dev/null"],
["target before a combined redirect", "printf token >./credentials.json&>/dev/null"],
["separate target before a combined redirect", "printf token > ./credentials.json&>/dev/null"],
["quoted target", 'cat > "~/x/.npmrc" <<EOF'],
["noclobber override", "printf key >|./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 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.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 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("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 } });
expect((await policy.fn(ctx)).decision).toBe("deny");
});

it("does not treat a heredoc operator in a comment as a delimiter", async () => {
const command = "# <<EOF\nprintf token > ./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<<EOF\n'\nprintf token > ./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 <<EOF\n$(printf token > ./credentials.json)\nEOF";
const ctx = makeCtx({ toolName: "Bash", toolInput: { command } });
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("checks adjacent command substitutions in an unquoted heredoc body", async () => {
const command = "cat <<EOF\n$(printf ok)$(printf token > ./credentials.json)\nEOF";
const ctx = makeCtx({ toolName: "Bash", toolInput: { command } });
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("does not end a command substitution at a quoted parenthesis", async () => {
const command = "cat <<EOF\n$(printf '%s' ')'; printf token > ./credentials.json)\nEOF";
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("checks adjacent backtick substitutions in an unquoted heredoc body", async () => {
const command = "cat <<EOF\n`printf ok``printf token > ./credentials.json`\nEOF";
const ctx = makeCtx({ toolName: "Bash", toolInput: { command } });
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("does not execute-looking literal text in an unquoted heredoc body", 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("does not treat a quoted hash as the start of a comment", async () => {
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 <<EOF\ntext\nEOF\nprintf token > ./credentials.json"],
["inside double quotes", "printf \"start\\\nend\"\ncat <<EOF\ntext\nEOF\nprintf token > ./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");
});

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");
});
Expand Down
14 changes: 13 additions & 1 deletion __tests__/hooks/two-tier/corpus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,11 +319,22 @@ export function comparableHandlerOutcome(
outcome: { exitCode: number; stdout: string; stderr: string; evaluation?: Record<string, unknown> },
activity: Record<string, unknown> | 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<string, unknown> | 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<string, unknown> | null = null;
if (activity) {
Expand All @@ -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 },
Expand Down
2 changes: 1 addition & 1 deletion docs/policies/authority.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
Expand Down
2 changes: 2 additions & 0 deletions docs/policies/local-configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<Warning>
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.
</Warning>
Expand Down
2 changes: 1 addition & 1 deletion src/audit/findings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ const POLICY_META: Record<string, { displayTitle: string; impact: string }> = {
},
"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",
Expand Down
Loading