tsafe-azure 1.0.3

Azure Key Vault integration for tsafe — optional secret pull.
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
//! Azure Key Vault HTTP client.
// `ureq::Error` is large; propagating it through `Result` triggers `clippy::result_large_err`.
#![allow(clippy::result_large_err)]

use crate::config::KvConfig;
use crate::error::KvError;

/// Outcome of a single secret push operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PushOutcome {
    /// Secret was absent in the remote vault and was created.
    Created,
    /// Secret existed in the remote vault and its value was updated.
    Updated,
    /// Secret existed in the remote vault with an identical value — no write made.
    Unchanged,
    /// Secret was deleted from the remote vault (only when `--delete-missing` is active).
    Deleted,
}

fn http_agent() -> ureq::Agent {
    ureq::AgentBuilder::new()
        .timeout_connect(std::time::Duration::from_secs(10))
        .timeout(std::time::Duration::from_secs(30))
        .build()
}

const API_VERSION: &str = "7.4";
const MAX_RETRIES_429: u32 = 3;
const MAX_RETRIES_TRANSIENT: u32 = 5;
const DEFAULT_RETRY_SECS: u64 = 2;

/// Execute an HTTP call with retry on 429 (throttled) responses.
/// Respects the `Retry-After` header if present; otherwise uses exponential backoff.
fn call_with_retry(
    make_request: impl Fn() -> Result<ureq::Response, ureq::Error>,
) -> Result<ureq::Response, ureq::Error> {
    let mut throttled_attempt = 0u32;
    let mut transient_attempt = 0u32;
    loop {
        match make_request() {
            Ok(resp) => return Ok(resp),
            Err(ureq::Error::Status(429, resp)) if throttled_attempt < MAX_RETRIES_429 => {
                let retry_after = resp
                    .header("Retry-After")
                    .and_then(|v| v.parse::<u64>().ok())
                    .unwrap_or(DEFAULT_RETRY_SECS * 2u64.pow(throttled_attempt));
                let wait = std::cmp::min(jittered_delay_secs(retry_after), 30);
                std::thread::sleep(std::time::Duration::from_secs(wait));
                throttled_attempt += 1;
            }
            Err(ureq::Error::Transport(t))
                if transient_attempt < MAX_RETRIES_TRANSIENT
                    && is_retryable_transport_error(t.to_string().as_str()) =>
            {
                let backoff = DEFAULT_RETRY_SECS * 2u64.pow(transient_attempt);
                let wait = std::cmp::min(jittered_delay_secs(backoff), 30);
                std::thread::sleep(std::time::Duration::from_secs(wait));
                transient_attempt += 1;
            }
            Err(e) => return Err(e),
        }
    }
}

fn is_retryable_transport_error(message: &str) -> bool {
    let msg = message.to_ascii_lowercase();
    msg.contains("timed out")
        || msg.contains("timeout")
        || msg.contains("connection reset")
        || msg.contains("connection refused")
        || msg.contains("econnreset")
        || msg.contains("econnrefused")
        || msg.contains("temporar")
}

fn jittered_delay_secs(base_secs: u64) -> u64 {
    if base_secs == 0 {
        return 0;
    }
    let jitter_cap = std::cmp::max(1, base_secs / 4);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    base_secs + (nanos % (jitter_cap + 1))
}

/// Map a ureq error to a KvError.
fn map_ureq_error(e: ureq::Error) -> KvError {
    match e {
        ureq::Error::Status(404, _) => KvError::NotFound(String::new()),
        ureq::Error::Status(s, r) => KvError::Http {
            status: s,
            message: r
                .into_string()
                .unwrap_or_else(|_| "<unreadable response>".into()),
        },
        other => KvError::Transport(other.to_string()),
    }
}

