diff --git a/src/core/secrets/config.rs b/src/core/secrets/config.rs index f968988..778a400 100644 --- a/src/core/secrets/config.rs +++ b/src/core/secrets/config.rs @@ -11,7 +11,7 @@ //! `keys.include` and `keys.exclude` *accumulate* across layers. //! Scalar fields (style, mode, enabled) take the most-specific value. -use globset::{Glob, GlobMatcher}; +use globset::{Glob, GlobSet, GlobSetBuilder}; use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; use thiserror::Error; @@ -586,24 +586,32 @@ impl SecretsConfig { patterns } - /// Check whether `key` matches any of the effective key-include patterns. - /// - /// Matching is case-insensitive and uses glob semantics (`*` wildcards). - pub fn key_matches(&self, key: &str) -> bool { - let patterns = self.effective_key_includes(); - let upper = key.to_ascii_uppercase(); - - for pat in &patterns { - let pat_upper = pat.to_ascii_uppercase(); - // Build a glob matcher. Patterns without path separators are - // matched as plain globs against the key name. - if let Ok(glob) = Glob::new(&pat_upper) { - let matcher: GlobMatcher = glob.compile_matcher(); - if matcher.is_match(&upper) { - return true; - } + /// The effective key-include patterns, compiled once. An invalid pattern is skipped. + pub fn key_matcher(&self) -> KeyMatcher { + let mut builder = GlobSetBuilder::new(); + for pat in self.effective_key_includes() { + if let Ok(glob) = Glob::new(&pat.to_ascii_uppercase()) { + builder.add(glob); } } - false + KeyMatcher(builder.build().unwrap_or_else(|_| GlobSet::empty())) + } + + /// Check whether `key` matches any of the effective key-include patterns. + /// + /// Matching is case-insensitive and uses glob semantics (`*` wildcards). Compiles the + /// patterns on every call: use [`Self::key_matcher`] to test many keys. + pub fn key_matches(&self, key: &str) -> bool { + self.key_matcher().is_match(key) + } +} + +/// The key-include patterns of a [`SecretsConfig`], compiled once. +pub struct KeyMatcher(GlobSet); + +impl KeyMatcher { + /// Whether `key` matches any pattern (both uppercased). + pub fn is_match(&self, key: &str) -> bool { + self.0.is_match(key.to_ascii_uppercase()) } } diff --git a/src/core/secrets/manifest.rs b/src/core/secrets/manifest.rs index 42ccf42..79e890f 100644 --- a/src/core/secrets/manifest.rs +++ b/src/core/secrets/manifest.rs @@ -359,10 +359,8 @@ fn parse_discovered_file(path: &Path) -> Result, ParseError> { /// Keep only entries whose key matches the effective key-include patterns /// from the configuration. fn filter_by_key_patterns(entries: Vec, config: &SecretsConfig) -> Vec { - entries - .into_iter() - .filter(|e| config.key_matches(&e.key)) - .collect() + let matcher = config.key_matcher(); + entries.into_iter().filter(|e| matcher.is_match(&e.key)).collect() } #[cfg(test)] diff --git a/src/core/secrets/mod.rs b/src/core/secrets/mod.rs index 554cfd2..5d5f8a0 100644 --- a/src/core/secrets/mod.rs +++ b/src/core/secrets/mod.rs @@ -8,7 +8,7 @@ pub mod patterns; pub mod redactor; pub mod scanner; -pub use config::SecretsConfig; +pub use config::{KeyMatcher, SecretsConfig}; pub use manifest::{Manifest, ManifestError}; pub use parser::{parse_secret_file, FileFormat, ParseError, SecretEntry}; pub use redactor::{RedactedText, Redaction, Redactor}; diff --git a/src/core/secrets/parser.rs b/src/core/secrets/parser.rs index 1d451b5..1115e5b 100644 --- a/src/core/secrets/parser.rs +++ b/src/core/secrets/parser.rs @@ -10,6 +10,7 @@ //! a program that loads it the first. [`super::manifest`] adds the derived spellings. use globset::Glob; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use thiserror::Error; @@ -378,10 +379,26 @@ fn push_spellings(entries: &mut Vec, key: &str, value: String, raw: /// 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 by_decoded: HashMap> = HashMap::new(); + for (decoded, raw) in tokens { + let raws = by_decoded.entry(decoded).or_default(); + if !raws.contains(&raw) { + raws.push(raw); + } + } + add_spellings_by(entries, |value| by_decoded.get(value).map(Vec::as_slice)); +} + +/// Appends, for each entry, the raws that `spellings` gives for its value (those that +/// differ from it), once per key and raw. +fn add_spellings_by<'a>(entries: &mut Vec, spellings: impl Fn(&str) -> Option<&'a [String]>) { + let mut seen: HashSet<(String, String)> = HashSet::new(); 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() }); + for raw in spellings(&entry.value).unwrap_or_default() { + if *raw != entry.value && seen.insert((entry.key.clone(), raw.clone())) { + added.push(SecretEntry { key: entry.key.clone(), value: raw.clone(), source: entry.source.clone() }); + } } } entries.append(&mut added); @@ -492,14 +509,11 @@ fn add_yaml_block_spellings(entries: &mut Vec, content: &str) { 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() }); - } + let mut by_text: HashMap> = HashMap::new(); + for (text, raw) in blocks { + by_text.entry(text).or_default().push(raw); } - entries.append(&mut added); + add_spellings_by(entries, |value| by_text.get(&squeezed(value)).map(Vec::as_slice)); } /// A number as a secret entry, unless it is too short to be one: [`MIN_NUMBER_LEN`]. diff --git a/tests/core_secrets_large_files.rs b/tests/core_secrets_large_files.rs new file mode 100644 index 0000000..695cf59 --- /dev/null +++ b/tests/core_secrets_large_files.rs @@ -0,0 +1,69 @@ +//! Large secret files parse in linear time: a 2 MB JSON and a 1 MB YAML manifest +//! (generated, fake values) finish under a bound that the quadratic scans missed. + +use std::fmt::Write; +use std::time::{Duration, Instant}; + +use dirigent_fermata::core::secrets::config::SecretsConfig; +use dirigent_fermata::core::secrets::manifest::Manifest; + +const BOUND: Duration = Duration::from_secs(60); + +/// A fake value of 24 characters with a JSON escape in it, so raw and decoded differ. +fn value(i: usize) -> String { + format!("fake{i:08}-abcdefghij\\n") +} + +fn config() -> SecretsConfig { + SecretsConfig::from_toml("[files]\npatterns = [\"secrets.json\", \"secrets.yaml\"]\n").unwrap() +} + +#[test] +fn a_2_mb_json_manifest_builds_within_the_bound() { + let dir = tempfile::tempdir().unwrap(); + let mut json = String::from("{"); + let mut n = 0; + while json.len() < 2_000_000 { + if n > 0 { + json.push(','); + } + write!(json, "\"api_key_{n}\":\"{}\"", value(n)).unwrap(); + n += 1; + } + json.push('}'); + std::fs::write(dir.path().join("secrets.json"), &json).unwrap(); + + let start = Instant::now(); + let manifest = Manifest::build(&config(), dir.path()).unwrap(); + assert!(start.elapsed() < BOUND, "took {:?}", start.elapsed()); + // Decoded and raw spelling of every value. + assert!(manifest.len() >= 2 * n, "{} entries for {n} keys", manifest.len()); +} + +#[test] +fn a_1_mb_yaml_manifest_builds_within_the_bound() { + let dir = tempfile::tempdir().unwrap(); + let mut yaml = String::new(); + let mut n = 0; + while yaml.len() < 1_000_000 { + writeln!(yaml, "api_key_{n}: \"{}\"", value(n)).unwrap(); + n += 1; + } + std::fs::write(dir.path().join("secrets.yaml"), &yaml).unwrap(); + + let start = Instant::now(); + let manifest = Manifest::build(&config(), dir.path()).unwrap(); + assert!(start.elapsed() < BOUND, "took {:?}", start.elapsed()); + assert!(manifest.len() >= 2 * n, "{} entries for {n} keys", manifest.len()); +} + +#[test] +fn a_compiled_key_matcher_agrees_with_key_matches() { + let config = SecretsConfig::from_toml("[keys]\ninclude = [\"my_thing_*\", \"[\"]\n").unwrap(); + let matcher = config.key_matcher(); + for key in ["API_KEY", "api_key", "My_Thing_One", "APP_NAME", "db_password", "["] { + assert_eq!(matcher.is_match(key), config.key_matches(key), "{key}"); + } + assert!(matcher.is_match("my_thing_x")); + assert!(!matcher.is_match("APP_NAME")); +}