tsafe-cli 1.0.26

Secrets runtime for developers — inject credentials into processes via exec, never into shell history or .env files
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! GCP Secret Manager HTTP client.
// `ureq::Error` is large; propagating it through `Result` triggers `clippy::result_large_err`.
#![allow(clippy::result_large_err)]

use super::config::{GcpConfig, GcpToken};
use super::error::GcpError;

/// Outcome of a single `push_secret` call.
#[derive(Debug, PartialEq, Eq)]
pub enum PushOutcome {
    /// The secret did not exist and was created with its first version.
    Created,
    /// The secret already existed and a new version was added.
    Updated,
    /// The secret was unchanged (reserved for callers; push_secret does not return this).
    Unchanged,
    /// The secret was deleted (reserved for callers; push_secret does not return this).
    Deleted,
}

const MAX_RETRIES_429: u32 = 3;
const MAX_RETRIES_TRANSIENT: u32 = 5;
const DEFAULT_RETRY_SECS: u64 = 2;

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

/// Execute an HTTP call with retry on 429 (throttled) responses.
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))
}

fn map_ureq_error(e: ureq::Error, secret_name: Option<&str>) -> GcpError {
    match e {
        ureq::Error::Status(404, _) => GcpError::NotFound(secret_name.unwrap_or("").to_string()),
        ureq::Error::Status(s, resp) => GcpError::Http {
            status: s,
            message: resp
                .into_string()
                .unwrap_or_else(|_| "<unreadable response>".into()),
        },
        other => GcpError::Transport(other.to_string()),
    }
}

/// Normalise a GCP secret name to an environment variable key.
/// Hyphens and dots are replaced with `_`; the result is uppercased.
///
/// GCP secret names may contain letters, digits, hyphens, and underscores.
/// Examples:
///   `my-secret`      → `MY_SECRET`
///   `db.password`    → `DB_PASSWORD`
///   `api_key`        → `API_KEY`
pub fn normalize_name(name: &str) -> String {
    name.replace(['-', '.'], "_").to_uppercase()
}

/// Extract the short secret name from a GCP full resource name.
/// e.g. `projects/my-project/secrets/my-secret` → `my-secret`
fn extract_short_name(full_name: &str) -> &str {
    full_name.split('/').next_back().unwrap_or(full_name)
}

/// Pull secrets from GCP Secret Manager, optionally filtered by `prefix`.
///
/// `get_token` is called once per page during listing and once more before
/// the per-secret access phase, ensuring tokens stay fresh on large vaults.
///
/// Returns `(normalized_key, value)` pairs ready to set in the local vault.
pub fn pull_secrets(
    cfg: &GcpConfig,
    get_token: &impl Fn() -> Result<GcpToken, GcpError>,
    prefix: Option<&str>,
) -> Result<Vec<(String, String)>, GcpError> {
    let names = list_secret_names(cfg, get_token, prefix)?;
    // Refresh token before the per-secret access phase.
    let token = get_token()?;
    let mut secrets = Vec::new();

    for name in &names {
        let value = access_secret(cfg, &token, name)?;
        let key = normalize_name(extract_short_name(name));
        secrets.push((key, value));
    }

    Ok(secrets)
}

/// List all secret names in the project (optionally filtered client-side by prefix).
/// Handles pagination via `nextPageToken`.
fn list_secret_names(
    cfg: &GcpConfig,
    get_token: &impl Fn() -> Result<GcpToken, GcpError>,
    prefix: Option<&str>,
) -> Result<Vec<String>, GcpError> {
    let mut names = Vec::new();
    let mut page_token: Option<String> = None;
    let agent = http_agent();

    loop {
        let token = get_token()?;
        let auth = format!("Bearer {}", token.0);

        // Build URL with optional pageToken
        let mut url = format!(
            "{}/projects/{}/secrets?pageSize=100",
            cfg.endpoint, cfg.project_id
        );
        if let Some(ref pt) = page_token {
            url.push_str("&pageToken=");
            url.push_str(&percent_encode_query_value(pt));
        }

        let url_clone = url.clone();
        let resp: serde_json::Value =
            call_with_retry(|| agent.get(&url_clone).set("Authorization", &auth).call())
                .map_err(|e| map_ureq_error(e, None))?
                .into_json()
                .map_err(|e| GcpError::Transport(e.to_string()))?;

        if let Some(secrets) = resp["secrets"].as_array() {
            for item in secrets {
                if let Some(full_name) = item["name"].as_str() {
                    let short = extract_short_name(full_name);
                    // Client-side prefix filter
                    if let Some(p) = prefix {
                        if !short.to_lowercase().starts_with(&p.to_lowercase()) {
                            continue;
                        }
                    }
                    if !short.is_empty() {
                        names.push(full_name.to_string());
                    }
                }
            }
        }

        page_token = resp["nextPageToken"].as_str().map(|s| s.to_string());
        if page_token.is_none() {
            break;
        }
    }

    Ok(names)
}

