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
41fn 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
70fn 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
90fn stripe_key_re() -> &'static Regex {
91 static_regex!(r"[sr]k_live_[0-9a-zA-Z]{10,}")
92}
93
94fn db_url_re() -> &'static Regex {
95 static_regex!(r"(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis)://[^\s]+:[^\s]+@")
96}
97
98fn npm_token_re() -> &'static Regex {
99 static_regex!(r"npm_[A-Za-z0-9]{10,}")
100}
101
102fn github_fine_grained_re() -> &'static Regex {
103 static_regex!(r"github_pat_[A-Za-z0-9_]{20,}")
104}
105
106const BUILTIN_PATTERNS: &[(&str, fn() -> &'static Regex)] = &[
107 ("aws_key", aws_key_re),
108 ("authorization_header", authorization_header_re),
109 ("private_key", private_key_re),
110 ("github_token", github_token_re),
111 ("github_fine_grained", github_fine_grained_re),
112 ("anthropic_key", anthropic_key_re),
113 ("openai_key", openai_key_re),
114 ("gitlab_pat", gitlab_pat_re),
115 ("jwt", jwt_re),
116 ("slack_token", slack_token_re),
117 ("stripe_key", stripe_key_re),
118 ("db_url", db_url_re),
119 ("npm_token", npm_token_re),
120];
121
122const GUARDED_PATTERNS: &[(&str, fn() -> &'static Regex)] = &[
126 ("generic_api_key", generic_api_key_re),
127 ("high_entropy_secret", high_entropy_b64_re),
128 ("url_encoded_secret", url_encoded_secret_re),
129];
130
131fn guarded_match_is_benign(caps: ®ex::Captures) -> bool {
135 let quoted = caps
138 .get(1)
139 .is_some_and(|prefix| prefix.as_str().ends_with(['"', '\'']));
140 caps.get(2).is_some_and(|value| {
141 if quoted {
142 crate::core::redaction::is_benign_quoted_value(value.as_str())
143 } else {
144 crate::core::redaction::is_benign_secret_value(value.as_str())
145 }
146 })
147}
148
149fn compile_excludes(patterns: &[String]) -> Vec<Regex> {
152 patterns.iter().filter_map(|p| Regex::new(p).ok()).collect()
153}
154
155fn excluded(excludes: &[Regex], matched: &str) -> bool {
156 excludes.iter().any(|ex| ex.is_match(matched))
157}
158
159fn make_redacted_preview(matched: &str) -> String {
160 let chars: Vec<char> = matched.chars().collect();
161 if chars.len() <= 6 {
162 return "***".to_string();
163 }
164 let prefix: String = chars[..4].iter().collect();
165 let suffix: String = chars[chars.len() - 2..].iter().collect();
166 format!("{prefix}***{suffix}")
167}
168
169fn collect_matches(
170 content: &str,
171 custom_patterns: &[String],
172 excludes: &[Regex],
173) -> Vec<SecretMatch> {
174 let mut matches = Vec::new();
175 let normalized = crate::core::redaction::normalize_secret_text(content);
176
177 let line_offsets: std::cell::OnceCell<Vec<usize>> = std::cell::OnceCell::new();
180
181 let offset_to_line = |byte_offset: usize| -> usize {
182 let line_offsets = line_offsets.get_or_init(|| {
183 std::iter::once(0)
184 .chain(normalized.match_indices('\n').map(|(i, _)| i + 1))
185 .collect()
186 });
187 match line_offsets.binary_search(&byte_offset) {
188 Ok(i) => i + 1,
189 Err(i) => i,
190 }
191 };
192
193 for &(name, regex_fn) in BUILTIN_PATTERNS {
194 let re = regex_fn();
195 for m in re.find_iter(&normalized) {
196 if excluded(excludes, m.as_str()) {
197 continue;
198 }
199 matches.push(SecretMatch {
200 pattern_name: name,
201 line_number: offset_to_line(m.start()),
202 redacted_preview: make_redacted_preview(m.as_str()),
203 });
204 }
205 }
206
207 for caps in bearer_token_re().captures_iter(&normalized) {
208 let Some(whole) = caps.get(0) else {
209 continue;
210 };
211 let credential = caps.get(1).is_some_and(|value| {
212 crate::core::redaction::bearer_value_is_credential(value.as_str())
213 });
214 if !credential || excluded(excludes, whole.as_str()) {
215 continue;
216 }
217 matches.push(SecretMatch {
218 pattern_name: "bearer_token",
219 line_number: offset_to_line(whole.start()),
220 redacted_preview: make_redacted_preview(whole.as_str()),
221 });
222 }
223
224 for &(name, regex_fn) in GUARDED_PATTERNS {
225 let re = regex_fn();
226 for caps in re.captures_iter(&normalized) {
227 let whole = caps.get(0).map_or("", |m| m.as_str());
228 if guarded_match_is_benign(&caps) || excluded(excludes, whole) {
229 continue;
230 }
231 let start = caps.get(0).map_or(0, |m| m.start());
232 matches.push(SecretMatch {
233 pattern_name: name,
234 line_number: offset_to_line(start),
235 redacted_preview: make_redacted_preview(whole),
236 });
237 }
238 }
239
240 for pattern_str in custom_patterns {
241 if let Ok(re) = Regex::new(pattern_str) {
242 for m in re.find_iter(&normalized) {
243 if excluded(excludes, m.as_str()) {
244 continue;
245 }
246 matches.push(SecretMatch {
247 pattern_name: "custom_pattern",
248 line_number: offset_to_line(m.start()),
249 redacted_preview: make_redacted_preview(m.as_str()),
250 });
251 }
252 }
253 }
254
255 matches
256}
257
258pub fn detect_secrets(content: &str) -> Vec<SecretMatch> {
259 collect_matches(content, &[], &[])
260}
261
262pub fn detect_secrets_with_custom(content: &str, custom_patterns: &[String]) -> Vec<SecretMatch> {
263 collect_matches(content, custom_patterns, &[])
264}
265
266pub fn scan_and_redact(
267 content: &str,
268 config: &SecretDetectionConfig,
269) -> (String, Vec<SecretMatch>) {
270 if !config.enabled {
271 return (content.to_string(), Vec::new());
272 }
273
274 let excludes = compile_excludes(&config.exclude_patterns);
275 let matches = collect_matches(content, &config.custom_patterns, &excludes);
276
277 if matches.is_empty() || !config.redact {
278 return (content.to_string(), matches);
279 }
280
281 let mut redacted =
282 crate::core::redaction::redact_text_with_excludes_for_detection(content, &excludes);
283
284 for pattern_str in &config.custom_patterns {
285 if let Ok(re) = Regex::new(pattern_str) {
286 redacted = re
287 .replace_all(&redacted, |caps: ®ex::Captures| {
288 let whole = caps.get(0).map_or("", |m| m.as_str());
289 if excluded(&excludes, whole) {
290 return whole.to_string();
291 }
292 "[REDACTED:custom_pattern]".to_string()
293 })
294 .to_string();
295 }
296 }
297
298 (redacted, matches)
299}
300
301pub fn scan_and_redact_from_config(content: &str) -> (String, Vec<SecretMatch>) {
302 let cfg = Config::load();
303 scan_and_redact(content, &cfg.secret_detection)
304}
305
306#[cfg(test)]
307#[path = "security_corpus_tests.rs"]
308mod security_corpus_tests;
309
310#[cfg(test)]
311pub mod tests {
312 use super::*;
313
314 #[test]
315 fn detects_aws_key() {
316 let input = concat!("aws_key = AK", "IAIOSFODNN7EXAMPLE");
317 let matches = detect_secrets(input);
318 assert!(matches.iter().any(|m| m.pattern_name == "aws_key"));
319 }
320
321 #[test]
322 fn detects_private_key_header() {
323 let input = concat!("-----BEGIN RSA PRIVATE", " KEY-----\nMIIEpAIB...");
324 let matches = detect_secrets(input);
325 assert!(matches.iter().any(|m| m.pattern_name == "private_key"));
326 }
327
328 #[test]
329 fn detects_github_token() {
330 let input = concat!(
331 "export GITHUB_TOKEN=gh",
332 "p_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk"
333 );
334 let matches = detect_secrets(input);
335 assert!(matches.iter().any(|m| m.pattern_name == "github_token"));
336 }
337
338 #[test]
339 fn detects_anthropic_key() {
340 let input = concat!("ANTHROPIC_API_KEY=sk-ant-api03-", "abcdef1234567890ABCD");
341 let matches = detect_secrets(input);
342 assert!(matches.iter().any(|m| m.pattern_name == "anthropic_key"));
343 }
344
345 #[test]
346 fn detects_openai_key() {
347 let input = concat!("OPENAI_API_KEY=sk-", "abcdefghijklmnopqrstuvwx");
348 let matches = detect_secrets(input);
349 assert!(matches.iter().any(|m| m.pattern_name == "openai_key"));
350 }
351
352 #[test]
353 fn detects_gitlab_pat() {
354 let input = concat!("token = glpat-", "xxxxxxxxxxxxxxxxxxxx");
355 let matches = detect_secrets(input);
356 assert!(matches.iter().any(|m| m.pattern_name == "gitlab_pat"));
357 }
358
359 #[test]
360 fn detects_generic_api_key() {
361 let input = concat!("api_key = abcdefghijklmnop", "qrstuvwxyz1234567890");
362 let matches = detect_secrets(input);
363 assert!(matches.iter().any(
364 |m| m.pattern_name == "generic_api_key" || m.pattern_name == "high_entropy_secret"
365 ));
366 }
367
368 #[test]
369 fn clean_content_returns_empty() {
370 let input = "fn main() { println!(\"hello world\"); }";
371 let matches = detect_secrets(input);
372 assert!(matches.is_empty());
373 }
374
375 #[test]
376 fn detects_jwt() {
377 let input = concat!("token = eyJhbGciOiJIU", "zI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkw");
378 let matches = detect_secrets(input);
379 assert!(matches.iter().any(|m| m.pattern_name == "jwt"));
380 }
381
382 #[test]
383 fn detects_slack_token() {
384 let input = concat!("SLACK_TOKEN=xoxb-12345", "67890-abcdefghij");
385 let matches = detect_secrets(input);
386 assert!(matches.iter().any(|m| m.pattern_name == "slack_token"));
387 }
388
389 #[test]
390 fn detects_stripe_key() {
391 let input = concat!("stripe_key = sk_", "live_abcdefghij1234567890");
392 let matches = detect_secrets(input);
393 assert!(matches.iter().any(|m| m.pattern_name == "stripe_key"));
394 }
395
396 #[test]
397 fn detects_db_url() {
398 let input = concat!(
399 "DATABASE_URL=postgres://user:pass",
400 "word@localhost:5432/db"
401 );
402 let matches = detect_secrets(input);
403 assert!(matches.iter().any(|m| m.pattern_name == "db_url"));
404 }
405
406 #[test]
407 fn detects_npm_token() {
408 let input = concat!("NPM_TOKEN=npm_abcd", "efghij1234567890");
409 let matches = detect_secrets(input);
410 assert!(matches.iter().any(|m| m.pattern_name == "npm_token"));
411 }
412
413 #[test]
414 fn detects_github_fine_grained() {
415 let input = concat!("token = github_pat_ABC", "DEFGHIJKLMNOPQRSTuv");
416 let matches = detect_secrets(input);
417 assert!(
418 matches
419 .iter()
420 .any(|m| m.pattern_name == "github_fine_grained")
421 );
422 }
423
424 #[test]
425 fn redacted_preview_format() {
426 let preview = make_redacted_preview(concat!("AK", "IAIOSFODNN7EXAMPLE"));
427 assert!(preview.starts_with("AKIA"));
428 assert!(preview.ends_with("LE"));
429 assert!(preview.contains("***"));
430 }
431
432 #[test]
433 fn redacted_preview_short_string() {
434 let preview = make_redacted_preview("short");
435 assert_eq!(preview, "***");
436 }
437
438 #[test]
439 fn scan_and_redact_replaces_secrets() {
440 let cfg = SecretDetectionConfig {
441 enabled: true,
442 redact: true,
443 ..Default::default()
444 };
445 let input = concat!("key = AK", "IAIOSFODNN7EXAMPLE");
446 let (redacted, matches) = scan_and_redact(input, &cfg);
447 assert!(!matches.is_empty());
448 assert!(redacted.contains("[REDACTED:aws_key]"));
449 assert!(!redacted.contains(concat!("AK", "IAIOSFODNN7EXAMPLE")));
450 }
451
452 #[test]
453 fn scan_without_redact_preserves_content() {
454 let cfg = SecretDetectionConfig {
455 enabled: true,
456 redact: false,
457 ..Default::default()
458 };
459 let input = concat!("key = AK", "IAIOSFODNN7EXAMPLE");
460 let (output, matches) = scan_and_redact(input, &cfg);
461 assert!(!matches.is_empty());
462 assert_eq!(output, input);
463 }
464
465 #[test]
466 fn disabled_detection_returns_unchanged() {
467 let cfg = SecretDetectionConfig {
468 enabled: false,
469 redact: true,
470 ..Default::default()
471 };
472 let input = concat!("key = AK", "IAIOSFODNN7EXAMPLE");
473 let (output, matches) = scan_and_redact(input, &cfg);
474 assert!(matches.is_empty());
475 assert_eq!(output, input);
476 }
477
478 #[test]
479 fn custom_pattern_detected() {
480 let cfg = SecretDetectionConfig {
481 enabled: true,
482 redact: true,
483 custom_patterns: vec![r"MYCORP_[A-Z]{10,}".to_string()],
484 ..Default::default()
485 };
486 let input = "value is MYCORP_ABCDEFGHIJKLMNO here";
487 let (redacted, matches) = scan_and_redact(input, &cfg);
488 assert!(matches.iter().any(|m| m.pattern_name == "custom_pattern"));
489 assert!(redacted.contains("[REDACTED:custom_pattern]"));
490 }
491
492 #[test]
493 fn line_numbers_are_correct() {
494 let input = concat!("line1\nline2\nAK", "IAIOSFODNN7EXAMPLE\nline4");
495 let matches = detect_secrets(input);
496 assert!(!matches.is_empty());
497 assert_eq!(matches[0].line_number, 3);
498 }
499
500 #[test]
501 fn key_value_secret_patterns_do_not_cross_lines() {
502 let input = [
503 "token:",
504 "\n",
505 "ABCDEFGHIJKLMNOP",
506 "QRSTUVWXYZabcdef",
507 "012345",
508 ]
509 .concat();
510 let matches = detect_secrets(&input);
511 assert!(
512 !matches
513 .iter()
514 .any(|m| matches!(m.pattern_name, "generic_api_key" | "high_entropy_secret")),
515 "a valueless key must not consume the next line: {matches:?}"
516 );
517
518 let same_line_input =
519 ["token: ", "ABCDEFGHIJKLMNOP", "QRSTUVWXYZabcdef", "012345"].concat();
520 let matches = detect_secrets(&same_line_input);
521 assert!(
522 matches.iter().any(|m| m.pattern_name == "generic_api_key"),
523 "same-line key/value secrets must still be detected: {matches:?}"
524 );
525 }
526
527 #[test]
528 fn multiple_secrets_on_different_lines() {
529 let input = concat!(
530 "AK",
531 "IAIOSFODNN7EXAMPLE\nclean\nsk-abcdef",
532 "ghijklmnopqrstuvwx"
533 );
534 let matches = detect_secrets(input);
535 assert!(matches.len() >= 2);
536 let aws = matches
537 .iter()
538 .find(|m| m.pattern_name == "aws_key")
539 .unwrap();
540 assert_eq!(aws.line_number, 1);
541 let oai = matches
542 .iter()
543 .find(|m| m.pattern_name == "openai_key")
544 .unwrap();
545 assert_eq!(oai.line_number, 3);
546 }
547
548 #[test]
549 fn ec_private_key_detected() {
550 let input = concat!("-----BEGIN EC PRIVATE", " KEY-----");
551 let matches = detect_secrets(input);
552 assert!(matches.iter().any(|m| m.pattern_name == "private_key"));
553 }
554
555 #[test]
556 fn openssh_private_key_detected() {
557 let input = concat!("-----BEGIN OPENSSH PRIVATE", " KEY-----");
558 let matches = detect_secrets(input);
559 assert!(matches.iter().any(|m| m.pattern_name == "private_key"));
560 }
561
562 #[test]
568 fn scan_and_redact_keeps_the_gateway_contract() {
569 let aws = format!("AK\u{200b}IA{}", "Q7".repeat(8));
570 let key_block = [
571 "-----BEGIN PRIVATE KEY",
572 "-----\nbody-line-one\nbody-line-two\n-----END PRIVATE KEY",
573 "-----",
574 ]
575 .concat();
576 let excluded_key = concat!("AK", "IAIOSFODNN7EXAMPLE");
577 let input = format!(
578 "keep before\nAWS_ACCESS_KEY_ID={aws}\n{key_block}\nticket EMP-4711\nsample {excluded_key}\nkeep after\n"
579 );
580 let cfg = SecretDetectionConfig {
581 custom_patterns: vec![r"EMP-\d{4}".into()],
582 exclude_patterns: vec![excluded_key.into()],
583 ..SecretDetectionConfig::default()
584 };
585
586 let report_only = SecretDetectionConfig {
587 redact: false,
588 ..cfg.clone()
589 };
590 let (unchanged, found) = scan_and_redact(&input, &report_only);
591 assert_eq!(unchanged, input, "report-only mode must not touch the text");
592 assert!(!found.is_empty());
593
594 let (redacted, _) = scan_and_redact(&input, &cfg);
595 assert!(redacted.starts_with("keep before\n"), "{redacted}");
596 assert!(redacted.ends_with("keep after\n"), "{redacted}");
597 assert!(
598 redacted.contains(excluded_key),
599 "excluded value kept verbatim"
600 );
601 assert!(!redacted.contains("EMP-4711"), "custom pattern redacted");
602 assert!(!redacted.contains("body-line-one"), "{redacted}");
603 let (_, residual) = scan_and_redact(&redacted, &report_only);
604 assert!(
605 residual.is_empty(),
606 "redacted output must not match again: {residual:?}\n{redacted}"
607 );
608 }
609}