envseal 0.3.8

Write-only secret vault with process-level access control — post-agent 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
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
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! Passphrase-protected master key management.
//!
//! The master key is the root of all encryption in envseal.
//! It is a random 32-byte key, encrypted at rest by a wrapping key
//! derived from a user-entered passphrase via Argon2id.
//!
//! # Key Hierarchy
//!
//! ```text
//! passphrase (entered via GUI popup — agent cannot access)
//!   → Argon2id(passphrase, argon2_salt) → wrapping_key
//!     → AES-256-GCM(wrapping_key, master_key) → encrypted on disk
//!       → master_key used for all vault encryption
//!       → master_key used for HMAC signing of policy.toml
//! ```
//!
//! # File Format: `master.key`
//!
//! ```text
//! [16 bytes: argon2_salt] [12 bytes: nonce] [N bytes: ciphertext+tag]
//! ```

use std::fs;
use std::path::{Path, PathBuf};

use aes_gcm::aead::{Aead, OsRng};
use aes_gcm::{AeadCore, Aes256Gcm, Key, KeyInit};
use argon2::{Algorithm, Argon2, Params, Version};
use hkdf::Hkdf;
use rand::RngCore;
use sha2::Sha256;
use zeroize::Zeroizing;
// `Zeroize` is only consumed inside the Linux `try_memfd_secret` path
// where we explicitly clear the stack copy of the master key after
// migrating it into `memfd_secret`-protected memory. Gating the
// import keeps it from being a dead-code warning on macOS/Windows.
#[cfg(target_os = "linux")]
use zeroize::Zeroize;

use crate::error::Error;
use crate::gui;
use crate::vault::hardware::{self, Backend, DeviceKeystore};

/// Argon2id salt length in bytes.
const ARGON2_SALT_LEN: usize = 16;

/// AES-256-GCM nonce length in bytes.
const NONCE_LEN: usize = 12;

/// Master key length in bytes (AES-256).
const MASTER_KEY_LEN: usize = 32;

/// Minimum passphrase length in characters.
const MIN_PASSPHRASE_LEN: usize = 8;

/// A zeroizing wrapper around the 32-byte master key.
///
/// The key is held in protected memory:
/// - Linux 5.14+: `memfd_secret()` — memory unmapped from kernel page tables,
///   invisible to root via `/proc/pid/mem`, ptrace, and core dumps.
/// - Older Linux / macOS: `mlock()` — prevents swap but visible to root.
///
/// Zeroed on drop via the `Zeroizing` wrapper.
pub struct MasterKey {
    /// The raw key bytes. Zeroized on drop.
    bytes: Zeroizing<[u8; MASTER_KEY_LEN]>,

    /// If true, the key is stored in a `memfd_secret` region.
    /// On drop, we close the fd instead of calling munlock.
    #[cfg(target_os = "linux")]
    in_secret_mem: bool,

    /// The `memfd_secret` file descriptor (if allocated).
    #[cfg(target_os = "linux")]
    secret_fd: Option<i32>,
    /// Pointer to mapped `memfd_secret` region.
    #[cfg(target_os = "linux")]
    secret_ptr: Option<usize>,
}

impl MasterKey {
    /// Get the key as an AES-256-GCM key reference.
    pub fn as_aes_key(&self) -> &Key<Aes256Gcm> {
        Key::<Aes256Gcm>::from_slice(self.as_bytes())
    }

    /// Get the raw key bytes (for HMAC signing).
    pub fn as_bytes(&self) -> &[u8; MASTER_KEY_LEN] {
        #[cfg(target_os = "linux")]
        {
            if self.in_secret_mem {
                if let Some(ptr) = self.secret_ptr {
                    // SAFETY: ptr points to a valid memfd_secret region containing the key
                    return unsafe { &*(ptr as *const [u8; MASTER_KEY_LEN]) };
                }
            }
        }
        &self.bytes
    }

    /// Protect the key bytes using the strongest available mechanism for the
    /// running OS.
    ///
    /// - **Linux 5.14+**: `memfd_secret()` — memory unmapped from kernel page
    ///   tables, invisible to root via `/proc/pid/mem`, ptrace, and core
    ///   dumps.
    /// - **Linux (older) / macOS**: `mlock()` — prevents swap; on Linux also
    ///   `MADV_DONTDUMP` to keep the page out of any future core dump.
    /// - **Windows**: `VirtualLock` — analogous to `mlock`, prevents the
    ///   working set page holding the key from being paged out to disk.
    fn protect(&mut self) {
        #[cfg(target_os = "linux")]
        {
            if self.try_memfd_secret() {
                return;
            }
        }

        // Fallback: mlock (all Unix platforms) + MADV_DONTDUMP
        #[cfg(unix)]
        unsafe {
            libc::mlock(self.bytes.as_ptr().cast::<libc::c_void>(), MASTER_KEY_LEN);
        }

        // ALWAYS ON: Mark key pages as DONTDUMP (belt-and-suspenders)
        #[cfg(target_os = "linux")]
        {
            crate::guard::mark_dontdump(self.bytes.as_ptr(), MASTER_KEY_LEN);
        }

        // Windows: VirtualLock pins the page in physical memory (no swap).
        // Best-effort — a page-cap quota or insufficient privilege will
        // make this fail; we accept the unprotected fallback rather than
        // refusing to open the vault.
        #[cfg(windows)]
        unsafe {
            use windows_sys::Win32::System::Memory::VirtualLock;
            VirtualLock(self.bytes.as_ptr() as *mut std::ffi::c_void, MASTER_KEY_LEN);
        }
    }

