eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
//! Store-local authentication root (ADR 0086 TC-D14, plan P0.6, bead
//! `bd-tc-epic-qzk7o.2.4` slice 1).
//!
//! One hardened per-store authentication root anchors every store-local MAC in
//! the confederation design: native-import authentication (slice 3), and the
//! lane / body exposure-approval envelopes (T1.4 / T5.9). The root is a single
//! 32-byte OS-CSPRNG secret from which purpose-specific BLAKE3 subkeys are
//! derived under fixed, non-overlapping domain strings. Cross-domain reuse is
//! impossible by construction: each [`MacDomain`] derives its own subkey via
//! `blake3::derive_key`, and MACs are `blake3::keyed_hash` under that subkey.
//!
//! Security contract (TC-D14): the raw root and any derived subkey never enter
//! the database, command output, logs, audit, support bundles, or the redacted
//! `ee backup` format. The only durable home for the root is the hardened key
//! file this module owns (`0700` directory / `0600` file, owner-only, no
//! symlinked components). The `Secret` newtype has a redacted `Debug` and best-effort
//! `Drop` zeroization, and no secret bytes are ever serialized except as the
//! raw-root hex inside that one key file. Explicit key recovery can also seal
//! that document in a passphrase-encrypted envelope; ordinary data backups
//! never carry plaintext keys or this recovery envelope.
//!
//! Availability failures (missing/corrupt/insecure key store, randomness
//! failure, or a primitive self-test regression) all fail closed with
//! [`StoreAuthError`], whose [`StoreAuthError::degraded_code`] is
//! [`MESH_STORE_AUTHENTICATION_UNAVAILABLE_CODE`]. Callers surface that as a
//! `high`-severity degraded entry and admit nothing on the strength of native
//! trust.
//!
//! This slice establishes the key lifecycle, hardened storage, known-answer
//! self-check, rotation window, and the fallible derivation API. Export header
//! MACs (slice 2) and import verification plus the `human_explicit` bypass
//! closure (slice 3) consume this module without re-implementing any of it.

use std::fmt;
use std::num::NonZeroU32;
use std::ops::Deref;
use std::path::{Path, PathBuf};

use fs4::FileExt as Fs4FileExt;
use ring::{aead, pbkdf2};
use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, Zeroizing};

use super::hex_lower;

/// Length of the root secret and every derived subkey, in bytes.
const KEY_LEN: usize = 32;
/// Length of a MAC / tag output, in bytes.
const MAC_LEN: usize = 32;
/// Length of an opaque key identifier, in bytes.
const KEY_ID_LEN: usize = 16;
/// File name of the hardened key store inside the injected keys directory.
pub(crate) const KEY_FILE_NAME: &str = "store_auth_root.json";
/// Temp sibling used for atomic replace during rotation.
const KEY_FILE_TMP_NAME: &str = "store_auth_root.json.tmp";
/// Persistent advisory-lock sibling coordinating readers with key rotation.
const KEY_LOCK_FILE_NAME: &str = "store_auth_root.lock";
/// On-disk key-file schema tag.
const KEY_FILE_SCHEMA: &str = "ee.store_auth.keyfile.v1";
/// Maximum retired keys retained for the same-store verification window.
const MAX_RETIRED_KEYS: usize = 4;
/// Hard cap on the key-file size we will read (a valid file is well under 1 KiB).
const MAX_KEY_FILE_BYTES: u64 = 64 * 1024;
const RECOVERY_SCHEMA: &str = "ee.store_auth.recovery.v1";
const RECOVERY_KDF: &str = "pbkdf2-hmac-sha256";
// OWASP's PBKDF2-HMAC-SHA256 work factor; fixed in v1 to bound untrusted work.
const RECOVERY_ITERATIONS: u32 = 600_000;
pub(crate) const MAX_RECOVERY_BYTES: usize = 512 * 1024;
pub(crate) const MAX_RECOVERY_PASSPHRASE_BYTES: usize = 4096;

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct StoreAuthRecoveryEnvelope {
    schema: String,
    kdf: String,
    iterations: u32,
    salt: [u8; 32],
    nonce: [u8; aead::NONCE_LEN],
    ciphertext: Vec<u8>,
}

/// Validated plaintext, only for the core recovery path's hardened key-file
/// publisher. Never render or place this value in ordinary backup records.
pub(crate) struct RecoveredStoreAuth {
    pub(crate) key_file: Zeroizing<Vec<u8>>,
    pub(crate) key_ids: Vec<String>,
}

impl fmt::Debug for RecoveredStoreAuth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RecoveredStoreAuth")
            .field("key_ids", &self.key_ids)
            .field("key_file", &"<redacted>")
            .finish()
    }
}

fn recovery_error(message: &str) -> StoreAuthError {
    StoreAuthError::Malformed {
        message: message.to_owned(),
    }
}

pub(crate) fn validate_recovery_passphrase(passphrase: &str) -> Result<(), StoreAuthError> {
    if passphrase.len() > MAX_RECOVERY_PASSPHRASE_BYTES
        || !(12..=1024).contains(&passphrase.chars().count())
        || passphrase.contains(['\r', '\n', '\0'])
    {
        return Err(recovery_error(
            "recovery passphrase must contain 12 to 1024 characters on a single line",
        ));
    }
    Ok(())
}

fn recovery_cipher(passphrase: &str, salt: &[u8]) -> Result<aead::LessSafeKey, StoreAuthError> {
    let iterations = NonZeroU32::new(RECOVERY_ITERATIONS)
        .ok_or_else(|| recovery_error("invalid recovery KDF work factor"))?;
    let mut key = Zeroizing::new([0_u8; KEY_LEN]);
    pbkdf2::derive(
        pbkdf2::PBKDF2_HMAC_SHA256,
        iterations,
        salt,
        passphrase.as_bytes(),
        key.as_mut(),
    );
    aead::UnboundKey::new(&aead::CHACHA20_POLY1305, key.as_ref())
        .map(aead::LessSafeKey::new)
        .map_err(|_| recovery_error("could not initialize recovery encryption"))
}

/// Degraded code emitted whenever the store-local authentication root cannot be
/// established or verified. Fail-closed: nothing is admitted at native trust.
pub const MESH_STORE_AUTHENTICATION_UNAVAILABLE_CODE: &str =
    "mesh_store_authentication_unavailable";

/// Canonical on-disk location of a workspace's store-authentication key
/// directory. Exporters and importers must open the same root, so every
/// caller resolves the directory through this helper.
#[must_use]
pub fn workspace_keys_dir(workspace_path: &Path) -> PathBuf {
    workspace_path
        .join(crate::config::WORKSPACE_MARKER)
        .join("keys")
}

/// Internal derivation context for the key-file integrity self-check. This is
/// deliberately *not* a public [`MacDomain`]: it authenticates the key file's
/// own consistency, not any consumer payload.
const SELF_CHECK_CONTEXT: &str = "ee.store_auth.self_check.v1";
/// Fixed message MAC'd under the self-check subkey. Its keyed digest is stored
/// in the key file and re-verified on open to detect corruption/truncation.
const SELF_CHECK_MESSAGE: &[u8] = b"ee.store_auth.self_check.message.v1";

// Known-answer vectors captured from the BLAKE3 reference implementation
// (`b3sum`) over the fixed root `0x00..0x1f`. They pin both the primitive
// wiring (`derive_key` + `keyed_hash`) and the exact domain strings so an
// accidental edit to a context string or a swapped crypto backend fails the
// self-test before any key material is generated or trusted.
const KAT_MESSAGE: &[u8] = b"ee-store-auth-kat-message";
const KAT_SUBKEY_HEX: &str = "cb573690cdf5ecbcfbc91c2dc82459a8d8161e673e52abd8e2be14dba253037f";
const KAT_MAC_HEX: &str = "d95066c3c600bbb4fb8f307bcfb553a56862e442155d2f5e3d80497ead8bd0c0";
const KAT_SELF_CHECK_HEX: &str = "2dc8db78eb25d723bae6ec5280656f8fe9070a417e476c859d194ef6f22d6f3e";