/// Pull secrets from the Key Vault, optionally filtered by `prefix`.
///
/// `acquire_token` is called once per pagination page during listing and once
/// more before the per-secret fetch phase, so tokens are always fresh even on
/// vaults with hundreds of secrets that take longer than the OAuth TTL to pull.
///
/// Returns `(normalized_key, value)` pairs ready to set in the local vault.
/// Secret names with hyphens are normalised to `UPPER_SNAKE_CASE`.
pub fn pull_secrets(
    cfg: &KvConfig,
    acquire_token: &impl Fn() -> Result<String, KvError>,
    prefix: Option<&str>,
) -> Result<Vec<(String, String)>, KvError> {
    let names = list_secret_names(cfg, acquire_token)?;
    // Acquire a fresh token before the per-secret fetch phase: the list
    // phase may have spanned multiple pages and taken significant time.
    let token = acquire_token()?;
    let mut secrets = Vec::new();

    for name in &names {
        if let Some(p) = prefix {
            if !name.to_lowercase().starts_with(&p.to_lowercase()) {
                continue;
            }
        }
        let value = get_secret(cfg, &token, name)?;
        let key = name.replace('-', "_").to_uppercase();
        secrets.push((key, value));
    }

    Ok(secrets)
}

/// List the names of all *enabled* secrets in the vault.
/// Handles pagination via `nextLink`. Acquires a fresh token per page so
/// long-running list operations survive OAuth token expiry.
fn list_secret_names(
    cfg: &KvConfig,
    acquire_token: &impl Fn() -> Result<String, KvError>,
) -> Result<Vec<String>, KvError> {
    let first_url = format!(
        "{}/secrets?api-version={API_VERSION}&maxresults=25",
        cfg.vault_url
    );
    let mut names = Vec::new();
    let mut next: Option<String> = Some(first_url);

    while let Some(url) = next.take() {
        let token = acquire_token()?;
        let agent = http_agent();
        let auth = format!("Bearer {token}");
        let url_clone = url.clone();
        let resp: serde_json::Value =
            call_with_retry(|| agent.get(&url_clone).set("Authorization", &auth).call())
                .map_err(map_ureq_error)?
                .into_json()
                .map_err(|e| KvError::Transport(e.to_string()))?;

        if let Some(items) = resp["value"].as_array() {
            for item in items {
                let enabled = item["attributes"]["enabled"].as_bool().unwrap_or(true);
                if !enabled {
                    continue;
                }
                if let Some(id) = item["id"].as_str() {
                    // `id` is either versioned:   https://vault/secrets/my-secret/abc123
                    // or unversioned (list API):   https://vault/secrets/my-secret
                    // Find the segment immediately after "secrets" in the path.
                    let parts: Vec<&str> = id.trim_end_matches('/').split('/').collect();
                    if let Some(secrets_idx) = parts.iter().position(|&p| p == "secrets") {
                        if let Some(&name) = parts.get(secrets_idx + 1) {
                            if !name.is_empty() {
                                names.push(name.to_string());
                            }
                        }
                    }
                }
            }
        }

        next = resp["nextLink"]
            .as_str()
            .filter(|url| url.starts_with(cfg.vault_url.as_str()))
            .map(|s| s.to_string());
    }

    Ok(names)
}

/// Fetch the current value of a single secret by name.
fn get_secret(cfg: &KvConfig, token: &str, name: &str) -> Result<String, KvError> {
    let url = format!("{}/secrets/{name}?api-version={API_VERSION}", cfg.vault_url);

    let agent = http_agent();
    let auth = format!("Bearer {token}");
    let url_clone = url.clone();
    let resp: serde_json::Value =
        call_with_retry(|| agent.get(&url_clone).set("Authorization", &auth).call())
            .map_err(|e| {
                // Enrich NotFound with the actual secret name.
                let err = map_ureq_error(e);
                match err {
                    KvError::NotFound(_) => KvError::NotFound(name.to_string()),
                    other => other,
                }
            })?
            .into_json()
            .map_err(|e| KvError::Transport(e.to_string()))?;

    resp["value"]
        .as_str()
        .map(|s| s.to_string())
        .ok_or_else(|| KvError::NotFound(name.to_string()))
}