    /// Attempt to store the key in `memfd_secret` memory.
    ///
    /// Returns true if successful, false if the syscall is unavailable
    /// (older kernel, `CONFIG_SECRETMEM` disabled, etc.).
    #[cfg(target_os = "linux")]
    fn try_memfd_secret(&mut self) -> bool {
        // memfd_secret() syscall number (x86_64)
        #[cfg(target_arch = "x86_64")]
        const SYS_MEMFD_SECRET: libc::c_long = 447;

        #[cfg(target_arch = "aarch64")]
        const SYS_MEMFD_SECRET: libc::c_long = 447;

        // Only proceed on known architectures
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        {
            return false;
        }

        #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
        unsafe {
            // Create a memfd_secret file descriptor
            // MUST pass O_CLOEXEC, otherwise execve() preserves the FD
            // into the untrusted child process, exposing the plaintext Master Key!
            let fd = libc::syscall(SYS_MEMFD_SECRET, libc::O_CLOEXEC as u32);
            if fd < 0 {
                // Syscall not available — kernel too old or secretmem disabled
                return false;
            }
            #[allow(clippy::cast_possible_truncation)]
            let fd = fd as i32;

            // Set the size to hold the master key
            #[allow(clippy::cast_possible_wrap)]
            let key_size = MASTER_KEY_LEN as libc::off_t;
            if libc::ftruncate(fd, key_size) != 0 {
                libc::close(fd);
                return false;
            }

            // Map the secret memory
            let ptr = libc::mmap(
                std::ptr::null_mut(),
                MASTER_KEY_LEN,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_SHARED,
                fd,
                0,
            );

            if ptr == libc::MAP_FAILED {
                libc::close(fd);
                return false;
            }

            // Copy key bytes into the secret memory region
            std::ptr::copy_nonoverlapping(self.bytes.as_ptr(), ptr.cast::<u8>(), MASTER_KEY_LEN);

            // Update self.bytes to point to... actually, since self.bytes is
            // a fixed array we can't change its address. Instead, we copy into
            // the secret region and zeroize the original location.
            // The key is now in BOTH locations briefly — zeroize the stack copy.
            // (The Zeroizing wrapper will handle the in-struct copy on drop.)

            self.in_secret_mem = true;
            self.secret_fd = Some(fd);
            self.secret_ptr = Some(ptr as usize);

            // Note: we keep the key in self.bytes for API compatibility.
            // The secret mmap region is the primary copy that is root-invisible.
            // Zeroize the stack copy immediately to prevent root-access leak.
            self.bytes.zeroize();
            // On drop, we zeroize and munmap the secret region.

            true
        }
    }
}

impl Drop for MasterKey {
    fn drop(&mut self) {
        #[cfg(target_os = "linux")]
        {
            if self.in_secret_mem {
                if let Some(ptr) = self.secret_ptr {
                    let ptr = ptr as *mut libc::c_void;
                    unsafe {
                        libc::explicit_bzero(ptr, MASTER_KEY_LEN);
                        libc::munmap(ptr, MASTER_KEY_LEN);
                    }
                }
                if let Some(fd) = self.secret_fd {
                    unsafe {
                        // The secret region was mapped from the fd
                        // Closing the fd + the Zeroizing wrapper handles cleanup
                        libc::close(fd);
                    }
                }
                // Don't munlock — memfd_secret doesn't use mlock
                // Zeroizing wrapper handles zeroing self.bytes
                return;
            }
        }

        // Fallback: munlock the mlock'd region
        #[cfg(unix)]
        unsafe {
            libc::munlock(self.bytes.as_ptr().cast::<libc::c_void>(), MASTER_KEY_LEN);
        }

        // Windows: undo the VirtualLock we performed in `protect`.
        #[cfg(windows)]
        unsafe {
            use windows_sys::Win32::System::Memory::VirtualUnlock;
            VirtualUnlock(self.bytes.as_ptr() as *mut std::ffi::c_void, MASTER_KEY_LEN);
        }
        // Zeroizing wrapper handles the actual zeroing.
    }
}

impl std::fmt::Debug for MasterKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MasterKey")
            .field("bytes", &"[REDACTED]")
            .finish()
    }
}

