zeph-vault 0.22.4

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

//! Age-encrypted vault backend.
//!
//! This module provides [`AgeVaultProvider`], the primary secret storage backend, and the
//! associated [`AgeVaultError`] type. Secrets are stored as a JSON object encrypted with an
//! x25519 keypair using the [age](https://age-encryption.org) format.

use std::collections::BTreeMap;
use std::fmt;
use std::future::Future;
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::pin::Pin;

use zeroize::Zeroizing;

use crate::VaultProvider;
use zeph_common::secret::VaultError;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors that can occur during age vault operations.
///
/// Each variant wraps the underlying cause so callers can match on failure type without
/// parsing error strings.
///
/// # Examples
///
/// ```
/// use zeph_vault::AgeVaultError;
///
/// let err = AgeVaultError::KeyParse("no identity line found".into());
/// assert!(err.to_string().contains("failed to parse age identity"));
/// ```
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum AgeVaultError {
    /// The key file could not be read from disk.
    #[error("failed to read key file: {0}")]
    KeyRead(std::io::Error),
    /// The key file content could not be parsed as an age identity.
    #[error("failed to parse age identity: {0}")]
    KeyParse(String),
    /// The vault file could not be read from disk.
    #[error("failed to read vault file: {0}")]
    VaultRead(std::io::Error),
    /// The age decryption step failed (wrong key, corrupted file, etc.).
    #[error("age decryption failed: {0}")]
    Decrypt(age::DecryptError),
    /// An I/O error occurred while reading plaintext from the age stream.
    #[error("I/O error during decryption: {0}")]
    Io(std::io::Error),
    /// The decrypted bytes could not be parsed as JSON.
    #[error("invalid JSON in vault: {0}")]
    Json(serde_json::Error),
    /// The age encryption step failed.
    #[error("age encryption failed: {0}")]
    Encrypt(String),
    /// The vault file (or its temporary predecessor) could not be written to disk.
    #[error("failed to write vault file: {0}")]
    VaultWrite(std::io::Error),
    /// The key file could not be written to disk.
    #[error("failed to write key file: {0}")]
    KeyWrite(std::io::Error),
    /// [`AgeVaultProvider::set_secret_mut`] was called with `overwrite: false` for a key that
    /// already exists in the vault.
    #[error("secret key already exists: {0} (pass overwrite=true to replace it)")]
    AlreadyExists(String),
    /// [`AgeVaultProvider::init_vault`] (or [`AgeVaultProvider::init_vault_at`]) found an
    /// existing `vault-key.txt` or `secrets.age` at the target location and `force` was not
    /// set.
    #[error("vault already exists at {0} (pass force=true / --force to overwrite it)")]
    VaultAlreadyExists(PathBuf),
}

// ---------------------------------------------------------------------------
// Provider
// ---------------------------------------------------------------------------

/// Age-encrypted vault backend.
///
/// Secrets are stored as a JSON object (`{"KEY": "value", ...}`) encrypted with an x25519
/// keypair using the [age](https://age-encryption.org) format. The in-memory secret values
/// are held in [`zeroize::Zeroizing`] buffers.
///
/// # File layout
///
/// ```text
/// <dir>/vault-key.txt   # age identity (private key), Unix mode 0600
/// <dir>/secrets.age     # age-encrypted JSON object
/// ```
///
/// # Initialising a new vault
///
/// Use [`AgeVaultProvider::init_vault`] to generate a fresh keypair and create an empty vault:
///
/// ```no_run
/// use std::path::Path;
/// use zeph_vault::AgeVaultProvider;
///
/// AgeVaultProvider::init_vault(Path::new("/etc/zeph"))?;
/// // Produces:
/// //   /etc/zeph/vault-key.txt  (mode 0600)
/// //   /etc/zeph/secrets.age    (empty encrypted vault)
/// # Ok::<_, zeph_vault::AgeVaultError>(())
/// ```
///
/// # Atomic writes
///
/// [`save`][AgeVaultProvider::save] writes to a `.age.tmp` sibling file first, then renames it
/// atomically, so a crash during write never leaves the vault in a corrupted state.
pub struct AgeVaultProvider {
    pub(crate) secrets: BTreeMap<String, Zeroizing<String>>,
    pub(crate) key_path: PathBuf,
    pub(crate) vault_path: PathBuf,
}

