envseal 0.3.12

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
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
//! 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.
    ///
    /// # Audit H4 — loud-fail on total fallback
    ///
    /// If none of the platform-specific mechanisms succeeds (kernel too
    /// old, ulimit too tight, no `CAP_IPC_LOCK`, Windows page-quota
    /// exhausted, etc.) the master key remains in a regular pageable
    /// allocation — readable from `/proc/<pid>/mem` by anything with
    /// the same UID, and potentially swappable to disk. That is a
    /// material weakening of the threat model and the operator must
    /// know about it. We emit a `memory.protection.unavailable` signal
    /// through the unified guard pipeline so it surfaces in the
    /// startup audit, doctor, and audit log — not silently into the
    /// void as before.
    fn protect(&mut self) {
        let mut any_succeeded = false;

        #[cfg(target_os = "linux")]
        {
            if self.try_memfd_secret() {
                return;
            }
        }

        // Fallback: mlock (all Unix platforms) + MADV_DONTDUMP. mlock
        // returns 0 on success, -1 on failure; we surface the failure
        // through the signal pipeline rather than burying it.
        #[cfg(unix)]
        {
            // SAFETY: bytes is a stable allocation of MASTER_KEY_LEN
            // bytes for the lifetime of the MasterKey.
            let rc =
                unsafe { libc::mlock(self.bytes.as_ptr().cast::<libc::c_void>(), MASTER_KEY_LEN) };
            if rc == 0 {
                any_succeeded = true;
            }
        }

        // 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, but we *announce* the fallback so
        // the operator's audit log and doctor view show it.
        #[cfg(windows)]
        {
            // SAFETY: bytes is a stable allocation of MASTER_KEY_LEN
            // bytes for the lifetime of the MasterKey. VirtualLock
            // returns nonzero on success.
            let ok = unsafe {
                use windows_sys::Win32::System::Memory::VirtualLock;
                VirtualLock(self.bytes.as_ptr() as *mut std::ffi::c_void, MASTER_KEY_LEN)
            } != 0;
            if ok {
                any_succeeded = true;
            }
        }

        if !any_succeeded {
            announce_memory_protection_unavailable();
        }
    }

    /// 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.
    }
}

/// Announce, exactly once per process, that no memory-protection
/// mechanism succeeded for the master key.
///
/// Routed through the unified Signal pipeline so the message lands
/// in the audit log, the doctor view, and (because it's a `Warn`
/// signal at the highest tier) in the next startup audit. We
/// deduplicate via a single `AtomicBool` so subsequent vault opens in
/// the same process do not re-emit the warning.
fn announce_memory_protection_unavailable() {
    use std::sync::atomic::{AtomicBool, Ordering};
    static ANNOUNCED: AtomicBool = AtomicBool::new(false);
    if ANNOUNCED.swap(true, Ordering::AcqRel) {
        return;
    }
    let _ = crate::guard::emit_signal_inline(
        crate::guard::Signal::new(
            crate::guard::SignalId::new("memory.protection.unavailable"),
            crate::guard::Category::DiskPermissions,
            crate::guard::Severity::Warn,
            "master-key memory is not protected",
            "all platform memory-protection mechanisms (memfd_secret, mlock, \
             VirtualLock) failed; the master key is in regular pageable \
             memory and may be readable from /proc/<pid>/mem or swapped to \
             disk. Likely cause: ulimit -l 0 (no CAP_IPC_LOCK), an SELinux \
             policy that denies mlock, or a Windows page-quota cap.",
            "raise the per-process locked-memory limit (e.g. `ulimit -l \
             unlimited` or `setcap cap_ipc_lock+ep $(which envseal)`); on \
             Windows, run as a user with `SeLockMemoryPrivilege`",
        ),
        &crate::security_config::load_system_defaults(),
    );
}

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 — **test / fuzzing only**.
///
/// # ⚠️ Security warning (audit M21)
///
/// This bypasses the passphrase, hardware seal, and FIDO2 layers
/// entirely. It exists so integration tests in `core/tests/` can
/// drive the vault state machine without a real GUI / authenticator,
/// and for `cargo-fuzz`. It is gated behind:
///
/// 1. The `test-backdoors` cargo feature, which is only enabled by
///    the dev-dependency alias in `core/Cargo.toml`. A regular
///    `cargo build` (release or debug) does **not** see this method.
/// 2. A runtime guard ([`assert_test_backdoor_safe`]) that aborts
///    the process if this constructor is reached outside a Cargo
///    test / fuzz / bench harness or without an explicit
///    `ENVSEAL_TEST_BACKDOORS_OK=1` opt-in. A compromised build that
///    flips `--features test-backdoors` for a release binary will
///    therefore fail to actually use the backdoor at runtime,
///    rather than silently exposing `Vault::open_with_key`.
#[cfg(any(test, feature = "test-backdoors"))]
#[doc(hidden)]
impl MasterKey {
    /// Create a `MasterKey` directly from raw bytes (testing only).
    ///
    /// Aborts the process when invoked outside a recognized test /
    /// fuzz / bench environment — see [`assert_test_backdoor_safe`].
    pub fn from_test_bytes(bytes: [u8; MASTER_KEY_LEN]) -> Self {
        crate::test_backdoors::assert_test_backdoor_safe();
        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);
    if !mk_path.exists() {
        return create_master_key(root, &mk_path);
    }
    // Audit H5: if `master.key` exists but parses as neither a valid
    // v2 (hardware) envelope nor a long-enough v1 inner blob, refuse
    // to silently delete it. Silent deletion is dangerous: a bad
    // backup, a partial filesystem write, or a stray-byte attack
    // could otherwise be turned into an "envseal happily creates a
    // new vault and loses every secret" event with no audit trail.
    // Surface a hard error and an audit-logged event; the operator
    // can recover the file from backup or run the explicit
    // `envseal emergency-revoke` flow if they really do want a fresh
    // start.
    match std::fs::read(&mk_path) {
        Err(e) => Err(Error::StorageIo(e)),
        Ok(raw) => {
            if crate::vault::hardware::parse_v2(&raw).is_ok() {
                return unlock_master_key(&mk_path);
            }
            let min_v1_len = ARGON2_SALT_LEN + NONCE_LEN;
            if raw.len() >= min_v1_len {
                return unlock_master_key(&mk_path);
            }
            let _ = crate::audit::log_required_at(
                root,
                &crate::audit::AuditEvent::SignalRecorded {
                    tier: "Lockdown".to_string(),
                    classification: format!(
                        "critical [vault.master_key.corrupt] {} bytes (need >= {min_v1_len}); \
                         refusing to auto-delete",
                        raw.len()
                    ),
                },
            );
            Err(Error::CryptoFailure(format!(
                "master.key at {} is too short to be valid ({} bytes; need >= {min_v1_len}). \
                 envseal refuses to silently delete it — a partial write or corrupted backup \
                 could otherwise cause every stored secret to be lost without warning. \
                 To start fresh, explicitly remove the file yourself \
                 (`rm {}/master.key`), or restore the file from a backup. \
                 If you intend to wipe the vault, use `envseal emergency-revoke`.",
                mk_path.display(),
                raw.len(),
                root.display(),
            )))
        }
    }
}