/// Create a MasterKey from raw bytes (testing / fuzzing only).
///
/// # Safety (logical)
///
/// This bypasses the passphrase/GUI flow entirely. Not available in
/// release builds unless the `test-backdoors` crate feature is enabled
/// (e.g. for `cargo-fuzz`).
#[cfg(any(test, feature = "test-backdoors"))]
#[doc(hidden)]
impl MasterKey {
    /// Create a `MasterKey` directly from raw bytes (testing only).
    pub fn from_test_bytes(bytes: [u8; MASTER_KEY_LEN]) -> Self {
        let mut key = Self {
            bytes: Zeroizing::new(bytes),
            #[cfg(target_os = "linux")]
            in_secret_mem: false,
            #[cfg(target_os = "linux")]
            secret_fd: None,
            #[cfg(target_os = "linux")]
            secret_ptr: None,
        };
        key.protect();
        key
    }
}

/// Path to the master key file within a vault root.
pub fn master_key_path(root: &Path) -> PathBuf {
    root.join("master.key")
}

/// Load or create the master key.
///
/// On first run: prompts for a new passphrase via GUI, generates a random
/// master key, wraps it with the passphrase, and writes to disk.
///
/// On subsequent runs: prompts for the passphrase via GUI and unwraps
/// the stored master key.
///
/// CLI/MCP callers use this. Desktop GUI callers use
/// [`open_master_key_with_passphrase`] (which dispatches to the
/// private `create_master_key_with` / `unlock_master_key_with`
/// helpers as appropriate) so the passphrase comes from the
/// in-window egui modal instead of a platform GUI dialog.
pub fn open_master_key(root: &Path) -> Result<MasterKey, Error> {
    let mk_path = master_key_path(root);
    let mut exists = mk_path.exists();

    if exists {
        if let Ok(raw) = std::fs::read(&mk_path) {
            if crate::vault::hardware::parse_v2(&raw).is_err() {
                let min_v1_len = ARGON2_SALT_LEN + NONCE_LEN;
                if raw.len() < min_v1_len {
                    let _ = std::fs::remove_file(&mk_path);
                    exists = false;
                }
            }
        } else {
            exists = false;
        }
    }

    if exists {
        unlock_master_key(&mk_path)
    } else {
        create_master_key(root, &mk_path)
    }
}

/// Unlock or create the master key using a caller-supplied passphrase.
///
/// Same as [`open_master_key`] but never prompts via the platform GUI —
/// callers (typically the desktop GUI) supply the passphrase themselves.
/// Refuses to create a new vault when one already exists; refuses to
/// unlock when none exists. The caller decides which path applies.
///
/// # Errors
/// `Error::SecretAlreadyExists` if the caller asks to create but a
/// vault is already initialized; `Error::SecretNotFound` for unlock
/// against a missing vault; underlying crypto errors otherwise.
pub fn open_master_key_with_passphrase(
    root: &Path,
    passphrase: &Zeroizing<String>,
) -> Result<MasterKey, Error> {
    let mk_path = master_key_path(root);
    let mut exists = mk_path.exists();

    // If the file exists but is corrupted, treat it as non-existent to allow overwrite.
    if exists {
        if let Ok(raw) = std::fs::read(&mk_path) {
            if crate::vault::hardware::parse_v2(&raw).is_err() {
                let min_v1_len = ARGON2_SALT_LEN + NONCE_LEN;
                if raw.len() < min_v1_len {
                    // It's definitely corrupted, delete it so we can create a new one
                    let _ = std::fs::remove_file(&mk_path);
                    exists = false;
                }
            }
        } else {
            exists = false; // Cannot read, treat as missing
        }
    }

    if exists {
        unlock_master_key_with(&mk_path, passphrase)
    } else {
        create_master_key_with(root, &mk_path, passphrase)
    }
}

/// Create a new master key protected by a passphrase + the strongest
/// available hardware key store on this device.
fn create_master_key(root: &Path, mk_path: &Path) -> Result<MasterKey, Error> {
    let passphrase =
        gui::request_passphrase(true, &crate::security_config::load_system_defaults())?;
    create_master_key_with(root, mk_path, &passphrase)
}

/// Same as [`create_master_key`] but takes the passphrase as a parameter
/// so the desktop GUI can supply it from its own in-window modal.
fn create_master_key_with(
    root: &Path,
    mk_path: &Path,
    passphrase: &Zeroizing<String>,
) -> Result<MasterKey, Error> {
    validate_passphrase(passphrase)?;

    // Generate random master key
    let mut master_bytes = [0u8; MASTER_KEY_LEN];
    OsRng.fill_bytes(&mut master_bytes);

    // Generate random Argon2 salt
    let mut argon2_salt = [0u8; ARGON2_SALT_LEN];
    OsRng.fill_bytes(&mut argon2_salt);

    // Derive wrapping key from passphrase
    let wrapping_key = derive_wrapping_key(passphrase, &argon2_salt)?;

    // Encrypt master key with wrapping key
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(wrapping_key.as_ref()));
    let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
    let ciphertext = cipher
        .encrypt(&nonce, master_bytes.as_ref())
        .map_err(|e| Error::CryptoFailure(format!("failed to wrap master key: {e}")))?;

    // Inner v1 envelope: argon2_salt || nonce || ciphertext+tag
    let mut inner = Vec::with_capacity(ARGON2_SALT_LEN + NONCE_LEN + ciphertext.len());
    inner.extend_from_slice(&argon2_salt);
    inner.extend_from_slice(&nonce);
    inner.extend_from_slice(&ciphertext);

    fs::create_dir_all(root)?;
    write_master_file(mk_path, &inner)?;

    let mut key = MasterKey {
        bytes: Zeroizing::new(master_bytes),
        #[cfg(target_os = "linux")]
        in_secret_mem: false,
        #[cfg(target_os = "linux")]
        secret_fd: None,
        #[cfg(target_os = "linux")]
        secret_ptr: None,
    };
    key.protect();
    master_bytes.fill(0);
    argon2_salt.fill(0);

    // Zeroize the wrapping key
    drop(wrapping_key);

    Ok(key)
}