impl fmt::Debug for AgeVaultProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AgeVaultProvider")
            .field("secrets", &format_args!("[{} secrets]", self.secrets.len()))
            .field("key_path", &self.key_path)
            .field("vault_path", &self.vault_path)
            .finish()
    }
}

impl AgeVaultProvider {
    /// Decrypt an age-encrypted JSON secrets file.
    ///
    /// This is an alias for [`load`][Self::load] provided for ergonomic construction.
    ///
    /// # Arguments
    ///
    /// - `key_path` — path to the age identity (private key) file. Lines starting with `#`
    ///   and blank lines are ignored; the first non-comment line is parsed as the identity.
    /// - `vault_path` — path to the age-encrypted JSON file.
    ///
    /// # Errors
    ///
    /// Returns [`AgeVaultError`] on key/vault read failure, parse error, or decryption failure.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// let vault = AgeVaultProvider::new(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// )?;
    /// println!("{} secrets loaded", vault.list_keys().len());
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    pub fn new(key_path: &Path, vault_path: &Path) -> Result<Self, AgeVaultError> {
        Self::load(key_path, vault_path)
    }

    /// Load vault from disk, storing paths for subsequent write operations.
    ///
    /// Reads and decrypts the vault, then retains both paths so that
    /// [`save`][Self::save] can re-encrypt and persist changes without requiring callers to
    /// pass paths again.
    ///
    /// This method performs blocking I/O on the calling thread. Use [`load_async`][Self::load_async]
    /// when calling from an async context to avoid stalling the tokio executor.
    ///
    /// # Errors
    ///
    /// Returns [`AgeVaultError`] on key/vault read failure, parse error, or decryption failure.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// let vault = AgeVaultProvider::load(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// )?;
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    #[tracing::instrument(name = "vault.age.load", skip_all, err)]
    pub fn load(key_path: &Path, vault_path: &Path) -> Result<Self, AgeVaultError> {
        let key_str =
            Zeroizing::new(std::fs::read_to_string(key_path).map_err(AgeVaultError::KeyRead)?);
        let identity = parse_identity(&key_str)?;
        let ciphertext = std::fs::read(vault_path).map_err(AgeVaultError::VaultRead)?;
        let secrets = decrypt_secrets(&identity, &ciphertext)?;
        Ok(Self {
            secrets,
            key_path: key_path.to_owned(),
            vault_path: vault_path.to_owned(),
        })
    }

    /// Async variant of [`load`][Self::load] — offloads blocking I/O to a `spawn_blocking` thread.
    ///
    /// Use this when calling from an async context to avoid stalling the tokio executor.
    ///
    /// # Errors
    ///
    /// Returns [`AgeVaultError`] on key/vault read failure, parse error, decryption failure, or
    /// if the blocking task panics.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// # async fn example() -> Result<(), zeph_vault::AgeVaultError> {
    /// let vault = AgeVaultProvider::load_async(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(name = "vault.age.load_async", skip_all, err)]
    pub async fn load_async(key_path: &Path, vault_path: &Path) -> Result<Self, AgeVaultError> {
        let key_path = key_path.to_owned();
        let vault_path = vault_path.to_owned();
        tokio::task::spawn_blocking(move || Self::load(&key_path, &vault_path))
            .await
            .map_err(|e| {
                AgeVaultError::Io(std::io::Error::other(format!(
                    "spawn_blocking panicked: {e}"
                )))
            })?
    }