/// 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);
    if !mk_path.exists() {
        return create_master_key_with(root, &mk_path, passphrase);
    }

    // Audit H5: same hard-fail policy as `open_master_key`. We
    // refuse to silently delete a too-short master.key. The desktop
    // GUI surfaces the returned `CryptoFailure` directly, so the
    // user sees the explanation instead of an unprompted "vault
    // was reset" surprise.
    match std::fs::read(&mk_path) {
        Err(e) => Err(Error::StorageIo(e)),
        Ok(raw) => {
            if crate::vault::hardware::parse_v2(&raw).is_ok() {
                return unlock_master_key_with(&mk_path, passphrase);
            }
            let min_v1_len = ARGON2_SALT_LEN + NONCE_LEN;
            if raw.len() >= min_v1_len {
                return unlock_master_key_with(&mk_path, passphrase);
            }
            let _ = crate::audit::log_required_at(
                root,
                &crate::audit::AuditEvent::SignalRecorded {
                    tier: "Lockdown".to_string(),
                    classification: format!(
                        "critical [vault.master_key.corrupt] {} bytes (need >= {min_v1_len}); \
                         refusing to auto-delete",
                        raw.len()
                    ),
                },
            );
            Err(Error::CryptoFailure(format!(
                "master.key at {} is too short to be valid ({} bytes; need >= {min_v1_len}). \
                 envseal refuses to silently delete it — restore from backup, or explicitly \
                 remove the file yourself if you intend to start over.",
                mk_path.display(),
                raw.len(),
            )))
        }
    }
}

/// 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)?;

        // Hot-fast path: try the legacy unlock. v1/v2 vaults
        // succeed here; v3 vaults fail closed with Fido2Required so
        // we can pick up the hardware path below without
        // double-prompting for the passphrase.
        let result = unlock_master_key_with(mk_path, &passphrase);

        // v3 vault dispatch — only available when the build
        // includes the `fido2-hardware` feature. Otherwise we let
        // the underlying Fido2Required propagate so the operator
        // sees a clear "rebuild with --features fido2-hardware"
        // message via the CLI.
        #[cfg(feature = "fido2-hardware")]
        let result = match result {
            Err(Error::Fido2Required) => {
                let mut auth = crate::vault::fido2_hardware::HwAuthenticator::discover()?;
                fido2_unlock::unlock_master_key_with_fido2(mk_path, &passphrase, &mut auth)
            }
            other => other,
        };

        match result {
            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))?;

    // v3 envelopes (FIDO2-enrolled vaults) cannot be unlocked through
    // the passphrase-only path — they require an authenticator. Surface
    // a precise error so the caller can prompt the user to attach a key
    // (or use the v3-aware unlock entry point).
    #[cfg(feature = "fido2")]
    if crate::vault::fido2::is_v3(&inner) {
        return Err(Error::Fido2Required);
    }

    unlock_master_key_v1_inner(&inner, passphrase)
}

