secrets-vault 2.3.0

AES-256-GCM encrypted key-value vault with PBKDF2 key derivation. Store API keys and tokens securely instead of plaintext dotfiles.
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
//! # secrets-vault
//!
//! AES-256-GCM encrypted key-value vault. **QVLT v2** encrypts every entry under
//! its own HKDF-derived key, so reading one secret decrypts exactly one record —
//! never the whole vault. The legacy v1 single-blob format is still readable
//! (migration only). Full format spec: `QVLT2_SPEC.md`.
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use secrets_vault::Vault;
//!
//! // Create or load a vault
//! let mut vault = Vault::new();
//! vault.set("API_KEY", "sk-secret-123");
//! vault.set("DB_URL", "postgres://localhost/mydb");
//!
//! // Encrypt and save
//! let bytes = vault.encrypt("my-passphrase")?;
//! std::fs::write("vault.qvlt", &bytes)?;
//!
//! // Load and decrypt
//! let data = std::fs::read("vault.qvlt")?;
//! let vault = Vault::decrypt(&data, "my-passphrase")?;
//! assert_eq!(vault.get("API_KEY"), Some("sk-secret-123"));
//! # Ok::<(), secrets_vault::VaultError>(())
//! ```
//!
//! ## Vault File Format (QVLT v2 — see QVLT2_SPEC.md §4)
//!
//! ```text
//! [4]  Magic "QVLT"   [1] Version 0x02   [1] KDF id   [2] Flags (0)
//! [16] Vault salt (stable across saves)  [4] u32 entry count
//! per entry (sorted by name): [1] scheme  [2] name len  [N] name
//!                             [12] nonce  [16] tag  [4] ct len  [C] ct
//! [32] Manifest MAC = HMAC-SHA256(mac_key, file[..len-32])
//! ```
//!
//! v1 (version 0x01) is a single blob: salt + nonce + tag + one ciphertext of
//! all entries. Kept read-only for migration.
//!
//! ## Security
//!
//! - AES-256-GCM authenticated encryption per entry; AAD binds version‖scheme‖name
//! - PBKDF2-HMAC-SHA256 @ 600,000 iterations once per open → HKDF-SHA256 per entry
//! - Values padded to 32-byte buckets (true length inside the authenticated plaintext)
//! - Whole-file HMAC-SHA256 manifest (constant-time verify) — deletion/reorder/rollback-within-file detection
//! - Plaintext and key material zeroized after use

use std::collections::BTreeMap;
use std::io::Write;

use aes_gcm::aead::{AeadInOut, Generate, KeyInit};
use aes_gcm::{Aes256Gcm, Key, Nonce, Tag};
use zeroize::{Zeroize, Zeroizing};

// ── Constants ──

const MAGIC: [u8; 4] = *b"QVLT";
const VERSION: u8 = 0x01;
/// Vault-level KDF salt length (v1 and v2).
pub const SALT_LEN: usize = 16;
const NONCE_LEN: usize = 12;
const TAG_LEN: usize = 16;
const HEADER_LEN: usize = 4 + 1 + SALT_LEN + NONCE_LEN + TAG_LEN; // 49

/// PBKDF2 iteration count (OWASP 2023 recommendation for SHA-256).
pub const ITERATIONS: u32 = 600_000;

/// Maximum key name length in bytes.
pub const MAX_KEY_LEN: usize = 256;

/// Maximum value length in bytes.
pub const MAX_VALUE_LEN: usize = 65536;

// ── Errors ──

/// Errors that can occur during vault operations.
#[derive(Debug)]
pub enum VaultError {
    /// Vault file is too small to contain a valid header.
    TooSmall,
    /// Magic bytes don't match "QVLT".
    BadMagic,
    /// Vault version is not supported.
    UnsupportedVersion(u8),
    /// AES-GCM decryption failed — wrong passphrase or tampered data.
    DecryptionFailed,
    /// AES-GCM encryption failed.
    EncryptionFailed,
    /// Vault data is malformed.
    MalformedData,
    /// v2: header names a KDF this build doesn't implement.
    UnsupportedKdf(u8),
    /// v2: unknown header flag bits set — fail closed (spec §4).
    UnsupportedFlags(u16),
    /// v2: entry uses a key scheme this build doesn't implement (spec §4.6).
    UnknownScheme(u8),
    /// v2: no entry with the requested name.
    NotFound,
    /// I/O error.
    Io(std::io::Error),
}

impl std::fmt::Display for VaultError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TooSmall => write!(f, "vault file too small"),
            Self::BadMagic => write!(f, "invalid vault file (bad magic)"),
            Self::UnsupportedVersion(v) => write!(f, "unsupported vault version: {v}"),
            Self::DecryptionFailed => write!(f, "decryption failed (wrong passphrase?)"),
            Self::EncryptionFailed => write!(f, "encryption failed"),
            Self::MalformedData => write!(f, "malformed vault data"),
            Self::UnsupportedKdf(k) => write!(f, "unsupported KDF id: {k}"),
            Self::UnsupportedFlags(fl) => write!(f, "unsupported vault flags: {fl:#06x}"),
            Self::UnknownScheme(s) => write!(f, "unknown entry key scheme: {s}"),
            Self::NotFound => write!(f, "key not found"),
            Self::Io(e) => write!(f, "I/O error: {e}"),
        }
    }
}

impl std::error::Error for VaultError {}

impl From<std::io::Error> for VaultError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

// ── Vault ──

/// An in-memory key-value store that can be encrypted to/from the QVLT format.
///
/// Keys are stored sorted (BTreeMap) for deterministic output.
/// Values are zeroed from memory when the vault is dropped.
#[derive(Debug, Clone)]
pub struct Vault {
    entries: BTreeMap<String, String>,
}

impl Vault {
    /// Create an empty vault.
    pub fn new() -> Self {
        Self {
            entries: BTreeMap::new(),
        }
    }

    /// Create a vault from an existing map.
    pub fn from_map(entries: BTreeMap<String, String>) -> Self {
        Self { entries }
    }

