Skip to main content

vtcode_commons/
sanitizer.rs

1//! Secret sanitization utilities for redacting sensitive information.
2//!
3//! Provides regex-based secret redaction for:
4//! - OpenAI API keys (`sk-...`)
5//! - AWS Access Key IDs (`AKIA...`)
6//! - Google API keys (`AIza...`, Gemini/Maps/Firebase)
7//! - GitHub App installation tokens (`ghs_...`, including ~520-char stateless JWTs)
8//! - Other GitHub token prefixes (`ghp_`/`gho_`/`ghu_`/`ghr_`/`github_pat_...`)
9//! - Bearer tokens (`Bearer ...`)
10//! - Generic secret assignments (`api_key=...`, `password:...`, etc.)
11//!
12//! Use this module to sanitize text before logging, displaying in UI,
13//! or storing in session archives.
14//!
15//! GitHub App installation tokens are treated as opaque strings per
16//! <https://github.blog/changelog/2026-05-15-github-app-installation-tokens-per-request-override-header/>
17//! and <https://github.blog/changelog/2026-10-02-stateless-github-app-installation-tokens-rolled-out>:
18//! `ghs_`-prefixed JWTs (~520 chars, two dots) must not be subject to length
19//! assumptions and must be redacted even without a `Bearer` prefix.
20
21use regex::Regex;
22use std::sync::LazyLock;
23
24/// OpenAI API key pattern: sk- followed by alphanumeric characters
25static OPENAI_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"sk-[A-Za-z0-9_-]{16,}"));
26
27/// AWS Access Key ID pattern: AKIA followed by 16 alphanumeric characters
28static AWS_ACCESS_KEY_ID_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"\bAKIA[0-9A-Z]{16}\b"));
29
30/// Google API key pattern (Gemini, Maps, Firebase): `AIza` + 35 URL-safe chars.
31static GOOGLE_API_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"\bAIza[0-9A-Za-z_-]{35}"));
32
33/// GitHub App installation token pattern (recommended by GitHub):
34/// `ghs_[A-Za-z0-9\.\-_]{36,}` matches both legacy opaque tokens (~40 chars)
35/// and stateless JWT-format tokens (~520 chars, two dots).
36static GITHUB_APP_TOKEN_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"ghs_[A-Za-z0-9.\-_]{36,}"));
37
38/// Remaining GitHub token family: personal (`ghp_`), OAuth (`gho_`),
39/// user-to-server (`ghu_`), and refresh (`ghr_`) tokens share the classic
40/// 36+ char suffix shape; fine-grained PATs use the distinctive
41/// `github_pat_` prefix with a 22+ char suffix. Same opaque-string
42/// treatment as `ghs_`: redact on prefix alone, without length oracles.
43static GITHUB_TOKEN_REGEX: LazyLock<Regex> =
44    LazyLock::new(|| compile_regex(r"(?:gh[pour]_[A-Za-z0-9.\-_]{36,}|github_pat_[A-Za-z0-9.\-_]{22,})"));
45
46/// Bearer token pattern: "Bearer " followed by token characters
47static BEARER_TOKEN_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"(?i)\bBearer\s+[A-Za-z0-9.\-_]{16,}\b"));
48
49/// Generic secret assignment pattern: key=value or key: value format
50/// Matches common secret key names like api_key, token, secret, password
51static SECRET_ASSIGNMENT_REGEX: LazyLock<Regex> = LazyLock::new(|| {
52    compile_regex(
53        r#"(?i)\b((?:[a-z0-9][a-z0-9_-]*?)?(?:api[\-_]?key|access[\-_]?key|client[\-_]?secret|credential|private[\-_]?key|token|secret|password|auth)[a-z0-9_-]*)\b(\s*[:=]\s*)(["']?)[^\s"']{8,}"#,
54    )
55});
56
57/// Maximum serialized size of a provider diagnostic after redaction.
58pub const PROVIDER_DIAGNOSTIC_MAX_BYTES: usize = 8 * 1024;
59const PROVIDER_DIAGNOSTIC_TRUNCATION_MARKER: &str = "… [diagnostic truncated]";
60
61/// Replacement marker for control characters in terminal-bound text.
62const TERMINAL_CONTROL_REPLACEMENT: char = '\u{FFFD}';
63
64/// Bidi controls that reorder terminal output while occupying no visible space.
65///
66/// A crafted override (U+202E) in a displayed URI or domain can visually spoof a
67/// trusted value, so these are neutralized like control characters. Joiners and
68/// other format characters stay intact: legitimate names may contain emoji.
69fn is_bidi_control(character: char) -> bool {
70    matches!(
71        character,
72        '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
73    )
74}
75
76fn is_neutralized_terminal_char(character: char) -> bool {
77    character.is_control() || is_bidi_control(character)
78}
79
80/// Neutralize control and bidi-reordering characters and bound length for terminal display.
81///
82/// Server-originated strings (resource URIs, domains, names) must pass through
83/// here before reaching terminal output: raw newlines split rows, BEL/CR/ESC
84/// enable terminal mangling, bidi controls visually reorder text, and unbounded
85/// values blow up layouts. Shell metacharacters (`$`, backticks) are inert in
86/// terminal output and preserved.
87pub fn sanitize_terminal_text(input: &str, max_chars: usize) -> String {
88    if input.chars().all(|character| !is_neutralized_terminal_char(character)) {
89        return crate::formatting::truncate_text(input, max_chars, "…");
90    }
91    let neutralized: String = input
92        .chars()
93        .map(|character| {
94            if is_neutralized_terminal_char(character) {
95                TERMINAL_CONTROL_REPLACEMENT
96            } else {
97                character
98            }
99        })
100        .collect();
101    crate::formatting::truncate_text(&neutralized, max_chars, "…")
102}
103
104/// Join disclosed entries with per-item sanitizing and a count-capped tail.
105///
106/// Each item is neutralized via [`sanitize_terminal_text`] with `max_item_chars`;
107/// at most `max_items` are shown before the remainder folds into a count.
108pub fn join_sanitized_truncated(items: &[String], max_items: usize, max_item_chars: usize) -> String {
109    let sanitized: Vec<String> = items.iter().map(|item| sanitize_terminal_text(item, max_item_chars)).collect();
110    if sanitized.len() <= max_items {
111        return sanitized.join(", ");
112    }
113    let shown: Vec<&str> = sanitized.iter().take(max_items).map(String::as_str).collect();
114    format!("{} … +{} more", shown.join(", "), sanitized.len() - max_items)
115}
116
117/// Redact secrets and sensitive keys from a string.
118///
119/// This is a best-effort operation using well-known regex patterns.
120/// Redacted values are replaced with `[REDACTED_SECRET]`.
121///
122/// # Examples
123///
124/// ```
125/// use vtcode_commons::sanitizer::redact_secrets;
126///
127/// let input = format!("Found key: {}", concat!("sk-", "test1234567890abcdef"));
128/// let output = redact_secrets(input);
129/// assert_eq!(output, "Found key: [REDACTED_SECRET]");
130/// ```
131pub fn redact_secrets(input: String) -> String {
132    let r1 = OPENAI_KEY_REGEX.replace_all(&input, "[REDACTED_SECRET]");
133    let r2 = AWS_ACCESS_KEY_ID_REGEX.replace_all(&r1, "[REDACTED_SECRET]");
134    let r2 = GOOGLE_API_KEY_REGEX.replace_all(&r2, "[REDACTED_SECRET]");
135    let r3 = GITHUB_APP_TOKEN_REGEX.replace_all(&r2, "[REDACTED_SECRET]");
136    let r4 = GITHUB_TOKEN_REGEX.replace_all(&r3, "[REDACTED_SECRET]");
137    let r5 = BEARER_TOKEN_REGEX.replace_all(&r4, "Bearer [REDACTED_SECRET]");
138    let r6 = SECRET_ASSIGNMENT_REGEX.replace_all(&r5, "$1$2$3[REDACTED_SECRET]");
139    // `into_owned` clones only when the final result is `Borrowed` (no regex
140    // matched at all); when any redaction occurred it moves the owned string
141    // without an extra allocation. Do NOT short-circuit on `Cow::Borrowed` —
142    // the final Cow is `Borrowed` whenever the *last* regex doesn't match,
143    // even if earlier regexes did, which would silently discard redactions.
144    r6.into_owned()
145}
146
147/// Redact secrets and return a bounded, UTF-8-safe provider diagnostic.
148///
149/// The input is sampled with a carry window so a secret beginning near the
150/// output boundary is still redacted before the final size limit is applied.
151pub fn sanitize_provider_diagnostic(input: impl AsRef<[u8]>) -> String {
152    let input = input.as_ref();
153    let sample_len = input.len().min(PROVIDER_DIAGNOSTIC_MAX_BYTES + STREAMING_REDACTION_CARRY_BYTES);
154    let sample = String::from_utf8_lossy(input.get(..sample_len).unwrap_or(input));
155    let redacted = redact_secrets(sample.into_owned());
156    if redacted.len() <= PROVIDER_DIAGNOSTIC_MAX_BYTES {
157        return redacted;
158    }
159
160    let content_limit = PROVIDER_DIAGNOSTIC_MAX_BYTES.saturating_sub(PROVIDER_DIAGNOSTIC_TRUNCATION_MARKER.len());
161    let end = redacted.floor_char_boundary(content_limit);
162    format!("{}{}", redacted.get(..end).unwrap_or(&redacted), PROVIDER_DIAGNOSTIC_TRUNCATION_MARKER)
163}
164
165/// Incrementally redact streamed output without retaining the full stream.
166///
167/// A bounded suffix is held between chunks so a secret split at an IO
168/// boundary is still matched by the same redaction rules as a complete line.
169#[derive(Debug, Default)]
170pub struct StreamingSecretRedactor {
171    pending: String,
172}
173
174const STREAMING_REDACTION_CARRY_BYTES: usize = 1_024;
175
176impl StreamingSecretRedactor {
177    /// Redact and return the safe prefix of `chunk`. The returned string may
178    /// be empty while the bounded carry window is being filled.
179    pub fn push(&mut self, chunk: &str) -> String {
180        self.pending.push_str(chunk);
181        if self.pending.len() <= STREAMING_REDACTION_CARRY_BYTES {
182            if !self.pending.contains('\n') {
183                return String::new();
184            }
185        }
186
187        let carry_split = self.pending.len().saturating_sub(STREAMING_REDACTION_CARRY_BYTES);
188        let line_split = self.pending.rfind('\n').map(|index| index + 1).unwrap_or(0);
189        let split_at = self.pending.floor_char_boundary(carry_split.max(line_split));
190        let prefix: String = self.pending.drain(..split_at).collect();
191        redact_secrets(prefix)
192    }
193
194    /// Redact and return the final carried suffix.
195    pub fn finish(self) -> String {
196        redact_secrets(self.pending)
197    }
198}
199
200#[allow(
201    clippy::panic,
202    reason = "Intentional compatibility, platform, or test-only suppression."
203)]
204fn compile_regex(pattern: &str) -> Regex {
205    match Regex::new(pattern) {
206        Ok(regex) => regex,
207        // Panic is acceptable thanks to the `load_regex` test
208        Err(err) => panic!("invalid regex pattern `{pattern}`: {err}"),
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn load_regex() {
218        // Verify all regex patterns compile without panicking
219        let _ = redact_secrets("test".to_string());
220    }
221
222    #[test]
223    fn redacts_openai_key() {
224        let input = format!("Found key: {}", concat!("sk-", "test1234567890abcdef"));
225        let output = redact_secrets(input);
226        assert_eq!(output, "Found key: [REDACTED_SECRET]");
227    }
228
229    #[test]
230    fn redacts_aws_access_key() {
231        // Assemble the documentation fixture at runtime so repository scans do not
232        // mistake it for a live credential.
233        let aws_key = concat!("AKIA", "IOSFODNN7EXAMPLE");
234        let input = format!(" creds: {aws_key} ");
235        let output = redact_secrets(input);
236        assert_eq!(output, " creds: [REDACTED_SECRET] ");
237    }
238
239    #[test]
240    fn redacts_google_api_key_but_not_short_lookalikes() {
241        // Runtime-assembled fixture: `AIza` + 35 URL-safe chars.
242        let key = concat!("AIza", "SyD3mo_k3y-0123456789abcdefghijklmn");
243        assert_eq!(key.len(), 39);
244        assert_eq!(redact_secrets(key.to_string()), "[REDACTED_SECRET]");
245        assert_eq!(redact_secrets(format!("key {key} end")), "key [REDACTED_SECRET] end");
246        // Shorter strings that merely start with the prefix stay intact.
247        let short = "AIzaShortValue";
248        assert_eq!(redact_secrets(short.to_string()), short);
249    }
250
251    #[test]
252    fn redacts_bearer_token() {
253        let input = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9".to_string();
254        let output = redact_secrets(input);
255        assert_eq!(output, "Authorization: Bearer [REDACTED_SECRET]");
256    }
257
258    #[test]
259    fn redacts_github_app_installation_tokens() {
260        // Legacy opaque format (~40 chars, no dots) and stateless JWT format
261        // (~520 chars, two dots) per May/Oct 2026 changelogs. Both must be
262        // treated as opaque and redacted even without a Bearer prefix.
263        // Fixtures are assembled at runtime so scans do not flag them.
264        let legacy = format!("ghs_{}", "a".repeat(36));
265        let header = format!("ghs_{}", "b".repeat(20));
266        let payload = format!("{}.", "c".repeat(250));
267        let signature = "d".repeat(250);
268        let stateless = format!("{header}.{payload}{signature}");
269        assert!(stateless.len() >= 500, "fixture should model ~520-char token");
270        assert_eq!(stateless.matches('.').count(), 2);
271
272        for token in [&legacy, &stateless] {
273            let bare = redact_secrets(format!("saw token {token} in logs"));
274            assert_eq!(bare, "saw token [REDACTED_SECRET] in logs");
275            assert!(!bare.contains(token.as_str()));
276
277            let bearer = redact_secrets(format!("Authorization: Bearer {token}"));
278            assert!(!bearer.contains(token.as_str()));
279        }
280    }
281
282    #[test]
283    fn github_app_token_threshold_is_36_chars() {
284        // Locks the GitHub-recommended `ghs_[A-Za-z0-9.\-_]{36,}` boundary:
285        // 35 chars must not redact on its own, 36 chars must.
286        let short = format!("ghs_{}", "a".repeat(35));
287        let exact = format!("ghs_{}", "a".repeat(36));
288        assert_eq!(redact_secrets(format!("saw {short} here")), format!("saw {short} here"));
289        assert_eq!(redact_secrets(format!("saw {exact} here")), "saw [REDACTED_SECRET] here");
290    }
291
292    #[test]
293    fn redacts_github_token_family_besides_app_tokens() {
294        // Fixtures are assembled at runtime so scans do not flag them.
295        for prefix in ["ghp_", "gho_", "ghu_", "ghr_"] {
296            let token = format!("{prefix}{}", "e".repeat(36));
297            let output = redact_secrets(format!("pasted {token} in chat"));
298            assert_eq!(output, "pasted [REDACTED_SECRET] in chat", "{prefix}");
299            assert!(!output.contains(token.as_str()));
300        }
301        let fine_grained = format!("github_pat_{}", "f".repeat(22));
302        let output = redact_secrets(format!("pasted {fine_grained} in chat"));
303        assert_eq!(output, "pasted [REDACTED_SECRET] in chat");
304        assert!(!output.contains(fine_grained.as_str()));
305    }
306
307    #[test]
308    fn github_token_family_thresholds_match_app_token_policy() {
309        // `gh?_` prefixes need a 36+ char suffix, `github_pat_` needs 22+;
310        // shorter lookalikes (docs, placeholders) must survive.
311        let short_classic = format!("ghp_{}", "a".repeat(35));
312        let exact_classic = format!("ghp_{}", "a".repeat(36));
313        assert_eq!(redact_secrets(format!("saw {short_classic} here")), format!("saw {short_classic} here"));
314        assert_eq!(redact_secrets(format!("saw {exact_classic} here")), "saw [REDACTED_SECRET] here");
315        let short_pat = format!("github_pat_{}", "a".repeat(21));
316        let exact_pat = format!("github_pat_{}", "a".repeat(22));
317        assert_eq!(redact_secrets(format!("saw {short_pat} here")), format!("saw {short_pat} here"));
318        assert_eq!(redact_secrets(format!("saw {exact_pat} here")), "saw [REDACTED_SECRET] here");
319    }
320
321    #[test]
322    fn redacts_github_app_token_split_across_stream_chunks() {
323        // A ~526-char stateless token fits in the 1_024-byte carry window, so
324        // halves split at an IO boundary must still redact on finish.
325        let token = format!("ghs_{}.{}.{}", "b".repeat(20), "c".repeat(250), "d".repeat(250));
326        let mid = token.floor_char_boundary(token.len() / 2);
327        let (first, second) = token.split_at(mid);
328        let mut redactor = StreamingSecretRedactor::default();
329        let mut output = redactor.push(first);
330        output.push_str(&redactor.push(&format!("{second}\n")));
331        output.push_str(&redactor.finish());
332        assert!(!output.contains(token.as_str()));
333        assert!(output.contains("[REDACTED_SECRET]"));
334    }
335
336    #[test]
337    fn redacts_api_key_assignment() {
338        let input = "api_key=sk-test12345678".to_string();
339        let output = redact_secrets(input);
340        assert_eq!(output, "api_key=[REDACTED_SECRET]");
341    }
342
343    #[test]
344    fn redacts_password_assignment() {
345        let input = "password: mysecretvalue".to_string();
346        let output = redact_secrets(input);
347        assert_eq!(output, "password: [REDACTED_SECRET]");
348    }
349
350    #[test]
351    fn redacts_token_in_quotes() {
352        let input = r#"token="abc123xyz789abcdef""#.to_string();
353        let output = redact_secrets(input);
354        assert_eq!(output, r#"token="[REDACTED_SECRET]""#);
355    }
356
357    #[test]
358    fn preserves_short_values() {
359        // Values under 8 characters should not be redacted
360        let input = "password: short".to_string();
361        let output = redact_secrets(input);
362        assert_eq!(output, "password: short");
363    }
364
365    #[test]
366    fn redacts_multiple_secrets() {
367        let openai_key = concat!("sk-", "test1234567890abcdef");
368        let aws_key = concat!("AKIA", "IOSFODNN7EXAMPLE");
369        let input = format!("Keys: {openai_key} and {aws_key}");
370        let output = redact_secrets(input);
371        // Verify both secrets are redacted
372        assert!(output.contains("[REDACTED_SECRET]"));
373        assert!(!output.contains(openai_key));
374        assert!(!output.contains(aws_key));
375    }
376
377    #[test]
378    fn preserves_non_secret_text() {
379        let input = "Hello world, this is normal text".to_string();
380        let output = redact_secrets(input);
381        assert_eq!(output, "Hello world, this is normal text");
382    }
383
384    #[test]
385    fn redacts_secrets_split_across_stream_chunks() {
386        let mut redactor = StreamingSecretRedactor::default();
387        let mut output = redactor.push("password=superse");
388        output.push_str(&redactor.push("cretvalue\n"));
389        output.push_str(&redactor.finish());
390
391        assert_eq!(output, "password=[REDACTED_SECRET]\n");
392        assert!(!output.contains("supersecretvalue"));
393    }
394
395    #[test]
396    fn terminal_text_neutralizes_controls_and_bounds_length() {
397        assert_eq!(sanitize_terminal_text("", 8), "");
398        assert_eq!(sanitize_terminal_text("abc", 8), "abc");
399        assert_eq!(sanitize_terminal_text("abcdefgh", 8), "abcdefgh");
400        assert_eq!(sanitize_terminal_text("abcdefghi", 8), "abcdefgh…");
401        assert_eq!(sanitize_terminal_text("ab", 0), "…");
402    }
403
404    #[test]
405    fn terminal_text_replaces_controls_but_preserves_shell_metachars() {
406        assert_eq!(sanitize_terminal_text("a\nb\rc\td\0e\x07f\x1bg", 64), "a�b�c�d�e�f�g");
407        assert_eq!(sanitize_terminal_text("price is $5 `code` ~user", 64), "price is $5 `code` ~user");
408        assert_eq!(sanitize_terminal_text("ui://x/\u{7f}app", 64), "ui://x/�app");
409    }
410
411    #[test]
412    fn terminal_text_truncates_on_char_boundaries() {
413        assert_eq!(sanitize_terminal_text("日本語テスト", 4), "日本語テ…");
414        assert_eq!(sanitize_terminal_text("日本語", 4), "日本語");
415    }
416
417    #[test]
418    fn terminal_text_neutralizes_bidi_controls_but_preserves_joiners() {
419        assert_eq!(sanitize_terminal_text("ui://\u{202e}evil/app", 64), "ui://�evil/app");
420        assert_eq!(sanitize_terminal_text("a\u{2066}b\u{2069}c", 64), "a�b�c");
421        assert_eq!(sanitize_terminal_text("x\u{200e}y\u{200f}z", 64), "x�y�z");
422        // Arabic Letter Mark is an invisible directional mark too.
423        assert_eq!(sanitize_terminal_text("a\u{061c}b", 64), "a�b");
424        // Zero-width joiners keep emoji sequences intact.
425        assert_eq!(sanitize_terminal_text("fam 👨\u{200d}👩\u{200d}👧 ok", 64), "fam 👨\u{200d}👩\u{200d}👧 ok");
426    }
427
428    #[test]
429    fn join_sanitized_truncated_folds_only_past_max() {
430        let items: Vec<String> = (0..8).map(|n| format!("d{n}")).collect();
431        assert_eq!(join_sanitized_truncated(&items, 8, usize::MAX), "d0, d1, d2, d3, d4, d5, d6, d7");
432        let items: Vec<String> = (0..9).map(|n| format!("d{n}")).collect();
433        assert_eq!(join_sanitized_truncated(&items, 8, usize::MAX), "d0, d1, d2, d3, d4, d5, d6, d7 … +1 more");
434        let items: Vec<String> = (0..11).map(|n| format!("d{n}")).collect();
435        assert_eq!(join_sanitized_truncated(&items, 8, usize::MAX), "d0, d1, d2, d3, d4, d5, d6, d7 … +3 more");
436        // Per-item caps apply before joining; controls in any item are neutralized.
437        let items = vec!["abcdefghij".to_string(), "x\ny".to_string()];
438        assert_eq!(join_sanitized_truncated(&items, 8, 4), "abcd…, x�y");
439        assert!(join_sanitized_truncated(&[], 8, usize::MAX).is_empty());
440    }
441
442    #[test]
443    fn provider_diagnostic_is_bounded_utf8_safe_and_redacted() {
444        let mut input = b"api_key=diagnostic-secret-value Bearer abcdefghijklmnop ".to_vec();
445        input.extend(std::iter::repeat_n(b'x', 20_000));
446        input.extend_from_slice("終端".as_bytes());
447        input.push(0xff);
448
449        let output = sanitize_provider_diagnostic(input);
450
451        assert!(output.len() <= PROVIDER_DIAGNOSTIC_MAX_BYTES);
452        assert!(output.is_char_boundary(output.len()));
453        assert!(!output.contains("diagnostic-secret-value"));
454        assert!(!output.contains("abcdefghijklmnop"));
455    }
456}