    /// Serialize and re-encrypt secrets to vault file using atomic write (temp + rename).
    ///
    /// Re-reads and re-parses the key file on each call. For CLI one-shot use this is
    /// acceptable; if used in a long-lived context consider caching the parsed identity.
    ///
    /// This method performs blocking I/O on the calling thread. Use [`save_async`][Self::save_async]
    /// when calling from an async context to avoid stalling the tokio executor.
    ///
    /// # Errors
    ///
    /// Returns [`AgeVaultError`] on encryption or write failure.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// let mut vault = AgeVaultProvider::load(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// )?;
    /// vault.set_secret_mut("MY_TOKEN".into(), "tok_abc123".into(), false)?;
    /// vault.save()?;
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    #[tracing::instrument(name = "vault.age.save", skip_all, err)]
    pub fn save(&self) -> Result<(), AgeVaultError> {
        let key_str = Zeroizing::new(
            std::fs::read_to_string(&self.key_path).map_err(AgeVaultError::KeyRead)?,
        );
        let identity = parse_identity(&key_str)?;
        let ciphertext = encrypt_secrets(&identity, &self.secrets)?;
        atomic_write(&self.vault_path, &ciphertext)
    }

    /// Async variant of [`save`][Self::save] — offloads blocking I/O to a `spawn_blocking` thread.
    ///
    /// Use this when calling from an async context to avoid stalling the tokio executor.
    ///
    /// # Errors
    ///
    /// Returns [`AgeVaultError`] on encryption or write failure, or if the blocking task panics.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// # async fn example() -> Result<(), zeph_vault::AgeVaultError> {
    /// let mut vault = AgeVaultProvider::load(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// )?;
    /// vault.set_secret_mut("MY_TOKEN".into(), "tok_abc123".into(), false)?;
    /// vault.save_async().await?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(name = "vault.age.save_async", skip_all, err)]
    pub async fn save_async(&self) -> Result<(), AgeVaultError> {
        let key_path = self.key_path.clone();
        let vault_path = self.vault_path.clone();
        let secrets = self.secrets.clone();
        tokio::task::spawn_blocking(move || {
            let key_str =
                Zeroizing::new(std::fs::read_to_string(&key_path).map_err(AgeVaultError::KeyRead)?);
            let identity = parse_identity(&key_str)?;
            let ciphertext = encrypt_secrets(&identity, &secrets)?;
            atomic_write(&vault_path, &ciphertext)
        })
        .await
        .map_err(|e| {
            AgeVaultError::Io(std::io::Error::other(format!(
                "spawn_blocking panicked: {e}"
            )))
        })?
    }

    /// Insert or update a secret in the in-memory map.
    ///
    /// Refuses to replace an existing key unless `overwrite` is `true`, so that callers cannot
    /// silently destroy a previously-stored secret by accident — see #5955 (and the sibling
    /// incident #5874, which hit the same gap in the `zeph init` durable-execution wizard before
    /// this guard existed at the vault layer). Callers that intend an unconditional update (e.g.
    /// OAuth token refresh) pass `overwrite: true` explicitly.
    ///
    /// Call [`save`][Self::save] afterwards to persist the change to disk.
    ///
    /// # Errors
    ///
    /// Returns [`AgeVaultError::AlreadyExists`] if `key` is already present and `overwrite` is
    /// `false`. The in-memory map is left untouched in that case.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// let mut vault = AgeVaultProvider::load(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// )?;
    /// vault.set_secret_mut("API_KEY".into(), "sk-...".into(), false)?;
    /// vault.save()?;
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    pub fn set_secret_mut(
        &mut self,
        key: String,
        value: String,
        overwrite: bool,
    ) -> Result<(), AgeVaultError> {
        if !overwrite && self.secrets.contains_key(&key) {
            return Err(AgeVaultError::AlreadyExists(key));
        }
        self.secrets.insert(key, Zeroizing::new(value));
        Ok(())
    }