    /// Get a value by key.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.entries.get(key).map(|s| s.as_str())
    }

    /// Set a key-value pair. Returns the previous value if the key existed.
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) -> Option<String> {
        self.entries.insert(key.into(), value.into())
    }

    /// Remove a key. Returns the value if it existed.
    pub fn delete(&mut self, key: &str) -> Option<String> {
        self.entries.remove(key)
    }

    /// List all key names (sorted).
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.entries.keys().map(|s| s.as_str())
    }

    /// Iterate over all key-value pairs (sorted by key).
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.entries.iter().map(|(k, v)| (k.as_str(), v.as_str()))
    }

    /// Number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the vault is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get a mutable reference to the underlying map.
    pub fn entries_mut(&mut self) -> &mut BTreeMap<String, String> {
        &mut self.entries
    }

    /// Clone the underlying map. (Cannot move due to Drop impl that zeroes memory.)
    pub fn to_map(&self) -> BTreeMap<String, String> {
        self.entries.clone()
    }

    // ── Encryption / Decryption ──

    /// Encrypt the vault into QVLT binary format.
    ///
    /// Uses a fresh random salt and nonce each time, so calling this twice
    /// with the same data produces different ciphertext.
    pub fn encrypt(&self, passphrase: &str) -> Result<Vec<u8>, VaultError> {
        let mut plaintext = serialize(&self.entries);

        let mut salt = [0u8; SALT_LEN];
        getrandom::fill(&mut salt).expect("OS RNG failure");
        let nonce = Nonce::generate();

        let key = derive_key(passphrase, &salt);
        let cipher = Aes256Gcm::new(&key);

        let tag = cipher
            .encrypt_inout_detached(&nonce, b"", plaintext.as_mut_slice().into())
            .map_err(|_| VaultError::EncryptionFailed)?;

        // Zero the derived key (it's on the stack, but let's be explicit)
        drop(cipher);

        let mut out = Vec::with_capacity(HEADER_LEN + plaintext.len());
        out.write_all(&MAGIC)?;
        out.write_all(&[VERSION])?;
        out.write_all(&salt)?;
        out.write_all(nonce.as_slice())?;
        out.write_all(tag.as_slice())?;
        out.write_all(&plaintext)?;

        Ok(out)
    }

    /// Decrypt a QVLT binary blob into a vault.
    ///
    /// Returns `VaultError::DecryptionFailed` if the passphrase is wrong
    /// or the data has been tampered with.
    pub fn decrypt(data: &[u8], passphrase: &str) -> Result<Self, VaultError> {
        if data.len() < HEADER_LEN {
            return Err(VaultError::TooSmall);
        }
        if data[0..4] != MAGIC {
            return Err(VaultError::BadMagic);
        }
        if data[4] != VERSION {
            return Err(VaultError::UnsupportedVersion(data[4]));
        }

        let salt = &data[5..5 + SALT_LEN];
        let nonce_bytes = &data[5 + SALT_LEN..5 + SALT_LEN + NONCE_LEN];
        let tag_bytes = &data[5 + SALT_LEN + NONCE_LEN..HEADER_LEN];
        let ciphertext = &data[HEADER_LEN..];

        let key = derive_key(passphrase, salt);
        let cipher = Aes256Gcm::new(&key);
        let nonce: &Nonce<_> = nonce_bytes.try_into().expect("nonce length is structural");
        let tag: &Tag = tag_bytes.try_into().expect("tag length is structural");

        let mut buf = ciphertext.to_vec();
        cipher
            .decrypt_inout_detached(nonce, b"", buf.as_mut_slice().into(), tag)
            .map_err(|_| VaultError::DecryptionFailed)?;

        let entries = deserialize(&buf);

        // Zero plaintext
        buf.zeroize();

        Ok(Self { entries })
    }

    // ── Shell output helpers ──

    /// Format all entries as `export KEY='VALUE'` lines for shell eval.
    ///
    /// Single quotes in values are escaped as `'\''`.
    pub fn to_shell_exports(&self) -> String {
        let mut out = String::new();
        for (key, value) in &self.entries {
            let escaped = value.replace('\'', "'\\''");
            out.push_str(&format!("export {key}='{escaped}'\n"));
        }
        out
    }

    /// Format all entries as a JSON object.
    pub fn to_json(&self) -> String {
        let mut out = String::from("{\n");
        let len = self.entries.len();
        for (i, (key, value)) in self.entries.iter().enumerate() {
            let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
            out.push_str(&format!("  \"{key}\": \"{escaped}\""));
            if i + 1 < len {
                out.push(',');
            }
            out.push('\n');
        }
        out.push_str("}\n");
        out
    }
}

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

impl Drop for Vault {
    fn drop(&mut self) {
        // Zero all values in memory
        for value in self.entries.values_mut() {
            unsafe {
                let bytes = value.as_bytes_mut();
                bytes.zeroize();
            }
        }
    }
}

// ── Key validation ──

/// Check if a key name is valid: non-empty, ≤256 bytes, and `[A-Za-z0-9_-]` only.
/// This is exactly Google Secret Manager's allowed secret-ID charset (hyphens are
/// valid there; dots are NOT), so a key that validates here is storable in every
/// backend — keychain account, HashMap key, and GSM secret ID alike. Hyphens matter
/// in practice: many real-world secret names are kebab-case (e.g. `prod-db-password`).
pub fn is_valid_key(key: &str) -> bool {
    !key.is_empty()
        && key.len() <= MAX_KEY_LEN
        && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

/// Check a project namespace is safe to use as a vault-key prefix: non-empty,
/// ≤256 bytes, and `[A-Za-z0-9_.-]` only — crucially NO slash, so `project/KEY`
/// has exactly one separator and can't be traversal/injection-abused.
pub fn is_valid_project(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= MAX_KEY_LEN
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
}

/// Parse KEY=VALUE lines (with optional `export` prefix and quote stripping).
///
/// Useful for importing from `.env` files or shell config exports.
pub fn parse_env_lines(input: &str) -> Vec<(String, String)> {
    let mut pairs = Vec::new();
    for line in input.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let kv = trimmed.strip_prefix("export ").unwrap_or(trimmed);
        if let Some((key, value)) = kv.split_once('=') {
            let key = key.trim();
            let value = value
                .trim()
                .trim_start_matches(|c| c == '"' || c == '\'')
                .trim_end_matches(|c| c == '"' || c == '\'');
            if is_valid_key(key) && !value.is_empty() {
                pairs.push((key.to_string(), value.to_string()));
            }
        }
    }
    pairs
}

/// Generate `n` cryptographically secure random bytes from the OS CSPRNG.
/// Used by `secrets gen` so a fresh credential never has to be printed.
pub fn random_bytes(n: usize) -> Vec<u8> {
    let mut buf = vec![0u8; n];
    getrandom::fill(&mut buf).expect("OS RNG failure");
    buf
}

/// Fresh random vault salt (v2: generated at vault creation / `rekey` only —
/// stable across ordinary saves so splicing needs no re-encryption).
pub fn random_salt() -> [u8; SALT_LEN] {
    let mut salt = [0u8; SALT_LEN];
    getrandom::fill(&mut salt).expect("OS RNG failure");
    salt
}

/// Encrypt arbitrary bytes into the same QVLT container the vault uses (AES-256-GCM,
/// PBKDF2-SHA256 @ 600k, fresh salt+nonce). Lets other on-disk artifacts (e.g. the
/// scoped registry) reuse the audited crypto core without touching `Vault`.
pub fn encrypt_blob(plaintext: &[u8], passphrase: &str) -> Result<Vec<u8>, VaultError> {
    let mut buf = plaintext.to_vec();
    let mut salt = [0u8; SALT_LEN];
    getrandom::fill(&mut salt).expect("OS RNG failure");
    let nonce = Nonce::generate();
    let key = derive_key(passphrase, &salt);
    let cipher = Aes256Gcm::new(&key);
    let tag = cipher
        .encrypt_inout_detached(&nonce, b"", buf.as_mut_slice().into())
        .map_err(|_| VaultError::EncryptionFailed)?;

    let mut out = Vec::with_capacity(HEADER_LEN + buf.len());
    out.write_all(&MAGIC)?;
    out.write_all(&[VERSION])?;
    out.write_all(&salt)?;
    out.write_all(nonce.as_slice())?;
    out.write_all(tag.as_slice())?;
    out.write_all(&buf)?;
    buf.zeroize();
    Ok(out)
}

