Skip to main content

lean_ctx/core/
redaction.rs

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        // Contract: redaction never disabled for non-admin roles.
18        true
19    }
20}
21
22/// Redacts text bound for the model (tool output). Only this entry point
23/// counts toward the value surface: persistence passes (`redact_text`) keep
24/// secrets out of files, not out of the model context, and an already
25/// redacted `[REDACTED:…]` marker never matches again, so nested passes over
26/// one output do not double count.
27pub 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    // Engine metrics K21: fingerprints only, and only while sharing is on.
34    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
44/// #718: unquoted identifier or property-access chains (`SvelteKit`,
45/// `inputEnv.POCKETBASE_SUPERUSER_PASSWORD`, `serverEnv.getStripeSecretKey`,
46/// `confirmRequiredEndpointKeySchema`) are code REFERENCES to a secret, never
47/// the literal value — the value lives in a gitignored `.env`. Digits make a
48/// token secret-shaped (base64/hex), so any digit keeps the redaction
49/// (conservative: `password=hunter2` stays covered).
50/// #827: detect pure numeric values — integers, floats, scientific notation.
51/// These are never secrets even when the key contains `token` or `key`.
52fn 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    // Integer, float, or scientific notation (1.4e-06, 0.5, 600, 1e10)
61    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
77/// #827: env-variable reference patterns that should not be redacted.
78/// Matches: `os.environ/NAME`, `os.getenv("NAME")`, `process.env.NAME`,
79/// `inputEnv.NAME`, `${NAME}`, `$NAME`, `%NAME%` (Windows).
80fn 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    // Variable interpolation: ${VAR}, $VAR, %VAR%
91    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    // Dotted identifier chains with an env-like prefix
101    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    // #827: env-variable reference patterns are not secrets.
120    // `os.environ/MY_SERVICE_API_KEY`, `process.env.NAME`, `${VAR}`, `$VAR`.
121    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
134/// #718: obvious provider-token placeholders, `your_key_here`,
135/// `<insert-token>`) are documentation, not secrets — `.env.example` files
136/// must survive ctx_read verbatim. #1831: so is an asterisk mask (`*****`),
137/// which is what a redactor itself writes in place of a secret.
138fn 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
171/// Right-hand sides that look like `key: value` but are obviously not secrets:
172/// TypeScript type annotations and language literals. Redacting these corrupts
173/// source files read through `ctx_read` (GH #430), so the key/value rules skip
174/// them. Compared case-insensitively after trimming surrounding quotes.
175fn is_non_secret_literal(value: &str) -> bool {
176    let v = value
177        .trim()
178        .trim_matches(|c| c == '"' || c == '\'' || c == '`');
179    // #827: pure numbers (integer, float, scientific notation) are never secrets.
180    // `input_cost_per_token: 1.4e-06` must not be redacted.
181    if looks_like_number(v) {
182        return true;
183    }
184    // Type expressions are never flat secret tokens: real keys/tokens are drawn
185    // from `[A-Za-z0-9+/=_-]`, whereas type annotations carry angle brackets,
186    // unions, arrays or call/object syntax. `password: Promise<string>` and
187    // `apiKey: Record<string, unknown>` must survive ctx_read verbatim (GH #430),
188    // but `password=Pa(ss)word1` only contains brackets and is a secret (#1302).
189    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
215/// Primitive type names of Rust, Go, Java and C-family languages. In
216/// `const MAX_TOKEN: usize = 4` the "value" after `TOKEN:` is a type
217/// annotation, never a credential; masking it corrupts every read of such a
218/// source. Matched exactly (case-sensitive), so a password that merely
219/// contains one of these words is still protected.
220fn 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
264/// One redaction rule: a labelled regex plus how the match is rebuilt.
265struct Rule {
266    label: &'static str,
267    re: &'static regex::Regex,
268    /// When set, group 1 is a prefix to keep and group 2 is the secret value;
269    /// the match is left untouched if that value is a non-secret literal
270    /// (`password: undefined`), an identifier reference
271    /// (`serverEnv.getStripeSecretKey`) or a provider-token placeholder —
272    /// see `is_benign_secret_value` (GH #430, #718).
273    guard_value: bool,
274}
275
276/// Normalization used only for matching: remove invisible zero-width format
277/// characters and fold full-width ASCII plus ideographic space to their ASCII
278/// forms. Original text and byte boundaries are retained for span-only edits.
279fn 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
315/// A normalized view for detection-only callers that do not need span offsets.
316pub(crate) fn normalize_secret_text(input: &str) -> String {
317    input.chars().filter_map(fold_secret_match_char).collect()
318}
319
320/// The markers of the "Private key block" rule, as that rule spells them
321/// (only a PRIVATE KEY END closes a block: a certificate's END does not).
322const 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
338/// Whether `text`, normalized as the "Private key block" rule sees it,
339/// holds a private-key header with no private-key END after it: the rule's
340/// match would continue in the text that follows.
341pub 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
356/// Whether `text`, normalized as the "Private key block" rule sees it,
357/// holds a private-key END marker (the one the rule closes a block on).
358pub fn contains_private_key_end(text: &str) -> bool {
359    private_key_marker(true).is_match(&normalize_secret_text(text))
360}
361
362/// Whether the word after a bare `Bearer` is a credential rather than prose or a
363/// placeholder. Precision matters on the default redaction path ("Bearer
364/// authentication", "Bearer YOUR_TOKEN_HERE" must survive), but the identifier
365/// heuristic cannot be used: an opaque base64 token can be letters only. A
366/// credential is long and mixes character classes.
367pub(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
378/// Combined benign-value check for key/value secret rules (#430 + #718):
379/// language literals and type annotations, unquoted identifier/property
380/// references, and documentation placeholders are never redacted.
381///
382/// The secret detector (`core::secret_detection`) and the redactor capture
383/// different spans of one expression: the redactor's value runs to the next
384/// blank, so it can carry the rest of a comparison operator (`=<x>` from
385/// `==<x>`) and trailing syntax (`<x>)`, `<x>:`), while the detector's value
386/// stops at the first character outside `[A-Za-z0-9_+/=-]`. Both layers judge
387/// through this function, which reduces either span to the same operand, so
388/// they cannot disagree about one value (GHSA-xmx8-69qv-7f86): a value one
389/// layer reports is never left unchanged by the other.
390pub(crate) fn is_benign_secret_value(value: &str) -> bool {
391    secret_value_span(value, false).is_none()
392}
393
394/// Benign-value check for a *quoted* value. A quoted string is a literal, never
395/// an identifier reference, so that heuristic is skipped (`API_KEY="<letters>"`
396/// is a credential). Literals, placeholders, UUIDs and plain numbers — digests,
397/// counters, ids in JSON — stay benign.
398pub(crate) fn is_benign_quoted_value(value: &str) -> bool {
399    secret_value_span(value, true).is_none()
400}
401
402/// The part of a guarded rule's value that is redacted: `None` when the value
403/// is benign, otherwise a byte range of `value`. A value that is a secret as a
404/// whole is redacted whole. A value that only reads as benign because of the
405/// text after the detector's run (`<run>(arg)`, `<run>|next`) has just that
406/// run redacted, so the syntax around it survives.
407pub(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        // The operand of `==<x>`, `:=<x>` or `===<x>` is judged exactly like
416        // the value of `key=<x>`.
417        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
448/// The value without the syntax that follows it in an expression: a trailing
449/// `:` and every unbalanced closing `)`, `]` or `}` (`if (key==<x>):`). Only
450/// the judgement uses this text; see `secret_value_span` for what is redacted.
451fn 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
473/// The detector reports the longest leading run of `[A-Za-z0-9_+/=-]` (20 or
474/// more characters) of a value. When the rest of the value makes it look
475/// benign (`<run>(arg)` reads as a call or a type), that run is judged on its
476/// own as well, so the redactor never keeps a run the detector reports.
477fn 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
483/// Whether a "Generic long secret" match is the slug of a knowledge fact's
484/// own key: the value of a JSON member named exactly `key` (`"key":"…"` or
485/// `"key": "…"`, the quoted form a serialized fact carries) that reads as
486/// words. The rule fires on any 32+ character value after a name ending in
487/// `key`, so every long fact key was masked — all to the same marker, which
488/// merged distinct facts on export and import and broke the ids readers
489/// derive from keys.
490///
491/// Nothing else is exempt: free text (`key: …`, `SIGNING_KEY=…`), any other
492/// member name (`encryption_key`, `auth`, `credential`), and a value that
493/// does not read as words stay masked. `prefix` is the rule's kept group
494/// (the character before the name, the name, the separator).
495///
496/// Known residual risk: a passphrase made of real words joined by `-`
497/// (diceware) stored as the value of a member named `key` reads as a slug
498/// and is kept. A secret belongs under a secret's name, where it is masked.
499pub(crate) fn is_fact_key_slug(prefix: &str, value: &str) -> bool {
500    matches!(prefix, "\"key\":\"" | "\"key\": \"") && looks_like_word_slug(value)
501}
502
503/// Lowercase words and short numbers joined by `-`
504/// (`governor-design-pull-forward-2026-10-29`): at least three parts, at
505/// least two of them words, and at least half of the letter parts words; a
506/// number has at most 8 digits (dates, years, counters — not a PIN or an
507/// account number). A word has a vowel in at least a fifth of its letters
508/// and no run of more than four consonants, or is a one-vowel word of five
509/// to nine letters whose consonants before and after the vowel are a common
510/// English onset and coda (`rights`, `scripts`, `strict`). A part that is
511/// neither must be one of a fixed list of abbreviations (`mr`, `mcp`), which
512/// do not count as words. Random letter groups (`qhztvbkr`, `xkq`) fail.
513/// Any part with a digit beside letters, an upper-case letter or another
514/// character fails the slug.
515fn 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
534/// Vowel-free abbreviations a fact key may carry. A fixed list: a rule for
535/// "short and vowel-free" let random letter groups pass as abbreviations.
536const 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
542/// Consonants before the single vowel of a one-vowel word.
543const 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
550/// Consonants after the single vowel of a one-vowel word.
551const 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
581/// #1095: when the regex `key=` consumes one `=` from `==`, the captured
582/// "value" is a bare `=` (or `==`, `!=`). A comparison operator is never
583/// a secret; redacting it corrupts source semantics.
584fn is_comparison_operator_residue(value: &str) -> bool {
585    let v = value.trim();
586    matches!(v, "=" | "==" | "!=" | "<=" | ">=" | "===" | "!==")
587}
588
589/// The single source of truth for secret patterns. `shell::redact` delegates
590/// here so the two layers can never drift apart again.
591///
592/// #718 word boundaries: the key/value alternations start with
593/// `(?:^|[^a-z0-9])` (consumed into the kept prefix — the regex crate has no
594/// lookbehind) so camelCase subwords (`superuserPassword`,
595/// `getStripeSecretKey`) never trigger a rule, while SNAKE_CASE env names
596/// (`GITHUB_FEEDBACK_TOKEN`) still do: `_` remains a permitted predecessor.
597fn redaction_rules() -> Vec<Rule> {
598    vec![
599        Rule {
600            label: "Bearer token",
601            // Not the identifier guard (a letters-only base64 token is still a
602            // credential); `bearer_value_is_credential` filters prose instead.
603            re: static_regex!(r"(?i)(bearer[ \t]+)([a-zA-Z0-9_\-\.]{8,})"),
604            guard_value: false,
605        },
606        Rule {
607            label: "Authorization header",
608            // Any token-character credential, however short: `Basic dTpw` (u:p) is
609            // four characters. Token characters only, so adjacent text survives.
610            re: static_regex!(
611                r"(?i)(authorization[ \t]*:[ \t]*(?:basic|bearer|token)[ \t]+)([A-Za-z0-9._~+/=-]+)"
612            ),
613            guard_value: false,
614        },
615        // Whole token is the secret — no prefix group, so the entire match is
616        // replaced. (Previously group 1 captured the key itself and leaked it.)
617        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            // No kept prefix: the whole block, markers included, is replaced.
625            // A block without its END marker (a truncated file, a line window,
626            // a log tail) is still masked: the header plus every following
627            // key-material line — PEM headers of encrypted keys, then pure
628            // base64 lines. The first other line (code, prose) ends it, so a
629            // source that only mentions the header keeps the rest of the file.
630            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        // Provider keys are masked whole — the prefix names the provider and
651        // key class, so it is not kept. Same patterns as the detector, which
652        // also matches them inside nested values without a `key=` prefix.
653        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            // Secret and restricted keys, live and test mode. The value class
678            // excludes `_`, so placeholder values such as `your_key` stay readable.
679            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        // Key/value secrets run after provider-specific forms so `key=<AWS key id>`
693        // retains the more precise provider class label.
694        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        // Group 1 = prefix (kept), group 2 = the 32+ char value. Guarded since
709        // #718: 32-char identifiers like `confirmRequiredEndpointKeySchema`
710        // are references, not secrets.
711        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    /// The public key a package signature was verified with, while its
727    /// document is being released on this thread.
728    static VERIFIED_SIGNER_KEY: std::cell::RefCell<Option<String>> =
729        const { std::cell::RefCell::new(None) };
730}
731
732/// Run `release` with `key` known as the Ed25519 PUBLIC key a package
733/// signature has just been verified with. Inside, the built-in "Generic long
734/// secret" rule — and only that rule — does not read the member
735/// `"signer_public_key":"<key>"` (a bundle) or `"public_key":"<key>"` (a
736/// package manifest's signature) as a secret: a public key is none, and the
737/// rule fires on it only because a 64-digit value follows a name ending in
738/// `key`. Every other rule, every configured pattern, every policy pack and
739/// the gateway still see the original text with the real key in it and
740/// decide as always. A `key` that is not 64 lowercase hex digits exempts
741/// nothing.
742pub 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
760/// Whether the generic rule's match is the verified signer key in its own
761/// member: `before` is the text up to the match, which starts at the `_` of
762/// `_key`. The secret detector's `high_entropy_secret` pattern (the same
763/// names, the same predecessor) applies the same exemption, so admission
764/// never reports a value this rule keeps.
765pub(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
770/// #718: `redact_text` with subtractive user patterns from
771/// `[secret_detection].exclude_patterns` — a match covered by any exclude
772/// regex is kept verbatim, so known-safe naming conventions can be carved out
773/// without disabling secret detection wholesale.
774pub fn redact_text_with_excludes(input: &str, excludes: &[regex::Regex]) -> String {
775    redact_counting(input, excludes).0
776}
777
778/// Database URL with inline credentials: scheme (1), user (2, may be empty —
779/// `redis://:pw@host`), password (3), host (4). The password runs to the last
780/// `@` before the host, so an unencoded `@` in it cannot leak a tail. Shared
781/// with the detector so both layers agree on what a credential is.
782pub(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
788/// userinfo with a password in any other URL (`https://[REDACTED:URL credentials]@host`): the
789/// tokens elsewhere in such a URL were masked, the password stayed (focus
790/// analysis 2026-10-15). Same groups as [`database_url_re`], and shared with
791/// the detector, so a placeholder password (`https://user:****@host`) is
792/// neither reported nor redacted (GHSA-xmx8-69qv-7f86).
793pub(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
799/// True when a [`database_url_re`] or [`url_credentials_re`] match carries a real credential. A
800/// placeholder password is not one, and neither is an already redacted
801/// `scheme://[REDACTED:db_url]@host` — its `:` would otherwise read as
802/// `user:password`, so a re-scan of redacted output found a "residual" secret
803/// and the context gateway withheld the whole file.
804pub(crate) fn database_url_has_credential(caps: &regex::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
812/// [`redact_text_with_excludes`] plus the number of secrets it replaced.
813///
814/// One mask label per secret kind: the rule's own `label`, whoever asks. The
815/// gateway's scanner (`secret_detection::scan_and_redact`) and a project
816/// pack's built-in pass (`policy::content::evaluate_text`) both end here, so a
817/// value masked by one is spelled exactly as the other would spell it and a
818/// second pass over masked text changes nothing. (The scanner used to map the
819/// labels to its pattern names — `[REDACTED:aws_key]` next to
820/// `[REDACTED:AWS key]` — which made every order-of-masking comparison fail
821/// for a built-in secret.)
822fn redact_counting(input: &str, excludes: &[regex::Regex]) -> (String, usize) {
823    let (out, found) = redact_found(input, excludes);
824    (out, found.len())
825}
826
827/// The redacted text and the label of each redacted span (never its text).
828fn 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    // The label of each replacement, index for index.
832    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            // A placeholder password or an already redacted URL is no
849            // credential (shared with the detector, see `database_url_re`).
850            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            // A quoted value is a literal, never an identifier reference, so the
876            // benign-value guard does not apply to it. When only the detector's
877            // run of the value is a secret, the redaction ends with that run
878            // and starts after the operator (GHSA-xmx8-69qv-7f86).
879            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                // #2255: `private var token: Session? = null` declares a type.
885                // The line scan runs only for unquoted, type-shaped `?` values,
886                // judged without a closing `)` (`fun f(token: Session?)`).
887                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            // Overlapping matches: the wider span wins. Skipping a wider match (a whole
927            // private-key block) because a narrower rule already hit inside it would
928            // leak the rest of the block.
929            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
993/// Whether the byte before `pos` in `text` is a quote (the value is a quoted literal).
994fn 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
1002/// Compile the configured `exclude_patterns` (#718). Invalid regexes are
1003/// skipped — a broken exclude must never disable redaction.
1004///
1005/// #952: regex compilation — the expensive part of this call — used to run
1006/// on every redaction call (`ctx_read`, `ctx_shell`, `ctx_execute` all funnel
1007/// through `redact_text_if_enabled`) regardless of whether the config had
1008/// changed. Cached here, keyed on `Arc::ptr_eq` against the config `Arc`:
1009/// `Config::load_arc` returns the *same* `Arc` when the underlying config
1010/// content hash is unchanged, so a real config edit is exactly what
1011/// invalidates this cache too — no separate change-detection needed.
1012pub 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/// Apply caller-supplied policy redaction patterns on top of the built-in
1044/// secret rules: each regex match becomes `[REDACTED:<label>]`. Returns the
1045/// transformed text and the number of redactions applied (for audit counts).
1046///
1047/// Used by context policy packs (GL #673) so a pack's `[redaction]` block
1048/// actually removes matching content from what the model sees. The patterns are
1049/// the pack's `[redaction]` entries, precompiled by
1050/// [`crate::core::policy::runtime`].
1051#[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: &regex::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;