hasp-backend-vault 0.2.0-alpha

vault:// backend for hasp — HashiCorp Vault KV HTTP client.
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
//! `vault://` backend for hasp.
//!
//! Grammar: `vault://<mount>/<path>?field=<key>`
//!   - `<mount>`  — Vault secrets engine mount point (host component).
//!   - `<path>`   — secret path within the mount, including KV-v2 `data/`
//!     prefix when applicable.
//!   - `?field=`  — optional key to extract from the JSON `data.data`
//!     object. When absent, the entire object is serialized.
//!
//! Supported operations: `get`, `put`, `list`, `delete`, `exists`.
//!
//! `put` semantics:
//! - Without `?field=`: the value must be valid JSON and replaces the entire
//!   `data.data` object. Symmetric with `get` without `?field=`, which
//!   serializes the whole object.
//! - With `?field=`: performs read-modify-write. Creates the secret if
//!   absent. Non-JSON values are stored as JSON strings. This is optimistic:
//!   no CAS, so concurrent writes are last-write-wins.
//!
//! Authentication is ambient only: `VAULT_ADDR` and `VAULT_TOKEN`.
//! If either is missing, every operation fails fast with
//! `AuthenticationFailed` before any network request, preventing
//! indefinite connection attempts against an undefined endpoint.
//!
//! Vault's HTTP API intentionally collapses 403 and 404 to prevent
//! existence oracles. This backend follows that choice: both map to
//! `NotFound` on `get` and to `false` on `exists`.

use hasp_core::{
    Backend, BackendFailureKind, Entry, Error, ExposeSecret, ProxyConfig, SecretString,
};
use std::time::Duration;
use url::Url;

/// URL shape for `vault://` addresses.
///
/// `mount`, `path`, and `field` are identifiers, not secret values.
/// They may appear in error messages (redacted per URL discipline).
#[derive(Debug)]
pub struct VaultUrl {
    pub mount: String,
    pub path: String,
    pub field: Option<String>,
}

impl TryFrom<&Url> for VaultUrl {
    type Error = Error;

    fn try_from(url: &Url) -> Result<Self, Self::Error> {
        if url.scheme() != "vault" {
            return Err(Error::InvalidUrl("expected vault:// scheme".into()));
        }

        let mount = url
            .host_str()
            .ok_or_else(|| Error::InvalidUrl("vault:// requires a mount point (host)".into()))?
            .to_owned();
        if mount.is_empty() {
            return Err(Error::InvalidUrl("vault:// mount must not be empty".into()));
        }

        let path = url.path().to_owned();

        let mut field = None;
        for (k, v) in url.query_pairs() {
            if k == "field" {
                field = Some(v.into_owned());
            } else {
                return Err(Error::InvalidUrl(format!(
                    "vault:// unknown query parameter: {k}"
                )));
            }
        }

        Ok(VaultUrl { mount, path, field })
    }
}

/// HTTP backend for HashiCorp Vault.
///
/// Construction is a no-op; errors surface on first use. Every request
/// builds a fresh `reqwest::blocking::Client` so the backend remains
/// lightweight.
#[derive(Debug)]
pub struct VaultBackend {
    proxy: Option<ProxyConfig>,
}

impl VaultBackend {
    /// Create a new `VaultBackend`.
    pub fn new() -> Self {
        Self::with_proxy(None)
    }

    /// Create a new `VaultBackend` with an explicit HTTP CONNECT proxy.
    pub fn with_proxy(proxy: Option<ProxyConfig>) -> Self {
        Self { proxy }
    }
}