/// Decrypt a QVLT container produced by [`encrypt_blob`]. Returns the plaintext
/// bytes (caller zeroizes after use).
pub fn decrypt_blob(data: &[u8], passphrase: &str) -> Result<Vec<u8>, VaultError> {
    if data.len() < HEADER_LEN {
        return Err(VaultError::TooSmall);
    }
    if data[0..4] != MAGIC {
        return Err(VaultError::BadMagic);
    }
    if data[4] != VERSION {
        return Err(VaultError::UnsupportedVersion(data[4]));
    }
    let salt = &data[5..5 + SALT_LEN];
    let nonce_bytes = &data[5 + SALT_LEN..5 + SALT_LEN + NONCE_LEN];
    let tag_bytes = &data[5 + SALT_LEN + NONCE_LEN..HEADER_LEN];
    let ciphertext = &data[HEADER_LEN..];

    let key = derive_key(passphrase, salt);
    let cipher = Aes256Gcm::new(&key);
    let nonce: &Nonce<_> = nonce_bytes.try_into().expect("nonce length is structural");
    let tag: &Tag = tag_bytes.try_into().expect("tag length is structural");

    let mut buf = ciphertext.to_vec();
    cipher
        .decrypt_inout_detached(nonce, b"", buf.as_mut_slice().into(), tag)
        .map_err(|_| VaultError::DecryptionFailed)?;
    Ok(buf)
}

// ── Internal: Binary serialization (QVLT format) ──

fn serialize(entries: &BTreeMap<String, String>) -> Vec<u8> {
    let mut buf = Vec::new();
    for (key, value) in entries {
        let klen = key.len();
        buf.push((klen >> 8) as u8);
        buf.push((klen & 0xFF) as u8);
        buf.extend_from_slice(key.as_bytes());
        let vlen = value.len();
        buf.push((vlen >> 24) as u8);
        buf.push(((vlen >> 16) & 0xFF) as u8);
        buf.push(((vlen >> 8) & 0xFF) as u8);
        buf.push((vlen & 0xFF) as u8);
        buf.extend_from_slice(value.as_bytes());
    }
    buf.extend_from_slice(&[0x00, 0x00]);
    buf
}

fn deserialize(data: &[u8]) -> BTreeMap<String, String> {
    let mut entries = BTreeMap::new();
    let mut pos = 0;
    while pos + 2 <= data.len() {
        let klen = ((data[pos] as usize) << 8) | (data[pos + 1] as usize);
        pos += 2;
        if klen == 0 {
            break;
        }
        if klen > MAX_KEY_LEN || pos + klen > data.len() {
            break;
        }
        let key = String::from_utf8_lossy(&data[pos..pos + klen]).to_string();
        pos += klen;
        if pos + 4 > data.len() {
            break;
        }
        let vlen = ((data[pos] as usize) << 24)
            | ((data[pos + 1] as usize) << 16)
            | ((data[pos + 2] as usize) << 8)
            | (data[pos + 3] as usize);
        pos += 4;
        if vlen > MAX_VALUE_LEN || pos + vlen > data.len() {
            break;
        }
        let value = String::from_utf8_lossy(&data[pos..pos + vlen]).to_string();
        pos += vlen;
        entries.insert(key, value);
    }
    entries
}

// ── Internal: Crypto ──

fn derive_key(passphrase: &str, salt: &[u8]) -> Key<Aes256Gcm> {
    let key =
        pbkdf2::pbkdf2_hmac_array::<sha2::Sha256, 32>(passphrase.as_bytes(), salt, ITERATIONS);
    Key::<Aes256Gcm>::try_from(&key[..]).expect("PBKDF2 output is 32 bytes")
}

// ═══════════════════════════════════════════════════════════════════════════
// QVLT v2 — per-entry encryption (QVLT2_SPEC.md)
// ═══════════════════════════════════════════════════════════════════════════

use hmac::Mac;

/// HMAC constructor. Since crypto-common 0.2 there is ONE `KeyInit` trait
/// shared by the cipher and the MAC, so the old `Mac`-vs-`KeyInit`
/// disambiguation is gone.
fn new_hmac(key: &[u8]) -> HmacSha256 {
    <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length")
}

/// v2 version byte.
pub const V2_VERSION: u8 = 0x02;
/// KDF id: PBKDF2-HMAC-SHA256 @ [`ITERATIONS`].
pub const KDF_PBKDF2: u8 = 0x01;
/// Entry key scheme: HKDF from the master secret.
pub const SCHEME_HKDF: u8 = 0x01;
/// v2 header: magic(4) + version(1) + kdf(1) + flags(2) + salt(16) + count(4).
pub const V2_HEADER_LEN: usize = 4 + 1 + 1 + 2 + SALT_LEN + 4; // 28
/// Trailing manifest MAC length (HMAC-SHA256).
pub const MAC_LEN: usize = 32;
/// Value padding bucket (spec §4.2): plaintext bodies are 4-byte true-length
/// prefix + value + zero pad, rounded up to a multiple of this.
pub const PAD_BLOCK: usize = 32;
/// Max storage-name length: project(256) + '/'(1) + key(256).
pub const MAX_NAME_LEN: usize = 513;
/// Largest legal padded body: 4-byte length prefix + MAX_VALUE_LEN, bucketed.
const MAX_PADDED: usize = (4 + MAX_VALUE_LEN).div_ceil(PAD_BLOCK) * PAD_BLOCK;

type HmacSha256 = hmac::Hmac<sha2::Sha256>;

/// A storage name is either `KEY` or `project/KEY` (spec §4.1) — at most one `/`.
pub fn is_valid_storage_name(name: &str) -> bool {
    match name.split_once('/') {
        Some((project, key)) => is_valid_project(project) && is_valid_key(key),
        None => is_valid_key(name),
    }
}

/// The vault-level KDF output. Derive ONCE per open (the expensive step), then
/// zeroize the passphrase — every other key HKDF-derives from this (spec §4.3).
/// Carries the salt it was derived under so entry/mac/registry keys need no
/// extra context.
pub struct MasterSecret {
    secret: Zeroizing<[u8; 32]>,
    salt: [u8; SALT_LEN],
}

impl MasterSecret {
    /// PBKDF2-HMAC-SHA256 @ 600k over the passphrase. The caller should drop
    /// (zeroize) the passphrase immediately after this returns.
    pub fn derive(passphrase: &str, salt: &[u8; SALT_LEN]) -> Self {
        let secret = Zeroizing::new(pbkdf2::pbkdf2_hmac_array::<sha2::Sha256, 32>(
            passphrase.as_bytes(),
            salt,
            ITERATIONS,
        ));
        Self { secret, salt: *salt }
    }

    /// Wrap an already-random 32-byte key as the master secret (the lease
    /// path, LEASE_DESIGN.md §4). A full-entropy key needs no stretching, so
    /// PBKDF2 is skipped; every HKDF derivation downstream (entry keys,
    /// manifest MAC) is identical to the passphrase path, and the container
    /// format is byte-for-byte the same QVLT v2.
    pub fn from_raw_key(key: &[u8; 32], salt: &[u8; SALT_LEN]) -> Self {
        Self { secret: Zeroizing::new(*key), salt: *salt }
    }

    pub fn salt(&self) -> &[u8; SALT_LEN] {
        &self.salt
    }

    fn hkdf(&self, info: &[u8]) -> Zeroizing<[u8; 32]> {
        let hk = hkdf::Hkdf::<sha2::Sha256>::new(Some(&self.salt), self.secret.as_ref());
        let mut okm = Zeroizing::new([0u8; 32]);
        hk.expand(info, okm.as_mut())
            .expect("32 bytes is a valid HKDF-SHA256 output length");
        okm
    }

