1macro_rules! static_regex {
2 ($pattern:expr_2021) => {{
3 static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
4 RE.get_or_init(|| {
5 regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
6 })
7 }};
8}
9
10pub mod structured;
11
12pub fn redaction_enabled_for_active_role() -> bool {
13 let role = crate::core::roles::active_role();
14 if role.role.name == "admin" {
15 role.io.redact_outputs
16 } else {
17 true
19 }
20}
21
22pub fn redact_text_if_enabled(input: &str) -> String {
28 if !redaction_enabled_for_active_role() {
29 return input.to_string();
30 }
31 let (out, found) = redact_found(input, config_exclude_patterns().as_slice());
32 let hits = found.len();
33 if hits > 0 {
35 crate::core::cloud_signals::note_secrets(&found);
36 }
37 crate::core::security_events::note(
38 crate::core::security_events::SecurityKind::SecretRedacted,
39 hits,
40 );
41 out
42}
43
44fn looks_like_number(v: &str) -> bool {
53 if v.is_empty() {
54 return false;
55 }
56 let s = v.trim_start_matches(['+', '-']);
57 if s.is_empty() {
58 return false;
59 }
60 s.parse::<f64>().is_ok()
62 && s.chars()
63 .all(|c| c.is_ascii_digit() || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-')
64}
65
66fn looks_like_uuid(value: &str) -> bool {
67 let value = value
68 .trim()
69 .trim_matches(|c| c == '"' || c == '\'' || c == '`' || c == '{' || c == '}');
70 let groups: Vec<&str> = value.split('-').collect();
71 groups.len() == 5
72 && [8, 4, 4, 4, 12].iter().zip(&groups).all(|(len, group)| {
73 group.len() == *len && group.chars().all(|ch| ch.is_ascii_hexdigit())
74 })
75}
76
77fn is_env_reference(v: &str) -> bool {
81 if v.starts_with("os.environ/")
82 || v.starts_with("os.getenv(")
83 || v.starts_with("process.env.")
84 || v.starts_with("System.getenv(")
85 || v.starts_with("ENV[")
86 || v.starts_with("env(")
87 {
88 return true;
89 }
90 if (v.starts_with("${") && v.ends_with('}'))
92 || (v.starts_with('$')
93 && v[1..]
94 .chars()
95 .all(|c| c.is_ascii_alphanumeric() || c == '_'))
96 || (v.starts_with('%') && v.ends_with('%') && v.len() > 2)
97 {
98 return true;
99 }
100 if let Some(prefix) = v.split('.').next() {
102 let pl = prefix.to_ascii_lowercase();
103 if matches!(
104 pl.as_str(),
105 "env" | "inputenv" | "serverenv" | "secrets" | "vars" | "environ"
106 ) && v.contains('.')
107 {
108 return true;
109 }
110 }
111 false
112}
113
114fn is_identifier_reference(value: &str) -> bool {
115 let v = value.trim();
116 if v.is_empty() || v.starts_with('"') || v.starts_with('\'') || v.starts_with('`') {
117 return false;
118 }
119 if is_env_reference(v) {
122 return true;
123 }
124 if v.contains(|c: char| c.is_ascii_digit()) {
125 return false;
126 }
127 v.split('.').all(|segment| {
128 let mut chars = segment.chars();
129 matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$')
130 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
131 })
132}
133
134fn is_placeholder_value(value: &str) -> bool {
139 let v = value
140 .trim()
141 .trim_matches(|c| c == '"' || c == '\'' || c == '`')
142 .to_ascii_lowercase();
143 if v.starts_with('<') && v.ends_with('>') {
144 return true;
145 }
146 if !v.is_empty() && v.chars().all(|c| c == '*') {
147 return true;
148 }
149 const MARKERS: &[&str] = &[
150 "change_me",
151 "change-me",
152 "changeme",
153 "example",
154 "placeholder",
155 "your_",
156 "your-",
157 "xxx",
158 "dummy",
159 "sample",
160 "todo",
161 "fixme",
162 "replace_me",
163 "replace-me",
164 "redacted",
165 "...",
166 "…",
167 ];
168 MARKERS.iter().any(|m| v.contains(m))
169}
170
171fn is_non_secret_literal(value: &str) -> bool {
176 let v = value
177 .trim()
178 .trim_matches(|c| c == '"' || c == '\'' || c == '`');
179 if looks_like_number(v) {
182 return true;
183 }
184 if v.contains(['<', '>', '|', '(', ')', '[', ']', '{', '}']) {
190 return lean_ctx_protocol::credential_redaction::is_code_shaped(v);
191 }
192 matches!(
193 v.to_ascii_lowercase().as_str(),
194 "" | "undefined"
195 | "null"
196 | "none"
197 | "nil"
198 | "true"
199 | "false"
200 | "string"
201 | "number"
202 | "boolean"
203 | "bigint"
204 | "symbol"
205 | "object"
206 | "any"
207 | "unknown"
208 | "never"
209 | "void"
210 | "nan"
211 | "date"
212 ) || is_primitive_type_name(v)
213}
214
215fn is_primitive_type_name(value: &str) -> bool {
221 matches!(
222 value,
223 "bool"
224 | "char"
225 | "str"
226 | "usize"
227 | "isize"
228 | "u8"
229 | "u16"
230 | "u32"
231 | "u64"
232 | "u128"
233 | "i8"
234 | "i16"
235 | "i32"
236 | "i64"
237 | "i128"
238 | "f32"
239 | "f64"
240 | "int"
241 | "int8"
242 | "int16"
243 | "int32"
244 | "int64"
245 | "uint"
246 | "uint8"
247 | "uint16"
248 | "uint32"
249 | "uint64"
250 | "uintptr"
251 | "float"
252 | "float32"
253 | "float64"
254 | "double"
255 | "long"
256 | "short"
257 | "byte"
258 | "rune"
259 | "error"
260 | "Self"
261 )
262}
263
264struct Rule {
266 label: &'static str,
267 re: &'static regex::Regex,
268 guard_value: bool,
274}
275
276fn normalize_for_secret_matching(input: &str) -> (String, Vec<usize>) {
280 let mut normalized = String::with_capacity(input.len());
281 let mut original_boundaries = vec![0usize];
282
283 for (start, ch) in input.char_indices() {
284 let end = start + ch.len_utf8();
285 let Some(folded) = fold_secret_match_char(ch) else {
286 if let Some(boundary) = original_boundaries.last_mut() {
287 *boundary = end;
288 }
289 continue;
290 };
291 let folded_len = folded.len_utf8();
292 normalized.push(folded);
293 for byte in 1..=folded_len {
294 original_boundaries.push(if byte == folded_len { end } else { start });
295 }
296 }
297
298 (normalized, original_boundaries)
299}
300
301fn fold_secret_match_char(ch: char) -> Option<char> {
302 if matches!(
303 ch,
304 '\u{200b}' | '\u{200c}' | '\u{200d}' | '\u{2060}' | '\u{feff}'
305 ) {
306 return None;
307 }
308 Some(match ch {
309 '\u{3000}' => ' ',
310 '\u{ff01}'..='\u{ff5e}' => char::from_u32(ch as u32 - 0xfee0).unwrap_or(ch),
311 _ => ch,
312 })
313}
314
315pub(crate) fn normalize_secret_text(input: &str) -> String {
317 input.chars().filter_map(fold_secret_match_char).collect()
318}
319
320const PRIVATE_KEY_KINDS: &str = r"(?:RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----";
323
324fn private_key_marker(end: bool) -> &'static regex::Regex {
325 static HEADER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
326 static END: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
327 let (cell, word) = if end {
328 (&END, "END")
329 } else {
330 (&HEADER, "BEGIN")
331 };
332 cell.get_or_init(|| {
333 regex::Regex::new(&format!(r"-----{word}\s+{PRIVATE_KEY_KINDS}"))
334 .expect("BUG: invalid private-key marker")
335 })
336}
337
338pub fn ends_inside_private_key_block(text: &str) -> bool {
342 let normalized = normalize_secret_text(text);
343 let last = |end: bool| {
344 private_key_marker(end)
345 .find_iter(&normalized)
346 .last()
347 .map(|found| found.start())
348 };
349 match (last(false), last(true)) {
350 (Some(header), Some(end)) => header > end,
351 (Some(_), None) => true,
352 (None, _) => false,
353 }
354}
355
356pub fn contains_private_key_end(text: &str) -> bool {
359 private_key_marker(true).is_match(&normalize_secret_text(text))
360}
361
362pub(crate) fn bearer_value_is_credential(value: &str) -> bool {
368 let classes = [
369 value.bytes().any(|b| b.is_ascii_uppercase()),
370 value.bytes().any(|b| b.is_ascii_lowercase()),
371 value.bytes().any(|b| b.is_ascii_digit()),
372 ];
373 value.len() >= 16
374 && classes.iter().filter(|present| **present).count() >= 2
375 && !is_placeholder_value(value)
376}
377
378pub(crate) fn is_benign_secret_value(value: &str) -> bool {
391 secret_value_span(value, false).is_none()
392}
393
394pub(crate) fn is_benign_quoted_value(value: &str) -> bool {
399 secret_value_span(value, true).is_none()
400}
401
402pub(crate) fn secret_value_span(value: &str, quoted: bool) -> Option<std::ops::Range<usize>> {
408 let canonical = canonical_secret_value(value);
409 let operand = if quoted {
410 canonical
411 } else {
412 if is_comparison_operator_residue(canonical) {
413 return None;
414 }
415 let operand = canonical.trim_start_matches(['=', '!', ':']);
418 if operand.is_empty() {
419 return None;
420 }
421 operand
422 };
423 let benign = |v: &str| {
424 if quoted {
425 is_comparison_operator_residue(v)
426 || is_non_secret_literal(v)
427 || is_placeholder_value(v)
428 || looks_like_uuid(v)
429 || (!v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()))
430 } else {
431 is_non_secret_literal(v)
432 || is_identifier_reference(v)
433 || is_placeholder_value(v)
434 || looks_like_uuid(v)
435 }
436 };
437 if !benign(operand) {
438 return Some(0..value.len());
439 }
440 let run = detector_run_len(operand);
441 if run == operand.len() || run < 20 || benign(&operand[..run]) {
442 return None;
443 }
444 let start = (value.len() - value.trim_start().len()) + (canonical.len() - operand.len());
445 Some(start..start + run)
446}
447
448fn canonical_secret_value(value: &str) -> &str {
452 let mut v = value.trim();
453 loop {
454 if let Some(rest) = v.strip_suffix(':') {
455 v = rest;
456 continue;
457 }
458 let open = match v.chars().last() {
459 Some(')') => '(',
460 Some(']') => '[',
461 Some('}') => '{',
462 _ => break,
463 };
464 let close = v.chars().last().unwrap_or(')');
465 if v.matches(open).count() >= v.matches(close).count() {
466 break;
467 }
468 v = &v[..v.len() - 1];
469 }
470 v
471}
472
473fn detector_run_len(value: &str) -> usize {
478 value
479 .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '/' | '=' | '-')))
480 .unwrap_or(value.len())
481}
482
483pub(crate) fn is_fact_key_slug(prefix: &str, value: &str) -> bool {
500 matches!(prefix, "\"key\":\"" | "\"key\": \"") && looks_like_word_slug(value)
501}
502
503fn looks_like_word_slug(value: &str) -> bool {
516 let parts: Vec<&str> = value.split('-').collect();
517 let mut words = 0usize;
518 let mut letter_parts = 0usize;
519 let all_parts_ok = parts.iter().all(|part| {
520 if !part.is_empty() && part.len() <= 8 && part.bytes().all(|b| b.is_ascii_digit()) {
521 return true;
522 }
523 if part.len() < 2 || part.len() > 24 || !part.bytes().all(|b| b.is_ascii_lowercase()) {
524 return false;
525 }
526 letter_parts += 1;
527 let word = is_slug_word(part);
528 words += usize::from(word);
529 word || SLUG_ABBREVIATIONS.contains(part)
530 });
531 parts.len() >= 3 && all_parts_ok && words >= 2 && words * 2 >= letter_parts
532}
533
534const SLUG_ABBREVIATIONS: &[&str] = &[
537 "cd", "cdn", "cfg", "cmd", "csv", "ctx", "db", "dns", "gc", "grpc", "http", "js", "jwt", "mcp",
538 "md", "ml", "mr", "msg", "npm", "pdf", "pkg", "png", "pr", "rs", "sql", "src", "ssh", "svg",
539 "tls", "tmp", "ts", "ttl", "xml",
540];
541
542const SLUG_ONSETS: &[&str] = &[
544 "", "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w",
545 "x", "z", "bl", "br", "ch", "cl", "cr", "dr", "fl", "fr", "gl", "gr", "ph", "pl", "pr", "sc",
546 "sh", "sk", "sl", "sm", "sn", "sp", "st", "sw", "th", "tr", "tw", "wh", "wr", "chr", "sch",
547 "scr", "shr", "spl", "spr", "str", "thr",
548];
549
550const SLUG_CODAS: &[&str] = &[
552 "bs", "ch", "ck", "cks", "ct", "cts", "ds", "ft", "fts", "ght", "ghts", "gs", "ks", "ld",
553 "lds", "lf", "lk", "lks", "ll", "lls", "lm", "lp", "ls", "lt", "lts", "mp", "mps", "ms", "nch",
554 "nd", "nds", "ng", "ngs", "ngth", "ngths", "nk", "nks", "ns", "nt", "nth", "nths", "nts", "ps",
555 "pt", "pts", "rch", "rd", "rds", "rk", "rks", "rm", "rms", "rn", "rns", "rst", "rt", "rth",
556 "rts", "sh", "sk", "sks", "sp", "ss", "st", "sts", "tch", "th", "ths", "ts", "ws", "x", "xt",
557 "xts",
558];
559
560fn is_slug_word(part: &str) -> bool {
561 let is_vowel = |b: u8| matches!(b, b'a' | b'e' | b'i' | b'o' | b'u' | b'y');
562 let vowels = part.bytes().filter(|b| is_vowel(*b)).count();
563 let mut run = 0usize;
564 let mut longest_run = 0usize;
565 for b in part.bytes() {
566 run = if is_vowel(b) { 0 } else { run + 1 };
567 longest_run = longest_run.max(run);
568 }
569 if vowels * 5 >= part.len() && longest_run <= 4 {
570 return true;
571 }
572 if vowels != 1 || !(5..=9).contains(&part.len()) {
573 return false;
574 }
575 let Some(at) = part.bytes().position(is_vowel) else {
576 return false;
577 };
578 SLUG_ONSETS.contains(&&part[..at]) && SLUG_CODAS.contains(&&part[at + 1..])
579}
580
581fn is_comparison_operator_residue(value: &str) -> bool {
585 let v = value.trim();
586 matches!(v, "=" | "==" | "!=" | "<=" | ">=" | "===" | "!==")
587}
588
589fn redaction_rules() -> Vec<Rule> {
598 vec![
599 Rule {
600 label: "Bearer token",
601 re: static_regex!(r"(?i)(bearer[ \t]+)([a-zA-Z0-9_\-\.]{8,})"),
604 guard_value: false,
605 },
606 Rule {
607 label: "Authorization header",
608 re: static_regex!(
611 r"(?i)(authorization[ \t]*:[ \t]*(?:basic|bearer|token)[ \t]+)([A-Za-z0-9._~+/=-]+)"
612 ),
613 guard_value: false,
614 },
615 Rule {
618 label: "AWS key",
619 re: static_regex!(r"(?:AKIA|ASIA)[0-9A-Z]{16}"),
620 guard_value: false,
621 },
622 Rule {
623 label: "Private key block",
624 re: static_regex!(
631 r"(?s)-----BEGIN\s+(?:RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----(?:.+?-----END\s+(?:RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----|(?-s:[^\n]*)(?:\r?\n[A-Za-z-]+:(?-s:[^\n]*))*(?:\r?\n[A-Za-z0-9+/=]+[ \t]*(?m:$))*)"
632 ),
633 guard_value: false,
634 },
635 Rule {
636 label: "GitHub token",
637 re: static_regex!(r"(gh[pousr]_)[a-zA-Z0-9_]{20,}"),
638 guard_value: false,
639 },
640 Rule {
641 label: "GitHub fine-grained token",
642 re: static_regex!(r"(github_pat_)[A-Za-z0-9_]{20,}"),
643 guard_value: false,
644 },
645 Rule {
646 label: "GitLab token",
647 re: static_regex!(r"(glpat-)[A-Za-z0-9_\-]{20,}"),
648 guard_value: false,
649 },
650 Rule {
654 label: "Anthropic API key",
655 re: crate::core::secret_detection::anthropic_key_re(),
656 guard_value: false,
657 },
658 Rule {
659 label: "OpenAI API key",
660 re: crate::core::secret_detection::openai_key_re(),
661 guard_value: false,
662 },
663 Rule {
664 label: "JWT",
665 re: static_regex!(
666 r"eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}(?:\.[A-Za-z0-9_\-]{8,})?"
667 ),
668 guard_value: false,
669 },
670 Rule {
671 label: "Slack token",
672 re: static_regex!(r"(xox[bpas]-)[0-9a-zA-Z\-]{10,}"),
673 guard_value: false,
674 },
675 Rule {
676 label: "Stripe key",
677 re: crate::core::secret_detection::stripe_key_re(),
680 guard_value: false,
681 },
682 Rule {
683 label: "Stripe webhook secret",
684 re: crate::core::secret_detection::stripe_webhook_secret_re(),
685 guard_value: false,
686 },
687 Rule {
688 label: "npm token",
689 re: static_regex!(r"(npm_)[A-Za-z0-9]{10,}"),
690 guard_value: false,
691 },
692 Rule {
695 label: "API key param",
696 re: static_regex!(
697 r#"(?im)((?:^|[^a-z0-9])(?:aws[_-]?secret[_-]?access[_-]?key|secret[_-]?access[_-]?key|api[_-]?key|apikey|access[_-]?key|secret[_-]?key|access[_-]?token|client[_-]?secret|token|password|passwd|pwd|secret)(?:\\?["'])?[ \t]*[=:][ \t]*(?:\\?["'])?)([^\s\r\n,;&"']+)"#
698 ),
699 guard_value: true,
700 },
701 Rule {
702 label: "URL-encoded secret",
703 re: static_regex!(
704 r"(?im)((?:^|[^a-z0-9])(?:aws[_-]?secret[_-]?access[_-]?key|secret[_-]?access[_-]?key|api[_-]?key|apikey|access[_-]?key|secret[_-]?key|access[_-]?token|client[_-]?secret|token|password|passwd|pwd|secret)[ \t]*[=:][ \t]*)(?:((?:%[0-9a-f]{2}|[A-Za-z0-9_\-]){20,}))"
705 ),
706 guard_value: true,
707 },
708 Rule {
712 label: "Generic long secret",
713 re: static_regex!(
714 r#"(?im)((?:^|[^a-z0-9])(?:key|token|secret|password|credential|auth)(?:\\?["'])?[ \t]*[=:][ \t]*(?:\\?["'])?)([a-zA-Z0-9+/=\-_]{32,})"#
715 ),
716 guard_value: true,
717 },
718 ]
719}
720
721pub fn redact_text(input: &str) -> String {
722 redact_text_with_excludes(input, &[])
723}
724
725thread_local! {
726 static VERIFIED_SIGNER_KEY: std::cell::RefCell<Option<String>> =
729 const { std::cell::RefCell::new(None) };
730}
731
732pub fn with_verified_signer_key<T>(key: &str, release: impl FnOnce() -> T) -> T {
743 let well_formed = key.len() == 64
744 && key
745 .bytes()
746 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
747 if !well_formed {
748 return release();
749 }
750 struct Restore(Option<String>);
751 impl Drop for Restore {
752 fn drop(&mut self) {
753 VERIFIED_SIGNER_KEY.with(|slot| *slot.borrow_mut() = self.0.take());
754 }
755 }
756 let _restore = Restore(VERIFIED_SIGNER_KEY.with(|slot| slot.replace(Some(key.to_owned()))));
757 release()
758}
759
760pub(crate) fn is_verified_signer_key(before: &str, value: &str) -> bool {
766 (before.ends_with("\"signer_public") || before.ends_with("\"public"))
767 && VERIFIED_SIGNER_KEY.with(|slot| slot.borrow().as_deref() == Some(value))
768}
769
770pub fn redact_text_with_excludes(input: &str, excludes: &[regex::Regex]) -> String {
775 redact_counting(input, excludes).0
776}
777
778pub(crate) fn database_url_re() -> &'static regex::Regex {
783 static_regex!(
784 r"(?i)((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis)://)([^:/@?#\s]*):([^/?#\s]+)@([^@/?#\s]+)"
785 )
786}
787
788pub(crate) fn url_credentials_re() -> &'static regex::Regex {
794 static_regex!(
795 r"(?i)((?:https?|ftps?|sftp|ssh|amqps?|smtps?|ldaps?|wss?|git)://)([^:/@?#\s]+):([^@/?#\s]+)@([^/?#\s]+)"
796 )
797}
798
799pub(crate) fn database_url_has_credential(caps: ®ex::Captures) -> bool {
805 caps.get(2)
806 .is_none_or(|user| !user.as_str().starts_with("[REDACTED"))
807 && caps
808 .get(3)
809 .is_some_and(|password| !is_placeholder_value(password.as_str()))
810}
811
812fn redact_counting(input: &str, excludes: &[regex::Regex]) -> (String, usize) {
823 let (out, found) = redact_found(input, excludes);
824 (out, found.len())
825}
826
827fn redact_found(input: &str, excludes: &[regex::Regex]) -> (String, Vec<&'static str>) {
829 let (normalized, boundaries) = normalize_for_secret_matching(input);
830 let mut replacements = Vec::new();
831 let mut labels: Vec<&'static str> = Vec::new();
833
834 for (re, label) in [
835 (database_url_re(), "Database credentials"),
836 (url_credentials_re(), "URL credentials"),
837 ] {
838 for caps in re.captures_iter(&normalized) {
839 let Some(whole) = caps.get(0) else {
840 continue;
841 };
842 let start = boundaries[whole.start()];
843 let end = boundaries[whole.end()];
844 let original = input.get(start..end).unwrap_or(whole.as_str());
845 if excluded(excludes, whole.as_str()) || excluded(excludes, original) {
846 continue;
847 }
848 if !database_url_has_credential(&caps) {
851 continue;
852 }
853 let scheme = caps
854 .get(1)
855 .map_or("", |m| original_span(input, &boundaries, m));
856 let host = caps
857 .get(4)
858 .map_or("", |m| original_span(input, &boundaries, m));
859 replacements.push((start, end, format!("{scheme}[REDACTED:{label}]@{host}")));
860 labels.push(label);
861 }
862 }
863
864 for rule in redaction_rules() {
865 for caps in rule.re.captures_iter(&normalized) {
866 let Some(whole) = caps.get(0) else {
867 continue;
868 };
869 let start = boundaries[whole.start()];
870 let mut end = boundaries[whole.end()];
871 let original = input.get(start..end).unwrap_or(whole.as_str());
872 if excluded(excludes, whole.as_str()) || excluded(excludes, original) {
873 continue;
874 }
875 let mut masked_from = None;
880 if rule.guard_value
881 && let Some(value) = caps.get(2)
882 {
883 let quoted = is_quoted_at(&normalized, value.start());
884 let canonical = canonical_secret_value(value.as_str());
888 if !quoted
889 && lean_ctx_protocol::credential_redaction::is_nullable_type_name(canonical)
890 {
891 let line_start = normalized[..value.start()]
892 .rfind('\n')
893 .map_or(0, |at| at + 1);
894 if lean_ctx_protocol::credential_redaction::is_nullable_type_annotation(
895 &normalized[line_start..value.start()],
896 canonical,
897 ) {
898 continue;
899 }
900 }
901 match secret_value_span(value.as_str(), quoted) {
902 None => continue,
903 Some(span) if span.len() < value.len() => {
904 masked_from = Some(boundaries[value.start() + span.start]);
905 end = boundaries[value.start() + span.end];
906 }
907 Some(_) => {}
908 }
909 }
910 if rule.label == "Bearer token"
911 && caps
912 .get(2)
913 .is_some_and(|value| !bearer_value_is_credential(value.as_str()))
914 {
915 continue;
916 }
917 if rule.label == "Generic long secret"
918 && caps.get(2).is_some_and(|value| {
919 caps.get(1)
920 .is_some_and(|prefix| is_fact_key_slug(prefix.as_str(), value.as_str()))
921 || is_verified_signer_key(&normalized[..whole.start()], value.as_str())
922 })
923 {
924 continue;
925 }
926 let overlapping: Vec<usize> = replacements
930 .iter()
931 .enumerate()
932 .filter(|(_, (other_start, other_end, _))| start < *other_end && *other_start < end)
933 .map(|(i, _)| i)
934 .collect();
935 if overlapping.iter().any(|&i| {
936 let (other_start, other_end, _) = &replacements[i];
937 *other_start <= start && end <= *other_end
938 }) {
939 continue;
940 }
941 let start = overlapping
942 .iter()
943 .map(|&i| replacements[i].0)
944 .fold(start, usize::min);
945 let end = overlapping
946 .iter()
947 .map(|&i| replacements[i].1)
948 .fold(end, usize::max);
949 for &i in overlapping.iter().rev() {
950 replacements.remove(i);
951 labels.remove(i);
952 }
953
954 let label = rule.label;
955 let replacement = if let Some(masked_from) = masked_from {
956 let kept = input
957 .get(boundaries[whole.start()]..masked_from)
958 .unwrap_or("");
959 format!("{kept}[REDACTED:{label}]")
960 } else {
961 caps.get(1).map_or_else(
962 || format!("[REDACTED:{label}]"),
963 |prefix| {
964 let original_prefix = original_span(input, &boundaries, prefix);
965 format!("{original_prefix}[REDACTED:{label}]")
966 },
967 )
968 };
969 replacements.push((start, end, replacement));
970 labels.push(label);
971 }
972 }
973
974 let mut spans: Vec<((usize, usize, String), &'static str)> =
975 replacements.into_iter().zip(labels).collect();
976 spans.sort_by_key(|((start, _, _), _)| *start);
977 let mut found = Vec::with_capacity(spans.len());
978 let mut out = input.to_string();
979 for ((start, end, replacement), label) in spans.into_iter().rev() {
980 found.push(label);
981 out.replace_range(start..end, &replacement);
982 }
983 found.reverse();
984 (out, found)
985}
986
987fn original_span<'a>(input: &'a str, boundaries: &[usize], matched: regex::Match<'_>) -> &'a str {
988 let start = boundaries.get(matched.start()).copied().unwrap_or_default();
989 let end = boundaries.get(matched.end()).copied().unwrap_or(start);
990 input.get(start..end).unwrap_or("")
991}
992
993fn is_quoted_at(text: &str, pos: usize) -> bool {
995 pos > 0 && matches!(text.as_bytes()[pos - 1], b'"' | b'\'')
996}
997
998fn excluded(excludes: &[regex::Regex], value: &str) -> bool {
999 excludes.iter().any(|pattern| pattern.is_match(value))
1000}
1001
1002pub fn config_exclude_patterns() -> std::sync::Arc<Vec<regex::Regex>> {
1013 type Cache = Option<(
1014 std::sync::Arc<crate::core::config::Config>,
1015 std::sync::Arc<Vec<regex::Regex>>,
1016 )>;
1017 static CACHE: std::sync::Mutex<Cache> = std::sync::Mutex::new(None);
1018
1019 let cfg = crate::core::config::Config::load_arc();
1020
1021 if let Ok(guard) = CACHE.lock()
1022 && let Some((cached_cfg, patterns)) = &*guard
1023 && std::sync::Arc::ptr_eq(cached_cfg, &cfg)
1024 {
1025 return std::sync::Arc::clone(patterns);
1026 }
1027
1028 let compiled = std::sync::Arc::new(
1029 cfg.secret_detection
1030 .exclude_patterns
1031 .iter()
1032 .filter_map(|p| regex::Regex::new(p).ok())
1033 .collect::<Vec<_>>(),
1034 );
1035
1036 if let Ok(mut guard) = CACHE.lock() {
1037 *guard = Some((cfg, std::sync::Arc::clone(&compiled)));
1038 }
1039
1040 compiled
1041}
1042
1043#[must_use]
1052pub fn redact_with_patterns(input: &str, patterns: &[(String, regex::Regex)]) -> (String, usize) {
1053 let mut out = input.to_string();
1054 let mut hits = 0usize;
1055 for (label, re) in patterns {
1056 let mut local = 0usize;
1057 out = re
1058 .replace_all(&out, |_caps: ®ex::Captures| {
1059 local += 1;
1060 format!("[REDACTED:{label}]")
1061 })
1062 .to_string();
1063 hits += local;
1064 }
1065 (out, hits)
1066}
1067
1068#[cfg(test)]
1069mod tests;