fn percent_encode_query_value(value: &str) -> String {
    value
        .bytes()
        .map(|byte| match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                (byte as char).to_string()
            }
            _ => format!("%{byte:02X}"),
        })
        .collect()
}

/// Access the latest version of a secret and return its string value.
/// `name` is the full resource path: `projects/{project}/secrets/{secret}`
fn access_secret(cfg: &GcpConfig, token: &GcpToken, name: &str) -> Result<String, GcpError> {
    let short = extract_short_name(name);
    let url = format!("{}/{name}/versions/latest:access", cfg.endpoint);
    let auth = format!("Bearer {}", token.0);
    let url_clone = url.clone();
    let agent = http_agent();

    let resp: serde_json::Value =
        call_with_retry(|| agent.get(&url_clone).set("Authorization", &auth).call())
            .map_err(|e| map_ureq_error(e, Some(short)))?
            .into_json()
            .map_err(|e| GcpError::Transport(e.to_string()))?;

    // payload.data is base64-encoded
    let b64 = resp["payload"]["data"]
        .as_str()
        .ok_or_else(|| GcpError::NotFound(short.to_string()))?;

    decode_secret_data(b64, short)
}

fn decode_secret_data(b64: &str, name: &str) -> Result<String, GcpError> {
    // GCP uses standard base64 (with padding)
    let bytes = base64_decode(b64)
        .map_err(|e| GcpError::Transport(format!("base64 decode failed for '{name}': {e}")))?;
    String::from_utf8(bytes).map_err(|_| {
        GcpError::NotFound(format!(
            "{name} — payload is not valid UTF-8 (binary secret not supported)"
        ))
    })
}

// ── write path ────────────────────────────────────────────────────────────────

/// Push a secret to GCP Secret Manager.
///
/// Two-call pattern:
/// 1. Check if the secret exists (`GET /projects/{project}/secrets/{name}`).
///    - 200 → secret exists → skip creation, go directly to version-add.
///    - 404 → secret is new → create the secret resource, then add the first version.
/// 2. Add a new version (`POST /projects/{project}/secrets/{name}/versions:add`).
///    The value is base64-encoded in `payload.data` per the Secret Manager API.
///
/// Partial-failure handling: if the secret resource is created but the
/// subsequent version-add call fails, a `tracing::warn!` audit note is emitted
/// (the secret exists with no versions) and an error is returned.  Re-running
/// `gcp-push` is safe — the existence check will find the now-present resource
/// and skip the create call on the next attempt.
#[tracing::instrument(skip(cfg, get_token, value), fields(name = %name))]
pub fn push_secret(
    cfg: &GcpConfig,
    get_token: &impl Fn() -> Result<GcpToken, GcpError>,
    name: &str,
    value: &str,
) -> Result<PushOutcome, GcpError> {
    let token = get_token()?;
    let agent = http_agent();
    let auth = format!("Bearer {}", token.0);

    // ── 1. Check for existence ────────────────────────────────────────────────
    let exists = check_secret_exists(cfg, &agent, &auth, name)?;

    // ── 2. Create secret resource if absent ───────────────────────────────────
    if !exists {
        create_secret_resource(cfg, &agent, &auth, name)?;
    }

    // ── 3. Add a new version (the actual secret value) ────────────────────────
    let add_result = add_secret_version(cfg, &agent, &auth, name, value);
    if let Err(ref e) = add_result {
        if !exists {
            // Secret resource was just created but version-add failed.
            // Log partial-failure so the operator knows the resource exists but
            // is empty (no versions).  A subsequent push is idempotent.
            tracing::warn!(
                secret_name = %name,
                error = %e,
                "partial-failure: secret resource created but version-add failed; \
                 secret has no versions — re-run gcp-push to recover"
            );
        }
        return add_result.map(|_| PushOutcome::Created); // unreachable but satisfies type
    }

    if exists {
        Ok(PushOutcome::Updated)
    } else {
        Ok(PushOutcome::Created)
    }
}

