diff --git a/src/core/secrets/manifest.rs b/src/core/secrets/manifest.rs index dc465e1..cbb480f 100644 --- a/src/core/secrets/manifest.rs +++ b/src/core/secrets/manifest.rs @@ -401,8 +401,9 @@ fn discover_files(patterns: &[String], root: &Path) -> Result, Mani Err(_) => continue, }; - // Only interested in files. - if !entry.file_type().is_file() { + // Files, and links to files: a link to a directory is not followed, a dangling + // one has nothing to read. + if !entry.file_type().is_file() && !(entry.path_is_symlink() && entry.path().is_file()) { continue; } diff --git a/src/core/secrets/parser.rs b/src/core/secrets/parser.rs index 047f74b..4d91dcf 100644 --- a/src/core/secrets/parser.rs +++ b/src/core/secrets/parser.rs @@ -13,6 +13,7 @@ use globset::Glob; use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use thiserror::Error; +use serde::Deserialize; // --------------------------------------------------------------------------- // Errors @@ -217,8 +218,11 @@ fn parse_env(content: &str, source: &Path) -> Result, ParseErro let trimmed = lines[i].trim(); i += 1; - // Skip blank lines and comments. - if trimmed.is_empty() || trimmed.starts_with('#') { + // Skip blank lines and comments, but a commented-out assignment is a value + // somebody once used: it is kept as an entry. + let commented = trimmed.starts_with('#'); + let trimmed = if commented { commented_assignment(trimmed).unwrap_or("") } else { trimmed }; + if trimmed.is_empty() { continue; } @@ -239,7 +243,8 @@ fn parse_env(content: &str, source: &Path) -> Result, ParseErro } let raw_value = raw_value.trim(); - let (value, raw) = match quoted_env_value(raw_value, &lines[i..]) { + let following = if commented { &[][..] } else { &lines[i..] }; + let (value, raw) = match quoted_env_value(raw_value, following) { Some(quoted) => { i += quoted.extra_lines; let value = if quoted.quote == '"' { unescape("ed.inner) } else { quoted.inner.clone() }; @@ -257,6 +262,18 @@ fn parse_env(content: &str, source: &Path) -> Result, ParseErro Ok(entries) } +/// The `[export ]IDENT=VALUE` a comment holds, or `None` for prose. An unquoted value +/// has no whitespace, so `# TOKEN=abc is the format` is a sentence, not an assignment. +fn commented_assignment(line: &str) -> Option<&str> { + let rest = line.trim_start_matches('#').trim(); + let assignment = rest.strip_prefix("export ").map_or(rest, str::trim_start); + let (key, value) = assignment.split_once('=')?; + let ident = key.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + let plain = !value.is_empty() && !value.contains(char::is_whitespace); + (ident && (plain || quoted_env_value(value, &[]).is_some())).then_some(assignment) +} + /// Shortest single token of a key file that counts as a secret: a word such as `localhost` /// must not be masked in every output. const MIN_OPAQUE_TOKEN_LEN: usize = 16; @@ -686,14 +703,14 @@ fn flatten_json_value( /// Parse YAML files. Nested mappings are flattened with dot separators. /// String and number values are extracted. fn parse_yaml(content: &str, source: &Path) -> Result, ParseError> { - let value: serde_yaml::Value = - serde_yaml::from_str(content).map_err(|e| ParseError::Format { + let mut entries = Vec::new(); + for document in serde_yaml::Deserializer::from_str(content) { + let value = serde_yaml::Value::deserialize(document).map_err(|e| ParseError::Format { path: source.to_path_buf(), message: format_message("YAML", e.location().map(|l| l.line())), })?; - - let mut entries = Vec::new(); - flatten_yaml_value(&value, "", source, &mut entries); + flatten_yaml_value(&value, "", source, &mut entries); + } add_file_spellings(&mut entries, yaml_tokens(content)); add_yaml_block_spellings(&mut entries, content); Ok(entries) @@ -745,14 +762,15 @@ fn flatten_yaml_value( } } -/// Parse Python-style assignment lines: `KEY = "value"` or `KEY = 'value'`. +/// Parse Python-style assignment lines: `KEY = "value"`, `KEY: str = 'value'`, with a +/// comment after the closing quote or none. /// /// This is heuristic — lines that don't match the pattern are silently skipped. fn parse_python_assignments( content: &str, source: &Path, ) -> Result, ParseError> { - let re = regex::Regex::new(r#"(?i)^([A-Z_][A-Z0-9_]*)\s*=\s*['"](.+?)['"]\s*$"#) + let re = regex::Regex::new(r#"(?i)^([A-Z_][A-Z0-9_]*)\s*(?::\s*[A-Z_][A-Z0-9_., \[\]|]*?)?\s*=\s*(?:"(.+?)"|'(.+?)')\s*(?:#.*)?$"#) .expect("valid regex"); let mut entries = Vec::new(); @@ -764,7 +782,8 @@ fn parse_python_assignments( } if let Some(caps) = re.captures(trimmed) { // The file's text first: a Python value is kept as written. - push_spellings(&mut entries, &caps[1], caps[2].to_string(), unescape(&caps[2]), source); + let value = caps.get(2).or_else(|| caps.get(3)).map_or("", |m| m.as_str()); + push_spellings(&mut entries, &caps[1], value.to_string(), unescape(value), source); } } diff --git a/tests/cli_hook_r2_values.rs b/tests/cli_hook_r2_values.rs new file mode 100644 index 0000000..ff55efd --- /dev/null +++ b/tests/cli_hook_r2_values.rs @@ -0,0 +1,252 @@ +//! 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 +// --------------------------------------------------------------------------- + +#[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"))); +}