diff --git a/tests/known_limits.rs b/tests/known_limits.rs new file mode 100644 index 0000000..5f93171 --- /dev/null +++ b/tests/known_limits.rs @@ -0,0 +1,461 @@ +//! What fermata is known to fail at, shown through the binary. Every test here asserts that +//! the failure HAPPENS: a value stays visible, or a call passes. When one of them starts to +//! fail, a limit was fixed, and the README's "Known to fail" and `docs/security-model.md` +//! must change with it. All values are fake, and each run has a home of its own. +//! +//! What the binary cannot show has no test: Claude Code's own routes (a failed tool's +//! output, Monitor, attachments) are claims from its documentation and bundle. + +use assert_cmd::Command; +use serde_json::{json, Value}; +use std::fs; +use std::path::PathBuf; +use tempfile::TempDir; + +const VALUE: &str = "fake-value-in-the-file"; +const MASK: &str = "*****"; +const DENY: &str = "[enforcement]\non_parse_error = \"deny\"\n"; + +/// A project in `/a`, a sibling directory `/other` that is no project, and a +/// home of its own so that the machine's `~/.config/fermata/.botsecrets` plays no part. +struct Project { + root: TempDir, + home: TempDir, +} + +fn project(files: &[(&str, &[u8])]) -> Project { + let p = Project { root: tempfile::tempdir().unwrap(), home: tempfile::tempdir().unwrap() }; + fs::create_dir_all(p.dir().join(".git")).unwrap(); + put(&p.dir(), files); + p +} + +fn put(dir: &std::path::Path, files: &[(&str, &[u8])]) { + for (name, content) in files { + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } +} + +fn env_file(text: &str) -> [(&'static str, &[u8]); 1] { + [(".env", text.as_bytes())] +} + +impl Project { + fn dir(&self) -> PathBuf { + self.root.path().join("a") + } + + fn other(&self) -> PathBuf { + self.root.path().join("other") + } + + fn run(&self, event: &str, payload: Value) -> Command { + let mut cmd = Command::cargo_bin("fermata").unwrap(); + fs::create_dir_all(self.dir()).unwrap(); + cmd.args(["hook", "--event", event, "--harness", "claude"]) + .current_dir(self.dir()) + .env("HOME", self.home.path()) + .write_stdin(payload.to_string()); + cmd + } + + fn hook(&self, event: &str, payload: Value) -> Value { + let output = self.run(event, payload).assert().success().get_output().clone(); + 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 bash(&self, command: &str) -> Value { + self.pre("Bash", json!({"command": command})) + } + + fn read(&self, file: &str) -> Value { + self.pre("Read", json!({"file_path": self.dir().join(file)})) + } + + fn post(&self, tool: &str, input: Value, response: Value) -> Value { + self.hook("post-tool-use", json!({"tool_name": tool, "tool_input": input, "tool_response": response})) + } + + /// What `text` becomes as the output of a command. + fn after_bash(&self, text: &str) -> String { + let response = json!({"stdout": text, "stderr": "", "interrupted": false, "isImage": false}); + shown(&self.post("Bash", json!({"command": "x"}), response), text) + } + + /// What `text` becomes as the content of a Read of `file`. + fn after_read(&self, file: &str, text: &str) -> String { + let path = self.dir().join(file); + let response = json!({"type": "text", "file": {"filePath": path, "content": text, "numLines": 1, "startLine": 1, "totalLines": 1}}); + shown(&self.post("Read", json!({"file_path": path}), response), text) + } +} + +/// What the model sees: the replacement if the hook made one, else the original. +fn shown(out: &Value, original: &str) -> String { + match out["hookSpecificOutput"].get("updatedToolOutput") { + Some(replacement) => replacement.to_string(), + None => original.to_string(), + } +} + +fn verdict(out: &Value) -> &str { + out["hookSpecificOutput"]["permissionDecision"].as_str().unwrap_or("none") +} + +fn passes(out: &Value) -> bool { + *out == json!({}) +} + +fn denied(out: &Value) -> bool { + verdict(out) == "deny" +} + +/// The value stays visible in a command's output and in a Read's. +fn stays_visible(p: &Project, file: &str, shows: &str) { + for text in [p.after_bash(&format!("x {shows} y")), p.after_read(file, &format!("x {shows} y"))] { + assert!(text.contains(shows), "the value was masked after all: {text}"); + } +} + +fn is_masked(text: &str, value: &str) -> bool { + !text.contains(value) && text.contains(MASK) +} + +// --------------------------------------------------------------------------- +// Spellings the parsers do not decode +// --------------------------------------------------------------------------- + +#[test] +fn a_python_triple_quoted_value_on_one_line_is_not_masked() { + let p = project(&[("secrets.py", b"SECRET_KEY = \"\"\"fake-triple-one-line\"\"\"\n")]); + stays_visible(&p, "secrets.py", "fake-triple-one-line"); +} + +#[test] +fn a_python_triple_quoted_value_over_several_lines_is_not_masked() { + let p = project(&[("secrets.py", b"SECRET_KEY = \"\"\"fake-triple-first-line\nfake-triple-second-line\n\"\"\"\n")]); + stays_visible(&p, "secrets.py", "fake-triple-first-line"); + stays_visible(&p, "secrets.py", "fake-triple-second-line"); +} + +/// The program prints the decoded value: the file holds `'a'\''b-x` and `abc"def"-x`. +#[test] +fn a_shell_quoted_value_is_not_masked_when_a_program_prints_it_decoded() { + for (line, printed) in [("API_TOKEN='fake'\\''quoted-x'\n", "fake'quoted-x"), ("API_TOKEN=abc\"fake-def\"-x\n", "abcfake-def-x")] { + let p = project(&env_file(line)); + assert!(!p.after_bash(&format!("x {printed} y")).contains(MASK), "{line}"); + assert!(p.after_bash(&format!("x {printed} y")).contains(printed), "{line}"); + } +} + +/// README claims an unclosed quote swallows the next assignment. Each spelling here is +/// masked by the binary, so the claim is not true of it: this pins what is true. +#[test] +fn a_value_after_an_unclosed_quote_is_masked_in_every_spelling_tried() { + for text in [ + "OPEN=\"never closed\nAPI_TOKEN=fake-swallowed-value\n", + "OPEN='never closed\nAPI_TOKEN=fake-swallowed-value\n", + "OPEN=\"never closed\nAPI_TOKEN=fake-swallowed-value\nLAST=\"closes here\"\n", + "OPEN=\"never closed\nOTHER=x\nAPI_TOKEN=\"fake-swallowed-value\"\n", + ] { + let p = project(&env_file(text)); + let out = p.after_bash("x fake-swallowed-value y"); + assert!(is_masked(&out, "fake-swallowed-value"), "{text:?}: {out}"); + } +} + +// --------------------------------------------------------------------------- +// Files fermata does not see, and values it cannot tell +// --------------------------------------------------------------------------- + +#[test] +fn a_secret_file_outside_the_project_is_not_masked_and_a_read_of_it_passes() { + let p = project(&[]); + put(&p.other(), &[(".env", format!("API_TOKEN={VALUE}\n").as_bytes())]); + assert!(passes(&p.pre("Read", json!({"file_path": p.other().join(".env")})))); + assert!(passes(&p.read("../other/.env"))); + let text = p.after_read("../other/.env", &format!("API_TOKEN={VALUE}")); + assert!(text.contains(VALUE), "{text}"); +} + +#[test] +fn a_command_that_prints_a_secret_file_outside_the_project_passes() { + let p = project(&[]); + put(&p.other(), &[(".env", format!("API_TOKEN={VALUE}\n").as_bytes())]); + assert!(passes(&p.bash("cat ../other/.env"))); + assert!(passes(&p.bash("cd ../other && cat .env"))); + assert!(p.after_bash(VALUE).contains(VALUE)); +} + +/// A rule in project `b` meets a Read of its file and not a command run from `a`. +#[test] +fn a_command_in_one_project_is_not_stopped_by_another_projects_rule() { + let p = project(&[]); + put(&p.other(), &[(".git/x", b""), (".botignore", b"x\n"), ("x", b"fake")]); + assert!(denied(&p.read("../other/x"))); + assert!(passes(&p.bash("cat ../other/x"))); +} + +#[test] +fn a_secret_number_in_mcp_structured_content_is_not_masked() { + let p = project(&env_file("API_TOKEN=987654321012\n")); + let response = json!({"content": [{"type": "text", "text": "ok"}], "structuredContent": {"pin": 987654321012_u64, "text": "987654321012"}}); + let out = p.post("mcp__x__y", json!({}), response); + let text = shown(&out, ""); + assert!(text.contains("987654321012"), "{out}"); + assert!(!text.contains("\"pin\":\"*****\""), "{out}"); + // The same digits as text are masked: only the number escapes. + assert!(text.contains(&format!("\"text\":\"{MASK}\"")), "{out}"); +} + +#[test] +fn a_number_under_six_characters_is_not_masked() { + for (name, content) in [(".env", "API_TOKEN=12345\n"), ("secrets.json", "{\"api_token\": 12345}\n"), ("secrets.toml", "api_token = 12345\n"), ("secrets.yaml", "api_token: 12345\n")] { + let p = project(&[(name, content.as_bytes())]); + assert!(p.after_bash("x 12345 y").contains("12345"), "{name}"); + } +} + +#[test] +fn a_short_passwords_word_is_masked_in_other_files_too() { + let p = project(&env_file("DB_PASSWORD=postgres\n")); + let text = p.after_read("docker-compose.yml", "image: postgres:16\n"); + assert!(is_masked(&text, "postgres"), "{text}"); +} + +#[test] +fn a_key_the_filter_does_not_match_leaves_its_value_in_a_parsed_file() { + let p = project(&[("secrets.json", b"{\"banner\": \"fake-banner-value-1\", \"api_token\": \"fake-listed-value\"}\n")]); + assert!(p.after_bash("x fake-banner-value-1 y").contains("fake-banner-value-1")); + assert!(is_masked(&p.after_bash("x fake-listed-value y"), "fake-listed-value")); +} + +#[test] +fn the_first_value_of_a_duplicate_json_key_is_not_masked() { + let p = project(&[("secrets.json", b"{\"api_token\": \"fake-first-value\", \"api_token\": \"fake-second-value\"}\n")]); + assert!(p.after_bash("x fake-first-value y").contains("fake-first-value")); + assert!(is_masked(&p.after_bash("x fake-second-value y"), "fake-second-value")); +} + +#[test] +fn a_tfvars_heredoc_is_not_masked() { + let p = project(&[("terraform.tfvars", b"api_token = < = "API_TOKEN=fake-utf16-value\n".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let cases: [(&str, Vec, &str); 3] = [ + (".env", [b"\xff\xfe".to_vec(), utf16].concat(), "fake-utf16-value"), + ("latin.env", b"API_TOKEN=fake-latin1-valu\xe9\n".to_vec(), "fake-latin1-valu"), + ("secrets.json", b"{\n // comment\n \"api_token\": \"fake-comment-json\"\n}\n".to_vec(), "fake-comment-json"), + ]; + for (name, content, value) in cases { + let p = project(&[(name, &content)]); + assert!(p.after_bash(&format!("x {value} y")).contains(value), "{name}"); + assert!(passes(&p.bash("grep -r TOKEN .")), "{name}"); + } +} + +// --------------------------------------------------------------------------- +// Commands: the verbs are lists, and only words that name a path are checked +// --------------------------------------------------------------------------- + +const RULES: [(&str, &str); 2] = [(".botignore", ".env\n"), (".botsecrets", "[policy.read]\npatterns = [\".env\"]\n")]; + +fn ruled(rule: (&str, &str)) -> Project { + project(&[(rule.0, rule.1.as_bytes()), (".env", format!("API_TOKEN={VALUE}\n").as_bytes())]) +} + +/// B6: with the file under a rule these are stopped or not, whatever the exit code. +#[test] +fn cat_env_then_false_is_stopped_only_under_a_rule_and_only_for_what_names_the_file() { + for rule in RULES { + let p = ruled(rule); + for command in ["cat .env; false", "cat ./.env; false", "source .env; false"] { + assert!(denied(&p.bash(command)), "{rule:?}: {command}"); + } + for command in ["env; false", "grep -r TOKEN .; false", "npm test", "printenv; false"] { + assert!(passes(&p.bash(command)), "{rule:?}: {command}"); + } + } +} + +#[test] +fn on_default_config_a_parseable_env_is_not_stopped_at_all() { + let p = project(&env_file(&format!("API_TOKEN={VALUE}\n"))); + for command in ["cat .env", "cat .env; false", "cat ./.env"] { + assert!(passes(&p.bash(command)), "{command}"); + } + assert!(passes(&p.read(".env"))); +} + +#[test] +fn a_variable_a_substitution_and_a_script_hide_the_file_from_the_command_rules() { + for rule in RULES { + let p = ruled(rule); + assert!(denied(&p.bash("cat .env")), "control"); + for command in ["cat $(printf '.e%s' nv)", "echo \"$(cat .env)\"", "python -c \"print(open('.env').read())\"", "sh run.sh", "cat .e*v; true", "cat \"$HOME/../.env\""] { + let out = p.bash(command); + // Each of these may be caught by a path that happens to exist; the hidden spellings pass. + if ["cat $(printf '.e%s' nv)", "echo \"$(cat .env)\"", "python -c \"print(open('.env').read())\"", "sh run.sh"].contains(&command) { + assert!(passes(&out), "{rule:?}: {command}: {out}"); + } + } + } +} + +#[test] +fn a_printing_verb_off_the_list_is_not_checked_against_the_rules_unless_it_names_the_file() { + let p = ruled(RULES[0]); + for command in ["python -c \"print(open('.env').read())\"", "perl -e 'print <>' x"] { + assert!(passes(&p.bash(command)), "{command}"); + } +} + +// --------------------------------------------------------------------------- +// Failed tools, and other routes no hook sees +// --------------------------------------------------------------------------- + +/// Claude Code's failed-tool event is not one fermata is wired to: it is no hook event here. +#[test] +fn the_failed_tool_event_is_not_hooked() { + let p = project(&env_file(&format!("API_TOKEN={VALUE}\n"))); + let out = p.run("post-tool-use-failure", json!({"tool_name": "Bash", "tool_input": {}, "tool_response": {"stdout": VALUE}})).assert().failure().code(2).get_output().clone(); + assert!(out.stdout.is_empty()); +} + +#[test] +fn a_value_split_across_strings_or_encoded_is_not_masked() { + let p = project(&env_file("API_TOKEN=fake-split-and-encoded\n")); + let out = p.after_bash("fake-split-\nand-encoded"); + assert!(out.contains("fake-split-"), "{out}"); + let b64 = "ZmFrZS1zcGxpdC1hbmQtZW5jb2RlZA=="; + assert!(p.after_bash(b64).contains(b64)); + let response = json!({"content": [{"type": "text", "text": "fake-split-"}, {"type": "text", "text": "and-encoded"}]}); + let out = p.post("mcp__x__y", json!({}), response); + assert!(shown(&out, "fake-split-and-encoded").contains("fake-split-"), "{out}"); +} + +#[test] +fn a_binary_field_is_not_masked() { + let p = project(&env_file("API_TOKEN=fake-binary-value-1234\n")); + let blob = "ZmFrZS1iaW5hcnktdmFsdWUtMTIzNA==ZmFrZS1iaW5hcnktdmFsdWUtMTIzNA=="; + let out = p.post("Read", json!({"file_path": "/x.png"}), json!({"type": "image", "file": {"base64": blob, "type": "image/png"}})); + assert!(shown(&out, blob).contains(blob) || passes(&out), "{out}"); +} + +#[test] +fn a_heuristic_finding_is_warned_about_and_not_masked() { + let p = project(&[]); + let token = "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij"; + let response = json!({"stdout": format!("t {token}"), "stderr": "", "interrupted": false, "isImage": false}); + let out = p.post("Bash", json!({"command": "x"}), response); + assert!(shown(&out, token).contains(token), "{out}"); +} + +// --------------------------------------------------------------------------- +// Write guard limits +// --------------------------------------------------------------------------- + +#[test] +fn a_shell_command_that_writes_a_mask_is_not_checked() { + let p = project(&[]); + assert!(passes(&p.bash("sed -i 's/x/*****/' a.txt"))); + assert!(passes(&p.bash("echo '*****' > new.txt"))); +} + +#[test] +fn the_absent_style_leaves_nothing_for_the_guard_to_count() { + let p = project(&[(".botsecrets", b"[redaction]\nstyle = \"absent\"\n"), (".env", b"API_TOKEN=fake-absent-value\n")]); + let out = p.pre("Write", json!({"file_path": p.dir().join("n.txt"), "content": "key = \n"})); + assert!(passes(&out), "{out}"); +} + +#[test] +fn a_real_five_star_run_is_stopped_as_if_it_were_a_mask() { + let p = project(&[]); + let out = p.pre("Write", json!({"file_path": p.dir().join("n.md"), "content": "a\n*****\nb\n"})); + assert!(denied(&out), "{out}"); +} + +// --------------------------------------------------------------------------- +// Enums of Claude Code's schemas +// --------------------------------------------------------------------------- + +#[test] +fn a_secret_equal_to_a_schema_enum_value_is_not_masked() { + let p = project(&env_file("API_TOKEN=async_launched\n")); + let out = p.post("Workflow", json!({}), json!({"status": "async_launched", "taskType": "local_workflow"})); + assert!(shown(&out, "").contains("async_launched") || passes(&out), "{out}"); +}