/// Returns `true` if the secret resource already exists in Secret Manager.
fn check_secret_exists(
    cfg: &GcpConfig,
    agent: &ureq::Agent,
    auth: &str,
    name: &str,
) -> Result<bool, GcpError> {
    let url = format!(
        "{}/projects/{}/secrets/{}",
        cfg.endpoint, cfg.project_id, name
    );
    let url_clone = url.clone();
    match call_with_retry(|| agent.get(&url_clone).set("Authorization", auth).call()) {
        Ok(_) => Ok(true),
        Err(ureq::Error::Status(404, _)) => Ok(false),
        Err(e) => Err(map_ureq_error(e, Some(name))),
    }
}

/// Create a new secret resource (without any version data).
fn create_secret_resource(
    cfg: &GcpConfig,
    agent: &ureq::Agent,
    auth: &str,
    name: &str,
) -> Result<(), GcpError> {
    let url = format!(
        "{}/projects/{}/secrets?secretId={}",
        cfg.endpoint, cfg.project_id, name
    );
    let body = serde_json::json!({
        "replication": { "automatic": {} }
    });
    let url_clone = url.clone();
    let body_str = body.to_string();
    call_with_retry(|| {
        agent
            .post(&url_clone)
            .set("Authorization", auth)
            .set("Content-Type", "application/json")
            .send_string(&body_str)
    })
    .map_err(|e| map_ureq_error(e, Some(name)))?;
    Ok(())
}

/// Add a new version of a secret with the given plaintext value.
/// The value is base64-encoded per the Secret Manager API requirement.
fn add_secret_version(
    cfg: &GcpConfig,
    agent: &ureq::Agent,
    auth: &str,
    name: &str,
    value: &str,
) -> Result<(), GcpError> {
    let url = format!(
        "{}/projects/{}/secrets/{}/versions:add",
        cfg.endpoint, cfg.project_id, name
    );
    let b64_value = base64_encode(value.as_bytes());
    let body = serde_json::json!({
        "payload": { "data": b64_value }
    });
    let url_clone = url.clone();
    let body_str = body.to_string();
    call_with_retry(|| {
        agent
            .post(&url_clone)
            .set("Authorization", auth)
            .set("Content-Type", "application/json")
            .send_string(&body_str)
    })
    .map_err(|e| map_ureq_error(e, Some(name)))?;
    Ok(())
}

/// Standard base64 encoder (no external dep — pairs with `base64_decode`).
pub(crate) fn base64_encode(data: &[u8]) -> String {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::new();
    let mut i = 0;
    while i < data.len() {
        let b0 = data[i] as u32;
        let b1 = if i + 1 < data.len() {
            data[i + 1] as u32
        } else {
            0
        };
        let b2 = if i + 2 < data.len() {
            data[i + 2] as u32
        } else {
            0
        };
        out.push(CHARS[((b0 >> 2) & 0x3F) as usize] as char);
        out.push(CHARS[(((b0 << 4) | (b1 >> 4)) & 0x3F) as usize] as char);
        out.push(if i + 1 < data.len() {
            CHARS[(((b1 << 2) | (b2 >> 6)) & 0x3F) as usize] as char
        } else {
            '='
        });
        out.push(if i + 2 < data.len() {
            CHARS[(b2 & 0x3F) as usize] as char
        } else {
            '='
        });
        i += 3;
    }
    out
}