/// Decrypt the master key from a v1 inner blob.
///
/// The v1 inner layout is `[argon2_salt(16)][nonce(12)][ciphertext+tag]`
/// — the original layout shipped before the v2 hardware wrap and v3
/// FIDO2 wrap were added. v2 master.key files carry this same payload
/// inside a hardware envelope; v3 master.key files use a different
/// inner layout that this function does not handle.
fn unlock_master_key_v1_inner(
    inner: &[u8],
    passphrase: &Zeroizing<String>,
) -> Result<MasterKey, Error> {
    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)?;

    decrypt_master_key_with_wrap(wrapping_key, nonce_bytes, ciphertext)
}

/// AES-GCM-decrypt the master key bytes given a 32-byte wrapping key,
/// nonce, and ciphertext, then move the plaintext into the protected
/// `MasterKey` storage.
///
/// Shared by the v1 and v3 unlock paths so the AES-GCM error mapping,
/// the master-key-length check, and the `MasterKey::protect()` call
/// live in exactly one place — fixing a bug here fixes both paths.
fn decrypt_master_key_with_wrap(
    wrapping_key: Zeroizing<[u8; 32]>,
    nonce_bytes: &[u8],
    ciphertext: &[u8],
) -> Result<MasterKey, Error> {
    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 the wrapping key.
    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();
    // Audit H3: refuse to create or rotate a vault when the device
    // returned `Backend::None` (no DPAPI / Secure Enclave / TPM 2.0
    // available) unless the operator explicitly opted in. The
    // previous behaviour was to silently fall back to passphrase-only
    // sealing — the threat model documented in README/THESIS assumes
    // the master.key envelope is bound to *this device*, and a
    // silent no-hardware fallback weakens that assumption without
    // the operator knowing. The env var name is verbose so it cannot
    // be set by accident and is easy to grep for in audit logs.
    // Recognized test/fuzz/bench environments bypass the refusal so
    // CI runners without a TPM / SEP / DPAPI can exercise the rest
    // of the vault state machine. End-user binaries hit the block.
    //
    // Detection: cargo always builds test binaries under `target/`,
    // and our own unit-test cfg flag is reliable inside the lib.
    // Either signal is sufficient — false positives here only let
    // the unhardened-vault-creation path through, which is harmless
    // for a real test (it's exactly what the test wants) and not
    // exploitable for an end user (the path doesn't reach a real
    // user vault).
    let path_looks_like_test = std::env::current_exe()
        .ok()
        .and_then(|p| {
            p.to_str()
                .map(|s| s.contains("/target/") || s.contains("\\target\\"))
        })
        .unwrap_or(false);
    let in_test_env = cfg!(test)
        || path_looks_like_test
        || std::env::var("CARGO_TARGET_TMPDIR").is_ok()
        || std::env::var("CARGO_FUZZ_TARGET").is_ok()
        || std::env::var("ENVSEAL_TEST_BACKDOORS_OK").is_ok();
    if matches!(backend, hardware::Backend::None)
        && std::env::var("ENVSEAL_ACCEPT_NO_HARDWARE_SEAL").is_err()
        && !in_test_env
    {
        let _ = crate::audit::log_required_at(
            mk_path.parent().unwrap_or(std::path::Path::new(".")),
            &crate::audit::AuditEvent::SignalRecorded {
                tier: "Hardened".to_string(),
                classification: "critical [vault.no_hardware_seal] refused master.key write — \
                     no DPAPI / Secure Enclave / TPM 2.0 available"
                    .to_string(),
            },
        );
        return Err(Error::HardwareSealFailed(format!(
            "no hardware-sealing backend is available on this machine \
             (no DPAPI / Secure Enclave / TPM 2.0). envseal refuses to \
             write {} as a passphrase-only vault by default — that downgrade \
             would silently weaken the on-disk threat model. \n\
             \n\
             To proceed anyway (e.g. on a CI runner or a VM without a vTPM), \
             set ENVSEAL_ACCEPT_NO_HARDWARE_SEAL=1 in your environment and \
             rerun the command. The operator who sets that flag is \
             acknowledging that a master.key on this machine is protected \
             only by the Argon2id-wrapped passphrase, not also by a \
             device-bound seal.",
            mk_path.display(),
        )));
    }
    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()
}