/// Unlock an existing master key by asking for the passphrase.
///
/// On v2 files, the inner envelope is first unwrapped by the active
/// hardware backend; if the file was sealed on a different device, the
/// hardware unseal fails with a descriptive `CryptoFailure` and the
/// passphrase is never even prompted for. This is the "sudo can't read
/// the key from another machine" guarantee.
///
/// Files that aren't a parseable v2 envelope are rejected as corrupted.
///
/// Loops on wrong-passphrase up to [`MAX_UNLOCK_ATTEMPTS`] times,
/// re-rendering the platform dialog with an inline "Incorrect
/// passphrase" hint between attempts. Without this loop a single
/// typo bounced the user all the way back to the CLI with a cryptic
/// `decryption failed` error and no way to retry without re-running
/// the original command. Hard-fail crypto errors (corrupted file,
/// hardware-seal mismatch, etc.) are returned immediately without
/// burning retries — only `wrong passphrase` decryption failures
/// trigger the loop.
fn unlock_master_key(mk_path: &Path) -> Result<MasterKey, Error> {
    let cfg = crate::security_config::load_system_defaults();
    let mut prev_error: Option<String> = None;
    for attempt in 1..=MAX_UNLOCK_ATTEMPTS {
        let passphrase = gui::request_passphrase_with_hint(false, prev_error.as_deref(), &cfg)?;
        match unlock_master_key_with(mk_path, &passphrase) {
            Ok(key) => return Ok(key),
            Err(Error::CryptoFailure(msg)) if msg.contains("wrong passphrase") => {
                let remaining = MAX_UNLOCK_ATTEMPTS - attempt;
                if remaining == 0 {
                    return Err(Error::CryptoFailure(format!(
                        "wrong passphrase after {MAX_UNLOCK_ATTEMPTS} attempts"
                    )));
                }
                prev_error = Some(format!(
                    "Incorrect passphrase. {remaining} attempt{} left.",
                    if remaining == 1 { "" } else { "s" }
                ));
            }
            Err(e) => return Err(e),
        }
    }
    // Loop exit without a return is unreachable given the bounds above,
    // but keep an explicit fallback so the function always returns.
    Err(Error::UserDenied)
}

/// Number of times the unlock dialog will re-prompt on wrong
/// passphrase before giving up. Three matches the OS-level lockscreen
/// behavior most operators are conditioned to expect.
const MAX_UNLOCK_ATTEMPTS: u32 = 3;

/// Same as [`unlock_master_key`] but takes the passphrase as a parameter
/// so the desktop GUI can supply it from its own in-window modal.
fn unlock_master_key_with(
    mk_path: &Path,
    passphrase: &Zeroizing<String>,
) -> Result<MasterKey, Error> {
    let raw = fs::read(mk_path)?;

    let inner = read_inner_envelope_at(&raw, Some(mk_path))?;

    let min_len = ARGON2_SALT_LEN + NONCE_LEN;
    if inner.len() < min_len {
        return Err(Error::CryptoFailure(
            "master.key file corrupted: too short".to_string(),
        ));
    }

    let argon2_salt = &inner[..ARGON2_SALT_LEN];
    let nonce_bytes = &inner[ARGON2_SALT_LEN..ARGON2_SALT_LEN + NONCE_LEN];
    let ciphertext = &inner[ARGON2_SALT_LEN + NONCE_LEN..];

    let wrapping_key = derive_wrapping_key(passphrase, argon2_salt)?;

    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(wrapping_key.as_ref()));
    let nonce = aes_gcm::Nonce::from_slice(nonce_bytes);

    let master_bytes_vec = Zeroizing::new(cipher.decrypt(nonce, ciphertext).map_err(|_| {
        Error::CryptoFailure(
            "wrong passphrase or corrupted master.key — decryption failed".to_string(),
        )
    })?);

    if master_bytes_vec.len() != MASTER_KEY_LEN {
        return Err(Error::CryptoFailure(format!(
            "master key has wrong length: expected {MASTER_KEY_LEN}, got {}",
            master_bytes_vec.len()
        )));
    }

    let mut master_bytes = [0u8; MASTER_KEY_LEN];
    master_bytes.copy_from_slice(&master_bytes_vec);

    let mut key = MasterKey {
        bytes: Zeroizing::new(master_bytes),
        #[cfg(target_os = "linux")]
        in_secret_mem: false,
        #[cfg(target_os = "linux")]
        secret_fd: None,
        #[cfg(target_os = "linux")]
        secret_ptr: None,
    };
    key.protect();
    master_bytes.fill(0);

    // Zeroize temporaries
    drop(wrapping_key);

    Ok(key)
}