/// Fail-closed error surface for the store-local authentication root. Every
/// variant maps to [`MESH_STORE_AUTHENTICATION_UNAVAILABLE_CODE`]: the store is
/// unavailable, so native trust is refused rather than degraded silently.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StoreAuthError {
    /// The OS CSPRNG failed to supply key material.
    Randomness { message: String },
    /// A filesystem operation on the key store failed.
    Io { path: String, message: String },
    /// The key file or its directory is accessible beyond the owner.
    InsecurePermissions { path: String, detail: String },
    /// A component of the key path is a symbolic link.
    SymlinkComponent { path: String },
    /// The key file could not be parsed or violates a structural invariant.
    Malformed { message: String },
    /// The key file schema tag did not match the supported version.
    SchemaMismatch { found: String, expected: String },
    /// The key file's stored integrity MAC did not match the current root.
    SelfCheckFailed,
    /// The BLAKE3 primitive self-test disagreed with the pinned reference
    /// vectors — the crypto backend is wrong or the domain strings drifted.
    PrimitiveKnownAnswerFailed { detail: String },
    /// `create` was asked to initialize a store that already exists.
    AlreadyInitialized { path: String },
    /// `open` was asked to load a store that has not been initialized.
    NotInitialized { path: String },
}

impl StoreAuthError {
    /// The single degraded code every store-auth failure surfaces.
    #[must_use]
    pub fn degraded_code(&self) -> &'static str {
        MESH_STORE_AUTHENTICATION_UNAVAILABLE_CODE
    }

    /// Human-readable, secret-free description for the degraded `message` field.
    #[must_use]
    pub fn message(&self) -> String {
        match self {
            Self::Randomness { message } => {
                format!("Store-authentication randomness failed: {message}")
            }
            Self::Io { path, message } => {
                format!("Store-authentication key store I/O failed at {path}: {message}")
            }
            Self::InsecurePermissions { path, detail } => {
                format!("Store-authentication key store at {path} is not owner-only: {detail}")
            }
            Self::SymlinkComponent { path } => {
                format!("Store-authentication key path {path} traverses a symbolic link")
            }
            Self::Malformed { message } => {
                format!("Store-authentication key store is malformed: {message}")
            }
            Self::SchemaMismatch { found, expected } => {
                format!(
                    "Store-authentication key store schema {found} is not the supported {expected}"
                )
            }
            Self::SelfCheckFailed => {
                "Store-authentication key store failed its integrity self-check".to_owned()
            }
            Self::PrimitiveKnownAnswerFailed { detail } => {
                format!("Store-authentication primitive self-test failed: {detail}")
            }
            Self::AlreadyInitialized { path } => {
                format!("Store-authentication key store already exists at {path}")
            }
            Self::NotInitialized { path } => {
                format!("Store-authentication key store is not initialized at {path}")
            }
        }
    }

    /// Actionable, secret-free repair hint for the degraded `repair` field.
    #[must_use]
    pub fn repair(&self) -> String {
        match self {
            Self::InsecurePermissions { .. } => {
                "Restrict the key directory to 0700 and the key file to 0600 (owner-only), \
                 then re-run."
                    .to_owned()
            }
            Self::SymlinkComponent { .. } => {
                "Replace the symlinked key path with a real owner-only directory and re-run."
                    .to_owned()
            }
            Self::SelfCheckFailed | Self::Malformed { .. } | Self::SchemaMismatch { .. } => {
                "The key store is unusable. Restore the protected key directory from a secure \
                 backup, or re-initialize the store (imported native-trust rows must be \
                 re-attested)."
                    .to_owned()
            }
            Self::NotInitialized { .. } => {
                "Initialize the store-authentication root before importing at native trust."
                    .to_owned()
            }
            _ => "Resolve the underlying key-store fault and re-run; nothing was admitted."
                .to_owned(),
        }
    }
}

impl fmt::Display for StoreAuthError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message())
    }
}

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

/// Opaque, non-secret key identifier. Random at creation, it names which key
/// authenticated an artifact without revealing anything about the root. Safe to
/// carry in import headers and to compare with `==`.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct KeyId([u8; KEY_ID_LEN]);

impl KeyId {
    /// Lowercase hex rendering (32 characters).
    #[must_use]
    pub fn to_hex(&self) -> String {
        hex_lower(&self.0)
    }

    /// Parse a 32-character lowercase-or-uppercase hex identifier.
    pub fn from_hex(value: &str) -> Result<Self, StoreAuthError> {
        Ok(Self(decode_hex_fixed::<KEY_ID_LEN>(value, "key id")?))
    }

    /// Raw identifier bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; KEY_ID_LEN] {
        &self.0
    }
}

impl fmt::Debug for KeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "KeyId({})", self.to_hex())
    }
}

impl fmt::Display for KeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_hex())
    }
}

/// A domain-separated authentication tag. This is a *public* authenticator (it
/// travels in import headers and approval envelopes), not secret key material,
/// so it is hex-serializable. Equality is constant-time to deny timing oracles
/// on verification.
#[derive(Clone, Copy)]
pub struct Mac([u8; MAC_LEN]);

impl Mac {
    /// Construct a MAC from its fixed-width wire representation.
    ///
    /// This does not authenticate the bytes. Callers must pass the result to
    /// [`StoreAuthRoot::verify`] before treating it as valid. The constructor
    /// exists for bounded binary envelopes (such as mesh approval tokens),
    /// where a hex round-trip would add an unnecessary second encoding.
    #[must_use]
    pub const fn from_bytes(bytes: [u8; MAC_LEN]) -> Self {
        Self(bytes)
    }

    /// Lowercase hex rendering (64 characters).
    #[must_use]
    pub fn to_hex(&self) -> String {
        hex_lower(&self.0)
    }

    /// Parse a 64-character hex tag.
    pub fn from_hex(value: &str) -> Result<Self, StoreAuthError> {
        Ok(Self(decode_hex_fixed::<MAC_LEN>(value, "mac")?))
    }

    /// Raw tag bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; MAC_LEN] {
        &self.0
    }
}

impl PartialEq for Mac {
    /// Constant-time comparison over the fixed-width tag.
    fn eq(&self, other: &Self) -> bool {
        constant_time_eq(&self.0, &other.0)
    }
}

impl Eq for Mac {}

impl fmt::Debug for Mac {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Mac({})", self.to_hex())
    }
}

/// Fixed subkey-derivation domains. Each derives a distinct BLAKE3 subkey from
/// the same root, so a tag minted for one purpose can never authenticate bytes
/// for another. `LaneApproval*` serves all T1.4 generic lane grants, including
/// the metadata `Lane::Body` permission. `BodyApproval*` is reserved exclusively
/// for the future T5.9 team-share-bodies consumer; no T1.4 code may select it.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MacDomain {
    /// `ee export` → `ee import jsonl` native-trust header MAC (slice 3).
    NativeImportRecordsRoot,
    /// `ee playbook import` header MAC — distinct domain and record tag.
    PlaybookImportRecordsRoot,
    /// T1.4 lane-approval canonical snapshot tag.
    LaneApprovalSnapshotTag,
    /// T1.4 lane-approval envelope MAC.
    LaneApprovalEnvelopeMac,
    /// T1.4 lane-approval durable audit identifier.
    LaneApprovalAuditId,
    /// T5.9 body-approval canonical snapshot tag.
    BodyApprovalSnapshotTag,
    /// T5.9 body-approval envelope MAC.
    BodyApprovalEnvelopeMac,
    /// T5.9 body-approval durable audit identifier.
    BodyApprovalAuditId,
}