/// FIDO2-aware vault creation and unlock entry points.
///
/// These are gated behind the `fido2` cargo feature so the default
/// build is unaffected. Behavior:
///
/// - [`create_master_key_with_fido2`] — enroll the supplied
///   authenticator, derive the v3 wrapping key from
///   passphrase + hmac-secret, write a v3 envelope.
/// - [`open_master_key_with_passphrase_and_fido2`] — dispatch on the
///   inner blob magic: v3 vaults consume the authenticator, v1/v2
///   vaults bypass it (no FIDO2 prompt).
///
/// The functions exist alongside the existing passphrase-only
/// variants; consumers that don't know about FIDO2 keep working
/// against v1 / v2 vaults exactly as before.
#[cfg(feature = "fido2")]
pub mod fido2_unlock {
    use super::{
        decrypt_master_key_with_wrap, derive_wrapping_key, master_key_path, read_inner_envelope_at,
        unlock_master_key_v1_inner, validate_passphrase, write_master_file, MasterKey,
        ARGON2_SALT_LEN, MASTER_KEY_LEN, NONCE_LEN,
    };
    use crate::error::Error;
    use crate::vault::fido2;
    use aes_gcm::aead::{Aead, OsRng};
    use aes_gcm::{AeadCore, Aes256Gcm, Key, KeyInit};
    use rand::RngCore;
    use std::fs;
    use std::path::Path;
    use zeroize::Zeroizing;

    /// Relying-party id used when minting credentials. Namespaces
    /// envseal vault credentials apart from any web credentials the
    /// same authenticator may hold.
    pub const RELYING_PARTY_ID: &str = "envseal.local";

    /// Relying-party human-readable name shown by some
    /// authenticators (or accompanying GUIs) during enrollment.
    pub const RELYING_PARTY_NAME: &str = "envseal vault";

