Skip to main content

eclipse_core/
redact.rs

1//! Finding secrets in a string and replacing them with a marker that says what was there.
2//!
3//! This is the matching half of the `redact-secrets` hook ([`crate::hooks`]); it is a pure
4//! function over text, so it can be tested without a loop, a config or a store.
5//!
6//! # Hand-written, high precision first
7//!
8//! There is no regex engine here, on purpose: every dependency is a thing to audit, and the
9//! shapes below are all "a literal prefix, then a run of characters from a small set". Each
10//! one is cheap to scan for and cheap to reason about. The trade is made explicit:
11//!
12//! - A pattern with a *distinctive prefix* (`sk-`, `ghp_`, `AKIA`, a PEM header) fires on the
13//!   prefix and a minimum length. A near-miss — one character short, a word that merely
14//!   contains the prefix — is left alone, because a false positive mangles a file the user
15//!   asked to read.
16//! - The *assignment* pattern (`password = …`) has no distinctive prefix, so it is the one
17//!   that can over-match: `token = refresh_access_token_now` looks like a secret to a scanner
18//!   that has no idea what a variable is. It is kept because `API_TOKEN=…` in an `.env` is the
19//!   commonest way a real secret reaches a prompt; `allow` is the escape hatch.
20//!
21//! # Properties that are tested
22//!
23//! - **Idempotent.** Redacting redacted text changes nothing. A marker never contains a run
24//!   the scanner would take for a secret, and the text before and after a marker is judged the
25//!   same way both times.
26//! - **A marker is not a secret.** Text that is already `[redacted:…]` is skipped whole.
27//! - **Ordinary text is byte-identical**: prose, logs, code that merely mentions a password.
28//! - **Matches never overlap**, and the earliest pattern in the text wins: in
29//!   `API_KEY=sk-…` the label is `api_key`, not a second marker nested in the first.
30//!
31//! Only the secret is replaced where a pattern has context worth keeping: `Bearer` stays,
32//! the user in `https://user:pass@host` stays, the name in `password=…` stays. The reader
33//! — the model — can still see what kind of thing was there.
34use std::collections::BTreeMap;
35
36/// What a redaction pass did.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Redacted {
39    pub text: String,
40    /// How many secrets were replaced. 0 means `text` is the input, byte for byte.
41    pub count: usize,
42}
43
44/// Replace every secret in `input`. A match that lies entirely inside one of the `allow`
45/// strings (compared literally) is left as it is.
46///
47/// The text is scanned again after a replacement until a scan finds nothing, because a
48/// replacement can change what a *neighbouring* pattern sees: a private key block that sat
49/// inside the password of a URL, say, took the spaces that kept that URL from being one.
50/// That is what makes the result idempotent by construction rather than by luck; it is
51/// bounded, and every extra scan is a cheap read over text that is already a marker or plain.
52pub fn redact(input: &str, allow: &[String]) -> Redacted {
53    let mut current = scan(input, allow);
54    for _ in 0..MAX_RESCANS {
55        if current.count == 0 {
56            break;
57        }
58        let again = scan(&current.text, allow);
59        if again.count == 0 {
60            break;
61        }
62        current = Redacted {
63            text: again.text,
64            count: current.count + again.count,
65        };
66    }
67    current
68}
69
70const MAX_RESCANS: usize = 8;
71
72/// One left-to-right pass.
73fn scan(input: &str, allow: &[String]) -> Redacted {
74    let b = input.as_bytes();
75    let allowed = allowed_spans(input, allow);
76    // Keyed by start. Matches found first win an overlap, so the map never holds two that
77    // touch, and iterating it yields them left to right.
78    let mut hits: BTreeMap<usize, Hit> = BTreeMap::new();
79
80    let mut i = 0;
81    while i < b.len() {
82        if let Some(end) = marker_end(b, i) {
83            i = end;
84            continue;
85        }
86        // Inside a span that is already taken, any match would overlap it and be refused;
87        // skipping it also keeps a long `token=token=token=…` from being measured from every
88        // `token`.
89        if let Some(taken) = hits.range(..=i).next_back().map(|(_, h)| h.end) {
90            if taken > i {
91                i = taken;
92                continue;
93            }
94        }
95        // Text that follows a replaced span will follow a `]`, which is not a word byte, so it
96        // starts on an edge even when the secret before it ended on one.
97        let after_hit = hits
98            .range(..=i)
99            .next_back()
100            .is_some_and(|(_, h)| h.end == i && h.replacement.is_some());
101        let Some(mut hit) = try_at(b, i, after_hit) else {
102            i += 1;
103            continue;
104        };
105        let ahead = hit.start > i;
106        if allowed.iter().any(|&(a, z)| a <= hit.start && hit.end <= z) {
107            // Reserved rather than dropped, so a smaller pattern cannot redact a piece of a
108            // string the user said to leave alone.
109            hit.replacement = None;
110        }
111        if !overlaps(&hits, hit.start, hit.end) {
112            let end = hit.end;
113            hits.insert(hit.start, hit);
114            if !ahead {
115                i = end;
116                continue;
117            }
118        }
119        // A match that starts further on (the value of `name = value`, the password of a
120        // URL) leaves the text before it still to be scanned: the user of that URL could be
121        // a key of its own.
122        i += 1;
123    }
124
125    let mut text = String::with_capacity(input.len());
126    let mut done = 0;
127    let mut count = 0;
128    for hit in hits.values() {
129        let Some(replacement) = &hit.replacement else {
130            continue;
131        };
132        text.push_str(slice(input, done, hit.start));
133        text.push_str(replacement);
134        done = hit.end;
135        count += 1;
136    }
137    text.push_str(slice(input, done, input.len()));
138    Redacted { text, count }
139}
140
141struct Hit {
142    start: usize,
143    end: usize,
144    /// `None` for a match the allow-list protects: it still reserves its span.
145    replacement: Option<String>,
146}
147
148fn hit(start: usize, end: usize, label: &str) -> Hit {
149    Hit {
150        start,
151        end,
152        replacement: Some(format!("[redacted:{label}]")),
153    }
154}
155
156fn overlaps(hits: &BTreeMap<usize, Hit>, start: usize, end: usize) -> bool {
157    hits.range(..end)
158        .next_back()
159        .is_some_and(|(_, h)| h.end > start)
160}
161
162/// Slicing that cannot panic. Every offset passed here sits next to an ASCII byte, so the
163/// fallback is not expected to run; an empty string is the safe answer if it ever does.
164fn slice(s: &str, from: usize, to: usize) -> &str {
165    s.get(from..to).unwrap_or_default()
166}
167
168fn allowed_spans(input: &str, allow: &[String]) -> Vec<(usize, usize)> {
169    allow
170        .iter()
171        .filter(|a| !a.is_empty())
172        .flat_map(|a| {
173            input
174                .match_indices(a.as_str())
175                .map(|(at, m)| (at, at + m.len()))
176        })
177        .collect()
178}
179
180const MARKER: &[u8] = b"[redacted:";
181
182/// If a marker starts at `i`, where it ends. A marker is ours (or looks it), never a secret.
183fn marker_end(b: &[u8], i: usize) -> Option<usize> {
184    if !b[i..].starts_with(MARKER) {
185        return None;
186    }
187    let tail = &b[i + MARKER.len()..];
188    let close = tail.iter().take(48).position(|&c| c == b']')?;
189    Some(i + MARKER.len() + close + 1)
190}
191
192fn try_at(b: &[u8], i: usize, after_hit: bool) -> Option<Hit> {
193    if b[i] == b'-' {
194        return private_key(b, i);
195    }
196    // Most patterns start on a word edge, so `task-…` and `desk_…` do not begin `sk-`.
197    let word_edge = after_hit || i == 0 || !is_word(b[i - 1]);
198    let found = if word_edge {
199        prefixed_token(b, i)
200            .or_else(|| url_password(b, i))
201            .or_else(|| bearer(b, i))
202            .or_else(|| jwt(b, i))
203    } else {
204        None
205    };
206    // A name may follow a hyphen (`--token=…`, `x-api-key:`), which a word edge would refuse.
207    found.or_else(|| {
208        let name_edge = after_hit || i == 0 || !is_ident(b[i - 1]);
209        name_edge.then(|| assignment(b, i)).flatten()
210    })
211}
212
213fn is_word(c: u8) -> bool {
214    c.is_ascii_alphanumeric() || c == b'_' || c == b'-'
215}
216
217fn is_ident(c: u8) -> bool {
218    c.is_ascii_alphanumeric() || c == b'_'
219}
220
221fn is_b64url(c: u8) -> bool {
222    c.is_ascii_alphanumeric() || c == b'_' || c == b'-'
223}
224
225/// End of the run of bytes at `from` that satisfy `pred`.
226fn run(b: &[u8], from: usize, pred: impl Fn(u8) -> bool) -> usize {
227    b[from.min(b.len())..]
228        .iter()
229        .position(|&c| !pred(c))
230        .map_or(b.len(), |n| from + n)
231}
232
233/// Whether `b[i..]` starts with `prefix`, byte for byte.
234fn at(b: &[u8], i: usize, prefix: &[u8]) -> bool {
235    b.get(i..).is_some_and(|t| t.starts_with(prefix))
236}
237
238fn prefixed_token(b: &[u8], i: usize) -> Option<Hit> {
239    // `sk-…`: OpenAI, Anthropic (`sk-ant-`), project keys (`sk-proj-`).
240    if at(b, i, b"sk-") {
241        let end = run(b, i + 3, is_b64url);
242        return (end - (i + 3) >= 20).then(|| hit(i, end, "api-key"));
243    }
244    // `ghp_ gho_ ghu_ ghs_ ghr_`: GitHub's own token kinds.
245    if at(b, i, b"gh") && b.get(i + 2).is_some_and(|c| b"pousr".contains(c)) && at(b, i + 3, b"_") {
246        let end = run(b, i + 4, |c| c.is_ascii_alphanumeric());
247        return (end - (i + 4) >= 30).then(|| hit(i, end, "github-token"));
248    }
249    if at(b, i, b"github_pat_") {
250        let end = run(b, i + 11, |c| c.is_ascii_alphanumeric() || c == b'_');
251        return (end - (i + 11) >= 20).then(|| hit(i, end, "github-token"));
252    }
253    // An AWS access key id is exactly four letters and sixteen of [A-Z0-9]. A seventeenth
254    // character means this is some other identifier that happens to begin `AKIA`.
255    if at(b, i, b"AKIA") || at(b, i, b"ASIA") {
256        let end = run(b, i + 4, |c| c.is_ascii_uppercase() || c.is_ascii_digit());
257        let tail_clean = !b.get(end).is_some_and(|c| c.is_ascii_alphanumeric());
258        return (end - (i + 4) == 16 && tail_clean).then(|| hit(i, end, "aws-key-id"));
259    }
260    if at(b, i, b"xox") && b.get(i + 3).is_some_and(|c| b"bparsa".contains(c)) && at(b, i + 4, b"-")
261    {
262        let end = run(b, i + 5, |c| c.is_ascii_alphanumeric() || c == b'-');
263        return (end - (i + 5) >= 10).then(|| hit(i, end, "slack-token"));
264    }
265    // A Google API key is `AIza` and 35 more.
266    if at(b, i, b"AIza") {
267        let end = run(b, i + 4, is_b64url);
268        return (end - (i + 4) >= 35).then(|| hit(i, end, "google-key"));
269    }
270    None
271}
272
273fn jwt(b: &[u8], i: usize) -> Option<Hit> {
274    if !at(b, i, b"eyJ") {
275        return None;
276    }
277    let first = run(b, i, is_b64url);
278    if first - i < 6 || b.get(first) != Some(&b'.') {
279        return None;
280    }
281    let second = run(b, first + 1, is_b64url);
282    if second - (first + 1) < 4 || b.get(second) != Some(&b'.') {
283        return None;
284    }
285    let third = run(b, second + 1, is_b64url);
286    (third - (second + 1) >= 4).then(|| hit(i, third, "jwt"))
287}
288
289fn bearer(b: &[u8], i: usize) -> Option<Hit> {
290    let word = b.get(i..i + 6)?;
291    if !word.eq_ignore_ascii_case(b"bearer") {
292        return None;
293    }
294    let gap = run(b, i + 6, |c| c == b' ' || c == b'\t');
295    if gap == i + 6 {
296        return None;
297    }
298    let mut end = run(b, gap, |c| {
299        is_b64url(c) || matches!(c, b'.' | b'~' | b'+' | b'/' | b'=')
300    });
301    // A full stop closes a sentence far more often than it ends a token.
302    while end > gap && b[end - 1] == b'.' {
303        end -= 1;
304    }
305    let token = &b[gap..end];
306    let varied = token.iter().any(u8::is_ascii_digit)
307        || (token.iter().any(u8::is_ascii_uppercase) && token.iter().any(u8::is_ascii_lowercase));
308    // Sixteen and a digit or mixed case: "Bearer authentication" is a phrase, not a token.
309    (token.len() >= 16 && varied).then(|| hit(gap, end, "bearer-token"))
310}
311
312/// `scheme://user:password@host`: the password goes, the user stays.
313fn url_password(b: &[u8], i: usize) -> Option<Hit> {
314    if !b[i].is_ascii_alphabetic() {
315        return None;
316    }
317    let scheme_end = i + b[i..]
318        .iter()
319        .take(32)
320        .position(|&c| !(c.is_ascii_alphanumeric() || matches!(c, b'+' | b'.' | b'-')))?;
321    if !at(b, scheme_end, b"://") {
322        return None;
323    }
324    let user_start = scheme_end + 3;
325    let stop = |c: u8| {
326        c.is_ascii_whitespace() || matches!(c, b'"' | b'\'' | b'<' | b'>' | b'/' | b'?' | b'#')
327    };
328    // `[` ends the user so that a marker already standing there is never read as one.
329    let user_end = run(b, user_start, |c| {
330        !stop(c) && !matches!(c, b':' | b'@' | b'[' | b']')
331    });
332    if user_end == user_start || b.get(user_end) != Some(&b':') {
333        return None;
334    }
335    let pass_start = user_end + 1;
336    let region_end = run(b, pass_start, |c| !stop(c));
337    // A password may hold an unescaped `@`; the host starts after the last one.
338    let at_sign = b[pass_start..region_end].iter().rposition(|&c| c == b'@')? + pass_start;
339    let pass = &b[pass_start..at_sign];
340    let placeholder = pass.first().is_some_and(|c| matches!(c, b'$' | b'{'))
341        || pass.iter().all(|&c| c == b'*')
342        || pass.starts_with(MARKER);
343    (!pass.is_empty() && !placeholder).then(|| hit(pass_start, at_sign, "password"))
344}
345
346/// Names whose value is a secret, longest first so `client_secret` is not reported as
347/// `secret`. A name matches when it *ends* with one: `API_TOKEN`, `DB_PASSWORD` and
348/// `AWS_SECRET_ACCESS_KEY` are how these appear in an `.env`, and the bare words almost never do.
349const NAMES: &[&str] = &[
350    "client_secret",
351    "access_key",
352    "api_key",
353    "apikey",
354    "password",
355    "passwd",
356    "secret",
357    "token",
358    "pwd",
359];
360
361fn secret_name(ident: &[u8]) -> Option<&'static str> {
362    let lowered: Vec<u8> = ident
363        .iter()
364        .map(|&c| {
365            if c == b'-' {
366                b'_'
367            } else {
368                c.to_ascii_lowercase()
369            }
370        })
371        .collect();
372    NAMES
373        .iter()
374        .find(|n| lowered.ends_with(n.as_bytes()))
375        .copied()
376}
377
378/// A value shaped like a name out of code — an uppercase letter inside it and no digit,
379/// `AccessTokenRequest`, `ApiKeyConfig`, `MY_SECRET_VALUE` — is a type, a field or a reference to
380/// another variable far more often than it is a secret, and this rule reads a great deal of code.
381/// Such a value is taken only under a password name, where an all-letter secret is ordinary.
382/// A lowercase run (`abcdefghijkl`) is what an unremarkable `.env` token looks like, so it stays;
383/// a real key of any prefix is caught by the prefix rules regardless.
384fn is_bare_identifier(value: &[u8]) -> bool {
385    let Some((first, rest)) = value.split_first() else {
386        return false;
387    };
388    if !(first.is_ascii_alphabetic() || *first == b'_') {
389        return false;
390    }
391    let shaped = rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_')
392        && !value.iter().any(u8::is_ascii_digit);
393    shaped && rest.iter().any(u8::is_ascii_uppercase)
394}
395
396fn assignment(b: &[u8], i: usize) -> Option<Hit> {
397    if !is_ident(b[i]) {
398        return None;
399    }
400    // A name is short; capping the run keeps a long hyphenated token from being rescanned
401    // from every segment.
402    let name_end = run(&b[..b.len().min(i + 65)], i, is_b64url);
403    if name_end - i > 64 {
404        return None;
405    }
406    let label = secret_name(&b[i..name_end])?;
407    let blank = |c: u8| c == b' ' || c == b'\t';
408    // `#415`: inside an escaped JSON string the bytes are `\"password\": \"…\"` — the backslash
409    // before each quote is part of the text, so a check that only looks for the quote sees `\` and
410    // gives up. Skip one escape before each quote; in plain text this is a no-op.
411    let quoteless = |b: &[u8], mut k: usize| -> usize {
412        if b.get(k) == Some(&b'\\') {
413            k += 1;
414        }
415        if matches!(b.get(k), Some(b'"' | b'\'')) {
416            k += 1;
417        }
418        k
419    };
420    let mut j = quoteless(b, name_end);
421    j = run(b, j, blank);
422    if !matches!(b.get(j), Some(b'=' | b':')) {
423        return None;
424    }
425    j += 1;
426    // `==` is a comparison and `::` a path, not an assignment.
427    if matches!(b.get(j), Some(b'=' | b':')) {
428        return None;
429    }
430    j = quoteless(b, run(b, j, blank));
431    // A password is a password whatever it looks like: `hunter2` and `Sup3r$ecret!` are the shapes
432    // a `cat .env` actually produces, and both were missed because the value was scanned as a
433    // base64url run (the `$` and `!` ended it after five characters) and then held to a twelve
434    // character floor (`#415`). So for those three names the value is any run without a separator.
435    let password = matches!(label, "password" | "passwd" | "pwd");
436    let end = if password {
437        run(b, j, |c| {
438            !matches!(
439                c,
440                b' ' | b'\t'
441                    | b'\n'
442                    | b'\r'
443                    | b'"'
444                    | b'\''
445                    | b'`'
446                    | b','
447                    | b';'
448                    | b')'
449                    | b']'
450                    | b'}'
451                    | b'>'
452                    | b'<'
453                    | b'&'
454                    | b'\\'
455            )
456        })
457    } else {
458        run(b, j, |c| is_b64url(c) || matches!(c, b'/' | b'+' | b'='))
459    };
460    // `${…}`, `$(…)`, `~/…` and `[redacted:…]` never start a value; an absolute path does not
461    // either. The marker matters for idempotence: without `[` here, the second pass reads
462    // `[redacted:password]` as a value that starts with `[` and ends at `]`, redacts it again, and
463    // the pass is no longer a fixed point.
464    if matches!(b.get(j), Some(b'/' | b'$' | b'[' | b'{' | b'(')) {
465        return None;
466    }
467    let len = end - j;
468    // Six characters is allowed only when something in them is not a letter — `hunter2`, `Sup3r$e!`
469    // — because `password: required` and `password: elevenchars` are a config schema, not a secret,
470    // and a redacted field name degrades every read of a codebase.
471    let acceptable = if password {
472        len >= 12 || (len >= 6 && b[j..end].iter().any(|c| !c.is_ascii_alphabetic()))
473    } else {
474        len >= 12
475    };
476    if !acceptable {
477        return None;
478    }
479    // A type or a variable name where a secret was expected: `token: AccessTokenRequest` is code.
480    if !matches!(label, "password" | "passwd" | "pwd") && is_bare_identifier(&b[j..end]) {
481        return None;
482    }
483    let closed = match b.get(end) {
484        None => true,
485        Some(c) if c.is_ascii_whitespace() => true,
486        Some(
487            b'"' | b'\'' | b'`' | b',' | b';' | b')' | b']' | b'}' | b'>' | b'&' | b'<' | b'\\',
488        ) => true,
489        // A full stop that ends a sentence, not one inside a dotted name.
490        Some(b'.') => !b.get(end + 1).is_some_and(|c| !c.is_ascii_whitespace()),
491        Some(_) => false,
492    };
493    closed.then(|| hit(j, end, label))
494}
495
496/// A PEM private key: the whole block, header to footer, becomes one marker.
497fn private_key(b: &[u8], i: usize) -> Option<Hit> {
498    const BEGIN: &[u8] = b"-----BEGIN ";
499    if !at(b, i, BEGIN) {
500        return None;
501    }
502    let label_start = i + BEGIN.len();
503    let label_end = label_start + find(&b[label_start..], b"-----", 40)?;
504    if !is_private_label(&b[label_start..label_end]) {
505        return None;
506    }
507    let body = label_end + 5;
508    if let Some(footer) = footer_end(b, body) {
509        return Some(hit(i, footer, "private-key"));
510    }
511    // No footer: the output was cut short, or the key was never closed. What was printed of
512    // the body is still a key, so take the header and the base64 lines that follow it, and
513    // stop at the first line that is something else.
514    let mut end = body;
515    let mut cursor = body;
516    let mut lines = 0;
517    while cursor < b.len() {
518        let line_end = b[cursor..]
519            .iter()
520            .position(|&c| c == b'\n')
521            .map_or(b.len(), |n| cursor + n);
522        let line = &b[cursor..line_end];
523        let lead = line
524            .iter()
525            .take_while(|&&c| c == b' ' || c == b'\t')
526            .count();
527        let text = trim_end(&line[lead..]);
528        let base64 = !text.is_empty()
529            && text
530                .iter()
531                .all(|&c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'/' | b'='));
532        let pem_header = text.starts_with(b"Proc-Type:") || text.starts_with(b"DEK-Info:");
533        if base64 && (text.len() >= 16 || lines > 0) {
534            lines += 1;
535            end = cursor + lead + text.len();
536        } else if !(pem_header || text.is_empty() && lines == 0) {
537            break;
538        }
539        cursor = line_end + 1;
540    }
541    (lines > 0).then(|| hit(i, end, "private-key"))
542}
543
544fn trim_end(mut text: &[u8]) -> &[u8] {
545    while let [rest @ .., b' ' | b'\t' | b'\r'] = text {
546        text = rest;
547    }
548    text
549}
550
551fn is_private_label(label: &[u8]) -> bool {
552    label.ends_with(b"PRIVATE KEY")
553}
554
555/// The longest key body searched for its footer. A 4096-bit RSA key is about 3 KiB; past this
556/// the block is read as unclosed, and its base64 lines are taken instead.
557const MAX_KEY_BODY: usize = 16 * 1024;
558
559/// Where the `-----END … PRIVATE KEY-----` line that closes a block starting at `from` ends.
560fn footer_end(b: &[u8], from: usize) -> Option<usize> {
561    const END: &[u8] = b"-----END ";
562    let at_footer = from + find(&b[from..], END, MAX_KEY_BODY)?;
563    let label_start = at_footer + END.len();
564    let label_end = label_start + find(&b[label_start..], b"-----", 40)?;
565    is_private_label(&b[label_start..label_end]).then_some(label_end + 5)
566}
567
568/// Offset of `needle` in the first `limit` bytes of `hay`.
569fn find(hay: &[u8], needle: &[u8], limit: usize) -> Option<usize> {
570    let hay = &hay[..hay.len().min(limit)];
571    hay.windows(needle.len()).position(|w| w == needle)
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577
578    fn r(text: &str) -> String {
579        redact(text, &[]).text
580    }
581
582    /// Run the scanner and check the two things every case owes: the replacement, and that
583    /// a second pass finds nothing more to do.
584    fn fires(input: &str, expected: &str) {
585        let first = redact(input, &[]);
586        assert_eq!(first.text, expected, "input: {input}");
587        assert!(first.count >= 1, "nothing was counted for: {input}");
588        let second = redact(&first.text, &[]);
589        assert_eq!(second.text, first.text, "not idempotent for: {input}");
590        assert_eq!(second.count, 0, "a marker was matched again: {input}");
591    }
592
593    fn passes(input: &str) {
594        let out = redact(input, &[]);
595        assert_eq!(out.text, input, "a near-miss was changed");
596        assert_eq!(out.count, 0);
597    }
598
599    // sk- ------------------------------------------------------------------------------------
600
601    #[test]
602    fn an_sk_key_of_twenty_or_more_characters_is_redacted() {
603        fires(
604            "key is sk-abcdefghij0123456789 ok",
605            "key is [redacted:api-key] ok",
606        );
607        fires(
608            "ANTHROPIC=sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv_wx-yz",
609            "ANTHROPIC=[redacted:api-key]",
610        );
611        fires("\"sk-proj-abcdefghij0123456789\"", "\"[redacted:api-key]\"");
612    }
613
614    #[test]
615    fn an_sk_prefix_that_is_short_or_inside_a_word_is_left_alone() {
616        passes("sk-abcdefghij012345678"); // 19 after the prefix
617        passes("sk-learn");
618        passes("the task-abcdefghij0123456789 queue");
619        passes("risk-assessment-for-the-whole-quarter");
620    }
621
622    // GitHub ----------------------------------------------------------------------------------
623
624    #[test]
625    fn github_tokens_of_every_kind_are_redacted() {
626        for kind in ["ghp", "gho", "ghu", "ghs", "ghr"] {
627            let token = format!("{kind}_0123456789abcdefghijABCDEFGHIJ");
628            fires(&format!("token {token}!"), "token [redacted:github-token]!");
629        }
630        fires(
631            "github_pat_11ABCDEFG0abcdefghij_klmnopqrstuvwxyz",
632            "[redacted:github-token]",
633        );
634    }
635
636    #[test]
637    fn a_github_token_that_is_too_short_or_of_an_unknown_kind_is_left_alone() {
638        passes("ghp_0123456789abcdefghijABCDEFGHI"); // 29
639        passes("ghx_0123456789abcdefghijABCDEFGHIJ");
640        passes("github_pat_short");
641        passes("ghp_ is the prefix GitHub uses");
642    }
643
644    // AWS -------------------------------------------------------------------------------------
645
646    #[test]
647    fn an_aws_access_key_id_is_redacted() {
648        fires(
649            "id AKIAIOSFODNN7EXAMPLE here",
650            "id [redacted:aws-key-id] here",
651        );
652        fires("ASIAIOSFODNN7EXAMPLE", "[redacted:aws-key-id]");
653    }
654
655    #[test]
656    fn something_that_only_starts_like_an_aws_key_id_is_left_alone() {
657        passes("AKIAIOSFODNN7EXAMPL"); // 15
658        passes("AKIAIOSFODNN7EXAMPLES"); // 17
659        passes("AKIAiosfodnn7example1234");
660        passes("AKIAIOSFODNN7EXAMPLEx");
661    }
662
663    // Slack -----------------------------------------------------------------------------------
664
665    #[test]
666    fn slack_tokens_are_redacted() {
667        for kind in ["xoxb", "xoxp", "xoxa", "xoxr", "xoxs"] {
668            fires(
669                &format!("{kind}-123456789012-AbCdEfGhIj"),
670                "[redacted:slack-token]",
671            );
672        }
673    }
674
675    #[test]
676    fn a_short_or_unknown_slack_shape_is_left_alone() {
677        passes("xoxb-123456789"); // 9
678        passes("xoxz-123456789012-AbCdEfGhIj");
679        passes("xoxb is how a bot token starts");
680    }
681
682    // Google ----------------------------------------------------------------------------------
683
684    #[test]
685    fn a_google_api_key_is_redacted() {
686        let key = format!("AIza{}", "Sy0123456789_abcdefghijKLMNOPQRST-x");
687        assert_eq!(key.len(), 4 + 35);
688        fires(&format!("key={key}&x=1"), "key=[redacted:google-key]&x=1");
689    }
690
691    #[test]
692    fn a_google_key_that_is_too_short_is_left_alone() {
693        passes("AIzaSy0123456789_abcdefghijKLMNOPQRST-"); // 34 after the prefix
694        passes("AIza is how a Google key starts");
695    }
696
697    // Private keys ----------------------------------------------------------------------------
698
699    #[test]
700    fn a_whole_private_key_block_becomes_one_marker() {
701        let block = "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA1234567890abcdef\nZm9vYmFy\n-----END RSA PRIVATE KEY-----";
702        fires(
703            &format!("before\n{block}\nafter"),
704            "before\n[redacted:private-key]\nafter",
705        );
706        fires(
707            "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----",
708            "[redacted:private-key]",
709        );
710        fires(
711            "-----BEGIN OPENSSH PRIVATE KEY-----\\nb3BlbnNzaC1rZXk\\n-----END OPENSSH PRIVATE KEY-----\\n",
712            "[redacted:private-key]\\n",
713        );
714    }
715
716    #[test]
717    fn a_private_key_cut_off_before_its_footer_is_still_redacted() {
718        fires(
719            "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\nKcwggSjAgEAAoIBAQC7VJTUt9Us8cKj\n[output truncated]",
720            "[redacted:private-key]\n[output truncated]",
721        );
722    }
723
724    #[test]
725    fn public_keys_certificates_and_a_bare_header_are_left_alone() {
726        passes("-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n-----END PUBLIC KEY-----");
727        passes("-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0B\n-----END CERTIFICATE-----");
728        passes("Keys start with -----BEGIN PRIVATE KEY----- and end with a footer.");
729    }
730
731    // Bearer ----------------------------------------------------------------------------------
732
733    #[test]
734    fn a_bearer_token_is_replaced_and_the_word_stays() {
735        fires(
736            "Authorization: Bearer abc123DEF456ghi789jkl",
737            "Authorization: Bearer [redacted:bearer-token]",
738        );
739        fires(
740            "curl -H 'authorization: bearer Zm9vYmFyYmF6cXV4MTIz'",
741            "curl -H 'authorization: bearer [redacted:bearer-token]'",
742        );
743        fires(
744            "Send Bearer abc123DEF456ghi789jkl.",
745            "Send Bearer [redacted:bearer-token].",
746        );
747    }
748
749    #[test]
750    fn the_word_bearer_in_prose_is_left_alone() {
751        passes("Bearer authentication is described in RFC 6750");
752        passes("the bearer of this letter");
753        passes("Bearer tokens are sent in a header");
754        passes("Bearer abcdefghijklmnopqrstuvwxyz"); // no digit, no mixed case
755    }
756
757    // JWT -------------------------------------------------------------------------------------
758
759    #[test]
760    fn a_jwt_is_redacted() {
761        fires(
762            "id_token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk;",
763            "id_token=[redacted:jwt];",
764        );
765    }
766
767    #[test]
768    fn something_that_only_looks_like_the_start_of_a_jwt_is_left_alone() {
769        passes("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9"); // two parts
770        passes("eyJ.a.b");
771        passes("see eyJ for the base64 of an opening brace and quote");
772        passes("xeyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.dBjftJeZ4CVP");
773    }
774
775    // URL userinfo ----------------------------------------------------------------------------
776
777    #[test]
778    fn the_password_in_a_url_is_replaced_and_the_user_stays() {
779        fires(
780            "clone https://alice:hunter2@example.com/repo.git",
781            "clone https://alice:[redacted:password]@example.com/repo.git",
782        );
783        fires(
784            "postgres://app:p%40ss@db.internal:5432/app",
785            "postgres://app:[redacted:password]@db.internal:5432/app",
786        );
787        fires(
788            "mongodb+srv://u:p@ss@cluster0.example.net/db",
789            "mongodb+srv://u:[redacted:password]@cluster0.example.net/db",
790        );
791    }
792
793    #[test]
794    fn urls_without_a_password_or_with_a_placeholder_are_left_alone() {
795        passes("https://example.com:8080/path");
796        passes("ssh://git@github.com/org/repo");
797        passes("https://alice@example.com/");
798        passes("http://[::1]:8080/");
799        passes("https://alice:${DB_PASSWORD}@example.com/");
800        passes("https://alice:****@example.com/");
801        passes("see user:pass@host for the format"); // no scheme
802        passes("https://example.com/a:b@c");
803    }
804
805    #[test]
806    fn a_secret_that_is_the_user_of_a_url_is_found_as_well() {
807        fires(
808            "https://sk-abcdefghij0123456789:hunter2@example.com",
809            "https://[redacted:api-key]:[redacted:password]@example.com",
810        );
811    }
812
813    // Assignments -----------------------------------------------------------------------------
814
815    #[test]
816    fn a_secret_named_assignment_is_redacted_and_the_name_stays() {
817        fires("API_TOKEN=abcdef0123456789", "API_TOKEN=[redacted:token]");
818        fires(
819            "export DB_PASSWORD=correct-horse-battery",
820            "export DB_PASSWORD=[redacted:password]",
821        );
822        fires(
823            "aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
824            "aws_secret_access_key = [redacted:access_key]",
825        );
826        fires(
827            r#"{"client_secret": "0123456789abcdefAB"}"#,
828            r#"{"client_secret": "[redacted:client_secret]"}"#,
829        );
830        fires(
831            "password: 'abcdefghijkl'",
832            "password: '[redacted:password]'",
833        );
834        fires(
835            "GET /x?access_token=abc123abc123abc&b=1",
836            "GET /x?access_token=[redacted:token]&b=1",
837        );
838        fires(
839            "GET /x?token=abc123abc123abc&b=1",
840            "GET /x?token=[redacted:token]&b=1",
841        );
842        fires("--token=abcdef0123456789", "--token=[redacted:token]");
843        fires("API_KEY=abcdef0123456789", "API_KEY=[redacted:api_key]");
844        fires("apikey=abcdef0123456789", "apikey=[redacted:apikey]");
845        fires("passwd = abcdef0123456789", "passwd = [redacted:passwd]");
846        fires("pwd=abcdef0123456789", "pwd=[redacted:pwd]");
847        fires("secret=abcdef0123456789", "secret=[redacted:secret]");
848        fires(
849            "access_key=abcdef0123456789",
850            "access_key=[redacted:access_key]",
851        );
852        // The exception above is for names that carry keys; a password may be all letters.
853        fires(
854            "DB_PASSWORD=correcthorsebatterystaple",
855            "DB_PASSWORD=[redacted:password]",
856        );
857        // `#415`: the two shapes a `cat .env` actually produces — a short value, and a value with
858        // punctuation in it — both used to pass through untouched.
859        fires("password=hunter2", "password=[redacted:password]");
860        // A name whose value carries punctuation: the `!` used to end the value run.
861        fires("DB_PASSWORD=hunter2!", "DB_PASSWORD=[redacted:password]");
862        // …and the same shape inside an escaped JSON string, where every quote has a backslash
863        // in front of it and the old scan gave up on the first one it met.
864        fires(
865            r#"{"json": "{\"password\": \"hunter2\"}"}"#,
866            r#"{"json": "{\"password\": \"[redacted:password]\"}"}"#,
867        );
868    }
869
870    #[test]
871    fn an_assignment_whose_value_is_not_a_plain_secret_is_left_alone() {
872        passes("password=short");
873        passes("password=elevenchars"); // 11
874        passes("token=${API_TOKEN_VALUE_FROM_ENV}");
875        passes("password=$(cat /run/secrets/db_password)");
876        passes("secret_path=/etc/ssl/private/server.key");
877        passes("token=/var/run/secrets/kubernetes.io/serviceaccount/token");
878        passes("OLDPWD=/home/user/projects/eclipse");
879        passes("token == abcdefghijklmnop");
880        passes("password: required");
881        passes("token = generate_secret_key_value()");
882        passes("tokenizer=abcdefghijklmnop");
883        passes("max_tokens=1234567890123");
884        // `#415`: this used to pass, deliberately (`!` ended the run after twelve characters of
885        // scanning). It is a password with a punctuation mark in it — the commonest shape there is.
886        fires("password=abcdefghijkl!zzz", "password=[redacted:password]");
887        // A type or a variable where a secret was expected. Seen in the agent's own source, so it
888        // is the case that matters most: a redacted field name degrades every read of a codebase.
889        passes("token: AccessTokenRequest");
890        passes("api_key: ApiKeyConfig");
891        passes("access_key: AuthenticationProvider");
892        passes("secret: SomeLongIdentifierName");
893    }
894
895    #[test]
896    fn a_value_that_is_a_known_key_is_reported_under_the_assignments_name() {
897        fires(
898            "API_KEY=sk-abcdefghij0123456789",
899            "API_KEY=[redacted:api_key]",
900        );
901    }
902
903    // The properties --------------------------------------------------------------------------
904
905    #[test]
906    fn ordinary_prose_and_logs_pass_through_byte_identical() {
907        passes("");
908        passes("The quick brown fox jumps over the lazy dog.");
909        passes("2026-11-28T19:00:00Z INFO server listening on 127.0.0.1:8787 (pid 4242)");
910        passes("error[E0432]: unresolved import `crate::redact` at src/lib.rs:12:5");
911        passes("commit d3fc7fe docs: the repository is private until the first public release");
912        passes("sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08");
913        passes("let token = lexer.next_token(); // tokens are not secrets");
914        passes("Reset your password at https://example.com/reset?user=1 and log in again.");
915        passes("héllo wörld — ünïcode ✓ and 日本語 pass through");
916        passes("    \t\n\r\n");
917    }
918
919    #[test]
920    fn an_already_redacted_region_is_not_touched() {
921        passes("key [redacted:api-key] and [redacted:private-key] and [redacted:token]");
922        passes("API_TOKEN=[redacted:token]");
923        passes("Authorization: Bearer [redacted:bearer-token]");
924        passes("https://alice:[redacted:password]@example.com/");
925    }
926
927    #[test]
928    fn redacting_twice_changes_nothing_more() {
929        let messy = [
930            "a sk-abcdefghij0123456789 b ghp_0123456789abcdefghijABCDEFGHIJ c AKIAIOSFODNN7EXAMPLE",
931            "Bearer abc123DEF456ghi789jkl then https://u:pw@h/ then password=abcdefghijkl1",
932            "API_KEY=sk-abcdefghij0123456789 token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.dBjftJeZ4CVP",
933            "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\nsk-abcdefghij0123456789",
934            "xoxb-123456789012-AbCdEfGhIj\u{e9}sk-abcdefghij0123456789",
935            "sk-abcdefghij0123456789sk-abcdefghij0123456789",
936            "token=abcdefghijkl token=abcdefghijkl,token=abcdefghijkl",
937        ];
938        for text in messy {
939            let once = redact(text, &[]);
940            assert!(once.count > 0, "nothing found in: {text}");
941            let twice = redact(&once.text, &[]);
942            assert_eq!(twice.text, once.text, "not idempotent for: {text}");
943            assert_eq!(twice.count, 0);
944        }
945    }
946
947    /// Fragments that border on every pattern, shuffled by a fixed generator: whatever comes
948    /// out must be a fixed point.
949    #[test]
950    fn a_pass_over_scrambled_fragments_is_always_a_fixed_point() {
951        let parts = [
952            "sk-",
953            "ghp_",
954            "AKIA",
955            "xoxb-",
956            "AIza",
957            "eyJ",
958            ".",
959            "Bearer ",
960            "://",
961            "user:",
962            "pw@",
963            "token=",
964            "password: ",
965            "\"",
966            "'",
967            " ",
968            "\n",
969            "-----BEGIN PRIVATE KEY-----",
970            "AAAA",
971            "-----END PRIVATE KEY-----",
972            "0123456789abcdefghijKLMNOP",
973            "[redacted:",
974            "]",
975            "=",
976            "é",
977            "/",
978            "_",
979            "-",
980            "api_key=",
981        ];
982        let mut seed: u64 = 0x2545F4914F6CDD1D;
983        for _ in 0..10_000 {
984            let mut text = String::new();
985            for _ in 0..24 {
986                seed ^= seed << 13;
987                seed ^= seed >> 7;
988                seed ^= seed << 17;
989                text.push_str(parts[(seed % parts.len() as u64) as usize]);
990            }
991            let once = redact(&text, &[]);
992            let twice = redact(&once.text, &[]);
993            assert_eq!(twice.text, once.text, "not a fixed point for: {text:?}");
994        }
995    }
996
997    #[test]
998    fn an_allowed_literal_is_skipped_and_its_neighbours_are_not() {
999        let fixture = "sk-fixture0000000000000000";
1000        let allow = vec![fixture.to_string()];
1001        let text = format!("fixture {fixture} real sk-abcdefghij0123456789 and API_KEY={fixture}");
1002        let out = redact(&text, &allow);
1003        assert_eq!(
1004            out.text,
1005            format!("fixture {fixture} real [redacted:api-key] and API_KEY={fixture}")
1006        );
1007        assert_eq!(out.count, 1);
1008    }
1009
1010    #[test]
1011    fn an_allowed_string_does_not_exempt_a_longer_secret_that_merely_contains_it() {
1012        let allow = vec!["sk-fixture0000000000000000".to_string()];
1013        let out = redact("sk-fixture0000000000000000-and-more-real-secret", &allow);
1014        assert_eq!(out.text, "[redacted:api-key]");
1015    }
1016
1017    #[test]
1018    fn an_allowed_value_keeps_the_assignment_around_it_whole() {
1019        let allow = vec!["abcdef0123456789".to_string()];
1020        let out = redact("API_TOKEN=abcdef0123456789", &allow);
1021        assert_eq!(out.text, "API_TOKEN=abcdef0123456789");
1022        assert_eq!(out.count, 0);
1023    }
1024
1025    #[test]
1026    fn the_count_is_the_number_of_secrets_replaced() {
1027        let out = redact("sk-abcdefghij0123456789 and AKIAIOSFODNN7EXAMPLE", &[]);
1028        assert_eq!(out.count, 2);
1029        assert_eq!(r("nothing here"), "nothing here");
1030    }
1031
1032    /// Long runs of the characters every pattern scans over must stay linear: a tool result
1033    /// can be 32 KB of anything, and this runs on every one.
1034    #[test]
1035    fn pathological_runs_are_scanned_in_linear_time() {
1036        let started = std::time::Instant::now();
1037        for text in [
1038            "a-".repeat(100_000),
1039            "sk-".repeat(60_000),
1040            "token=".repeat(30_000),
1041            "[redacted:".repeat(20_000),
1042            "https://a:".repeat(20_000),
1043            "-----BEGIN PRIVATE KEY-----".repeat(5_000),
1044            "Bearer ".repeat(30_000),
1045            "a".repeat(200_000),
1046            "eyJ.".repeat(50_000),
1047            "password: x".repeat(20_000),
1048            "xoxb-".repeat(40_000),
1049        ] {
1050            let _ = redact(&text, &[]);
1051        }
1052        assert!(
1053            started.elapsed() < std::time::Duration::from_secs(10),
1054            "scanning took {:?}",
1055            started.elapsed()
1056        );
1057    }
1058
1059    #[test]
1060    fn multibyte_text_around_a_secret_survives() {
1061        fires(
1062            "clé: sk-abcdefghij0123456789 — fin",
1063            "clé: [redacted:api-key] — fin",
1064        );
1065    }
1066}