    /// Per-entry key. Info length-prefixes the name so entry infos are
    /// prefix-free among themselves and against the fixed labels (spec §4.3).
    fn entry_key(&self, name: &str) -> Zeroizing<[u8; 32]> {
        let mut info = Vec::with_capacity(14 + name.len());
        info.extend_from_slice(b"qvlt2:entry:");
        info.extend_from_slice(&(name.len() as u16).to_be_bytes());
        info.extend_from_slice(name.as_bytes());
        self.hkdf(&info)
    }

    fn mac_key(&self) -> Zeroizing<[u8; 32]> {
        self.hkdf(b"qvlt2:manifest")
    }

    /// Key for the raw-key registry container (spec §6.2).
    pub fn registry_key(&self) -> Zeroizing<[u8; 32]> {
        self.hkdf(b"qvlt2:registry")
    }
}

/// True if the bytes look like a QVLT v2 file (magic + version only — full
/// validation happens in [`VaultReader::open`]).
pub fn is_v2(data: &[u8]) -> bool {
    data.len() >= V2_HEADER_LEN && data[0..4] == MAGIC && data[4] == V2_VERSION
}

/// True if the bytes look like a legacy v1 file.
pub fn is_v1(data: &[u8]) -> bool {
    data.len() >= HEADER_LEN && data[0..4] == MAGIC && data[4] == VERSION
}

/// Parse a v2 header far enough to return the vault salt — needed BEFORE key
/// derivation (chicken/egg: the master secret derives from this salt). Also
/// enforces the fail-closed prefix checks: magic, version, KDF id, zero flags.
pub fn v2_salt(data: &[u8]) -> Result<[u8; SALT_LEN], VaultError> {
    if data.len() < V2_HEADER_LEN + MAC_LEN {
        return Err(VaultError::TooSmall);
    }
    if data[0..4] != MAGIC {
        return Err(VaultError::BadMagic);
    }
    if data[4] != V2_VERSION {
        return Err(VaultError::UnsupportedVersion(data[4]));
    }
    if data[5] != KDF_PBKDF2 {
        return Err(VaultError::UnsupportedKdf(data[5]));
    }
    let flags = u16::from_be_bytes([data[6], data[7]]);
    if flags != 0 {
        return Err(VaultError::UnsupportedFlags(flags));
    }
    let mut salt = [0u8; SALT_LEN];
    salt.copy_from_slice(&data[8..8 + SALT_LEN]);
    Ok(salt)
}

/// One parsed (not decrypted) record: byte offsets into the file image.
struct RecordMeta {
    scheme: u8,
    name: String,
    /// Offset of the record's first byte (the scheme byte).
    rec_off: usize,
    /// Offset of the nonce (name end).
    nonce_off: usize,
    ct_len: usize,
}

impl RecordMeta {
    fn tag_off(&self) -> usize {
        self.nonce_off + NONCE_LEN
    }
    fn ct_off(&self) -> usize {
        self.tag_off() + TAG_LEN + 4
    }
    fn end(&self) -> usize {
        self.ct_off() + self.ct_len
    }
}

/// A validated v2 vault image supporting selective decryption and no-read
/// splicing (spec §5). Holds the raw bytes; values stay ciphertext until
/// [`Self::decrypt_one`] is called for a specific name.
pub struct VaultReader {
    data: Vec<u8>,
    salt: [u8; SALT_LEN],
    records: Vec<RecordMeta>,
}

impl VaultReader {
    /// Full structural validation + manifest MAC verification (spec §4,
    /// normative order: bounds before any length-driven allocation, exact
    /// tiling, sorted unique valid names, then MAC).
    pub fn open(data: Vec<u8>, master: &MasterSecret) -> Result<Self, VaultError> {
        let salt = v2_salt(&data)?;
        if salt != master.salt {
            // Wrong MasterSecret for this file (e.g. stale broker after rekey).
            return Err(VaultError::DecryptionFailed);
        }
        let count = u32::from_be_bytes([data[24], data[25], data[26], data[27]]) as usize;
        let body_end = data.len() - MAC_LEN;

        let mut records = Vec::new();
        let mut pos = V2_HEADER_LEN;
        for _ in 0..count {
            // Every length is bounds-checked against the remaining region
            // BEFORE any slice/allocation driven by it (spec §4).
            if pos + 3 > body_end {
                return Err(VaultError::MalformedData);
            }
            let scheme = data[pos];
            if scheme != SCHEME_HKDF {
                // v2 readers know only scheme 0x01; unknown schemes have
                // unknown layouts, so the whole parse fails closed (§4.6).
                return Err(VaultError::UnknownScheme(scheme));
            }
            let name_len = u16::from_be_bytes([data[pos + 1], data[pos + 2]]) as usize;
            if name_len == 0 || name_len > MAX_NAME_LEN || pos + 3 + name_len + NONCE_LEN + TAG_LEN + 4 > body_end {
                return Err(VaultError::MalformedData);
            }
            let name = std::str::from_utf8(&data[pos + 3..pos + 3 + name_len])
                .map_err(|_| VaultError::MalformedData)?
                .to_string();
            if !is_valid_storage_name(&name) {
                return Err(VaultError::MalformedData);
            }
            if let Some(prev) = records.last() {
                let prev: &RecordMeta = prev;
                if prev.name.as_bytes() >= name.as_bytes() {
                    // Strict byte-lexicographic order ⇒ sorted AND unique.
                    return Err(VaultError::MalformedData);
                }
            }
            let nonce_off = pos + 3 + name_len;
            let ct_len_off = nonce_off + NONCE_LEN + TAG_LEN;
            let ct_len = u32::from_be_bytes([
                data[ct_len_off],
                data[ct_len_off + 1],
                data[ct_len_off + 2],
                data[ct_len_off + 3],
            ]) as usize;
            if ct_len == 0
                || ct_len % PAD_BLOCK != 0
                || ct_len > MAX_PADDED
                || ct_len_off + 4 + ct_len > body_end
            {
                return Err(VaultError::MalformedData);
            }
            records.push(RecordMeta { scheme, name, rec_off: pos, nonce_off, ct_len });
            pos = ct_len_off + 4 + ct_len;
        }
        if pos != body_end {
            // Records must exactly tile the region between header and MAC.
            return Err(VaultError::MalformedData);
        }

        let mac_key = master.mac_key();
        let mut mac = new_hmac(mac_key.as_ref());
        mac.update(&data[..body_end]);
        // (spec §4.5: MAC input is file || external_context; context is empty in v2)
        mac.verify_slice(&data[body_end..])
            .map_err(|_| VaultError::DecryptionFailed)?;

        Ok(Self { data, salt, records })
    }

