arbiter-credential 0.0.53

Credential resolution and injection middleware for the Arbiter proxy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! Credential injection middleware.
//!
//! Scans outgoing HTTP request bodies and headers for credential reference
//! patterns (`${CRED:ref_name}`) and substitutes them with resolved secret
//! values. Also scans response bodies to ensure credentials never leak back
//! to the agent.
//!
//! This module provides standalone async functions. Wiring into the full proxy
//! pipeline is done in the main binary crate.

use regex::Regex;
use secrecy::{ExposeSecret, SecretString};
use std::sync::LazyLock;
use tracing::{debug, warn};

use crate::error::CredentialError;
use crate::provider::CredentialProvider;

/// Pattern matching `${CRED:reference_name}`. The reference name is captured
/// in group 1 and may contain alphanumerics, underscores, hyphens, and dots.
static CRED_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\$\{CRED:([A-Za-z0-9_.\-]+)\}").expect("credential pattern is valid regex")
});

/// The sentinel string used to mask leaked credentials in response bodies.
const REDACTED: &str = "[CREDENTIAL]";

/// Result of injecting credentials into a request.
///
/// Manual Debug implementation redacts the body and headers fields
/// to prevent accidental credential exposure through logging.
pub struct InjectedRequest {
    /// The rewritten request body with credential references substituted.
    pub body: String,
    /// Rewritten headers (name, value) with credential references substituted.
    pub headers: Vec<(String, String)>,
    /// Which credential references were resolved during injection.
    pub resolved_refs: Vec<String>,
    /// The actual resolved secret values for response scrubbing.
    /// Stored as [`SecretString`] so they are zeroized on drop and never
    /// accidentally exposed through `Debug` or `Display`.
    pub resolved_values: Vec<SecretString>,
}

impl std::fmt::Debug for InjectedRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InjectedRequest")
            .field("body", &"[REDACTED]")
            .field("headers", &format!("{} entries", self.headers.len()))
            .field("resolved_refs", &self.resolved_refs)
            .field(
                "resolved_values",
                &format!("{} secrets", self.resolved_values.len()),
            )
            .finish()
    }
}

/// Inject credentials into a request body and a set of headers.
///
/// Every occurrence of `${CRED:ref}` in `body` and in the header values is
/// replaced with the resolved secret. Returns an error if any referenced
/// credential cannot be resolved.
pub async fn inject_credentials(
    body: &str,
    headers: &[(String, String)],
    provider: &dyn CredentialProvider,
) -> Result<InjectedRequest, CredentialError> {
    let mut resolved_refs: Vec<String> = Vec::new();
    let mut resolved_values: Vec<SecretString> = Vec::new();

    // --- body ---
    let new_body = replace_refs(body, provider, &mut resolved_refs, &mut resolved_values).await?;

    // --- headers ---
    let mut new_headers = Vec::with_capacity(headers.len());
    for (name, value) in headers {
        let new_value =
            replace_refs(value, provider, &mut resolved_refs, &mut resolved_values).await?;
        new_headers.push((name.clone(), new_value));
    }

    debug!(count = resolved_refs.len(), "credential injection complete");

    Ok(InjectedRequest {
        body: new_body,
        headers: new_headers,
        resolved_refs,
        resolved_values,
    })
}

/// Encoding-aware response scrubbing using [`SecretString`] values.
///
/// The plaintext is only exposed for the duration of the scrub operation and
/// is not stored in any intermediate `String` that outlives this call.
///
/// `known_values` should contain the secret values that were injected into the
/// outgoing request so we can detect them if the upstream echoes them back.
pub fn scrub_response(body: &str, known_values: &[SecretString]) -> String {
    // Sort credentials by length (longest first) to prevent
    // partial-match interference. If credential A = "abc" and B = "abcdef",
    // scrubbing A first would mangle B's value, preventing its detection.
    let mut sorted_values: Vec<&SecretString> = known_values.iter().collect();
    sorted_values.sort_by_key(|v| std::cmp::Reverse(v.expose_secret().len()));

    let mut scrubbed = body.to_string();
    for secret in sorted_values {
        let value = secret.expose_secret();
        if value.is_empty() {
            continue;
        }
        if value.len() < 4 {
            // Warn about short credentials that risk over-scrubbing.
            // Values under 4 chars match too many substrings, but we still
            // scrub them because failing to scrub a real credential is worse.
            tracing::debug!(
                len = value.len(),
                "scrubbing short credential value; consider using longer secrets"
            );
        }
        scrub_single_value(&mut scrubbed, value);
    }
    scrubbed
}

