Files
fermata/tests/cli_hook_fail_closed.rs
T
g4borg 969cff212f fix(fermata): the hooks refuse under on_parse_error = "deny", and no error quotes a file
PostToolUse replaced nothing when a secret file or the config failed. Under deny
it now puts a refusal naming the file in place of the output, in the tool's own
shape: Claude Code ignores a replacement that does not match a built-in tool's
schema. PreToolUse answers deny for a config or rules it cannot load or apply.

A config that cannot be loaded leaves the setting unknown: a layer with a line
setting deny counts, a layer whose bytes cannot be read counts as deny, and
anything else stays open as today.

Parse errors keep the format and line number and drop the parser's text.
2026-11-06 23:36:57 +01:00

266 lines
11 KiB
Rust

//! The hook's failure paths: a project that sets `on_parse_error = "deny"` gets a
//! refusal instead of a pass, every other project stays open, and nothing printed
//! or returned quotes a file that failed.
use assert_cmd::Command;
use serde_json::{json, Value};
use std::fs;
use tempfile::TempDir;
const VALUE: &str = "value-on-the-failing-line";
const BROKEN_TOML: &str = "API_TOKEN = \"value-on-the-failing-line\" broken [\n";
const DENY: &str = "[enforcement]\non_parse_error = \"deny\"\n";
const RESPONSE: &str = "output of the tool, value-on-the-failing-line in it";
/// A project with these files, and a home of its own so that the machine's
/// `~/.config/fermata/.botsecrets` plays no part.
struct Project {
dir: TempDir,
home: TempDir,
}
fn project(files: &[(&str, &str)]) -> Project {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(".botignore"), "").unwrap();
for (name, content) in files {
fs::write(dir.path().join(name), content).unwrap();
}
Project { dir, home: tempfile::tempdir().unwrap() }
}
impl Project {
fn hook(&self, event: &str, payload: Value) -> (Value, String) {
let output = Command::cargo_bin("fermata")
.unwrap()
.args(["hook", "--event", event, "--harness", "claude"])
.current_dir(self.dir.path())
.env("HOME", self.home.path())
.write_stdin(payload.to_string())
.assert()
.success()
.get_output()
.clone();
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(!stderr.contains(VALUE), "stderr quotes the file: {stderr}");
(serde_json::from_slice(&output.stdout).unwrap(), stderr)
}
fn post(&self, response: Value) -> (Value, String) {
self.hook("post-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "x"}, "tool_response": response}))
}
fn pre_read(&self, file: &str) -> Value {
let path = self.dir.path().join(file);
self.hook("pre-tool-use", json!({"tool_name": "Read", "tool_input": {"file_path": path}})).0
}
fn pre_bash(&self) -> Value {
self.hook("pre-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "ls"}})).0
}
}
/// The refusal that replaced a text response.
fn refusal(out: &Value) -> &str {
let text = out["hookSpecificOutput"]["updatedToolOutput"].as_str().unwrap_or_else(|| panic!("not withheld: {out}"));
assert!(text.starts_with("[fermata] Tool output withheld"), "{text}");
assert!(!out.to_string().contains(VALUE), "{out}");
text
}
fn verdict(out: &Value) -> &str {
out["hookSpecificOutput"]["permissionDecision"].as_str().unwrap()
}
fn deny_reason(out: &Value) -> &str {
assert_eq!(verdict(out), "deny", "{out}");
out["hookSpecificOutput"]["permissionDecisionReason"].as_str().unwrap()
}
// ---------------------------------------------------------------------------
// PostToolUse, under `deny`
// ---------------------------------------------------------------------------
#[test]
fn a_discovered_file_that_cannot_be_parsed_withholds_the_output_under_deny() {
let p = project(&[(".botsecrets", DENY), ("secrets.toml", BROKEN_TOML)]);
let (out, _) = p.post(json!(RESPONSE));
assert!(refusal(&out).contains("secrets.toml"), "{out}");
// The control: once it parses, the hook redacts and keeps the rest.
fs::write(p.dir.path().join("secrets.toml"), format!("API_TOKEN = \"{VALUE}\"\n")).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}");
}
#[test]
fn a_file_override_that_cannot_be_parsed_withholds_the_output_under_deny() {
let config = format!("{DENY}[[file]]\npath = \"conf.toml\"\n");
let p = project(&[(".botsecrets", &config), ("conf.toml", BROKEN_TOML)]);
let (out, _) = p.post(json!(RESPONSE));
assert!(refusal(&out).contains("conf.toml"), "{out}");
}
/// 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.
#[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.
let p = project(&[("secrets.toml", BROKEN_TOML)]);
assert_eq!(p.post(json!({"stdout": RESPONSE})), (json!({}), String::new()));
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 updated = &out["hookSpecificOutput"]["updatedToolOutput"];
assert_eq!(updated["mode"], "files_with_matches");
assert_eq!(updated["filenames"].as_array().unwrap().len(), 1);
assert!(!out.to_string().contains(VALUE), "{out}");
}
#[test]
fn an_mcp_tools_object_response_is_replaced_whole_under_deny() {
let p = project(&[(".botsecrets", DENY), ("secrets.toml", BROKEN_TOML)]);
let (out, _) = p.hook(
"post-tool-use",
json!({"tool_name": "mcp__x__y", "tool_input": {}, "tool_response": {"type": VALUE, "text": RESPONSE}}),
);
assert!(refusal(&out).contains("secrets.toml"), "{out}");
}
#[test]
fn file_patterns_that_cannot_be_compiled_withhold_the_output_under_deny() {
let config = format!("[files]\npatterns = [\"a[\"]\n{DENY}");
let (out, _) = project(&[(".botsecrets", &config)]).post(json!(RESPONSE));
assert!(refusal(&out).contains(".botsecrets"), "{out}");
}
// ---------------------------------------------------------------------------
// PostToolUse, when the config itself cannot be read
// ---------------------------------------------------------------------------
#[test]
fn a_broken_config_that_says_deny_withholds_the_output() {
let broken = format!("{DENY}{BROKEN_TOML}");
let (out, stderr) = project(&[(".botsecrets", &broken)]).post(json!(RESPONSE));
assert!(refusal(&out).contains(".botsecrets"), "{out}");
assert!(stderr.contains(".botsecrets"), "{stderr}");
// Other spellings, and another layer than the broken one.
let p = project(&[(".botsecrets", BROKEN_TOML), (".botsecrets.local", "enforcement.on_parse_error = 'deny'\n")]);
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"));
let p = project(&[(".botsecrets", DENY), (".botsecrets.local", BROKEN_TOML)]);
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets.local"));
}
/// A config in a user's home counts as the others do.
#[test]
fn a_broken_user_global_config_that_says_deny_withholds_the_output() {
let p = project(&[]);
let dir = p.home.path().join(".config/fermata");
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join(".botsecrets"), format!("{DENY}{BROKEN_TOML}")).unwrap();
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"));
}
#[cfg(unix)]
#[test]
fn a_config_whose_bytes_cannot_be_read_withholds_the_output() {
use std::os::unix::fs::PermissionsExt;
let p = project(&[(".botsecrets", "")]);
let file = p.dir.path().join(".botsecrets");
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!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"));
assert_eq!(verdict(&p.pre_bash()), "deny");
}
/// A broken config that does not say `deny` stays open, as it always has. Only the
/// message changes.
#[test]
fn a_broken_config_without_deny_stays_open_and_quotes_nothing() {
for broken in [BROKEN_TOML.to_string(), format!("# on_parse_error = \"deny\"\n{BROKEN_TOML}")] {
let p = project(&[(".botsecrets", &broken)]);
let (out, stderr) = p.post(json!(RESPONSE));
assert_eq!(out, json!({}));
assert!(stderr.contains(".botsecrets") && stderr.contains("line "), "{stderr}");
assert_eq!(verdict(&p.pre_bash()), "allow");
}
}
// ---------------------------------------------------------------------------
// PostToolUse, other settings
// ---------------------------------------------------------------------------
/// `hook` itself asserts that stderr quotes nothing.
#[test]
fn other_settings_stay_open_and_quote_nothing() {
for setting in ["", "[enforcement]\non_parse_error = \"allow\"\n", "[enforcement]\non_parse_error = \"mask-entire-file\"\n"] {
// A discovered file, and a `[[file]]` override.
let config = format!("{setting}[[file]]\npath = \"conf.toml\"\n");
let p = project(&[(".botsecrets", &config), ("secrets.toml", BROKEN_TOML), ("conf.toml", BROKEN_TOML)]);
let (out, stderr) = p.post(json!("no secrets here"));
assert_eq!(out, json!({}), "setting {setting:?}");
assert!(stderr.contains("secrets.toml") && stderr.contains("conf.toml"), "{stderr}");
}
}
// ---------------------------------------------------------------------------
// PreToolUse
// ---------------------------------------------------------------------------
#[test]
fn the_gate_refuses_when_a_config_that_says_deny_is_broken() {
let broken = format!("{DENY}{BROKEN_TOML}");
let p = project(&[(".botsecrets", &broken), ("safe.txt", "")]);
let (read, bash) = (p.pre_read("safe.txt"), p.pre_bash());
for out in [&read, &bash] {
let reason = deny_reason(out);
assert!(reason.contains(".botsecrets") && !reason.contains(VALUE), "{reason}");
}
}
#[test]
fn the_gate_refuses_when_rules_cannot_be_loaded_under_deny() {
let bad_rules = "[policy.read]\npatterns = [\"a[\"]\n";
let p = project(&[(".botsecrets", &format!("{DENY}{bad_rules}")), ("safe.txt", "")]);
assert!(deny_reason(&p.pre_read("safe.txt")).contains("rules"));
assert!(deny_reason(&p.pre_bash()).contains("rules"));
// The control: the same rules with no `deny` stay open.
let p = project(&[(".botsecrets", bad_rules), ("safe.txt", "")]);
assert_eq!(verdict(&p.pre_read("safe.txt")), "allow");
assert_eq!(verdict(&p.pre_bash()), "allow");
}
#[test]
fn the_gate_refuses_when_a_command_rule_cannot_be_applied_under_deny() {
let bad_rules = "[policy.bash]\ndeny = [\"a[\"]\n";
let p = project(&[(".botsecrets", &format!("{DENY}{bad_rules}"))]);
assert!(deny_reason(&p.pre_bash()).contains("rules"));
let p = project(&[(".botsecrets", bad_rules)]);
assert_eq!(verdict(&p.pre_bash()), "allow");
}