/// Derive a dedicated HMAC key from the master key using HKDF-SHA256.
///
/// Never falls back to the raw master key — domain separation must hold.
pub fn derive_hmac_key(master_key: &[u8; 32]) -> Result<[u8; 32], Error> {
    let hk = Hkdf::<Sha256>::new(Some(b"envseal-hmac-salt-v1"), master_key);
    let mut out = [0u8; 32];
    hk.expand(b"envseal-policy-security-hmac", &mut out)
        .map_err(|_| {
            Error::CryptoFailure(
                "HKDF-derived HMAC key expansion failed (invalid output length)".to_string(),
            )
        })?;
    Ok(out)
}

/// Derive a 32-byte wrapping key from a passphrase using Argon2id.
///
/// Parameters (OWASP recommended):
/// - Memory: 64 MiB
/// - Iterations: 3
/// - Parallelism: 4
fn derive_wrapping_key(passphrase: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>, Error> {
    let params = Params::new(
        65536, // 64 MiB memory
        3,     // 3 iterations
        4,     // 4 parallel lanes
        Some(32),
    )
    .map_err(|e| Error::CryptoFailure(format!("invalid argon2 params: {e}")))?;

    let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);

    let mut output = Zeroizing::new([0u8; 32]);
    argon2
        .hash_password_into(passphrase.as_bytes(), salt, output.as_mut())
        .map_err(|e| Error::CryptoFailure(format!("argon2id derivation failed: {e}")))?;

    Ok(output)
}

/// Validate passphrase meets minimum security requirements.
fn validate_passphrase(passphrase: &str) -> Result<(), Error> {
    if passphrase.len() < MIN_PASSPHRASE_LEN {
        return Err(Error::CryptoFailure(format!(
            "passphrase too short: minimum {MIN_PASSPHRASE_LEN} characters required"
        )));
    }
    Ok(())
}

/// Change the passphrase protecting the master key.
///
/// Requires the current passphrase to unlock, then re-wraps with
/// the new passphrase.
pub fn change_passphrase(root: &Path) -> Result<(), Error> {
    let mk_path = master_key_path(root);
    if !mk_path.exists() {
        return Err(Error::CryptoFailure(
            "no master key found — store a secret first".to_string(),
        ));
    }

    // Unlock with current passphrase
    let master_key = unlock_master_key(&mk_path)?;

    // Get new passphrase
    let new_passphrase =
        gui::request_passphrase(true, &crate::security_config::load_system_defaults())?;
    validate_passphrase(&new_passphrase)?;

    // Generate new salt
    let mut new_salt = [0u8; ARGON2_SALT_LEN];
    OsRng.fill_bytes(&mut new_salt);

    // Derive new wrapping key
    let wrapping_key = derive_wrapping_key(&new_passphrase, &new_salt)?;

    // Re-encrypt master key
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(wrapping_key.as_ref()));
    let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
    let ciphertext = cipher
        .encrypt(&nonce, master_key.as_bytes().as_ref())
        .map_err(|e| Error::CryptoFailure(format!("failed to re-wrap master key: {e}")))?;

    // Write new master.key (re-wrapped with hardware seal)
    let mut inner = Vec::with_capacity(ARGON2_SALT_LEN + NONCE_LEN + ciphertext.len());
    inner.extend_from_slice(&new_salt);
    inner.extend_from_slice(&nonce);
    inner.extend_from_slice(&ciphertext);

    write_master_file(&mk_path, &inner)?;

    Ok(())
}