impl MacDomain {
    /// The fixed, non-overlapping derivation context for this domain.
    #[must_use]
    pub const fn context(self) -> &'static str {
        match self {
            Self::NativeImportRecordsRoot => "ee.store_auth.native_import.records_root.v1",
            Self::PlaybookImportRecordsRoot => "ee.store_auth.playbook_import.records_root.v1",
            Self::LaneApprovalSnapshotTag => "ee.store_auth.lane_approval.snapshot_tag.v1",
            Self::LaneApprovalEnvelopeMac => "ee.store_auth.lane_approval.envelope_mac.v1",
            Self::LaneApprovalAuditId => "ee.store_auth.lane_approval.audit_id.v1",
            Self::BodyApprovalSnapshotTag => "ee.store_auth.body_approval.snapshot_tag.v1",
            Self::BodyApprovalEnvelopeMac => "ee.store_auth.body_approval.envelope_mac.v1",
            Self::BodyApprovalAuditId => "ee.store_auth.body_approval.audit_id.v1",
        }
    }
}

/// Which key in the verification window authenticated an artifact.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KeyClass {
    /// The store's current key.
    Current,
    /// A retired key still inside the bounded same-store window.
    Retired,
}

/// Outcome of verifying a candidate MAC against a specific key identifier.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KeyVerification {
    /// The candidate matched the named key.
    Match { key_class: KeyClass },
    /// The named key exists in the window but the candidate did not match.
    Mismatch,
    /// The named key is not the current key and not inside the retired window.
    KeyOutsideWindow,
}

/// A 32-byte secret with a redacted `Debug` and `zeroize`-backed `Drop`.
struct Secret([u8; KEY_LEN]);

impl Secret {
    fn as_bytes(&self) -> &[u8; KEY_LEN] {
        &self.0
    }
}

impl fmt::Debug for Secret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Secret(<redacted>)")
    }
}

impl Drop for Secret {
    fn drop(&mut self) {
        self.0.zeroize();
    }
}

/// One (key id, root) pair. Derivation and MAC construction happen here so the
/// raw root never escapes; derived subkeys live only for the duration of a MAC
/// and are zeroized on drop.
#[derive(Debug)]
struct KeyEntry {
    key_id: KeyId,
    root: Secret,
}

impl KeyEntry {
    fn derive(&self, context: &str) -> Secret {
        Secret(blake3::derive_key(context, self.root.as_bytes()))
    }

    fn mac(&self, domain: MacDomain, message: &[u8]) -> Mac {
        let subkey = self.derive(domain.context());
        let tag = blake3::keyed_hash(subkey.as_bytes(), message);
        Mac(*tag.as_bytes())
    }

    fn self_check(&self) -> Mac {
        let subkey = self.derive(SELF_CHECK_CONTEXT);
        let tag = blake3::keyed_hash(subkey.as_bytes(), SELF_CHECK_MESSAGE);
        Mac(*tag.as_bytes())
    }

    fn to_file_entry(&self) -> KeyFileEntry {
        KeyFileEntry {
            key_id: self.key_id.to_hex(),
            root: hex_lower(self.root.as_bytes()),
        }
    }
}

/// The loaded store-local authentication root: a current key plus a bounded
/// window of retired keys usable only for verifying same-store artifacts.
pub struct StoreAuthRoot {
    keys_dir: PathBuf,
    current: KeyEntry,
    retired: Vec<KeyEntry>,
}

/// A current store-auth root held under the key store's shared advisory lock.
///
/// Approval callers keep this guard alive across their database transaction,
/// so [`StoreAuthRoot::rotate`] cannot replace the current key after snapshot
/// verification but before the grant and audit commit.
pub struct StoreAuthReadGuard {
    root: StoreAuthRoot,
    lock_file: std::fs::File,
}

impl Deref for StoreAuthReadGuard {
    type Target = StoreAuthRoot;

    fn deref(&self) -> &Self::Target {
        &self.root
    }
}

impl fmt::Debug for StoreAuthReadGuard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("StoreAuthReadGuard")
            .field(&self.root)
            .finish()
    }
}

impl Drop for StoreAuthReadGuard {
    fn drop(&mut self) {
        let _ = Fs4FileExt::unlock(&self.lock_file);
    }
}

struct StoreAuthWriteGuard {
    lock_file: std::fs::File,
}

impl Drop for StoreAuthWriteGuard {
    fn drop(&mut self) {
        let _ = Fs4FileExt::unlock(&self.lock_file);
    }
}

impl fmt::Debug for StoreAuthRoot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StoreAuthRoot")
            .field("keys_dir", &self.keys_dir)
            .field("current_key_id", &self.current.key_id)
            .field("retired_keys", &self.retired.len())
            .finish()
    }
}

impl StoreAuthRoot {
    /// Open the store if it exists, otherwise create it. The common wiring path.
    pub fn open_or_create(keys_dir: impl AsRef<Path>) -> Result<Self, StoreAuthError> {
        let keys_dir = keys_dir.as_ref();
        let path = keys_dir.join(KEY_FILE_NAME);
        match path.try_exists() {
            Ok(true) => Self::open(keys_dir),
            Ok(false) => match Self::create(keys_dir) {
                // A concurrent creator won the race between our existence check
                // and the exclusive create; adopt their root instead of ours.
                Err(StoreAuthError::AlreadyInitialized { .. }) => Self::open(keys_dir),
                other => other,
            },
            Err(error) => Err(StoreAuthError::Io {
                path: path.display().to_string(),
                message: error.to_string(),
            }),
        }
    }

    /// Create a fresh root, failing if one already exists. The key file is
    /// claimed exclusively (`O_EXCL`) so two racing processes cannot mint
    /// divergent roots.
    pub fn create(keys_dir: impl AsRef<Path>) -> Result<Self, StoreAuthError> {
        primitive_known_answer_check()?;
        let keys_dir = keys_dir.as_ref();
        let path = keys_dir.join(KEY_FILE_NAME);
        reject_symlink_components(keys_dir, &path)?;
        ensure_hardened_dir(keys_dir)?;

        let current = KeyEntry {
            key_id: KeyId(random_bytes::<KEY_ID_LEN>()?),
            root: Secret(random_bytes::<KEY_LEN>()?),
        };
        let root = Self {
            keys_dir: keys_dir.to_path_buf(),
            current,
            retired: Vec::new(),
        };
        let serialized = root.serialize()?;
        write_exclusive(&path, &serialized)?;
        Ok(root)
    }

    /// Load and verify an existing root: hardened permissions, no symlinked
    /// components, schema match, bounded window, and an integrity self-check.
    pub fn open(keys_dir: impl AsRef<Path>) -> Result<Self, StoreAuthError> {
        primitive_known_answer_check()?;
        let keys_dir = keys_dir.as_ref();
        let path = keys_dir.join(KEY_FILE_NAME);
        reject_symlink_components(keys_dir, &path)?;
        match path.try_exists() {
            Ok(true) => {}
            Ok(false) => {
                return Err(StoreAuthError::NotInitialized {
                    path: path.display().to_string(),
                });
            }
            Err(error) => {
                return Err(StoreAuthError::Io {
                    path: path.display().to_string(),
                    message: error.to_string(),
                });
            }
        }
        enforce_owner_only_dir(keys_dir)?;
        enforce_owner_only_file(&path)?;

        let bytes = Zeroizing::new(read_key_file(&path)?);
        Self::from_serialized(keys_dir, &bytes)
    }