    /// Entry names, sorted. No decryption.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.records.iter().map(|r| r.name.as_str())
    }

    pub fn len(&self) -> usize {
        self.records.len()
    }

    pub fn is_empty(&self) -> bool {
        self.records.is_empty()
    }

    pub fn contains(&self, name: &str) -> bool {
        self.find(name).is_some()
    }

    fn find(&self, name: &str) -> Option<&RecordMeta> {
        self.records
            .binary_search_by(|r| r.name.as_str().cmp(name))
            .ok()
            .map(|i| &self.records[i])
    }

    /// Decrypt exactly one record (G1). Every other entry stays ciphertext.
    /// Returns the true-length value bytes.
    pub fn decrypt_one(
        &self,
        master: &MasterSecret,
        name: &str,
    ) -> Result<Zeroizing<Vec<u8>>, VaultError> {
        let rec = self.find(name).ok_or(VaultError::NotFound)?;
        let key = master.entry_key(name);
        let cipher = Aes256Gcm::new(key.as_ref().try_into().expect("derived keys are 32 bytes"));
        let nonce: &Nonce<_> = (&self.data[rec.nonce_off..rec.nonce_off + NONCE_LEN])
            .try_into()
            .expect("nonce length is structural");
        let tag: &Tag = (&self.data[rec.tag_off()..rec.tag_off() + TAG_LEN])
            .try_into()
            .expect("tag length is structural");
        let aad = record_aad(rec.scheme, name);

        let mut body =
            Zeroizing::new(self.data[rec.ct_off()..rec.ct_off() + rec.ct_len].to_vec());
        cipher
            .decrypt_inout_detached(nonce, &aad, (body.as_mut_slice()).into(), tag)
            .map_err(|_| VaultError::DecryptionFailed)?;

        let true_len =
            u32::from_be_bytes([body[0], body[1], body[2], body[3]]) as usize;
        if true_len > MAX_VALUE_LEN || 4 + true_len > body.len() {
            return Err(VaultError::MalformedData);
        }
        Ok(Zeroizing::new(body[4..4 + true_len].to_vec()))
    }

    /// Decrypt every entry — for the inherently whole-vault operations
    /// (`list`, `env`, `export`, migration). Discouraged elsewhere.
    pub fn decrypt_all(&self, master: &MasterSecret) -> Result<Vault, VaultError> {
        let mut entries = BTreeMap::new();
        for r in &self.records {
            let v = self.decrypt_one(master, &r.name)?;
            let s = String::from_utf8_lossy(&v).into_owned();
            entries.insert(r.name.clone(), s);
        }
        Ok(Vault { entries })
    }

    /// Rebuild the file with `upserts` applied and `deletes` removed — WITHOUT
    /// decrypting any untouched entry (spec §5.2): their record bytes are
    /// re-emitted verbatim; only the manifest MAC is recomputed.
    pub fn splice(
        &self,
        master: &MasterSecret,
        upserts: &[(String, Zeroizing<Vec<u8>>)],
        deletes: &[String],
    ) -> Result<Vec<u8>, VaultError> {
        enum Src<'a> {
            Keep(&'a RecordMeta),
            New(&'a str, &'a [u8]),
        }
        let mut merged: BTreeMap<&str, Src> = self
            .records
            .iter()
            .map(|r| (r.name.as_str(), Src::Keep(r)))
            .collect();
        for name in deletes {
            merged.remove(name.as_str());
        }
        for (name, value) in upserts {
            if !is_valid_storage_name(name) || value.len() > MAX_VALUE_LEN || value.is_empty() {
                return Err(VaultError::MalformedData);
            }
            merged.insert(&name[..], Src::New(name, value));
        }

        let mut out = Vec::new();
        write_v2_header(&mut out, &self.salt, merged.len() as u32)?;
        for (name, src) in &merged {
            match src {
                Src::Keep(rec) => out.extend_from_slice(&self.data[rec.rec_off..rec.end()]),
                Src::New(name, value) => write_record(&mut out, master, name, value)?,
            }
            let _ = name;
        }
        append_mac(&mut out, master);
        Ok(out)
    }
}

fn record_aad(scheme: u8, name: &str) -> Vec<u8> {
    let mut aad = Vec::with_capacity(2 + name.len());
    aad.push(V2_VERSION);
    aad.push(scheme);
    aad.extend_from_slice(name.as_bytes());
    aad
}

fn write_v2_header(out: &mut Vec<u8>, salt: &[u8; SALT_LEN], count: u32) -> Result<(), VaultError> {
    out.write_all(&MAGIC)?;
    out.write_all(&[V2_VERSION, KDF_PBKDF2, 0, 0])?;
    out.write_all(salt)?;
    out.write_all(&count.to_be_bytes())?;
    Ok(())
}

fn write_record(
    out: &mut Vec<u8>,
    master: &MasterSecret,
    name: &str,
    value: &[u8],
) -> Result<(), VaultError> {
    // Padded body: u32 true length + value + zero pad to the bucket (§4.2).
    let padded = (4 + value.len()).div_ceil(PAD_BLOCK) * PAD_BLOCK;
    let mut body = Zeroizing::new(vec![0u8; padded]);
    body[..4].copy_from_slice(&(value.len() as u32).to_be_bytes());
    body[4..4 + value.len()].copy_from_slice(value);

    let key = master.entry_key(name);
    let cipher = Aes256Gcm::new(key.as_ref().try_into().expect("derived keys are 32 bytes"));
    let nonce = Nonce::generate();
    let aad = record_aad(SCHEME_HKDF, name);
    let tag = cipher
        .encrypt_inout_detached(&nonce, &aad, (body.as_mut_slice()).into())
        .map_err(|_| VaultError::EncryptionFailed)?;

    out.push(SCHEME_HKDF);
    out.write_all(&(name.len() as u16).to_be_bytes())?;
    out.write_all(name.as_bytes())?;
    out.write_all(nonce.as_slice())?;
    out.write_all(tag.as_slice())?;
    out.write_all(&(padded as u32).to_be_bytes())?;
    out.write_all(&body)?;
    Ok(())
}

fn append_mac(out: &mut Vec<u8>, master: &MasterSecret) {
    let mac_key = master.mac_key();
    let mut mac = new_hmac(mac_key.as_ref());
    mac.update(out);
    out.extend_from_slice(&mac.finalize().into_bytes());
}

/// Build a fresh v2 file from scratch (empty vault creation, migration,
/// rekey). `entries` need not be sorted; names are validated.
pub fn v2_create(
    master: &MasterSecret,
    entries: &[(String, Zeroizing<Vec<u8>>)],
) -> Result<Vec<u8>, VaultError> {
    let mut sorted: BTreeMap<&str, &[u8]> = BTreeMap::new();
    for (name, value) in entries {
        if !is_valid_storage_name(name) || value.len() > MAX_VALUE_LEN || value.is_empty() {
            return Err(VaultError::MalformedData);
        }
        sorted.insert(&name[..], value);
    }
    let mut out = Vec::new();
    write_v2_header(&mut out, &master.salt, sorted.len() as u32)?;
    for (name, value) in &sorted {
        write_record(&mut out, master, name, value)?;
    }
    append_mac(&mut out, master);
    Ok(out)
}

// ── Raw-key blob container (registry v2, spec §6.2) ──
//
// The registry moves off direct-passphrase PBKDF2 onto a key HKDF-derived from
// the master secret — the expensive KDF already happened at the vault level,
// and it lets the session broker zeroize the passphrase at startup.

const RAW_MAGIC: [u8; 4] = *b"QRG2";
const RAW_AAD: &[u8] = b"qvlt2:registry";