    /// Open or create the master key, supplying a FIDO2 authenticator.
    ///
    /// Behavior matches [`super::open_master_key_with_passphrase`]
    /// with an additional dispatch:
    ///
    /// - If the file does not exist, a new v3 vault is created and
    ///   the authenticator is enrolled.
    /// - If the file exists and parses as v3, the authenticator is
    ///   consulted to derive the wrapping key.
    /// - If the file exists and parses as v1/v2, the FIDO2 path is
    ///   bypassed entirely and the legacy unlock proceeds — backwards
    ///   compatibility is automatic for users who add a key to an
    ///   already-initialized vault (they will need to re-key via
    ///   `envseal security fido2-enroll` to migrate to v3, which
    ///   ships in commit 2).
    ///
    /// # Errors
    ///
    /// Returns the same errors as the passphrase-only variant plus
    /// [`Error::Fido2AssertionFailed`] when the authenticator
    /// rejects the assertion.
    pub fn open_master_key_with_passphrase_and_fido2<A>(
        root: &Path,
        passphrase: &Zeroizing<String>,
        authenticator: &mut A,
    ) -> Result<MasterKey, Error>
    where
        A: fido2::Fido2Authenticator,
    {
        let mk_path = master_key_path(root);
        let exists = mk_path.exists();

        // Audit H5: refuse to silently delete a too-short master.key.
        // Mirror the policy of `open_master_key` on the FIDO2 path.
        if exists {
            match std::fs::read(&mk_path) {
                Err(e) => return Err(Error::StorageIo(e)),
                Ok(raw) => {
                    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 _ = crate::audit::log_required_at(
                                root,
                                &crate::audit::AuditEvent::SignalRecorded {
                                    tier: "Lockdown".to_string(),
                                    classification: format!(
                                        "critical [vault.master_key.corrupt] {} bytes \
                                         (need >= {min_v1_len}); refusing to auto-delete \
                                         (FIDO2 path)",
                                        raw.len()
                                    ),
                                },
                            );
                            return Err(Error::CryptoFailure(format!(
                                "master.key at {} is too short to be valid ({} bytes; need \
                                 >= {min_v1_len}). envseal refuses to silently delete it; \
                                 restore from backup or explicitly remove the file before \
                                 retrying.",
                                mk_path.display(),
                                raw.len(),
                            )));
                        }
                    }
                }
            }
        }

        if exists {
            unlock_master_key_with_fido2(&mk_path, passphrase, authenticator)
        } else {
            create_master_key_with_fido2(root, &mk_path, passphrase, authenticator)
        }
    }

    /// Create a new v3 master.key by enrolling the supplied
    /// authenticator. Writes a v3 inner blob wrapped by the active
    /// hardware backend exactly the same way the v1 path does — the
    /// only difference is the inner layout.
    pub fn create_master_key_with_fido2<A>(
        root: &Path,
        mk_path: &Path,
        passphrase: &Zeroizing<String>,
        authenticator: &mut A,
    ) -> Result<MasterKey, Error>
    where
        A: fido2::Fido2Authenticator,
    {
        validate_passphrase(passphrase)?;

        // Enroll the authenticator. The credential id is opaque to
        // us; we store it verbatim in the envelope.
        let credential_id = authenticator.make_credential(RELYING_PARTY_ID, RELYING_PARTY_NAME)?;

        // Generate fresh random salts for this vault.
        let mut master_bytes = [0u8; MASTER_KEY_LEN];
        OsRng.fill_bytes(&mut master_bytes);

        let mut argon2_salt = [0u8; ARGON2_SALT_LEN];
        OsRng.fill_bytes(&mut argon2_salt);

        let mut hmac_salt = [0u8; fido2::HMAC_SALT_LEN];
        OsRng.fill_bytes(&mut hmac_salt);

        // Pull the FIDO2 hmac-secret response and combine with the
        // Argon2-derived passphrase half to produce the wrapping key.
        let fido2_secret = authenticator.assert_with_hmac(&credential_id, &hmac_salt)?;
        let argon2_output = derive_wrapping_key(passphrase, &argon2_salt)?;
        let wrapping_key =
            fido2::combine_passphrase_and_fido2(&argon2_output, &fido2_secret, &hmac_salt);

        // Encrypt the master key under the v3 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!("v3: failed to wrap master key: {e}")))?;

        let envelope = fido2::V3Envelope {
            credential_id,
            hmac_salt,
            argon2_salt,
            nonce: nonce.into(),
            ciphertext,
        };
        let inner = fido2::pack(&envelope)?;

        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);
        hmac_salt.fill(0);

        // Best-effort wipe of the temporaries — Zeroizing handles the
        // wrapping key and argon2 output.
        drop(wrapping_key);
        drop(argon2_output);

        Ok(key)
    }

    /// Unlock an existing master.key. v3 envelopes consume the
    /// authenticator; v1/v2 envelopes bypass it via the legacy
    /// passphrase path (so attaching a key to a non-FIDO2 vault is
    /// a no-op until the user re-keys with `fido2-enroll`).
    pub fn unlock_master_key_with_fido2<A>(
        mk_path: &Path,
        passphrase: &Zeroizing<String>,
        authenticator: &mut A,
    ) -> Result<MasterKey, Error>
    where
        A: fido2::Fido2Authenticator,
    {
        let raw = fs::read(mk_path)?;
        let inner = read_inner_envelope_at(&raw, Some(mk_path))?;

        if !fido2::is_v3(&inner) {
            // Legacy v1/v2 vault — FIDO2 not in use here. Use the
            // standard passphrase path. The authenticator parameter
            // is intentionally unused; backwards compat means
            // attaching a key to a non-FIDO2 vault is silent.
            let _ = authenticator;
            return unlock_master_key_v1_inner(&inner, passphrase);
        }

        let env = fido2::parse(&inner)?;
        let cred_hash = credential_id_hash(&env.credential_id);

        // Derive both halves and combine. Argon2 first (slow, cheap
        // failure if passphrase is bad? — no, Argon2 cannot fail on
        // bad passphrase since it just hashes; the actual passphrase
        // check happens in AEAD-decrypt below). FIDO2 second (fast,
        // requires touch — bad passphrase still costs the user a
        // touch, which is acceptable: the touch is the second
        // factor, not a confirmation of the first).
        let argon2_output = derive_wrapping_key(passphrase, &env.argon2_salt)?;
        let fido2_secret = match authenticator.assert_with_hmac(&env.credential_id, &env.hmac_salt)
        {
            Ok(s) => s,
            Err(e) => {
                let _ = crate::audit::log(&crate::audit::AuditEvent::Fido2Unlock {
                    credential_id_hash: cred_hash.clone(),
                    succeeded: false,
                });
                return Err(e);
            }
        };
        let wrapping_key =
            fido2::combine_passphrase_and_fido2(&argon2_output, &fido2_secret, &env.hmac_salt);

        let result = decrypt_master_key_with_wrap(wrapping_key, &env.nonce, &env.ciphertext);
        let _ = crate::audit::log(&crate::audit::AuditEvent::Fido2Unlock {
            credential_id_hash: cred_hash,
            succeeded: result.is_ok(),
        });
        result
    }

    /// Re-wrap an unlocked master key from v1/v2 layout into a v3
    /// envelope, enrolling the supplied authenticator.
    ///
    /// Use case: an existing vault user wants to add a security key
    /// without rotating every stored secret. We keep the master key
    /// bytes identical (so every existing `*.seal` file in the
    /// vault still decrypts) and only change the wrapping layer.
    pub fn enroll_fido2_on_existing_master<A>(
        mk_path: &Path,
        master_key: &MasterKey,
        passphrase: &Zeroizing<String>,
        authenticator: &mut A,
    ) -> Result<(), Error>
    where
        A: fido2::Fido2Authenticator,
    {
        validate_passphrase(passphrase)?;

        let credential_id = authenticator.make_credential(RELYING_PARTY_ID, RELYING_PARTY_NAME)?;

        let mut argon2_salt = [0u8; ARGON2_SALT_LEN];
        OsRng.fill_bytes(&mut argon2_salt);

        let mut hmac_salt = [0u8; fido2::HMAC_SALT_LEN];
        OsRng.fill_bytes(&mut hmac_salt);

        let fido2_secret = authenticator.assert_with_hmac(&credential_id, &hmac_salt)?;
        let argon2_output = derive_wrapping_key(passphrase, &argon2_salt)?;
        let wrapping_key =
            fido2::combine_passphrase_and_fido2(&argon2_output, &fido2_secret, &hmac_salt);

        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!("v3 enroll: re-wrap failed: {e}")))?;

        let envelope = fido2::V3Envelope {
            credential_id,
            hmac_salt,
            argon2_salt,
            nonce: nonce.into(),
            ciphertext,
        };
        let inner = fido2::pack(&envelope)?;

        write_master_file(mk_path, &inner)?;

        argon2_salt.fill(0);
        hmac_salt.fill(0);
        drop(wrapping_key);
        drop(argon2_output);
        Ok(())
    }

    /// Re-wrap an unlocked master key from v3 back into the v1
    /// passphrase-only layout. Used by `envseal security
    /// fido2-disable` once the user has authenticated to remove
    /// the security-key requirement.
    pub fn disable_fido2_keep_master(
        mk_path: &Path,
        master_key: &MasterKey,
        passphrase: &Zeroizing<String>,
    ) -> Result<(), Error> {
        validate_passphrase(passphrase)?;

        let mut argon2_salt = [0u8; ARGON2_SALT_LEN];
        OsRng.fill_bytes(&mut argon2_salt);

        let wrapping_key = derive_wrapping_key(passphrase, &argon2_salt)?;
        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!("v3 disable: re-wrap failed: {e}")))?;

        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);

        write_master_file(mk_path, &inner)?;

        argon2_salt.fill(0);
        drop(wrapping_key);
        Ok(())
    }

    /// Inspect a master.key file and report whether it is v3
    /// (FIDO2-enrolled) and, if so, the credential id.
    pub fn fido2_status_at(mk_path: &Path) -> Result<Fido2Status, Error> {
        if !mk_path.exists() {
            return Ok(Fido2Status::NoVault);
        }
        let raw = std::fs::read(mk_path)?;
        let inner = read_inner_envelope_at(&raw, None)?;
        if !fido2::is_v3(&inner) {
            return Ok(Fido2Status::NotEnrolled);
        }
        let env = fido2::parse(&inner)?;
        Ok(Fido2Status::Enrolled {
            credential_id: env.credential_id,
        })
    }

    /// Return value of [`fido2_status_at`].
    #[derive(Debug, Clone)]
    pub enum Fido2Status {
        /// `master.key` does not exist on disk.
        NoVault,
        /// `master.key` exists but is a v1/v2 envelope.
        NotEnrolled,
        /// `master.key` is a v3 envelope.
        Enrolled {
            /// Opaque credential id stored in the envelope.
            credential_id: Vec<u8>,
        },
    }

    /// Hex-encoded SHA-256 of a credential id. Stable identifier for
    /// audit logs and doctor reports without leaking the raw id.
    #[must_use]
    pub fn credential_id_hash(credential_id: &[u8]) -> String {
        use sha2::Digest;
        use std::fmt::Write as _;
        let digest = sha2::Sha256::digest(credential_id);
        let mut out = String::with_capacity(digest.len() * 2);
        for b in digest {
            let _ = write!(out, "{b:02x}");
        }
        out
    }
}

