Skip to main content

agentmux_common/
redact.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shape-based, best-effort secret redaction — the one Rust implementation
5//! `SPEC_ERROR_COPY_EVERYWHERE_2026_09_24.md` §4.5 asks every formatter that
6//! puts error/log text on the clipboard to share, instead of each inventing
7//! its own. Moved here from `crates/srv-core/src/backend/continuity.rs`, which
8//! only recognized credential-prefixed tokens and PEM private keys — enough
9//! for a continuation packet, not enough for raw stderr and request details
10//! (Codex P1 on #3689).
11//!
12//! Deliberately manual string scanning, not the `regex` crate: nothing in
13//! this workspace depends on `regex` today, and `continuity.rs`'s own
14//! pre-existing redaction (kept here unchanged) already established that as
15//! the house style for this kind of text scan.
16//!
17//! Mirrored on the TypeScript side by `frontend/app/errors/redact.ts`, and
18//! both are tested against the same `docs/specs/fixtures/redaction-vectors.json`
19//! so the two can't drift apart (§4.5).
20
21/// The prefixes a credential-shaped token starts with. Public so a caller can tell cheaply, before decoding, that a text
22/// may hold one: a plain substring test, which no escaping of the text around a token can hide.
23pub const SECRET_PREFIXES: &[&str] = &[
24    "github_pat_", "ghp_", "gho_", "ghu_", "ghs_", "ghr_", "sk-", "xoxa-", "xoxb-", "xoxo-", "xoxp-", "xoxr-", "xoxs-",
25    "AKIA",
26];
27
28const REDACTED_HEADERS: &[&str] = &["authorization", "proxy-authorization", "x-api-key", "api-key", "cookie", "set-cookie"];
29
30const SENSITIVE_KEY_SUBSTRINGS: &[&str] = &[
31    "password", "passwd", "pwd", "secret", "token", "api_key", "apikey", "access_key", "private_key", "client_secret",
32    "credential",
33];
34
35/// The full redaction pipeline. Order matters: the original credential-prefix
36/// and private-key passes run first (unchanged, so their existing callers'
37/// exact output is preserved byte-for-byte on inputs that only they match),
38/// then the newer, broader shape-based passes.
39pub fn redact_secrets(text: &str) -> String {
40    let out = redact_credential_prefixes(text);
41    let out = redact_private_keys(&out);
42    let out = redact_headers(&out);
43    let out = redact_key_value_pairs(&out);
44    let out = redact_url_userinfo(&out);
45    let out = redact_jwts(&out);
46    redact_aws_secret_key(&out)
47}
48
49/// Blanks credential-prefixed tokens that start a word, and PEM private keys, and nothing else: the
50/// two passes of [`redact_secrets`] that look for a secret by its shape alone, without its
51/// `key: value` passes. Unlike [`redact_secrets`], a prefix inside a word does not count, so page
52/// text such as `disk-usage-report-weekly` (`sk-` inside `disk-`) comes back whole. Linear in the
53/// length of the text.
54pub fn redact_token_shapes(text: &str) -> String {
55    redact_private_keys(&redact_prefixed_tokens_at_word_start(text))
56}
57
58fn redact_prefixed_tokens_at_word_start(text: &str) -> String {
59    let word_char = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
60    let mut out = String::with_capacity(text.len());
61    let mut copied = 0;
62    let mut prev_is_word = false;
63    for (i, c) in text.char_indices() {
64        let is_word = word_char(c);
65        if is_word && !prev_is_word {
66            // A word starts here: its end is the next character that isn't one.
67            let word_end = text[i..].find(|c: char| !word_char(c)).map_or(text.len(), |n| i + n);
68            let word = &text[i..word_end];
69            if SECRET_PREFIXES.iter().any(|p| word.starts_with(p) && word.len() - p.len() >= 16) {
70                out.push_str(&text[copied..i]);
71                out.push_str("[redacted secret]");
72                copied = word_end;
73            }
74        }
75        prev_is_word = is_word;
76    }
77    out.push_str(&text[copied..]);
78    out
79}
80
81/// Blanks credential-prefixed tokens (`ghp_...`, `sk-...`, AWS access-key
82/// ids, …). Deliberately shape-based: it errs toward redacting a long token
83/// that merely looks like a secret. Was `continuity.rs::redact_secrets`.
84fn redact_credential_prefixes(text: &str) -> String {
85    let mut out = String::with_capacity(text.len());
86    let mut rest = text;
87    loop {
88        let hit = SECRET_PREFIXES
89            .iter()
90            .filter_map(|p| rest.find(p).map(|i| (i, *p)))
91            .min_by_key(|(i, p)| (*i, std::cmp::Reverse(p.len())));
92        let Some((at, prefix)) = hit else {
93            out.push_str(rest);
94            break;
95        };
96        let after = &rest[at + prefix.len()..];
97        let body = after
98            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
99            .unwrap_or(after.len());
100        out.push_str(&rest[..at]);
101        if body >= 16 {
102            out.push_str("[redacted secret]");
103        } else {
104            out.push_str(&rest[at..at + prefix.len() + body]);
105        }
106        rest = &after[body..];
107    }
108    out
109}
110
111/// Blanks PEM private keys (`-----BEGIN ... PRIVATE KEY-----` blocks), never
112/// a certificate. Public — `continuity.rs`'s own tests exercise this pass in
113/// isolation (ReAgent P0 on #3643: a certificate ahead of a key must not end
114/// the scan and let the key through).
115pub fn redact_private_keys(text: &str) -> String {
116    let mut out = text.to_string();
117    let mut from = 0;
118    while let Some(found) = out[from..].find("-----BEGIN") {
119        let start = from + found;
120        let header_end = out[start..].find('\n').map_or(out.len(), |i| start + i);
121        if !out[start..header_end].contains("PRIVATE KEY") {
122            from = header_end;
123            continue;
124        }
125        let end = out[start..]
126            .find("-----END")
127            .and_then(|i| out[start + i..].find("KEY-----").map(|j| start + i + j + "KEY-----".len()))
128            .unwrap_or(out.len());
129        out.replace_range(start..end, "[redacted private key]");
130        from = start + "[redacted private key]".len();
131    }
132    out
133}
134
135fn ends_with_newline_preserved(original: &str, out: String) -> String {
136    if original.ends_with('\n') && !out.ends_with('\n') {
137        let mut out = out;
138        out.push('\n');
139        out
140    } else {
141        out
142    }
143}
144
145/// Blanks `Authorization:` / `Proxy-Authorization:` / `x-api-key:` /
146/// `api-key:` / `cookie:` / `set-cookie:` header *values* (any scheme —
147/// `Bearer`, `Basic`, `Token`, a raw key, a cookie jar), line by line.
148fn redact_headers(text: &str) -> String {
149    let redacted = text
150        .lines()
151        .map(|line| {
152            let trimmed_start = line.trim_start();
153            let indent_len = line.len() - trimmed_start.len();
154            if let Some(colon) = trimmed_start.find(':') {
155                let name = trimmed_start[..colon].trim();
156                if REDACTED_HEADERS.iter().any(|h| h.eq_ignore_ascii_case(name)) {
157                    return format!("{}{}: [redacted]", &line[..indent_len], name);
158                }
159            }
160            line.to_string()
161        })
162        .collect::<Vec<_>>()
163        .join("\n");
164    ends_with_newline_preserved(text, redacted)
165}
166
167fn is_key_char(c: char) -> bool {
168    c.is_ascii_alphanumeric() || c == '_' || c == '-'
169}
170
171fn is_sensitive_key(key: &str) -> bool {
172    let lower = key.trim_matches(|c| c == '"' || c == '\'').to_ascii_lowercase();
173    SENSITIVE_KEY_SUBSTRINGS.iter().any(|s| lower.contains(s))
174}
175
176/// Blanks `key=value`, `key: value` and JSON `"key": "value"` pairs whose
177/// key *contains* a sensitive substring, case-insensitive — deliberately
178/// "contains", not "equals" (§4.5's literal wording), matching this module's
179/// existing err-toward-redacting philosophy. A key like `tokenizer` is
180/// redacted by this rule even though the word alone is harmless prose
181/// (`ordinary_words_that_share_a_prefix_survive_redaction` below covers the
182/// prose case, which never has the `key=`/`key:` shape this rule requires).
183fn redact_key_value_pairs(text: &str) -> String {
184    let chars: Vec<(usize, char)> = text.char_indices().collect();
185    let mut out = String::with_capacity(text.len());
186    let mut last_end = 0usize;
187    let mut idx = 0usize;
188    while idx < chars.len() {
189        let (_, ch) = chars[idx];
190        if ch != '=' && ch != ':' {
191            idx += 1;
192            continue;
193        }
194        // A JSON key's closing quote sits right before ':' — skip past it so
195        // the key-char scan below reaches the actual key text, not nothing.
196        let mut key_end_idx = idx;
197        if key_end_idx > 0 && matches!(chars[key_end_idx - 1].1, '"' | '\'') {
198            key_end_idx -= 1;
199        }
200        let mut key_start_idx = key_end_idx;
201        while key_start_idx > 0 && is_key_char(chars[key_start_idx - 1].1) {
202            key_start_idx -= 1;
203        }
204        if key_start_idx == key_end_idx {
205            idx += 1;
206            continue;
207        }
208        let key_start_byte = chars[key_start_idx].0;
209        let key_end_byte = chars[key_end_idx].0;
210        let key = &text[key_start_byte..key_end_byte];
211        if !is_sensitive_key(key) {
212            idx += 1;
213            continue;
214        }
215        // Forward: separator, optional whitespace, optional quote, the value.
216        let mut v = idx + 1;
217        while v < chars.len() && (chars[v].1 == ' ' || chars[v].1 == '\t') {
218            v += 1;
219        }
220        let val_quote = if v < chars.len() && (chars[v].1 == '"' || chars[v].1 == '\'') { Some(chars[v].1) } else { None };
221        let val_start = if val_quote.is_some() { v + 1 } else { v };
222        let mut w = val_start;
223        if let Some(vq) = val_quote {
224            while w < chars.len() && chars[w].1 != vq {
225                w += 1;
226            }
227        } else {
228            while w < chars.len() && !matches!(chars[w].1, ' ' | '\t' | '\n' | '\r' | ',' | '}' | ')' | ';') {
229                w += 1;
230            }
231        }
232        let value_prefix_end = if chars.get(val_start).is_some() || val_start == chars.len() {
233            if val_start < chars.len() { chars[val_start].0 } else { text.len() }
234        } else {
235            text.len()
236        };
237        out.push_str(&text[last_end..value_prefix_end]);
238        out.push_str("[redacted]");
239        let skip_to = if val_quote.is_some() { w + 1 } else { w };
240        last_end = if skip_to < chars.len() { chars[skip_to].0 } else { text.len() };
241        if val_quote.is_some() && w < chars.len() {
242            out.push(chars[w].1);
243        }
244        idx = skip_to;
245    }
246    out.push_str(&text[last_end..]);
247    out
248}
249
250/// Blanks URL userinfo passwords: `scheme://user:password@host` keeps
251/// `scheme://user:[redacted]@host`.
252fn redact_url_userinfo(text: &str) -> String {
253    let mut out = String::with_capacity(text.len());
254    let mut last_end = 0usize;
255    let mut search_from = 0usize;
256    while let Some(rel) = text[search_from..].find("://") {
257        let scheme_end = search_from + rel + 3;
258        let authority_end = text[scheme_end..]
259            .find(|c: char| c == '/' || c == '?' || c == '#' || c.is_whitespace())
260            .map(|i| scheme_end + i)
261            .unwrap_or(text.len());
262        let authority = &text[scheme_end..authority_end];
263        if let Some(at_rel) = authority.find('@') {
264            let at_pos = scheme_end + at_rel;
265            let userinfo = &authority[..at_rel];
266            if let Some(colon_rel) = userinfo.find(':') {
267                let colon_pos = scheme_end + colon_rel;
268                out.push_str(&text[last_end..=colon_pos]);
269                out.push_str("[redacted]");
270                last_end = at_pos;
271            }
272        }
273        search_from = authority_end.max(scheme_end + 1);
274        if search_from > text.len() {
275            break;
276        }
277    }
278    out.push_str(&text[last_end..]);
279    out
280}
281
282fn is_base64url_char(c: char) -> bool {
283    c.is_ascii_alphanumeric() || c == '-' || c == '_'
284}
285
286/// Blanks JWTs: three base64url segments, the first starting `eyJ` (a
287/// base64url-encoded `{"` — every JWT header starts with a JSON object).
288fn redact_jwts(text: &str) -> String {
289    let mut out = String::with_capacity(text.len());
290    let mut last_end = 0usize;
291    let mut search_from = 0usize;
292    while let Some(rel) = text[search_from..].find("eyJ") {
293        let start = search_from + rel;
294        let prev_is_word = start > 0 && is_base64url_char(text[..start].chars().next_back().unwrap());
295        if prev_is_word {
296            search_from = start + 3;
297            continue;
298        }
299        let seg1_end = start + text[start..].find(|c: char| !is_base64url_char(c)).unwrap_or(text.len() - start);
300        let dot1_ok = seg1_end < text.len() && text.as_bytes()[seg1_end] == b'.';
301        if !dot1_ok {
302            search_from = start + 3;
303            continue;
304        }
305        let seg2_start = seg1_end + 1;
306        let seg2_end = seg2_start + text[seg2_start..].find(|c: char| !is_base64url_char(c)).unwrap_or(text.len() - seg2_start);
307        let dot2_ok = seg2_end > seg2_start && seg2_end < text.len() && text.as_bytes()[seg2_end] == b'.';
308        if !dot2_ok {
309            search_from = start + 3;
310            continue;
311        }
312        let seg3_start = seg2_end + 1;
313        let seg3_end = seg3_start + text[seg3_start..].find(|c: char| !is_base64url_char(c)).unwrap_or(text.len() - seg3_start);
314        if seg3_end == seg3_start {
315            search_from = start + 3;
316            continue;
317        }
318        out.push_str(&text[last_end..start]);
319        out.push_str("[redacted]");
320        last_end = seg3_end;
321        search_from = seg3_end;
322    }
323    out.push_str(&text[last_end..]);
324    out
325}
326
327fn is_base64_char(c: char) -> bool {
328    c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '='
329}
330
331/// Blanks a 40-character base64 value on the same line as
332/// `aws_secret_access_key` (any case).
333fn redact_aws_secret_key(text: &str) -> String {
334    let redacted = text
335        .lines()
336        .map(|line| {
337            if !line.to_ascii_lowercase().contains("aws_secret_access_key") {
338                return line.to_string();
339            }
340            let chars: Vec<(usize, char)> = line.char_indices().collect();
341            let mut i = 0usize;
342            while i < chars.len() {
343                if !is_base64_char(chars[i].1) {
344                    i += 1;
345                    continue;
346                }
347                let run_start = i;
348                let mut j = i;
349                while j < chars.len() && is_base64_char(chars[j].1) {
350                    j += 1;
351                }
352                if j - run_start == 40 {
353                    let start_byte = chars[run_start].0;
354                    let end_byte = if j < chars.len() { chars[j].0 } else { line.len() };
355                    return format!("{}[redacted]{}", &line[..start_byte], &line[end_byte..]);
356                }
357                i = j;
358            }
359            line.to_string()
360        })
361        .collect::<Vec<_>>()
362        .join("\n");
363    ends_with_newline_preserved(text, redacted)
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369    use std::path::PathBuf;
370
371    /// An Anthropic API key (the shape of the one a person adds in Connectors > Accounts), made up and built from pieces.
372    #[test]
373    fn an_anthropic_api_key_is_redacted_wherever_it_appears() {
374        let key = ["sk-ant", "-api03-", "MADEUPMADEUPMADEUPMADEUPMADEUP0123456789"].concat();
375        for text in [format!("key {key} used"), format!("x-api-key: {key}"), format!("ANTHROPIC_API_KEY={key}"), format!("{{\"error\":\"bad {key}\"}}")] {
376            let out = redact_secrets(&text);
377            assert!(!out.contains("MADEUP") && !out.contains(&key), "{text} -> {out}");
378        }
379        assert!(!redact_token_shapes(&format!("pasted {key}")).contains("MADEUP"), "the shape pass alone catches it too");
380    }
381
382    #[test]
383    fn a_private_key_after_a_certificate_is_still_redacted() {
384        let text = "-----BEGIN CERTIFICATE-----\nMIIBcert\n-----END CERTIFICATE-----\n\
385                    -----BEGIN RSA PRIV\
386                    ATE KEY-----\nMIIEsecret\n-----END RSA PRIV\
387                    ATE KEY-----\ndone";
388        let out = redact_private_keys(text);
389        assert!(out.contains("MIIBcert"), "a certificate is public: {out}");
390        assert!(!out.contains("MIIEsecret"), "{out}");
391        assert!(out.contains("[redacted private key]") && out.ends_with("done"));
392    }
393
394    #[test]
395    fn every_slack_token_family_is_redacted() {
396        for prefix in ["xoxa-", "xoxb-", "xoxo-", "xoxp-", "xoxr-", "xoxs-"] {
397            let token = format!("{prefix}1234567890-abcdefghijklmnop");
398            assert_eq!(redact_secrets(&format!("t {token} t")), "t [redacted secret] t", "{prefix}");
399        }
400    }
401
402    #[test]
403    fn ordinary_words_that_share_a_prefix_survive_redaction() {
404        assert_eq!(redact_secrets("a task-list and a desk-lamp"), "a task-list and a desk-lamp");
405    }
406
407    #[test]
408    fn authorization_header_any_scheme_is_redacted() {
409        assert_eq!(redact_secrets("Authorization: Bearer abc.def.ghi"), "Authorization: [redacted]");
410        assert_eq!(redact_secrets("Authorization: Basic dXNlcjpwYXNz"), "Authorization: [redacted]");
411        assert_eq!(redact_secrets("proxy-authorization: Token xyz"), "proxy-authorization: [redacted]");
412    }
413
414    #[test]
415    fn cookie_and_api_key_headers_are_redacted() {
416        assert_eq!(redact_secrets("x-api-key: abc123"), "x-api-key: [redacted]");
417        assert_eq!(redact_secrets("Cookie: session=abc123"), "Cookie: [redacted]");
418        assert_eq!(redact_secrets("Set-Cookie: session=abc123; Path=/"), "Set-Cookie: [redacted]");
419    }
420
421    #[test]
422    fn key_value_forms_are_redacted() {
423        assert_eq!(redact_secrets("password=hunter2"), "password=[redacted]");
424        assert_eq!(redact_secrets("password: hunter2"), "password: [redacted]");
425        assert_eq!(redact_secrets(r#"{"password": "hunter2"}"#), r#"{"password": "[redacted]"}"#);
426        assert_eq!(redact_secrets("client_secret=abc123"), "client_secret=[redacted]");
427        assert_eq!(redact_secrets("credential=abc123"), "credential=[redacted]");
428    }
429
430    #[test]
431    fn url_userinfo_password_is_redacted_not_the_username() {
432        assert_eq!(
433            redact_secrets("fetch https://alice:hunter2@example.com/path?q=1"),
434            "fetch https://alice:[redacted]@example.com/path?q=1"
435        );
436    }
437
438    #[test]
439    fn a_jwt_is_redacted_whole() {
440        let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U";
441        assert_eq!(redact_secrets(&format!("token is {jwt} end")), "token is [redacted] end");
442    }
443
444    #[test]
445    fn an_aws_secret_access_key_is_redacted() {
446        assert_eq!(
447            redact_secrets("aws_secret_access_key=ABCDEFGHIJabcdefghij1234567890ABCDEFGHIJ"),
448            "aws_secret_access_key=[redacted]"
449        );
450    }
451
452    #[test]
453    fn a_secret_straddling_a_cut_boundary_is_still_redacted() {
454        let long = format!("{}ghp_abcdefghijklmnopqrstuvwxyz0123{}", "a".repeat(1_994), "b".repeat(5_000));
455        let out = redact_secrets(&long);
456        assert!(!out.contains("ghp_ab"), "a fragment of the token leaked");
457        assert!(out.contains("[redacted secret]"));
458    }
459
460    /// §4.5 / §8: one shared set of vectors, run by both this crate and
461    /// `frontend/app/errors/redact.test.ts`, so the two implementations
462    /// can't silently drift apart.
463    #[test]
464    fn shared_redaction_vectors() {
465        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
466            .parent()
467            .and_then(std::path::Path::parent)
468            .expect("crates/common is two levels below the repo root")
469            .join("docs/specs/fixtures/redaction-vectors.json");
470        let raw = std::fs::read_to_string(&root).unwrap_or_else(|e| panic!("reading {root:?}: {e}"));
471        let vectors: Vec<serde_json::Value> = serde_json::from_str(&raw).expect("valid JSON");
472        assert!(!vectors.is_empty());
473        for v in &vectors {
474            let name = v["name"].as_str().unwrap_or("<unnamed>");
475            let input = v["input"].as_str().expect("vector.input is a string");
476            let expected = v["expected"].as_str().expect("vector.expected is a string");
477            assert_eq!(redact_secrets(input), expected, "vector {name:?}");
478        }
479    }
480}