    /// Remove a secret from the in-memory map.
    ///
    /// Returns `true` if the key existed and was removed, `false` if it was not present.
    /// Call [`save`][Self::save] afterwards to persist the removal to disk.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// let mut vault = AgeVaultProvider::load(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// )?;
    /// let removed = vault.remove_secret_mut("OLD_KEY");
    /// if removed {
    ///     vault.save()?;
    /// }
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    pub fn remove_secret_mut(&mut self, key: &str) -> bool {
        self.secrets.remove(key).is_some()
    }

    /// Return sorted list of secret keys (no values exposed).
    ///
    /// Keys are returned in ascending lexicographic order. Secret values are never included.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// let vault = AgeVaultProvider::load(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// )?;
    /// for key in vault.list_keys() {
    ///     println!("{key}");
    /// }
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    #[must_use]
    pub fn list_keys(&self) -> Vec<&str> {
        let mut keys: Vec<&str> = self.secrets.keys().map(String::as_str).collect();
        keys.sort_unstable();
        keys
    }

    /// Look up a secret value by key, returning `None` if not present.
    ///
    /// Returns a borrowed `&str` tied to the lifetime of the vault. For async use across await
    /// points, use [`VaultProvider::get_secret`] instead, which returns an owned `String`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// let vault = AgeVaultProvider::load(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    /// )?;
    /// match vault.get("ZEPH_OPENAI_API_KEY") {
    ///     Some(key) => println!("key length: {}", key.len()),
    ///     None => println!("key not configured"),
    /// }
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&str> {
        self.secrets.get(key).map(|v| v.as_str())
    }

    /// Generate a new x25519 keypair, write the key file (mode 0600), and create an empty
    /// encrypted vault.
    ///
    /// Creates `dir` and all missing parent directories before writing files. Existing files
    /// are not checked — calling this on an already-initialised directory will overwrite both
    /// the key and the vault, making the old key irrecoverable.
    ///
    /// # Output files
    ///
    /// | File | Contents | Unix mode |
    /// |------|----------|-----------|
    /// | `<dir>/vault-key.txt` | age identity (private + public key comment) | `0600` |
    /// | `<dir>/secrets.age`   | age-encrypted empty JSON object `{}` | default |
    ///
    /// Refuses to overwrite a pre-existing vault at `dir` — see [`AgeVaultProvider::init_vault_at`]
    /// for the underlying guard and a `force` escape hatch.
    ///
    /// # Errors
    ///
    /// Returns [`AgeVaultError::VaultAlreadyExists`] if `vault-key.txt` or `secrets.age` already
    /// exists under `dir`, or [`AgeVaultError`] on key/vault write failure or encryption failure.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// AgeVaultProvider::init_vault(Path::new("/etc/zeph"))?;
    /// // /etc/zeph/vault-key.txt and /etc/zeph/secrets.age are now ready.
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    pub fn init_vault(dir: &Path) -> Result<(), AgeVaultError> {
        Self::init_vault_at(&dir.join("vault-key.txt"), &dir.join("secrets.age"), false)
    }