    pub(crate) fn from_serialized(keys_dir: &Path, bytes: &[u8]) -> Result<Self, StoreAuthError> {
        primitive_known_answer_check()?;
        if bytes.len() as u64 > MAX_KEY_FILE_BYTES {
            return Err(recovery_error("key file exceeds the size limit"));
        }
        let doc: KeyFileDoc =
            serde_json::from_slice(bytes).map_err(|error| StoreAuthError::Malformed {
                message: format!("key file JSON: {error}"),
            })?;
        if doc.schema != KEY_FILE_SCHEMA {
            return Err(StoreAuthError::SchemaMismatch {
                found: doc.schema,
                expected: KEY_FILE_SCHEMA.to_owned(),
            });
        }
        if doc.retired.len() > MAX_RETIRED_KEYS {
            return Err(StoreAuthError::Malformed {
                message: format!(
                    "retired window has {} keys, exceeds max {MAX_RETIRED_KEYS}",
                    doc.retired.len()
                ),
            });
        }

        let current = doc.current.into_entry()?;
        let retired = doc
            .retired
            .into_iter()
            .map(KeyFileEntry::into_entry)
            .collect::<Result<Vec<_>, _>>()?;
        let root = Self {
            keys_dir: keys_dir.to_path_buf(),
            current,
            retired,
        };

        let expected = Mac::from_hex(&doc.self_check)?;
        if root.current.self_check() != expected {
            return Err(StoreAuthError::SelfCheckFailed);
        }
        let ids = root.window_key_ids();
        if ids
            .iter()
            .enumerate()
            .any(|(index, id)| ids[..index].contains(id))
        {
            return Err(recovery_error(
                "key file contains duplicate key identifiers",
            ));
        }
        Ok(root)
    }

    /// Seal the complete current/retired window without changing the source.
    /// Each envelope gets independent OS-random salt and nonce values.
    pub(crate) fn encrypted_recovery(&self, passphrase: &str) -> Result<Vec<u8>, StoreAuthError> {
        validate_recovery_passphrase(passphrase)?;
        let salt = random_bytes::<32>()?;
        let nonce = random_bytes::<{ aead::NONCE_LEN }>()?;
        let mut ciphertext = Zeroizing::new(self.serialize()?);
        recovery_cipher(passphrase, &salt)?
            .seal_in_place_append_tag(
                aead::Nonce::assume_unique_for_key(nonce),
                aead::Aad::from(RECOVERY_SCHEMA.as_bytes()),
                &mut *ciphertext,
            )
            .map_err(|_| recovery_error("could not encrypt recovery keys"))?;
        let envelope = StoreAuthRecoveryEnvelope {
            schema: RECOVERY_SCHEMA.to_owned(),
            kdf: RECOVERY_KDF.to_owned(),
            iterations: RECOVERY_ITERATIONS,
            salt,
            nonce,
            ciphertext: ciphertext.to_vec(),
        };
        serde_json::to_vec(&envelope)
            .map_err(|_| recovery_error("could not serialize encrypted recovery keys"))
    }

    /// Authenticate and validate recovery material before the caller creates
    /// any destination. KDF parameters are bounded before expensive work.
    pub(crate) fn decrypt_recovery(
        bytes: &[u8],
        passphrase: &str,
    ) -> Result<RecoveredStoreAuth, StoreAuthError> {
        validate_recovery_passphrase(passphrase)?;
        if bytes.len() > MAX_RECOVERY_BYTES {
            return Err(recovery_error(
                "encrypted recovery envelope exceeds the size limit",
            ));
        }
        let envelope: StoreAuthRecoveryEnvelope = serde_json::from_slice(bytes)
            .map_err(|_| recovery_error("invalid encrypted recovery envelope"))?;
        if envelope.schema != RECOVERY_SCHEMA
            || envelope.kdf != RECOVERY_KDF
            || envelope.iterations != RECOVERY_ITERATIONS
            || envelope.ciphertext.len() < aead::CHACHA20_POLY1305.tag_len()
            || envelope.ciphertext.len() as u64
                > MAX_KEY_FILE_BYTES + aead::CHACHA20_POLY1305.tag_len() as u64
        {
            return Err(recovery_error(
                "unsupported or malformed encrypted recovery envelope",
            ));
        }
        let cipher = recovery_cipher(passphrase, &envelope.salt)?;
        let mut plaintext = Zeroizing::new(envelope.ciphertext);
        let opened = cipher
            .open_in_place(
                aead::Nonce::assume_unique_for_key(envelope.nonce),
                aead::Aad::from(RECOVERY_SCHEMA.as_bytes()),
                plaintext.as_mut(),
            )
            .map_err(|_| {
                recovery_error("recovery decryption failed: wrong passphrase or modified envelope")
            })?;
        let root = Self::from_serialized(Path::new("recovered-store-auth"), opened)
            .map_err(|_| recovery_error("decrypted recovery key file is invalid"))?;
        Ok(RecoveredStoreAuth {
            key_file: Zeroizing::new(root.serialize()?),
            key_ids: root.window_key_ids().iter().map(KeyId::to_hex).collect(),
        })
    }

    /// Load the current root while holding the key store's shared advisory
    /// lock. Rotation waits until the returned guard is dropped.
    pub fn open_read_locked(
        keys_dir: impl AsRef<Path>,
    ) -> Result<StoreAuthReadGuard, StoreAuthError> {
        let keys_dir = keys_dir.as_ref();
        let lock_file = open_key_lock_file(keys_dir)?;
        Fs4FileExt::lock_shared(&lock_file).map_err(|error| StoreAuthError::Io {
            path: keys_dir.join(KEY_LOCK_FILE_NAME).display().to_string(),
            message: format!("acquire shared key-store lock: {error}"),
        })?;
        match Self::open(keys_dir) {
            Ok(root) => Ok(StoreAuthReadGuard { root, lock_file }),
            Err(error) => {
                let _ = Fs4FileExt::unlock(&lock_file);
                Err(error)
            }
        }
    }

    /// Rotate to a fresh root. The prior current key moves into the bounded
    /// retired window (oldest evicted past `MAX_RETIRED_KEYS`); the key file
    /// is atomically replaced. Returns the new current key id.
    pub fn rotate(&mut self) -> Result<KeyId, StoreAuthError> {
        let lock_file = open_key_lock_file(&self.keys_dir)?;
        Fs4FileExt::lock(&lock_file).map_err(|error| StoreAuthError::Io {
            path: self.keys_dir.join(KEY_LOCK_FILE_NAME).display().to_string(),
            message: format!("acquire exclusive key-store lock: {error}"),
        })?;
        let _write_guard = StoreAuthWriteGuard { lock_file };

        // Adopt the latest on-disk window only after acquiring the exclusive
        // lock. This prevents two stale in-memory handles from losing each
        // other's retired-key history during consecutive rotations.
        let disk = Self::open(&self.keys_dir)?;
        self.current = disk.current;
        self.retired = disk.retired;

        let new_entry = KeyEntry {
            key_id: KeyId(random_bytes::<KEY_ID_LEN>()?),
            root: Secret(random_bytes::<KEY_LEN>()?),
        };
        let previous = std::mem::replace(&mut self.current, new_entry);
        self.retired.insert(0, previous);
        self.retired.truncate(MAX_RETIRED_KEYS);

        let path = self.keys_dir.join(KEY_FILE_NAME);
        let tmp = self.keys_dir.join(KEY_FILE_TMP_NAME);
        let serialized = self.serialize()?;
        write_replace(&tmp, &path, &serialized)?;
        Ok(self.current.key_id)
    }