/// Encoding-aware response scrubbing for plain `&[String]` values.
///
/// Backward-compatible entry point for callers that do not yet use
/// [`SecretString`]. Prefer [`scrub_response`] with `SecretString` values.
#[deprecated(
    since = "0.0.12",
    note = "use scrub_response with SecretString values instead"
)]
pub fn scrub_response_plain(body: &str, known_values: &[String]) -> String {
    let mut sorted_values: Vec<&String> = known_values.iter().collect();
    sorted_values.sort_by_key(|v| std::cmp::Reverse(v.len()));

    let mut scrubbed = body.to_string();
    for value in sorted_values {
        if value.is_empty() {
            continue;
        }
        scrub_single_value(&mut scrubbed, value);
    }
    scrubbed
}

/// Scrub all encoded variants of a single credential value from a response body.
fn scrub_single_value(scrubbed: &mut String, value: &str) {
    // Direct match
    if scrubbed.contains(value) {
        warn!("credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(value, REDACTED);
    }
    // URL-encoded variant
    let url_encoded = urlencoding_encode(value);
    if url_encoded != value && scrubbed.contains(&url_encoded) {
        warn!("URL-encoded credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&url_encoded, REDACTED);
    }
    // Lowercase percent-encoded variant (RFC 3986 allows both %2F and %2f).
    let url_lower = urlencoding_encode_lower(value);
    if url_lower != url_encoded && url_lower != value && scrubbed.contains(&url_lower) {
        warn!("lowercase-percent-encoded credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&url_lower, REDACTED);
    }
    // JSON-escaped variant (handles quotes, backslashes, etc.)
    if let Ok(json_str) = serde_json::to_string(value) {
        // Remove surrounding quotes from JSON string
        let json_escaped = &json_str[1..json_str.len() - 1];
        if json_escaped != value && scrubbed.contains(json_escaped) {
            warn!("JSON-escaped credential value detected in response body, scrubbing");
            *scrubbed = scrubbed.replace(json_escaped, REDACTED);
        }
    }
    // Hex-encoded variant (lowercase)
    let hex_encoded: String = value.bytes().map(|b| format!("{:02x}", b)).collect();
    if scrubbed.contains(&hex_encoded) {
        warn!("hex-encoded credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&hex_encoded, REDACTED);
    }
    // Uppercase hex variant.
    let hex_upper: String = value.bytes().map(|b| format!("{:02X}", b)).collect();
    if hex_upper != hex_encoded && scrubbed.contains(&hex_upper) {
        warn!("uppercase-hex-encoded credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&hex_upper, REDACTED);
    }
    // Base64-encoded credential scrubbing.
    let b64_encoded = base64_encode_value(value);
    if b64_encoded != value && scrubbed.contains(&b64_encoded) {
        warn!("base64-encoded credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&b64_encoded, REDACTED);
    }
    // Base64url variant (RFC 4648 S5: '-' '_', no padding).
    let b64url_encoded = base64url_encode_value(value);
    if b64url_encoded != value
        && b64url_encoded != b64_encoded
        && scrubbed.contains(&b64url_encoded)
    {
        warn!("base64url-encoded credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&b64url_encoded, REDACTED);
    }
    // Unicode JSON escape sequence variant (\u00XX per character).
    let unicode_escaped = unicode_json_escape(value);
    if unicode_escaped != value && scrubbed.contains(&unicode_escaped) {
        warn!("unicode-escaped credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&unicode_escaped, REDACTED);
    }
    // Double URL-encoding variant.
    let double_url_encoded = urlencoding_encode(&url_encoded);
    if double_url_encoded != url_encoded && scrubbed.contains(&double_url_encoded) {
        warn!("double-URL-encoded credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&double_url_encoded, REDACTED);
    }
    // HTML entity encoded variants (decimal and hex).
    // A malicious upstream could embed credentials as &#78;&#79; or &#x4E;&#x4F;
    // in HTML responses to evade direct string matching.
    let html_decimal = html_entity_encode_decimal(value);
    if scrubbed.contains(&html_decimal) {
        warn!(
            "HTML-entity-encoded (decimal) credential value detected in response body, scrubbing"
        );
        *scrubbed = scrubbed.replace(&html_decimal, REDACTED);
    }
    let html_hex = html_entity_encode_hex(value);
    if html_hex != html_decimal && scrubbed.contains(&html_hex) {
        warn!("HTML-entity-encoded (hex) credential value detected in response body, scrubbing");
        *scrubbed = scrubbed.replace(&html_hex, REDACTED);
    }
}

/// HTML decimal entity encoding (&#DDD; per character).
fn html_entity_encode_decimal(input: &str) -> String {
    input.bytes().map(|b| format!("&#{};", b)).collect()
}

/// HTML hex entity encoding (&#xHH; per character).
fn html_entity_encode_hex(input: &str) -> String {
    input.bytes().map(|b| format!("&#x{:02X};", b)).collect()
}

/// Simple percent-encoding for credential scrubbing.
fn urlencoding_encode(input: &str) -> String {
    let mut encoded = String::new();
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                encoded.push(byte as char);
            }
            _ => {
                encoded.push_str(&format!("%{:02X}", byte));
            }
        }
    }
    encoded
}

/// Lowercase percent-encoding variant for credential scrubbing.
/// RFC 3986 allows both `%2F` and `%2f`; the standard encoder uses uppercase,
/// but a malicious upstream may use lowercase to evade scrubbing.
fn urlencoding_encode_lower(input: &str) -> String {
    let mut encoded = String::new();
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                encoded.push(byte as char);
            }
            _ => {
                encoded.push_str(&format!("%{:02x}", byte));
            }
        }
    }
    encoded
}

/// Unicode JSON escape sequence encoding (\u00XX per byte).
/// A credential "abc" becomes "\u0061\u0062\u0063" which is valid JSON
/// and renders identically when parsed.
fn unicode_json_escape(input: &str) -> String {
    input.bytes().map(|b| format!("\\u{:04x}", b)).collect()
}

/// Collect all `${CRED:...}` references found in `input`.
pub fn find_refs(input: &str) -> Vec<String> {
    CRED_PATTERN
        .captures_iter(input)
        .map(|cap| cap[1].to_string())
        .collect()
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Replace all `${CRED:ref}` patterns in `input` by resolving each reference
/// through the provider. Appends resolved reference names and values.
async fn replace_refs(
    input: &str,
    provider: &dyn CredentialProvider,
    resolved: &mut Vec<String>,
    secret_values: &mut Vec<SecretString>,
) -> Result<String, CredentialError> {
    // Collect all matches first so we can resolve them.
    let refs = find_refs(input);
    if refs.is_empty() {
        return Ok(input.to_string());
    }

    // Validate all credential references exist before injecting any.
    // This prevents partial injection where some refs are resolved but others fail,
    // which could leak information about which credential names are valid.
    let mut resolved_pairs: Vec<(String, SecretString)> = Vec::new();
    for reference in &refs {
        let value = provider.resolve(reference).await?;
        resolved_pairs.push((reference.clone(), value));
    }

    let mut output = input.to_string();
    for (reference, secret) in &resolved_pairs {
        let placeholder = format!("${{CRED:{reference}}}");
        output = output.replace(&placeholder, secret.expose_secret());
        if !resolved.contains(reference) {
            resolved.push(reference.clone());
            // Capture resolved values at injection time.
            // Previously the handler re-resolved from the provider for scrubbing,
            // which could return different values after credential rotation.
            secret_values.push(SecretString::from(secret.expose_secret().to_owned()));
        }
    }

    Ok(output)
}

/// Base64url encoding (RFC 4648 S5) for credential scrubbing.
/// Uses '-' and '_' instead of '+' and '/', no padding.
fn base64url_encode_value(input: &str) -> String {
    let standard = base64_encode_value(input);
    standard
        .replace('+', "-")
        .replace('/', "_")
        .trim_end_matches('=')
        .to_string()
}

/// Simple base64 encoding for credential scrubbing (standard alphabet, with padding).
fn base64_encode_value(input: &str) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let bytes = input.as_bytes();
    let mut result = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
        let triple = (b0 << 16) | (b1 << 8) | b2;
        result.push(ALPHABET[((triple >> 18) & 0x3F) as usize] as char);
        result.push(ALPHABET[((triple >> 12) & 0x3F) as usize] as char);
        if chunk.len() > 1 {
            result.push(ALPHABET[((triple >> 6) & 0x3F) as usize] as char);
        } else {
            result.push('=');
        }
        if chunk.len() > 2 {
            result.push(ALPHABET[(triple & 0x3F) as usize] as char);
        } else {
            result.push('=');
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::provider::{CredentialProvider, CredentialRef};
    use async_trait::async_trait;
    use std::collections::HashMap;

    /// A trivial in-memory provider for tests.
    struct MockProvider {
        store: HashMap<String, String>,
    }

    impl MockProvider {
        fn new(entries: &[(&str, &str)]) -> Self {
            Self {
                store: entries
                    .iter()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect(),
            }
        }
    }

    #[async_trait]
    impl CredentialProvider for MockProvider {
        async fn resolve(&self, reference: &str) -> Result<SecretString, CredentialError> {
            self.store
                .get(reference)
                .map(|v| SecretString::from(v.clone()))
                .ok_or_else(|| CredentialError::NotFound(reference.to_string()))
        }

        async fn list_refs(&self) -> Result<Vec<CredentialRef>, CredentialError> {
            Ok(self
                .store
                .keys()
                .map(|k| CredentialRef {
                    name: k.clone(),
                    provider: "mock".into(),
                    last_rotated: None,
                })
                .collect())
        }
    }

    /// Helper: create a Vec<SecretString> from plain string slices.
    fn secret_vec(values: &[&str]) -> Vec<SecretString> {
        values
            .iter()
            .map(|v| SecretString::from(v.to_string()))
            .collect()
    }

    #[tokio::test]
    async fn injects_body_credentials() {
        let provider = MockProvider::new(&[("api_key", "sk-secret-123")]);
        let body = r#"{"key": "${CRED:api_key}"}"#;

        let result = inject_credentials(body, &[], &provider).await.unwrap();
        assert_eq!(result.body, r#"{"key": "sk-secret-123"}"#);
        assert_eq!(result.resolved_refs, vec!["api_key"]);
    }

    #[tokio::test]
    async fn injects_header_credentials() {
        let provider = MockProvider::new(&[("token", "ghp_abc")]);
        let headers = vec![
            (
                "Authorization".to_string(),
                "Bearer ${CRED:token}".to_string(),
            ),
            ("X-Custom".to_string(), "plain-value".to_string()),
        ];

        let result = inject_credentials("", &headers, &provider).await.unwrap();
        assert_eq!(result.headers[0].1, "Bearer ghp_abc");
        assert_eq!(result.headers[1].1, "plain-value");
    }

    #[tokio::test]
    async fn multiple_refs_in_body() {
        let provider = MockProvider::new(&[("a", "AAA"), ("b", "BBB")]);
        let body = "first=${CRED:a}&second=${CRED:b}";

        let result = inject_credentials(body, &[], &provider).await.unwrap();
        assert_eq!(result.body, "first=AAA&second=BBB");
        assert!(result.resolved_refs.contains(&"a".to_string()));
        assert!(result.resolved_refs.contains(&"b".to_string()));
    }

    #[tokio::test]
    async fn unknown_ref_returns_error() {
        let provider = MockProvider::new(&[]);
        let body = "key=${CRED:missing}";

        let err = inject_credentials(body, &[], &provider).await.unwrap_err();
        assert!(matches!(err, CredentialError::NotFound(_)));
    }

    #[tokio::test]
    async fn no_refs_is_passthrough() {
        let provider = MockProvider::new(&[]);
        let body = "no credential references here";

        let result = inject_credentials(body, &[], &provider).await.unwrap();
        assert_eq!(result.body, body);
        assert!(result.resolved_refs.is_empty());
    }

    #[test]
    fn scrub_response_masks_leaked_values() {
        let body = r#"{"echo": "sk-secret-123", "other": "safe"}"#;
        let known = secret_vec(&["sk-secret-123"]);

        let scrubbed = scrub_response(body, &known);
        assert_eq!(scrubbed, r#"{"echo": "[CREDENTIAL]", "other": "safe"}"#);
    }

    #[test]
    fn scrub_response_no_match_is_passthrough() {
        let body = "nothing to see here";
        let known = secret_vec(&["secret"]);
        let scrubbed = scrub_response(body, &known);
        assert_eq!(scrubbed, body);
    }

    #[test]
    fn scrub_response_empty_value_ignored() {
        let body = "some body";
        let known = secret_vec(&[""]);
        let scrubbed = scrub_response(body, &known);
        assert_eq!(scrubbed, body);
    }

    #[test]
    fn scrub_response_multiple_values() {
        let body = "has AAA and BBB in it";
        let known = secret_vec(&["AAA", "BBB"]);
        let scrubbed = scrub_response(body, &known);
        assert_eq!(scrubbed, "has [CREDENTIAL] and [CREDENTIAL] in it");
    }

    #[test]
    fn find_refs_extracts_all_references() {
        let input = "${CRED:one} and ${CRED:two.three} and ${CRED:four-five}";
        let refs = find_refs(input);
        assert_eq!(refs, vec!["one", "two.three", "four-five"]);
    }

    #[test]
    fn find_refs_empty_on_no_match() {
        assert!(find_refs("no credentials here").is_empty());
    }

    // -----------------------------------------------------------------------
    // Encoding-aware scrubbing tests
    // -----------------------------------------------------------------------

    #[test]
    fn scrub_response_url_encoded() {
        let known = secret_vec(&["p@ss w0rd!"]);
        let body = "the response contains p%40ss%20w0rd%21 in a query string";

        let scrubbed = scrub_response(body, &known);
        assert_eq!(
            scrubbed,
            "the response contains [CREDENTIAL] in a query string"
        );
        assert!(!scrubbed.contains("%40"));
        assert!(!scrubbed.contains("%20"));
        assert!(!scrubbed.contains("%21"));
    }

    #[test]
    fn scrub_response_json_escaped() {
        let known = secret_vec(&[r#"pass"word\"#]);
        let body = r#"{"field": "pass\"word\\"}"#;

        let scrubbed = scrub_response(body, &known);
        assert_eq!(scrubbed, r#"{"field": "[CREDENTIAL]"}"#);
        assert!(!scrubbed.contains("pass"));
        assert!(!scrubbed.contains("word"));
    }

    #[test]
    fn scrub_response_hex_encoded() {
        let hex_of_secret = "736563726574";
        let body = format!("debug dump: hex={hex_of_secret} end");
        let known = secret_vec(&["secret"]);

        let scrubbed = scrub_response(&body, &known);
        assert_eq!(scrubbed, "debug dump: hex=[CREDENTIAL] end");
        assert!(!scrubbed.contains(hex_of_secret));
    }

    #[test]
    fn scrub_response_base64_encoded() {
        let b64 = base64_encode_value("my-secret-key");
        assert_eq!(b64, "bXktc2VjcmV0LWtleQ==");
        let body = format!("Authorization: Basic {b64} is here");
        let known = secret_vec(&["my-secret-key"]);

        let scrubbed = scrub_response(&body, &known);
        assert_eq!(scrubbed, "Authorization: Basic [CREDENTIAL] is here");
        assert!(!scrubbed.contains(&b64));
    }

    #[test]
    fn scrub_response_longest_first_ordering() {
        let known = secret_vec(&["abc", "abcdef"]);
        let body = "values: abcdef and abc end";

        let scrubbed = scrub_response(body, &known);
        assert_eq!(scrubbed, "values: [CREDENTIAL] and [CREDENTIAL] end");
        assert!(!scrubbed.contains("abc"));
        assert!(!scrubbed.contains("abcdef"));
    }

    #[test]
    fn scrub_response_all_encodings_simultaneously() {
        let secret = "s3cr&t!";
        let url_enc = urlencoding_encode(secret);
        let hex_enc: String = secret.bytes().map(|b| format!("{:02x}", b)).collect();
        let b64_enc = base64_encode_value(secret);
        let json_enc = {
            let full = serde_json::to_string(secret).unwrap();
            full[1..full.len() - 1].to_string()
        };

        let body =
            format!("plain={secret} url={url_enc} json={json_enc} hex={hex_enc} b64={b64_enc}");
        let known = secret_vec(&[secret]);

        let scrubbed = scrub_response(&body, &known);

        assert_eq!(
            scrubbed,
            "plain=[CREDENTIAL] url=[CREDENTIAL] json=[CREDENTIAL] hex=[CREDENTIAL] b64=[CREDENTIAL]"
        );
        assert!(!scrubbed.contains(secret));
        assert!(!scrubbed.contains(&url_enc));
        assert!(!scrubbed.contains(&hex_enc));
        assert!(!scrubbed.contains(&b64_enc));
    }

    #[tokio::test]
    async fn scrub_response_partial_injection_prevented() {
        let provider = MockProvider::new(&[("valid_key", "resolved-value")]);
        let body = "first=${CRED:valid_key}&second=${CRED:missing_key}";

        let result = inject_credentials(body, &[], &provider).await;
        assert!(
            result.is_err(),
            "injection must fail when any ref is unresolvable"
        );
        assert!(
            matches!(result.unwrap_err(), CredentialError::NotFound(ref name) if name == "missing_key")
        );
    }

    #[tokio::test]
    async fn resolved_values_captured_at_injection_time() {
        let provider = MockProvider::new(&[("key_a", "alpha-secret"), ("key_b", "beta-secret")]);
        let body = "a=${CRED:key_a} b=${CRED:key_b}";

        let result = inject_credentials(body, &[], &provider).await.unwrap();

        assert_eq!(result.body, "a=alpha-secret b=beta-secret");

        let exposed: Vec<&str> = result
            .resolved_values
            .iter()
            .map(|s| s.expose_secret())
            .collect();
        assert!(exposed.contains(&"alpha-secret"));
        assert!(exposed.contains(&"beta-secret"));
        assert_eq!(result.resolved_values.len(), 2);

        let leaked_response = "upstream echoed alpha-secret back";
        let scrubbed = scrub_response(leaked_response, &result.resolved_values);
        assert_eq!(scrubbed, "upstream echoed [CREDENTIAL] back");
    }

    // -----------------------------------------------------------------------
    // Recursive credential injection must not expand
    // -----------------------------------------------------------------------

    #[test]
    fn recursive_ref_not_expanded() {
        let input = "${CRED:${CRED:inner}}";
        let refs = find_refs(input);
        assert_eq!(
            refs,
            vec!["inner"],
            "only the inner ref 'inner' should be matched. Got: {:?}",
            refs
        );

        let input3 = "${CRED:${CRED:${CRED:deep}}}";
        let refs3 = find_refs(input3);
        assert_eq!(
            refs3,
            vec!["deep"],
            "only the innermost ref 'deep' should be matched. Got: {:?}",
            refs3
        );
    }

    #[tokio::test]
    async fn recursive_injection_does_not_re_expand() {
        let provider = MockProvider::new(&[("outer", "${CRED:inner}"), ("inner", "real-secret")]);
        let body = "key=${CRED:outer}";

        let result = inject_credentials(body, &[], &provider).await.unwrap();

        assert_eq!(
            result.body, "key=${CRED:inner}",
            "credential values containing ${{CRED:...}} must NOT be re-expanded"
        );
        assert_eq!(result.resolved_refs, vec!["outer"]);
    }

    // -----------------------------------------------------------------------
    // Credential value with regex metacharacters in scrubbing
    // -----------------------------------------------------------------------

    #[test]
    fn credential_with_special_chars_in_value() {
        let special_value = r"p@$$w0rd!.*+";
        let body = format!("the password is {} here", special_value);
        let known = secret_vec(&[special_value]);

        let scrubbed = scrub_response(&body, &known);
        assert_eq!(
            scrubbed, "the password is [CREDENTIAL] here",
            "credential with regex metacharacters must be scrubbed literally"
        );
        assert!(
            !scrubbed.contains(special_value),
            "original credential value must not survive in scrubbed output"
        );
    }

    #[test]
    fn credential_ref_name_injection_rejected() {
        assert!(find_refs("${CRED:../../etc/passwd}").is_empty());
        assert!(find_refs("${CRED:..\\..\\windows\\system32}").is_empty());
        assert!(find_refs("${CRED:ref;rm -rf /}").is_empty());
        assert!(find_refs("${CRED:ref$(whoami)}").is_empty());
        assert!(find_refs("${CRED:ref`id`}").is_empty());
        assert!(find_refs("${CRED:ref name}").is_empty());
        assert!(find_refs("${CRED:ref&other}").is_empty());
        assert!(find_refs("${CRED:ref|pipe}").is_empty());
        assert!(find_refs("${CRED:}").is_empty());
        assert_eq!(
            find_refs("${CRED:valid.ref-name_123}"),
            vec!["valid.ref-name_123"]
        );
        assert_eq!(find_refs("${CRED:API_KEY}"), vec!["API_KEY"]);
        assert_eq!(find_refs("${CRED:my-secret.v2}"), vec!["my-secret.v2"]);
    }

    // -----------------------------------------------------------------------
    // Encoding variant bypass tests
    // -----------------------------------------------------------------------

    fn test_base64url_encode(input: &str) -> String {
        let standard = base64_encode_value(input);
        standard
            .replace('+', "-")
            .replace('/', "_")
            .trim_end_matches('=')
            .to_string()
    }

    #[test]
    fn scrub_response_base64url_bypass() {
        let secret = "secret+key/value";
        let b64url_encoded = test_base64url_encode(secret);
        let b64_standard = base64_encode_value(secret);
        assert_ne!(
            b64url_encoded, b64_standard,
            "base64url and standard base64 should differ for this input"
        );

        let body = format!("token={b64url_encoded} end");
        let known = secret_vec(&[secret]);
        let scrubbed = scrub_response(&body, &known);

        assert!(
            !scrubbed.contains(&b64url_encoded),
            "SCRUBBING BYPASS: base64url-encoded credential survives in response: {scrubbed}"
        );
    }

    #[test]
    fn scrub_response_uppercase_hex_bypass() {
        let secret = "sk-key";
        let upper_hex: String = secret.bytes().map(|b| format!("{:02X}", b)).collect();
        let lower_hex: String = secret.bytes().map(|b| format!("{:02x}", b)).collect();
        assert_ne!(
            upper_hex, lower_hex,
            "test requires hex representations to differ: upper={upper_hex} lower={lower_hex}"
        );

        let body = format!("hex={upper_hex} end");
        let known = secret_vec(&[secret]);
        let scrubbed = scrub_response(&body, &known);

        assert!(
            !scrubbed.contains(&upper_hex),
            "SCRUBBING BYPASS: uppercase-hex credential survives in response: {scrubbed}"
        );
    }

    #[test]
    fn scrub_response_double_url_encoding_bypass() {
        let secret = "p@ss!";
        let single_encoded = urlencoding_encode(secret);
        let double_encoded = urlencoding_encode(&single_encoded);

        assert_ne!(single_encoded, double_encoded);

        let body = format!("reflected={double_encoded} end");
        let known = secret_vec(&[secret]);
        let scrubbed = scrub_response(&body, &known);

        assert!(
            !scrubbed.contains(&double_encoded),
            "SCRUBBING BYPASS: double-URL-encoded credential survives in response: {scrubbed}"
        );
    }

    // -----------------------------------------------------------------------
    // Memory safety: SecretString Debug/Display never leaks plaintext
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn secret_string_debug_does_not_leak() {
        let provider = MockProvider::new(&[("api_key", "super-secret-value-12345")]);
        let body = r#"{"key": "${CRED:api_key}"}"#;

        let result = inject_credentials(body, &[], &provider).await.unwrap();

        // Debug formatting of resolved_values must NOT contain the plaintext.
        // Note: the body field legitimately contains the injected credential
        // (it's the rewritten request), so we check resolved_values specifically.
        let values_debug = format!("{:?}", result.resolved_values);
        assert!(
            !values_debug.contains("super-secret-value-12345"),
            "Debug output of resolved_values must not contain plaintext credential. Got: {values_debug}"
        );
        // The SecretString Debug impl should show the redacted wrapper
        assert!(
            values_debug.contains("REDACTED") || values_debug.contains("SecretBox"),
            "Debug output should show redacted wrapper, got: {values_debug}"
        );
    }

    #[test]
    fn scrub_response_with_secret_string() {
        // Verify that scrub_response works correctly with SecretString values,
        // scrubbing all encoding variants.
        let secrets = secret_vec(&["my-api-key-999"]);
        let b64 = base64_encode_value("my-api-key-999");
        let hex: String = "my-api-key-999"
            .bytes()
            .map(|b| format!("{:02x}", b))
            .collect();

        let body = format!("plain=my-api-key-999 b64={b64} hex={hex}");
        let scrubbed = scrub_response(&body, &secrets);

        assert!(
            !scrubbed.contains("my-api-key-999"),
            "plaintext must be scrubbed"
        );
        assert!(!scrubbed.contains(&b64), "base64 must be scrubbed");
        assert!(!scrubbed.contains(&hex), "hex must be scrubbed");
        assert_eq!(
            scrubbed,
            "plain=[CREDENTIAL] b64=[CREDENTIAL] hex=[CREDENTIAL]"
        );
    }

    #[tokio::test]
    async fn scrub_response_lowercase_percent_encoding() {
        let secret = SecretString::from("my-secret/value".to_string());
        // Lowercase percent-encoded: '/' becomes %2f instead of %2F
        let response = "result: my-secret%2fvalue";
        let scrubbed = scrub_response(response, &[secret]);
        assert!(
            !scrubbed.contains("my-secret"),
            "lowercase percent-encoded credential should be scrubbed"
        );
        assert!(scrubbed.contains(REDACTED));
    }

    #[tokio::test]
    async fn scrub_response_unicode_json_escape() {
        let secret = SecretString::from("abc".to_string());
        let response = r#"{"data": "\u0061\u0062\u0063"}"#;
        let scrubbed = scrub_response(response, &[secret]);
        assert!(
            !scrubbed.contains(r"\u0061\u0062\u0063"),
            "unicode-escaped credential should be scrubbed"
        );
        assert!(scrubbed.contains(REDACTED));
    }
}