    /// Generates a fresh age keypair and an empty encrypted vault at explicit `key_path` and
    /// `vault_path` locations, mirroring [`AgeVaultProvider::load`]'s explicit-path signature.
    ///
    /// Unlike [`AgeVaultProvider::init_vault`] (which always derives the standard
    /// `vault-key.txt`/`secrets.age` filenames from a directory), this accepts arbitrary target
    /// paths — the correct entry point when the caller has resolved `--vault-key`/`--vault-path`
    /// CLI overrides that may not follow the default directory/filename convention.
    ///
    /// # Overwrite guard
    ///
    /// If either `key_path` or `vault_path` already exists and `force` is `false`, the vault is
    /// left untouched and [`AgeVaultError::VaultAlreadyExists`] is returned — a partial prior
    /// state (only one of the two files present) is treated the same as a full prior vault,
    /// since it is itself evidence of an earlier init attempt worth protecting. Pass `force:
    /// true` to regenerate the keypair and overwrite both files unconditionally.
    ///
    /// The existence check and the subsequent write are not wrapped in a single filesystem lock,
    /// so a racing concurrent call between the check and the write could still both pass the
    /// guard; this is a best-effort, not a hard mutual-exclusion guarantee.
    ///
    /// # Errors
    ///
    /// Returns [`AgeVaultError::VaultAlreadyExists`] when a vault already exists and `force` is
    /// `false`, or [`AgeVaultError`] on key/vault write failure or encryption failure.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use zeph_vault::AgeVaultProvider;
    ///
    /// AgeVaultProvider::init_vault_at(
    ///     Path::new("/etc/zeph/vault-key.txt"),
    ///     Path::new("/etc/zeph/secrets.age"),
    ///     false,
    /// )?;
    /// # Ok::<_, zeph_vault::AgeVaultError>(())
    /// ```
    pub fn init_vault_at(
        key_path: &Path,
        vault_path: &Path,
        force: bool,
    ) -> Result<(), AgeVaultError> {
        use age::secrecy::ExposeSecret as _;

        let existing = if key_path.exists() {
            Some(key_path)
        } else if vault_path.exists() {
            Some(vault_path)
        } else {
            None
        };

        if let Some(existing_path) = existing {
            if !force {
                return Err(AgeVaultError::VaultAlreadyExists(
                    existing_path.to_path_buf(),
                ));
            }
            println!("Overwriting existing vault at {}.", existing_path.display());
        }

        if let Some(parent) = key_path.parent() {
            std::fs::create_dir_all(parent).map_err(AgeVaultError::KeyWrite)?;
        }
        if let Some(parent) = vault_path.parent() {
            std::fs::create_dir_all(parent).map_err(AgeVaultError::VaultWrite)?;
        }

        let identity = age::x25519::Identity::generate();
        let public_key = identity.to_public();

        let key_content = Zeroizing::new(format!(
            "# public key: {}\n{}\n",
            public_key,
            identity.to_string().expose_secret()
        ));

        write_private_file(key_path, key_content.as_bytes())?;

        let empty: BTreeMap<String, Zeroizing<String>> = BTreeMap::new();
        let ciphertext = encrypt_secrets(&identity, &empty)?;
        atomic_write(vault_path, &ciphertext)?;

        println!("Vault initialized:");
        println!("  Key:   {}", key_path.display());
        println!("  Vault: {}", vault_path.display());

        Ok(())
    }
}

impl VaultProvider for AgeVaultProvider {
    fn get_secret(
        &self,
        key: &str,
    ) -> Pin<Box<dyn Future<Output = Result<Option<String>, VaultError>> + Send + '_>> {
        let result = self.secrets.get(key).map(|v| (**v).clone());
        Box::pin(async move { Ok(result) })
    }

    fn list_keys(&self) -> Vec<String> {
        let mut keys: Vec<String> = self.secrets.keys().cloned().collect();
        keys.sort_unstable();
        keys
    }
}

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

pub(crate) fn parse_identity(key_str: &str) -> Result<age::x25519::Identity, AgeVaultError> {
    let key_line = key_str
        .lines()
        .find(|l| !l.starts_with('#') && !l.trim().is_empty())
        .ok_or_else(|| AgeVaultError::KeyParse("no identity line found".into()))?;
    key_line
        .trim()
        .parse()
        .map_err(|e: &str| AgeVaultError::KeyParse(e.to_owned()))
}