    /// The current key identifier.
    #[must_use]
    pub fn current_key_id(&self) -> KeyId {
        self.current.key_id
    }

    /// All key identifiers accepted for same-store verification (current first,
    /// then retired, most-recent-first).
    #[must_use]
    pub fn window_key_ids(&self) -> Vec<KeyId> {
        let mut ids = Vec::with_capacity(1 + self.retired.len());
        ids.push(self.current.key_id);
        ids.extend(self.retired.iter().map(|entry| entry.key_id));
        ids
    }

    /// Compute a domain-separated MAC under the current key.
    ///
    /// Fallible by contract (TC-D14 / P0.6): the in-memory backend cannot fail
    /// today, but the signature reserves fallibility for a future keychain- or
    /// HSM-backed root without churning every call site.
    pub fn mac(&self, domain: MacDomain, message: &[u8]) -> Result<Mac, StoreAuthError> {
        Ok(self.current.mac(domain, message))
    }

    /// Constant-time verify a candidate MAC against the current key.
    pub fn verify(
        &self,
        domain: MacDomain,
        message: &[u8],
        candidate: &Mac,
    ) -> Result<bool, StoreAuthError> {
        Ok(self.current.mac(domain, message) == *candidate)
    }

    /// Verify a candidate MAC against the key named by `key_id`, honoring the
    /// bounded retired window. Approval consumers must additionally require
    /// [`KeyClass::Current`]; import may accept [`KeyClass::Retired`].
    pub fn verify_with_key(
        &self,
        key_id: KeyId,
        domain: MacDomain,
        message: &[u8],
        candidate: &Mac,
    ) -> Result<KeyVerification, StoreAuthError> {
        let (entry, key_class) = if self.current.key_id == key_id {
            (&self.current, KeyClass::Current)
        } else if let Some(entry) = self.retired.iter().find(|entry| entry.key_id == key_id) {
            (entry, KeyClass::Retired)
        } else {
            return Ok(KeyVerification::KeyOutsideWindow);
        };
        if entry.mac(domain, message) == *candidate {
            Ok(KeyVerification::Match { key_class })
        } else {
            Ok(KeyVerification::Mismatch)
        }
    }

    fn serialize(&self) -> Result<Vec<u8>, StoreAuthError> {
        let doc = KeyFileDoc {
            schema: KEY_FILE_SCHEMA.to_owned(),
            current: self.current.to_file_entry(),
            retired: self.retired.iter().map(KeyEntry::to_file_entry).collect(),
            self_check: self.current.self_check().to_hex(),
        };
        serde_json::to_vec_pretty(&doc).map_err(|error| StoreAuthError::Io {
            path: self.keys_dir.join(KEY_FILE_NAME).display().to_string(),
            message: format!("serialize key file: {error}"),
        })
    }
}

/// On-disk key-file document. The `root` fields carry the raw root as hex; this
/// file is the sole legitimate home for that material.
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct KeyFileDoc {
    schema: String,
    current: KeyFileEntry,
    #[serde(default)]
    retired: Vec<KeyFileEntry>,
    self_check: String,
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct KeyFileEntry {
    key_id: String,
    root: String,
}

impl fmt::Debug for KeyFileEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KeyFileEntry")
            .field("key_id", &self.key_id)
            .field("root", &"<redacted>")
            .finish()
    }
}

impl Drop for KeyFileEntry {
    fn drop(&mut self) {
        self.root.zeroize();
    }
}

impl KeyFileEntry {
    fn into_entry(self) -> Result<KeyEntry, StoreAuthError> {
        Ok(KeyEntry {
            key_id: KeyId::from_hex(&self.key_id)?,
            root: Secret(decode_hex_fixed::<KEY_LEN>(&self.root, "root")?),
        })
    }
}

/// Verify the BLAKE3 wiring and domain strings against pinned reference vectors
/// before any key material is generated or trusted.
fn primitive_known_answer_check() -> Result<(), StoreAuthError> {
    let root: [u8; KEY_LEN] = std::array::from_fn(|index| index as u8);

    let subkey = blake3::derive_key(MacDomain::NativeImportRecordsRoot.context(), &root);
    if hex_lower(&subkey) != KAT_SUBKEY_HEX {
        return Err(StoreAuthError::PrimitiveKnownAnswerFailed {
            detail: "derive_key subkey mismatch".to_owned(),
        });
    }
    let mac = blake3::keyed_hash(&subkey, KAT_MESSAGE);
    if hex_lower(mac.as_bytes()) != KAT_MAC_HEX {
        return Err(StoreAuthError::PrimitiveKnownAnswerFailed {
            detail: "keyed_hash MAC mismatch".to_owned(),
        });
    }
    let self_check_subkey = blake3::derive_key(SELF_CHECK_CONTEXT, &root);
    let self_check = blake3::keyed_hash(&self_check_subkey, SELF_CHECK_MESSAGE);
    if hex_lower(self_check.as_bytes()) != KAT_SELF_CHECK_HEX {
        return Err(StoreAuthError::PrimitiveKnownAnswerFailed {
            detail: "self-check construction mismatch".to_owned(),
        });
    }
    Ok(())
}

fn random_bytes<const N: usize>() -> Result<[u8; N], StoreAuthError> {
    let mut buffer = [0_u8; N];
    getrandom::fill(&mut buffer).map_err(|error| StoreAuthError::Randomness {
        message: error.to_string(),
    })?;
    Ok(buffer)
}

/// Constant-time equality over equal-length byte slices.
fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    if left.len() != right.len() {
        return false;
    }
    let mut diff = 0_u8;
    for (a, b) in left.iter().zip(right.iter()) {
        diff |= a ^ b;
    }
    diff == 0
}

fn decode_hex_fixed<const N: usize>(value: &str, label: &str) -> Result<[u8; N], StoreAuthError> {
    let trimmed = value.trim();
    if trimmed.len() != N * 2 {
        return Err(StoreAuthError::Malformed {
            message: format!(
                "{label} must be {} hex chars, found {}",
                N * 2,
                trimmed.len()
            ),
        });
    }
    let bytes = trimmed.as_bytes();
    let mut out = [0_u8; N];
    let mut index = 0;
    while index < N {
        let high = hex_nibble(bytes[index * 2], label)?;
        let low = hex_nibble(bytes[index * 2 + 1], label)?;
        out[index] = (high << 4) | low;
        index += 1;
    }
    Ok(out)
}

fn hex_nibble(byte: u8, label: &str) -> Result<u8, StoreAuthError> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        b'A'..=b'F' => Ok(byte - b'A' + 10),
        _ => Err(StoreAuthError::Malformed {
            message: format!("{label} contains a non-hex character"),
        }),
    }
}

fn read_key_file(path: &Path) -> Result<Vec<u8>, StoreAuthError> {
    let metadata = std::fs::symlink_metadata(path).map_err(|error| StoreAuthError::Io {
        path: path.display().to_string(),
        message: error.to_string(),
    })?;
    if metadata.len() > MAX_KEY_FILE_BYTES {
        return Err(StoreAuthError::Malformed {
            message: format!("key file is {} bytes, exceeds cap", metadata.len()),
        });
    }
    std::fs::read(path).map_err(|error| StoreAuthError::Io {
        path: path.display().to_string(),
        message: error.to_string(),
    })
}

fn reject_symlink_components(keys_dir: &Path, path: &Path) -> Result<(), StoreAuthError> {
    for candidate in [keys_dir, path] {
        if let Ok(metadata) = std::fs::symlink_metadata(candidate)
            && metadata.file_type().is_symlink()
        {
            return Err(StoreAuthError::SymlinkComponent {
                path: candidate.display().to_string(),
            });
        }
    }
    Ok(())
}