impl Default for VaultBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl Backend for VaultBackend {
    fn scheme(&self) -> &'static str {
        "vault"
    }

    fn validate(&self, url: &Url) -> Result<(), Error> {
        VaultUrl::try_from(url).map(|_| ())
    }

    fn get(&self, url: &Url) -> Result<SecretString, Error> {
        check_ambient_credentials()?;
        let vault_url = VaultUrl::try_from(url)?;
        let (token, addr) = ambient_credentials()?;
        let request_url = build_request_url(&addr, &vault_url.mount, &vault_url.path);

        let client = build_client(self.proxy.as_ref())?;
        let response = client
            .get(&request_url)
            .header("X-Vault-Token", token)
            .send()
            .map_err(map_reqwest_error)?;

        let status = response.status();
        if status != reqwest::StatusCode::OK {
            return Err(map_vault_status(status, url));
        }

        let body: serde_json::Value = response.json().map_err(|e| Error::Backend {
            scheme: "vault",
            kind: BackendFailureKind::Permanent,
            message: format!("invalid JSON from Vault: {e}"),
        })?;

        extract_secret(&body, vault_url.field.as_deref())
    }

    fn put(&self, url: &Url, value: &SecretString) -> Result<(), Error> {
        check_ambient_credentials()?;
        let vault_url = VaultUrl::try_from(url)?;
        let (token, addr) = ambient_credentials()?;
        let request_url = build_request_url(&addr, &vault_url.mount, &vault_url.path);

        let client = build_client(self.proxy.as_ref())?;

        let data = if let Some(ref field) = vault_url.field {
            // Read-modify-write: optimistic, no CAS.
            let get_resp = client
                .get(&request_url)
                .header("X-Vault-Token", &token)
                .send()
                .map_err(map_reqwest_error)?;

            let mut obj = match get_resp.status() {
                reqwest::StatusCode::OK => {
                    let body: serde_json::Value = get_resp.json().map_err(|e| Error::Backend {
                        scheme: "vault",
                        kind: BackendFailureKind::Permanent,
                        message: format!("invalid JSON from Vault: {e}"),
                    })?;
                    body.get("data")
                        .and_then(|d| d.get("data"))
                        .cloned()
                        .unwrap_or_else(|| serde_json::json!({}))
                }
                reqwest::StatusCode::FORBIDDEN | reqwest::StatusCode::NOT_FOUND => {
                    serde_json::json!({})
                }
                status => return Err(map_vault_status(status, url)),
            };

            let json_value = serde_json::from_str(value.expose_secret())
                .unwrap_or_else(|_| serde_json::Value::String(value.expose_secret().to_owned()));

            if let Some(map) = obj.as_object_mut() {
                map.insert(field.clone(), json_value);
            } else {
                return Err(Error::Backend {
                    scheme: "vault",
                    kind: BackendFailureKind::Permanent,
                    message: "Vault secret data is not a JSON object; cannot update field".into(),
                });
            }
            obj
        } else {
            serde_json::from_str(value.expose_secret()).map_err(|e| {
                Error::InvalidUrl(format!("vault:// put value must be valid JSON: {e}"))
            })?
        };

        let body = serde_json::json!({ "data": data });

        let post_resp = client
            .post(&request_url)
            .header("X-Vault-Token", &token)
            .json(&body)
            .send()
            .map_err(map_reqwest_error)?;

        match post_resp.status() {
            reqwest::StatusCode::OK | reqwest::StatusCode::NO_CONTENT => Ok(()),
            status => Err(map_vault_status(status, url)),
        }
    }

    fn list(&self, url: &Url) -> Result<Vec<Entry>, Error> {
        check_ambient_credentials()?;
        let vault_url = VaultUrl::try_from(url)?;
        let (token, addr) = ambient_credentials()?;

        // Convert the URL path into a metadata list prefix.
        // KV v2 paths like /data/myapp/config become myapp (parent dir)
        // for the LIST /v1/{mount}/metadata/{prefix} endpoint.
        let path_str = vault_url.path.trim_start_matches('/');
        let prefix = if let Some(after_data) = path_str.strip_prefix("data/") {
            after_data
                .rfind('/')
                .map(|i| &after_data[..i])
                .unwrap_or("")
        } else {
            path_str.rfind('/').map(|i| &path_str[..i]).unwrap_or("")
        };

        let metadata_path = if prefix.is_empty() {
            "/metadata".into()
        } else {
            format!("/metadata/{prefix}")
        };

        let request_url = build_request_url(&addr, &vault_url.mount, &metadata_path);

        let client = build_client(self.proxy.as_ref())?;
        let response = client
            .request(
                reqwest::Method::from_bytes(b"LIST").expect("LIST is a valid HTTP method"),
                &request_url,
            )
            .header("X-Vault-Token", &token)
            .send()
            .map_err(map_reqwest_error)?;

        let status = response.status();
        if status != reqwest::StatusCode::OK {
            return Err(map_vault_status(status, url));
        }

        let body: serde_json::Value = response.json().map_err(|e| Error::Backend {
            scheme: "vault",
            kind: BackendFailureKind::Permanent,
            message: format!("invalid JSON from Vault: {e}"),
        })?;

        let keys = body
            .get("data")
            .and_then(|d| d.get("keys"))
            .and_then(|k| k.as_array())
            .ok_or_else(|| Error::Backend {
                scheme: "vault",
                kind: BackendFailureKind::Permanent,
                message: "Vault LIST response missing data.keys field".into(),
            })?;

        let mut entries = Vec::new();
        for key in keys {
            let name = key.as_str().unwrap_or("").trim_end_matches('/').to_owned();
            if name.is_empty() {
                continue;
            }

            // Reconstruct a canonical vault:// URL.  List entries are
            // whole secrets, so strip any ?field= from the original URL.
            let entry_url = if vault_url.path.starts_with("/data/") {
                let base_path = vault_url.path.trim_start_matches("/data/");
                let parent = base_path.rfind('/').map(|i| &base_path[..i]).unwrap_or("");
                if parent.is_empty() {
                    format!("vault://{}/data/{name}", vault_url.mount)
                } else {
                    format!("vault://{}/data/{}/{name}", vault_url.mount, parent)
                }
            } else {
                format!("vault://{}/{name}", vault_url.mount)
            };

            let parsed = Url::parse(&entry_url).map_err(|e| Error::Backend {
                scheme: "vault",
                kind: BackendFailureKind::Permanent,
                message: format!("failed to parse list entry URL: {e}"),
            })?;

            entries.push(Entry { name, url: parsed });
        }

        Ok(entries)
    }

    fn delete(&self, url: &Url) -> Result<(), Error> {
        check_ambient_credentials()?;
        let vault_url = VaultUrl::try_from(url)?;
        let (token, addr) = ambient_credentials()?;
        let request_url = build_request_url(&addr, &vault_url.mount, &vault_url.path);

        let client = build_client(self.proxy.as_ref())?;
        let response = client
            .delete(&request_url)
            .header("X-Vault-Token", &token)
            .send()
            .map_err(map_reqwest_error)?;

        match response.status() {
            reqwest::StatusCode::NO_CONTENT => Ok(()),
            status => Err(map_vault_status(status, url)),
        }
    }

    fn exists(&self, url: &Url) -> Result<bool, Error> {
        check_ambient_credentials()?;
        let vault_url = VaultUrl::try_from(url)?;
        let (token, addr) = ambient_credentials()?;
        let request_url = build_request_url(&addr, &vault_url.mount, &vault_url.path);

        let client = build_client(self.proxy.as_ref())?;
        let response = client
            .get(&request_url)
            .header("X-Vault-Token", token)
            .send()
            .map_err(map_reqwest_error)?;

        match response.status() {
            reqwest::StatusCode::OK => Ok(true),
            reqwest::StatusCode::FORBIDDEN | reqwest::StatusCode::NOT_FOUND => Ok(false),
            status => Err(map_vault_status(status, url)),
        }
    }
}