pub(crate) fn decrypt_secrets(
    identity: &age::x25519::Identity,
    ciphertext: &[u8],
) -> Result<BTreeMap<String, Zeroizing<String>>, AgeVaultError> {
    let decryptor = age::Decryptor::new(ciphertext).map_err(AgeVaultError::Decrypt)?;
    let mut reader = decryptor
        .decrypt(std::iter::once(identity as &dyn age::Identity))
        .map_err(AgeVaultError::Decrypt)?;
    let mut plaintext = Zeroizing::new(Vec::with_capacity(ciphertext.len()));
    reader
        .read_to_end(&mut plaintext)
        .map_err(AgeVaultError::Io)?;
    let raw: BTreeMap<String, String> =
        serde_json::from_slice(&plaintext).map_err(AgeVaultError::Json)?;
    Ok(raw
        .into_iter()
        .map(|(k, v)| (k, Zeroizing::new(v)))
        .collect())
}

pub(crate) fn encrypt_secrets(
    identity: &age::x25519::Identity,
    secrets: &BTreeMap<String, Zeroizing<String>>,
) -> Result<Vec<u8>, AgeVaultError> {
    let recipient = identity.to_public();
    let encryptor =
        age::Encryptor::with_recipients(std::iter::once(&recipient as &dyn age::Recipient))
            .map_err(|e| AgeVaultError::Encrypt(e.to_string()))?;
    let plain: BTreeMap<&str, &str> = secrets
        .iter()
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect();
    let json = Zeroizing::new(serde_json::to_vec(&plain).map_err(AgeVaultError::Json)?);
    let mut ciphertext = Vec::with_capacity(json.len() + 64);
    let mut writer = encryptor
        .wrap_output(&mut ciphertext)
        .map_err(|e| AgeVaultError::Encrypt(e.to_string()))?;
    writer.write_all(&json).map_err(AgeVaultError::Io)?;
    writer
        .finish()
        .map_err(|e| AgeVaultError::Encrypt(e.to_string()))?;
    Ok(ciphertext)
}

pub(crate) fn atomic_write(path: &Path, data: &[u8]) -> Result<(), AgeVaultError> {
    zeph_common::fs_secure::atomic_write_private(path, data).map_err(AgeVaultError::VaultWrite)
}

