//! The read gate: a Read of a file on the secret list that fermata cannot mask is //! stopped under every `on_parse_error`, and `on_unparsed_read = "allow"` turns that off. //! A Grep with a `path` is a Read. All values are fake. use assert_cmd::Command; use dirigent_fermata::core::secrets::{parser::parse_content, FileFormat}; use serde_json::{json, Value}; use std::fs; use std::path::Path; use tempfile::TempDir; const VALUE: &str = "fake-value-in-the-file"; const SETTINGS: [&str; 3] = ["", "[enforcement]\non_parse_error = \"allow\"\n", "[enforcement]\non_parse_error = \"deny\"\n"]; struct Project { dir: TempDir, home: TempDir, } fn project(botsecrets: &str, files: &[(&str, &[u8])]) -> Project { let dir = tempfile::tempdir().unwrap(); fs::create_dir(dir.path().join(".git")).unwrap(); fs::write(dir.path().join(".botsecrets"), botsecrets).unwrap(); for (name, content) in files { let path = dir.path().join(name); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path, 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(); assert!(!String::from_utf8_lossy(&output.stderr).contains(VALUE)); 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 read(&self, file: &str) -> Value { self.pre("Read", json!({"file_path": self.dir.path().join(file)})) } fn check(&self, file: &str) -> i32 { Command::cargo_bin("fermata") .unwrap() .args(["check", "--op", "read", file]) .current_dir(self.dir.path()) .env("HOME", self.home.path()) .output() .unwrap() .status .code() .unwrap() } } fn reason(out: &Value) -> &str { assert_eq!(out["hookSpecificOutput"]["permissionDecision"], "deny", "{out}"); out["hookSpecificOutput"]["permissionDecisionReason"].as_str().unwrap() } /// What each row of the secret list that stays stopped holds. Row by row, with what each /// masks elsewhere: `tests/cli_hook_secret_formats.rs`. fn unmaskable_files() -> Vec<(&'static str, Vec)> { let private_pem = format!("-----BEGIN PRIVATE KEY-----\n{VALUE}\n-----END PRIVATE KEY-----\n").into_bytes(); vec![ ("id_rsa", private_pem.clone()), ("id_ed25519", private_pem.clone()), ("server.pem", private_pem.clone()), ("server.key", private_pem.clone()), ("config/master.key", format!("{VALUE}-with-words and spaces\n").into_bytes()), ("a.p12", b"\x30\x82fake".to_vec()), ("a.pfx", b"\x30\x82fake".to_vec()), ("terraform.tfstate", format!("{{\"outputs\":{{\"db\":{{\"value\":\"{VALUE}\"}}}}}}").into_bytes()), ("x.tfstate", format!("{{\"outputs\":{{\"db\":{{\"value\":\"{VALUE}\"}}}}}}").into_bytes()), (".netrc", format!("machine x login u password {VALUE}\n").into_bytes()), (".htpasswd", format!("u:{VALUE}\n").into_bytes()), ("secrets.txt", format!("{VALUE}\n").into_bytes()), ("credentials.bak", format!("{VALUE}\n").into_bytes()), ("secrets.toml~", format!("{VALUE}\n").into_bytes()), ] } #[test] fn a_read_of_a_file_it_cannot_mask_is_stopped_under_every_on_parse_error() { for setting in SETTINGS { for (name, content) in unmaskable_files() { let p = project(setting, &[(name, &content)]); let out = p.read(name); let text = reason(&out); assert!(text.contains(name), "{name} under {setting:?}: {text}"); assert!(text.contains("on_unparsed_read") && text.contains("ask the user"), "{text}"); assert!(!out.to_string().contains(VALUE), "{out}"); } } } #[test] fn on_unparsed_read_allow_lets_each_of_them_through() { for (name, content) in unmaskable_files() { let p = project("[enforcement]\non_unparsed_read = \"allow\"\n", &[(name, &content)]); assert_eq!(p.read(name), json!({}), "{name}"); } } /// A file with a parser that fails cannot be masked either. #[test] fn a_file_that_fails_to_parse_is_stopped() { for setting in SETTINGS { for (name, content) in [ (".env.gpg", b"\x85\x02\xff\xfe\x00fake".to_vec()), (".env", [0xff, 0xfe].into_iter().chain("API_TOKEN=fake-utf16-value\n".encode_utf16().flat_map(u16::to_le_bytes)).collect()), (".env.local", "API_TOKEN=fake-utf16-value\n".encode_utf16().flat_map(u16::to_le_bytes).collect()), ("secrets.toml", format!("api_token = \"{VALUE}\" broken [\n").into_bytes()), ("credentials.json", format!("{{\n// a comment\n\"api_token\": \"{VALUE}\"}}").into_bytes()), ] { let p = project(setting, &[(name, &content)]); let out = p.read(name); assert!(reason(&out).contains(name), "{out}"); assert!(!out.to_string().contains(VALUE), "{out}"); } } } /// `.env` and properties yield a value from nearly any line, so a file with lines and no /// entry holds something fermata does not understand. A comment or a blank line is nothing. #[test] fn an_env_file_with_lines_and_no_entry_is_stopped_and_an_empty_one_is_not() { let p = project("", &[(".env", format!("{VALUE} with no sign in it\n").as_bytes())]); assert!(reason(&p.read(".env")).contains(".env")); let props = "[files]\npatterns = [\"a.properties\"]\n"; let p = project(props, &[("a.properties", b"=fake-value-with-no-key\n")]); assert!(reason(&p.read("a.properties")).contains("a.properties")); for content in ["", "\n\n", "# only a comment\n\n"] { let p = project("", &[(".env", content.as_bytes())]); assert_eq!(p.read(".env"), json!({}), "{content:?}"); } let p = project(props, &[("a.properties", b"! a comment\n# another\n")]); assert_eq!(p.read("a.properties"), json!({})); } /// The files fermata can mask, and source named like a secret file. #[test] fn what_can_be_masked_or_is_source_passes() { for setting in SETTINGS { for (name, content) in [ (".env", format!("API_TOKEN={VALUE}\n")), ("secrets.toml", format!("api_token = \"{VALUE}\"\n")), ("secrets.rs", "pub fn load() {}\n".to_string()), ("credentials.ts", "export const x = 1;\n".to_string()), ("secrets.tf", "variable \"x\" {}\n".to_string()), ("secrets.tpl", "{{ x }}\n".to_string()), ("credentials.example", "API_TOKEN=\n".to_string()), ("secrets.d.ts", "export {};\n".to_string()), ("secrets.pyi", "def load() -> str: ...\n".to_string()), ("credentials.pyi", "def load() -> str: ...\n".to_string()), ("secrets.mdx", "# x\n".to_string()), ("secrets.scss", "a {}\n".to_string()), ("secrets.less", "a {}\n".to_string()), ("secrets.ps1", "Get-Date\n".to_string()), ("secrets.bat", "echo\n".to_string()), ("notes.txt", "x\n".to_string()), ] { let p = project(setting, &[(name, content.as_bytes())]); assert_eq!(p.read(name), json!({}), "{name} under {setting:?}"); } } } /// Python assignments are one kind of line in a source file. A module of functions has /// none, and that says nothing. #[test] fn a_python_file_of_functions_passes() { let source = "import os\n\ndef load():\n return os.environ[\"X\"]\n"; let p = project("", &[("secrets.py", source.as_bytes())]); assert_eq!(p.read("secrets.py"), json!({})); } const HELM: &str = "{{- if .Values.x }}\napi_token: {{ .Values.t }}\n{{- end }}\n"; /// A template that does not parse holds its values elsewhere. Read passes with the note, /// because a template can hold a literal value: a named limit. #[test] fn a_template_that_does_not_parse_passes_with_the_note() { assert!(parse_content(HELM, FileFormat::Yaml, Path::new("x")).is_err(), "the fixture must fail to parse"); let json_template = "{\"api_token\": {% if x %}\"a\"{% endif %}}"; assert!(parse_content(json_template, FileFormat::Json, Path::new("x")).is_err(), "the fixture must fail to parse"); for (name, content) in [("templates/secrets.yaml", HELM), ("secrets.yml", HELM), ("credentials.json", json_template)] { let p = project("", &[(name, content.as_bytes())]); assert_eq!(p.read(name), json!({}), "{name}"); let path = p.dir.path().join(name); let out = p.hook( "post-tool-use", json!({"tool_name": "Read", "tool_input": {"file_path": path}, "tool_response": {"type": "text", "file": {"filePath": path, "content": content, "numLines": 1, "startLine": 1, "totalLines": 1}}}), ); assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains(name), "{out}"); } } #[test] fn a_grep_with_a_path_is_a_read() { let p = project("", &[("id_rsa", b"fake key text"), ("src/a.txt", b"x")]); let path = p.dir.path().join("id_rsa"); assert!(reason(&p.pre("Grep", json!({"pattern": "x", "path": path}))).contains("id_rsa")); // A relative path, against the session's directory. let out = p.hook("pre-tool-use", json!({"tool_name": "Grep", "cwd": p.dir.path(), "tool_input": {"pattern": "x", "path": "id_rsa"}})); assert!(reason(&out).contains("id_rsa")); // A directory is no file the gate can judge, and no path is no read of anything named. assert_eq!(p.pre("Grep", json!({"pattern": "x", "path": p.dir.path().join("src")})), json!({})); assert_eq!(p.pre("Grep", json!({"pattern": "x"})), json!({})); // The path rules meet a Grep too. let p = project("", &[(".botignore", b"src/\n"), ("src/a.txt", b"x")]); assert!(reason(&p.pre("Grep", json!({"pattern": "x", "path": p.dir.path().join("src/a.txt")}))).contains("botignore")); } #[test] fn the_gate_stops_reads_and_nothing_else() { let p = project("", &[("id_rsa", b"fake key text")]); let path = p.dir.path().join("id_rsa"); assert_eq!(p.pre("Write", json!({"file_path": path, "content": "x"})), json!({})); assert_eq!(p.pre("Edit", json!({"file_path": path, "old_string": "a", "new_string": "b"})), json!({})); // A file that is not there yet has nothing to show. assert_eq!(p.read("id_ecdsa"), json!({})); } #[cfg(unix)] #[test] fn a_link_to_a_file_on_the_list_is_stopped() { let p = project("", &[("id_rsa", b"fake key text")]); std::os::unix::fs::symlink(p.dir.path().join("id_rsa"), p.dir.path().join("notes")).unwrap(); assert!(reason(&p.read("notes")).contains("id_rsa")); } #[test] fn a_check_of_the_read_op_meets_the_gate() { let p = project("", &[("id_rsa", b"fake key text"), ("a.txt", b"x")]); assert_eq!(p.check("id_rsa"), 1); assert_eq!(p.check("a.txt"), 0); } /// A `[[file]]` override with a format gives the file a parser, and that parser may fail. #[test] fn a_file_override_with_a_format_gives_the_gate_a_parser() { let config = "[[file]]\npath = \"secrets.txt\"\nformat = \"env\"\n"; let p = project(config, &[("secrets.txt", format!("API_TOKEN={VALUE}\n").as_bytes())]); assert_eq!(p.read("secrets.txt"), json!({})); let config = "[[file]]\npath = \"secrets.txt\"\nformat = \"json\"\n"; let p = project(config, &[("secrets.txt", format!("api_token = {VALUE}\n").as_bytes())]); assert!(reason(&p.read("secrets.txt")).contains("secrets.txt")); // No format means the file's name decides. let config = "[[file]]\npath = \"secrets.txt\"\n"; let p = project(config, &[("secrets.txt", format!("API_TOKEN={VALUE}\n").as_bytes())]); assert!(reason(&p.read("secrets.txt")).contains("secrets.txt")); } /// The list is the project's own: a file off the list is not stopped, one on it is. #[test] fn the_gate_follows_the_projects_list() { let p = project("[files]\npatterns = [\".env\", \"private/*\"]\n", &[("id_rsa", b"x"), ("private/notes.txt", b"x")]); assert_eq!(p.read("id_rsa"), json!({})); assert!(reason(&p.read("private/notes.txt")).contains("notes.txt")); } /// A `[files]` list with no usable pattern leaves the built-in list, keeps the rules beside /// it and says so. #[test] fn a_files_list_with_no_usable_pattern_leaves_the_default_list_and_keeps_the_rules() { let config = "[files]\npatterns = [\"a[\"]\n[policy.read]\npatterns = [\"blocked.txt\"]\n"; let files: &[(&str, &[u8])] = &[(".botignore", b"ignored.txt\n"), ("ignored.txt", b"x"), ("blocked.txt", b"x"), ("id_rsa", b"fake key text")]; let p = project(config, files); assert!(reason(&p.read("id_rsa")).contains("id_rsa")); assert!(reason(&p.read("ignored.txt")).contains(".botignore")); assert!(reason(&p.read("blocked.txt")).contains("blocked.txt")); assert_eq!(p.check("id_rsa"), 2); let response = json!({"stdout": "x", "stderr": "", "interrupted": false}); let note = p.hook("post-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "x"}, "tool_response": response})); assert!(note["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("a["), "{note}"); assert!(note["hookSpecificOutput"].get("updatedToolOutput").is_none(), "{note}"); // A tool that shows no text pays nothing for it. let quiet = p.hook("post-tool-use", json!({"tool_name": "Write", "tool_input": {}, "tool_response": {"type": "create"}})); assert_eq!(quiet, json!({})); let p = project(&format!("{config}[enforcement]\non_parse_error = \"deny\"\n"), files); assert!(reason(&p.read("id_rsa")).contains("[files]")); assert!(reason(&p.pre("Bash", json!({"command": "ls"}))).contains("[files]")); }