/// Build a `reqwest::blocking::Client` with an optional proxy and a
/// 10-second timeout.
fn build_client(proxy: Option<&ProxyConfig>) -> Result<reqwest::blocking::Client, Error> {
    let mut builder = reqwest::blocking::Client::builder().timeout(Duration::from_secs(10));

    if let Some(p) = proxy {
        let reqwest_proxy =
            reqwest::Proxy::all(p.url_without_credentials()).map_err(|e| Error::Backend {
                scheme: "vault",
                kind: BackendFailureKind::Permanent,
                message: format!("invalid proxy URL: {e}"),
            })?;
        builder = builder.proxy(reqwest_proxy);
    }

    builder.build().map_err(|e| Error::Backend {
        scheme: "vault",
        kind: BackendFailureKind::Permanent,
        message: format!("failed to build HTTP client: {e}"),
    })
}

/// Return the ambient Vault address and token.
///
/// Fails with `AuthenticationFailed` if either variable is missing.
fn ambient_credentials() -> Result<(String, String), Error> {
    let token = std::env::var("VAULT_TOKEN").map_err(|_| {
        Error::AuthenticationFailed("no ambient Vault credentials; set VAULT_TOKEN".into())
    })?;
    let addr = std::env::var("VAULT_ADDR").map_err(|_| {
        Error::AuthenticationFailed("no ambient Vault address; set VAULT_ADDR".into())
    })?;
    Ok((token, addr))
}

/// Fail fast if no ambient Vault credentials are present.
fn check_ambient_credentials() -> Result<(), Error> {
    ambient_credentials().map(|_| ())
}

/// Construct the full Vault API URL.
///
/// Trims trailing slashes from `addr` and appends `/v1/<mount><path>`.
fn build_request_url(addr: &str, mount: &str, path: &str) -> String {
    format!("{}/v1/{}{path}", addr.trim_end_matches('/'), mount)
}