pub fn encrypt_raw_blob(plaintext: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, VaultError> {
    let cipher = Aes256Gcm::new(key.try_into().expect("derived keys are 32 bytes"));
    let nonce = Nonce::generate();
    let mut buf = plaintext.to_vec();
    let tag = cipher
        .encrypt_inout_detached(&nonce, RAW_AAD, buf.as_mut_slice().into())
        .map_err(|_| VaultError::EncryptionFailed)?;
    let mut out = Vec::with_capacity(4 + NONCE_LEN + TAG_LEN + buf.len());
    out.write_all(&RAW_MAGIC)?;
    out.write_all(nonce.as_slice())?;
    out.write_all(tag.as_slice())?;
    out.write_all(&buf)?;
    buf.zeroize();
    Ok(out)
}

pub fn decrypt_raw_blob(data: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, VaultError> {
    if data.len() < 4 + NONCE_LEN + TAG_LEN {
        return Err(VaultError::TooSmall);
    }
    if data[0..4] != RAW_MAGIC {
        return Err(VaultError::BadMagic);
    }
    let nonce: &Nonce<_> = (&data[4..4 + NONCE_LEN]).try_into().expect("nonce length is structural");
    let tag: &Tag = (&data[4 + NONCE_LEN..4 + NONCE_LEN + TAG_LEN]).try_into().expect("tag length is structural");
    let cipher = Aes256Gcm::new(key.try_into().expect("derived keys are 32 bytes"));
    let mut buf = data[4 + NONCE_LEN + TAG_LEN..].to_vec();
    cipher
        .decrypt_inout_detached(nonce, RAW_AAD, buf.as_mut_slice().into(), tag)
        .map_err(|_| VaultError::DecryptionFailed)?;
    Ok(buf)
}

// ── Tests ──

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

    #[test]
    fn round_trip() {
        let mut vault = Vault::new();
        vault.set("API_KEY", "sk-secret-123");
        vault.set("DB_URL", "postgres://localhost/mydb");

        let encrypted = vault.encrypt("test-pass").unwrap();
        let decrypted = Vault::decrypt(&encrypted, "test-pass").unwrap();

        assert_eq!(decrypted.get("API_KEY"), Some("sk-secret-123"));
        assert_eq!(decrypted.get("DB_URL"), Some("postgres://localhost/mydb"));
        assert_eq!(decrypted.len(), 2);
    }

    #[test]
    fn wrong_passphrase() {
        let vault = Vault::new();
        let encrypted = vault.encrypt("correct").unwrap();
        assert!(matches!(
            Vault::decrypt(&encrypted, "wrong"),
            Err(VaultError::DecryptionFailed)
        ));
    }

    #[test]
    fn tamper_detection() {
        let mut vault = Vault::new();
        vault.set("KEY", "value");
        let mut encrypted = vault.encrypt("pass").unwrap();
        // Flip a byte in the ciphertext
        if let Some(last) = encrypted.last_mut() {
            *last ^= 0xFF;
        }
        assert!(Vault::decrypt(&encrypted, "pass").is_err());
    }

    #[test]
    fn fresh_nonce_per_encrypt() {
        let vault = Vault::new();
        let a = vault.encrypt("pass").unwrap();
        let b = vault.encrypt("pass").unwrap();
        // Same data, different ciphertext (different salt + nonce)
        assert_ne!(a, b);
    }

    #[test]
    fn shell_escaping() {
        let mut vault = Vault::new();
        vault.set("KEY", "it's a \"test\"");
        let exports = vault.to_shell_exports();
        assert!(exports.contains("'it'\\''s a \"test\"'"));
    }

    #[test]
    fn valid_keys() {
        assert!(is_valid_key("API_KEY"));
        assert!(is_valid_key("key123"));
        assert!(is_valid_key("prod-db-password"));   // kebab-case (GSM-valid)
        assert!(is_valid_key("metatron-enterprise-lock"));
        assert!(!is_valid_key(""));
        assert!(!is_valid_key("has space"));
        assert!(!is_valid_key("has.dot"));           // dots are NOT GSM-valid
        assert!(!is_valid_key("has/slash"));
    }

    // ── QVLT v2 ──

    fn zv(s: &str) -> Zeroizing<Vec<u8>> {
        Zeroizing::new(s.as_bytes().to_vec())
    }

    fn test_master() -> MasterSecret {
        // Fixed salt so tests are deterministic where it matters.
        MasterSecret::derive("test-pass", &[7u8; SALT_LEN])
    }

    fn sample_file(master: &MasterSecret) -> Vec<u8> {
        v2_create(
            master,
            &[
                ("API_KEY".into(), zv("sk-secret-123")),
                ("DB_URL".into(), zv("postgres://localhost/mydb")),
                ("proj/TOKEN".into(), zv("t-42")),
            ],
        )
        .unwrap()
    }

    #[test]
    fn v2_round_trip_one() {
        let m = test_master();
        let file = sample_file(&m);
        let r = VaultReader::open(file, &m).unwrap();
        assert_eq!(r.len(), 3);
        assert_eq!(&*r.decrypt_one(&m, "API_KEY").unwrap(), b"sk-secret-123");
        assert_eq!(&*r.decrypt_one(&m, "proj/TOKEN").unwrap(), b"t-42");
        assert!(matches!(r.decrypt_one(&m, "NOPE"), Err(VaultError::NotFound)));
    }

    #[test]
    fn v2_wrong_passphrase() {
        let m = test_master();
        let file = sample_file(&m);
        let wrong = MasterSecret::derive("wrong", &[7u8; SALT_LEN]);
        // MAC key differs → open fails before any entry decryption.
        assert!(matches!(
            VaultReader::open(file, &wrong),
            Err(VaultError::DecryptionFailed)
        ));
    }

    #[test]
    fn v2_salt_mismatch_rejected() {
        let m = test_master();
        let file = sample_file(&m);
        // A master derived under a different salt (stale broker after rekey).
        let stale = MasterSecret::derive("test-pass", &[9u8; SALT_LEN]);
        assert!(matches!(
            VaultReader::open(file, &stale),
            Err(VaultError::DecryptionFailed)
        ));
    }

    #[test]
    fn v2_ciphertext_tamper_detected() {
        let m = test_master();
        let mut file = sample_file(&m);
        let n = file.len();
        file[n - MAC_LEN - 1] ^= 0xFF; // last ciphertext byte
        assert!(VaultReader::open(file, &m).is_err());
    }

    #[test]
    fn v2_record_deletion_detected() {
        let m = test_master();
        let file = sample_file(&m);
        // Forge: drop the middle record by rebuilding without re-MACing.
        let r = VaultReader::open(file.clone(), &m).unwrap();
        let victim = r.records.iter().find(|r| r.name == "DB_URL").unwrap();
        let mut forged = Vec::new();
        forged.extend_from_slice(&file[..victim.rec_off]);
        forged.extend_from_slice(&file[victim.end()..]);
        forged[24..28].copy_from_slice(&2u32.to_be_bytes());
        assert!(VaultReader::open(forged, &m).is_err());
    }

    #[test]
    fn v2_transplant_rejected_by_aad() {
        // Even with a VALID manifest MAC, a ciphertext moved under another name
        // must fail: the AAD binds the name into the AEAD itself. Swap the
        // crypto material (nonce+tag+ctlen+ct) of two same-bucket entries,
        // then re-MAC with the real key — simulating a buggy code path that
        // re-MACs without noticing the transplant.
        let m = test_master();
        let f2 = v2_create(&m, &[("AAA".into(), zv("x")), ("BBB".into(), zv("y"))]).unwrap();
        let r2 = VaultReader::open(f2.clone(), &m).unwrap();
        let ra = &r2.records[0];
        let rb = &r2.records[1];
        let mut forged = f2.clone();
        forged[ra.nonce_off..ra.end()].copy_from_slice(&f2[rb.nonce_off..rb.end()]);
        forged[rb.nonce_off..rb.end()].copy_from_slice(&f2[ra.nonce_off..ra.end()]);
        // Re-MAC the forged file (attacker without keys can't — but AAD must
        // hold even against a buggy path that re-MACs, so simulate with keys).
        let body_end = forged.len() - MAC_LEN;
        let mk = m.mac_key();
        let mut mac = new_hmac(mk.as_ref());
        mac.update(&forged[..body_end]);
        let tag = mac.finalize().into_bytes();
        forged[body_end..].copy_from_slice(&tag);
        let rf = VaultReader::open(forged, &m).unwrap();
        assert!(rf.decrypt_one(&m, "AAA").is_err());
        assert!(rf.decrypt_one(&m, "BBB").is_err());
    }

    #[test]
    fn v2_reorder_rejected() {
        // Unsorted records are a structural error before MAC verification.
        let m = test_master();
        let f = v2_create(&m, &[("AAA".into(), zv("x")), ("BBB".into(), zv("y"))]).unwrap();
        let r = VaultReader::open(f.clone(), &m).unwrap();
        let (ra, rb) = (&r.records[0], &r.records[1]);
        let mut forged = f[..V2_HEADER_LEN].to_vec();
        forged.extend_from_slice(&f[rb.rec_off..rb.end()]);
        forged.extend_from_slice(&f[ra.rec_off..ra.end()]);
        let body_end = forged.len();
        let mk = m.mac_key();
        let mut mac = new_hmac(mk.as_ref());
        mac.update(&forged);
        forged.extend_from_slice(&mac.finalize().into_bytes());
        let _ = body_end;
        assert!(matches!(
            VaultReader::open(forged, &m),
            Err(VaultError::MalformedData)
        ));
    }

    #[test]
    fn v2_truncation_and_bounds() {
        let m = test_master();
        let file = sample_file(&m);
        // Truncations at every interesting boundary fail, never panic.
        for cut in [0, 3, V2_HEADER_LEN - 1, V2_HEADER_LEN, V2_HEADER_LEN + 5, file.len() - 1] {
            assert!(VaultReader::open(file[..cut].to_vec(), &m).is_err());
        }
        // Absurd declared ct length must fail bounds, not allocate.
        let r = VaultReader::open(file.clone(), &m).unwrap();
        let rec = &r.records[0];
        let mut forged = file.clone();
        let off = rec.tag_off() + TAG_LEN;
        forged[off..off + 4].copy_from_slice(&u32::MAX.to_be_bytes());
        assert!(VaultReader::open(forged, &m).is_err());
    }

    #[test]
    fn v2_unknown_scheme_and_flags_fail_closed() {
        let m = test_master();
        let file = sample_file(&m);
        let mut s = file.clone();
        s[V2_HEADER_LEN] = 0x02; // first record's scheme byte
        assert!(matches!(
            VaultReader::open(s, &m),
            Err(VaultError::UnknownScheme(0x02))
        ));
        let mut fl = file.clone();
        fl[6] = 0x80; // flag bit
        assert!(matches!(
            VaultReader::open(fl, &m),
            Err(VaultError::UnsupportedFlags(_))
        ));
        let mut kdf = file;
        kdf[5] = 0x02;
        assert!(matches!(
            VaultReader::open(kdf, &m),
            Err(VaultError::UnsupportedKdf(0x02))
        ));
    }

    #[test]
    fn v2_padding_buckets_hide_length() {
        let m = test_master();
        // 1-byte and 27-byte values land in the same 32-byte bucket (4-byte
        // length prefix + value ≤ 32) → identical ct length on the wire.
        let f1 = v2_create(&m, &[("K".into(), zv("a"))]).unwrap();
        let f2 = v2_create(&m, &[("K".into(), zv("abcdefghijklmnopqrstuvwxyza"))]).unwrap();
        assert_eq!(f1.len(), f2.len());
        // 29 bytes crosses into the next bucket.
        let f3 = v2_create(&m, &[("K".into(), zv("abcdefghijklmnopqrstuvwxyzabc"))]).unwrap();
        assert_eq!(f3.len(), f1.len() + PAD_BLOCK);
        // Round-trips exactly (true length recovered, padding stripped).
        let r = VaultReader::open(f3, &m).unwrap();
        assert_eq!(&*r.decrypt_one(&m, "K").unwrap(), b"abcdefghijklmnopqrstuvwxyzabc");
    }

    #[test]
    fn v2_splice_upsert_delete_without_reading() {
        let m = test_master();
        let file = sample_file(&m);
        let r = VaultReader::open(file, &m).unwrap();
        let out = r
            .splice(
                &m,
                &[("NEW_KEY".into(), zv("fresh")), ("API_KEY".into(), zv("rotated"))],
                &["DB_URL".to_string()],
            )
            .unwrap();
        let r2 = VaultReader::open(out, &m).unwrap();
        assert_eq!(
            r2.names().collect::<Vec<_>>(),
            vec!["API_KEY", "NEW_KEY", "proj/TOKEN"]
        );
        assert_eq!(&*r2.decrypt_one(&m, "API_KEY").unwrap(), b"rotated");
        assert_eq!(&*r2.decrypt_one(&m, "NEW_KEY").unwrap(), b"fresh");
        // Untouched record survived byte-verbatim re-emission.
        assert_eq!(&*r2.decrypt_one(&m, "proj/TOKEN").unwrap(), b"t-42");
    }

    #[test]
    fn v2_duplicate_name_rejected() {
        let m = test_master();
        let f = v2_create(&m, &[("AAA".into(), zv("x")), ("AAB".into(), zv("x"))]).unwrap();
        let r = VaultReader::open(f.clone(), &m).unwrap();
        let ra = &r.records[0];
        // Duplicate AAA by overwriting AAB's name bytes in place (same length).
        let mut forged = f.clone();
        let rb = &r.records[1];
        forged[rb.rec_off + 3..rb.rec_off + 6].copy_from_slice(b"AAA");
        let _ = ra;
        assert!(matches!(
            VaultReader::open(forged, &m),
            Err(VaultError::MalformedData)
        ));
    }

    #[test]
    fn v2_storage_name_grammar() {
        assert!(is_valid_storage_name("API_KEY"));
        assert!(is_valid_storage_name("proj/API_KEY"));
        assert!(is_valid_storage_name("my.proj/prod-db-password"));
        assert!(!is_valid_storage_name("a/b/c"));
        assert!(!is_valid_storage_name("/KEY"));
        assert!(!is_valid_storage_name("proj/"));
        assert!(!is_valid_storage_name(""));
        assert!(!is_valid_storage_name("has.dot")); // dots invalid in bare keys
    }

    // ── Cryptographic known-answer tests (KATs) ──
    //
    // Round-trip tests have a blind spot: if a derivation detail (HKDF info
    // string, AAD layout, padding, MAC input) drifts, encrypt AND decrypt
    // drift together and every round-trip stays green — while every REAL
    // vault on disk becomes unreadable. These tests pin the exact bytes.

    fn hex(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{b:02x}")).collect()
    }

    /// Full-composition KAT: a vault file committed to the repo (generated
    /// 2026-07-24 via the CLI) must decrypt to these exact contents FOREVER.
    /// If this test fails, the change breaks every existing vault — do not
    /// "fix" the expectations; fix the code (or write a migration).
    #[test]
    fn golden_file_kat() {
        let data = include_bytes!("../tests/golden/golden_v2.qvlt").to_vec();
        let salt = v2_salt(&data).unwrap();
        let m = MasterSecret::derive("golden-pass-do-not-change", &salt);
        let r = VaultReader::open(data, &m).unwrap();
        assert_eq!(
            r.names().collect::<Vec<_>>(),
            vec!["BIGKEY", "GREETING", "MULTILINE", "app1/API_KEY", "app2/API_KEY"]
        );
        assert_eq!(&*r.decrypt_one(&m, "GREETING").unwrap(), b"hello-world");
        assert_eq!(&*r.decrypt_one(&m, "MULTILINE").unwrap(), b"line1\nline2");
        assert_eq!(&*r.decrypt_one(&m, "app1/API_KEY").unwrap(), b"value-app1");
        assert_eq!(&*r.decrypt_one(&m, "app2/API_KEY").unwrap(), b"value-app2");
        assert_eq!(
            &*r.decrypt_one(&m, "BIGKEY").unwrap(),
            b"0123456789012345678901234567890123456789012345678901234567890123"
        );
    }

    /// Derivation-chain KATs, cross-checked against an INDEPENDENT
    /// implementation (Python hashlib/hmac, computed 2026-07-24). Pins the
    /// PBKDF2 parameters and every HKDF info string: any accidental change
    /// to "qvlt2:entry:"/"qvlt2:manifest"/"qvlt2:registry", the length
    /// prefix, or the salt wiring fails here with a precise finger.
    #[test]
    fn derivation_kats_cross_impl() {
        let salt: [u8; SALT_LEN] = core::array::from_fn(|i| i as u8);
        let m = MasterSecret::derive("golden-pass", &salt);
        assert_eq!(
            hex(m.secret.as_ref()),
            "15bd048606d475f651612dd37b8dcd2e8e11534c8b689d0a6a44d1b8819eff7d"
        );
        assert_eq!(
            hex(m.entry_key("API_KEY").as_ref()),
            "8c92f6013a1f708304488ce1d7237b1389d37c3194d3c05fa9dddc1350d05a5c"
        );
        assert_eq!(
            hex(m.mac_key().as_ref()),
            "ae55458d0fb8334b5642ff9db564921ecfd59454e31b8fe33d909e4d71ff0fb9"
        );
        assert_eq!(
            hex(m.registry_key().as_ref()),
            "eb12b87f7bb7e45749bc5f998d1be4f34a04ef238ca881ecb4eccdd71d6acf4d"
        );
    }

    /// RFC 5869 Appendix A.1 (HKDF-SHA256, basic case) — anchors our use of
    /// the `hkdf` crate to the standard's own test vector.
    #[test]
    fn hkdf_rfc5869_a1() {
        let ikm = [0x0bu8; 22];
        let salt: Vec<u8> = (0x00..=0x0c).collect();
        let info: Vec<u8> = (0xf0..=0xf9).collect();
        let hk = hkdf::Hkdf::<sha2::Sha256>::new(Some(&salt), &ikm);
        let mut okm = [0u8; 42];
        hk.expand(&info, &mut okm).unwrap();
        assert_eq!(
            hex(&okm),
            "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
        );
    }

    /// RFC 4231 test case 1 (HMAC-SHA256) — anchors the manifest-MAC
    /// primitive to the standard's own test vector.
    #[test]
    fn hmac_rfc4231_case1() {
        let mut mac = new_hmac(&[0x0bu8; 20]);
        mac.update(b"Hi There");
        assert_eq!(
            hex(&mac.finalize().into_bytes()),
            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
        );
    }

    /// Deterministic mutation smoke-fuzz: thousands of corrupted / truncated /
    /// garbage variants of a valid file must never panic the parser — every
    /// outcome is Ok or a clean Err. (The real coverage-guided harness lives
    /// in fuzz/; this keeps a panic-safety floor in plain `cargo test`.)
    #[test]
    fn mutation_smoke_no_panic() {
        let m = test_master();
        let base = sample_file(&m);
        // xorshift64* — deterministic, no external RNG dep.
        let mut s: u64 = 0x9E3779B97F4A7C15;
        let mut rng = move || {
            s ^= s >> 12;
            s ^= s << 25;
            s ^= s >> 27;
            s = s.wrapping_mul(0x2545F4914F6CDD1D);
            s
        };
        for i in 0..5000u64 {
            let mut d = base.clone();
            match i % 4 {
                0 => {
                    // flip 1–3 random bytes
                    for _ in 0..=(rng() % 3) {
                        let idx = (rng() as usize) % d.len();
                        d[idx] ^= (rng() as u8) | 1;
                    }
                }
                1 => {
                    // truncate at a random point
                    d.truncate((rng() as usize) % (d.len() + 1));
                }
                2 => {
                    // splice random garbage into a random window
                    let start = (rng() as usize) % d.len();
                    let end = (start + 1 + (rng() as usize) % 64).min(d.len());
                    for b in &mut d[start..end] {
                        *b = rng() as u8;
                    }
                }
                _ => {
                    // pure garbage of random length
                    let n = (rng() as usize) % 600;
                    d = (0..n).map(|_| rng() as u8).collect();
                }
            }
            if let Ok(r) = VaultReader::open(d, &m) {
                for name in r.names().map(String::from).collect::<Vec<_>>() {
                    let _ = r.decrypt_one(&m, &name);
                }
            }
        }
    }

    #[test]
    fn raw_key_master_round_trip() {
        // The lease path: a v2 container under a raw random key instead of a
        // PBKDF2-derived one. Same format, same selective decryption.
        let key = [0x5au8; 32];
        let salt = [3u8; SALT_LEN];
        let m = MasterSecret::from_raw_key(&key, &salt);
        let file = v2_create(
            &m,
            &[("DATABASE_URL".into(), zv("postgres://x")), ("TOKEN".into(), zv("t-1"))],
        )
        .unwrap();
        let r = VaultReader::open(file.clone(), &m).unwrap();
        assert_eq!(&*r.decrypt_one(&m, "DATABASE_URL").unwrap(), b"postgres://x");
        assert_eq!(&*r.decrypt_one(&m, "TOKEN").unwrap(), b"t-1");

        // A different raw key fails the manifest MAC before any decryption.
        let other = MasterSecret::from_raw_key(&[0xa5u8; 32], &salt);
        assert!(matches!(
            VaultReader::open(file, &other),
            Err(VaultError::DecryptionFailed)
        ));
    }

    #[test]
    fn raw_blob_round_trip_and_tamper() {
        let key = [42u8; 32];
        let enc = encrypt_raw_blob(b"registry-json", &key).unwrap();
        assert_eq!(decrypt_raw_blob(&enc, &key).unwrap(), b"registry-json");
        assert!(decrypt_raw_blob(&enc, &[43u8; 32]).is_err());
        let mut t = enc.clone();
        let n = t.len();
        t[n - 1] ^= 1;
        assert!(decrypt_raw_blob(&t, &key).is_err());
    }

    #[test]
    fn v1_still_readable() {
        // Migration path: v1 files remain decryptable.
        let mut vault = Vault::new();
        vault.set("OLD", "value");
        let v1 = vault.encrypt("pass").unwrap();
        assert!(is_v1(&v1));
        assert!(!is_v2(&v1));
        let back = Vault::decrypt(&v1, "pass").unwrap();
        assert_eq!(back.get("OLD"), Some("value"));
    }

    #[test]
    fn parse_env() {
        let input = r#"
export API_KEY="sk-123"
DB_URL=postgres://localhost
# comment
export EMPTY=

BARE=value
"#;
        let pairs = parse_env_lines(input);
        assert_eq!(pairs.len(), 3);
        // parse_env_lines returns in file order, not sorted
        assert_eq!(pairs[0], ("API_KEY".into(), "sk-123".into()));
        assert_eq!(pairs[1], ("DB_URL".into(), "postgres://localhost".into()));
        assert_eq!(pairs[2], ("BARE".into(), "value".into()));
    }
}