#[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(all(test, feature = "fido2"))]
mod fido2_e2e_tests {
    use super::fido2_unlock::{
        create_master_key_with_fido2, credential_id_hash, disable_fido2_keep_master,
        enroll_fido2_on_existing_master, fido2_status_at,
        open_master_key_with_passphrase_and_fido2, unlock_master_key_with_fido2, Fido2Status,
    };
    use super::*;
    use crate::error::Error;
    use crate::vault::fido2::tests::MockAuthenticator;
    use tempfile::tempdir;

    fn mk_passphrase() -> Zeroizing<String> {
        Zeroizing::new("correct-horse-battery-staple".to_string())
    }

    #[test]
    fn create_then_unlock_with_same_authenticator_succeeds() {
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let mut auth = MockAuthenticator::new([0x42; 32]);

        let pass = mk_passphrase();
        let key1 =
            create_master_key_with_fido2(dir.path(), &mk, &pass, &mut auth).expect("create v3");
        let key1_bytes = *key1.as_bytes();

        let key2 = unlock_master_key_with_fido2(&mk, &pass, &mut auth).expect("unlock v3");
        assert_eq!(
            *key2.as_bytes(),
            key1_bytes,
            "round-trip through v3 envelope must preserve master key bytes"
        );
    }

    #[test]
    fn unlock_v3_without_authenticator_returns_fido2_required() {
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let mut auth = MockAuthenticator::new([0x77; 32]);

        let pass = mk_passphrase();
        let _ = create_master_key_with_fido2(dir.path(), &mk, &pass, &mut auth).unwrap();

        // Try to unlock through the legacy passphrase-only path —
        // must surface Fido2Required, not silently fall through.
        let err = unlock_master_key_with(&mk, &pass).unwrap_err();
        assert!(
            matches!(err, Error::Fido2Required),
            "expected Fido2Required, got {err:?}"
        );
    }

