Skip to main content

lean_ctx/core/
secret_detection.rs

1use std::sync::OnceLock;
2
3use regex::Regex;
4
5use crate::core::config::{Config, SecretDetectionConfig};
6
7macro_rules! static_regex {
8    ($pattern:expr_2021) => {{
9        static RE: OnceLock<Regex> = OnceLock::new();
10        RE.get_or_init(|| Regex::new($pattern).expect(concat!("invalid regex: ", $pattern)))
11    }};
12}
13
14#[derive(Debug, Clone)]
15pub struct SecretMatch {
16    pub pattern_name: &'static str,
17    pub line_number: usize,
18    pub redacted_preview: String,
19}
20
21fn aws_key_re() -> &'static Regex {
22    static_regex!(r"(?:AKIA|ASIA)[0-9A-Z]{16}")
23}
24
25fn private_key_re() -> &'static Regex {
26    static_regex!(r"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----")
27}
28
29fn github_token_re() -> &'static Regex {
30    static_regex!(r"gh[ps]_[A-Za-z0-9_]{36,}")
31}
32
33pub(crate) fn anthropic_key_re() -> &'static Regex {
34    static_regex!(r"sk-ant-[A-Za-z0-9_\-]{20,}")
35}
36
37pub(crate) fn openai_key_re() -> &'static Regex {
38    static_regex!(r"\bsk-(?:(?:proj|svcacct)-[A-Za-z0-9_\-]{20,}|[A-Za-z0-9]{20,})")
39}
40
41// #718 word boundaries for the generic key/value patterns: the keyword must
42// not be a camelCase subword (`superuserPassword`), while SNAKE_CASE env
43// names (`MY_TOKEN=…`) keep matching — `_` stays a permitted predecessor.
44// Group 1 = predecessor + key prefix (kept on redaction), group 2 = value
45// (guarded: identifier references and placeholders are benign).
46// #1830: blanks only around the separator — a valueless `token:` line must not
47// take the next line for its value.
48fn generic_api_key_re() -> &'static Regex {
49    static_regex!(
50        r#"(?im)((?:^|[^a-z0-9])(?:aws[_-]?secret[_-]?access[_-]?key|secret[_-]?access[_-]?key|api[_-]?key|secret[_-]?key|token|password|passwd|access[_-]?token|client[_-]?secret)(?:\\?["'])?[ \t]*[=:][ \t]*(?:\\?["'])?)([A-Za-z0-9_+/=\-]{20,})"#
51    )
52}
53
54fn high_entropy_b64_re() -> &'static Regex {
55    static_regex!(
56        r#"(?im)((?:^|[^a-z0-9])(?:key|token|secret|password|credential|auth)(?:\\?["'])?[ \t]*[=:][ \t]*(?:\\?["'])?)([A-Za-z0-9+/=\-_]{40,})"#
57    )
58}
59
60fn url_encoded_secret_re() -> &'static Regex {
61    static_regex!(
62        r#"(?im)((?:^|[^a-z0-9])(?:aws[_-]?secret[_-]?access[_-]?key|secret[_-]?access[_-]?key|api[_-]?key|secret[_-]?key|token|password|passwd|access[_-]?token|client[_-]?secret)(?:\\?["'])?[ \t]*[=:][ \t]*(?:\\?["'])?)((?:%[0-9a-f]{2}|[A-Za-z0-9_\-]){20,})"#
63    )
64}
65
66fn authorization_header_re() -> &'static Regex {
67    static_regex!(r"(?i)authorization[ \t]*:[ \t]*(?:bearer|basic)[ \t]+[A-Za-z0-9_+/=\-.]{4,}")
68}
69
70/// A bare `Bearer <token>` outside an `Authorization:` header (curl flags, logs).
71/// Group 1 is filtered by `redaction::bearer_value_is_credential`, the same check
72/// the core redactor applies, so prose ("Bearer authentication") stays clean and
73/// the two layers cannot disagree.
74fn bearer_token_re() -> &'static Regex {
75    static_regex!(r"(?i)bearer[ \t]+([A-Za-z0-9_\-.]{8,})")
76}
77
78fn gitlab_pat_re() -> &'static Regex {
79    static_regex!(r"glpat-[A-Za-z0-9_\-]{20,}")
80}
81
82fn jwt_re() -> &'static Regex {
83    static_regex!(r"eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}")
84}
85
86fn slack_token_re() -> &'static Regex {
87    static_regex!(r"xox[bpas]-[0-9a-zA-Z\-]{10,}")
88}
89
90/// Stripe secret (`sk_`) and restricted (`rk_`) keys in live and test mode.
91/// Group 1 is the key-class prefix the redactor keeps.
92pub(crate) fn stripe_key_re() -> &'static Regex {
93    static_regex!(r"([sr]k_(?:live|test)_)[0-9a-zA-Z]{10,}")
94}
95
96/// Stripe webhook signing secret (`whsec_` plus a base64 value). Group 1 is
97/// the prefix the redactor keeps; 16 value characters keep prose clean.
98pub(crate) fn stripe_webhook_secret_re() -> &'static Regex {
99    static_regex!(r"(whsec_)[A-Za-z0-9+/]{16,}={0,2}")
100}
101
102fn npm_token_re() -> &'static Regex {
103    static_regex!(r"npm_[A-Za-z0-9]{10,}")
104}
105
106fn github_fine_grained_re() -> &'static Regex {
107    static_regex!(r"github_pat_[A-Za-z0-9_]{20,}")
108}
109
110const BUILTIN_PATTERNS: &[(&str, fn() -> &'static Regex)] = &[
111    ("aws_key", aws_key_re),
112    ("authorization_header", authorization_header_re),
113    ("private_key", private_key_re),
114    ("github_token", github_token_re),
115    ("github_fine_grained", github_fine_grained_re),
116    ("anthropic_key", anthropic_key_re),
117    ("openai_key", openai_key_re),
118    ("gitlab_pat", gitlab_pat_re),
119    ("jwt", jwt_re),
120    ("slack_token", slack_token_re),
121    ("stripe_key", stripe_key_re),
122    ("stripe_webhook_secret", stripe_webhook_secret_re),
123    ("npm_token", npm_token_re),
124];
125
126/// Key/value patterns with a kept prefix (group 1) and a guarded value
127/// (group 2): identifier references, placeholders and language literals are
128/// benign (#718) and neither reported nor redacted.
129const GUARDED_PATTERNS: &[(&str, fn() -> &'static Regex)] = &[
130    ("generic_api_key", generic_api_key_re),
131    ("high_entropy_secret", high_entropy_b64_re),
132    ("url_encoded_secret", url_encoded_secret_re),
133];
134
135/// True when a guarded-pattern match should be skipped: the value is benign
136/// (#718) — shares the benign-value heuristics with `core::redaction` so the
137/// two layers cannot drift.
138fn guarded_match_is_benign(caps: &regex::Captures) -> bool {
139    // A quoted value is a literal, never an identifier reference — same rule as
140    // the core redactor, so the scanner cannot report "clean" for what it redacts.
141    let quoted = caps
142        .get(1)
143        .is_some_and(|prefix| prefix.as_str().ends_with(['"', '\'']));
144    caps.get(2).is_some_and(|value| {
145        if quoted {
146            crate::core::redaction::is_benign_quoted_value(value.as_str())
147        } else {
148            crate::core::redaction::is_benign_secret_value(value.as_str())
149        }
150    })
151}
152
153/// Compile the subtractive `exclude_patterns` from config (#718). Invalid
154/// regexes are skipped — a broken exclude must never disable detection.
155fn compile_excludes(patterns: &[String]) -> Vec<Regex> {
156    patterns.iter().filter_map(|p| Regex::new(p).ok()).collect()
157}
158
159fn excluded(excludes: &[Regex], matched: &str) -> bool {
160    excludes.iter().any(|ex| ex.is_match(matched))
161}
162
163fn make_redacted_preview(matched: &str) -> String {
164    let chars: Vec<char> = matched.chars().collect();
165    if chars.len() <= 6 {
166        return "***".to_string();
167    }
168    let prefix: String = chars[..4].iter().collect();
169    let suffix: String = chars[chars.len() - 2..].iter().collect();
170    format!("{prefix}***{suffix}")
171}
172
173fn collect_matches(
174    content: &str,
175    custom_patterns: &[String],
176    excludes: &[Regex],
177) -> Vec<SecretMatch> {
178    let mut matches = Vec::new();
179    let normalized = crate::core::redaction::normalize_secret_text(content);
180
181    // Built on the first match only: most content has none. Offsets index
182    // the normalized text the patterns run on.
183    let line_offsets: std::cell::OnceCell<Vec<usize>> = std::cell::OnceCell::new();
184
185    let offset_to_line = |byte_offset: usize| -> usize {
186        let line_offsets = line_offsets.get_or_init(|| {
187            std::iter::once(0)
188                .chain(normalized.match_indices('\n').map(|(i, _)| i + 1))
189                .collect()
190        });
191        match line_offsets.binary_search(&byte_offset) {
192            Ok(i) => i + 1,
193            Err(i) => i,
194        }
195    };
196
197    for &(name, regex_fn) in BUILTIN_PATTERNS {
198        let re = regex_fn();
199        for m in re.find_iter(&normalized) {
200            if excluded(excludes, m.as_str()) {
201                continue;
202            }
203            matches.push(SecretMatch {
204                pattern_name: name,
205                line_number: offset_to_line(m.start()),
206                redacted_preview: make_redacted_preview(m.as_str()),
207            });
208        }
209    }
210
211    for caps in bearer_token_re().captures_iter(&normalized) {
212        let Some(whole) = caps.get(0) else {
213            continue;
214        };
215        let credential = caps.get(1).is_some_and(|value| {
216            crate::core::redaction::bearer_value_is_credential(value.as_str())
217        });
218        if !credential || excluded(excludes, whole.as_str()) {
219            continue;
220        }
221        matches.push(SecretMatch {
222            pattern_name: "bearer_token",
223            line_number: offset_to_line(whole.start()),
224            redacted_preview: make_redacted_preview(whole.as_str()),
225        });
226    }
227
228    // Same rule as the redactor: a placeholder password or an already
229    // redacted URL is no credential, so redacted output never re-matches.
230    // Database URLs and every other URL with userinfo share that test
231    // (GHSA-xmx8-69qv-7f86: `https://user:****@host` stays deliverable).
232    for (name, re) in [
233        ("db_url", crate::core::redaction::database_url_re()),
234        (
235            "url_credentials",
236            crate::core::redaction::url_credentials_re(),
237        ),
238    ] {
239        for caps in re.captures_iter(&normalized) {
240            let Some(whole) = caps.get(0) else {
241                continue;
242            };
243            if !crate::core::redaction::database_url_has_credential(&caps)
244                || excluded(excludes, whole.as_str())
245            {
246                continue;
247            }
248            matches.push(SecretMatch {
249                pattern_name: name,
250                line_number: offset_to_line(whole.start()),
251                redacted_preview: make_redacted_preview(whole.as_str()),
252            });
253        }
254    }
255
256    for &(name, regex_fn) in GUARDED_PATTERNS {
257        let re = regex_fn();
258        for caps in re.captures_iter(&normalized) {
259            let whole = caps.get(0).map_or("", |m| m.as_str());
260            if guarded_match_is_benign(&caps)
261                || (name == "high_entropy_secret"
262                    && caps.get(2).is_some_and(|value| {
263                        caps.get(1).is_some_and(|prefix| {
264                            crate::core::redaction::is_fact_key_slug(
265                                prefix.as_str(),
266                                value.as_str(),
267                            )
268                        }) || caps.get(0).is_some_and(|found| {
269                            // The redactor's "Generic long secret" rule keeps
270                            // a verified package signer key (GHSA-xmx8).
271                            crate::core::redaction::is_verified_signer_key(
272                                &normalized[..found.start()],
273                                value.as_str(),
274                            )
275                        })
276                    }))
277                || excluded(excludes, whole)
278            {
279                continue;
280            }
281            let start = caps.get(0).map_or(0, |m| m.start());
282            matches.push(SecretMatch {
283                pattern_name: name,
284                line_number: offset_to_line(start),
285                redacted_preview: make_redacted_preview(whole),
286            });
287        }
288    }
289
290    for pattern_str in custom_patterns {
291        if let Ok(re) = Regex::new(pattern_str) {
292            for m in re.find_iter(&normalized) {
293                if excluded(excludes, m.as_str()) {
294                    continue;
295                }
296                matches.push(SecretMatch {
297                    pattern_name: "custom_pattern",
298                    line_number: offset_to_line(m.start()),
299                    redacted_preview: make_redacted_preview(m.as_str()),
300                });
301            }
302        }
303    }
304
305    matches
306}
307
308/// How many matches the `custom_patterns` of `config` alone have in
309/// `content` — no built-in pattern runs. The custom-pattern step of
310/// `collect_matches` on its own: the same normalized text, the same
311/// `exclude_patterns`, a pattern that does not compile is skipped. For a
312/// caller that has counted the built-in patterns elsewhere (the gateway's
313/// whole-text pass for custom patterns that can match across lines).
314pub(crate) fn custom_pattern_hits(content: &str, config: &SecretDetectionConfig) -> usize {
315    let excludes = compile_excludes(&config.exclude_patterns);
316    let normalized = crate::core::redaction::normalize_secret_text(content);
317    config
318        .custom_patterns
319        .iter()
320        .filter_map(|pattern| Regex::new(pattern).ok())
321        .map(|re| {
322            re.find_iter(&normalized)
323                .filter(|found| !excluded(&excludes, found.as_str()))
324                .count()
325        })
326        .sum()
327}
328
329pub fn detect_secrets(content: &str) -> Vec<SecretMatch> {
330    collect_matches(content, &[], &[])
331}
332
333pub fn detect_secrets_with_custom(content: &str, custom_patterns: &[String]) -> Vec<SecretMatch> {
334    collect_matches(content, custom_patterns, &[])
335}
336
337pub fn scan_and_redact(
338    content: &str,
339    config: &SecretDetectionConfig,
340) -> (String, Vec<SecretMatch>) {
341    if !config.enabled {
342        return (content.to_string(), Vec::new());
343    }
344
345    let excludes = compile_excludes(&config.exclude_patterns);
346    let matches = collect_matches(content, &config.custom_patterns, &excludes);
347
348    if matches.is_empty() || !config.redact {
349        return (content.to_string(), matches);
350    }
351
352    // The same masker and the same labels as every other redaction pass
353    // (`redaction::redact_counting`): one spelling per secret kind.
354    let mut redacted = crate::core::redaction::redact_text_with_excludes(content, &excludes);
355
356    for pattern_str in &config.custom_patterns {
357        if let Ok(re) = Regex::new(pattern_str) {
358            redacted = re
359                .replace_all(&redacted, |caps: &regex::Captures| {
360                    let whole = caps.get(0).map_or("", |m| m.as_str());
361                    if excluded(&excludes, whole) {
362                        return whole.to_string();
363                    }
364                    "[REDACTED:custom_pattern]".to_string()
365                })
366                .to_string();
367        }
368    }
369
370    (redacted, matches)
371}
372
373pub fn scan_and_redact_from_config(content: &str) -> (String, Vec<SecretMatch>) {
374    let cfg = Config::load();
375    scan_and_redact(content, &cfg.secret_detection)
376}
377
378#[cfg(test)]
379#[path = "security_corpus_tests.rs"]
380mod security_corpus_tests;
381
382#[cfg(test)]
383pub mod tests {
384    use super::*;
385
386    #[test]
387    fn detects_aws_key() {
388        let input = concat!("aws_key = AK", "IAIOSFODNN7EXAMPLE");
389        let matches = detect_secrets(input);
390        assert!(matches.iter().any(|m| m.pattern_name == "aws_key"));
391    }
392
393    #[test]
394    fn detects_private_key_header() {
395        let input = concat!("-----BEGIN RSA PRIVATE", " KEY-----\nMIIEpAIB...");
396        let matches = detect_secrets(input);
397        assert!(matches.iter().any(|m| m.pattern_name == "private_key"));
398    }
399
400    #[test]
401    fn detects_github_token() {
402        let input = concat!(
403            "export GITHUB_TOKEN=gh",
404            "p_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk"
405        );
406        let matches = detect_secrets(input);
407        assert!(matches.iter().any(|m| m.pattern_name == "github_token"));
408    }
409
410    #[test]
411    fn detects_anthropic_key() {
412        let input = concat!("ANTHROPIC_API_KEY=sk-ant-api03-", "abcdef1234567890ABCD");
413        let matches = detect_secrets(input);
414        assert!(matches.iter().any(|m| m.pattern_name == "anthropic_key"));
415    }
416
417    #[test]
418    fn detects_openai_key() {
419        let input = concat!("OPENAI_API_KEY=sk-", "abcdefghijklmnopqrstuvwx");
420        let matches = detect_secrets(input);
421        assert!(matches.iter().any(|m| m.pattern_name == "openai_key"));
422    }
423
424    #[test]
425    fn detects_gitlab_pat() {
426        let input = concat!("token = glpat-", "xxxxxxxxxxxxxxxxxxxx");
427        let matches = detect_secrets(input);
428        assert!(matches.iter().any(|m| m.pattern_name == "gitlab_pat"));
429    }
430
431    #[test]
432    fn detects_generic_api_key() {
433        let input = concat!("api_key = abcdefghijklmnop", "qrstuvwxyz1234567890");
434        let matches = detect_secrets(input);
435        assert!(matches.iter().any(
436            |m| m.pattern_name == "generic_api_key" || m.pattern_name == "high_entropy_secret"
437        ));
438    }
439
440    #[test]
441    fn clean_content_returns_empty() {
442        let input = "fn main() { println!(\"hello world\"); }";
443        let matches = detect_secrets(input);
444        assert!(matches.is_empty());
445    }
446
447    #[test]
448    fn detects_jwt() {
449        let input = concat!("token = eyJhbGciOiJIU", "zI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkw");
450        let matches = detect_secrets(input);
451        assert!(matches.iter().any(|m| m.pattern_name == "jwt"));
452    }
453
454    #[test]
455    fn detects_slack_token() {
456        let input = concat!("SLACK_TOKEN=xoxb-12345", "67890-abcdefghij");
457        let matches = detect_secrets(input);
458        assert!(matches.iter().any(|m| m.pattern_name == "slack_token"));
459    }
460
461    #[test]
462    fn detects_stripe_key() {
463        let input = concat!("stripe_key = sk_", "live_abcdefghij1234567890");
464        let matches = detect_secrets(input);
465        assert!(matches.iter().any(|m| m.pattern_name == "stripe_key"));
466    }
467
468    #[test]
469    fn detects_stripe_test_and_webhook_secrets() {
470        let test_key = concat!("sk_", "test_abcdefghij1234567890");
471        assert!(
472            detect_secrets(test_key)
473                .iter()
474                .any(|m| m.pattern_name == "stripe_key")
475        );
476        let webhook = concat!("whsec_", "abcdefghij1234567890");
477        assert!(
478            detect_secrets(webhook)
479                .iter()
480                .any(|m| m.pattern_name == "stripe_webhook_secret")
481        );
482        assert!(detect_secrets("whsec_ prefix").is_empty());
483    }
484
485    #[test]
486    fn detects_db_url() {
487        let input = concat!(
488            "DATABASE_URL=postgres://user:pass",
489            "word@localhost:5432/db"
490        );
491        let matches = detect_secrets(input);
492        assert!(matches.iter().any(|m| m.pattern_name == "db_url"));
493    }
494
495    /// Ops telemetry (3.11.4): `ctx_read` withheld whole files with
496    /// `(secret.redacted, redaction.incomplete)` — the redacted database URL
497    /// `scheme://[REDACTED:db_url]@host` matched the detector's
498    /// `user:password@` again. Redacted output must never re-match.
499    #[test]
500    fn redacted_database_urls_do_not_match_again() {
501        let url = |scheme: &str, user: &str, pw: &str| {
502            format!("{scheme}{}{user}:{pw}{}db.internal:5432/app", "://", "@")
503        };
504        let cases = [
505            url("postgres", "app", "s3cretPassw0rd"),
506            url("postgresql", "app", "Zq7Lm2Vx"),
507            url("mysql", "root", "hunter2hunter2"),
508            url("mongodb+srv", "admin", "Xy9pQ2rT"),
509            url("redis", "", "Zk3mP9qL"),
510            url("postgres", "app", "p@ss"),
511        ];
512        let report_only = SecretDetectionConfig {
513            redact: false,
514            ..SecretDetectionConfig::default()
515        };
516        for case in cases {
517            let input = format!("DATABASE_URL={case}\nkeep after\n");
518            assert!(
519                detect_secrets(&input)
520                    .iter()
521                    .any(|m| m.pattern_name == "db_url"),
522                "credential must be detected: {input}"
523            );
524            let (redacted, _) = scan_and_redact(&input, &SecretDetectionConfig::default());
525            assert!(
526                !redacted.contains("Passw0rd") && !redacted.contains("ss@db"),
527                "{redacted}"
528            );
529            assert!(redacted.ends_with("keep after\n"), "{redacted}");
530            let (_, residual) = scan_and_redact(&redacted, &report_only);
531            assert!(
532                residual.is_empty(),
533                "re-scan of {redacted} found {residual:?}"
534            );
535        }
536        // A documentation placeholder is neither reported nor rewritten.
537        let doc = format!("DATABASE_URL={}\n", url("postgres", "user", "changeme"));
538        assert!(detect_secrets(&doc).is_empty(), "{doc}");
539    }
540
541    #[test]
542    fn detects_npm_token() {
543        let input = concat!("NPM_TOKEN=npm_abcd", "efghij1234567890");
544        let matches = detect_secrets(input);
545        assert!(matches.iter().any(|m| m.pattern_name == "npm_token"));
546    }
547
548    #[test]
549    fn detects_github_fine_grained() {
550        let input = concat!("token = github_pat_ABC", "DEFGHIJKLMNOPQRSTuv");
551        let matches = detect_secrets(input);
552        assert!(
553            matches
554                .iter()
555                .any(|m| m.pattern_name == "github_fine_grained")
556        );
557    }
558
559    #[test]
560    fn redacted_preview_format() {
561        let preview = make_redacted_preview(concat!("AK", "IAIOSFODNN7EXAMPLE"));
562        assert!(preview.starts_with("AKIA"));
563        assert!(preview.ends_with("LE"));
564        assert!(preview.contains("***"));
565    }
566
567    #[test]
568    fn redacted_preview_short_string() {
569        let preview = make_redacted_preview("short");
570        assert_eq!(preview, "***");
571    }
572
573    #[test]
574    fn scan_and_redact_replaces_secrets() {
575        let cfg = SecretDetectionConfig {
576            enabled: true,
577            redact: true,
578            ..Default::default()
579        };
580        let input = concat!("key = AK", "IAIOSFODNN7EXAMPLE");
581        let (redacted, matches) = scan_and_redact(input, &cfg);
582        assert!(!matches.is_empty());
583        assert!(redacted.contains("[REDACTED:AWS key]"));
584        assert!(!redacted.contains(concat!("AK", "IAIOSFODNN7EXAMPLE")));
585    }
586
587    #[test]
588    fn scan_without_redact_preserves_content() {
589        let cfg = SecretDetectionConfig {
590            enabled: true,
591            redact: false,
592            ..Default::default()
593        };
594        let input = concat!("key = AK", "IAIOSFODNN7EXAMPLE");
595        let (output, matches) = scan_and_redact(input, &cfg);
596        assert!(!matches.is_empty());
597        assert_eq!(output, input);
598    }
599
600    #[test]
601    fn disabled_detection_returns_unchanged() {
602        let cfg = SecretDetectionConfig {
603            enabled: false,
604            redact: true,
605            ..Default::default()
606        };
607        let input = concat!("key = AK", "IAIOSFODNN7EXAMPLE");
608        let (output, matches) = scan_and_redact(input, &cfg);
609        assert!(matches.is_empty());
610        assert_eq!(output, input);
611    }
612
613    #[test]
614    fn custom_pattern_detected() {
615        let cfg = SecretDetectionConfig {
616            enabled: true,
617            redact: true,
618            custom_patterns: vec![r"MYCORP_[A-Z]{10,}".to_string()],
619            ..Default::default()
620        };
621        let input = "value is MYCORP_ABCDEFGHIJKLMNO here";
622        let (redacted, matches) = scan_and_redact(input, &cfg);
623        assert!(matches.iter().any(|m| m.pattern_name == "custom_pattern"));
624        assert!(redacted.contains("[REDACTED:custom_pattern]"));
625    }
626
627    #[test]
628    fn line_numbers_are_correct() {
629        let input = concat!("line1\nline2\nAK", "IAIOSFODNN7EXAMPLE\nline4");
630        let matches = detect_secrets(input);
631        assert!(!matches.is_empty());
632        assert_eq!(matches[0].line_number, 3);
633    }
634
635    #[test]
636    fn key_value_secret_patterns_do_not_cross_lines() {
637        let input = [
638            "token:",
639            "\n",
640            "ABCDEFGHIJKLMNOP",
641            "QRSTUVWXYZabcdef",
642            "012345",
643        ]
644        .concat();
645        let matches = detect_secrets(&input);
646        assert!(
647            !matches
648                .iter()
649                .any(|m| matches!(m.pattern_name, "generic_api_key" | "high_entropy_secret")),
650            "a valueless key must not consume the next line: {matches:?}"
651        );
652
653        let same_line_input =
654            ["token: ", "ABCDEFGHIJKLMNOP", "QRSTUVWXYZabcdef", "012345"].concat();
655        let matches = detect_secrets(&same_line_input);
656        assert!(
657            matches.iter().any(|m| m.pattern_name == "generic_api_key"),
658            "same-line key/value secrets must still be detected: {matches:?}"
659        );
660    }
661
662    #[test]
663    fn multiple_secrets_on_different_lines() {
664        let input = concat!(
665            "AK",
666            "IAIOSFODNN7EXAMPLE\nclean\nsk-abcdef",
667            "ghijklmnopqrstuvwx"
668        );
669        let matches = detect_secrets(input);
670        assert!(matches.len() >= 2);
671        let aws = matches
672            .iter()
673            .find(|m| m.pattern_name == "aws_key")
674            .unwrap();
675        assert_eq!(aws.line_number, 1);
676        let oai = matches
677            .iter()
678            .find(|m| m.pattern_name == "openai_key")
679            .unwrap();
680        assert_eq!(oai.line_number, 3);
681    }
682
683    #[test]
684    fn ec_private_key_detected() {
685        let input = concat!("-----BEGIN EC PRIVATE", " KEY-----");
686        let matches = detect_secrets(input);
687        assert!(matches.iter().any(|m| m.pattern_name == "private_key"));
688    }
689
690    #[test]
691    fn openssh_private_key_detected() {
692        let input = concat!("-----BEGIN OPENSSH PRIVATE", " KEY-----");
693        let matches = detect_secrets(input);
694        assert!(matches.iter().any(|m| m.pattern_name == "private_key"));
695    }
696
697    /// The context-gateway admission path relies on this contract: report-only mode
698    /// returns the input untouched, custom/exclude patterns are honoured, and redacted
699    /// output has no residual match (admission re-scans it and withholds on a hit).
700    /// Normalization (zero-width, full-width) only affects matching, never the bytes
701    /// outside a redacted span.
702    #[test]
703    fn scan_and_redact_keeps_the_gateway_contract() {
704        let aws = format!("AK\u{200b}IA{}", "Q7".repeat(8));
705        let key_block = [
706            "-----BEGIN PRIVATE KEY",
707            "-----\nbody-line-one\nbody-line-two\n-----END PRIVATE KEY",
708            "-----",
709        ]
710        .concat();
711        let excluded_key = concat!("AK", "IAIOSFODNN7EXAMPLE");
712        let input = format!(
713            "keep before\nAWS_ACCESS_KEY_ID={aws}\n{key_block}\nticket EMP-4711\nsample {excluded_key}\nkeep after\n"
714        );
715        let cfg = SecretDetectionConfig {
716            custom_patterns: vec![r"EMP-\d{4}".into()],
717            exclude_patterns: vec![excluded_key.into()],
718            ..SecretDetectionConfig::default()
719        };
720
721        let report_only = SecretDetectionConfig {
722            redact: false,
723            ..cfg.clone()
724        };
725        let (unchanged, found) = scan_and_redact(&input, &report_only);
726        assert_eq!(unchanged, input, "report-only mode must not touch the text");
727        assert!(!found.is_empty());
728
729        let (redacted, _) = scan_and_redact(&input, &cfg);
730        assert!(redacted.starts_with("keep before\n"), "{redacted}");
731        assert!(redacted.ends_with("keep after\n"), "{redacted}");
732        assert!(
733            redacted.contains(excluded_key),
734            "excluded value kept verbatim"
735        );
736        assert!(!redacted.contains("EMP-4711"), "custom pattern redacted");
737        assert!(!redacted.contains("body-line-one"), "{redacted}");
738        let (_, residual) = scan_and_redact(&redacted, &report_only);
739        assert!(
740            residual.is_empty(),
741            "redacted output must not match again: {residual:?}\n{redacted}"
742        );
743    }
744}