fn ensure_hardened_dir(keys_dir: &Path) -> Result<(), StoreAuthError> {
    std::fs::create_dir_all(keys_dir).map_err(|error| StoreAuthError::Io {
        path: keys_dir.display().to_string(),
        message: error.to_string(),
    })?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(keys_dir, std::fs::Permissions::from_mode(0o700)).map_err(
            |error| StoreAuthError::Io {
                path: keys_dir.display().to_string(),
                message: format!("harden directory permissions: {error}"),
            },
        )?;
    }
    Ok(())
}

#[cfg(unix)]
fn enforce_owner_only_dir(keys_dir: &Path) -> Result<(), StoreAuthError> {
    enforce_owner_only_mode(keys_dir, "key directory")
}

#[cfg(unix)]
fn enforce_owner_only_file(path: &Path) -> Result<(), StoreAuthError> {
    enforce_owner_only_mode(path, "key file")
}

#[cfg(unix)]
fn enforce_owner_only_mode(path: &Path, label: &str) -> Result<(), StoreAuthError> {
    use std::os::unix::fs::PermissionsExt;
    let metadata = std::fs::symlink_metadata(path).map_err(|error| StoreAuthError::Io {
        path: path.display().to_string(),
        message: error.to_string(),
    })?;
    let mode = metadata.permissions().mode() & 0o777;
    if mode & 0o077 != 0 {
        return Err(StoreAuthError::InsecurePermissions {
            path: path.display().to_string(),
            detail: format!("{label} mode {mode:04o} grants group/other access"),
        });
    }
    Ok(())
}

#[cfg(not(unix))]
fn enforce_owner_only_dir(_keys_dir: &Path) -> Result<(), StoreAuthError> {
    // Non-Unix permission hardening relies on the default per-user profile ACL;
    // an explicit ACL tightening pass is a documented residual for this slice.
    Ok(())
}

#[cfg(not(unix))]
fn enforce_owner_only_file(_path: &Path) -> Result<(), StoreAuthError> {
    Ok(())
}