    #[test]
    fn unlock_v3_with_wrong_authenticator_fails() {
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let mut enroll = MockAuthenticator::new([0xAA; 32]);

        let pass = mk_passphrase();
        let _ = create_master_key_with_fido2(dir.path(), &mk, &pass, &mut enroll).unwrap();

        // A different authenticator (different device key) cannot
        // produce the right hmac-secret output. The credential id
        // it doesn't recognize → assertion fails. Even if we
        // construct a mock that recognizes the id, the per-credential
        // key would differ and the AES-GCM unwrap would fail. Both
        // failure modes are acceptable; assert that one of them
        // happens (i.e. unlock is not successful).
        let mut wrong = MockAuthenticator::new([0xBB; 32]);
        let result = unlock_master_key_with_fido2(&mk, &pass, &mut wrong);
        assert!(result.is_err(), "wrong authenticator must not unlock");
    }

    #[test]
    fn unlock_v3_with_wrong_passphrase_fails() {
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let mut auth = MockAuthenticator::new([0xCC; 32]);

        let pass = mk_passphrase();
        let _ = create_master_key_with_fido2(dir.path(), &mk, &pass, &mut auth).unwrap();

        let bad_pass = Zeroizing::new("wrong-passphrase".to_string());
        let result = unlock_master_key_with_fido2(&mk, &bad_pass, &mut auth);
        match result {
            Err(Error::CryptoFailure(msg)) => assert!(
                msg.contains("decryption failed"),
                "expected decrypt error, got {msg}"
            ),
            other => panic!("expected CryptoFailure, got {other:?}"),
        }
    }

    #[test]
    fn open_with_fido2_creates_when_missing_and_unlocks_when_present() {
        let dir = tempdir().unwrap();
        let mut auth = MockAuthenticator::new([0xDE; 32]);
        let pass = mk_passphrase();

        // Missing → create.
        let key1 = open_master_key_with_passphrase_and_fido2(dir.path(), &pass, &mut auth).unwrap();
        let key1_bytes = *key1.as_bytes();

        // Present → unlock.
        let key2 = open_master_key_with_passphrase_and_fido2(dir.path(), &pass, &mut auth).unwrap();
        assert_eq!(*key2.as_bytes(), key1_bytes);
    }

    #[test]
    fn enroll_then_unlock_preserves_master_key_bytes() {
        // The whole point of `enroll_fido2_on_existing_master` is
        // that the master key bytes survive the re-wrap, so every
        // existing vaulted secret stays decryptable. Pin that
        // contract.
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let pass = mk_passphrase();

        let key_v1 = create_master_key_with(dir.path(), &mk, &pass).unwrap();
        let bytes_v1 = *key_v1.as_bytes();
        drop(key_v1);

        // Enroll a mock authenticator on top.
        let mut auth = MockAuthenticator::new([0x10; 32]);
        let key_v1_again = open_master_key_with_passphrase(dir.path(), &pass).unwrap();
        enroll_fido2_on_existing_master(&mk, &key_v1_again, &pass, &mut auth).unwrap();
        drop(key_v1_again);

        // The vault is now v3.
        match fido2_status_at(&mk).unwrap() {
            Fido2Status::Enrolled { .. } => {}
            other => panic!("expected v3 after enroll, got {other:?}"),
        }

        // Unlock through the FIDO2 path — bytes must match.
        let key_v3 = unlock_master_key_with_fido2(&mk, &pass, &mut auth).unwrap();
        assert_eq!(
            *key_v3.as_bytes(),
            bytes_v1,
            "enrollment must not rotate the master key bytes"
        );
    }

    #[test]
    fn enroll_then_disable_round_trips_back_to_v1() {
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let pass = mk_passphrase();

        let key_v1 = create_master_key_with(dir.path(), &mk, &pass).unwrap();
        let bytes_original = *key_v1.as_bytes();
        drop(key_v1);

        // Enroll.
        let mut auth = MockAuthenticator::new([0x20; 32]);
        let key_for_enroll = open_master_key_with_passphrase(dir.path(), &pass).unwrap();
        enroll_fido2_on_existing_master(&mk, &key_for_enroll, &pass, &mut auth).unwrap();
        drop(key_for_enroll);
        assert!(matches!(
            fido2_status_at(&mk).unwrap(),
            Fido2Status::Enrolled { .. }
        ));

        // Disable.
        let key_for_disable = unlock_master_key_with_fido2(&mk, &pass, &mut auth).unwrap();
        disable_fido2_keep_master(&mk, &key_for_disable, &pass).unwrap();
        drop(key_for_disable);
        assert!(matches!(
            fido2_status_at(&mk).unwrap(),
            Fido2Status::NotEnrolled
        ));

        // Standard unlock must work again, with the original bytes.
        let key_after = open_master_key_with_passphrase(dir.path(), &pass).unwrap();
        assert_eq!(*key_after.as_bytes(), bytes_original);
    }

