feat(fermata): a Write or Edit that adds a mask is stopped; masked output says so

count_masks counts runs of exactly five stars, or <REDACTED: marks under typed and
named; absent counts 0. write_pairs gives each change's text before and after. The
guard denies when a change holds more marks than what it replaces, and a Write's
"before" is the file on disk, read only if the new text holds a mark. Both projects
of a path call decide. on_mask_write = "allow" turns it off. The refusal says "ask the
user", names the setting and quotes nothing.

Each PostToolUse that masked adds a note beside the output.

cli_hook_fail_closed: a masked Write's only note is now the masks note, asserted
exactly, in place of "no note".
This commit is contained in:
2026-11-07 01:25:30 +01:00
parent 6d2311d248
commit c03000ddeb
7 changed files with 383 additions and 4 deletions
+3 -2
View File
@@ -278,11 +278,12 @@ fn a_typo_in_botsecrets_keeps_the_other_layers_and_the_default_list() {
assert!(!note.contains("polcy"), "{tool}: {note}");
}
// A Write costs the session no line for it, masked or not.
// A Write costs the session no line for it, masked or not: a masked one says only
// that it was masked.
assert_eq!(tool_output(&p, "Write", "clean"), json!({}));
let out = tool_output(&p, "Write", VALUE);
assert!(!out.to_string().contains(VALUE), "{out}");
assert!(out["hookSpecificOutput"].get("additionalContext").is_none(), "{out}");
assert_eq!(out["hookSpecificOutput"]["additionalContext"], "[fermata] Values in this output are masked. Do not write them back into a file.", "{out}");
}
/// A broken user-global layer: the project's own rules stand.
+303
View File
@@ -0,0 +1,303 @@
//! The write guard: a Write, Edit or MultiEdit that adds a mask is stopped, because an
//! agent that read `*****` and writes it back corrupts the file. Each output that was
//! masked says so beside it. All values here are fake.
use assert_cmd::Command;
use dirigent_fermata::core::secrets::config::RedactionStyle;
use dirigent_fermata::core::secrets::{count_masks, Manifest, Redactor, SecretEntry};
use serde_json::{json, Value};
use std::fs;
use tempfile::TempDir;
const MASK: &str = "*****";
const NOTE: &str = "[fermata] Values in this output are masked. Do not write them back into a file.";
/// Text around a mask, which a refusal must not quote.
const NEIGHBOUR: &str = "fake-neighbouring-text";
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 {
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(NEIGHBOUR), "stderr quotes the content: {stderr}");
serde_json::from_slice(&output.stdout).unwrap()
}
fn pre(&self, tool: &str, input: Value) -> Value {
self.hook("pre-tool-use", json!({"tool_name": tool, "tool_input": input}))
}
fn file(&self, name: &str) -> String {
self.dir.path().join(name).display().to_string()
}
fn write(&self, name: &str, content: &str) -> Value {
self.pre("Write", json!({"file_path": self.file(name), "content": content}))
}
fn edit(&self, old: &str, new: &str) -> Value {
self.pre("Edit", json!({"file_path": self.file("a.txt"), "old_string": old, "new_string": new}))
}
fn multi_edit(&self, edits: &[(&str, &str)]) -> Value {
let edits: Vec<Value> = edits.iter().map(|(old, new)| json!({"old_string": old, "new_string": new})).collect();
self.pre("MultiEdit", json!({"file_path": self.file("a.txt"), "edits": edits}))
}
fn post(&self, tool: &str, response: Value) -> Value {
self.hook("post-tool-use", json!({"tool_name": tool, "tool_input": {}, "tool_response": response}))
}
}
fn styled(style: &str) -> String {
format!("[redaction]\nstyle = \"{style}\"\n")
}
fn assert_denied(out: &Value) {
let specific = &out["hookSpecificOutput"];
assert_eq!(specific["permissionDecision"], "deny", "{out}");
let reason = specific["permissionDecisionReason"].as_str().unwrap();
assert!(reason.contains("ask the user") && reason.contains("on_mask_write"), "{reason}");
assert!(!reason.contains(NEIGHBOUR), "{reason}");
}
fn assert_silent(out: &Value) {
assert_eq!(*out, json!({}));
}
// ---------------------------------------------------------------------------
// Write
// ---------------------------------------------------------------------------
#[test]
fn a_write_of_a_new_file_with_a_mask_is_denied() {
let p = project(&[]);
assert_denied(&p.write("new.txt", &format!("key = {MASK}\n{NEIGHBOUR}\n")));
}
#[test]
fn a_write_of_a_file_already_holding_the_mask_passes() {
let p = project(&[("a.txt", "a = *****\n")]);
assert_silent(&p.write("a.txt", &format!("{NEIGHBOUR}\na = {MASK}\n")));
}
#[test]
fn a_write_with_more_masks_than_the_file_on_disk_is_denied() {
let p = project(&[("a.txt", "a = *****\n")]);
assert_denied(&p.write("a.txt", &format!("a = {MASK}\nb = {MASK}\n")));
}
#[test]
fn a_write_with_no_mask_passes() {
let p = project(&[]);
assert_silent(&p.write("new.txt", "plain text\n"));
}
/// The masks of a file that is not UTF-8 are still the file's.
#[test]
fn the_masks_of_a_binary_file_on_disk_count() {
let p = project(&[]);
fs::write(p.dir.path().join("a.bin"), b"\xff\xfe ***** \x00\n").unwrap();
assert_silent(&p.write("a.bin", MASK));
}
/// The file is the one the session means, not one in this process's directory.
#[test]
fn a_relative_path_is_the_sessions() {
let launch = project(&[]);
let session = project(&[("a.txt", "a = *****\n")]);
let payload = |content: &str| {
json!({"tool_name": "Write", "cwd": session.dir.path(), "tool_input": {"file_path": "a.txt", "content": content}})
};
assert_silent(&launch.hook("pre-tool-use", payload(MASK)));
assert_denied(&launch.hook("pre-tool-use", payload(&format!("{MASK} {MASK}"))));
}
// ---------------------------------------------------------------------------
// Edit, MultiEdit
// ---------------------------------------------------------------------------
#[test]
fn an_edit_adding_a_mask_is_denied() {
let p = project(&[]);
assert_denied(&p.edit("key = old", &format!("key = {MASK}")));
assert_denied(&p.edit(&format!("a = {MASK}"), &format!("a = {MASK}\nb = {MASK}")));
}
#[test]
fn an_edit_keeping_or_removing_a_mask_passes() {
let p = project(&[]);
assert_silent(&p.edit(&format!("a = {MASK}"), &format!("a = {MASK} # {NEIGHBOUR}")));
assert_silent(&p.edit(&format!("a = {MASK}"), "a = read from the environment"));
assert_silent(&p.edit("plain", "text"));
}
#[test]
fn a_multi_edit_is_judged_edit_by_edit() {
let p = project(&[]);
assert_denied(&p.multi_edit(&[("plain", "text"), ("key = old", &format!("key = {MASK}"))]));
assert_silent(&p.multi_edit(&[("plain", "text"), (&format!("a = {MASK}"), &format!("b = {MASK}"))]));
}
// ---------------------------------------------------------------------------
// The setting
// ---------------------------------------------------------------------------
#[test]
fn on_mask_write_allow_passes_each_tool() {
let p = project(&[(".botsecrets", "[enforcement]\non_mask_write = \"allow\"\n")]);
assert_silent(&p.write("new.txt", MASK));
assert_silent(&p.edit("old", MASK));
assert_silent(&p.multi_edit(&[("old", MASK)]));
}
/// A typo costs its layer, and the default of the guard stands.
#[test]
fn a_broken_config_keeps_the_guard() {
let p = project(&[(".botsecrets", "[polcy]\nx = 1\n")]);
assert_denied(&p.write("new.txt", MASK));
}
/// The session's project and the file's each decide, and the worst stands.
#[test]
fn the_sessions_project_guards_a_write_into_another() {
let session = project(&[]);
let other = project(&[(".botsecrets", "[enforcement]\non_mask_write = \"allow\"\n")]);
assert_denied(&session.write(&other.file("new.txt"), MASK));
assert_silent(&other.write(&other.file("new.txt"), MASK));
}
// ---------------------------------------------------------------------------
// What counts as a mask
// ---------------------------------------------------------------------------
#[test]
fn a_banner_or_a_rule_of_stars_is_no_mask() {
let p = project(&[]);
for text in ["/***********/", "****", "******", "/* ****************************** */", "a ** b *** c"] {
assert_silent(&p.write("new.txt", text));
assert_silent(&p.edit("old", text));
}
}
#[test]
fn count_masks_counts_each_styles_marks() {
use RedactionStyle::{Absent, Masked, Named, Typed};
for (style, text, count) in [
(Masked, "", 0),
(Masked, "*****", 1),
(Masked, "a ***** b ***** c", 2),
(Masked, "*****\n*****", 2),
(Masked, "x*****y", 1),
(Masked, "****", 0),
(Masked, "******", 0),
(Masked, "/***********/", 0),
(Masked, "<REDACTED:string:5>", 0),
(Typed, "<REDACTED:string:5> <REDACTED:string:7>", 2),
(Typed, "*****", 0),
(Named, "<REDACTED:API_TOKEN>", 1),
(Named, "*****", 0),
(Absent, "***** <REDACTED:API_TOKEN>", 0),
] {
assert_eq!(count_masks(style, text), count, "{style:?} {text:?}");
}
}
/// What the redactor writes is what the guard counts, one mark per value, in each style.
#[test]
fn count_masks_finds_what_the_redactor_writes() {
let entry = SecretEntry { key: "API_TOKEN".into(), value: SECRET.into(), source: "/p/.env".into() };
let manifest = Manifest::from_entries(vec![entry]);
let text = format!("a {SECRET} b {SECRET} c");
for (style, count) in [(RedactionStyle::Masked, 2), (RedactionStyle::Typed, 2), (RedactionStyle::Named, 2), (RedactionStyle::Absent, 0)] {
let redacted = Redactor::new(&manifest, style).redact(&text);
assert_eq!(count_masks(style, &redacted.text), count, "{style:?}: {}", redacted.text);
}
}
#[test]
fn typed_and_named_marks_count_under_their_styles() {
let p = project(&[(".botsecrets", &styled("typed"))]);
assert_denied(&p.write("new.txt", "key = <REDACTED:string:12>\n"));
assert_silent(&p.edit("a = <REDACTED:string:12>", "b = <REDACTED:string:12>"));
assert_silent(&p.write("new.txt", MASK));
let p = project(&[(".botsecrets", &styled("named"))]);
assert_denied(&p.write("new.txt", "key = <REDACTED:API_TOKEN>\n"));
assert_denied(&p.edit("old", "<REDACTED:API_TOKEN>"));
assert_silent(&p.write("new.txt", MASK));
}
#[test]
fn the_absent_style_has_no_mark_to_count() {
let p = project(&[(".botsecrets", &styled("absent"))]);
assert_silent(&p.write("new.txt", MASK));
assert_silent(&p.edit("old", "<REDACTED:API_TOKEN>"));
}
/// The stated limit: only the three tools that write a file's text are read.
#[test]
fn a_shell_command_that_writes_is_not_checked() {
let p = project(&[]);
assert_silent(&p.pre("Bash", json!({"command": "echo '*****' > new.txt"})));
}
// ---------------------------------------------------------------------------
// The note beside masked output
// ---------------------------------------------------------------------------
const SECRET: &str = "fake-token-4242-abcdef";
fn with_secret() -> Project {
project(&[(".env", &format!("API_TOKEN={SECRET}\n"))])
}
#[test]
fn masked_output_says_so_beside_it() {
let p = with_secret();
let bash = json!({"stdout": format!("token {SECRET}"), "stderr": "", "interrupted": false, "isImage": false});
let write = json!({"type": "create", "filePath": "/p/x", "content": SECRET, "structuredPatch": [], "originalFile": null});
for (tool, response) in [("Bash", bash), ("Write", write)] {
let out = p.post(tool, response);
assert_eq!(out["hookSpecificOutput"]["additionalContext"], NOTE, "{tool}: {out}");
assert!(!out.to_string().contains(SECRET), "{tool}: {out}");
}
}
#[test]
fn output_with_nothing_masked_has_no_note() {
let out = with_secret().post("Bash", json!({"stdout": "clean", "stderr": "", "interrupted": false, "isImage": false}));
assert_silent(&out);
}
#[test]
fn the_note_stands_beside_the_heuristic_warning() {
let p = with_secret();
let stdout = format!("{SECRET} ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij");
let out = p.post("Bash", json!({"stdout": stdout, "stderr": "", "interrupted": false, "isImage": false}));
let context = out["hookSpecificOutput"]["additionalContext"].as_str().unwrap();
assert!(context.starts_with(NOTE) && context.contains("WARNING"), "{context}");
assert!(!context.contains("ghp_"), "{context}");
}