/// Wrap the passphrase-encrypted inner blob with the active hardware
/// keystore and write the resulting v2 file atomically.
///
/// The sequence is:
/// 1. Seal under the active hardware backend.
/// 2. Pack into the v2 envelope.
/// 3. Write to a `master.key.tmp.<pid>.<nanos>` sibling file with the
///    owner-only permissions/ACL applied at create time (no umask
///    race window).
/// 4. `fsync` the bytes.
/// 5. Atomically `rename` over the existing `master.key`.
///
/// A power loss before step 5 leaves the previous master.key intact
/// and the tmp file orphaned (the tmp filename is unique, so two
/// concurrent rotations don't collide). A power loss after step 5
/// has the new file fully durable.
fn write_master_file(mk_path: &Path, inner: &[u8]) -> Result<(), Error> {
    let keystore = DeviceKeystore::select();
    let backend = keystore.backend();
    let sealed = keystore
        .seal(inner)
        .map_err(|e| Error::HardwareSealFailed(format!("seal of master.key failed: {e}")))?;
    let envelope = hardware::pack_v2(backend, &sealed);

    let parent = mk_path.parent().ok_or_else(|| {
        Error::CryptoFailure(format!(
            "master.key path {} has no parent — cannot stage atomic write",
            mk_path.display()
        ))
    })?;
    fs::create_dir_all(parent)?;

    let tmp_path = atomic_tmp_path(mk_path);

    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        // create_new(true) → fails if the tmp already exists, eliminating
        // the chance of writing into a file another process owns.
        let mut f = fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .mode(0o600)
            .open(&tmp_path)?;
        f.write_all(&envelope)?;
        f.sync_all()?;
        // Drop the file handle before rename so Windows-style file-locking
        // (no-op on Unix) cannot interfere.
        drop(f);
    }
    #[cfg(not(unix))]
    {
        if let Err(e) = fs::write(&tmp_path, &envelope) {
            // Best-effort cleanup of any partial tmp before propagating.
            let _ = fs::remove_file(&tmp_path);
            return Err(Error::StorageIo(e));
        }
        // Apply NTFS owner-only DACL on the tmp BEFORE rename so the
        // final master.key never exists with a permissive ACL.
        #[cfg(windows)]
        {
            let _ = crate::policy::windows_acl::set_owner_only_dacl(&tmp_path);
        }
    }

    if let Err(e) = fs::rename(&tmp_path, mk_path) {
        // Rename failed → leave the previous master.key intact; remove tmp.
        let _ = fs::remove_file(&tmp_path);
        return Err(Error::StorageIo(e));
    }

    // Best-effort: fsync the parent dir on Unix so the rename is durable.
    #[cfg(unix)]
    {
        if let Ok(dir) = fs::File::open(parent) {
            let _ = dir.sync_all();
        }
    }

    Ok(())
}

/// Build a unique tmp filename for the atomic master.key rotation.
/// `(pid, nanos)` is unique enough — concurrent rotations from the
/// same process within the same nanosecond would collide, but that
/// requires nanosecond-resolution clock contention from a single
/// thread which the standard library prevents.
fn atomic_tmp_path(mk_path: &Path) -> std::path::PathBuf {
    use std::time::{SystemTime, UNIX_EPOCH};
    let pid = std::process::id();
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    let mut p = mk_path.to_path_buf();
    let stem = mk_path
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("master.key");
    p.set_file_name(format!("{stem}.tmp.{pid}.{nanos}"));
    p
}

/// Read a master.key file and return the inner passphrase-wrapped
/// blob.
///
/// v2 is the canonical on-disk format. However, vaults created before
/// the v2 envelope was introduced wrote the raw inner blob
/// (`argon2_salt || nonce || ciphertext+tag`) directly — no magic,
/// no backend id, no length prefix. We call that the "legacy v1"
/// layout.
///
/// When [`hardware::parse_v2`] rejects the blob (missing magic), we
/// check whether the file is a plausible v1 inner blob (≥ 28 bytes =
/// `ARGON2_SALT_LEN + NONCE_LEN` minimum). If so, we accept it as-is
/// and transparently upgrade the file to v2 on disk so subsequent
/// unlocks go through the normal path. This makes the upgrade
/// seamless for existing users.
#[cfg(test)]
fn read_inner_envelope(raw: &[u8]) -> Result<Vec<u8>, Error> {
    read_inner_envelope_at(raw, None)
}

/// Inner implementation that optionally receives the `master.key`
/// path so it can perform the v1→v2 on-disk upgrade.
fn read_inner_envelope_at(raw: &[u8], mk_path: Option<&Path>) -> Result<Vec<u8>, Error> {
    if let Ok(env) = hardware::parse_v2(raw) {
        let keystore = DeviceKeystore::select();
        let active = keystore.backend();
        if env.backend != Backend::None && env.backend != active {
            return Err(Error::DeviceMismatch {
                sealed_by: env.backend.name().to_string(),
                active: active.name().to_string(),
            });
        }
        // An envelope produced by Backend::None is a no-op outer wrap —
        // the sealed bytes ARE the inner blob. Anything else routes
        // through the active backend's unseal.
        if env.backend == Backend::None {
            Ok(env.sealed.to_vec())
        } else {
            keystore.unseal(env.sealed).map_err(|e| {
                Error::HardwareSealFailed(format!(
                    "unseal of master.key failed — likely a different user logon, \
                     a different physical device, or a wiped TPM/SEP keypair: {e}"
                ))
            })
        }
    } else {
        // ── Legacy v1 migration ──────────────────────────────
        // Pre-v2 master.key files are raw inner blobs:
        //   [16 bytes argon2_salt] [12 bytes nonce] [N bytes ciphertext+tag]
        // Minimum plausible size = 16 + 12 = 28 (a ciphertext of
        // zero length is degenerate but structurally valid).
        let min_v1_len = ARGON2_SALT_LEN + NONCE_LEN;
        if raw.len() < min_v1_len {
            return Err(Error::CryptoFailure(
                "master.key is too short to be a valid v1 or v2 file — \
                 the vault may be corrupted"
                    .to_string(),
            ));
        }
        eprintln!(
            "envseal: ℹ️  detected legacy (pre-v2) master.key — \
             upgrading to v2 envelope format on disk"
        );
        // The raw bytes ARE the inner blob in v1 — accept them.
        let inner = raw.to_vec();
        // Best-effort on-disk upgrade: re-wrap through
        // write_master_file which seals with the active hardware
        // backend and writes a proper v2 envelope.
        if let Some(path) = mk_path {
            if let Err(e) = write_master_file(path, &inner) {
                eprintln!(
                    "envseal: ⚠️  v1→v2 on-disk upgrade failed \
                     (vault still usable, will retry next unlock): {e}"
                );
            }
        }
        Ok(inner)
    }
}