pub(crate) fn write_private_file(path: &Path, data: &[u8]) -> Result<(), AgeVaultError> {
    zeph_common::fs_secure::write_private(path, data).map_err(AgeVaultError::KeyWrite)
}

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

    fn init_temp_vault(dir: &Path) -> (PathBuf, PathBuf) {
        AgeVaultProvider::init_vault(dir).expect("init_vault failed");
        (dir.join("vault-key.txt"), dir.join("secrets.age"))
    }

    #[test]
    fn round_trip() {
        let dir = tempdir().unwrap();
        let (key_path, vault_path) = init_temp_vault(dir.path());

        let mut vault = AgeVaultProvider::new(&key_path, &vault_path).unwrap();
        vault
            .set_secret_mut("KEY".into(), "val".into(), false)
            .unwrap();
        vault.save().unwrap();

        let loaded = AgeVaultProvider::load(&key_path, &vault_path).unwrap();
        assert_eq!(loaded.get("KEY"), Some("val"));
    }

    #[test]
    fn remove_secret() {
        let dir = tempdir().unwrap();
        let (key_path, vault_path) = init_temp_vault(dir.path());

        let mut vault = AgeVaultProvider::new(&key_path, &vault_path).unwrap();
        vault
            .set_secret_mut("KEY".into(), "val".into(), false)
            .unwrap();

        assert!(vault.remove_secret_mut("KEY"));
        assert!(!vault.remove_secret_mut("KEY"));
        assert_eq!(vault.get("KEY"), None);
    }

    #[test]
    fn init_vault_creates_files() {
        let dir = tempdir().unwrap();
        AgeVaultProvider::init_vault(dir.path()).unwrap();

        assert!(dir.path().join("vault-key.txt").exists());
        assert!(dir.path().join("secrets.age").exists());
    }

    #[test]
    fn init_vault_refuses_to_overwrite_existing_vault() {
        let dir = tempdir().unwrap();
        AgeVaultProvider::init_vault(dir.path()).unwrap();
        let key_path = dir.path().join("vault-key.txt");
        let vault_path = dir.path().join("secrets.age");
        let original_key = std::fs::read(&key_path).unwrap();

        let err = AgeVaultProvider::init_vault(dir.path()).unwrap_err();
        assert!(matches!(err, AgeVaultError::VaultAlreadyExists(_)));

        // Neither file was touched by the rejected re-init.
        assert_eq!(std::fs::read(&key_path).unwrap(), original_key);
        let _ = vault_path; // existence already implied by init_vault_creates_files
    }

    #[test]
    fn init_vault_at_force_overwrites_existing_vault() {
        let dir = tempdir().unwrap();
        let key_path = dir.path().join("vault-key.txt");
        let vault_path = dir.path().join("secrets.age");
        AgeVaultProvider::init_vault_at(&key_path, &vault_path, false).unwrap();
        let original_key = std::fs::read(&key_path).unwrap();

        AgeVaultProvider::init_vault_at(&key_path, &vault_path, true).unwrap();
        let new_key = std::fs::read(&key_path).unwrap();

        assert_ne!(original_key, new_key, "force must regenerate the keypair");
    }

    #[test]
    fn init_vault_at_respects_explicit_non_default_paths() {
        let dir = tempdir().unwrap();
        let key_path = dir.path().join("custom-key.txt");
        let vault_path = dir.path().join("custom-vault.age");

        AgeVaultProvider::init_vault_at(&key_path, &vault_path, false).unwrap();

        assert!(key_path.exists());
        assert!(vault_path.exists());
        // The standard default-named files must not have been created as a side effect.
        assert!(!dir.path().join("vault-key.txt").exists());
        assert!(!dir.path().join("secrets.age").exists());
    }

    #[test]
    fn init_vault_at_guards_when_only_vault_file_present() {
        let dir = tempdir().unwrap();
        let key_path = dir.path().join("vault-key.txt");
        let vault_path = dir.path().join("secrets.age");
        // Simulate a partial prior state: only `secrets.age` exists, `vault-key.txt` does not
        // (e.g. an interrupted write, or a corrupted/incomplete prior init).
        std::fs::write(&vault_path, b"not a real age file").unwrap();

        let err = AgeVaultProvider::init_vault_at(&key_path, &vault_path, false).unwrap_err();
        match err {
            AgeVaultError::VaultAlreadyExists(path) => assert_eq!(path, vault_path),
            other => panic!("expected VaultAlreadyExists, got {other:?}"),
        }
        // Neither the guard nor the refused init may have created/touched the key file.
        assert!(!key_path.exists());
        assert_eq!(std::fs::read(&vault_path).unwrap(), b"not a real age file");
    }

    #[test]
    fn init_vault_at_creates_independent_parent_dirs_for_key_and_vault() {
        let dir = tempdir().unwrap();
        // key_path and vault_path live under two entirely separate, not-yet-existing nested
        // parent directories — proves each parent is created independently rather than the two
        // calls collapsing into a no-op because they happen to share an already-existing parent.
        let key_path = dir.path().join("keys/sub/vault-key.txt");
        let vault_path = dir.path().join("secrets/sub/secrets.age");

        AgeVaultProvider::init_vault_at(&key_path, &vault_path, false).unwrap();

        assert!(
            key_path.exists(),
            "key file must exist under its own parent chain"
        );
        assert!(
            vault_path.exists(),
            "vault file must exist under its own, separate parent chain"
        );
        assert!(dir.path().join("keys/sub").is_dir());
        assert!(dir.path().join("secrets/sub").is_dir());
    }

    #[test]
    fn load_missing_vault_errors() {
        let dir = tempdir().unwrap();
        let key_path = dir.path().join("vault-key.txt");
        let vault_path = dir.path().join("secrets.age");

        let result = AgeVaultProvider::load(&key_path, &vault_path);
        assert!(result.is_err());
    }

    #[test]
    #[cfg(unix)]
    fn key_file_has_restricted_permissions() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempdir().unwrap();
        let (key_path, _) = init_temp_vault(dir.path());

        let mode = std::fs::metadata(&key_path).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            mode, 0o600,
            "vault-key.txt must have mode 0600, got {mode:o}"
        );
    }

    #[test]
    fn load_blank_key_returns_key_parse_error() {
        let dir = tempdir().unwrap();
        let key_path = dir.path().join("vault-key.txt");
        let vault_path = dir.path().join("secrets.age");

        // Key file with only comments and blank lines — no valid identity line.
        std::fs::write(&key_path, "# comment\n\n# another comment\n").unwrap();
        // Vault file must exist so the error comes from key parsing, not vault read.
        std::fs::write(&vault_path, b"").unwrap();

        let result = AgeVaultProvider::load(&key_path, &vault_path);
        assert!(
            matches!(result, Err(AgeVaultError::KeyParse(_))),
            "expected KeyParse, got {result:?}",
        );
    }

    #[test]
    fn decrypt_corrupted_ciphertext_returns_decrypt_error() {
        let dir = tempdir().unwrap();
        let (key_path, vault_path) = init_temp_vault(dir.path());

        // Overwrite the encrypted vault with random garbage.
        std::fs::write(&vault_path, b"not valid age ciphertext at all").unwrap();

        let result = AgeVaultProvider::load(&key_path, &vault_path);
        assert!(
            matches!(result, Err(AgeVaultError::Decrypt(_))),
            "expected Decrypt, got {result:?}",
        );
    }

    #[test]
    fn save_leaves_no_tmp_file() {
        let dir = tempdir().unwrap();
        let (key_path, vault_path) = init_temp_vault(dir.path());

        let mut vault = AgeVaultProvider::new(&key_path, &vault_path).unwrap();
        vault
            .set_secret_mut("TMP_TEST".into(), "value".into(), false)
            .unwrap();
        vault.save().unwrap();

        let tmp_path = vault_path.with_added_extension("tmp");
        assert!(!tmp_path.exists(), ".age.tmp must not exist after save()");
        assert!(vault_path.exists(), "secrets.age must exist after save()");
    }

    /// Regression for #5955: `set_secret_mut` must refuse to replace an existing key when
    /// `overwrite` is `false`, and must leave the previous value untouched.
    #[test]
    fn set_secret_mut_rejects_overwrite_when_not_requested() {
        let dir = tempdir().unwrap();
        let (key_path, vault_path) = init_temp_vault(dir.path());

        let mut vault = AgeVaultProvider::new(&key_path, &vault_path).unwrap();
        vault
            .set_secret_mut("KEY".into(), "original".into(), false)
            .unwrap();

        let result = vault.set_secret_mut("KEY".into(), "clobbered".into(), false);
        assert!(
            matches!(result, Err(AgeVaultError::AlreadyExists(ref k)) if k == "KEY"),
            "expected AlreadyExists(\"KEY\"), got {result:?}",
        );
        assert_eq!(vault.get("KEY"), Some("original"));
    }

    /// Regression for #5955: `overwrite: true` must replace an existing value.
    #[test]
    fn set_secret_mut_replaces_when_overwrite_requested() {
        let dir = tempdir().unwrap();
        let (key_path, vault_path) = init_temp_vault(dir.path());

        let mut vault = AgeVaultProvider::new(&key_path, &vault_path).unwrap();
        vault
            .set_secret_mut("KEY".into(), "original".into(), false)
            .unwrap();
        vault
            .set_secret_mut("KEY".into(), "updated".into(), true)
            .unwrap();

        assert_eq!(vault.get("KEY"), Some("updated"));
    }
}