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