    #[test]
    fn fido2_status_at_reports_no_vault_when_file_missing() {
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        match fido2_status_at(&mk).unwrap() {
            Fido2Status::NoVault => {}
            other => panic!("expected NoVault, got {other:?}"),
        }
    }

    #[test]
    fn fido2_status_at_reports_not_enrolled_for_v1_vault() {
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let pass = mk_passphrase();
        let _ = create_master_key_with(dir.path(), &mk, &pass).unwrap();
        match fido2_status_at(&mk).unwrap() {
            Fido2Status::NotEnrolled => {}
            other => panic!("expected NotEnrolled, got {other:?}"),
        }
    }

    #[test]
    fn credential_id_hash_is_stable_64_hex_chars() {
        let id = b"opaque-credential-bytes-of-some-length-32+bytes";
        let h = credential_id_hash(id);
        assert_eq!(h.len(), 64);
        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));

        // Same input → same hash.
        assert_eq!(h, credential_id_hash(id));

        // Different input → different hash.
        let different = credential_id_hash(b"different-credential");
        assert_ne!(h, different);
    }

    #[test]
    fn enroll_disable_repeats_with_fresh_credential_each_cycle() {
        // Enroll, disable, enroll again — the second enrollment
        // must succeed with a fresh credential id (not be silently
        // blocked by stale state).
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let pass = mk_passphrase();
        let _ = create_master_key_with(dir.path(), &mk, &pass).unwrap();

        let mut auth1 = MockAuthenticator::new([0x33; 32]);
        let key = open_master_key_with_passphrase(dir.path(), &pass).unwrap();
        enroll_fido2_on_existing_master(&mk, &key, &pass, &mut auth1).unwrap();
        drop(key);
        let Fido2Status::Enrolled {
            credential_id: cred1,
        } = fido2_status_at(&mk).unwrap()
        else {
            panic!("not enrolled after first enroll");
        };

        let key = unlock_master_key_with_fido2(&mk, &pass, &mut auth1).unwrap();
        disable_fido2_keep_master(&mk, &key, &pass).unwrap();
        drop(key);

        // Fresh authenticator (different device key) for second enrollment.
        let mut auth2 = MockAuthenticator::new([0x44; 32]);
        let key = open_master_key_with_passphrase(dir.path(), &pass).unwrap();
        enroll_fido2_on_existing_master(&mk, &key, &pass, &mut auth2).unwrap();
        let Fido2Status::Enrolled {
            credential_id: cred2,
        } = fido2_status_at(&mk).unwrap()
        else {
            panic!("not enrolled after second enroll");
        };

        assert_ne!(
            cred1, cred2,
            "second enrollment with a different authenticator must yield a different credential id"
        );
    }

    #[test]
    fn unlock_v3_with_corrupted_envelope_fails_clean() {
        // Truncating the v3 envelope after enrollment must fail
        // with a clean parse error, not panic.
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let pass = mk_passphrase();
        let mut auth = MockAuthenticator::new([0x55; 32]);
        let _ = create_master_key_with_fido2(dir.path(), &mk, &pass, &mut auth).unwrap();

        // Truncate the file to ~half its size.
        let raw = std::fs::read(&mk).unwrap();
        let truncated = &raw[..raw.len() / 2];
        std::fs::write(&mk, truncated).unwrap();

        let result = unlock_master_key_with_fido2(&mk, &pass, &mut auth);
        assert!(result.is_err(), "truncated v3 envelope must fail to unlock");
    }

    #[test]
    fn fido2_path_does_not_disturb_legacy_v1_vault() {
        // A v1 vault (created without FIDO2) must still unlock
        // through the FIDO2-aware entry point — the authenticator
        // is silently bypassed because the inner blob is not v3.
        // This is the LAW 2 backwards-compat guarantee: existing
        // users who upgrade to a FIDO2-capable client don't see a
        // disruption until they explicitly enroll a key.
        let dir = tempdir().unwrap();
        let mk = master_key_path(dir.path());
        let pass = mk_passphrase();
        let key1 = create_master_key_with(dir.path(), &mk, &pass).unwrap();
        let key1_bytes = *key1.as_bytes();
        drop(key1);

        let mut auth = MockAuthenticator::new([0xEF; 32]);
        let key2 =
            unlock_master_key_with_fido2(&mk, &pass, &mut auth).expect("v1 vault must still open");
        assert_eq!(*key2.as_bytes(), key1_bytes);
    }
}

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