diff --git a/src/core/secrets/manifest.rs b/src/core/secrets/manifest.rs index 16deb35..42ccf42 100644 --- a/src/core/secrets/manifest.rs +++ b/src/core/secrets/manifest.rs @@ -39,10 +39,11 @@ impl ManifestError { // Manifest // --------------------------------------------------------------------------- -/// The complete set of known secrets discovered from a project. +/// The complete set of known secrets discovered from a project, one entry per +/// spelling: a value's file text, its decoded text, its escaped forms and the lines +/// of a multi-line value each have their own (see [`spellings`]). /// -/// Entries are sorted by value length descending (longest first) so the -/// redactor replaces the most specific match before shorter substrings. +/// Entries are sorted by value length descending (longest first). #[derive(Debug, Clone)] pub struct Manifest { entries: Vec, @@ -52,6 +53,70 @@ pub struct Manifest { /// redaction (e.g. `"yes"`, `"on"`, `"42"`). const MIN_VALUE_LEN: usize = 4; +/// Shortest line of a multi-line value that is a spelling of its own, for output that +/// shows the value in part: a Read with a line range, a grep, a diff. +/// +/// The value is whole only in a file's bytes, so its lines must match alone, and a line +/// matches everywhere. PEM and base64 bodies have lines of 64 or 76 characters; below 8 +/// sit what also appears in ordinary text (`}`, `end`, `true`, `prod`). The price is the +/// tail of a body shorter than 8, which still passes when read away from the rest: +/// a few characters of a key. +const MIN_LINE_LEN: usize = 8; + +/// The value's own text and every form it takes elsewhere. The file's raw text comes +/// from [`super::parser`], which gives it its own entry; it comes through here as well. +fn spellings(value: &str) -> Vec { + let mut forms = vec![value.to_string()]; + let trimmed = value.trim_end_matches(['\n', '\r']); + for text in [value, trimmed] { + forms.push(text.to_string()); + // As a JSON string (a credentials file, a tool's JSON output). + if let Ok(quoted) = serde_json::to_string(text) { + forms.push(quoted[1..quoted.len() - 1].to_string()); + } + // With line ends written as `\n`, the form `.env` files and shells use. + forms.push(text.replace('\r', "\\r").replace('\n', "\\n").replace('\t', "\\t")); + // The same text from a file with Windows line ends. + if text.contains('\n') && !text.contains('\r') { + forms.push(text.replace('\n', "\r\n")); + } + } + if value.contains('\n') { + forms.extend(value.lines().map(str::trim).filter(|line| is_secret_line(line)).map(str::to_string)); + } + forms +} + +/// Whether a line of a multi-line value is worth masking alone. PEM armor names a +/// format, and the same words stand in scripts and docs. A line with no letter or +/// digit (`--------`) is layout. +fn is_secret_line(line: &str) -> bool { + let armor = (line.starts_with("-----BEGIN ") || line.starts_with("-----END ")) && line.ends_with("-----"); + line.len() >= MIN_LINE_LEN && !armor && line.chars().any(char::is_alphanumeric) +} + +/// One entry per spelling, deduplicated, longest first, none too short to mask. +fn finish(entries: Vec) -> Vec { + let mut entries: Vec = entries + .into_iter() + .flat_map(|entry| { + spellings(&entry.value).into_iter().map(move |value| SecretEntry { value, ..entry.clone() }) + }) + .collect(); + + // Deduplicate (same key + value from different discovery paths). + entries.sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.value.cmp(&b.value))); + entries.dedup_by(|a, b| a.key == b.key && a.value == b.value); + + // Sort by value length descending (longest first for redaction). + entries.sort_by(|a, b| b.value.len().cmp(&a.value.len())); + + // Remove entries with very short values to avoid false replacements. + entries.retain(|e| e.value.len() >= MIN_VALUE_LEN); + + entries +} + /// File name endings of the working files editors leave beside what they edit: /// Kate's swap file and the `~` backup of vim and emacs. Vim's swap names are /// [`is_vim_swap`]. @@ -163,40 +228,22 @@ impl Manifest { } } - // 5. Deduplicate (same key + value from different discovery paths). - entries.sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.value.cmp(&b.value))); - entries.dedup_by(|a, b| a.key == b.key && a.value == b.value); - - // 6. Sort by value length descending (longest first for redaction). - entries.sort_by(|a, b| b.value.len().cmp(&a.value.len())); - - // 7. Remove entries with very short values to avoid false replacements. - entries.retain(|e| e.value.len() >= MIN_VALUE_LEN); - - Ok(Self { entries }) + // 5. Every spelling, deduplicated, longest first. + Ok(Self { entries: finish(entries) }) } /// Build a manifest from a pre-built list of secret entries. /// /// Applies the same post-processing as [`Manifest::build`]: + /// - Adds an entry per other spelling of each value. /// - Deduplicates entries with the same key and value. /// - Sorts by value length descending (longest first for redaction). /// - Removes entries with values shorter than 4 characters. /// /// Useful for testing and for library consumers that obtain secrets /// from sources other than filesystem discovery. - pub fn from_entries(mut entries: Vec) -> Self { - // Deduplicate (same key + value). - entries.sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.value.cmp(&b.value))); - entries.dedup_by(|a, b| a.key == b.key && a.value == b.value); - - // Sort by value length descending (longest first for redaction). - entries.sort_by(|a, b| b.value.len().cmp(&a.value.len())); - - // Remove entries with very short values to avoid false replacements. - entries.retain(|e| e.value.len() >= MIN_VALUE_LEN); - - Self { entries } + pub fn from_entries(entries: Vec) -> Self { + Self { entries: finish(entries) } } /// Build an empty manifest (no secrets known). @@ -216,7 +263,7 @@ impl Manifest { self.entries.is_empty() } - /// Number of known secrets. + /// Number of known spellings of secrets. pub fn len(&self) -> usize { self.entries.len() } diff --git a/src/core/secrets/parser.rs b/src/core/secrets/parser.rs index 5d434a0..1d451b5 100644 --- a/src/core/secrets/parser.rs +++ b/src/core/secrets/parser.rs @@ -3,6 +3,11 @@ //! Reads secret files (`.env`, TOML, JSON, YAML, Python assignments, //! Java `.properties`) and extracts key-value pairs as [`SecretEntry`] items. //! Nested structures are flattened with dot-separated keys. +//! +//! A value gets one entry per spelling the file gives it: the decoded text first, +//! then the text as it stands in the file when that differs (`\n` in a JSON string, +//! a YAML block with its indentation). A tool that reads the file shows the second, +//! a program that loads it the first. [`super::manifest`] adds the derived spellings. use globset::Glob; use std::path::{Path, PathBuf}; @@ -63,6 +68,12 @@ pub struct SecretEntry { pub source: PathBuf, } +/// Shortest number kept as a secret. A number under a key that looks secret is often +/// a setting (`CACHE_KEY_TTL: 3600`), and masking `3600` in every output does more harm +/// than it prevents: a secret number that short is guessed anyway. Quoted values keep +/// the general minimum of the manifest. +const MIN_NUMBER_LEN: usize = 6; + /// Supported secret-file formats. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FileFormat { @@ -172,13 +183,17 @@ pub fn parse_content( /// Parse `.env` / dotenv files. /// -/// Supports `KEY=VALUE`, `KEY="VALUE"`, `KEY='VALUE'`, and the `export` -/// prefix. Comments (`#`) and empty lines are skipped. +/// Supports `KEY=VALUE`, `KEY="VALUE"`, `KEY='VALUE'`, quoted values over several +/// lines, a comment after a value and the `export` prefix. Comments (`#`) and empty +/// lines are skipped. fn parse_env(content: &str, source: &Path) -> Result, ParseError> { let mut entries = Vec::new(); + let lines: Vec<&str> = content.lines().collect(); + let mut i = 0; - for line in content.lines() { - let trimmed = line.trim(); + while i < lines.len() { + let trimmed = lines[i].trim(); + i += 1; // Skip blank lines and comments. if trimmed.is_empty() || trimmed.starts_with('#') { @@ -201,45 +216,301 @@ fn parse_env(content: &str, source: &Path) -> Result, ParseErro continue; } - let value = strip_env_value(raw_value); + let raw_value = raw_value.trim(); + let (value, raw) = match quoted_env_value(raw_value, &lines[i..]) { + Some(quoted) => { + i += quoted.extra_lines; + let value = if quoted.quote == '"' { unescape("ed.inner) } else { quoted.inner.clone() }; + (value, quoted.inner) + } + None => { + let raw = strip_env_comment(raw_value).to_string(); + (unescape_shell_word(&raw), raw) + } + }; - entries.push(SecretEntry { - key, - value, - source: source.to_path_buf(), - }); + push_spellings(&mut entries, &key, value, raw, source); } Ok(entries) } -/// Strip surrounding quotes and trailing whitespace from an env value. -fn strip_env_value(raw: &str) -> String { - let trimmed = raw.trim(); +/// A quoted `.env` value: the text between the quotes, as written. +struct QuotedEnvValue { + quote: char, + inner: String, + /// Lines used after the one holding the key. + extra_lines: usize, +} - // Double-quoted value. - if trimmed.starts_with('"') && trimmed.ends_with('"') && trimmed.len() >= 2 { - let inner = &trimmed[1..trimmed.len() - 1]; - // Interpret common escape sequences. - return inner.replace("\\n", "\n").replace("\\t", "\t"); +/// The quoted value starting `raw`, closed on this line or on a later one. +/// +/// The closing quote is one that only a comment or nothing follows, so `"a"b"` holds +/// `a"b`. A value running over lines closes at the first quote on a later line, and +/// when more text follows that quote there is no such value: an opening quote nobody +/// closed must not swallow `NEXT="value"` below it. +fn quoted_env_value(raw: &str, following: &[&str]) -> Option { + let quote = raw.chars().next().filter(|c| matches!(c, '"' | '\''))?; + let body = &raw[1..]; + + let on_line = quote_positions(body, quote); + if let Some(&end) = on_line.iter().find(|&&end| ends_env_value(&body[end + 1..])) { + return Some(QuotedEnvValue { quote, inner: body[..end].to_string(), extra_lines: 0 }); + } + if !on_line.is_empty() { + return None; } - // Single-quoted value (literal, no escapes). - if trimmed.starts_with('\'') && trimmed.ends_with('\'') && trimmed.len() >= 2 { - return trimmed[1..trimmed.len() - 1].to_string(); + let mut inner = body.to_string(); + for (n, line) in following.iter().enumerate() { + inner.push('\n'); + if let Some(&end) = quote_positions(line, quote).first() { + if !ends_env_value(&line[end + 1..]) { + return None; + } + inner.push_str(&line[..end]); + return Some(QuotedEnvValue { quote, inner, extra_lines: n + 1 }); + } + inner.push_str(line); + } + None +} + +/// Byte offsets of the closing-capable quotes in `text`. A backslash escapes in double +/// quotes and is plain text in single quotes. +fn quote_positions(text: &str, quote: char) -> Vec { + let mut positions = Vec::new(); + let mut chars = text.char_indices(); + while let Some((at, c)) = chars.next() { + if c == '\\' && quote == '"' { + chars.next(); + } else if c == quote { + positions.push(at); + } + } + positions +} + +/// Whether what follows a closing quote leaves the value complete. +fn ends_env_value(rest: &str) -> bool { + let rest = rest.trim_start(); + rest.is_empty() || rest.starts_with('#') +} + +/// An unquoted value without its inline comment. +fn strip_env_comment(raw: &str) -> &str { + let comment = raw + .char_indices() + .find(|&(at, c)| c == '#' && raw[..at].ends_with([' ', '\t'])) + .map(|(at, _)| at); + match comment { + Some(at) => raw[..at].trim_end(), + None => raw, + } +} + +/// Backslash escapes as dotenv loaders and most languages read them. An unknown +/// escape stays as written. +fn unescape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some('u') => { + let hex: String = chars.clone().take(4).collect(); + match u32::from_str_radix(&hex, 16).ok().filter(|_| hex.len() == 4).and_then(char::from_u32) { + Some(decoded) => { + out.push(decoded); + chars.nth(3); + } + None => out.push_str("\\u"), + } + } + Some(other) if other.is_ascii_punctuation() || other == ' ' => out.push(other), + Some(other) => { + out.push('\\'); + out.push(other); + } + None => out.push('\\'), + } + } + out +} + +/// An unquoted word as a shell reads it: a backslash keeps the next character. +fn unescape_shell_word(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + if c == '\\' { + out.extend(chars.next()); + } else { + out.push(c); + } + } + out +} + +/// Push `value`, and `raw` as a second entry of the same key if the file spells it +/// differently. +fn push_spellings(entries: &mut Vec, key: &str, value: String, raw: String, source: &Path) { + let differs = raw != value; + entries.push(SecretEntry { key: key.to_string(), value, source: source.to_path_buf() }); + if differs { + entries.push(SecretEntry { key: key.to_string(), value: raw, source: source.to_path_buf() }); + } +} + +// --------------------------------------------------------------------------- +// The spellings a file gives its values +// --------------------------------------------------------------------------- + +/// Adds an entry per `(decoded, raw)` token of the file whose decoded text is the value +/// of an entry. The parsers of JSON, TOML and YAML keep no source text, so the file is +/// scanned for its literals again: a literal only counts when it decodes to a known value, +/// which is why a scan that misreads a corner of the format finds nothing rather than +/// something wrong. +fn add_file_spellings(entries: &mut Vec, tokens: Vec<(String, String)>) { + let mut added = Vec::new(); + for entry in entries.iter() { + for (_, raw) in tokens.iter().filter(|(decoded, raw)| *decoded == entry.value && *raw != entry.value) { + added.push(SecretEntry { key: entry.key.clone(), value: raw.clone(), source: entry.source.clone() }); + } + } + entries.append(&mut added); +} + +/// The string and number literals of a JSON text. +fn json_tokens(content: &str) -> Vec<(String, String)> { + let literal = regex::Regex::new(r#"(?s)"(?:[^"\\]|\\.)*"|-?[0-9][0-9.eE+-]*"#).expect("valid regex"); + literal + .find_iter(content) + .filter_map(|m| { + let text = m.as_str(); + if text.starts_with('"') { + let decoded: String = serde_json::from_str(text).ok()?; + Some((decoded, text[1..text.len() - 1].to_string())) + } else { + let number: serde_json::Number = serde_json::from_str(text).ok()?; + Some((number.to_string(), text.to_string())) + } + }) + .collect() +} + +/// The string and number literals of a TOML text. Strings and comments come first in +/// the pattern, so what they hold is not read as a number. +fn toml_tokens(content: &str) -> Vec<(String, String)> { + let literal = regex::Regex::new( + r#"(?s)"""(.*?)"""|'''(.*?)'''|"((?:[^"\\\n]|\\.)*)"|'([^'\n]*)'|#[^\n]*|([-+]?[0-9][0-9a-zA-Z_.+:-]*)"#, + ) + .expect("valid regex"); + literal + .captures_iter(content) + .filter_map(|caps| { + let whole = caps.get(0)?.as_str(); + let inner = (1..=5).find_map(|n| caps.get(n))?.as_str(); + let table: toml::Table = format!("x = {whole}").parse().ok()?; + let decoded = match table.get("x")? { + toml::Value::String(s) => s.clone(), + toml::Value::Integer(n) => n.to_string(), + toml::Value::Float(n) => n.to_string(), + _ => return None, + }; + // TOML drops a newline right after the opening delimiter. + Some((decoded, inner.strip_prefix('\n').unwrap_or(inner).to_string())) + }) + .collect() +} + +/// The quoted strings and plain numbers of a YAML text, each where a value can begin, +/// so an apostrophe in plain text opens nothing. +fn yaml_tokens(content: &str) -> Vec<(String, String)> { + let literal = regex::Regex::new( + r#"(?m)(?:^|[ \t])#[^\n]*|(?:^[ \t]*|[:\-][ \t]+|[\[,{][ \t]*)("(?:[^"\\]|\\[\s\S])*"|'(?:[^']|'')*'|[-+.0-9][-+._0-9a-zA-Z]*)"#, + ) + .expect("valid regex"); + literal + .captures_iter(content) + .filter_map(|caps| { + let text = caps.get(1)?.as_str(); + match serde_yaml::from_str::(text).ok()? { + serde_yaml::Value::String(s) if text.starts_with(['"', '\'']) => { + Some((s, text[1..text.len() - 1].to_string())) + } + serde_yaml::Value::Number(n) => Some((n.to_string(), text.to_string())), + _ => None, + } + }) + .collect() +} + +/// Adds the file's text of each YAML value that runs over lines (a `|` or `>` block, a +/// plain scalar that continues below its key). Folding turns line ends into spaces and +/// indentation goes, so the decoded value is found again by its text without whitespace. +fn add_yaml_block_spellings(entries: &mut Vec, content: &str) { + fn squeezed(text: &str) -> String { + text.chars().filter(|c| !c.is_whitespace()).collect() + } + fn indent(line: &str) -> usize { + line.len() - line.trim_start_matches(' ').len() } - // Unquoted — trim trailing whitespace (already trimmed above) and strip - // inline comments. - if let Some(pos) = trimmed.find(" #") { - trimmed[..pos].trim_end().to_string() - } else { - trimmed.to_string() + let lines: Vec<&str> = content.lines().collect(); + let mut blocks: Vec<(String, String)> = Vec::new(); + for (i, line) in lines.iter().enumerate() { + let below: Vec<&str> = { + let taken: Vec<&str> = + lines[i + 1..].iter().take_while(|l| l.trim().is_empty() || indent(l) > indent(line)).copied().collect(); + let end = taken.iter().rposition(|l| !l.trim().is_empty()).map_or(0, |last| last + 1); + taken[..end].to_vec() + }; + if below.is_empty() { + continue; + } + // What the key's own line adds to the value: nothing for a block header. + let mut head = line.trim_start(); + while let Some(rest) = head.strip_prefix("- ") { + head = rest.trim_start(); + } + let head = head.split_once(": ").map_or(head, |(_, rest)| rest).trim(); + let head = if head.starts_with(['|', '>']) || head.ends_with(':') { "" } else { head }; + let mut raw = head.to_string(); + for part in &below { + if !raw.is_empty() { + raw.push('\n'); + } + raw.push_str(part); + } + blocks.push((squeezed(&raw), raw)); + } + + let mut added = Vec::new(); + for entry in entries.iter() { + let wanted = squeezed(&entry.value); + for (_, raw) in blocks.iter().filter(|(text, _)| *text == wanted) { + added.push(SecretEntry { key: entry.key.clone(), value: raw.clone(), source: entry.source.clone() }); + } + } + entries.append(&mut added); +} + +/// A number as a secret entry, unless it is too short to be one: [`MIN_NUMBER_LEN`]. +fn push_number(entries: &mut Vec, key: &str, text: String, source: &Path) { + if !key.is_empty() && text.len() >= MIN_NUMBER_LEN { + entries.push(SecretEntry { key: key.to_string(), value: text, source: source.to_path_buf() }); } } /// Parse TOML files. Nested tables are flattened with dot separators. -/// Only string values are extracted. +/// String and number values are extracted. fn parse_toml(content: &str, source: &Path) -> Result, ParseError> { let table: toml::Value = content.parse().map_err(|e: toml::de::Error| ParseError::Format { path: source.to_path_buf(), @@ -248,6 +519,7 @@ fn parse_toml(content: &str, source: &Path) -> Result, ParseErr let mut entries = Vec::new(); flatten_toml_value(&table, "", source, &mut entries); + add_file_spellings(&mut entries, toml_tokens(content)); Ok(entries) } @@ -287,13 +559,15 @@ fn flatten_toml_value( flatten_toml_value(v, &key, source, entries); } } - // Integer, Float, Boolean, Datetime — skip, not secrets. + toml::Value::Integer(n) => push_number(entries, prefix, n.to_string(), source), + toml::Value::Float(n) => push_number(entries, prefix, n.to_string(), source), + // Boolean, Datetime — skip, not secrets. _ => {} } } /// Parse JSON files. Nested objects are flattened with dot separators. -/// Arrays use numeric indices. Only string values are extracted. +/// Arrays use numeric indices. String and number values are extracted. fn parse_json(content: &str, source: &Path) -> Result, ParseError> { let value: serde_json::Value = serde_json::from_str(content).map_err(|e| ParseError::Format { @@ -303,6 +577,7 @@ fn parse_json(content: &str, source: &Path) -> Result, ParseErr let mut entries = Vec::new(); flatten_json_value(&value, "", source, &mut entries); + add_file_spellings(&mut entries, json_tokens(content)); Ok(entries) } @@ -342,13 +617,14 @@ fn flatten_json_value( flatten_json_value(v, &key, source, entries); } } - // Number, Bool, Null — skip. + serde_json::Value::Number(n) => push_number(entries, prefix, n.to_string(), source), + // Bool, Null — skip. _ => {} } } /// Parse YAML files. Nested mappings are flattened with dot separators. -/// Only string values are extracted. +/// 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 { @@ -358,6 +634,8 @@ fn parse_yaml(content: &str, source: &Path) -> Result, ParseErr let mut entries = Vec::new(); flatten_yaml_value(&value, "", source, &mut entries); + add_file_spellings(&mut entries, yaml_tokens(content)); + add_yaml_block_spellings(&mut entries, content); Ok(entries) } @@ -401,7 +679,8 @@ fn flatten_yaml_value( flatten_yaml_value(v, &key, source, entries); } } - // Number, Bool, Null, Tagged — skip. + serde_yaml::Value::Number(n) => push_number(entries, prefix, n.to_string(), source), + // Bool, Null, Tagged — skip. _ => {} } } @@ -424,11 +703,8 @@ fn parse_python_assignments( continue; } if let Some(caps) = re.captures(trimmed) { - entries.push(SecretEntry { - key: caps[1].to_string(), - value: caps[2].to_string(), - source: source.to_path_buf(), - }); + // 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); } } @@ -454,10 +730,12 @@ fn parse_properties(content: &str, source: &Path) -> Result, Pa // Handle continuation lines (trailing `\`). let mut logical_line = String::new(); + let mut physical = Vec::new(); let mut current = trimmed.to_string(); while current.ends_with('\\') { // Remove trailing backslash and append next line. logical_line.push_str(¤t[..current.len() - 1]); + physical.push(current[..current.len() - 1].to_string()); current = lines .next() .map(|l| l.trim_start().to_string()) @@ -471,11 +749,13 @@ fn parse_properties(content: &str, source: &Path) -> Result, Pa continue; } - entries.push(SecretEntry { - key, - value, - source: source.to_path_buf(), - }); + push_spellings(&mut entries, &key, value.clone(), unescape(&value), source); + // The file holds a continued value in pieces, one per line. + if !physical.is_empty() { + physical.push(current); + physical[0] = split_property_line(&physical[0]).1; + entries.push(SecretEntry { key, value: physical.join("\n"), source: source.to_path_buf() }); + } } Ok(entries) diff --git a/src/core/secrets/redactor.rs b/src/core/secrets/redactor.rs index 0c2fc67..9014f5a 100644 --- a/src/core/secrets/redactor.rs +++ b/src/core/secrets/redactor.rs @@ -3,6 +3,11 @@ //! Takes the known-secrets [`Manifest`] and efficiently replaces every //! occurrence of a secret value in arbitrary text using an Aho-Corasick //! automaton for multi-pattern matching. +//! +//! A value has several spellings, and one can overlap another. All matches are +//! found, and overlapping ones become one masked range under the longest of them. +//! Taking the leftmost match first would leave the tail of a longer spelling that +//! starts inside a shorter one. use aho_corasick::AhoCorasick; @@ -20,7 +25,7 @@ pub struct Redaction { pub key: String, /// Byte offset in the *original* text where the match starts. pub offset: usize, - /// Length (in bytes) of the original secret value that was replaced. + /// Length (in bytes) of the original text that was replaced. pub original_len: usize, } @@ -65,15 +70,13 @@ pub struct Redactor { #[derive(Debug, Clone)] struct RedactorEntry { key: String, - value_len: usize, } impl Redactor { /// Build a redactor from a manifest and redaction style. /// - /// The manifest entries are already sorted by value length descending, - /// but Aho-Corasick with `LeftmostLongest` handles overlap correctly - /// regardless of input order. + /// The manifest entries are sorted by value length descending, so among equally + /// long matches the first entry names the secret. pub fn new(manifest: &Manifest, style: RedactionStyle) -> Self { let secrets = manifest.entries(); if secrets.is_empty() { @@ -90,14 +93,12 @@ impl Redactor { .iter() .map(|e| RedactorEntry { key: e.key.clone(), - value_len: e.value.len(), }) .collect(); - // LeftmostLongest ensures that when one secret value is a substring - // of another, the longer match wins. + // Standard match kind: the only one that reports overlapping matches. let automaton = AhoCorasick::builder() - .match_kind(aho_corasick::MatchKind::LeftmostLongest) + .match_kind(aho_corasick::MatchKind::Standard) .build(&patterns) .ok(); // If build fails (shouldn't for valid strings), fall back to no-op. @@ -127,23 +128,23 @@ impl Redactor { let mut redactions = Vec::new(); let mut last_end = 0; - for mat in automaton.find_iter(text) { - let entry = &self.entries[mat.pattern().as_usize()]; + for range in masked_ranges(automaton, text) { + let entry = &self.entries[range.pattern]; // Append text before the match. - result.push_str(&text[last_end..mat.start()]); + result.push_str(&text[last_end..range.start]); // Append the replacement placeholder. - let replacement = self.format_replacement(entry); + let replacement = self.format_replacement(entry, range.end - range.start); result.push_str(&replacement); redactions.push(Redaction { key: entry.key.clone(), - offset: mat.start(), - original_len: entry.value_len, + offset: range.start, + original_len: range.end - range.start, }); - last_end = mat.end(); + last_end = range.end; } // Append remaining text after the last match. @@ -156,10 +157,10 @@ impl Redactor { } /// Format the replacement string according to the configured style. - fn format_replacement(&self, entry: &RedactorEntry) -> String { + fn format_replacement(&self, entry: &RedactorEntry, len: usize) -> String { match self.style { RedactionStyle::Masked => "*****".to_string(), - RedactionStyle::Typed => format!("", entry.value_len), + RedactionStyle::Typed => format!(""), RedactionStyle::Named => format!("", entry.key), RedactionStyle::Absent => String::new(), } @@ -170,3 +171,37 @@ impl Redactor { self.automaton.is_some() } } + +/// A stretch of text to mask, named after the longest match in it. +struct MaskedRange { + start: usize, + end: usize, + pattern: usize, +} + +/// Every match in `text`, in order, with overlapping ones merged. +fn masked_ranges(automaton: &AhoCorasick, text: &str) -> Vec { + let mut matches: Vec = automaton.find_overlapping_iter(text).collect(); + matches.sort_by_key(|m| (m.start(), m.end())); + + let mut ranges: Vec = Vec::new(); + let mut longest = 0; + for m in matches { + let pattern = m.pattern().as_usize(); + match ranges.last_mut() { + Some(range) if m.start() < range.end => { + range.end = range.end.max(m.end()); + let better = m.len() > longest || (m.len() == longest && pattern < range.pattern); + if better { + range.pattern = pattern; + longest = m.len(); + } + } + _ => { + ranges.push(MaskedRange { start: m.start(), end: m.end(), pattern }); + longest = m.len(); + } + } + } + ranges +} diff --git a/tests/cli_hook_spellings.rs b/tests/cli_hook_spellings.rs new file mode 100644 index 0000000..4c7d39e --- /dev/null +++ b/tests/cli_hook_spellings.rs @@ -0,0 +1,232 @@ +//! A value spelled in its own file differently from how it decodes. Read shows the +//! file's bytes, a program that loaded the file shows the decoded text, and every such +//! spelling has to be masked. All values here are fake. + +use assert_cmd::Command; +use serde_json::{json, Value}; +use std::fs; +use tempfile::TempDir; + +/// Fake PEM body lines. `TAIL` is shorter than the line minimum. +const LINE_1: &str = "FAKEFAKEpemBODYlineONExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; +const LINE_2: &str = "FAKEFAKEpemBODYlineTWOyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; +const TAIL: &str = "abc="; + +fn pem() -> String { + format!("-----BEGIN PRIVATE KEY-----\n{LINE_1}\n{LINE_2}\n{TAIL}\n-----END PRIVATE KEY-----\n") +} + +fn escaped_pem() -> String { + pem().replace('\n', "\\n") +} + +fn project(files: &[(&str, &str)]) -> (TempDir, TempDir) { + 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(); + } + (dir, tempfile::tempdir().unwrap()) +} + +fn hook(p: &(TempDir, TempDir), response: &Value) -> Value { + let output = Command::cargo_bin("fermata") + .unwrap() + .args(["hook", "--event", "post-tool-use", "--harness", "claude"]) + .current_dir(p.0.path()) + .env("HOME", p.1.path()) + .write_stdin(json!({"tool_name": "Read", "tool_input": {}, "tool_response": response}).to_string()) + .assert() + .success() + .get_output() + .clone(); + serde_json::from_slice(&output.stdout).unwrap() +} + +/// What the model gets from `Read` of a file holding `text`. +fn read(p: &(TempDir, TempDir), text: &str) -> String { + let response = json!({ + "type": "text", + "file": {"filePath": "/p/f", "content": text, "numLines": 1, "startLine": 1, "totalLines": 1}, + }); + let out = hook(p, &response); + out["hookSpecificOutput"]["updatedToolOutput"]["file"]["content"] + .as_str() + .unwrap_or(text) + .to_string() +} + +/// `Read` of the file itself shows none of `parts`, in a project that declares it. +fn file_read_hides(name: &str, content: &str, parts: &[&str]) { + let botsecrets = format!("[files]\npatterns = [\"{name}\"]\n[keys]\ninclude = [\"*\"]\n"); + let p = project(&[(".botsecrets", &botsecrets), (name, content)]); + let shown = read(&p, content); + for part in parts { + assert!(!shown.contains(part), "{name}: {part:?} reached the model in:\n{shown}"); + } +} + +// --------------------------------------------------------------------------- +// The file's own bytes +// --------------------------------------------------------------------------- + +#[test] +fn a_google_key_file_with_the_default_config() { + let key = escaped_pem(); + let content = format!("{{\n \"type\": \"service_account\",\n \"private_key_id\": \"fakeid1234\",\n \"private_key\": \"{key}\"\n}}\n"); + let p = project(&[(".botsecrets", ""), ("service-account.json", &content)]); + let shown = read(&p, &content); + assert!(!shown.contains("fakeid1234"), "{shown}"); + assert!(!shown.contains(LINE_1) && !shown.contains(LINE_2), "{shown}"); + assert!(shown.contains("service_account"), "other values stay: {shown}"); +} + +#[test] +fn json_escapes() { + file_read_hides("s.json", r#"{"k": "fake\"quoted\\value"}"#, &[r#"fake\"quoted\\value"#]); + file_read_hides("s.json", r#"{"k": "fake\u0041unicode"}"#, &[r"fake\u0041unicode"]); + file_read_hides("s.json", r#"{"k": "fake\/slash\tvalue"}"#, &[r"fake\/slash\tvalue"]); +} + +#[test] +fn an_env_value_with_escapes() { + let content = format!("PRIVATE_KEY=\"{}\"\nAPI_TOKEN=plainfake123\n", escaped_pem()); + file_read_hides(".env", &content, &[LINE_1, LINE_2, "plainfake123"]); + file_read_hides(".env", "K=\"fake\\tvalue\"\n", &["fake\\tvalue"]); +} + +#[test] +fn an_env_value_over_real_lines() { + let content = format!("PRIVATE_KEY=\"{}\"\nAPI_TOKEN=plainfake123\n", pem()); + file_read_hides(".env", &content, &[LINE_1, LINE_2, "plainfake123"]); + let single = format!("PRIVATE_KEY='{}'\nAPI_TOKEN=plainfake123\n", pem()); + file_read_hides(".env", &single, &[LINE_1, LINE_2, "plainfake123"]); +} + +#[test] +fn yaml_spellings() { + let block = format!("key: |\n {LINE_1}\n {LINE_2}\nother: x\n"); + file_read_hides("s.yaml", &block, &[LINE_1, LINE_2]); + let folded = format!("key: >-\n {LINE_1}\n {LINE_2}\nother: x\n"); + file_read_hides("s.yaml", &folded, &[LINE_1, LINE_2]); + let plain = format!("key: {LINE_1}\n {LINE_2}\nother: x\n"); + file_read_hides("s.yaml", &plain, &[LINE_1, LINE_2]); + let nested = format!("a:\n - key: |\n {LINE_1}\n {LINE_2}\n"); + file_read_hides("s.yaml", &nested, &[LINE_1, LINE_2]); + file_read_hides("s.yaml", "key: \"fake\\nyaml\\tvalue\"\n", &["fake\\nyaml\\tvalue"]); + file_read_hides("s.yaml", "key: 'fake''quoted value'\n", &["fake''quoted value"]); + let over_lines = "key: \"fake quoted\n over lines value\"\n"; + file_read_hides("s.yaml", over_lines, &["fake quoted", "over lines value"]); +} + +#[test] +fn toml_spellings() { + file_read_hides("s.toml", "key = \"fake\\tvalue\\\"x\"\n", &["fake\\tvalue\\\"x"]); + let lines = format!("key = \"\"\"\n{LINE_1}\n{LINE_2}\n\"\"\"\n"); + file_read_hides("s.toml", &lines, &[LINE_1, LINE_2]); + let joined = format!("key = \"\"\"\\\n{LINE_1}\\\n{LINE_2}\"\"\"\n"); + file_read_hides("s.toml", &joined, &[LINE_1, LINE_2]); + file_read_hides("s.toml", "# an 'odd' comment\nkey = 'fake literal' # \"note\n", &["fake literal"]); +} + +#[test] +fn python_and_properties_spellings() { + let joined = format!("key={LINE_1}\\\n {LINE_2}\n"); + file_read_hides("s.properties", &joined, &[LINE_1, LINE_2]); + let botsecrets = "[files]\npatterns = [\"s.py\"]\n[keys]\ninclude = [\"*\"]\n"; + let p = project(&[(".botsecrets", botsecrets), ("s.py", "KEY = \"fake\\nvalue1\"\n")]); + assert_eq!(read(&p, "printed: fake\nvalue1"), "printed: *****"); + assert_eq!(read(&p, "file: fake\\nvalue1"), "file: *****"); +} + +// --------------------------------------------------------------------------- +// Numbers +// --------------------------------------------------------------------------- + +#[test] +fn numbers_in_a_secret_file() { + file_read_hides("s.toml", "api_token = 987654321\n", &["987654321"]); + file_read_hides("s.json", "{\"api_token\": 987654321}", &["987654321"]); + file_read_hides("s.yaml", "api_token: 987654321\n", &["987654321"]); + file_read_hides("s.toml", "api_token = 987_654_321\n", &["987_654_321"]); + file_read_hides("s.json", "{\"api_token\": 123456789012345678901234567890}", &["123456789012345678901234567890"]); + file_read_hides("s.yaml", "pin: 0012345678\n", &["0012345678"]); +} + +/// A short number under a matching key is a setting more often than a secret. +#[test] +fn a_short_number_stays() { + let botsecrets = "[files]\npatterns = [\"s.toml\"]\n[keys]\ninclude = [\"*\"]\n"; + let p = project(&[(".botsecrets", botsecrets), ("s.toml", "cache_key_ttl = 36000\n")]); + assert_eq!(read(&p, "ttl is 36000"), "ttl is 36000"); + let p = project(&[(".botsecrets", botsecrets), ("s.toml", "cache_key_ttl = 360000\n")]); + assert_eq!(read(&p, "ttl is 360000"), "ttl is *****"); +} + +// --------------------------------------------------------------------------- +// What a program prints +// --------------------------------------------------------------------------- + +/// `.env` values as a shell or a dotenv loader decodes them. +#[test] +fn an_env_value_as_a_program_prints_it() { + let botsecrets = "[files]\npatterns = [\".env\"]\n"; + for (line, printed) in [ + ("API_TOKEN=\"fakevalue\" # prod", "fakevalue"), + ("API_TOKEN=\"fake\\\"value\"", "fake\"value"), + ("API_TOKEN=fake\\ value", "fake value"), + ("API_TOKEN='fake value' # prod", "fake value"), + ("API_TOKEN=fakevalue # prod", "fakevalue"), + ("API_TOKEN=\"fake$value\"", "fake$value"), + ] { + let p = project(&[(".botsecrets", botsecrets), (".env", line)]); + assert_eq!(read(&p, &format!("echo: {printed}\n")), "echo: *****\n", "{line}"); + } +} + +// --------------------------------------------------------------------------- +// Part of a value +// --------------------------------------------------------------------------- + +/// A Read with a line range, a grep, a diff: the value is not whole. +#[test] +fn each_line_of_a_value_is_masked_alone() { + let content = format!("PRIVATE_KEY=\"{}\"\n", pem()); + let p = project(&[(".botsecrets", "[files]\npatterns = [\".env\"]\n"), (".env", &content)]); + assert_eq!(read(&p, &format!("3: {LINE_2}\n")), "3: *****\n"); +} + +#[test] +fn a_whole_value_gets_one_mask() { + let content = format!("PRIVATE_KEY=\"{}\"\n", pem()); + let p = project(&[(".botsecrets", "[files]\npatterns = [\".env\"]\n"), (".env", &content)]); + assert_eq!(read(&p, &content), "PRIVATE_KEY=\"*****\"\n"); + assert_eq!(read(&p, &format!("a {} b", pem().trim_end())), "a ***** b"); +} + +/// Short lines, PEM armor and layout appear in ordinary text. The price is stated in +/// `MIN_LINE_LEN`: a short tail read away from its value passes. +#[test] +fn short_lines_armor_and_layout_are_not_masked_alone() { + let value = format!("-----BEGIN PRIVATE KEY-----\n{LINE_1}\nprod\n--------\n1234567\n12345678\n-----END PRIVATE KEY-----"); + let content = format!("PRIVATE_KEY=\"{value}\"\n"); + let p = project(&[(".botsecrets", "[files]\npatterns = [\".env\"]\n"), (".env", &content)]); + for text in ["see -----BEGIN PRIVATE KEY----- here", "-----END PRIVATE KEY-----", "prod", "--------", "1234567"] { + assert_eq!(read(&p, text), text); + } + assert_eq!(read(&p, "12345678"), "*****"); +} + +// --------------------------------------------------------------------------- +// A malformed .env +// --------------------------------------------------------------------------- + +/// An opening quote nobody closed must not swallow the keys below it. +#[test] +fn an_unclosed_quote_leaves_the_next_key_alone() { + let content = "BROKEN_TOKEN=\"unclosedfake\nAPI_TOKEN=\"nextfakevalue\"\nOTHER_TOKEN=lastfakevalue\n"; + let botsecrets = "[files]\npatterns = [\".env\"]\n"; + let p = project(&[(".botsecrets", botsecrets), (".env", content)]); + let shown = read(&p, "nextfakevalue lastfakevalue"); + assert_eq!(shown, "***** *****"); +} diff --git a/tests/core_secrets_parser.rs b/tests/core_secrets_parser.rs index e781e97..9429878 100644 --- a/tests/core_secrets_parser.rs +++ b/tests/core_secrets_parser.rs @@ -239,9 +239,11 @@ fn properties_comments() { fn properties_continuation_lines() { let content = "long.value=hello \\\n world"; let entries = parse_content(content, FileFormat::Properties, p("app.properties")).unwrap(); - assert_eq!(entries.len(), 1); + assert_eq!(entries.len(), 2); assert_eq!(entries[0].key, "long.value"); assert_eq!(entries[0].value, "hello world"); + // The pieces as the file holds them. + assert_eq!(entries[1].value, "hello\nworld"); } // --------------------------------------------------------------------------- diff --git a/tests/core_secrets_redactor.rs b/tests/core_secrets_redactor.rs index f1c6d7a..697ee0a 100644 --- a/tests/core_secrets_redactor.rs +++ b/tests/core_secrets_redactor.rs @@ -371,3 +371,40 @@ fn duplicate_entries_deduplicated() { ]); assert_eq!(manifest.len(), 1); } + +// --------------------------------------------------------------------------- +// Spellings that overlap +// --------------------------------------------------------------------------- + +/// A longer spelling starting inside a shorter one must not lose its tail to it. +#[test] +fn overlapping_matches_are_masked_whole() { + let r = make_redactor(vec![entry("A", "abc-long"), entry("B", "long-tail-of-a-longer-value")], RedactionStyle::Masked); + let result = r.redact("x abc-long-tail-of-a-longer-value y"); + assert_eq!(result.text, "x ***** y"); + assert_eq!(result.redactions.len(), 1); + assert_eq!(result.redactions[0].key, "B", "named after the longest"); + assert_eq!(result.redactions[0].offset, 2); + assert_eq!(result.redactions[0].original_len, "abc-long-tail-of-a-longer-value".len()); +} + +#[test] +fn a_shorter_value_inside_a_longer_one_does_not_split_the_mask() { + let r = make_redactor(vec![entry("A", "inner-value"), entry("B", "outer-inner-value-outer")], RedactionStyle::Named); + assert_eq!(r.redact("outer-inner-value-outer").text, ""); + assert_eq!(r.redact("the inner-value alone").text, "the alone"); +} + +#[test] +fn the_typed_mask_counts_what_it_replaced() { + let r = make_redactor(vec![entry("A", "abc-long"), entry("B", "long-tail-value")], RedactionStyle::Typed); + assert_eq!(r.redact("abc-long-tail-value").text, ""); +} + +#[test] +fn matches_that_only_touch_stay_two() { + let r = make_redactor(vec![entry("A", "first-value"), entry("B", "second-value")], RedactionStyle::Masked); + let result = r.redact("first-valuesecond-value"); + assert_eq!(result.text, "**********"); + assert_eq!(result.redactions.len(), 2); +}