Skip to main content

rig_core/
redact.rs

1//! Finding and redacting secrets in text a host logs, shows or shares: API keys and tokens by
2//! their known shapes, private key blocks, and values assigned to secret-named variables.
3//!
4//! A shape matches only where a token starts, so the same letters inside a word or a base64
5//! blob are not a key. A secret with neither a known shape nor a telling name, such as a
6//! password in prose, is not found.
7//!
8//! ```
9//! use rig_core::redact;
10//!
11//! let line = "export ANTHROPIC_API_KEY=sk-ant-api03-abcdefghijklmnopqrstuvwxyz";
12//! assert!(redact::has_secret(line));
13//! assert_eq!(redact::text(line), "export ANTHROPIC_API_KEY=[REDACTED]");
14//! assert_eq!(redact::text("nothing to hide"), "nothing to hide");
15//! ```
16
17use std::borrow::Cow;
18use std::fmt;
19use std::ops::Range;
20
21use serde_json::Value;
22
23#[cfg(test)]
24mod tests;
25
26/// What [`text`] and [`json`] put in place of a secret.
27pub const REDACTED: &str = "[REDACTED]";
28
29/// What kind of secret a [`SecretMatch`] is.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31#[non_exhaustive]
32pub enum Kind {
33    /// An OpenAI API key: `sk-`, `sk-proj-` or `sk-svcacct-`.
34    OpenAiApiKey,
35    /// An Anthropic API key: `sk-ant-`.
36    AnthropicApiKey,
37    /// A Google API key: `AIza`.
38    GoogleApiKey,
39    /// An AWS access key id: `AKIA` or `ASIA`.
40    AwsAccessKey,
41    /// A GitHub token: `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_` or
42    /// `github_pat_`.
43    GitHubToken,
44    /// A GitLab personal access token: `glpat-`.
45    GitLabToken,
46    /// A Slack token: `xoxa-`, `xoxb-`, `xoxp-`, `xoxr-` or `xoxs-`.
47    SlackToken,
48    /// A Stripe secret or restricted key: `sk_live_`, `sk_test_`,
49    /// `rk_live_` or `rk_test_`.
50    StripeKey,
51    /// A Hugging Face access token: `hf_`.
52    HuggingFaceToken,
53    /// A JSON Web Token, such as an OAuth access or id token: a base64url
54    /// header and payload, each a JSON object (`eyJ…`), and a signature,
55    /// joined by `.`; the signature may be empty.
56    JsonWebToken,
57    /// A PEM private key block, `-----BEGIN … PRIVATE KEY-----` through its
58    /// end line, or through the end of the text when it has none.
59    PrivateKey,
60    /// A value assigned to a name that says it is secret, `NAME=value` or
61    /// `NAME: value`: the name in upper snake case and, or ending in,
62    /// `SECRET`, `TOKEN`, `PASSWORD`, `PASSWD`, `API_KEY`, `ACCESS_KEY`,
63    /// `SECRET_KEY` or `PRIVATE_KEY` (so `AWS_SECRET_ACCESS_KEY` and
64    /// `GITHUB_TOKEN`, not `MAX_TOKENS` or `TOKEN_COUNT`). The value runs
65    /// to its closing quote when quoted, else to whitespace, a quote, `,`,
66    /// `;` or `&` (the next assignment of a query string), less a sentence's
67    /// closing `.`, `,`, `:`, `!`, `?` or `)` unless that leaves it too
68    /// short; one of at most
69    /// 7 characters, all digits, starting with `$` (a reference such as
70    /// `$GITHUB_TOKEN`), with characters other than printable ASCII (a
71    /// placeholder such as `‹SECRET_1›`), or one holding [`REDACTED`] is
72    /// not a secret, so redacting text again changes nothing.
73    /// Only the value is the secret.
74    Assigned,
75}
76
77impl Kind {
78    /// The kind's name, such as `OpenAI API key`.
79    pub fn name(self) -> &'static str {
80        match self {
81            Self::OpenAiApiKey => "OpenAI API key",
82            Self::AnthropicApiKey => "Anthropic API key",
83            Self::GoogleApiKey => "Google API key",
84            Self::AwsAccessKey => "AWS access key",
85            Self::GitHubToken => "GitHub token",
86            Self::GitLabToken => "GitLab token",
87            Self::SlackToken => "Slack token",
88            Self::StripeKey => "Stripe key",
89            Self::HuggingFaceToken => "Hugging Face token",
90            Self::JsonWebToken => "JSON Web Token",
91            Self::PrivateKey => "private key",
92            Self::Assigned => "assigned secret",
93        }
94    }
95}
96
97impl fmt::Display for Kind {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.write_str(self.name())
100    }
101}
102
103/// A secret [`find`] found: its kind, and where it is in the text, in
104/// bytes.
105#[derive(Clone, Debug, PartialEq, Eq)]
106pub struct SecretMatch {
107    /// What kind of secret it is.
108    pub kind: Kind,
109    /// Where it is in the text searched.
110    pub range: Range<usize>,
111}
112
113/// Every secret in `input`, in order and not overlapping.
114///
115/// ```
116/// use rig_core::redact::{self, Kind};
117///
118/// let found: Vec<_> = redact::find("id AKIA0123456789ABCDEF here").collect();
119/// assert_eq!(found.len(), 1);
120/// assert_eq!(found[0].kind, Kind::AwsAccessKey);
121/// assert_eq!(found[0].range, 3..23);
122/// ```
123pub fn find(input: &str) -> impl Iterator<Item = SecretMatch> + '_ {
124    // Bytes, not chars: every token character is ASCII, so a token starts
125    // on a char boundary, and the bytes of any other character are skipped.
126    let bytes = input.as_bytes();
127    let mut at = 0;
128    // Where the last secret ended: what follows it starts a token, as it
129    // does after the secret is redacted, so redacting twice finds nothing new.
130    let mut ended = 0;
131    std::iter::from_fn(move || {
132        while let Some(&byte) = bytes.get(at) {
133            if !is_token_byte(byte) {
134                at += 1;
135                continue;
136            }
137            let rest = bytes.get(at..).unwrap_or_default();
138            let len = rest
139                .iter()
140                .position(|&byte| !is_token_byte(byte))
141                .unwrap_or(rest.len());
142            let token = rest.get(..len).unwrap_or_default();
143            if may_be_secret(token)
144                && (starts_token(input, at) || at == ended)
145                && let Some(rest) = input.get(at..)
146            {
147                let found = secret_at(rest).map(|(kind, len)| (kind, 0..len));
148                let found = found.or_else(|| Some((Kind::Assigned, assigned(rest)?)));
149                if let Some((kind, range)) = found {
150                    let range = at + range.start..at + range.end;
151                    (at, ended) = (range.end, range.end);
152                    return Some(SecretMatch { kind, range });
153                }
154            }
155            // A token's tail starts no key, so skip to the token's end.
156            at += len;
157        }
158        None
159    })
160}
161
162/// Whether `input` holds a secret.
163pub fn has_secret(input: &str) -> bool {
164    find(input).next().is_some()
165}
166
167/// `input` with every secret replaced by [`REDACTED`]; borrowed when it has
168/// none.
169pub fn text(input: &str) -> Cow<'_, str> {
170    text_with(input, |_| REDACTED.to_owned())
171}
172
173/// `input` with every secret replaced by what `replace` gives for it, such
174/// as a placeholder that names it; borrowed when it has none.
175pub fn text_with(input: &str, mut replace: impl FnMut(&str) -> String) -> Cow<'_, str> {
176    let mut found = find(input).peekable();
177    if found.peek().is_none() {
178        return Cow::Borrowed(input);
179    }
180    let mut out = String::with_capacity(input.len());
181    let mut from = 0;
182    for secret in found {
183        out.push_str(input.get(from..secret.range.start).unwrap_or_default());
184        from = secret.range.end;
185        out.push_str(&replace(input.get(secret.range).unwrap_or_default()));
186    }
187    out.push_str(input.get(from..).unwrap_or_default());
188    Cow::Owned(out)
189}
190
191/// The most a [`Streamed`] holds back, in bytes: a private key block, the
192/// longest secret, is a few kilobytes.
193const HELD_MOST: usize = 16 * 1024;
194
195/// A text that arrives in pieces, such as a streamed reply, cut where no
196/// secret crosses: what [`Self::push`] and [`Self::finish`] return, each
197/// redacted on its own, joined, is the pieces joined redacted. It holds back
198/// only what a later piece may still make part of a secret, and at most
199/// 16 KiB.
200///
201/// ```
202/// use rig_core::redact::{self, Streamed};
203///
204/// let mut streamed = Streamed::default();
205/// let mut shown = String::new();
206/// for piece in ["export GITHUB_TOKEN=gh", "p_abcdefghijklmnopqrstuvwxyz0123456789\nnext "] {
207///     shown += &redact::text(&streamed.push(piece));
208/// }
209/// shown += &redact::text(&streamed.finish());
210/// assert_eq!(shown, "export GITHUB_TOKEN=[REDACTED]\nnext ");
211/// ```
212#[derive(Clone, Debug, Default)]
213pub struct Streamed {
214    /// What came and was not returned yet.
215    held: String,
216}
217
218impl Streamed {
219    /// Takes `piece` and returns what no later piece can change.
220    pub fn push(&mut self, piece: &str) -> String {
221        self.held.push_str(piece);
222        let rest = self.held.split_off(settled(&self.held));
223        std::mem::replace(&mut self.held, rest)
224    }
225
226    /// Returns what it still holds: the text ended.
227    pub fn finish(&mut self) -> String {
228        std::mem::take(&mut self.held)
229    }
230}
231
232/// How much of `input`, a text that may still grow, no secret found in the
233/// grown text can cross: up to the last run of key characters, the line
234/// that names a secret, or the line of a secret that runs to the end, such
235/// as a private key block. At most [`HELD_MOST`] bytes stay held.
236fn settled(input: &str) -> usize {
237    let word = input
238        .char_indices()
239        .rfind(|&(_, ch)| !is_token_char(ch) && !matches!(ch, '.' | '+' | '/'))
240        .map_or(0, |(at, ch)| at + ch.len_utf8());
241    let line_of = |at: usize| {
242        input
243            .get(..at)
244            .and_then(|before| before.rfind('\n'))
245            .map_or(0, |at| at + 1)
246    };
247    let line = line_of(input.len());
248    let last = input.get(line..).unwrap_or_default();
249    // A run of key characters that ends as a secret name does, wherever in
250    // the run [`find`] may start a token.
251    let named = SECRET_NAMES.iter().any(|name| {
252        last.match_indices(name).any(|(at, _)| {
253            let after = last.get(at + name.len()..).unwrap_or_default();
254            !after.starts_with(is_token_char)
255        })
256    });
257    let mut cut = word;
258    if named || last.contains("-----BEGIN ") {
259        cut = cut.min(line);
260    }
261    let found: Vec<_> = find(input).collect();
262    // A secret that reaches the end may still grow, as a block not yet ended.
263    for found in found.iter().rev() {
264        let past = cut < found.range.end || found.range.end == input.len();
265        if found.range.start < cut && past {
266            cut = line_of(found.range.start);
267        }
268    }
269    let least = input.len().saturating_sub(HELD_MOST);
270    let cut = input.ceil_char_boundary(cut.max(least));
271    // A whole secret the bound cuts through goes out whole, so it is
272    // redacted as in the whole text: an assigned value with its name before
273    // it and its closing quote after it.
274    let whole = |found: &SecretMatch| {
275        let (start, end) = (found.range.start, found.range.end);
276        if found.kind != Kind::Assigned {
277            return start..end;
278        }
279        let before = input.get(..start).unwrap_or_default();
280        let named = before.trim_end_matches(['=', ':', '"', '\'', ' ', '\t']);
281        let quoted = input
282            .get(end..)
283            .is_some_and(|after| after.starts_with(['"', '\'']));
284        named.trim_end_matches(is_token_char).len()..end + usize::from(quoted)
285    };
286    let through = found
287        .iter()
288        .map(whole)
289        .find(|whole| whole.start < cut && cut < whole.end && whole.end < input.len());
290    through.map_or(cut, |whole| whole.end)
291}
292
293/// Every string in `value` redacted as [`text`] redacts it, and one that
294/// holds JSON, such as a provider's raw tool-call arguments, as that JSON
295/// too: an escape such as `\n` would hide where a secret starts. Whether
296/// any was. Object keys are left as they are.
297pub fn json(value: &mut Value) -> bool {
298    json_with(value, &mut |_| REDACTED.to_owned())
299}
300
301/// [`json`], each secret replaced by what `replace` gives for it.
302fn json_with(value: &mut Value, replace: &mut impl FnMut(&str) -> String) -> bool {
303    match value {
304        Value::String(string) => {
305            let mut changed = match text_with(string, &mut *replace) {
306                Cow::Owned(redacted) => {
307                    *string = redacted;
308                    true
309                }
310                Cow::Borrowed(_) => false,
311            };
312            if string.trim_start().starts_with(['{', '['])
313                && let Ok(mut inner) = serde_json::from_str::<Value>(string)
314                && json_with(&mut inner, replace)
315            {
316                *string = inner.to_string();
317                changed = true;
318            }
319            changed
320        }
321        Value::Array(items) => items
322            .iter_mut()
323            .fold(false, |any, item| json_with(item, replace) | any),
324        Value::Object(fields) => fields
325            .values_mut()
326            .fold(false, |any, field| json_with(field, replace) | any),
327        Value::Null | Value::Bool(_) | Value::Number(_) => false,
328    }
329}
330
331/// The secret `rest` starts with, and its length in bytes.
332fn secret_at(rest: &str) -> Option<(Kind, usize)> {
333    if rest.starts_with("-----BEGIN ") {
334        return private_key(rest).map(|len| (Kind::PrivateKey, len));
335    }
336    if let Some(len) = json_web_token(rest) {
337        return Some((Kind::JsonWebToken, len));
338    }
339    let token = rest.get(..token_len(rest))?;
340    if let Some(len) = aws_access_key(token) {
341        return Some((Kind::AwsAccessKey, len));
342    }
343    let kind = TOKENS.iter().find_map(|&(prefix, min, kind)| {
344        let tail = token.strip_prefix(prefix)?;
345        is_plausible(tail, min).then_some(kind)
346    })?;
347    Some((kind, token.len()))
348}
349
350/// Token shapes: a prefix, the fewest characters after it, and the kind. A
351/// longer prefix comes before a shorter one it starts with.
352const TOKENS: &[(&str, usize, Kind)] = &[
353    ("sk-ant-", 16, Kind::AnthropicApiKey),
354    ("sk-proj-", 16, Kind::OpenAiApiKey),
355    ("sk-svcacct-", 16, Kind::OpenAiApiKey),
356    ("sk-", 32, Kind::OpenAiApiKey),
357    ("AIza", 20, Kind::GoogleApiKey),
358    ("github_pat_", 22, Kind::GitHubToken),
359    ("ghp_", 30, Kind::GitHubToken),
360    ("gho_", 30, Kind::GitHubToken),
361    ("ghu_", 30, Kind::GitHubToken),
362    ("ghs_", 30, Kind::GitHubToken),
363    ("ghr_", 30, Kind::GitHubToken),
364    ("glpat-", 20, Kind::GitLabToken),
365    ("xoxa-", 10, Kind::SlackToken),
366    ("xoxb-", 10, Kind::SlackToken),
367    ("xoxp-", 10, Kind::SlackToken),
368    ("xoxr-", 10, Kind::SlackToken),
369    ("xoxs-", 10, Kind::SlackToken),
370    ("sk_live_", 16, Kind::StripeKey),
371    ("sk_test_", 16, Kind::StripeKey),
372    ("rk_live_", 16, Kind::StripeKey),
373    ("rk_test_", 16, Kind::StripeKey),
374    ("hf_", 30, Kind::HuggingFaceToken),
375];
376
377/// The names, or ends of names after a `_`, that say a variable holds a
378/// secret.
379const SECRET_NAMES: &[&str] = &[
380    "SECRET",
381    "TOKEN",
382    "PASSWORD",
383    "PASSWD",
384    "API_KEY",
385    "ACCESS_KEY",
386    "SECRET_KEY",
387    "PRIVATE_KEY",
388];
389
390/// Where the secret value assigned to the secret-named variable `rest`
391/// starts with is, in `rest`: see [`Kind::Assigned`]. `None` when the value
392/// is a key of a known shape, which the scan finds as its own kind.
393fn assigned(rest: &str) -> Option<Range<usize>> {
394    let name = rest.get(..token_len(rest))?;
395    let upper_snake = name.starts_with(|ch: char| ch.is_ascii_uppercase())
396        && name
397            .chars()
398            .all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_');
399    let secret_named = SECRET_NAMES.iter().any(|end| {
400        name.strip_suffix(end)
401            .is_some_and(|head| head.is_empty() || head.ends_with('_'))
402    });
403    if !upper_snake || !secret_named {
404        return None;
405    }
406    // A quoted name's closing quote, then `=` or `:`, spaces around it.
407    let after = rest.get(name.len()..)?;
408    let after = after.strip_prefix(['"', '\'']).unwrap_or(after);
409    let after = after.trim_start_matches([' ', '\t']);
410    let after = after.strip_prefix(['=', ':'])?;
411    let after = after.trim_start_matches([' ', '\t']);
412    let start = rest.len() - after.len();
413    let plausible = |value: &str| {
414        value.len() >= 8
415            && value.chars().all(|ch| ch.is_ascii_graphic() || ch == ' ')
416            && !value.starts_with('$')
417            && !value.chars().all(|ch| ch.is_ascii_digit())
418            && !value.contains(REDACTED)
419            && secret_at(value).is_none()
420    };
421    let (from, value) = match after.chars().next()? {
422        quote @ ('"' | '\'') => {
423            let inner = after.get(1..)?;
424            (start + 1, inner.get(..inner.find(quote)?)?)
425        }
426        _ => {
427            let whole = after.get(..after.find(ends_value).unwrap_or(after.len()))?;
428            // A sentence's closing punctuation is not part of the value,
429            // unless the value is too short without it.
430            let trimmed = whole.trim_end_matches(['.', ',', ':', '!', '?', ')']);
431            (start, if trimmed.len() >= 8 { trimmed } else { whole })
432        }
433    };
434    plausible(value).then(|| from..from + value.len())
435}
436
437/// Whether `ch` ends an unquoted assigned value: whitespace, a quote, or a
438/// separator between assignments (`,`, `;`, `&`).
439fn ends_value(ch: char) -> bool {
440    ch.is_whitespace() || matches!(ch, '"' | '\'' | '`' | ',' | ';' | '&')
441}
442
443/// Whether `tail`, the rest of a token after a key's prefix, is long
444/// enough and has a letter, so `sk-` followed by a number or a short word
445/// is not a key.
446fn is_plausible(tail: &str, min: usize) -> bool {
447    tail.len() >= min && tail.chars().any(|ch| ch.is_ascii_alphabetic())
448}
449
450/// The length of the AWS access key id `token` starts with: `AKIA` or
451/// `ASIA` and 16 upper-case letters or digits, no more.
452fn aws_access_key(token: &str) -> Option<usize> {
453    let tail = token
454        .strip_prefix("AKIA")
455        .or_else(|| token.strip_prefix("ASIA"))?;
456    let len = tail
457        .chars()
458        .take_while(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit())
459        .count();
460    (len == 16).then_some(4 + len)
461}
462
463/// The length of the JSON Web Token `rest` starts with: a header and a
464/// payload of at least 10 base64url characters each, both starting `eyJ`
465/// (`{"`), each followed by `.`, then the signature's base64url characters,
466/// if any.
467fn json_web_token(rest: &str) -> Option<usize> {
468    let mut len = 0;
469    for _ in 0..2 {
470        let part = rest.get(len..)?;
471        let segment = token_len(part);
472        if !part.starts_with("eyJ") || segment < 10 || !part.get(segment..)?.starts_with('.') {
473            return None;
474        }
475        len += segment + 1;
476    }
477    Some(len + token_len(rest.get(len..)?))
478}
479
480/// Whether a secret may start at `token`, a run of token characters: it
481/// starts as a key's prefix, a private key's header or a JSON Web Token
482/// does, or it is upper case and ends as a secret name does. A cheap test
483/// before the full one.
484fn may_be_secret(token: &[u8]) -> bool {
485    let first = token.first().copied().unwrap_or_default();
486    let second = token.get(1).copied().unwrap_or_default();
487    let shaped = matches!(
488        (first, second),
489        (b's' | b'r', b'k')
490            | (b'A', b'I' | b'K' | b'S')
491            | (b'g', b'h' | b'i' | b'l')
492            | (b'x', b'o')
493            | (b'h', b'f')
494            | (b'e', b'y')
495            | (b'-', b'-')
496    );
497    let named =
498        first.is_ascii_uppercase() && matches!(token.last(), Some(b'T' | b'N' | b'D' | b'Y'));
499    shaped || named
500}
501
502/// Whether `byte` may be part of a key: [`is_token_char`] for bytes.
503fn is_token_byte(byte: u8) -> bool {
504    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
505}
506
507/// The length of the private key block `rest` starts with, through its end
508/// line, else through the end of `rest`.
509fn private_key(rest: &str) -> Option<usize> {
510    let header = rest.get("-----BEGIN ".len()..)?;
511    let label = header.split_once("-----")?.0;
512    let is_key = label.ends_with("PRIVATE KEY")
513        && label.chars().all(|ch| ch.is_ascii_uppercase() || ch == ' ');
514    if !is_key {
515        return None;
516    }
517    let end = format!("-----END {label}-----");
518    Some(
519        rest.find(end.as_str())
520            .map_or(rest.len(), |at| at + end.len()),
521    )
522}
523
524/// The length of the run of token characters `rest` starts with.
525fn token_len(rest: &str) -> usize {
526    rest.find(|ch| !is_token_char(ch)).unwrap_or(rest.len())
527}
528
529/// Whether `ch` may be part of a key.
530fn is_token_char(ch: char) -> bool {
531    ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-')
532}
533
534/// Whether a token starts at `at` in `input`: the character before is
535/// neither a token character nor base64's `+` or `/`, so the same letters
536/// inside a word or a base64 blob (a signature, ciphertext, an image) are
537/// not read as the start of a key.
538fn starts_token(input: &str, at: usize) -> bool {
539    input
540        .get(..at)
541        .and_then(|before| before.chars().next_back())
542        .is_none_or(|ch| !is_token_char(ch) && !matches!(ch, '+' | '/'))
543}