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 serde_json::Value;
23use std::sync::LazyLock;
24
25/// OpenAI API key pattern: sk- followed by alphanumeric characters
26static OPENAI_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"sk-[A-Za-z0-9_-]{16,}"));
27
28/// AWS Access Key ID pattern: AKIA followed by 16 alphanumeric characters
29static AWS_ACCESS_KEY_ID_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"\bAKIA[0-9A-Z]{16}\b"));
30
31/// Google API key pattern (Gemini, Maps, Firebase): `AIza` + 35 URL-safe chars.
32static GOOGLE_API_KEY_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"\bAIza[0-9A-Za-z_-]{35}"));
33
34/// GitHub App installation token pattern (recommended by GitHub):
35/// `ghs_[A-Za-z0-9\.\-_]{36,}` matches both legacy opaque tokens (~40 chars)
36/// and stateless JWT-format tokens (~520 chars, two dots).
37static GITHUB_APP_TOKEN_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"ghs_[A-Za-z0-9.\-_]{36,}"));
38
39/// Remaining GitHub token family: personal (`ghp_`), OAuth (`gho_`),
40/// user-to-server (`ghu_`), and refresh (`ghr_`) tokens share the classic
41/// 36+ char suffix shape; fine-grained PATs use the distinctive
42/// `github_pat_` prefix with a 22+ char suffix. Same opaque-string
43/// treatment as `ghs_`: redact on prefix alone, without length oracles.
44static GITHUB_TOKEN_REGEX: LazyLock<Regex> =
45    LazyLock::new(|| compile_regex(r"(?:gh[pour]_[A-Za-z0-9.\-_]{36,}|github_pat_[A-Za-z0-9.\-_]{22,})"));
46
47/// Bearer token pattern: "Bearer " followed by token characters
48static BEARER_TOKEN_REGEX: LazyLock<Regex> = LazyLock::new(|| compile_regex(r"(?i)\bBearer\s+[A-Za-z0-9.\-_]{16,}\b"));
49
50/// Generic secret assignment pattern: key=value or key: value format
51/// Matches common secret key names like api_key, token, secret, password.
52/// Group 4 captures the value so [`redact_secrets`] can spare code-shaped
53/// values (see [`is_code_expression_value`]); quoted values always redact.
54static SECRET_ASSIGNMENT_REGEX: LazyLock<Regex> = LazyLock::new(|| {
55    compile_regex(
56        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,})"#,
57    )
58});
59
60/// Strip one `Ident` (`[A-Za-z_][A-Za-z0-9_]*`) prefix, returning the rest.
61fn strip_ident_prefix(rest: &str) -> Option<&str> {
62    let first = rest.chars().next()?;
63    if !(first == '_' || first.is_ascii_alphabetic()) {
64        return None;
65    }
66    rest.strip_prefix(first)
67        .map(|tail| tail.trim_start_matches(|c: char| c == '_' || c.is_ascii_alphanumeric()))
68}
69
70/// Skip one balanced `<...>` group (turbofish / generic args), returning the
71/// rest. Returns `None` when the angles never balance (unbalanced input fails
72/// closed). Depth counting handles nesting (`Vec<HashMap<String, u8>>`).
73fn strip_balanced_angles(rest: &str) -> Option<&str> {
74    let mut depth = 0u32;
75    for (byte_index, c) in rest.char_indices() {
76        match c {
77            '<' => depth += 1,
78            '>' => {
79                depth = depth.checked_sub(1)?;
80                if depth == 0 {
81                    return rest.get(byte_index + 1..);
82                }
83            }
84            _ => {}
85        }
86    }
87    None
88}
89
90/// Strip one path segment — `Ident` plus optional balanced generic args
91/// (`Vec<u8>`, `f<T>`) — returning the rest.
92fn strip_path_segment(rest: &str) -> Option<&str> {
93    let rest = strip_ident_prefix(rest)?.trim_start();
94    if rest.starts_with('<') {
95        return strip_balanced_angles(rest).map(str::trim_start);
96    }
97    Some(rest)
98}
99
100/// Whether a dotted value positively validates as a JWT/JWE: the first
101/// dot-segment base64url-decodes (standard alphabet accepted too, fail
102/// closed) to a JSON object carrying an `alg` string, per RFC 7519/7516.
103/// Truncated prefixes (`eyJhbGciOi...`.`eyJzdWIiOi...`) validate the same
104/// way, so chunked secrets still redact. Anything undecodable, non-JSON,
105/// or missing `alg` is not a JWT.
106fn looks_like_jwt(value: &str) -> bool {
107    use base64::Engine as _;
108    let Some(first) = value.split('.').next().filter(|segment| !segment.is_empty()) else {
109        return false;
110    };
111    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
112        .decode(first)
113        .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(first));
114    let Ok(bytes) = bytes else {
115        return false;
116    };
117    let Ok(json) = serde_json::from_slice::<Value>(&bytes) else {
118        return false;
119    };
120    json.get("alg").and_then(Value::as_str).is_some()
121}
122
123/// Whether an unquoted assignment value is a code expression rather than an
124/// opaque credential: `[&*]* Segment ((:: | .) Segment | ::<Args> Segment?)*`
125/// (`!`? `(`/`[` | bare-path tail), where `Segment` is `Ident` plus optional
126/// balanced `<...>` generic args.
127///
128/// A trailing call/macro/index operation proves code outright. A bare
129/// multi-segment path (`config.auth_token,`, `Option::None`) with only
130/// struct/statement punctuation (one trailing `,`/`;`, then `?`* for the
131/// try-operator) also proves code — except dotted paths must positively fail
132/// JWT validation first, since bare JWTs share the `Ident(.Ident)*` shape.
133/// Single-segment values without a call (`mysecretvalue`, `hunter2?,`)
134/// always fail closed and still redact, as do quoted values.
135///
136/// Accepted recall trade-off: non-JWT dotted secrets (an unquoted dotted
137/// lowercase passphrase like `correct.horse.battery`) now pass through.
138/// Real dotted-secret formats keep their protection — JWT/JWE via the
139/// positive check above, GitHub stateless tokens and Bearer tokens via the
140/// earlier dedicated patterns — and quoted values always redact.
141fn is_code_expression_value(value: &str) -> bool {
142    let Some(mut rest) = strip_path_segment(value.trim_start_matches(['&', '*'])) else {
143        return false;
144    };
145    let mut had_join = false;
146    loop {
147        rest = rest.trim_start();
148        if let Some(after_scopes) = rest.strip_prefix("::").map(str::trim_start) {
149            // Optional turbofish: `::<Args>` carries generic args with no
150            // ident, and the segment after it is optional (`parse::<u32>()`).
151            let (after_scopes, had_turbofish) = if after_scopes.starts_with('<') {
152                match strip_balanced_angles(after_scopes).map(str::trim_start) {
153                    Some(after_args) => (after_args, true),
154                    None => return false,
155                }
156            } else {
157                (after_scopes, false)
158            };
159            match strip_path_segment(after_scopes) {
160                Some(after_segment) => rest = after_segment,
161                None if had_turbofish => rest = after_scopes,
162                None => return false,
163            }
164            had_join = true;
165        } else if let Some(after_dot) = rest.strip_prefix('.').map(str::trim_start) {
166            let Some(after_segment) = strip_path_segment(after_dot) else {
167                return false;
168            };
169            rest = after_segment;
170            had_join = true;
171        } else {
172            break;
173        }
174    }
175    let rest = rest.trim_start();
176    let after_bang = rest.strip_prefix('!').map(str::trim_start).unwrap_or(rest);
177    if after_bang.starts_with('(') || after_bang.starts_with('[') {
178        return true;
179    }
180    if !had_join {
181        return false;
182    }
183    // Bare path tail: tolerate struct/statement punctuation and try-operators,
184    // then require end of value. Anything else fails closed.
185    let bare = rest.strip_suffix([',', ';']).unwrap_or(rest).trim_end_matches('?');
186    if !bare.is_empty() {
187        return false;
188    }
189    // A `::` path cannot be a JWT; a dotted path must positively fail JWT
190    // validation (fail closed: truncated/chunked JWT prefixes still redact).
191    if !value.contains('.') {
192        return true;
193    }
194    !looks_like_jwt(value)
195}
196
197/// Maximum serialized size of a provider diagnostic after redaction.
198pub const PROVIDER_DIAGNOSTIC_MAX_BYTES: usize = 8 * 1024;
199const PROVIDER_DIAGNOSTIC_TRUNCATION_MARKER: &str = "… [diagnostic truncated]";
200
201/// Replacement marker for control characters in terminal-bound text.
202const TERMINAL_CONTROL_REPLACEMENT: char = '\u{FFFD}';
203
204/// Bidi controls that reorder terminal output while occupying no visible space.
205///
206/// A crafted override (U+202E) in a displayed URI or domain can visually spoof a
207/// trusted value, so these are neutralized like control characters. Joiners and
208/// other format characters stay intact: legitimate names may contain emoji.
209fn is_bidi_control(character: char) -> bool {
210    matches!(
211        character,
212        '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
213    )
214}
215
216fn is_neutralized_terminal_char(character: char) -> bool {
217    character.is_control() || is_bidi_control(character)
218}
219
220/// Neutralize control and bidi-reordering characters and bound length for terminal display.
221///
222/// Server-originated strings (resource URIs, domains, names) must pass through
223/// here before reaching terminal output: raw newlines split rows, BEL/CR/ESC
224/// enable terminal mangling, bidi controls visually reorder text, and unbounded
225/// values blow up layouts. Shell metacharacters (`$`, backticks) are inert in
226/// terminal output and preserved.
227pub fn sanitize_terminal_text(input: &str, max_chars: usize) -> String {
228    if input.chars().all(|character| !is_neutralized_terminal_char(character)) {
229        return crate::formatting::truncate_text(input, max_chars, "…");
230    }
231    let neutralized: String = input
232        .chars()
233        .map(|character| {
234            if is_neutralized_terminal_char(character) {
235                TERMINAL_CONTROL_REPLACEMENT
236            } else {
237                character
238            }
239        })
240        .collect();
241    crate::formatting::truncate_text(&neutralized, max_chars, "…")
242}
243
244/// Join disclosed entries with per-item sanitizing and a count-capped tail.
245///
246/// Each item is neutralized via [`sanitize_terminal_text`] with `max_item_chars`;
247/// at most `max_items` are shown before the remainder folds into a count.
248pub fn join_sanitized_truncated(items: &[String], max_items: usize, max_item_chars: usize) -> String {
249    let sanitized: Vec<String> = items.iter().map(|item| sanitize_terminal_text(item, max_item_chars)).collect();
250    if sanitized.len() <= max_items {
251        return sanitized.join(", ");
252    }
253    let shown: Vec<&str> = sanitized.iter().take(max_items).map(String::as_str).collect();
254    format!("{} … +{} more", shown.join(", "), sanitized.len() - max_items)
255}
256
257/// Redact secrets and sensitive keys from a string.
258///
259/// This is a best-effort operation using well-known regex patterns.
260/// Redacted values are replaced with `[REDACTED_SECRET]`.
261///
262/// # Examples
263///
264/// ```
265/// use vtcode_commons::sanitizer::redact_secrets;
266///
267/// let input = format!("Found key: {}", concat!("sk-", "test1234567890abcdef"));
268/// let output = redact_secrets(input);
269/// assert_eq!(output, "Found key: [REDACTED_SECRET]");
270/// ```
271pub fn redact_secrets(input: String) -> String {
272    let r1 = OPENAI_KEY_REGEX.replace_all(&input, "[REDACTED_SECRET]");
273    let r2 = AWS_ACCESS_KEY_ID_REGEX.replace_all(&r1, "[REDACTED_SECRET]");
274    let r2 = GOOGLE_API_KEY_REGEX.replace_all(&r2, "[REDACTED_SECRET]");
275    let r3 = GITHUB_APP_TOKEN_REGEX.replace_all(&r2, "[REDACTED_SECRET]");
276    let r4 = GITHUB_TOKEN_REGEX.replace_all(&r3, "[REDACTED_SECRET]");
277    let r5 = BEARER_TOKEN_REGEX.replace_all(&r4, "Bearer [REDACTED_SECRET]");
278    let r6 = SECRET_ASSIGNMENT_REGEX.replace_all(&r5, |caps: &regex::Captures| {
279        if !caps[3].is_empty() || !is_code_expression_value(&caps[4]) {
280            format!("{}{}{}[REDACTED_SECRET]", &caps[1], &caps[2], &caps[3])
281        } else {
282            caps[0].to_string()
283        }
284    });
285    // `into_owned` clones only when the final result is `Borrowed` (no regex
286    // matched at all); when any redaction occurred it moves the owned string
287    // without an extra allocation. Do NOT short-circuit on `Cow::Borrowed` —
288    // the final Cow is `Borrowed` whenever the *last* regex doesn't match,
289    // even if earlier regexes did, which would silently discard redactions.
290    r6.into_owned()
291}
292
293/// Redact secrets in every string of a JSON value, in place.
294///
295/// Recurses into arrays and objects; numbers, booleans, and nulls are left
296/// untouched. Use this before persisting or transmitting tool arguments,
297/// tool results, or other semi-structured payloads that may embed secrets.
298pub fn redact_json_value(value: &mut Value) {
299    match value {
300        Value::String(text) => {
301            let redacted = redact_secrets(std::mem::take(text));
302            *text = redacted;
303        }
304        Value::Array(values) => {
305            for value in values {
306                redact_json_value(value);
307            }
308        }
309        Value::Object(values) => {
310            for value in values.values_mut() {
311                redact_json_value(value);
312            }
313        }
314        Value::Null | Value::Bool(_) | Value::Number(_) => {}
315    }
316}
317
318/// Redact secrets and return a bounded, UTF-8-safe provider diagnostic.
319///
320/// The input is sampled with a carry window so a secret beginning near the
321/// output boundary is still redacted before the final size limit is applied.
322pub fn sanitize_provider_diagnostic(input: impl AsRef<[u8]>) -> String {
323    let input = input.as_ref();
324    let sample_len = input.len().min(PROVIDER_DIAGNOSTIC_MAX_BYTES + STREAMING_REDACTION_CARRY_BYTES);
325    let sample = String::from_utf8_lossy(input.get(..sample_len).unwrap_or(input));
326    let redacted = redact_secrets(sample.into_owned());
327    if redacted.len() <= PROVIDER_DIAGNOSTIC_MAX_BYTES {
328        return redacted;
329    }
330
331    let content_limit = PROVIDER_DIAGNOSTIC_MAX_BYTES.saturating_sub(PROVIDER_DIAGNOSTIC_TRUNCATION_MARKER.len());
332    let end = redacted.floor_char_boundary(content_limit);
333    format!("{}{}", redacted.get(..end).unwrap_or(&redacted), PROVIDER_DIAGNOSTIC_TRUNCATION_MARKER)
334}
335
336/// Incrementally redact streamed output without retaining the full stream.
337///
338/// A bounded suffix is held between chunks so a secret split at an IO
339/// boundary is still matched by the same redaction rules as a complete line.
340#[derive(Debug, Default)]
341pub struct StreamingSecretRedactor {
342    pending: String,
343}
344
345const STREAMING_REDACTION_CARRY_BYTES: usize = 1_024;
346
347impl StreamingSecretRedactor {
348    /// Redact and return the safe prefix of `chunk`. The returned string may
349    /// be empty while the bounded carry window is being filled.
350    pub fn push(&mut self, chunk: &str) -> String {
351        self.pending.push_str(chunk);
352        if self.pending.len() <= STREAMING_REDACTION_CARRY_BYTES {
353            if !self.pending.contains('\n') {
354                return String::new();
355            }
356        }
357
358        let carry_split = self.pending.len().saturating_sub(STREAMING_REDACTION_CARRY_BYTES);
359        let line_split = self.pending.rfind('\n').map(|index| index + 1).unwrap_or(0);
360        let split_at = self.pending.floor_char_boundary(carry_split.max(line_split));
361        let prefix: String = self.pending.drain(..split_at).collect();
362        redact_secrets(prefix)
363    }
364
365    /// Redact and return the final carried suffix.
366    pub fn finish(self) -> String {
367        redact_secrets(self.pending)
368    }
369}
370
371#[allow(
372    clippy::panic,
373    reason = "Intentional compatibility, platform, or test-only suppression."
374)]
375fn compile_regex(pattern: &str) -> Regex {
376    match Regex::new(pattern) {
377        Ok(regex) => regex,
378        // Panic is acceptable thanks to the `load_regex` test
379        Err(err) => panic!("invalid regex pattern `{pattern}`: {err}"),
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    #[test]
388    fn load_regex() {
389        // Verify all regex patterns compile without panicking
390        let _ = redact_secrets("test".to_string());
391    }
392
393    #[test]
394    fn redacts_openai_key() {
395        let input = format!("Found key: {}", concat!("sk-", "test1234567890abcdef"));
396        let output = redact_secrets(input);
397        assert_eq!(output, "Found key: [REDACTED_SECRET]");
398    }
399
400    #[test]
401    fn redacts_aws_access_key() {
402        // Assemble the documentation fixture at runtime so repository scans do not
403        // mistake it for a live credential.
404        let aws_key = concat!("AKIA", "IOSFODNN7EXAMPLE");
405        let input = format!(" creds: {aws_key} ");
406        let output = redact_secrets(input);
407        assert_eq!(output, " creds: [REDACTED_SECRET] ");
408    }
409
410    #[test]
411    fn redacts_google_api_key_but_not_short_lookalikes() {
412        // Runtime-assembled fixture: `AIza` + 35 URL-safe chars.
413        let key = concat!("AIza", "SyD3mo_k3y-0123456789abcdefghijklmn");
414        assert_eq!(key.len(), 39);
415        assert_eq!(redact_secrets(key.to_string()), "[REDACTED_SECRET]");
416        assert_eq!(redact_secrets(format!("key {key} end")), "key [REDACTED_SECRET] end");
417        // Shorter strings that merely start with the prefix stay intact.
418        let short = "AIzaShortValue";
419        assert_eq!(redact_secrets(short.to_string()), short);
420    }
421
422    #[test]
423    fn redacts_bearer_token() {
424        let input = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9".to_string();
425        let output = redact_secrets(input);
426        assert_eq!(output, "Authorization: Bearer [REDACTED_SECRET]");
427    }
428
429    #[test]
430    fn redacts_github_app_installation_tokens() {
431        // Legacy opaque format (~40 chars, no dots) and stateless JWT format
432        // (~520 chars, two dots) per May/Oct 2026 changelogs. Both must be
433        // treated as opaque and redacted even without a Bearer prefix.
434        // Fixtures are assembled at runtime so scans do not flag them.
435        let legacy = format!("ghs_{}", "a".repeat(36));
436        let header = format!("ghs_{}", "b".repeat(20));
437        let payload = format!("{}.", "c".repeat(250));
438        let signature = "d".repeat(250);
439        let stateless = format!("{header}.{payload}{signature}");
440        assert!(stateless.len() >= 500, "fixture should model ~520-char token");
441        assert_eq!(stateless.matches('.').count(), 2);
442
443        for token in [&legacy, &stateless] {
444            let bare = redact_secrets(format!("saw token {token} in logs"));
445            assert_eq!(bare, "saw token [REDACTED_SECRET] in logs");
446            assert!(!bare.contains(token.as_str()));
447
448            let bearer = redact_secrets(format!("Authorization: Bearer {token}"));
449            assert!(!bearer.contains(token.as_str()));
450        }
451    }
452
453    #[test]
454    fn github_app_token_threshold_is_36_chars() {
455        // Locks the GitHub-recommended `ghs_[A-Za-z0-9.\-_]{36,}` boundary:
456        // 35 chars must not redact on its own, 36 chars must.
457        let short = format!("ghs_{}", "a".repeat(35));
458        let exact = format!("ghs_{}", "a".repeat(36));
459        assert_eq!(redact_secrets(format!("saw {short} here")), format!("saw {short} here"));
460        assert_eq!(redact_secrets(format!("saw {exact} here")), "saw [REDACTED_SECRET] here");
461    }
462
463    #[test]
464    fn redacts_github_token_family_besides_app_tokens() {
465        // Fixtures are assembled at runtime so scans do not flag them.
466        for prefix in ["ghp_", "gho_", "ghu_", "ghr_"] {
467            let token = format!("{prefix}{}", "e".repeat(36));
468            let output = redact_secrets(format!("pasted {token} in chat"));
469            assert_eq!(output, "pasted [REDACTED_SECRET] in chat", "{prefix}");
470            assert!(!output.contains(token.as_str()));
471        }
472        let fine_grained = format!("github_pat_{}", "f".repeat(22));
473        let output = redact_secrets(format!("pasted {fine_grained} in chat"));
474        assert_eq!(output, "pasted [REDACTED_SECRET] in chat");
475        assert!(!output.contains(fine_grained.as_str()));
476    }
477
478    #[test]
479    fn github_token_family_thresholds_match_app_token_policy() {
480        // `gh?_` prefixes need a 36+ char suffix, `github_pat_` needs 22+;
481        // shorter lookalikes (docs, placeholders) must survive.
482        let short_classic = format!("ghp_{}", "a".repeat(35));
483        let exact_classic = format!("ghp_{}", "a".repeat(36));
484        assert_eq!(redact_secrets(format!("saw {short_classic} here")), format!("saw {short_classic} here"));
485        assert_eq!(redact_secrets(format!("saw {exact_classic} here")), "saw [REDACTED_SECRET] here");
486        let short_pat = format!("github_pat_{}", "a".repeat(21));
487        let exact_pat = format!("github_pat_{}", "a".repeat(22));
488        assert_eq!(redact_secrets(format!("saw {short_pat} here")), format!("saw {short_pat} here"));
489        assert_eq!(redact_secrets(format!("saw {exact_pat} here")), "saw [REDACTED_SECRET] here");
490    }
491
492    #[test]
493    fn redacts_github_app_token_split_across_stream_chunks() {
494        // A ~526-char stateless token fits in the 1_024-byte carry window, so
495        // halves split at an IO boundary must still redact on finish.
496        let token = format!("ghs_{}.{}.{}", "b".repeat(20), "c".repeat(250), "d".repeat(250));
497        let mid = token.floor_char_boundary(token.len() / 2);
498        let (first, second) = token.split_at(mid);
499        let mut redactor = StreamingSecretRedactor::default();
500        let mut output = redactor.push(first);
501        output.push_str(&redactor.push(&format!("{second}\n")));
502        output.push_str(&redactor.finish());
503        assert!(!output.contains(token.as_str()));
504        assert!(output.contains("[REDACTED_SECRET]"));
505    }
506
507    #[test]
508    fn redacts_api_key_assignment() {
509        let input = "api_key=sk-test12345678".to_string();
510        let output = redact_secrets(input);
511        assert_eq!(output, "api_key=[REDACTED_SECRET]");
512    }
513
514    #[test]
515    fn redacts_password_assignment() {
516        let input = "password: mysecretvalue".to_string();
517        let output = redact_secrets(input);
518        assert_eq!(output, "password: [REDACTED_SECRET]");
519    }
520
521    #[test]
522    fn redacts_token_in_quotes() {
523        let input = r#"token="abc123xyz789abcdef""#.to_string();
524        let output = redact_secrets(input);
525        assert_eq!(output, r#"token="[REDACTED_SECRET]""#);
526    }
527
528    #[test]
529    fn preserves_rust_option_constructor_values() {
530        // Session session-vtcode-20261202T131652Z_409402-22559: `token_budget:
531        // Some(1000)` was redacted, corrupting the agent's view of source and
532        // breaking apply_patch with redacted-context refusals.
533        for input in [
534            "token_budget: Some(1000),",
535            "token_budget: Option::from(1000),",
536            "let snapshot = GoalSnapshot { token_budget: Some(1000) };",
537        ] {
538            assert_eq!(redact_secrets(input.to_string()), input, "{input}");
539        }
540        // Asymmetric pair: an opaque value after the same key family still redacts.
541        assert_eq!(redact_secrets("token=abc123xyz789".to_string()), "token=[REDACTED_SECRET]");
542    }
543
544    #[test]
545    fn preserves_call_and_macro_shaped_values() {
546        for input in [
547            "secret: generate_key(),",
548            "auth: &authenticate(user),",
549            "token: self.refresh(),",
550            "secret: format!(",
551            "password: hash_password(pw)?,",
552        ] {
553            assert_eq!(redact_secrets(input.to_string()), input, "{input}");
554        }
555        // Asymmetric pair: a bare opaque value after the same keys still redacts.
556        assert_eq!(redact_secrets("secret: generatekeyvalue123".to_string()), "secret: [REDACTED_SECRET]");
557    }
558
559    #[test]
560    fn preserves_bracket_constructor_values() {
561        let input = "token: vec![1,2,3],";
562        assert_eq!(redact_secrets(input.to_string()), input);
563    }
564
565    #[test]
566    fn preserves_generic_and_turbofish_call_values() {
567        for input in [
568            "token: collect::<Vec<_>>(),",
569            "secret = resp.json::<Token>().await?,",
570            "auth: parse::<u32>(),",
571            "token: f::<Vec<HashMap<String,u8>>>(),",
572            "secret: Vec<u8>::new(),",
573        ] {
574            assert_eq!(redact_secrets(input.to_string()), input, "{input}");
575        }
576        // Asymmetric pair: unbalanced angles fail closed.
577        assert_eq!(redact_secrets("token: abc<def(ghi)".to_string()), "token: [REDACTED_SECRET]");
578    }
579
580    #[test]
581    fn preserves_bare_path_values() {
582        // Field and scope paths are code even without a trailing call; only
583        // values that positively validate as JWTs stay redacted (see below).
584        for input in [
585            "token: config.auth_token,",
586            "secret = self.vault.read_key;",
587            "auth: creds.store.load",
588            "token: Option::None,",
589            "secret: crate::auth::KEY,",
590            "token: resp.json?,",
591        ] {
592            assert_eq!(redact_secrets(input.to_string()), input, "{input}");
593        }
594        // Asymmetric pairs: single segments without a call still redact,
595        // even with trailing punctuation.
596        assert_eq!(redact_secrets("token: abcdefgh,".to_string()), "token: [REDACTED_SECRET]");
597        assert_eq!(redact_secrets("secret: hunter2?,".to_string()), "secret: [REDACTED_SECRET]");
598        // Accepted recall trade-off (see `is_code_expression_value`): a
599        // non-JWT dotted lowercase value passes through.
600        assert_eq!(redact_secrets("secret: correct.horse.battery".to_string()), "secret: correct.horse.battery");
601    }
602
603    #[test]
604    fn still_redacts_jwt_shaped_values() {
605        // Bare dotted paths preserve, so JWTs are fenced by positive
606        // validation instead of shape alone. The jwt.io example token (John
607        // Doe fixture, not a real credential) is assembled at runtime so
608        // repository scans do not flag it.
609        let jwt = concat!(
610            "eyJhbGciOiJIUzI1NiJ9",
611            ".",
612            "eyJzdWIiOiIxMjM0NTY3ODkwIn0",
613            ".",
614            "SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
615        );
616        assert_eq!(redact_secrets(format!("token: {jwt}")), "token: [REDACTED_SECRET]");
617    }
618
619    #[test]
620    fn still_redacts_jwe_and_truncated_jwt_prefixes() {
621        use base64::Engine as _;
622        let encode = |json: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
623        // JWE compact serialization: 5 segments, JSON header with `alg`.
624        let jwe = format!("{}.e30.e30.e30.e30", encode(r#"{"alg":"RSA-OAEP","enc":"A256GCM"}"#));
625        assert_eq!(redact_secrets(format!("token: {jwe}")), "token: [REDACTED_SECRET]");
626        // `alg:none` and truncated two-segment prefixes validate the same
627        // way, so streaming chunks of a secret still redact.
628        for header in [r#"{"alg":"none"}"#, r#"{"alg":"HS256","typ":"JWT"}"#] {
629            let prefix = format!("{}.e30", encode(header));
630            assert_eq!(redact_secrets(format!("token: {prefix}")), "token: [REDACTED_SECRET]");
631        }
632    }
633
634    #[test]
635    fn jwt_validation_requires_decodable_json_with_string_alg() {
636        // Not base64url / not JSON / no `alg` / non-string `alg`: not a JWT.
637        for value in ["config.auth_token", "e30.e30", "####.x", "a", ""] {
638            assert!(!looks_like_jwt(value), "{value}");
639        }
640        use base64::Engine as _;
641        let encode = |json: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
642        assert!(!looks_like_jwt(&format!("{}.e30", encode(r#"{"alg":1}"#))));
643        // Positive controls: HS256, none, and JWE headers validate.
644        for header in [
645            r#"{"alg":"HS256"}"#,
646            r#"{"alg":"none"}"#,
647            r#"{"alg":"ECDH-ES","enc":"A128CBC"}"#,
648        ] {
649            assert!(looks_like_jwt(&format!("{}.e30.e30", encode(header))), "{header}");
650        }
651    }
652
653    #[test]
654    fn still_redacts_paren_values_without_call_shape() {
655        // Fail closed: parens alone do not prove code. Only `Ident(::Ident)*`
656        // (`.Ident`)* `!`? `(`/`[` values are excluded.
657        assert_eq!(redact_secrets("password: p@ss(w0rd)!".to_string()), "password: [REDACTED_SECRET]");
658        assert_eq!(redact_secrets("password: (hidden-value)".to_string()), "password: [REDACTED_SECRET]");
659        // Quoted values stay opaque: a call lookalike in quotes still redacts.
660        assert_eq!(redact_secrets(r#"token="Some(1000)opaque""#.to_string()), r#"token="[REDACTED_SECRET]""#);
661    }
662
663    #[test]
664    fn bare_value_length_boundary_is_eight_chars() {
665        // Pins the `{8,}` quantifier on the group-4 capture path.
666        assert_eq!(redact_secrets("token: abcdefgh".to_string()), "token: [REDACTED_SECRET]");
667        assert_eq!(redact_secrets("token: abcdefg".to_string()), "token: abcdefg");
668    }
669
670    #[test]
671    fn code_expression_value_shapes() {
672        for value in [
673            "Some(1000),",
674            "Option::from(1),",
675            "a::b::c(",
676            "a.b(",
677            "&f(",
678            "*f[",
679            "f!(",
680            "f ! (",
681            "f<T>(x),",
682            "a::<T>()",
683            "Vec<u8>::new()",
684            "a::<Vec<HashMap<String,u8>>>(),",
685            "config.auth_token,",
686            "a.b.c;",
687            "a::B::C",
688            "xxx.yyy.zzz",
689        ] {
690            assert!(is_code_expression_value(value), "{value}");
691        }
692        for value in [
693            "",
694            "(",
695            "12345678",
696            "mysecretvalue",
697            "p@ss(w0rd)!",
698            "(hidden)",
699            "a.2(",
700            "mut f(",
701            "a::<T(x",
702            "a<T",
703            "a::",
704            "singleident,",
705            "hunter2?,",
706        ] {
707            assert!(!is_code_expression_value(value), "{value}");
708        }
709    }
710
711    #[test]
712    fn preserves_short_values() {
713        // Values under 8 characters should not be redacted
714        let input = "password: short".to_string();
715        let output = redact_secrets(input);
716        assert_eq!(output, "password: short");
717    }
718
719    #[test]
720    fn redacts_multiple_secrets() {
721        let openai_key = concat!("sk-", "test1234567890abcdef");
722        let aws_key = concat!("AKIA", "IOSFODNN7EXAMPLE");
723        let input = format!("Keys: {openai_key} and {aws_key}");
724        let output = redact_secrets(input);
725        // Verify both secrets are redacted
726        assert!(output.contains("[REDACTED_SECRET]"));
727        assert!(!output.contains(openai_key));
728        assert!(!output.contains(aws_key));
729    }
730
731    #[test]
732    fn preserves_non_secret_text() {
733        let input = "Hello world, this is normal text".to_string();
734        let output = redact_secrets(input);
735        assert_eq!(output, "Hello world, this is normal text");
736    }
737
738    #[test]
739    fn redacts_secrets_split_across_stream_chunks() {
740        let mut redactor = StreamingSecretRedactor::default();
741        let mut output = redactor.push("password=superse");
742        output.push_str(&redactor.push("cretvalue\n"));
743        output.push_str(&redactor.finish());
744
745        assert_eq!(output, "password=[REDACTED_SECRET]\n");
746        assert!(!output.contains("supersecretvalue"));
747    }
748
749    #[test]
750    fn terminal_text_neutralizes_controls_and_bounds_length() {
751        assert_eq!(sanitize_terminal_text("", 8), "");
752        assert_eq!(sanitize_terminal_text("abc", 8), "abc");
753        assert_eq!(sanitize_terminal_text("abcdefgh", 8), "abcdefgh");
754        assert_eq!(sanitize_terminal_text("abcdefghi", 8), "abcdefgh…");
755        assert_eq!(sanitize_terminal_text("ab", 0), "…");
756    }
757
758    #[test]
759    fn terminal_text_replaces_controls_but_preserves_shell_metachars() {
760        assert_eq!(sanitize_terminal_text("a\nb\rc\td\0e\x07f\x1bg", 64), "a�b�c�d�e�f�g");
761        assert_eq!(sanitize_terminal_text("price is $5 `code` ~user", 64), "price is $5 `code` ~user");
762        assert_eq!(sanitize_terminal_text("ui://x/\u{7f}app", 64), "ui://x/�app");
763    }
764
765    #[test]
766    fn terminal_text_truncates_on_char_boundaries() {
767        assert_eq!(sanitize_terminal_text("日本語テスト", 4), "日本語テ…");
768        assert_eq!(sanitize_terminal_text("日本語", 4), "日本語");
769    }
770
771    #[test]
772    fn terminal_text_neutralizes_bidi_controls_but_preserves_joiners() {
773        assert_eq!(sanitize_terminal_text("ui://\u{202e}evil/app", 64), "ui://�evil/app");
774        assert_eq!(sanitize_terminal_text("a\u{2066}b\u{2069}c", 64), "a�b�c");
775        assert_eq!(sanitize_terminal_text("x\u{200e}y\u{200f}z", 64), "x�y�z");
776        // Arabic Letter Mark is an invisible directional mark too.
777        assert_eq!(sanitize_terminal_text("a\u{061c}b", 64), "a�b");
778        // Zero-width joiners keep emoji sequences intact.
779        assert_eq!(sanitize_terminal_text("fam 👨\u{200d}👩\u{200d}👧 ok", 64), "fam 👨\u{200d}👩\u{200d}👧 ok");
780    }
781
782    #[test]
783    fn join_sanitized_truncated_folds_only_past_max() {
784        let items: Vec<String> = (0..8).map(|n| format!("d{n}")).collect();
785        assert_eq!(join_sanitized_truncated(&items, 8, usize::MAX), "d0, d1, d2, d3, d4, d5, d6, d7");
786        let items: Vec<String> = (0..9).map(|n| format!("d{n}")).collect();
787        assert_eq!(join_sanitized_truncated(&items, 8, usize::MAX), "d0, d1, d2, d3, d4, d5, d6, d7 … +1 more");
788        let items: Vec<String> = (0..11).map(|n| format!("d{n}")).collect();
789        assert_eq!(join_sanitized_truncated(&items, 8, usize::MAX), "d0, d1, d2, d3, d4, d5, d6, d7 … +3 more");
790        // Per-item caps apply before joining; controls in any item are neutralized.
791        let items = vec!["abcdefghij".to_string(), "x\ny".to_string()];
792        assert_eq!(join_sanitized_truncated(&items, 8, 4), "abcd…, x�y");
793        assert!(join_sanitized_truncated(&[], 8, usize::MAX).is_empty());
794    }
795
796    #[test]
797    fn provider_diagnostic_is_bounded_utf8_safe_and_redacted() {
798        let mut input = b"api_key=diagnostic-secret-value Bearer abcdefghijklmnop ".to_vec();
799        input.extend(std::iter::repeat_n(b'x', 20_000));
800        input.extend_from_slice("終端".as_bytes());
801        input.push(0xff);
802
803        let output = sanitize_provider_diagnostic(input);
804
805        assert!(output.len() <= PROVIDER_DIAGNOSTIC_MAX_BYTES);
806        assert!(output.is_char_boundary(output.len()));
807        assert!(!output.contains("diagnostic-secret-value"));
808        assert!(!output.contains("abcdefghijklmnop"));
809    }
810
811    #[test]
812    fn redact_json_value_scrubs_nested_strings_and_preserves_shape() {
813        let secret = format!("{}-{}", "sk-test1234567890abcdef", "payload");
814        let mut value = serde_json::json!({
815            "output": format!("result with {secret} inside"),
816            "nested": { "args": [format!("token={secret}"), "clean"] },
817            "count": 42,
818            "ok": true,
819            "nothing": null,
820        });
821
822        redact_json_value(&mut value);
823
824        let serialized = value.to_string();
825        assert!(!serialized.contains(&secret), "secret must not survive: {serialized}");
826        assert!(serialized.contains("[REDACTED_SECRET]"), "{serialized}");
827        assert_eq!(value["count"], 42);
828        assert_eq!(value["ok"], true);
829        assert!(value["nothing"].is_null());
830        assert_eq!(value["nested"]["args"][1], "clean");
831    }
832
833    #[test]
834    fn redact_json_value_leaves_clean_payloads_untouched() {
835        let mut value = serde_json::json!({"output": "plain text", "items": ["a", "b"]});
836        let before = value.clone();
837        redact_json_value(&mut value);
838        assert_eq!(value, before);
839    }
840}