/// Open the persistent owner-only advisory lock file used to serialize key
/// rotation against approval transactions. The file contains no key material
/// and is never removed; descriptor close is the crash-safe unlock path.
fn open_key_lock_file(keys_dir: &Path) -> Result<std::fs::File, StoreAuthError> {
    ensure_hardened_dir(keys_dir)?;
    let path = keys_dir.join(KEY_LOCK_FILE_NAME);
    reject_symlink_components(keys_dir, &path)?;
    let mut options = std::fs::OpenOptions::new();
    options.read(true).write(true).create(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let file = options.open(&path).map_err(|error| StoreAuthError::Io {
        path: path.display().to_string(),
        message: format!("open key-store lock: {error}"),
    })?;
    enforce_owner_only_file(&path)?;
    Ok(file)
}

/// Exclusively create the key file (`O_EXCL`), owner-only on Unix.
fn write_exclusive(path: &Path, bytes: &[u8]) -> Result<(), StoreAuthError> {
    use std::io::Write as _;
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options.open(path).map_err(|error| {
        if error.kind() == std::io::ErrorKind::AlreadyExists {
            StoreAuthError::AlreadyInitialized {
                path: path.display().to_string(),
            }
        } else {
            StoreAuthError::Io {
                path: path.display().to_string(),
                message: error.to_string(),
            }
        }
    })?;
    file.write_all(bytes).map_err(|error| StoreAuthError::Io {
        path: path.display().to_string(),
        message: error.to_string(),
    })?;
    file.sync_all().map_err(|error| StoreAuthError::Io {
        path: path.display().to_string(),
        message: error.to_string(),
    })?;
    Ok(())
}

/// Atomically replace an existing key file via a hardened temp sibling + rename.
fn write_replace(tmp: &Path, path: &Path, bytes: &[u8]) -> Result<(), StoreAuthError> {
    use std::io::Write as _;
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options.open(tmp).map_err(|error| StoreAuthError::Io {
        path: tmp.display().to_string(),
        message: error.to_string(),
    })?;
    file.write_all(bytes).map_err(|error| StoreAuthError::Io {
        path: tmp.display().to_string(),
        message: error.to_string(),
    })?;
    file.sync_all().map_err(|error| StoreAuthError::Io {
        path: tmp.display().to_string(),
        message: error.to_string(),
    })?;
    std::fs::rename(tmp, path).map_err(|error| StoreAuthError::Io {
        path: path.display().to_string(),
        message: format!("atomic replace: {error}"),
    })?;
    Ok(())
}

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

    fn keys_dir() -> tempfile::TempDir {
        tempfile::TempDir::new().expect("tempdir")
    }

    #[test]
    fn encrypted_recovery_preserves_the_complete_rotation_window() {
        let dir = keys_dir();
        let mut root = StoreAuthRoot::create(dir.path()).expect("create");
        let message = b"portable backup evidence";
        let mut signatures = Vec::new();
        for index in 0..=MAX_RETIRED_KEYS {
            signatures.push((
                root.current_key_id(),
                root.mac(MacDomain::NativeImportRecordsRoot, message)
                    .expect("mac"),
            ));
            if index < MAX_RETIRED_KEYS {
                root.rotate().expect("rotate");
            }
        }
        let original = std::fs::read(dir.path().join(KEY_FILE_NAME)).expect("read source");
        let passphrase = "synthetic recovery passphrase 123";
        let encrypted = root.encrypted_recovery(passphrase).expect("encrypt");
        let second = root.encrypted_recovery(passphrase).expect("encrypt again");
        assert_ne!(encrypted, second, "independent salt and nonce");
        let recovered = StoreAuthRoot::decrypt_recovery(&encrypted, passphrase).expect("decrypt");
        let reopened =
            StoreAuthRoot::from_serialized(dir.path(), &recovered.key_file).expect("parse");
        assert_eq!(root.window_key_ids(), reopened.window_key_ids());
        for (id, mac) in signatures {
            assert!(matches!(
                reopened
                    .verify_with_key(id, MacDomain::NativeImportRecordsRoot, message, &mac)
                    .expect("verify"),
                KeyVerification::Match { .. }
            ));
        }
        assert_eq!(
            original,
            std::fs::read(dir.path().join(KEY_FILE_NAME)).expect("read unchanged")
        );
        let doc: KeyFileDoc = serde_json::from_slice(&original).expect("key doc");
        let public_output = format!(
            "{} {recovered:?} {doc:?}",
            String::from_utf8_lossy(&encrypted)
        );
        assert!(!public_output.contains(passphrase));
        for entry in std::iter::once(&doc.current).chain(&doc.retired) {
            assert!(!public_output.contains(&entry.root), "root secret leaked");
        }
    }

    #[test]
    fn encrypted_recovery_rejects_wrong_password_tampering_and_unbounded_work() {
        let dir = keys_dir();
        let root = StoreAuthRoot::create(dir.path()).expect("create");
        let passphrase = "synthetic recovery passphrase 123";
        let bytes = root.encrypted_recovery(passphrase).expect("encrypt");
        assert!(StoreAuthRoot::decrypt_recovery(&bytes, "different synthetic passphrase").is_err());
        let envelope: StoreAuthRecoveryEnvelope = serde_json::from_slice(&bytes).expect("envelope");
        for field in [
            "ciphertext",
            "nonce",
            "salt",
            "schema",
            "kdf",
            "iterations",
            "empty",
        ] {
            let mut changed = envelope.clone();
            match field {
                "ciphertext" => changed.ciphertext[0] ^= 1,
                "nonce" => changed.nonce[0] ^= 1,
                "salt" => changed.salt[0] ^= 1,
                "schema" => changed.schema.push('x'),
                "kdf" => changed.kdf.push('x'),
                "iterations" => changed.iterations = u32::MAX,
                _ => changed.ciphertext.clear(),
            }
            let changed = serde_json::to_vec(&changed).expect("changed envelope");
            assert!(
                StoreAuthRoot::decrypt_recovery(&changed, passphrase).is_err(),
                "accepted changed {field}"
            );
        }
        assert!(StoreAuthRoot::decrypt_recovery(&bytes[..bytes.len() / 2], passphrase).is_err());
        assert!(
            StoreAuthRoot::decrypt_recovery(&vec![b' '; MAX_RECOVERY_BYTES + 1], passphrase)
                .is_err()
        );
    }

    #[test]
    fn encrypted_recovery_rejects_invalid_plaintext_and_passphrases() {
        for passphrase in [
            "",
            "short",
            "long enough but\nmultiline",
            "long enough but\0nul",
        ] {
            assert!(validate_recovery_passphrase(passphrase).is_err());
        }
        assert!(validate_recovery_passphrase(&"x".repeat(1025)).is_err());
        assert!(validate_recovery_passphrase(&"🦀".repeat(1024)).is_ok());
        let dir = keys_dir();
        let root = StoreAuthRoot::create(dir.path()).expect("create");
        let mut doc: serde_json::Value =
            serde_json::from_slice(&root.serialize().expect("serialize")).expect("json");
        doc["retired"] = serde_json::json!([doc["current"].clone()]);
        let passphrase = "synthetic recovery passphrase 123";
        let mut envelope: StoreAuthRecoveryEnvelope =
            serde_json::from_slice(&root.encrypted_recovery(passphrase).expect("encrypt"))
                .expect("envelope");
        envelope.nonce = random_bytes().expect("fresh nonce");
        envelope.ciphertext = serde_json::to_vec(&doc).expect("duplicate key payload");
        recovery_cipher(passphrase, &envelope.salt)
            .expect("cipher")
            .seal_in_place_append_tag(
                aead::Nonce::assume_unique_for_key(envelope.nonce),
                aead::Aad::from(RECOVERY_SCHEMA.as_bytes()),
                &mut envelope.ciphertext,
            )
            .expect("seal");
        let invalid = serde_json::to_vec(&envelope).expect("invalid envelope");
        let error = StoreAuthRoot::decrypt_recovery(&invalid, passphrase)
            .expect_err("duplicate identifiers rejected");
        assert!(
            matches!(error, StoreAuthError::Malformed { message } if message == "decrypted recovery key file is invalid")
        );
    }

    #[test]
    fn primitive_known_answer_check_passes_against_reference_vectors() {
        primitive_known_answer_check().expect("BLAKE3 wiring must match pinned b3sum vectors");
    }

    #[test]
    fn create_then_open_round_trips_and_macs_are_stable() {
        let dir = keys_dir();
        let created = StoreAuthRoot::create(dir.path()).expect("create");
        let message = b"records-root-digest";
        let mac_before = created
            .mac(MacDomain::NativeImportRecordsRoot, message)
            .expect("mac");
        drop(created);

        let opened = StoreAuthRoot::open(dir.path()).expect("open");
        let mac_after = opened
            .mac(MacDomain::NativeImportRecordsRoot, message)
            .expect("mac");
        assert_eq!(mac_before, mac_after, "MAC must survive a reopen");
        assert!(
            opened
                .verify(MacDomain::NativeImportRecordsRoot, message, &mac_before)
                .expect("verify")
        );
    }

    #[test]
    fn open_or_create_is_idempotent() {
        let dir = keys_dir();
        let first = StoreAuthRoot::open_or_create(dir.path()).expect("first");
        let id = first.current_key_id();
        drop(first);
        let second = StoreAuthRoot::open_or_create(dir.path()).expect("second");
        assert_eq!(id, second.current_key_id(), "must adopt the existing root");
    }

    #[test]
    fn read_guard_blocks_rotation_lock_until_the_transaction_finishes() {
        let dir = keys_dir();
        StoreAuthRoot::create(dir.path()).expect("create");
        let guard = StoreAuthRoot::open_read_locked(dir.path()).expect("shared read lock");
        let contender = open_key_lock_file(dir.path()).expect("rotation contender");

        assert!(
            matches!(
                Fs4FileExt::try_lock(&contender),
                Err(fs4::TryLockError::WouldBlock)
            ),
            "rotation must not enter while an approval transaction holds the read guard"
        );

        drop(guard);
        Fs4FileExt::try_lock(&contender)
            .expect("rotation may enter after the approval transaction releases its guard");
        Fs4FileExt::unlock(&contender).expect("unlock contender");
    }

    #[test]
    fn create_twice_is_already_initialized() {
        let dir = keys_dir();
        StoreAuthRoot::create(dir.path()).expect("create");
        let error = StoreAuthRoot::create(dir.path()).expect_err("second create must fail");
        assert!(matches!(error, StoreAuthError::AlreadyInitialized { .. }));
    }

    #[test]
    fn open_uninitialized_is_not_initialized() {
        let dir = keys_dir();
        let error = StoreAuthRoot::open(dir.path()).expect_err("open must fail");
        assert!(matches!(error, StoreAuthError::NotInitialized { .. }));
    }

    #[test]
    fn inaccessible_key_path_is_io_not_not_initialized() {
        let dir = keys_dir();
        let regular_file = dir.path().join("not-a-directory");
        std::fs::write(&regular_file, b"occupied").expect("write regular-file path component");
        let impossible_keys_dir = regular_file.join("keys");

        for error in [
            StoreAuthRoot::open(&impossible_keys_dir).expect_err("open must reject invalid path"),
            StoreAuthRoot::open_or_create(&impossible_keys_dir)
                .expect_err("open-or-create must reject invalid path"),
        ] {
            assert!(
                matches!(error, StoreAuthError::Io { .. }),
                "an inaccessible key path is an I/O fault, not an absent store: {error:?}"
            );
        }
    }

    #[test]
    fn distinct_domains_yield_distinct_macs() {
        let dir = keys_dir();
        let root = StoreAuthRoot::create(dir.path()).expect("create");
        let message = b"same-bytes";
        let native = root
            .mac(MacDomain::NativeImportRecordsRoot, message)
            .expect("mac");
        let playbook = root
            .mac(MacDomain::PlaybookImportRecordsRoot, message)
            .expect("mac");
        assert_ne!(
            native, playbook,
            "cross-domain MACs over identical bytes must differ"
        );
    }

    #[test]
    fn lane_mac_cannot_replay_in_the_reserved_body_approval_domain() {
        let dir = keys_dir();
        let root = StoreAuthRoot::create(dir.path()).expect("create");
        let message = b"T1.4 body metadata lane snapshot";
        let lane = root
            .mac(MacDomain::LaneApprovalSnapshotTag, message)
            .expect("lane MAC");

        assert!(
            root.verify(MacDomain::LaneApprovalSnapshotTag, message, &lane)
                .expect("verify in lane domain"),
            "the generic T1.4 lane domain must accept its own MAC"
        );
        assert!(
            !root
                .verify(MacDomain::BodyApprovalSnapshotTag, message, &lane)
                .expect("verify in reserved body domain"),
            "a T1.4 metadata-body lane MAC must not replay in T5.9's reserved domain"
        );
    }

    #[test]
    fn tampered_message_fails_verification() {
        let dir = keys_dir();
        let root = StoreAuthRoot::create(dir.path()).expect("create");
        let mac = root
            .mac(MacDomain::NativeImportRecordsRoot, b"authentic")
            .expect("mac");
        assert!(
            !root
                .verify(MacDomain::NativeImportRecordsRoot, b"tampered", &mac)
                .expect("verify")
        );
    }

    #[test]
    fn two_stores_have_independent_roots() {
        let dir_a = keys_dir();
        let dir_b = keys_dir();
        let root_a = StoreAuthRoot::create(dir_a.path()).expect("a");
        let root_b = StoreAuthRoot::create(dir_b.path()).expect("b");
        assert_ne!(root_a.current_key_id(), root_b.current_key_id());
        let message = b"cross-store";
        let mac_a = root_a
            .mac(MacDomain::NativeImportRecordsRoot, message)
            .expect("mac");
        assert!(
            !root_b
                .verify(MacDomain::NativeImportRecordsRoot, message, &mac_a)
                .expect("verify"),
            "a foreign store's MAC must not verify"
        );
    }

    #[test]
    fn rotation_moves_prior_key_into_the_window() {
        let dir = keys_dir();
        let mut root = StoreAuthRoot::create(dir.path()).expect("create");
        let old_id = root.current_key_id();
        let message = b"pre-rotation";
        let old_mac = root
            .mac(MacDomain::NativeImportRecordsRoot, message)
            .expect("mac");

        let new_id = root.rotate().expect("rotate");
        assert_ne!(old_id, new_id, "rotation must mint a new key id");
        assert_eq!(new_id, root.current_key_id());

        // Old key still verifies within the window, classed Retired.
        let verdict = root
            .verify_with_key(
                old_id,
                MacDomain::NativeImportRecordsRoot,
                message,
                &old_mac,
            )
            .expect("verify");
        assert_eq!(
            verdict,
            KeyVerification::Match {
                key_class: KeyClass::Retired
            }
        );

        // Current key over the same message is a distinct tag.
        let current_verdict = root
            .verify_with_key(
                new_id,
                MacDomain::NativeImportRecordsRoot,
                message,
                &old_mac,
            )
            .expect("verify");
        assert_eq!(current_verdict, KeyVerification::Mismatch);
    }

    #[test]
    fn rotation_window_evicts_the_oldest_key() {
        let dir = keys_dir();
        let mut root = StoreAuthRoot::create(dir.path()).expect("create");
        let oldest = root.current_key_id();
        let message = b"windowed";
        let oldest_mac = root
            .mac(MacDomain::NativeImportRecordsRoot, message)
            .expect("mac");

        // Rotate MAX_RETIRED_KEYS + 1 times so the very first key falls out.
        for _ in 0..(MAX_RETIRED_KEYS + 1) {
            root.rotate().expect("rotate");
        }
        assert_eq!(root.window_key_ids().len(), MAX_RETIRED_KEYS + 1);
        let verdict = root
            .verify_with_key(
                oldest,
                MacDomain::NativeImportRecordsRoot,
                message,
                &oldest_mac,
            )
            .expect("verify");
        assert_eq!(verdict, KeyVerification::KeyOutsideWindow);
    }

    #[test]
    fn rotation_persists_and_reopens() {
        let dir = keys_dir();
        let mut root = StoreAuthRoot::create(dir.path()).expect("create");
        let old_id = root.current_key_id();
        let message = b"persisted-rotation";
        let old_mac = root
            .mac(MacDomain::NativeImportRecordsRoot, message)
            .expect("mac");
        let new_id = root.rotate().expect("rotate");
        drop(root);

        let reopened = StoreAuthRoot::open(dir.path()).expect("reopen");
        assert_eq!(reopened.current_key_id(), new_id);
        let verdict = reopened
            .verify_with_key(
                old_id,
                MacDomain::NativeImportRecordsRoot,
                message,
                &old_mac,
            )
            .expect("verify");
        assert_eq!(
            verdict,
            KeyVerification::Match {
                key_class: KeyClass::Retired
            }
        );
    }

    #[test]
    fn corrupted_root_fails_the_self_check() {
        let dir = keys_dir();
        StoreAuthRoot::create(dir.path()).expect("create");
        let path = dir.path().join(KEY_FILE_NAME);
        let raw = std::fs::read_to_string(&path).expect("read");
        let mut doc: serde_json::Value = serde_json::from_str(&raw).expect("json");
        // Flip the stored root but leave selfCheck untouched.
        doc["current"]["root"] = serde_json::Value::String("00".repeat(KEY_LEN));
        std::fs::write(&path, doc.to_string()).expect("write");

        let error = StoreAuthRoot::open(dir.path()).expect_err("self-check must fail");
        assert_eq!(error, StoreAuthError::SelfCheckFailed);
    }

    #[test]
    fn schema_mismatch_is_rejected() {
        let dir = keys_dir();
        StoreAuthRoot::create(dir.path()).expect("create");
        let path = dir.path().join(KEY_FILE_NAME);
        let raw = std::fs::read_to_string(&path).expect("read");
        let mut doc: serde_json::Value = serde_json::from_str(&raw).expect("json");
        doc["schema"] = serde_json::Value::String("ee.store_auth.keyfile.v0".to_owned());
        std::fs::write(&path, doc.to_string()).expect("write");

        let error = StoreAuthRoot::open(dir.path()).expect_err("schema must fail");
        assert!(matches!(error, StoreAuthError::SchemaMismatch { .. }));
    }

    #[cfg(unix)]
    #[test]
    fn group_readable_key_file_is_insecure() {
        use std::os::unix::fs::PermissionsExt;
        let dir = keys_dir();
        StoreAuthRoot::create(dir.path()).expect("create");
        let path = dir.path().join(KEY_FILE_NAME);
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).expect("chmod");

        let error = StoreAuthRoot::open(dir.path()).expect_err("insecure perms must fail");
        assert!(matches!(error, StoreAuthError::InsecurePermissions { .. }));
    }

    #[cfg(unix)]
    #[test]
    fn created_key_file_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let dir = keys_dir();
        StoreAuthRoot::create(dir.path()).expect("create");
        let path = dir.path().join(KEY_FILE_NAME);
        let mode = std::fs::symlink_metadata(&path)
            .expect("metadata")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode & 0o077, 0, "created key file must be owner-only");
    }

    #[test]
    fn secret_debug_is_redacted_and_mac_debug_shows_hex() {
        let secret = Secret([7_u8; KEY_LEN]);
        assert_eq!(format!("{secret:?}"), "Secret(<redacted>)");
        let mac = Mac([0xab_u8; MAC_LEN]);
        assert!(format!("{mac:?}").contains(&"ab".repeat(MAC_LEN)));
        assert_eq!(Mac::from_bytes(*mac.as_bytes()), mac);
    }

    #[test]
    fn key_id_hex_round_trips() {
        let id = KeyId([0x3c_u8; KEY_ID_LEN]);
        let parsed = KeyId::from_hex(&id.to_hex()).expect("round trip");
        assert_eq!(id, parsed);
        assert!(KeyId::from_hex("zz").is_err());
    }

    #[test]
    fn error_degraded_code_is_the_store_auth_code() {
        let error = StoreAuthError::SelfCheckFailed;
        assert_eq!(
            error.degraded_code(),
            MESH_STORE_AUTHENTICATION_UNAVAILABLE_CODE
        );
        assert!(!error.message().is_empty());
        assert!(!error.repair().is_empty());
    }

    #[test]
    fn constant_time_eq_matches_semantic_equality() {
        assert!(constant_time_eq(b"abcd", b"abcd"));
        assert!(!constant_time_eq(b"abcd", b"abce"));
        assert!(!constant_time_eq(b"abc", b"abcd"));
    }
}