//! 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 = 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, "", 0), (Typed, " ", 2), (Typed, "*****", 0), (Named, "", 1), (Named, "*****", 0), (Absent, "***** ", 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 = \n")); assert_silent(&p.edit("a = ", "b = ")); assert_silent(&p.write("new.txt", MASK)); let p = project(&[(".botsecrets", &styled("named"))]); assert_denied(&p.write("new.txt", "key = \n")); assert_denied(&p.edit("old", "")); 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", "")); } /// 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}"); } // --------------------------------------------------------------------------- // Empty text and a Monitor without a command // --------------------------------------------------------------------------- #[test] fn the_absent_style_leaves_no_empty_text() { let p = project(&[(".env", &format!("API_TOKEN={SECRET}\n")), (".botsecrets", &styled("absent"))]); let todo = json!({"oldTodos": [], "newTodos": [{"content": SECRET, "status": "pending", "activeForm": "Working"}]}); let out = p.post("TodoWrite", todo); assert_eq!(out["hookSpecificOutput"]["updatedToolOutput"]["newTodos"][0]["content"], "[fermata]", "{out}"); let mcp = json!({"content": [{"type": "text", "text": SECRET}]}); let out = p.post("mcp__srv__t", mcp); assert_eq!(out["hookSpecificOutput"]["updatedToolOutput"]["content"][0]["text"], "[fermata]", "{out}"); } #[test] fn a_monitor_without_a_command_is_left_alone() { let p = project(&[]); let output = Command::cargo_bin("fermata") .unwrap() .args(["hook", "--event", "pre-tool-use", "--harness", "claude"]) .current_dir(p.dir.path()) .env("HOME", p.home.path()) .write_stdin(json!({"tool_name": "Monitor", "tool_input": {"ws": "wss://example.test/x"}}).to_string()) .assert() .success() .get_output() .clone(); assert_eq!(output.stdout, b"{}"); assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr)); }