/// Map `reqwest` network errors into the locked `hasp_core::Error` taxonomy.
///
/// Timeouts and connection failures are `Transient`; everything else is
/// `Permanent`.
fn map_reqwest_error(err: reqwest::Error) -> Error {
    if err.is_timeout() || err.is_connect() {
        Error::Backend {
            scheme: "vault",
            kind: BackendFailureKind::Transient,
            message: format!("Vault request failed: {err}"),
        }
    } else {
        Error::Backend {
            scheme: "vault",
            kind: BackendFailureKind::Permanent,
            message: format!("Vault request failed: {err}"),
        }
    }
}

/// Map Vault HTTP status codes into the locked `hasp_core::Error` taxonomy.
///
/// 403 and 404 both map to `NotFound` per Vault's intentional
/// collapse of permission-denied and not-found.
fn map_vault_status(status: reqwest::StatusCode, url: &Url) -> Error {
    match status {
        reqwest::StatusCode::FORBIDDEN | reqwest::StatusCode::NOT_FOUND => {
            Error::NotFound(url.to_string())
        }
        reqwest::StatusCode::TOO_MANY_REQUESTS => Error::Backend {
            scheme: "vault",
            kind: BackendFailureKind::Throttled,
            message: format!("Vault returned HTTP {status}"),
        },
        status if status.is_server_error() => Error::Backend {
            scheme: "vault",
            kind: BackendFailureKind::Transient,
            message: format!("Vault returned HTTP {status}"),
        },
        status => Error::Backend {
            scheme: "vault",
            kind: BackendFailureKind::Permanent,
            message: format!("Vault returned HTTP {status}"),
        },
    }
}

