fix(fermata): PostToolUse redacts any response shape, and a refusal fits each tool's schema

Built-in tools and normal MCP results send tool_response as an object or an
array, which the hook read as empty: nothing was redacted under any setting.
The hook now walks any shape, masks every string and returns the same shape.

Enum and literal values of Claude Code's output schemas (read from v2.1.314)
stay when they match exactly, because a mask there fails the schema and the
original is used. A secret that cannot take a mask refuses the output under
every setting. Refusals: Bash and Read answer a minimal schema-valid output,
others keep their shape with exact enum values only.

Also: an unreadable config layer no longer counts as deny, multi-line string
spellings of deny count, vim's other swap names and Kate's are editor files,
the heuristic warning moves to additionalContext, and PreToolUse answers
quietly for tools it has no rules for.
This commit is contained in:
2026-11-06 23:36:57 +01:00
parent 5c3b239f59
commit b69fbf3ae2
10 changed files with 901 additions and 196 deletions
+42 -30
View File
@@ -102,37 +102,29 @@ fn a_file_override_that_cannot_be_parsed_withholds_the_output_under_deny() {
}
/// Claude Code ignores a replacement that does not match a built-in tool's schema
/// and uses the original, so a plain string would withhold nothing here.
/// and uses the original, so a plain string would withhold nothing here. Each tool
/// and shape against its schema: `tests/cli_hook_redaction.rs`.
#[test]
fn an_object_response_is_withheld_in_its_own_shape_under_deny() {
// The control: without `deny` an object response is what it was, not looked at.
// The control: without `deny` the output goes on, with this file's values unknown.
let p = project(&[("secrets.toml", BROKEN_TOML)]);
assert_eq!(p.post(json!({"stdout": RESPONSE})), (json!({}), String::new()));
let (out, stderr) = p.post(json!({"stdout": RESPONSE}));
assert_eq!(out, json!({}));
assert!(stderr.contains("secrets.toml"), "{stderr}");
let p = project(&[(".botsecrets", DENY), ("secrets.toml", BROKEN_TOML)]);
let (out, _) = p.post(json!({"stdout": RESPONSE, "stderr": "", "interrupted": false, "isImage": false}));
let updated = &out["hookSpecificOutput"]["updatedToolOutput"];
assert!(updated["stdout"].as_str().unwrap().contains("secrets.toml"), "{out}");
assert_eq!((&updated["interrupted"], &updated["isImage"]), (&json!(false), &json!(false)));
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("secrets.toml"), "{out}");
assert!(!out.to_string().contains(VALUE), "{out}");
let (out, _) = p.post(json!({
"type": "text",
"file": {"filePath": "/p/x", "content": RESPONSE, "numLines": 1, "startLine": 1, "totalLines": 1},
}));
let updated = &out["hookSpecificOutput"]["updatedToolOutput"];
assert_eq!(updated["type"], "text");
assert_eq!(updated["file"]["numLines"], 1);
assert!(updated["file"]["content"].as_str().unwrap().contains("withheld"), "{out}");
assert!(!out.to_string().contains(VALUE), "{out}");
// A list keeps one item, and a value under a tag's name is no tag.
let (out, _) = p.post(json!({"mode": "files_with_matches", "filenames": [VALUE, VALUE], "type": RESPONSE}));
let (out, _) = p.hook(
"post-tool-use",
json!({"tool_name": "Grep", "tool_input": {}, "tool_response": {"mode": "files_with_matches", "numFiles": 2, "filenames": [VALUE, VALUE], "type": RESPONSE}}),
);
let updated = &out["hookSpecificOutput"]["updatedToolOutput"];
assert_eq!(updated["mode"], "files_with_matches");
assert_eq!(updated["numFiles"], 2);
// A list keeps one item, and a value under a tag's name is no tag.
assert_eq!(updated["filenames"].as_array().unwrap().len(), 1);
assert!(updated["type"].as_str().unwrap().contains("withheld"), "{out}");
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("secrets.toml"), "{out}");
assert!(!out.to_string().contains(VALUE), "{out}");
}
@@ -181,20 +173,38 @@ fn a_broken_user_global_config_that_says_deny_withholds_the_output() {
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"));
}
/// A layer whose bytes cannot be read says nothing. It must not stop every project
/// on the machine when it is the user-global one, and another layer's `deny` counts.
#[cfg(unix)]
#[test]
fn a_config_whose_bytes_cannot_be_read_withholds_the_output() {
fn a_config_whose_bytes_cannot_be_read_says_nothing() {
use std::os::unix::fs::PermissionsExt;
let p = project(&[(".botsecrets", "")]);
let file = p.dir.path().join(".botsecrets");
let p = project(&[]);
let dir = p.home.path().join(".config/fermata");
fs::create_dir_all(&dir).unwrap();
let file = dir.join(".botsecrets");
fs::write(&file, "").unwrap();
fs::set_permissions(&file, fs::Permissions::from_mode(0o000)).unwrap();
if fs::read(&file).is_ok() {
return; // Running as root: the file cannot be made unreadable.
}
assert_eq!(p.post(json!(RESPONSE)).0, json!({}));
assert_eq!(verdict(&p.pre_bash()), "allow");
fs::write(p.dir.path().join(".botsecrets"), DENY).unwrap();
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"));
assert_eq!(verdict(&p.pre_bash()), "deny");
}
/// TOML's multi-line strings are spellings of the setting too.
#[test]
fn a_broken_config_with_a_multi_line_string_deny_withholds_the_output() {
for setting in ["[enforcement]\non_parse_error = \"\"\"deny\"\"\"\n", "[enforcement]\non_parse_error = '''deny'''\n"] {
let broken = format!("{setting}{BROKEN_TOML}");
assert!(refusal(&project(&[(".botsecrets", &broken)]).post(json!(RESPONSE)).0).contains(".botsecrets"));
}
}
/// A broken config that does not say `deny` stays open, as it always has. Only the
/// message changes.
#[test]
@@ -228,11 +238,13 @@ fn other_settings_stay_open_and_quote_nothing() {
/// An editor's file does not take down every tool output of a `deny` project.
#[test]
fn an_editors_swap_file_does_not_withhold_under_deny() {
let p = project(&[(".botsecrets", DENY), (".env", "API_TOKEN=value-on-the-failing-line\n")]);
fs::write(p.dir.path().join(".env.swp"), b"b0VIM \xff\xfe\x00\x01").unwrap();
let (out, _) = p.post(json!(RESPONSE));
let text = out["hookSpecificOutput"]["updatedToolOutput"].as_str().unwrap();
assert!(text.starts_with("output of the tool") && !text.contains(VALUE), "{text}");
for name in [".env.swp", ".env.swm", ".env.kate-swp"] {
let p = project(&[(".botsecrets", DENY), (".env", "API_TOKEN=value-on-the-failing-line\n")]);
fs::write(p.dir.path().join(name), b"b0VIM \xff\xfe\x00\x01").unwrap();
let (out, _) = p.post(json!(RESPONSE));
let text = out["hookSpecificOutput"]["updatedToolOutput"].as_str().unwrap();
assert!(text.starts_with("output of the tool") && !text.contains(VALUE), "{name}: {text}");
}
}
// ---------------------------------------------------------------------------
+8 -5
View File
@@ -126,7 +126,7 @@ fn post_tool_use_empty_response_passthrough() {
}
#[test]
fn post_tool_use_heuristic_enforce_appends_warning() {
fn post_tool_use_heuristic_enforce_warns_beside_the_output() {
// Use a config with heuristic in enforce mode (the default).
let botsecrets = r#"
[files]
@@ -159,13 +159,16 @@ mode = "enforce"
.clone();
let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
let updated = v["hookSpecificOutput"]["updatedToolOutput"]
let context = v["hookSpecificOutput"]["additionalContext"]
.as_str()
.expect("expected updatedToolOutput with heuristic warning");
.expect("expected additionalContext with heuristic warning");
assert!(
updated.contains("[fermata] WARNING"),
"expected heuristic warning, got: {updated}"
context.contains("[fermata] WARNING"),
"expected heuristic warning, got: {context}"
);
assert!(!context.contains("ghp_"), "the warning quotes the match: {context}");
// The warning takes no place in the output: it has no shape to put it in.
assert!(v["hookSpecificOutput"].get("updatedToolOutput").is_none(), "{v}");
}
#[test]
+438
View File
@@ -0,0 +1,438 @@
//! PostToolUse on the shapes Claude Code really sends. Built-in tools send objects,
//! normal MCP results arrays, so a hook that reads only strings redacts nothing.
//!
//! No test here runs Claude Code. `SCHEMAS` is the part of each tool's output schema
//! these payloads touch, read from the bundled source of v2.1.314, and `conforms`
//! stands in for its `safeParse`: a replacement that fails it would be dropped for
//! the original output.
use assert_cmd::Command;
use serde_json::{json, Value};
use std::fs;
use tempfile::TempDir;
const SECRET: &str = "fake-token-4242-abcdef";
const MASK: &str = "*****";
fn project(env: &str, botsecrets: &str) -> (TempDir, TempDir) {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(".botignore"), "").unwrap();
fs::write(dir.path().join(".env"), env).unwrap();
fs::write(dir.path().join(".botsecrets"), botsecrets).unwrap();
(dir, tempfile::tempdir().unwrap())
}
fn hook(p: &(TempDir, TempDir), tool: &str, response: &Value) -> Value {
let output = Command::cargo_bin("fermata")
.unwrap()
.args(["hook", "--event", "post-tool-use", "--harness", "claude"])
.current_dir(p.0.path())
.env("HOME", p.1.path())
.write_stdin(json!({"tool_name": tool, "tool_input": {}, "tool_response": response}).to_string())
.assert()
.success()
.get_output()
.clone();
serde_json::from_slice(&output.stdout).unwrap()
}
fn with_secret() -> (TempDir, TempDir) {
project(&format!("API_TOKEN={SECRET}\n"), "[files]\npatterns = [\".env\"]\n")
}
/// Real-shaped responses, each with the secret in the text the model would read.
fn payloads() -> Vec<(&'static str, Value)> {
let line = format!("API_TOKEN={SECRET}");
vec![
("Bash", json!({"stdout": format!("token {SECRET}\n"), "stderr": "", "interrupted": false, "isImage": false})),
("Bash", json!({"stdout": "", "stderr": format!("failed with {SECRET}"), "interrupted": false, "noOutputExpected": false})),
("Bash", json!({
"stdout": format!("[main abc] {SECRET}"), "stderr": "", "interrupted": false,
"gitOperation": {
"commit": {"sha": "abc", "kind": "committed", "branch": "main"},
"branch": {"ref": "main", "action": "merged"},
"pr": {"number": 7, "url": "https://x/7", "action": "auto-merge-enabled"},
},
})),
("Read", json!({
"type": "text",
"file": {"filePath": "/p/.env", "content": format!("{line}\n"), "numLines": 1, "startLine": 1, "totalLines": 1},
})),
("Grep", json!({"mode": "content", "numFiles": 1, "filenames": [], "content": format!(".env:1:{line}"), "numLines": 1})),
("Grep", json!({"mode": "files_with_matches", "numFiles": 1, "filenames": [format!("/p/{SECRET}.txt")]})),
("Glob", json!({"durationMs": 1, "numFiles": 1, "filenames": [format!("/p/{SECRET}.txt")], "truncated": false})),
("Write", json!({
"type": "create", "filePath": "/p/x", "content": line, "structuredPatch": [], "originalFile": null,
})),
("Write", json!({
"type": "update", "filePath": "/p/x", "content": line, "originalFile": line,
"structuredPatch": [{"oldStart": 1, "oldLines": 1, "newStart": 1, "newLines": 1, "lines": [format!("-{line}"), "+x"]}],
"gitDiff": {"filename": "x", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": format!("-{line}"), "repository": null},
})),
("Edit", json!({
"filePath": "/p/x", "oldString": line, "newString": "x", "originalFile": line,
"structuredPatch": [{"oldStart": 1, "oldLines": 1, "newStart": 1, "newLines": 1, "lines": [format!("-{line}"), "+x"]}],
"userModified": false, "replaceAll": false,
})),
("WebFetch", json!({"bytes": 1, "code": 200, "codeText": "OK", "result": format!("page says {SECRET}"), "durationMs": 1, "url": "https://x"})),
("NotebookEdit", json!({
"new_source": line, "cell_type": "code", "language": "python", "edit_mode": "replace",
"notebook_path": "/p/n.ipynb", "original_file": line, "updated_file": line,
})),
("Agent", json!({
"status": "completed", "prompt": "p", "agentId": "a",
"content": [{"type": "text", "text": format!("subagent read {SECRET}")}],
"totalToolUseCount": 1, "totalDurationMs": 1, "totalTokens": 1,
})),
("mcp__srv__tool", json!([{"type": "text", "text": format!("token {SECRET}")}])),
("mcp__srv__tool", json!([{"type": "text", "text": "clean"}, {"type": "text", "text": format!("token {SECRET}")}])),
("mcp__srv__tool", json!({"content": [{"type": "text", "text": line}], "isError": false})),
]
}
/// Types: `"string"`, `"number"`, `"bool"`; a trailing `?` allows null or absence;
/// an array of strings is an enum; an array of one schema is a list of it; an object
/// is an object with those fields, others being free (zod strips them).
fn schema(tool: &str) -> Option<Value> {
let patch = json!([{"oldStart": "number", "oldLines": "number", "newStart": "number", "newLines": "number", "lines": ["string"]}]);
let git_diff = json!({"filename": "string", "status": ["modified", "added"], "additions": "number", "deletions": "number", "changes": "number", "patch": "string"});
Some(match tool {
"Bash" => json!({
"stdout": "string", "stderr": "string", "interrupted": "bool", "isImage": "bool?",
"gitOperation?": {
"commit?": {"sha": "string", "kind": ["committed", "amended", "cherry-picked"], "branch": "string?"},
"push?": {"branch": "string"},
"branch?": {"ref": "string", "action": ["merged", "rebased"]},
"pr?": {"number": "number", "url": "string?", "action": ["created", "edited", "merged", "commented", "closed", "reopened", "ready", "draft", "auto-merge-enabled", "auto-merge-disabled"]},
},
}),
"Read" => json!({"type": ["text"], "file": {"filePath": "string", "content": "string", "numLines": "number", "startLine": "number", "totalLines": "number"}}),
"Grep" => json!({"mode": ["content", "files_with_matches", "count"], "numFiles": "number", "filenames": ["string"], "content": "string?", "numLines": "number?"}),
"Glob" => json!({"durationMs": "number", "numFiles": "number", "filenames": ["string"], "truncated": "bool"}),
"Write" => json!({"type": ["create", "update"], "filePath": "string", "content": "string", "structuredPatch": patch, "originalFile": "string?", "gitDiff?": git_diff}),
"Edit" => json!({"filePath": "string", "oldString": "string", "newString": "string", "originalFile": "string?", "structuredPatch": patch, "userModified": "bool", "replaceAll": "bool", "gitDiff?": git_diff}),
"WebFetch" => json!({"bytes": "number", "code": "number", "codeText": "string", "result": "string", "durationMs": "number", "url": "string"}),
"NotebookEdit" => json!({"new_source": "string", "cell_type": ["code", "markdown"], "language": "string", "edit_mode": "string", "notebook_path": "string", "original_file": "string", "updated_file": "string"}),
"Agent" => json!({"status": ["completed"], "prompt": "string", "agentId": "string", "content": [{"type": ["text"], "text": "string"}], "totalToolUseCount": "number", "totalDurationMs": "number", "totalTokens": "number"}),
_ => return None, // MCP output is not validated.
})
}
fn conforms(schema: &Value, value: &Value, path: &str) -> Result<(), String> {
let fail = || Err(format!("{path}: {value} does not match {schema}"));
match schema {
Value::String(kind) => {
let (kind, optional) = kind.strip_suffix('?').map_or((kind.as_str(), false), |k| (k, true));
let ok = (optional && value.is_null())
|| match kind {
"string" => value.is_string(),
"number" => value.is_number(),
_ => value.is_boolean(),
};
if ok { Ok(()) } else { fail() }
}
Value::Array(items) if items.iter().all(|i| i.as_str().is_some_and(|s| !matches!(s, "string" | "number" | "bool"))) => {
if items.contains(value) { Ok(()) } else { fail() }
}
Value::Array(items) => match value.as_array() {
Some(values) => values.iter().try_for_each(|v| conforms(&items[0], v, path)),
None => fail(),
},
Value::Object(fields) => {
if !value.is_object() {
return fail();
}
for (name, field) in fields {
let (name, optional) = name.strip_suffix('?').map_or((name.as_str(), false), |n| (n, true));
match value.get(name) {
None if optional || field.as_str().is_some_and(|k| k.ends_with('?')) => {}
None => return Err(format!("{path}.{name} is missing")),
Some(v) => conforms(field, v, &format!("{path}.{name}"))?,
}
}
Ok(())
}
_ => fail(),
}
}
/// `after` is `before` with the secret masked, and nothing else: same keys, same
/// order of lists, same numbers and booleans.
fn same_shape(before: &Value, after: &Value, path: &str) {
match (before, after) {
(Value::String(b), Value::String(a)) => assert_eq!(*a, b.replace(SECRET, MASK), "{path}"),
(Value::Array(b), Value::Array(a)) => {
assert_eq!(b.len(), a.len(), "{path}");
b.iter().zip(a).for_each(|(b, a)| same_shape(b, a, path));
}
(Value::Object(b), Value::Object(a)) => {
assert_eq!(b.keys().collect::<Vec<_>>(), a.keys().collect::<Vec<_>>(), "{path}");
b.iter().for_each(|(k, v)| same_shape(v, &a[k], &format!("{path}.{k}")));
}
(b, a) => assert_eq!(b, a, "{path}"),
}
}
fn updated(out: &Value) -> &Value {
let updated = &out["hookSpecificOutput"]["updatedToolOutput"];
assert!(!updated.is_null(), "nothing replaced: {out}");
assert_eq!(out["hookSpecificOutput"]["hookEventName"], "PostToolUse");
updated
}
#[test]
fn every_shape_is_redacted_under_every_setting() {
let settings = ["", "[enforcement]\non_parse_error = \"allow\"\n", "[enforcement]\non_parse_error = \"deny\"\n"];
for setting in settings {
let p = project(&format!("API_TOKEN={SECRET}\n"), &format!("{setting}[files]\npatterns = [\".env\"]\n"));
for (tool, response) in payloads() {
let out = hook(&p, tool, &response);
assert!(!out.to_string().contains(SECRET), "{tool} under {setting:?}: {out}");
updated(&out);
}
}
}
#[test]
fn only_the_secret_changes_and_the_shape_stays() {
let p = with_secret();
for (tool, response) in payloads() {
let out = hook(&p, tool, &response);
same_shape(&response, updated(&out), tool);
assert!(out.to_string().contains(MASK), "{tool}: {out}");
}
}
#[test]
fn the_replacement_matches_the_tools_schema() {
let p = with_secret();
for (tool, response) in payloads() {
// The fixture itself must be what the schema describes.
if let Some(schema) = schema(tool) {
conforms(&schema, &response, tool).unwrap();
conforms(&schema, updated(&hook(&p, tool, &response)), tool).unwrap();
}
}
}
#[test]
fn a_string_response_stays_a_string_and_a_clean_response_answers_nothing() {
let p = with_secret();
let out = hook(&p, "mcp__srv__tool", &json!(format!("token {SECRET}")));
assert_eq!(*updated(&out), json!(format!("token {MASK}")));
for response in [
json!({"stdout": "clean", "stderr": "", "interrupted": false, "isImage": false}),
json!([{"type": "text", "text": "clean"}]),
json!("clean"),
] {
assert_eq!(hook(&p, "Bash", &response), json!({}), "{response}");
}
}
// ---------------------------------------------------------------------------
// Enum and literal fields
// ---------------------------------------------------------------------------
/// A secret that is also an enum value. Masking it would fail the schema, and Claude
/// Code would then use the original output. The listed value stays: it tells nothing.
#[test]
fn a_secret_equal_to_a_schema_value_keeps_the_field_and_masks_the_text() {
for (word, tool, response) in [
("committed", "Bash", json!({"stdout": "it committed x", "stderr": "", "interrupted": false, "gitOperation": {"commit": {"sha": "abc", "kind": "committed"}}})),
("completed", "Agent", json!({"status": "completed", "prompt": "p", "agentId": "a", "content": [{"type": "text", "text": "completed it"}], "totalToolUseCount": 1, "totalDurationMs": 1, "totalTokens": 1})),
("markdown", "NotebookEdit", json!({"new_source": "a markdown cell", "cell_type": "markdown", "language": "python", "edit_mode": "replace", "notebook_path": "n", "original_file": "o", "updated_file": "u"})),
("modified", "Edit", json!({"filePath": "/p/x", "oldString": "modified", "newString": "x", "originalFile": null, "structuredPatch": [], "userModified": false, "replaceAll": false, "gitDiff": {"filename": "x", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "p"}})),
("text", "Read", json!({"type": "text", "file": {"filePath": "/p/x", "content": "plain text", "numLines": 1, "startLine": 1, "totalLines": 1}})),
("create", "Write", json!({"type": "create", "filePath": "/p/x", "content": "create it", "structuredPatch": [], "originalFile": null})),
("count", "Grep", json!({"mode": "count", "numFiles": 0, "filenames": ["/p/count"]})),
] {
let p = project(&format!("API_TOKEN={word}\n"), "[files]\npatterns = [\".env\"]\n");
let out = hook(&p, tool, &response);
conforms(&schema(tool).unwrap(), updated(&out), &format!("{tool} with {word}")).unwrap();
assert!(out.to_string().contains(MASK), "{tool}: {out}");
}
}
/// A token under an enum's name that the schema does not list is no enum value. A
/// built-in's schema would refuse the mask, so the whole output is refused.
#[test]
fn a_secret_where_a_built_in_cannot_take_a_mask_withholds_the_output() {
let p = with_secret();
for (tool, response) in [
("Bash", json!({"stdout": SECRET, "stderr": "", "interrupted": false, "type": SECRET})),
("Bash", json!({"stdout": "x", "stderr": "", "interrupted": false, "gitOperation": {"commit": {"sha": "a", "kind": format!("{SECRET}-x")}}})),
("Bash", json!({"stdout": SECRET, "stderr": "", "interrupted": false, SECRET: "x"})),
] {
let out = hook(&p, tool, &response);
assert!(!out.to_string().contains(SECRET), "{out}");
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("API_TOKEN"), "{out}");
assert!(updated(&out).to_string().contains("withheld"), "{out}");
conforms(&schema(tool).unwrap(), updated(&out), tool).unwrap();
}
}
/// A word that is a key of the output is refused, not passed. A fixed name in the
/// schema cannot take a mask.
#[test]
fn a_secret_equal_to_a_schema_key_withholds_rather_than_passes() {
let p = project("API_TOKEN=stdout\n", "[files]\npatterns = [\".env\"]\n");
let response = json!({"stdout": "x", "stderr": "", "interrupted": false});
let out = hook(&p, "Bash", &response);
conforms(&schema("Bash").unwrap(), updated(&out), "Bash").unwrap();
assert!(updated(&out)["stdout"].as_str().unwrap().contains("API_TOKEN"), "{out}");
}
/// A notebook cell's `source` is text, though `source` is also a literal elsewhere.
#[test]
fn a_notebook_cells_source_is_masked_not_refused() {
let p = with_secret();
let response = json!({"type": "notebook", "file": {"filePath": "/p/n.ipynb", "cells": [{"cellType": "code", "source": format!("t = '{SECRET}'")}]}});
let out = hook(&p, "Read", &response);
same_shape(&response, updated(&out), "Read");
}
// ---------------------------------------------------------------------------
// Object keys, and what stays
// ---------------------------------------------------------------------------
#[test]
fn an_mcp_results_keys_are_masked_and_stay_apart() {
let p = with_secret();
let out = hook(&p, "mcp__srv__tool", &json!({
SECRET: 1,
format!("x{SECRET}"): "x",
"*****": 2,
"nested": [{SECRET: true}],
}));
assert!(!out.to_string().contains(SECRET), "{out}");
let updated = updated(&out).as_object().unwrap();
assert_eq!(updated.len(), 4, "{updated:?}");
assert_eq!(updated["x*****"], "x");
}
/// AskUserQuestion's answers are keyed by question text, not by schema names.
#[test]
fn a_built_in_records_keys_are_masked() {
let p = with_secret();
let out = hook(&p, "AskUserQuestion", &json!({"questions": [], "answers": {SECRET: "yes"}}));
assert_eq!(updated(&out)["answers"], json!({MASK: "yes"}));
assert!(!out.to_string().contains(SECRET), "{out}");
}
/// A short secret can match inside base64 by chance. Masking there breaks the image
/// and the next API request.
#[test]
fn binary_fields_stay_and_text_beside_them_is_masked() {
let p = project("API_TOKEN=QUJD\n", "[files]\npatterns = [\".env\"]\n");
let data = "QUJD".repeat(32);
for (tool, response) in [
("Read", json!({"type": "image", "file": {"base64": data, "type": "image/png", "originalSize": 3}})),
("Read", json!({"type": "pdf", "file": {"filePath": "/p/x.pdf", "base64": data, "originalSize": 3}})),
("Bash", json!({"stdout": format!("data:image/png;base64,{data}"), "stderr": "", "interrupted": false, "isImage": true})),
("mcp__srv__tool", json!([{"type": "image", "data": data, "mimeType": "image/png"}])),
] {
assert_eq!(hook(&p, tool, &response), json!({}), "{tool}");
}
// A token named `data` is text, and so is `base64` in an MCP result.
let out = hook(&p, "mcp__srv__tool", &json!({"data": "QUJD", "base64": "QUJD"}));
assert_eq!(*updated(&out), json!({"data": MASK, "base64": MASK}));
}
/// A value split across two strings is not one match: the documented limit.
#[test]
fn a_value_split_across_fields_is_not_found() {
let (head, tail) = SECRET.split_at(10);
let p = with_secret();
let out = hook(&p, "Bash", &json!({"stdout": head, "stderr": tail, "interrupted": false}));
assert_eq!(out, json!({}));
}
#[test]
fn the_heuristic_warning_sits_beside_an_object_response() {
let p = project("UNRELATED_KEY=foo\n", "[files]\npatterns = [\".env\"]\n");
let response = json!({"stdout": "log: ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij", "stderr": "", "interrupted": false, "isImage": false});
let out = hook(&p, "Bash", &response);
let specific = &out["hookSpecificOutput"];
assert!(specific.get("updatedToolOutput").is_none(), "{out}");
let context = specific["additionalContext"].as_str().unwrap();
assert!(context.contains("WARNING") && !context.contains("ghp_"), "{context}");
}
// ---------------------------------------------------------------------------
// Refusals under `deny`
// ---------------------------------------------------------------------------
/// Under `deny` with a broken secret file, each output is replaced by something its
/// schema takes. A rejected refusal would let the original through.
#[test]
fn the_refusal_matches_each_tools_schema() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(".botignore"), "").unwrap();
fs::write(dir.path().join(".botsecrets"), "[enforcement]\non_parse_error = \"deny\"\n").unwrap();
fs::write(dir.path().join("secrets.toml"), format!("API_TOKEN = \"{SECRET}\" broken [\n")).unwrap();
let p = (dir, tempfile::tempdir().unwrap());
for (tool, response) in payloads() {
let out = hook(&p, tool, &response);
assert!(!out.to_string().contains(SECRET), "{tool}: {out}");
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("secrets.toml"), "{out}");
if let Some(schema) = schema(tool) {
conforms(&schema, updated(&out), tool).unwrap();
}
}
// Bash and Read drop what could fail or mislead the mapper.
let out = hook(&p, "Bash", &json!({"stdout": SECRET, "stderr": "", "interrupted": false, "isImage": true, "gitOperation": {"commit": {"sha": "a", "kind": "new-kind"}}}));
let bash = updated(&out);
assert_eq!(bash["isImage"], false);
assert!(bash.get("gitOperation").is_none(), "{out}");
for response in [
json!({"type": "image", "file": {"base64": "QUJD", "type": "image/png", "originalSize": 3}}),
json!({"type": "pdf", "file": {"filePath": "/p/x.pdf", "base64": "QUJD", "originalSize": 3}}),
json!({"type": "notebook", "file": {"filePath": "/p/n", "cells": []}}),
] {
let out = hook(&p, "Read", &response);
let read = updated(&out);
conforms(&schema("Read").unwrap(), read, "Read").unwrap();
assert!(read["file"]["content"].as_str().unwrap().contains("withheld"), "{out}");
assert!(!out.to_string().contains("QUJD"), "{out}");
}
// A built-in that answers a list takes a list.
let out = hook(&p, "ListMcpResourcesTool", &json!([{"uri": SECRET, "name": "n", "server": "s"}]));
assert!(updated(&out).is_array(), "{out}");
assert!(!out.to_string().contains(SECRET), "{out}");
// Keys that are free text go, length limits hold.
let out = hook(&p, "AskUserQuestion", &json!({"questions": [], "answers": {SECRET: "yes"}}));
assert_eq!(updated(&out)["answers"], json!({}));
let out = hook(&p, "ReportFindings", &json!({"count": 1, "findings": [{"file": "f", "summary": SECRET, "failure_scenario": "x", "short_summary": "s", "category": "c", "verdict": "CONFIRMED"}]}));
let finding = &updated(&out)["findings"][0];
assert!(finding["short_summary"].as_str().unwrap().chars().count() <= 60, "{out}");
assert!(finding["category"].as_str().unwrap().chars().count() <= 40, "{out}");
assert_eq!(finding["verdict"], "CONFIRMED");
// M-4: a token under an enum's name is not kept.
let out = hook(&p, "Grep", &json!({"mode": SECRET, "numFiles": 0, "filenames": []}));
assert!(!out.to_string().contains(SECRET), "{out}");
}
#[test]
fn the_pre_tool_use_hook_is_quiet_on_a_tool_it_has_no_rules_for() {
let p = with_secret();
let output = Command::cargo_bin("fermata")
.unwrap()
.args(["hook", "--event", "pre-tool-use", "--harness", "claude"])
.current_dir(p.0.path())
.env("HOME", p.1.path())
.write_stdin(json!({"tool_name": "Grep", "tool_input": {"pattern": "x"}}).to_string())
.assert()
.success()
.get_output()
.clone();
assert_eq!(serde_json::from_slice::<Value>(&output.stdout).unwrap(), json!({}));
assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr));
}
+1 -1
View File
@@ -344,7 +344,7 @@ fn deny_config() -> SecretsConfig {
fn an_editors_file_that_cannot_be_read_does_not_refuse_and_one_that_can_stays_known() {
let dir = tempfile::tempdir().unwrap();
let config = deny_config();
for name in [".env.swp", ".env.swo", ".env.swn", ".env.swx", ".env.local~"] {
for name in [".env.swp", ".env.swo", ".env.swn", ".env.swm", ".env.swa", ".env.swx", ".env.kate-swp", ".env.local~"] {
fs::write(dir.path().join(name), NOT_UTF8).unwrap();
}
fs::write(dir.path().join(".env.bak.swp"), "API_KEY=readable-swap-value-1234\n").unwrap();
+6 -4
View File
@@ -95,14 +95,16 @@ fn parses_post_tool_use_payload() {
let p = ClaudeAdapter.parse_post_tool_use(payload).unwrap();
assert_eq!(p.tool_name, "Read");
assert_eq!(p.tool_response, "SECRET=abc");
assert!(p.has_output());
}
#[test]
fn parses_post_tool_use_missing_response() {
// tool_response absent → defaults to empty string.
// tool_response absent → no output to look at.
let payload = br#"{"tool_name":"Bash","tool_input":{"command":"ls"}}"#;
let p = ClaudeAdapter.parse_post_tool_use(payload).unwrap();
assert_eq!(p.tool_response, "");
assert_eq!(p.tool_response, serde_json::Value::Null);
assert!(!p.has_output());
}
#[test]
@@ -110,7 +112,7 @@ fn renders_post_tool_use_with_redacted_output() {
let payload = br#"{"tool_name":"Read","tool_input":{},"tool_response":"x"}"#;
let p = ClaudeAdapter.parse_post_tool_use(payload).unwrap();
let out = ClaudeAdapter
.render_post_tool_use(&p, Some("redacted text"))
.render_post_tool_use(&p, Some(&serde_json::json!("redacted text")), None)
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
assert_eq!(v["hookSpecificOutput"]["hookEventName"], "PostToolUse");
@@ -124,7 +126,7 @@ fn renders_post_tool_use_with_redacted_output() {
fn renders_post_tool_use_passthrough() {
let payload = br#"{"tool_name":"Read","tool_input":{},"tool_response":"clean"}"#;
let p = ClaudeAdapter.parse_post_tool_use(payload).unwrap();
let out = ClaudeAdapter.render_post_tool_use(&p, None).unwrap();
let out = ClaudeAdapter.render_post_tool_use(&p, None, None).unwrap();
let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
assert_eq!(v, serde_json::json!({}));
}