Files
fermata/tests/cli_hook_r2_values.rs
T
g4borg 6bf602aa6a fix(fermata): a bad glob costs only itself; commands read what is there, behind a wrapper or a shell
- A glob in [files] or [policy] that does not compile costs only that pattern while open,
  with a note by name beside text output. A [files] list with none left leaves the built-in
  list. Under deny the refusal stays, and the channel filter stays strict.
- A file named `credentials` is on the default list, at any depth.
- A word with a separator counts only if the path is there, the shell may expand it, or a
  redirect names it: packages, branches and hosts' paths are not denied.
- timeout, nice, ionice, stdbuf, xargs and busybox are prefixes; `2>&1` stays in its segment.
- `bash|sh|zsh -c` and `eval` arguments are read as command lines.
- A `<<` with no closing line is no heredoc. A commented line's own comment is dropped.
  Text holding NUL fails to parse. The unknown-field message says so. Durations are bound
  to under 6 characters. More source extensions pass the gate.
- Removed: HarnessAdapter::post_tool_op (dead since 3C was dropped), tool_op back inline.
2026-11-07 02:00:45 +01:00

259 lines
9.9 KiB
Rust

//! The R-2 rows of values a secret file holds in a spelling the parsers missed: a commented
//! `.env` line, a symlinked `.env`, a second YAML document, a Python line with a trailing
//! comment or an annotation. Each is masked in what a Read and a command show, under the
//! default and under `deny`, with Read passing the file. All values are fake.
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 SETTINGS: [&str; 2] = ["", "[enforcement]\non_parse_error = \"deny\"\n"];
const DENY: &str = SETTINGS[1];
struct Project {
dir: TempDir,
home: TempDir,
}
fn project(botsecrets: &str, files: &[(&str, &str)]) -> 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 {
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();
serde_json::from_slice(&output.stdout).unwrap()
}
fn path(&self, name: &str) -> PathBuf {
self.dir.path().join(name)
}
fn pre_read(&self, name: &str) -> Value {
self.hook("pre-tool-use", json!({"tool_name": "Read", "tool_input": {"file_path": self.path(name)}}))
}
fn post_read(&self, name: &str, text: &str) -> Value {
let path = self.path(name);
self.hook(
"post-tool-use",
json!({"tool_name": "Read", "tool_input": {"file_path": path}, "tool_response": {"type": "text", "file": {"filePath": path, "content": text, "numLines": 1, "startLine": 1, "totalLines": 1}}}),
)
}
fn post_bash(&self, text: &str) -> Value {
self.hook(
"post-tool-use",
json!({"tool_name": "Bash", "tool_input": {"command": "echo $X"}, "tool_response": {"stdout": text, "stderr": "", "interrupted": false, "isImage": false}}),
)
}
}
fn replaced(out: &Value) -> bool {
out["hookSpecificOutput"].get("updatedToolOutput").is_some()
}
fn denied(out: &Value) -> bool {
out["hookSpecificOutput"]["permissionDecision"] == "deny"
}
/// A Read passes the file, and `value` is masked in what a Read and a command show.
fn masked(setting: &str, files: &[(&str, &str)], read: &str, value: &str) {
let p = project(setting, files);
let label = format!("{files:?} under {setting:?}");
assert_eq!(p.pre_read(read), json!({}), "{label}");
for out in [p.post_read(read, &format!("x {value} y")), p.post_bash(&format!("x {value} y"))] {
assert!(replaced(&out), "{label}: nothing masked: {out}");
assert!(!out.to_string().contains(value) && out.to_string().contains(MASK), "{label}: {out}");
}
}
fn masked_in_both(files: &[(&str, &str)], read: &str, value: &str) {
for setting in SETTINGS {
masked(setting, files, read, value);
}
}
// ---------------------------------------------------------------------------
// Commented `.env` lines
// ---------------------------------------------------------------------------
/// A commented line with a comment of its own, as a live line may have.
#[test]
fn a_commented_assignment_with_a_trailing_comment_is_masked() {
masked_in_both(&[(".env", &format!("# API_TOKEN={VALUE} # old\n"))], ".env", VALUE);
}
#[test]
fn a_commented_assignment_is_masked() {
for line in [
format!("#API_TOKEN={VALUE}\n"),
format!("# API_TOKEN={VALUE}\n"),
format!("# export API_TOKEN={VALUE}\n"),
format!("#API_TOKEN=\"{VALUE}\"\n"),
format!("## API_TOKEN='{VALUE}'\n"),
] {
masked_in_both(&[(".env", &line)], ".env", VALUE);
}
}
#[test]
fn a_prose_comment_adds_no_entry() {
for line in ["# API_TOKEN=fake-prose-value is the format\n", "# set API_TOKEN=fake-prose-value first\n", "# API_TOKEN = fake-prose-value\n"] {
for setting in SETTINGS {
let p = project(setting, &[(".env", line)]);
let out = p.post_bash("x fake-prose-value y");
assert!(!replaced(&out), "{line:?} under {setting:?}: {out}");
}
}
}
// ---------------------------------------------------------------------------
// Symlinks
// ---------------------------------------------------------------------------
/// The target lies outside the patterns and outside the project: only the link is found.
#[test]
fn a_symlinked_env_is_masked() {
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("shared.conf"), format!("API_TOKEN={VALUE}\n")).unwrap();
for setting in SETTINGS {
let p = project(setting, &[]);
std::os::unix::fs::symlink(outside.path().join("shared.conf"), p.path(".env")).unwrap();
// The link's target is `shared.conf`, a name no pattern lists.
assert_eq!(p.pre_read(".env"), json!({}), "{setting:?}");
for out in [p.post_read(".env", &format!("x {VALUE} y")), p.post_bash(&format!("x {VALUE} y"))] {
assert!(replaced(&out) && !out.to_string().contains(VALUE), "{setting:?}: {out}");
}
}
}
#[test]
fn a_symlink_to_a_relative_target_is_masked() {
for setting in SETTINGS {
let p = project(setting, &[("shared.conf", &format!("API_TOKEN={VALUE}\n"))]);
std::os::unix::fs::symlink("shared.conf", p.path(".env")).unwrap();
let out = p.post_bash(&format!("x {VALUE} y"));
assert!(replaced(&out) && !out.to_string().contains(VALUE), "{setting:?}: {out}");
}
}
#[test]
fn a_dangling_symlink_is_ignored() {
for setting in SETTINGS {
let p = project(setting, &[(".env", &format!("API_TOKEN={VALUE}\n"))]);
std::os::unix::fs::symlink("nowhere.conf", p.path("secrets.toml")).unwrap();
let out = p.post_bash(&format!("x {VALUE} y"));
assert!(replaced(&out), "{setting:?}: the real file stopped masking: {out}");
assert!(!p.post_bash("clean").to_string().contains("secrets.toml"), "{setting:?}");
}
}
#[test]
fn a_symlinked_directory_is_not_followed() {
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join(".env"), format!("API_TOKEN={VALUE}\n")).unwrap();
let p = project("", &[]);
std::os::unix::fs::symlink(outside.path(), p.path("linked")).unwrap();
assert!(!replaced(&p.post_bash(&format!("x {VALUE} y"))));
}
/// A link whose target will not parse is a secret file that failed, like any other.
#[test]
fn a_symlinked_env_that_will_not_parse_is_stopped_under_deny_and_named_otherwise() {
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("broken.conf"), b"\xff\xfe\x00bad").unwrap();
let link = |setting: &str| {
let p = project(setting, &[(".env", "")]);
fs::remove_file(p.path(".env")).unwrap();
std::os::unix::fs::symlink(outside.path().join("broken.conf"), p.path(".env")).unwrap();
p
};
let p = link(DENY);
assert!(denied(&p.pre_read(".env")));
assert!(denied(&p.hook("pre-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "cat .env"}}))));
let p = link("");
let out = p.post_read("x", "x");
let note = out["hookSpecificOutput"]["additionalContext"].as_str().unwrap_or_default();
assert!(note.contains(".env"), "{out}");
}
// ---------------------------------------------------------------------------
// Multi-document YAML
// ---------------------------------------------------------------------------
#[test]
fn every_yaml_document_is_masked() {
let content = format!("api_token: {VALUE}\n---\napi_key: fake-second-document-value\n---\nother:\n db_password: fake-third-document-value\n");
for value in [VALUE, "fake-second-document-value", "fake-third-document-value"] {
masked_in_both(&[("secrets.yaml", &content)], "secrets.yaml", value);
}
}
#[test]
fn a_leading_document_marker_and_an_end_marker_parse() {
let content = format!("---\napi_token: {VALUE}\n...\n---\napi_key: fake-second-document-value\n");
masked_in_both(&[("secrets.yml", &content)], "secrets.yml", "fake-second-document-value");
}
// ---------------------------------------------------------------------------
// Python
// ---------------------------------------------------------------------------
#[test]
fn a_python_line_with_a_trailing_comment_is_masked() {
for line in [
format!("API_TOKEN = \"{VALUE}\" # prod\n"),
format!("API_TOKEN = '{VALUE}' # prod\n"),
format!("API_TOKEN = \"{VALUE}\"#prod\n"),
format!("API_TOKEN = \"{VALUE}\" # say \"hi\"\n"),
] {
masked_in_both(&[("secrets.py", &line)], "secrets.py", VALUE);
}
}
#[test]
fn a_python_annotation_is_masked() {
for line in [
format!("API_TOKEN: str = \"{VALUE}\"\n"),
format!("API_TOKEN : str = '{VALUE}' # note\n"),
format!("API_TOKEN: Final[str] = \"{VALUE}\"\n"),
format!("API_TOKEN: Optional[str]=\"{VALUE}\"\n"),
] {
masked_in_both(&[("secrets.py", &line)], "secrets.py", VALUE);
}
}
/// The value keeps its `#`; the comment is only what follows the closing quote.
#[test]
fn a_hash_inside_the_quotes_stays_in_the_value() {
masked_in_both(&[("secrets.py", "API_TOKEN = \"fake-a#b-value\" # note\n")], "secrets.py", "fake-a#b-value");
masked_in_both(&[("secrets.py", "API_TOKEN = \"fake-a#b-value\"\n")], "secrets.py", "fake-a#b-value");
}
#[test]
fn python_code_that_is_no_assignment_adds_nothing() {
let p = project("", &[("secrets.py", "def f(x: str = \"fake-default-value\"):\n return x\n")]);
assert!(!replaced(&p.post_bash("x fake-default-value y")));
}