/// Extract the secret value from a Vault KV read response.
///
/// Locates `data.data` then either extracts the named `field` via the
/// shared `hasp_core::extract_field` (supports dotted paths) or
/// serializes the entire object. Secret values are wrapped in
/// `SecretString` at this boundary.
fn extract_secret(body: &serde_json::Value, field: Option<&str>) -> Result<SecretString, Error> {
    let data = body
        .get("data")
        .and_then(|d| d.get("data"))
        .ok_or_else(|| Error::Backend {
            scheme: "vault",
            kind: BackendFailureKind::Permanent,
            message: "Vault response missing data.data field".into(),
        })?;

    let value = match field {
        Some(f) => hasp_core::extract_field(data, f)?,
        None => data.to_string(),
    };

    Ok(SecretString::new(value.into()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use hasp_core::test_utils::{EnvGuard, ENV_LOCK};
    use hasp_core::ExposeSecret;

    #[test]
    fn parse_valid_url_with_field() {
        let url = Url::parse("vault://secret/data/myapp/config?field=password").unwrap();
        let v = VaultUrl::try_from(&url).unwrap();
        assert_eq!(v.mount, "secret");
        assert_eq!(v.path, "/data/myapp/config");
        assert_eq!(v.field, Some("password".into()));
    }

    #[test]
    fn parse_valid_url_without_field() {
        let url = Url::parse("vault://kv/data/prod/db").unwrap();
        let v = VaultUrl::try_from(&url).unwrap();
        assert_eq!(v.mount, "kv");
        assert_eq!(v.path, "/data/prod/db");
        assert_eq!(v.field, None);
    }

    #[test]
    fn parse_valid_url_root_path() {
        let url = Url::parse("vault://secret/").unwrap();
        let v = VaultUrl::try_from(&url).unwrap();
        assert_eq!(v.mount, "secret");
        assert_eq!(v.path, "/");
        assert_eq!(v.field, None);
    }

    #[test]
    fn parse_missing_host_fails() {
        let url = Url::parse("vault:///data/myapp/config").unwrap();
        assert!(VaultUrl::try_from(&url).is_err());
    }

    #[test]
    fn parse_empty_mount_fails() {
        let url = Url::parse("vault:///").unwrap();
        assert!(VaultUrl::try_from(&url).is_err());
    }

    #[test]
    fn parse_unknown_query_fails() {
        let url = Url::parse("vault://secret/data/app?raw=true").unwrap();
        assert!(VaultUrl::try_from(&url).is_err());
    }

    #[test]
    fn error_map_403_to_not_found() {
        let url = Url::parse("vault://secret/data/myapp/config").unwrap();
        let err = map_vault_status(reqwest::StatusCode::FORBIDDEN, &url);
        assert!(matches!(err, Error::NotFound(ref s) if s == "vault://secret/data/myapp/config"));
    }

    #[test]
    fn error_map_404_to_not_found() {
        let url = Url::parse("vault://secret/data/myapp/config").unwrap();
        let err = map_vault_status(reqwest::StatusCode::NOT_FOUND, &url);
        assert!(matches!(err, Error::NotFound(_)));
    }

    #[test]
    fn error_map_429_to_throttled() {
        let url = Url::parse("vault://secret/data/myapp/config").unwrap();
        let err = map_vault_status(reqwest::StatusCode::TOO_MANY_REQUESTS, &url);
        assert!(matches!(
            err,
            Error::Backend {
                kind: BackendFailureKind::Throttled,
                ..
            }
        ));
    }

    #[test]
    fn error_map_500_to_transient() {
        let url = Url::parse("vault://secret/data/myapp/config").unwrap();
        let err = map_vault_status(reqwest::StatusCode::INTERNAL_SERVER_ERROR, &url);
        assert!(matches!(
            err,
            Error::Backend {
                kind: BackendFailureKind::Transient,
                ..
            }
        ));
    }

    #[test]
    fn error_map_418_to_permanent() {
        let url = Url::parse("vault://secret/data/myapp/config").unwrap();
        let err = map_vault_status(reqwest::StatusCode::IM_A_TEAPOT, &url);
        assert!(matches!(
            err,
            Error::Backend {
                kind: BackendFailureKind::Permanent,
                ..
            }
        ));
    }

    #[test]
    fn extract_field_found() {
        let body = serde_json::json!({
            "data": {
                "data": {
                    "password": "secret123"
                }
            }
        });
        let secret = extract_secret(&body, Some("password")).unwrap();
        assert_eq!(secret.expose_secret(), "secret123");
    }

    #[test]
    fn extract_field_as_number_returns_stringified() {
        let body = serde_json::json!({
            "data": {
                "data": {
                    "count": 42
                }
            }
        });
        let secret = extract_secret(&body, Some("count")).unwrap();
        assert_eq!(secret.expose_secret(), "42");
    }

    #[test]
    fn extract_field_missing() {
        let body = serde_json::json!({
            "data": {
                "data": {
                    "password": "secret123"
                }
            }
        });
        let err = extract_secret(&body, Some("missing")).unwrap_err();
        assert!(matches!(err, Error::NotFound(_)));
    }

    #[test]
    fn extract_field_dotted_path_into_nested_object() {
        let body = serde_json::json!({
            "data": {
                "data": {
                    "credentials": { "api_key": "ak-xyz" }
                }
            }
        });
        let secret = extract_secret(&body, Some(".credentials.api_key")).unwrap();
        assert_eq!(secret.expose_secret(), "ak-xyz");
    }

    #[test]
    fn extract_no_field_returns_json() {
        let body = serde_json::json!({
            "data": {
                "data": {
                    "password": "secret123"
                }
            }
        });
        let secret = extract_secret(&body, None).unwrap();
        assert_eq!(secret.expose_secret(), r#"{"password":"secret123"}"#);
    }

    #[test]
    fn extract_missing_data_data() {
        let body = serde_json::json!({ "data": {} });
        let err = extract_secret(&body, Some("password")).unwrap_err();
        assert!(matches!(err, Error::Backend { .. }));
    }

    #[test]
    fn preflight_auth_no_token_fails_fast() {
        let _lock = ENV_LOCK.lock().unwrap();

        let old_token = std::env::var("VAULT_TOKEN").ok();
        let old_addr = std::env::var("VAULT_ADDR").ok();
        std::env::remove_var("VAULT_TOKEN");
        std::env::remove_var("VAULT_ADDR");

        let result = check_ambient_credentials();

        match old_token {
            Some(v) => std::env::set_var("VAULT_TOKEN", v),
            None => std::env::remove_var("VAULT_TOKEN"),
        }
        match old_addr {
            Some(v) => std::env::set_var("VAULT_ADDR", v),
            None => std::env::remove_var("VAULT_ADDR"),
        }

        assert!(
            matches!(result, Err(Error::AuthenticationFailed(_))),
            "expected AuthenticationFailed when no ambient credentials are present"
        );
    }

    #[test]
    fn preflight_auth_token_no_addr_fails_fast() {
        let _lock = ENV_LOCK.lock().unwrap();

        let old_token = std::env::var("VAULT_TOKEN").ok();
        let old_addr = std::env::var("VAULT_ADDR").ok();
        std::env::remove_var("VAULT_TOKEN");
        std::env::remove_var("VAULT_ADDR");

        let _guard = EnvGuard::set("VAULT_TOKEN", "test-token");
        let result = check_ambient_credentials();

        match old_token {
            Some(v) => std::env::set_var("VAULT_TOKEN", v),
            None => std::env::remove_var("VAULT_TOKEN"),
        }
        match old_addr {
            Some(v) => std::env::set_var("VAULT_ADDR", v),
            None => std::env::remove_var("VAULT_ADDR"),
        }

        assert!(
            matches!(result, Err(Error::AuthenticationFailed(_))),
            "expected AuthenticationFailed when VAULT_ADDR is missing"
        );
    }

    #[test]
    fn preflight_auth_both_present_ok() {
        let _lock = ENV_LOCK.lock().unwrap();
        let _token_guard = EnvGuard::set("VAULT_TOKEN", "test-token");
        let _addr_guard = EnvGuard::set("VAULT_ADDR", "http://localhost:8200");
        assert!(check_ambient_credentials().is_ok());
    }

    #[test]
    fn list_parsing_from_json() {
        let body = serde_json::json!({
            "data": {
                "keys": [
                    "app/",
                    "db/",
                    "shared"
                ]
            }
        });

        let keys = body
            .get("data")
            .and_then(|d| d.get("keys"))
            .and_then(|k| k.as_array())
            .expect("keys array");

        assert_eq!(keys.len(), 3);
        let names: Vec<String> = keys
            .iter()
            .map(|k| {
                let s = k.as_str().unwrap_or("").trim_end_matches('/');
                s.to_owned()
            })
            .collect();
        assert_eq!(names, vec!["app", "db", "shared"]);
    }

    #[test]
    fn list_url_strips_field_query() {
        // list entries are whole secrets, not fields
        let url = Url::parse("vault://secret/data/myapp/config?field=password").unwrap();
        let v = VaultUrl::try_from(&url).unwrap();
        assert_eq!(v.mount, "secret");
        assert_eq!(v.path, "/data/myapp/config");
        // The field is dropped when constructing the entry URL in list()
    }

    #[test]
    fn put_invalid_json_without_field() {
        let _lock = ENV_LOCK.lock().unwrap();
        let _token_guard = EnvGuard::set("VAULT_TOKEN", "test-token");
        let _addr_guard = EnvGuard::set("VAULT_ADDR", "http://localhost:8200");

        let backend = VaultBackend::new();
        let url = Url::parse("vault://secret/data/test").unwrap();
        let dummy = SecretString::new("not-valid-json".into());

        let err = backend.put(&url, &dummy).unwrap_err();
        assert!(
            matches!(err, Error::InvalidUrl(ref s) if s.contains("must be valid JSON")),
            "expected InvalidUrl for non-JSON value without field, got: {err:?}"
        );
    }

    #[test]
    fn put_with_field_requires_auth() {
        let _lock = ENV_LOCK.lock().unwrap();
        let _token_guard = EnvGuard::set("VAULT_TOKEN", "test-token");
        let _addr_guard = EnvGuard::set("VAULT_ADDR", "http://localhost:8200");

        let backend = VaultBackend::new();
        let url = Url::parse("vault://secret/data/test?field=password").unwrap();
        let dummy = SecretString::new("secret123".into());

        let err = backend.put(&url, &dummy).unwrap_err();
        assert!(
            matches!(
                err,
                Error::Backend { .. } | Error::NotFound(_) | Error::AuthenticationFailed(_)
            ),
            "expected network-layer error for put with field, got: {err:?}"
        );
    }

    #[test]
    fn supported_operations() {
        let backend = VaultBackend::new();
        let url = Url::parse("vault://secret/data/test?field=password").unwrap();

        assert!(
            matches!(
                backend.delete(&url),
                Err(Error::AuthenticationFailed(_))
                    | Err(Error::Backend { .. })
                    | Err(Error::NotFound(_))
            ),
            "delete supported (fails at network layer)"
        );

        assert!(
            matches!(
                backend.list(&url),
                Err(Error::AuthenticationFailed(_))
                    | Err(Error::Backend { .. })
                    | Err(Error::NotFound(_))
            ),
            "list supported (fails at network layer)"
        );

        let dummy = SecretString::new(r#"{"password":"x}"#.into());
        assert!(
            matches!(
                backend.put(&url, &dummy),
                Err(Error::AuthenticationFailed(_))
                    | Err(Error::Backend { .. })
                    | Err(Error::NotFound(_))
            ),
            "put now supported (fails at network layer)"
        );
    }
}