/// Minimal base64 standard decoder (no external dep — avoids pulling in the workspace `base64`
/// dep which uses a different API version than expected here).
fn base64_decode(s: &str) -> Result<Vec<u8>, String> {
    // Strip padding and build alphabet lookup
    let s = s.trim_end_matches('=');
    if s.len() % 4 == 1 {
        return Err("invalid base64 length".into());
    }
    let mut out = Vec::with_capacity(s.len() * 3 / 4 + 1);
    let mut buf = 0u32;
    let mut bits = 0u32;

    for ch in s.bytes() {
        let v = match ch {
            b'A'..=b'Z' => (ch - b'A') as u32,
            b'a'..=b'z' => (ch - b'a' + 26) as u32,
            b'0'..=b'9' => (ch - b'0' + 52) as u32,
            b'+' => 62,
            b'/' => 63,
            _ => return Err(format!("invalid base64 char: {}", ch as char)),
        };
        buf = (buf << 6) | v;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push(((buf >> bits) & 0xFF) as u8);
        }
    }

    Ok(out)
}

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

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

    fn cfg(url: &str) -> GcpConfig {
        // endpoint is the base — we append /v1 in config; tests pass full base
        GcpConfig::with_endpoint("test-project", format!("{url}/v1"))
    }

    fn test_token() -> GcpToken {
        GcpToken("test-token".into())
    }

    fn list_response(names: &[&str], next_token: Option<&str>) -> String {
        let items: Vec<String> = names
            .iter()
            .map(|n| format!(r#"{{"name":"projects/test-project/secrets/{n}"}}"#))
            .collect();
        match next_token {
            Some(tok) => format!(
                r#"{{"secrets":[{}],"nextPageToken":"{tok}"}}"#,
                items.join(",")
            ),
            None => format!(r#"{{"secrets":[{}]}}"#, items.join(",")),
        }
    }

    fn access_response(value: &str) -> String {
        // GCP returns base64-encoded data
        let b64 = base64_encode(value.as_bytes());
        format!(
            r#"{{"name":"projects/test-project/secrets/my-secret/versions/1","payload":{{"data":"{b64}"}}}}"#
        )
    }

    // ── pure-logic tests ──────────────────────────────────────────────────────

    #[test]
    fn normalize_name_hyphens() {
        assert_eq!(normalize_name("my-secret"), "MY_SECRET");
    }

    #[test]
    fn normalize_name_dots() {
        assert_eq!(normalize_name("db.password"), "DB_PASSWORD");
    }

    #[test]
    fn normalize_name_underscores_preserved() {
        assert_eq!(normalize_name("api_key"), "API_KEY");
    }

    #[test]
    fn percent_encode_query_value_escapes_reserved_bytes() {
        assert_eq!(
            percent_encode_query_value("tok/with+=reserved"),
            "tok%2Fwith%2B%3Dreserved"
        );
    }

    #[test]
    fn extract_short_name_from_full_path() {
        assert_eq!(
            extract_short_name("projects/my-project/secrets/my-secret"),
            "my-secret"
        );
    }

    #[test]
    fn extract_short_name_passthrough_for_plain_name() {
        assert_eq!(extract_short_name("my-secret"), "my-secret");
    }

    #[test]
    fn base64_decode_hello() {
        let encoded = "aGVsbG8="; // "hello"
        let bytes = base64_decode(encoded).unwrap();
        assert_eq!(String::from_utf8(bytes).unwrap(), "hello");
    }

    #[test]
    fn base64_decode_no_padding() {
        // "hello" without padding
        let bytes = base64_decode("aGVsbG8").unwrap();
        assert_eq!(String::from_utf8(bytes).unwrap(), "hello");
    }

    #[test]
    fn base64_decode_empty() {
        assert!(base64_decode("").unwrap().is_empty());
    }

    #[test]
    fn base64_decode_rejects_impossible_length() {
        let err = base64_decode("a").unwrap_err();
        assert!(err.contains("invalid base64 length"));
    }

    #[test]
    fn base64_roundtrip() {
        let original = "s3cr3t-v@lue!";
        let encoded = base64_encode(original.as_bytes());
        let decoded = base64_decode(&encoded).unwrap();
        assert_eq!(String::from_utf8(decoded).unwrap(), original);
    }

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

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

        let result = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), 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"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["my-db-password"], None))
            .create();
        let _access = server
            .mock(
                "GET",
                mockito::Matcher::Regex(
                    r"^/v1/projects/test-project/secrets/my-db-password/versions/latest:access"
                        .to_string(),
                ),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(access_response("s3cr3t"))
            .create();

        let secrets = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), 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_pagination() {
        let mut server = mockito::Server::new();
        let _page1 = server
            .mock(
                "GET",
                mockito::Matcher::Regex(
                    r"^/v1/projects/test-project/secrets\?pageSize".to_string(),
                ),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["secret-a"], Some("page2-tok")))
            .expect(1)
            .create();
        let _page2 = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"pageToken=page2-tok".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["secret-b"], None))
            .expect(1)
            .create();
        let _acc = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"versions/latest:access".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(access_response("val"))
            .expect(2)
            .create();

        let secrets = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), 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 pull_secrets_prefix_filter() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["app-token", "db-password"], None))
            .create();
        let _acc = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"app-token/versions/latest:access".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(access_response("tok-xyz"))
            .create();

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

    #[test]
    fn pull_secrets_prefix_filter_is_case_insensitive() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["App-Token", "db-password"], None))
            .create();
        let _acc = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"App-Token/versions/latest:access".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(access_response("tok-xyz"))
            .expect(1)
            .create();

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

    #[test]
    fn pull_secrets_404_returns_not_found() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["ghost"], None))
            .create();
        let _acc = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"ghost/versions/latest:access".to_string()),
            )
            .with_status(404)
            .with_body(
                r#"{"error":{"code":404,"message":"Secret not found","status":"NOT_FOUND"}}"#,
            )
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), None).unwrap_err();
        assert!(
            matches!(err, GcpError::NotFound(_)),
            "expected NotFound, got {err:?}"
        );
    }

    #[test]
    fn pull_secrets_403_returns_http_error() {
        let mut server = mockito::Server::new();
        let _m = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets".to_string()),
            )
            .with_status(403)
            .with_body(r#"{"error":{"code":403,"message":"Permission denied","status":"PERMISSION_DENIED"}}"#)
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), None).unwrap_err();
        assert!(
            matches!(err, GcpError::Http { status: 403, .. }),
            "expected Http 403, got {err:?}"
        );
    }

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

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

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

        let err = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), None).unwrap_err();
        assert!(matches!(err, GcpError::Transport(_)));
    }

    #[test]
    fn pull_secrets_malformed_access_json_returns_transport_error() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["my-secret"], None))
            .create();
        let _acc = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"my-secret/versions/latest:access".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body("not json")
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), None).unwrap_err();
        assert!(matches!(err, GcpError::Transport(_)));
    }

    #[test]
    fn access_invalid_base64_payload_returns_transport_error() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["bad-b64"], None))
            .create();
        let _acc = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"bad-b64/versions/latest:access".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"payload":{"data":"a"}}"#)
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), None).unwrap_err();
        assert!(
            matches!(err, GcpError::Transport(ref msg) if msg.contains("base64 decode failed")),
            "expected base64 transport error, got {err:?}"
        );
    }

    #[test]
    fn access_binary_payload_returns_not_found() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["binary-secret"], None))
            .create();
        let _acc = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"binary-secret/versions/latest:access".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"payload":{"data":"//8="}}"#)
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), None).unwrap_err();
        assert!(
            matches!(err, GcpError::NotFound(ref msg) if msg.contains("payload is not valid UTF-8")),
            "expected non-UTF-8 payload error, got {err:?}"
        );
    }

    #[test]
    fn pull_secrets_429_exhausts_retries_returns_http_error() {
        let mut server = mockito::Server::new();
        let _m = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/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(test_token()), None).unwrap_err();
        assert!(matches!(err, GcpError::Http { status: 429, .. }));
    }

    #[test]
    fn token_refresh_failure_before_access_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"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["my-secret"], None))
            .create();

        let err = pull_secrets(
            &cfg(&server.url()),
            &|| {
                let n = call_count.fetch_add(1, Ordering::SeqCst);
                if n == 0 {
                    Ok(test_token())
                } else {
                    Err(GcpError::Auth("token expired".into()))
                }
            },
            None,
        )
        .unwrap_err();

        assert!(
            matches!(err, GcpError::Auth(_)),
            "expected Auth error on token refresh, got {err:?}"
        );
    }

    #[test]
    fn token_failure_on_first_list_call_propagates_error() {
        let server = mockito::Server::new();
        let err = pull_secrets(
            &cfg(&server.url()),
            &|| Err(GcpError::Auth("no credentials".into())),
            None,
        )
        .unwrap_err();
        assert!(matches!(err, GcpError::Auth(_)));
    }

    #[test]
    fn access_missing_payload_returns_not_found() {
        let mut server = mockito::Server::new();
        let _list = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(list_response(&["partial-secret"], None))
            .create();
        let _acc = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"partial-secret/versions/latest:access".to_string()),
            )
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"name":"...","payload":{}}"#) // no 'data' field
            .create();

        let err = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), None).unwrap_err();
        assert!(
            matches!(err, GcpError::NotFound(_)),
            "missing payload.data should return NotFound, got {err:?}"
        );
    }

    #[test]
    fn authorization_header_contains_bearer_token() {
        let mut server = mockito::Server::new();
        let _m = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/v1/projects/test-project/secrets\?".to_string()),
            )
            .match_header("Authorization", "Bearer test-token")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"secrets":[]}"#)
            .create();

        let result = pull_secrets(&cfg(&server.url()), &|| Ok(test_token()), None).unwrap();
        assert!(result.is_empty());
    }
    #[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("permission denied"));
    }

    #[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));
    }
}