/// Push a single secret to Azure Key Vault using upsert semantics.
///
/// The caller is responsible for reverse-normalizing the local key name to the
/// AKV provider name before calling this function (e.g. `MY_SECRET` → `my-secret`).
///
/// If the remote secret already exists with an identical value (compared via
/// SHA-256 fingerprint), no write is made and `PushOutcome::Unchanged` is returned.
///
/// # Soft-delete conflict
/// If the PUT returns HTTP 409 with a body indicating the secret is in a deleted
/// but recoverable state, `KvError::SoftDeleted(name)` is returned. The operator
/// must recover or purge the secret in the Azure portal before retrying.
pub fn push_secret(
    cfg: &KvConfig,
    acquire_token: &impl Fn() -> Result<String, KvError>,
    name: &str,
    value: &str,
) -> Result<PushOutcome, KvError> {
    let token = acquire_token()?;

    // Check if remote already has this secret and if the value is identical.
    let current_value = get_secret_opt(cfg, &token, name)?;

    if let Some(ref remote_value) = current_value {
        if remote_value == value {
            return Ok(PushOutcome::Unchanged);
        }
    }

    // PUT to upsert.
    let url = format!("{}/secrets/{name}?api-version={API_VERSION}", cfg.vault_url);
    let body = serde_json::json!({ "value": value });
    let body_str = serde_json::to_string(&body).map_err(|e| KvError::Transport(e.to_string()))?;

    let agent = http_agent();
    let auth = format!("Bearer {token}");
    let url_clone = url.clone();
    let name_owned = name.to_string();

    let result = call_with_retry(|| {
        agent
            .put(&url_clone)
            .set("Authorization", &auth)
            .set("Content-Type", "application/json")
            .send_string(&body_str)
    });

    match result {
        Ok(_) => {
            if current_value.is_some() {
                Ok(PushOutcome::Updated)
            } else {
                Ok(PushOutcome::Created)
            }
        }
        Err(ureq::Error::Status(409, resp)) => {
            let body = resp.into_string().unwrap_or_else(|_| "<unreadable>".into());
            let body_lower = body.to_ascii_lowercase();
            if body_lower.contains("deleted")
                && (body_lower.contains("recoverable") || body_lower.contains("soft"))
            {
                Err(KvError::SoftDeleted(name_owned))
            } else {
                Err(KvError::Http {
                    status: 409,
                    message: body,
                })
            }
        }
        Err(e) => Err(map_ureq_error(e)),
    }
}

/// Delete a single secret from Azure Key Vault.
///
/// On vaults with soft-delete enabled (the default for AKV), this initiates a
/// soft-delete; the secret enters a 30-day recoverable state. The caller is
/// responsible for warning the operator accordingly.
///
/// Returns `Ok(())` if the secret was deleted. Returns `Ok(())` if the secret
/// was already absent (idempotent). Returns `Err` on unexpected HTTP errors.
pub fn delete_secret(
    cfg: &KvConfig,
    acquire_token: &impl Fn() -> Result<String, KvError>,
    name: &str,
) -> Result<(), KvError> {
    let token = acquire_token()?;
    let url = format!("{}/secrets/{name}?api-version={API_VERSION}", cfg.vault_url);

    let agent = http_agent();
    let auth = format!("Bearer {token}");
    let url_clone = url.clone();

    let result = call_with_retry(|| agent.delete(&url_clone).set("Authorization", &auth).call());

    match result {
        Ok(_) => Ok(()),
        Err(ureq::Error::Status(404, _)) => Ok(()),
        Err(e) => Err(map_ureq_error(e)),
    }
}

/// Fetch the current value of a single secret by name, returning `None` if the
/// secret does not exist (404) rather than an error.
fn get_secret_opt(cfg: &KvConfig, token: &str, name: &str) -> Result<Option<String>, KvError> {
    match get_secret(cfg, token, name) {
        Ok(v) => Ok(Some(v)),
        Err(KvError::NotFound(_)) => Ok(None),
        Err(e) => Err(e),
    }
}

// ── tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── pure-logic tests (no HTTP) ────────────────────────────────────────────

    #[test]
    fn key_normalisation() {
        let name = "my-super-secret";
        let key = name.replace('-', "_").to_uppercase();
        assert_eq!(key, "MY_SUPER_SECRET");
    }

    #[test]
    fn id_parsing_versioned_url() {
        let id = "https://myvault.vault.azure.net/secrets/my-secret/abc123def456";
        let parts: Vec<&str> = id.trim_end_matches('/').split('/').collect();
        let secrets_idx = parts.iter().position(|&p| p == "secrets").unwrap();
        assert_eq!(parts[secrets_idx + 1], "my-secret");
    }

    #[test]
    fn id_parsing_unversioned_url() {
        // Azure list API returns unversioned URLs — this is the bug the old test masked.
        let id = "https://myvault.vault.azure.net/secrets/my-secret";
        let parts: Vec<&str> = id.trim_end_matches('/').split('/').collect();
        let secrets_idx = parts.iter().position(|&p| p == "secrets").unwrap();
        assert_eq!(parts[secrets_idx + 1], "my-secret");
    }

    #[test]
    fn nextlink_ssrf_guard_rejects_foreign_origin() {
        // The filter `url.starts_with(cfg.vault_url)` must reject nextLinks that
        // point to a different host, preventing SSRF via a malicious AKV response.
        let vault_url = "https://myvault.vault.azure.net";
        let malicious_next = "https://evil.example.com/secrets?api-version=7.4";
        assert!(
            !malicious_next.starts_with(vault_url),
            "SSRF guard should reject nextLink from a different origin"
        );
    }

    #[test]
    fn nextlink_ssrf_guard_accepts_same_origin() {
        let vault_url = "https://myvault.vault.azure.net";
        let valid_next = "https://myvault.vault.azure.net/secrets?api-version=7.4&$skiptoken=abc";
        assert!(valid_next.starts_with(vault_url));
    }

    #[test]
    fn retryable_transport_classifier_detects_timeout() {
        assert!(is_retryable_transport_error("operation timed out"));
        assert!(is_retryable_transport_error("Connection refused"));
        assert!(!is_retryable_transport_error("certificate verify failed"));
    }

    #[test]
    fn jittered_delay_stays_within_25_percent_bound() {
        let base = 20;
        let jittered = jittered_delay_secs(base);
        assert!(jittered >= base);
        assert!(jittered <= base + (base / 4));
    }

    // ── mock-server tests ─────────────────────────────────────────────────────

    fn list_response(names: &[&str], next_link: Option<&str>) -> String {
        let items: Vec<String> = names
            .iter()
            .map(|n| {
                format!(r#"{{"id":"https://vault/secrets/{n}","attributes":{{"enabled":true}}}}"#)
            })
            .collect();
        let next = next_link
            .map(|u| format!(r#","nextLink":"{u}""#))
            .unwrap_or_default();
        format!(r#"{{"value":[{}]{}}}"#, items.join(","), next)
    }

    fn secret_response(value: &str) -> String {
        format!(r#"{{"value":"{value}"}}"#)
    }

    fn cfg(url: &str) -> KvConfig {
        KvConfig {
            vault_url: url.to_string(),
        }
    }

    #[test]
    fn pull_secrets_empty_vault() {
        let mut server = mockito::Server::new();
        let _m = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"value":[]}"#)
            .create();

        let result =
            pull_secrets(&cfg(&server.url()), &|| Ok("test-token".to_string()), None).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn pull_secrets_fetches_and_normalises_key() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["my-db-password"], None))
            .create();
        let _get = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/secrets/my-db-password\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(secret_response("s3cr3t"))
            .create();

        let secrets = pull_secrets(&cfg(&server.url()), &|| Ok("tok".to_string()), None).unwrap();
        assert_eq!(secrets.len(), 1);
        assert_eq!(secrets[0].0, "MY_DB_PASSWORD");
        assert_eq!(secrets[0].1, "s3cr3t");
    }

    #[test]
    fn pull_secrets_skips_disabled_secrets() {
        let mut server = mockito::Server::new();
        let disabled_item = r#"{"value":[{"id":"https://vault/secrets/disabled-key","attributes":{"enabled":false}}]}"#;
        let _m = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(disabled_item)
            .create();

        let secrets = pull_secrets(&cfg(&server.url()), &|| Ok("tok".to_string()), None).unwrap();
        assert!(secrets.is_empty(), "disabled secrets must be filtered out");
    }

    #[test]
    fn pull_secrets_prefix_filter() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["app-token", "db-password"], None))
            .create();
        let _get = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/secrets/app-token\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(secret_response("tok-xyz"))
            .create();

        let secrets =
            pull_secrets(&cfg(&server.url()), &|| Ok("tok".to_string()), Some("app-")).unwrap();
        assert_eq!(secrets.len(), 1);
        assert_eq!(secrets[0].0, "APP_TOKEN");
    }

    #[test]
    fn pull_secrets_pagination() {
        let mut server = mockito::Server::new();
        let page2_url = format!("{}/secrets?api-version=7.4&skiptoken=p2", server.url());
        let _page1 = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["secret-a"], Some(&page2_url)))
            .create();
        let _page2 = server
            .mock("GET", mockito::Matcher::Regex(r"skiptoken=p2".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["secret-b"], None))
            .create();
        let _get_a = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/secrets/secret-a\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(secret_response("val-a"))
            .create();
        let _get_b = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/secrets/secret-b\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(secret_response("val-b"))
            .create();

        let secrets = pull_secrets(&cfg(&server.url()), &|| Ok("tok".to_string()), None).unwrap();
        assert_eq!(secrets.len(), 2);
        let keys: Vec<&str> = secrets.iter().map(|(k, _)| k.as_str()).collect();
        assert!(keys.contains(&"SECRET_A"));
        assert!(keys.contains(&"SECRET_B"));
    }

    #[test]
    fn get_secret_404_returns_not_found() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["ghost"], None))
            .create();
        let _get = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/secrets/ghost\?".to_string()),
            )
            .with_status(404)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"error":{"code":"SecretNotFound"}}"#)
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok("tok".to_string()), None).unwrap_err();
        assert!(matches!(err, KvError::NotFound(_)));
    }

    #[test]
    fn list_returns_http_error_on_server_fault() {
        let mut server = mockito::Server::new();
        let _m = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets".to_string()))
            .with_status(503)
            .with_body("Service Unavailable")
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok("tok".to_string()), None).unwrap_err();
        assert!(matches!(err, KvError::Http { status: 503, .. }));
    }

    // ── OAuth / network negative paths (Track 5 § C) ─────────────────────────

    /// Token acquisition failure on the pre-fetch refresh (after list completes).
    /// The list page returns one secret; the second acquire_token call fails.
    /// pull_secrets must propagate the error without partially applying secrets.
    #[test]
    fn token_refresh_failure_before_fetch_phase_propagates_error() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let call_count = AtomicUsize::new(0);

        let mut server = mockito::Server::new();
        let _list = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["db-password"], None))
            .create();

        let err = pull_secrets(
            &cfg(&server.url()),
            &|| {
                // First call (during list) succeeds; second call (pre-fetch) fails.
                let n = call_count.fetch_add(1, Ordering::SeqCst);
                if n == 0 {
                    Ok("valid-token".to_string())
                } else {
                    Err(KvError::Auth("token refresh: 401 Unauthorized".into()))
                }
            },
            None,
        )
        .unwrap_err();

        assert!(
            matches!(err, KvError::Auth(_)),
            "expected Auth error, got {err:?}"
        );
    }

    /// Token acquisition failure on the very first list call (page 1).
    #[test]
    fn token_acquisition_failure_on_list_propagates_error() {
        let server = mockito::Server::new();
        // No mock needed — token fails before first HTTP call.
        let err = pull_secrets(
            &cfg(&server.url()),
            &|| Err(KvError::Auth("no credentials".into())),
            None,
        )
        .unwrap_err();
        assert!(matches!(err, KvError::Auth(_)));
    }

    /// Key Vault returns 401 on the list endpoint (expired token passed in).
    #[test]
    fn list_endpoint_401_returns_http_error() {
        let mut server = mockito::Server::new();
        let _m = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(401)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"error":{"code":"Unauthorized","message":"Invalid token"}}"#)
            .create();

        let err =
            pull_secrets(&cfg(&server.url()), &|| Ok("expired-tok".into()), None).unwrap_err();
        assert!(
            matches!(err, KvError::Http { status: 401, .. }),
            "expected Http 401, got {err:?}"
        );
    }

    /// Key Vault returns 401 when fetching a specific secret (token expired mid-pull).
    #[test]
    fn get_secret_401_returns_http_error() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["my-secret"], None))
            .create();
        let _get = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/secrets/my-secret\?".to_string()),
            )
            .with_status(401)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"error":{"code":"Unauthorized"}}"#)
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok("tok".into()), None).unwrap_err();
        assert!(
            matches!(err, KvError::Http { status: 401, .. }),
            "expected Http 401 on get, got {err:?}"
        );
    }

    /// List endpoint returns 200 with body that is not valid JSON.
    #[test]
    fn list_endpoint_malformed_json_returns_transport_error() {
        let mut server = mockito::Server::new();
        let _m = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body("this is not json {{{{")
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok("tok".into()), None).unwrap_err();
        assert!(
            matches!(err, KvError::Transport(_)),
            "expected Transport error on malformed JSON, got {err:?}"
        );
    }

    /// Get-secret endpoint returns 200 with body that is not valid JSON.
    #[test]
    fn get_secret_malformed_json_returns_transport_error() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["broken-secret"], None))
            .create();
        let _get = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/secrets/broken-secret\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body("not valid json")
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok("tok".into()), None).unwrap_err();
        assert!(
            matches!(err, KvError::Transport(_)),
            "expected Transport on malformed get body, got {err:?}"
        );
    }

    /// 429 throttling exhausts MAX_RETRIES and surfaces as Http 429.
    /// Uses `Retry-After: 0` to avoid sleeping in tests.
    #[test]
    fn list_endpoint_429_exhausts_retries_returns_http_error() {
        let mut server = mockito::Server::new();
        // Return 429 on every attempt (MAX_RETRIES + 1 = 4 total calls).
        let _m = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(429)
            .with_header("Retry-After", "0")
            .with_body("Too Many Requests")
            .expect(MAX_RETRIES_429 as usize + 1)
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok("tok".into()), None).unwrap_err();
        assert!(
            matches!(err, KvError::Http { status: 429, .. }),
            "expected Http 429 after retries exhausted, got {err:?}"
        );
    }

    /// The Authorization header sent to Key Vault must carry the token value.
    #[test]
    fn authorization_header_contains_bearer_token() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .match_header("Authorization", "Bearer my-test-token")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"value":[]}"#)
            .create();

        // If the header doesn't match, mockito returns 501 and the mock is not satisfied.
        let result =
            pull_secrets(&cfg(&server.url()), &|| Ok("my-test-token".into()), None).unwrap();
        assert!(result.is_empty());
    }

    /// SSRF guard: nextLink from a foreign origin is silently dropped (no follow).
    #[test]
    fn nextlink_ssrf_guard_drops_foreign_origin_silently() {
        let mut server = mockito::Server::new();
        let malicious_next = "https://evil.example.com/secrets?api-version=7.4";
        let _list = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(format!(r#"{{"value":[],"nextLink":"{malicious_next}"}}"#))
            .create();

        // Should succeed with zero secrets and NOT follow the malicious nextLink.
        let result = pull_secrets(&cfg(&server.url()), &|| Ok("tok".into()), None).unwrap();
        assert!(result.is_empty());
    }

    /// pull_secrets with pagination where token fails on second page's acquire call.
    #[test]
    fn token_refresh_failure_on_pagination_page2_propagates_error() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let call_count = AtomicUsize::new(0);

        let mut server = mockito::Server::new();
        let page2_url = format!("{}/secrets?api-version=7.4&skiptoken=p2", server.url());
        let _page1 = server
            .mock("GET", mockito::Matcher::Regex(r"^/secrets\?".to_string()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["secret-a"], Some(&page2_url)))
            .create();
        // page2 is never hit because the token fails before it

        let err = pull_secrets(
            &cfg(&server.url()),
            &|| {
                let n = call_count.fetch_add(1, Ordering::SeqCst);
                if n == 0 {
                    Ok("good-token".into())
                } else {
                    Err(KvError::Auth("401 on second page token".into()))
                }
            },
            None,
        )
        .unwrap_err();

        assert!(
            matches!(err, KvError::Auth(_)),
            "expected Auth error from page-2 token failure, got {err:?}"
        );
    }
}