/// Report the active hardware keystore backend on this device. Used
/// by `envseal doctor` and the audit log to surface the actual
/// protection tier the user is getting.
pub fn active_backend() -> Backend {
    DeviceKeystore::select().backend()
}

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

    /// Build a synthetic passphrase-wrapped inner blob of the right
    /// minimum size for `read_inner_envelope` plumbing tests.
    /// Contents don't matter — these tests verify the v2 envelope
    /// framing, not the AES-GCM unseal.
    fn synthetic_inner_blob() -> Vec<u8> {
        // 16 (salt) + 12 (nonce) + 48 (ciphertext+tag for 32-byte plain)
        vec![0u8; 16 + 12 + 48]
    }

    #[test]
    fn legacy_v1_blob_accepted_as_migration() {
        // Pre-v2 master.key files (raw inner blob without the ES2\0
        // header) are now accepted as legacy v1 and returned as-is.
        let v1_blob = synthetic_inner_blob();
        let inner = read_inner_envelope(&v1_blob)
            .expect("plausible v1 blob should be accepted for migration");
        assert_eq!(inner, v1_blob);
    }

    #[test]
    fn too_short_blob_rejected() {
        // Blobs shorter than salt+nonce (28 bytes) are rejected even
        // under the v1 migration path.
        let tiny = vec![0u8; 10];
        let err = read_inner_envelope(&tiny).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("too short") || msg.contains("corrupted"),
            "expected short-file error, got: {msg}"
        );
    }

    #[test]
    fn v2_envelope_with_active_backend_unseals() {
        // Round-trip: build a v2 envelope using the active keystore,
        // then read it back. On Windows this exercises real DPAPI.
        let dir = tempdir().unwrap();
        let mk = dir.path().join("master.key");
        let inner = synthetic_inner_blob();
        write_master_file(&mk, &inner).unwrap();

        let raw = std::fs::read(&mk).unwrap();
        // Must start with the v2 magic.
        assert_eq!(&raw[..4], hardware::V2_MAGIC.as_slice());

        let recovered_inner = read_inner_envelope(&raw).unwrap();
        assert_eq!(recovered_inner, inner);
    }

    #[test]
    fn v2_envelope_with_mismatched_backend_id_is_rejected() {
        // Construct a v2 envelope claiming a backend that isn't this
        // platform's active one. On Windows the active backend is
        // DPAPI, so we mark the envelope as TPM2 — read should fail
        // with a clear error rather than silently feeding garbage to
        // DPAPI.
        let active = active_backend();
        let mismatch = match active {
            Backend::Dpapi => Backend::Tpm2,
            Backend::SecureEnclave | Backend::Tpm2 | Backend::None => Backend::Dpapi,
        };
        if mismatch == active {
            return; // No way to construct a mismatch on this platform — skip.
        }
        let envelope = hardware::pack_v2(mismatch, &synthetic_inner_blob());
        let err = read_inner_envelope(&envelope).unwrap_err();
        match err {
            Error::DeviceMismatch {
                sealed_by,
                active: active_str,
            } => {
                assert_eq!(sealed_by, mismatch.name());
                assert_eq!(active_str, active.name());
            }
            other => panic!("expected DeviceMismatch, got {other:?}"),
        }
    }

    #[test]
    fn v2_envelope_with_none_backend_passes_through() {
        // A v2 envelope explicitly tagged backend=None contains the
        // inner blob unwrapped — should be returned as-is even if
        // the active platform has hardware available.
        let inner = synthetic_inner_blob();
        let envelope = hardware::pack_v2(Backend::None, &inner);
        let recovered = read_inner_envelope(&envelope).unwrap();
        assert_eq!(recovered, inner);
    }

    #[test]
    fn write_master_file_is_atomic_no_tmp_leaks() {
        // After a successful rotation, the only file in the directory
        // should be `master.key` itself — no `master.key.tmp.*` leftover.
        let dir = tempdir().unwrap();
        let mk = dir.path().join("master.key");
        write_master_file(&mk, &synthetic_inner_blob()).unwrap();

        let entries: Vec<_> = std::fs::read_dir(dir.path())
            .unwrap()
            .filter_map(Result::ok)
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        assert!(entries.contains(&"master.key".to_string()));
        for name in &entries {
            assert!(
                !name.contains(".tmp."),
                "found leftover tmp file after rotation: {name}"
            );
        }
    }

    #[test]
    fn write_master_file_overwrites_previous_atomically() {
        // Two successive writes leave the second envelope on disk
        // and don't leave any partial state from the first.
        let dir = tempdir().unwrap();
        let mk = dir.path().join("master.key");

        let first = synthetic_inner_blob();
        let mut second = synthetic_inner_blob();
        second[1] = 0xAA; // distinguish from first
        second[2] = 0xBB;

        write_master_file(&mk, &first).unwrap();
        write_master_file(&mk, &second).unwrap();

        let raw_now = std::fs::read(&mk).unwrap();
        let recovered = read_inner_envelope(&raw_now).unwrap();
        assert_eq!(recovered, second);
    }

    #[test]
    fn write_master_file_fails_clean_when_parent_unwritable() {
        // Targeting a path under a non-existent parent that we make
        // read-only forces a write failure. The error must propagate
        // and no garbage tmp file may be left in unrelated locations.
        let dir = tempdir().unwrap();
        let nested = dir.path().join("does/not/exist/master.key");
        // This succeeds because write_master_file creates parent dirs.
        // To force a real failure on Windows where create_dir_all
        // generally works, we instead point at a path whose parent
        // is itself a regular file.
        let blocker = dir.path().join("blocker");
        std::fs::write(&blocker, b"x").unwrap();
        let bad = blocker.join("master.key");
        let _ = nested; // unused on this path

        let result = write_master_file(&bad, &synthetic_inner_blob());
        assert!(
            result.is_err(),
            "writing under a regular-file parent must fail"
        );
    }

    #[test]
    fn atomic_tmp_path_is_unique_per_invocation() {
        let mk = std::path::PathBuf::from("/some/dir/master.key");
        let a = atomic_tmp_path(&mk);
        // Sleep a hair to guarantee a different nanosecond on platforms
        // with low-resolution clocks.
        std::thread::sleep(std::time::Duration::from_nanos(1));
        let b = atomic_tmp_path(&mk);
        assert_ne!(a, b);
        assert!(a.to_string_lossy().contains("master.key.tmp."));
    }

    #[test]
    fn write_then_read_corrupted_inner_still_fails_unseal_chain() {
        // Sanity: corrupting the v2 envelope's body makes unseal fail
        // (covered by DPAPI's own tests, but verified here at the
        // keychain layer too).
        let dir = tempdir().unwrap();
        let mk = dir.path().join("master.key");
        write_master_file(&mk, &synthetic_inner_blob()).unwrap();
        let mut raw = std::fs::read(&mk).unwrap();
        // Flip a bit deep inside the sealed body.
        let last = raw.len() - 1;
        raw[last] ^= 0x01;
        let result = read_inner_envelope(&raw);
        // On `Backend::None` corruption is invisible (passthrough);
        // on hardware backends the unseal must reject.
        if active_backend() != Backend::None {
            assert!(result.is_err(), "corrupted envelope must fail to unseal");
        }
    }
}

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

    #[test]
    fn different_keys_different_aes() {
        let key1 = MasterKey::from_test_bytes([0x01; 32]);
        let key2 = MasterKey::from_test_bytes([0x02; 32]);
        assert_ne!(
            key1.as_aes_key(),
            key2.as_aes_key(),
            "Fix: different bytes must produce different AES keys"
        );
    }

    #[test]
    fn master_key_as_aes_key_length() {
        let key = MasterKey::from_test_bytes([0x42; 32]);
        let aes_key = key.as_aes_key();
        assert_eq!(aes_key.len(), 32, "Fix: AES-256 key must be 32 bytes");
    }

    #[test]
    fn master_key_debug_redacts() {
        let key = MasterKey::from_test_bytes([0xAA; 32]);
        let debug = format!("{key:?}");
        assert!(
            debug.contains("REDACTED"),
            "Fix: Debug must not leak key bytes"
        );
        assert!(
            !debug.contains("170"),
            "Fix: raw byte values must not appear in debug"
        );
        assert!(
            !debug.contains("0xaa"),
            "Fix: hex bytes must not appear in debug"
        );
    }

    #[test]
    fn master_key_zeroizes_on_drop() {
        let key = MasterKey::from_test_bytes([0xFF; 32]);
        // Key is alive — bytes should be 0xFF
        assert_eq!(key.as_bytes()[0], 0xFF);
        assert_eq!(key.as_bytes()[31], 0xFF);
        // After drop, Zeroizing ensures zeroing — we can't observe this
        // from outside, but we verify the type implements Drop correctly
        // by ensuring drop doesn't panic
        drop(key);
    }

    #[test]
    fn test_key_deterministic() {
        let key1 = MasterKey::from_test_bytes([0x42; 32]);
        let key2 = MasterKey::from_test_bytes([0x42; 32]);
        assert_eq!(
            key1.as_bytes(),
            key2.as_bytes(),
            "Fix: same input bytes must produce same key"
        );
    }
}