ferrocrypt 0.3.0

Recipient-oriented file and directory encryption: passphrase (Argon2id) and X25519 public-key recipients, XChaCha20-Poly1305 STREAM payloads, HKDF-SHA3-256 / HMAC-SHA3-256 key derivation and authentication.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
//! Shared `.fcr` encrypted-file header build/parse path.
//!
//! The format defines **one** encrypted-file container with a typed recipient
//! list — there is no per-mode envelope or "symmetric vs hybrid" type byte.
//! Every encrypt and decrypt path therefore shares the same header
//! arithmetic and MAC scope, and this module is the **single source of
//! truth** for it.
//!
//! Wire layout (`FORMAT.md` §3):
//!
//! ```text
//! [prefix(12)] [header_fixed(31)] [recipient_entries(N)] [ext_bytes] [header_mac(32)] [payload]
//! ```
//!
//! The header MAC covers `prefix || header_fixed || recipient_entries ||
//! ext_bytes` exactly. Keeping the encode and decode paths in one place
//! eliminates a class of "encrypt and decrypt cover different byte ranges"
//! bugs.
//!
//! ## What this module does NOT do
//!
//! - It does not authenticate the header. The MAC is computed/verified by
//!   `format::compute_header_mac` / `verify_header_mac`; this module
//!   *includes* the MAC tag in the on-disk byte stream and the parsed result,
//!   but the caller is responsible for verifying it after they've recovered a
//!   candidate `header_key` from a successful recipient unwrap. Per
//!   `FORMAT.md` §3.7, a candidate `file_key` is not final until the MAC
//!   verifies.
//! - It does not validate `ext_bytes` TLV structure. TLV validation runs
//!   *after* MAC verification (so the validator can trust authenticated
//!   bytes). Callers invoke `crypto::tlv::validate_tlv` on `ext_bytes` after
//!   `format::verify_header_mac` succeeds.
//! - Recipient-mixing policy and classification live in `recipient/policy.rs`.
//!   Recipient unwrapping lives in `recipient/native`, coordinated by
//!   `protocol.rs`.

use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use crate::archive;
use crate::crypto::keys::{HeaderKey, PayloadKey};
use crate::crypto::stream::{STREAM_NONCE_SIZE, payload_encryptor};
use crate::error::{CryptoError, FormatDefect};
use crate::format::{
    self, HEADER_FIXED_SIZE, HEADER_MAC_SIZE, HeaderFixed, Kind, PREFIX_SIZE, Prefix,
    check_recipient_count, read_exact_or_truncated,
};
use crate::fs::atomic;
use crate::fs::paths::{INCOMPLETE_SUFFIX, OUTPUT_LABEL, parent_or_cwd, reject_occupied};
use crate::recipient::{self, RecipientEntry};

/// Tempfile name prefix for the in-flight `.fcr` write. Combined with
/// [`INCOMPLETE_SUFFIX`] this yields a `.ferrocrypt-*.incomplete`
/// staging name in the destination directory; on success
/// [`atomic::finalize_file`] promotes it to the user-visible
/// output path.
const TEMP_FILE_PREFIX: &str = ".ferrocrypt-";

/// Resource caps for encrypted-file headers.
///
/// Used by header readers and [`crate::Encryptor::header_read_limits`] to
/// enforce the same limits before writing.
///
/// The defaults mirror `format::*_LOCAL_CAP_DEFAULT` and apply to every
/// reader path. Callers may raise individual caps for trusted input
/// (for example, files from a known origin that legitimately use more
/// recipient slots, larger recipient bodies, or a larger header than
/// the conservative defaults allow) by calling the `max_*` builder
/// methods. Each builder clamps at the structural maximum for that
/// field — the `.fcr` format cannot represent values above
/// [`HeaderReadLimits::HEADER_LEN_STRUCTURAL_MAX`],
/// [`HeaderReadLimits::RECIPIENT_COUNT_STRUCTURAL_MAX`], or
/// [`HeaderReadLimits::RECIPIENT_BODY_LEN_STRUCTURAL_MAX`], so callers
/// cannot accidentally request a cap higher than what the structural
/// parser would accept anyway.
///
/// Caps are enforced **before** any cryptographic operation runs. Per
/// `FORMAT.md` §1 and §3.2, malicious input must not be able to force
/// unbounded work, and exceeding a local cap surfaces as a distinct
/// `*CapExceeded` error rather than as a generic format defect.
///
/// The struct is `#[non_exhaustive]` so future releases can add further
/// caps without a breaking change.
///
/// This type remains `Copy`: its resource caps are numeric bounds, including
/// any caps added in future releases.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct HeaderReadLimits {
    /// Hard cap on `prefix.header_len`.
    pub(crate) max_header_len: u32,
    /// Hard cap on `header_fixed.recipient_count`.
    pub(crate) max_recipient_count: u16,
    /// Hard cap on each individual recipient entry's `body_len`. Applies
    /// to known and unknown entries alike, so an unknown-recipient slot
    /// cannot force excessive allocation in a reader that would skip it.
    pub(crate) max_recipient_body_len: u32,
    /// Hard cap on the aggregate header-MAC input a single file may
    /// demand: `supported_recipient_count * (prefix + header)` bytes.
    /// The three caps above bound one dimension each; this one bounds
    /// their product, which is what the reader actually hashes.
    pub(crate) max_header_mac_work_bytes: u64,
}

impl Default for HeaderReadLimits {
    fn default() -> Self {
        Self {
            max_header_len: Self::HEADER_LEN_DEFAULT,
            max_recipient_count: Self::RECIPIENT_COUNT_DEFAULT,
            max_recipient_body_len: Self::RECIPIENT_BODY_LEN_DEFAULT,
            max_header_mac_work_bytes: Self::HEADER_MAC_WORK_BYTES_DEFAULT,
        }
    }
}

impl HeaderReadLimits {
    /// Structural maximum for `prefix.header_len` (16 MiB,
    /// `FORMAT.md` §3.1). Builder methods clamp at this value.
    pub const HEADER_LEN_STRUCTURAL_MAX: u32 = format::HEADER_LEN_MAX;
    /// Structural maximum for `header_fixed.recipient_count` (4096,
    /// `FORMAT.md` §3.2). Builder methods clamp at this value.
    pub const RECIPIENT_COUNT_STRUCTURAL_MAX: u16 = format::RECIPIENT_COUNT_MAX;
    /// Structural maximum for each recipient entry's `body_len`
    /// (16 MiB, `FORMAT.md` §3.3). Builder methods clamp at this
    /// value.
    pub const RECIPIENT_BODY_LEN_STRUCTURAL_MAX: u32 = format::BODY_LEN_MAX;
    /// Structural maximum for aggregate header-MAC input (about
    /// 64 GiB): the largest recipient count times the largest
    /// `prefix || header`, so no `.fcr` file can demand more. Builder
    /// methods clamp at this value.
    pub const HEADER_MAC_WORK_BYTES_STRUCTURAL_MAX: u64 = format::HEADER_MAC_WORK_MAX;

    /// Default value used by [`HeaderReadLimits::default`] for
    /// `max_header_len`. Mirrored on the writer side so the default
    /// `Encryptor` never produces a header longer than the default
    /// reader will accept.
    pub const HEADER_LEN_DEFAULT: u32 = format::HEADER_LEN_LOCAL_CAP_DEFAULT;
    /// Default value used by [`HeaderReadLimits::default`] for
    /// `max_recipient_count`. Mirrored on the writer side via
    /// [`crate::Encryptor::header_read_limits`] so a default
    /// `Encryptor` rejects recipient lists above this cap before any
    /// X25519 ECDH runs.
    pub const RECIPIENT_COUNT_DEFAULT: u16 = format::RECIPIENT_COUNT_LOCAL_CAP_DEFAULT;
    /// Default value used by [`HeaderReadLimits::default`] for
    /// `max_recipient_body_len`. Applies symmetrically on encrypt
    /// (native entries sit well under this cap) and decrypt.
    pub const RECIPIENT_BODY_LEN_DEFAULT: u32 = format::BODY_LEN_LOCAL_CAP_DEFAULT;
    /// Default value used by [`HeaderReadLimits::default`] for
    /// `max_header_mac_work_bytes` (about 64 MiB): the most work
    /// [`Self::RECIPIENT_COUNT_DEFAULT`] and [`Self::HEADER_LEN_DEFAULT`]
    /// can demand together. It therefore rejects nothing the other
    /// defaults accept, and only applies once a caller raises one of
    /// them.
    pub const HEADER_MAC_WORK_BYTES_DEFAULT: u64 = format::HEADER_MAC_WORK_LOCAL_CAP_DEFAULT;

    /// Sets the maximum accepted `prefix.header_len`, clamped at
    /// [`Self::HEADER_LEN_STRUCTURAL_MAX`]. Files declaring a longer
    /// header reject with [`CryptoError::HeaderLenCapExceeded`] before
    /// any allocation.
    pub fn max_header_len(mut self, value: u32) -> Self {
        self.max_header_len = value.min(Self::HEADER_LEN_STRUCTURAL_MAX);
        self
    }

    /// Sets the maximum accepted recipient count, clamped at
    /// [`Self::RECIPIENT_COUNT_STRUCTURAL_MAX`]. Files declaring more
    /// entries reject with [`CryptoError::RecipientCountCapExceeded`].
    /// Past roughly 750 X25519 recipients, raising this cap alone is
    /// not enough:
    /// [`max_header_mac_work_bytes`](Self::max_header_mac_work_bytes)
    /// binds next, on the writer and the reader alike.
    pub fn max_recipient_count(mut self, value: u16) -> Self {
        self.max_recipient_count = value.min(Self::RECIPIENT_COUNT_STRUCTURAL_MAX);
        self
    }

    /// Sets the maximum accepted per-entry `body_len`, clamped at
    /// [`Self::RECIPIENT_BODY_LEN_STRUCTURAL_MAX`]. Applies to known and
    /// unknown recipient types alike. Entries with a larger body reject
    /// with [`CryptoError::RecipientBodyCapExceeded`].
    pub fn max_recipient_body_len(mut self, value: u32) -> Self {
        self.max_recipient_body_len = value.min(Self::RECIPIENT_BODY_LEN_STRUCTURAL_MAX);
        self
    }

    /// Sets the maximum accepted aggregate header-MAC input, clamped at
    /// [`Self::HEADER_MAC_WORK_BYTES_STRUCTURAL_MAX`]. Files needing
    /// more reject with [`CryptoError::HeaderMacWorkCapExceeded`].
    ///
    /// Every candidate recipient that unwraps a file key verifies the
    /// header MAC over the whole `prefix || header`, so a file's
    /// worst-case MAC input is the supported-recipient count multiplied by
    /// `prefix || header` length. Increasing either factor increases this
    /// product linearly when the other is fixed; increasing both can produce
    /// quadratic growth. This cap bounds the product independently of the
    /// individual count and length limits.
    pub fn max_header_mac_work_bytes(mut self, value: u64) -> Self {
        self.max_header_mac_work_bytes = value.min(Self::HEADER_MAC_WORK_BYTES_STRUCTURAL_MAX);
        self
    }

    /// Single source of truth for the `header_len` cap check. Used by
    /// the reader's `read_encrypted_header` against the header declared
    /// in the prefix and by writer-side preflight against the calculated
    /// header length.
    pub(crate) fn enforce_header_len(&self, header_len: u32) -> Result<(), CryptoError> {
        if header_len > self.max_header_len {
            return Err(CryptoError::HeaderLenCapExceeded {
                header_len,
                local_cap: self.max_header_len,
            });
        }
        Ok(())
    }

    /// Single source of truth for the `recipient_count` cap check.
    /// Called from the reader's `read_encrypted_header` (against the
    /// `header_fixed.recipient_count` declared on disk) AND from the
    /// writer's [`crate::Encryptor::write`] (against the in-memory
    /// recipient list size) so default-encrypt and default-decrypt
    /// stay in lockstep.
    pub(crate) fn enforce_recipient_count(&self, count: u16) -> Result<(), CryptoError> {
        if count > self.max_recipient_count {
            return Err(CryptoError::RecipientCountCapExceeded {
                count,
                local_cap: self.max_recipient_count,
            });
        }
        Ok(())
    }

    /// Single source of truth for the per-recipient `body_len` cap
    /// check. The reader applies this inside `RecipientEntry::parse_one`
    /// (to avoid a dependency cycle); writer-side preflight calls this
    /// method against the canonical native body lengths before any
    /// wrapping/KDF work runs.
    pub(crate) fn enforce_recipient_body_len(&self, body_len: u32) -> Result<(), CryptoError> {
        if body_len > self.max_recipient_body_len {
            return Err(CryptoError::RecipientBodyCapExceeded {
                body_len,
                local_cap: self.max_recipient_body_len,
            });
        }
        Ok(())
    }

    /// Single source of truth for the aggregate header-MAC work cap.
    /// `candidate_count` is the number of recipient entries the reader
    /// may have to try, and `header_len` is the header those entries sit
    /// in; the product with [`format::PREFIX_SIZE`] is the total input
    /// [`format::verify_header_mac`] can be handed for one file.
    ///
    /// The reader calls this right after recipient classification, so a
    /// file over the cap is refused before any private-key unlock, key
    /// agreement, KDF, or MAC work (`FORMAT.md` §3.7). The writer calls it
    /// against the entry list it is about to seal, so it never emits a file
    /// the same-configured reader would refuse.
    ///
    /// The arithmetic is `u64` and saturating: the operands come from a
    /// `u16`-bounded count and a `u32` length, so the true product
    /// always fits, and saturation could only report a larger total.
    pub(crate) fn enforce_header_mac_work(
        &self,
        candidate_count: usize,
        header_len: u32,
    ) -> Result<(), CryptoError> {
        let per_candidate = (format::PREFIX_SIZE as u64).saturating_add(header_len as u64);
        let work_bytes = (candidate_count as u64).saturating_mul(per_candidate);
        if work_bytes > self.max_header_mac_work_bytes {
            return Err(CryptoError::HeaderMacWorkCapExceeded {
                work_bytes,
                local_cap: self.max_header_mac_work_bytes,
            });
        }
        Ok(())
    }
}

// The reader enforces `max_recipient_body_len` inside
// `RecipientEntry::parse_one`: that module sits below `container` in the
// dependency graph and cannot import [`HeaderReadLimits`] without a cycle. The
// cap is therefore passed as a `u32`, and `recipient/entry.rs` constructs the
// typed [`CryptoError::RecipientBodyCapExceeded`] error. Writer-side preflight
// calls [`HeaderReadLimits::enforce_recipient_body_len`] directly against the
// canonical native body lengths before any wrapping or KDF work runs. The cap
// value still has a single source of truth
// ([`HeaderReadLimits::max_recipient_body_len`] +
// [`HeaderReadLimits::RECIPIENT_BODY_LEN_DEFAULT`]); only the reader-side check
// site lives in `recipient/entry.rs`.

/// A structurally parsed `.fcr` header. Authenticity has NOT been checked;
/// the caller must call [`format::verify_header_mac`] with a `header_key`
/// derived from a successfully unwrapped candidate `file_key` before
/// trusting `ext_bytes` or accepting the candidate.
///
/// The byte buffers ([`prefix_bytes`](Self::prefix_bytes),
/// [`header_bytes`](Self::header_bytes)) are kept verbatim because the MAC
/// is computed over the on-disk encoding, not over the parsed structs.
pub(crate) struct ParsedEncryptedHeader {
    /// Raw 12-byte prefix as read from disk (input to MAC).
    pub prefix_bytes: [u8; PREFIX_SIZE],
    /// Parsed `header_fixed` fields.
    pub fixed: HeaderFixed,
    /// Raw `header` region as read from disk (input to MAC). This is
    /// `header_fixed || recipient_entries || ext_bytes`, of length
    /// `prefix.header_len`.
    pub header_bytes: Vec<u8>,
    /// Parsed recipient entries, in declared order. Length matches
    /// `fixed.recipient_count`.
    pub recipient_entries: Vec<RecipientEntry>,
    /// Unverified extension TLV bytes covered by the header MAC. Caller must run
    /// `crypto::tlv::validate_tlv` on this after MAC verification.
    pub ext_bytes: Vec<u8>,
    /// On-disk header MAC tag. Caller must verify against
    /// `format::compute_header_mac(prefix_bytes, header_bytes, header_key)`.
    pub header_mac: [u8; HEADER_MAC_SIZE],
}

impl ParsedEncryptedHeader {
    /// Declared `header_len`: the length of the authenticated
    /// [`Self::header_bytes`] region. The reader caps `header_len` at
    /// [`HeaderReadLimits::HEADER_LEN_STRUCTURAL_MAX`] (16 MiB) before
    /// the region is read, so the conversion cannot saturate; the
    /// fallback fails closed by over-reporting rather than wrapping.
    pub(crate) fn header_len(&self) -> u32 {
        u32::try_from(self.header_bytes.len()).unwrap_or(u32::MAX)
    }
}

/// A serialized `.fcr` header bundled with the streaming materials needed
/// to write the rest of the file.
///
/// Wire layout: `prefix_bytes || header_bytes || header_mac || <payload>`.
/// The caller writes these three byte regions in order, then streams the
/// encrypted payload after `header_mac` using `payload_key` + `stream_nonce`.
///
/// The payload key and nonce travel with the serialized header. Callers of
/// [`build_encrypted_header`] must supply matching derivation inputs.
pub(crate) struct BuiltEncryptedHeader {
    pub prefix_bytes: [u8; PREFIX_SIZE],
    pub header_bytes: Vec<u8>,
    pub header_mac: [u8; HEADER_MAC_SIZE],
    pub stream_nonce: [u8; STREAM_NONCE_SIZE],
    pub payload_key: PayloadKey,
}

/// Wraps a byte slice so `{:?}` renders as compact lowercase hex
/// instead of `[70, 67, 82, 0, ...]`. Local to the manual `Debug`
/// impl below; not allocating (writes byte-by-byte to the formatter).
struct HexBytes<'a>(&'a [u8]);

impl std::fmt::Debug for HexBytes<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for b in self.0 {
            write!(f, "{b:02x}")?;
        }
        Ok(())
    }
}

// Manual `Debug` redacts `payload_key`. `Zeroizing<[u8; 32]>` derives
// `Debug` transparently from `[u8; 32]`, which would print the raw key
// bytes via `{:?}` (used by `Result::unwrap_err`, panic messages, etc.).
// If a future field also holds secret material, redact it here too.
//
// The non-secret byte fields (`prefix_bytes`, `header_mac`,
// `stream_nonce`) render as lowercase hex via `HexBytes` — easier to
// read in panic / log lines than a raw decimal byte array.
// `header_bytes` shows only its length: it can be up to about 16 MiB
// (`HEADER_LEN_MAX`), so dumping its content in every debug print
// would be noisy and expensive.
impl std::fmt::Debug for BuiltEncryptedHeader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuiltEncryptedHeader")
            .field("prefix_bytes", &HexBytes(&self.prefix_bytes))
            .field("header_bytes_len", &self.header_bytes.len())
            .field("header_mac", &HexBytes(&self.header_mac))
            .field("stream_nonce", &HexBytes(&self.stream_nonce))
            .field("payload_key", &"<redacted>")
            .finish()
    }
}

// Manual `Debug` mirrors `BuiltEncryptedHeader`: `header_bytes` can be
// up to about 16 MiB (`HEADER_LEN_MAX`) and `ext_bytes` up to 64 KiB, so a
// derived implementation would dump megabytes of byte noise into any panic or
// log line that renders a parsed header. No secret material here; all fields
// are on-disk bytes, so this is log hygiene only.
impl std::fmt::Debug for ParsedEncryptedHeader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParsedEncryptedHeader")
            .field("prefix_bytes", &HexBytes(&self.prefix_bytes))
            .field("fixed", &self.fixed)
            .field("header_bytes_len", &self.header_bytes.len())
            .field("recipient_entry_count", &self.recipient_entries.len())
            .field("ext_bytes_len", &self.ext_bytes.len())
            .field("header_mac", &HexBytes(&self.header_mac))
            .finish()
    }
}

/// Reads, structurally validates, and bounds-checks a `.fcr` header from
/// `reader`. Stops after the MAC tag — the caller streams the payload
/// from the same reader afterwards.
///
/// Performs no cryptographic work. Each cap is checked before the allocation
/// it bounds; the full header buffer precedes the per-entry checks:
///
/// 1. read the 12-byte prefix, reporting a shorter input as
///    [`FormatDefect::Truncated`] before its magic is checked, then
///    [`Prefix::parse`] it (BadMagic / WrongKind / UnsupportedVersion /
///    MalformedHeader / OversizedHeader);
/// 2. enforce `prefix.header_len <= limits.max_header_len`;
/// 3. read the entire `header_len`-byte `header` region into one buffer;
/// 4. read the 32-byte header MAC tag into a fixed-size buffer. Steps 3
///    and 4 are the container's framing reads and complete before any
///    structural parse: per `FORMAT.md` §3.7 step 3, early EOF in either
///    surfaces as [`FormatDefect::Truncated`] rather than a downstream
///    structural defect;
/// 5. parse the leading 31 bytes as `header_fixed` → [`HeaderFixed::parse`]
///    (header_flags == 0, recipient_count in range, ext_len in range,
///    region lengths self-consistent). A `header_len` too small to hold
///    `header_fixed` rejects as `MalformedHeader` here, after the
///    framing reads;
/// 6. enforce `recipient_count <= limits.max_recipient_count`;
/// 7. parse the recipient list from `header[31..31+recipient_entries_len]`,
///    enforcing `body_len <= limits.max_recipient_body_len` per entry;
/// 8. capture the trailing `ext_bytes` slice (TLV validation deferred
///    to AFTER MAC verification — see `FORMAT.md` §3.7);
/// 9. return the parsed header. **MAC is not yet verified.**
pub(crate) fn read_encrypted_header<R: Read>(
    reader: &mut R,
    limits: HeaderReadLimits,
) -> Result<ParsedEncryptedHeader, CryptoError> {
    let (prefix_bytes, prefix) = format::read_prefix_from_reader(reader, Kind::Encrypted)?;

    limits.enforce_header_len(prefix.header_len)?;

    // Cap-bounded above. Cast is safe.
    let header_len = prefix.header_len as usize;
    let mut header_bytes = vec![0u8; header_len];
    read_exact_or_truncated(reader, &mut header_bytes)?;

    // Per `FORMAT.md` §3.7 step 3, the MAC-tag read is a framing read:
    // it must complete, or fail as `Truncated`, before structural parsing
    // starts. Otherwise a file that omits the MAC bytes could surface as
    // `MalformedHeader` instead of `Truncated`.
    let mut header_mac = [0u8; HEADER_MAC_SIZE];
    read_exact_or_truncated(reader, &mut header_mac)?;

    // Undersized-header rejection point (`FORMAT.md` §3.7): the prefix
    // stage accepts any `header_len` up to the structural maximum, so a
    // header too small to hold `header_fixed` is caught here, after the
    // framing reads above have completed.
    let fixed_bytes: &[u8; HEADER_FIXED_SIZE] = header_bytes
        .first_chunk()
        .ok_or(CryptoError::InvalidFormat(FormatDefect::MalformedHeader))?;
    let fixed = HeaderFixed::parse(fixed_bytes, prefix.header_len)?;

    limits.enforce_recipient_count(fixed.recipient_count)?;

    let entries_start = HEADER_FIXED_SIZE;
    let entries_end = entries_start
        .checked_add(fixed.recipient_entries_len as usize)
        .ok_or(CryptoError::InvalidFormat(FormatDefect::MalformedHeader))?;
    let ext_end = entries_end
        .checked_add(fixed.ext_len as usize)
        .ok_or(CryptoError::InvalidFormat(FormatDefect::MalformedHeader))?;
    if ext_end != header_len {
        return Err(CryptoError::InvalidFormat(FormatDefect::MalformedHeader));
    }

    let recipient_entries = recipient::parse_recipient_entries(
        &header_bytes[entries_start..entries_end],
        fixed.recipient_count,
        limits.max_recipient_body_len,
    )?;

    let ext_bytes = header_bytes[entries_end..ext_end].to_vec();

    Ok(ParsedEncryptedHeader {
        prefix_bytes,
        fixed,
        header_bytes,
        recipient_entries,
        ext_bytes,
        header_mac,
    })
}

/// Builds and authenticates a `.fcr` header from caller-supplied recipient
/// entries, ext_bytes, stream nonce, and the subkeys derived from the
/// per-file `file_key`.
///
/// The caller is responsible for:
/// - generating `stream_nonce` (typically `random_bytes::<STREAM_NONCE_SIZE>()?`);
/// - deriving `payload_key` and `header_key` from the freshly generated
///   `file_key` via `crypto::keys::derive_subkeys` (or equivalent);
/// - constructing `recipient_entries` via the per-recipient `wrap`
///   helpers (`recipient::argon2id::wrap`, `recipient::x25519::wrap`).
///
/// On success returns a [`BuiltEncryptedHeader`] holding the three byte
/// regions to write in order (prefix, header, MAC) plus `stream_nonce`
/// and `payload_key` for the payload streamer. Bundling these together
/// keeps the header and payload material together. Both subkeys must have been
/// derived from the same file key and the supplied nonce; this function cannot
/// verify their relationship.
///
/// The combined header length is checked against the 16 MiB structural
/// maximum before the recipient buffer is allocated. Oversized recipient
/// lists therefore fail before aggregate serialization.
pub(crate) fn build_encrypted_header(
    recipient_entries: &[RecipientEntry],
    ext_bytes: &[u8],
    stream_nonce: [u8; STREAM_NONCE_SIZE],
    payload_key: PayloadKey,
    header_key: &HeaderKey,
) -> Result<BuiltEncryptedHeader, CryptoError> {
    // Reject an invalid count before per-entry validation. Saturation is
    // safe here because `u16::MAX` always exceeds the structural cap.
    // `HeaderFixed` revalidates the assembled fields below.
    let recipient_count: u16 = recipient_entries.len().try_into().unwrap_or(u16::MAX);
    check_recipient_count(recipient_count)?;

    // Validate each entry and calculate the combined encoded length
    // before allocating the recipient buffer. Per-entry validation
    // errors are preserved, and the header limit is enforced first.
    let mut entries_len_u64: u64 = 0;
    for entry in recipient_entries {
        entries_len_u64 = entries_len_u64
            .checked_add(entry.checked_wire_len()? as u64)
            .ok_or(CryptoError::InvalidFormat(FormatDefect::MalformedHeader))?;
    }
    let header_len_u64 = (HEADER_FIXED_SIZE as u64)
        .checked_add(entries_len_u64)
        .and_then(|v| v.checked_add(ext_bytes.len() as u64))
        .ok_or(CryptoError::InvalidFormat(FormatDefect::MalformedHeader))?;
    // Compare against the structural max while the value is still u64,
    // so the rejection reports the real computed length; only an
    // unrepresentable above-`u32` total saturates the reported value.
    // `validate_structural` re-checks the narrowed value below.
    if header_len_u64 > u64::from(format::HEADER_LEN_MAX) {
        return Err(CryptoError::InvalidFormat(FormatDefect::OversizedHeader {
            header_len: u32::try_from(header_len_u64).unwrap_or(u32::MAX),
        }));
    }
    let header_len: u32 = header_len_u64
        .try_into()
        .map_err(|_| crate::error::internal_invariant!("header length narrowing failed"))?;

    // The aggregate cap above guarantees that the capacity and casts fit
    // `u32` and `usize` on every supported target.
    let mut entries_bytes = Vec::with_capacity(entries_len_u64 as usize);
    for entry in recipient_entries {
        entries_bytes.extend_from_slice(&entry.to_bytes_checked()?);
    }
    let recipient_entries_len: u32 = entries_bytes.len().try_into().unwrap_or(u32::MAX);
    let ext_len: u32 = ext_bytes.len().try_into().unwrap_or(u32::MAX);

    let fixed = HeaderFixed {
        header_flags: 0,
        recipient_count,
        recipient_entries_len,
        ext_len,
        stream_nonce,
    };
    // Single source of truth for `header_fixed` structural rules,
    // shared with the reader's `HeaderFixed::parse`. Catches:
    // `recipient_count == 0` / `> RECIPIENT_COUNT_MAX`, `ext_len >
    // EXT_LEN_MAX`, and section-length consistency in one call.
    fixed.validate_structural(header_len)?;

    let prefix_bytes = Prefix::build_encrypted(header_len)?;
    let fixed_bytes = fixed.to_bytes();

    let mut header_bytes = Vec::with_capacity(header_len as usize);
    header_bytes.extend_from_slice(&fixed_bytes);
    header_bytes.extend_from_slice(&entries_bytes);
    header_bytes.extend_from_slice(ext_bytes);
    debug_assert_eq!(header_bytes.len(), header_len as usize);

    let header_mac = format::compute_header_mac(&prefix_bytes, &header_bytes, header_key)?;

    Ok(BuiltEncryptedHeader {
        prefix_bytes,
        header_bytes,
        header_mac,
        stream_nonce,
        payload_key,
    })
}

/// Resolves the destination path for an encrypted file. If `output_file`
/// is supplied, it is used verbatim; otherwise the file is written under
/// `output_dir` as `<base_name>.<ENCRYPTED_EXTENSION>`.
pub(crate) fn resolve_encrypted_output_path(
    output_dir: &Path,
    output_file: Option<&Path>,
    base_name: &str,
) -> PathBuf {
    match output_file {
        Some(path) => path.to_path_buf(),
        None => output_dir.join(format!("{}.{}", base_name, format::ENCRYPTED_EXTENSION)),
    }
}

/// Streams a prepared FCA archive into an encrypted `.fcr` file at the
/// resolved output path, using the supplied [`BuiltEncryptedHeader`]
/// bundle.
///
/// On-disk byte order: `prefix(12) || header(31 + entries + ext) || mac(32)
/// || payload(STREAM)`. The header bytes, MAC, payload key, and stream
/// nonce are taken from `built`. The payload is
/// XChaCha20-Poly1305 STREAM-BE32 keyed by `built.payload_key` over the
/// archive captured in `prepared`. No plaintext intermediate files touch
/// disk: the FCA stream passes directly through
/// [`EncryptWriter`](crate::crypto::stream::EncryptWriter).
///
/// Accepting [`archive::PreparedArchive`] ensures that source metadata was
/// collected before this function creates the ciphertext staging file. An
/// output path inside the input tree therefore cannot add the staging file to
/// the archive.
///
/// The file is staged under a `.ferrocrypt-*.incomplete` name in the
/// destination's parent directory, then committed without overwriting via
/// [`atomic::finalize_file`] after [`atomic::sync_file_durable`] completes
/// the available file durability barrier. A pre-existing
/// output path rejects with `CryptoError::InvalidInput` before any
/// tempfile is created, so an unrelated file at the destination is
/// never touched.
pub(crate) fn write_encrypted_file(
    prepared: archive::PreparedArchive,
    output_dir: &Path,
    output_file: Option<&Path>,
    base_name: &str,
    built: &BuiltEncryptedHeader,
) -> Result<PathBuf, CryptoError> {
    write_encrypted_file_with_post_finalize(
        prepared,
        output_dir,
        output_file,
        base_name,
        built,
        |_| Ok(()),
        |_| Ok(()),
    )
}

/// Implementation seam for two intervals a test needs to reach: after the
/// staged file exists and before any ciphertext reaches it, and between
/// finalization and the path returned to the caller. Production supplies
/// no-ops; tests substitute the destination directory in the first and
/// replace the final entry in the second.
fn write_encrypted_file_with_post_finalize(
    prepared: archive::PreparedArchive,
    output_dir: &Path,
    output_file: Option<&Path>,
    base_name: &str,
    built: &BuiltEncryptedHeader,
    after_staging: impl FnOnce(&Path) -> std::io::Result<()>,
    after_finalize: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, CryptoError> {
    let output_path = resolve_encrypted_output_path(output_dir, output_file, base_name);
    reject_occupied(&output_path, OUTPUT_LABEL)?;

    // Linux and macOS anchor the commit to the destination directory before
    // the staged file exists. A handle opened at the commit instead would
    // denote whatever occupies the destination path by then: a local writer
    // who moves the staged file into a directory of their own and installs it
    // at that path would have the finished output committed there. The other
    // targets deliberately retain their existing path-based backend and must
    // not acquire an otherwise-unused readable directory handle.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    let committed_dir =
        atomic::OutputDir::open_for_commit(parent_or_cwd(&output_path)).map_err(CryptoError::Io)?;

    let mut builder = tempfile::Builder::new();
    builder.prefix(TEMP_FILE_PREFIX).suffix(INCOMPLETE_SUFFIX);
    // Pin the on-disk mode at owner-only read/write so the `.fcr`
    // file's permissions cannot drift if `tempfile`'s default changes
    // in a future release. AEAD-protected ciphertext does not need to
    // be unreadable on disk for confidentiality, but the conservative
    // default mirrors the `private.key` writer (`protocol.rs` keygen)
    // and matches what users expect for a freshly-written secret.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        builder.permissions(std::fs::Permissions::from_mode(0o600));
    }
    let mut tmp = builder.tempfile_in(parent_or_cwd(&output_path))?;
    // Before any ciphertext on Linux/macOS: a destination replaced between
    // the anchor and this create is refused now rather than after the whole
    // file has been written.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    committed_dir.confirm_staged(&tmp)?;
    after_staging(tmp.path())?;

    tmp.as_file_mut().write_all(&built.prefix_bytes)?;
    tmp.as_file_mut().write_all(&built.header_bytes)?;
    tmp.as_file_mut().write_all(&built.header_mac)?;

    let encrypt_writer = payload_encryptor(&built.payload_key, &built.stream_nonce, tmp);
    let encrypt_writer = prepared.write_to(encrypt_writer)?;
    let tmp = encrypt_writer.finish()?;
    atomic::sync_file_durable(tmp.as_file())?;

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    let finalized = atomic::finalize_file(tmp, &output_path, OUTPUT_LABEL, &committed_dir)
        .map_err(atomic::FinalizeFileError::into_crypto_error)?;
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    let finalized = atomic::finalize_file_path_based(tmp, &output_path, OUTPUT_LABEL)
        .map_err(atomic::FinalizeFileError::into_crypto_error)?;
    after_finalize(&output_path)?;
    // Keep the committed handle alive through the final namespace check so
    // the path returned to the caller still denotes the file just written.
    finalized.confirm_reported_path(&output_path)?;
    Ok(output_path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::keys::{DerivedSubkeys, FILE_KEY_SIZE, FileKey, derive_subkeys};
    use crate::recipient::entry::RECIPIENT_FLAG_CRITICAL;
    use crate::recipient::{argon2id, x25519};

    /// Every cap this type carries is measured from both sides by
    /// `tests/config_symmetry.rs`, which requires the writer and the
    /// reader to refuse at the same value.
    ///
    /// Rust has no reflection, so a new field does not join that suite
    /// by itself. This destructure stops compiling when one is added,
    /// which is the prompt to route it and then name it here.
    #[test]
    fn every_cap_is_routed_into_the_symmetry_suite() {
        let HeaderReadLimits {
            max_header_len: _,
            max_recipient_count: _,
            max_recipient_body_len: _,
            max_header_mac_work_bytes: _,
        } = HeaderReadLimits::default();
    }
    fn dummy_entry(type_name: &str, body_len: usize) -> RecipientEntry {
        RecipientEntry {
            type_name: type_name.to_string(),
            recipient_flags: 0,
            body: vec![0xAB; body_len],
        }
    }

    fn dummy_subkeys() -> DerivedSubkeys {
        // Stable inputs so the test is deterministic.
        let file_key = FileKey::from_bytes_for_tests([0x42u8; FILE_KEY_SIZE]);
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        derive_subkeys(&file_key, &stream_nonce).unwrap()
    }

    /// The writer holds its destination anchor from before the staged
    /// file exists, so a local writer who moves that staged file into a
    /// directory of their own and installs it at the destination path
    /// cannot have the finished `.fcr` committed there. Driven through
    /// the after-staging seam rather than a timing race.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn encrypted_writer_refuses_a_destination_swapped_in_after_staging() {
        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("input.txt");
        let output_dir = tmp.path().join("out");
        let replacement = tmp.path().join("replacement");
        let moved = tmp.path().join("out.moved");
        let output_path = output_dir.join("output.fcr");
        std::fs::write(&input, b"plaintext").unwrap();
        std::fs::create_dir(&output_dir).unwrap();
        std::fs::create_dir(&replacement).unwrap();

        let prepared = archive::prepare_archive(&input, archive::ArchiveLimits::default()).unwrap();
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let built = build_encrypted_header(
            std::slice::from_ref(&entry),
            b"",
            stream_nonce,
            payload_key,
            &header_key,
        )
        .unwrap();

        let err = write_encrypted_file_with_post_finalize(
            prepared,
            &output_dir,
            Some(&output_path),
            "unused",
            &built,
            |staged| {
                let name = staged.file_name().expect("the staged file has a name");
                std::fs::rename(staged, replacement.join(name))?;
                std::fs::rename(&output_dir, &moved)?;
                std::fs::rename(&replacement, &output_dir)
            },
            |_| Ok(()),
        )
        .expect_err("a staged file moved out of the anchored directory must refuse the commit");

        assert!(
            !output_path.exists(),
            "the substituted directory must receive no output: {err}"
        );
        assert!(
            !moved.join("output.fcr").exists(),
            "the original directory must receive none either"
        );
    }

    /// The writer must check the final path at its own return boundary, after
    /// the atomic helper has returned. Replacing that entry in this interval
    /// is reported, and neither the committed file nor the replacement is
    /// removed.
    #[cfg(unix)]
    #[test]
    fn encrypted_writer_rejects_a_path_replaced_after_finalization() {
        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("input.txt");
        let output_dir = tmp.path().join("out");
        let output_path = output_dir.join("output.fcr");
        let committed_path = output_dir.join("committed.fcr");
        std::fs::write(&input, b"plaintext").unwrap();
        std::fs::create_dir(&output_dir).unwrap();

        let prepared = archive::prepare_archive(&input, archive::ArchiveLimits::default()).unwrap();
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let built = build_encrypted_header(
            std::slice::from_ref(&entry),
            b"",
            stream_nonce,
            payload_key,
            &header_key,
        )
        .unwrap();

        let err = write_encrypted_file_with_post_finalize(
            prepared,
            &output_dir,
            Some(&output_path),
            "unused",
            &built,
            |_| Ok(()),
            |_| {
                std::fs::rename(&output_path, &committed_path)?;
                std::fs::write(&output_path, b"replacement")
            },
        )
        .expect_err("the writer must reject a replaced return path");

        assert!(
            matches!(
                err,
                CryptoError::InvalidInput(message)
                    if message.contains("reported path changed")
            ),
            "the path replacement must be reported explicitly"
        );
        let committed = std::fs::read(&committed_path).unwrap();
        assert!(
            committed.starts_with(&format::MAGIC),
            "the committed encrypted file must survive under its new name"
        );
        assert_eq!(std::fs::read(&output_path).unwrap(), b"replacement");
    }

    /// A final path check that cannot run fails the write with an error
    /// that keeps its kind and says the output is complete, because the
    /// file is already committed; the file stays. The output directory
    /// becomes untraversable after finalization, so the check's read by
    /// path is refused while the retained handle still works.
    #[cfg(unix)]
    #[test]
    fn encrypted_writer_reports_an_unconfirmed_path_as_complete() {
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("input.txt");
        let output_dir = tmp.path().join("out");
        let output_path = output_dir.join("output.fcr");
        std::fs::write(&input, b"plaintext").unwrap();
        std::fs::create_dir(&output_dir).unwrap();

        let prepared = archive::prepare_archive(&input, archive::ArchiveLimits::default()).unwrap();
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let built = build_encrypted_header(
            std::slice::from_ref(&entry),
            b"",
            stream_nonce,
            payload_key,
            &header_key,
        )
        .unwrap();

        let outcome = write_encrypted_file_with_post_finalize(
            prepared,
            &output_dir,
            Some(&output_path),
            "unused",
            &built,
            |_| Ok(()),
            |_| std::fs::set_permissions(&output_dir, std::fs::Permissions::from_mode(0o000)),
        );
        std::fs::set_permissions(&output_dir, std::fs::Permissions::from_mode(0o755)).unwrap();

        match outcome {
            // A privileged runner reads the path despite the mode.
            Ok(path) => assert_eq!(path, output_path),
            Err(CryptoError::Io(error)) => {
                assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
                let expected = format!(
                    "Output is complete, but its reported path could not be confirmed: {}: ",
                    crate::error::sanitize_path_for_display(&output_path)
                );
                assert!(
                    error.to_string().starts_with(&expected),
                    "expected a message starting with {expected:?}, got: {error}"
                );
            }
            Err(other) => panic!("the denial must be reported as I/O, got: {other}"),
        }
        assert!(
            std::fs::read(&output_path)
                .unwrap()
                .starts_with(&format::MAGIC),
            "the committed encrypted file must stay"
        );
    }

    /// Concatenates the three on-disk byte regions a writer emits in
    /// order: `prefix || header || mac`. Used by every round-trip /
    /// reader-side test below to feed the parser.
    fn on_disk_bytes(built: &BuiltEncryptedHeader) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(
            built.prefix_bytes.len() + built.header_bytes.len() + built.header_mac.len(),
        );
        bytes.extend_from_slice(&built.prefix_bytes);
        bytes.extend_from_slice(&built.header_bytes);
        bytes.extend_from_slice(&built.header_mac);
        bytes
    }

    #[test]
    fn build_then_read_round_trip_single_recipient() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);

        let built = build_encrypted_header(
            std::slice::from_ref(&entry),
            b"",
            stream_nonce,
            payload_key,
            &header_key,
        )
        .unwrap();

        let bytes = on_disk_bytes(&built);
        let parsed =
            read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()).unwrap();

        assert_eq!(parsed.prefix_bytes, built.prefix_bytes);
        assert_eq!(parsed.header_bytes, built.header_bytes);
        assert_eq!(parsed.header_mac, built.header_mac);
        assert_eq!(parsed.fixed.recipient_count, 1);
        assert_eq!(parsed.fixed.stream_nonce, stream_nonce);
        assert_eq!(parsed.fixed.ext_len, 0);
        assert_eq!(parsed.recipient_entries.len(), 1);
        assert_eq!(parsed.recipient_entries[0].type_name, argon2id::TYPE_NAME);
        assert_eq!(parsed.recipient_entries[0].body, entry.body);
        assert!(parsed.ext_bytes.is_empty());

        // MAC verifies under the same header_key (sanity check; this
        // is what `protocol::decrypt` does after recipient unwrap).
        format::verify_header_mac(
            &parsed.prefix_bytes,
            &parsed.header_bytes,
            &header_key,
            &parsed.header_mac,
        )
        .unwrap();
    }

    #[test]
    fn build_then_read_round_trip_two_recipients_with_ext() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x09u8; STREAM_NONCE_SIZE];
        let entries = vec![
            dummy_entry(x25519::TYPE_NAME, x25519::BODY_LENGTH),
            RecipientEntry {
                type_name: x25519::TYPE_NAME.to_string(),
                recipient_flags: RECIPIENT_FLAG_CRITICAL,
                body: vec![0xCDu8; x25519::BODY_LENGTH],
            },
        ];
        let ext = b"hello-ext";

        let built =
            build_encrypted_header(&entries, ext, stream_nonce, payload_key, &header_key).unwrap();

        let bytes = on_disk_bytes(&built);
        let parsed =
            read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()).unwrap();
        assert_eq!(parsed.fixed.recipient_count, 2);
        assert_eq!(parsed.recipient_entries.len(), 2);
        assert_eq!(parsed.recipient_entries[0].body, entries[0].body);
        assert_eq!(parsed.recipient_entries[1].body, entries[1].body);
        assert!(parsed.recipient_entries[1].is_critical());
        assert_eq!(parsed.ext_bytes, ext);

        format::verify_header_mac(
            &parsed.prefix_bytes,
            &parsed.header_bytes,
            &header_key,
            &parsed.header_mac,
        )
        .unwrap();
    }

    #[test]
    fn build_rejects_zero_recipients() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let err =
            build_encrypted_header(&[], b"", [0u8; STREAM_NONCE_SIZE], payload_key, &header_key)
                .unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::RecipientCountOutOfRange { count: 0 }) => {}
            other => panic!("expected RecipientCountOutOfRange(0), got {other:?}"),
        }
    }

    /// An entry list longer than the structural maximum is rejected
    /// before any entry is serialized, independent of the caller's
    /// preflight.
    #[test]
    fn build_rejects_recipient_count_above_structural_max() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let over = usize::from(HeaderReadLimits::RECIPIENT_COUNT_STRUCTURAL_MAX) + 1;
        let entries: Vec<_> = (0..over)
            .map(|_| dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH))
            .collect();
        let err = build_encrypted_header(
            &entries,
            b"",
            [0u8; STREAM_NONCE_SIZE],
            payload_key,
            &header_key,
        )
        .unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::RecipientCountOutOfRange { count }) => {
                assert_eq!(usize::from(count), over);
            }
            other => panic!("expected RecipientCountOutOfRange, got {other:?}"),
        }
    }

    /// A computed header length above the 16 MiB structural max is
    /// rejected with the real computed value, not a sentinel.
    #[test]
    fn build_rejects_oversized_header_with_computed_length() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let big_ext = vec![0u8; format::HEADER_LEN_MAX as usize];
        let err = build_encrypted_header(
            &[entry],
            &big_ext,
            [0u8; STREAM_NONCE_SIZE],
            payload_key,
            &header_key,
        )
        .unwrap_err();
        let expected_len = HEADER_FIXED_SIZE as u32
            + (crate::recipient::entry::ENTRY_HEADER_SIZE
                + argon2id::TYPE_NAME.len()
                + argon2id::BODY_LENGTH) as u32
            + format::HEADER_LEN_MAX;
        match err {
            CryptoError::InvalidFormat(FormatDefect::OversizedHeader { header_len }) => {
                assert_eq!(header_len, expected_len);
            }
            other => panic!("expected OversizedHeader with the computed length, got {other:?}"),
        }
    }

    /// Tests the header-length limit using recipient bytes rather than
    /// `ext_bytes`, including the reported calculated length.
    #[test]
    fn build_rejects_oversized_entries_with_computed_length() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let entry = dummy_entry(x25519::TYPE_NAME, format::BODY_LEN_MAX as usize);
        let err = build_encrypted_header(
            &[entry],
            b"",
            [0u8; STREAM_NONCE_SIZE],
            payload_key,
            &header_key,
        )
        .unwrap_err();
        let expected_len = HEADER_FIXED_SIZE as u32
            + (crate::recipient::entry::ENTRY_HEADER_SIZE + x25519::TYPE_NAME.len()) as u32
            + format::BODY_LEN_MAX;
        match err {
            CryptoError::InvalidFormat(FormatDefect::OversizedHeader { header_len }) => {
                assert_eq!(header_len, expected_len);
            }
            other => panic!("expected OversizedHeader with the computed length, got {other:?}"),
        }
    }

    /// `build_encrypted_header` propagates `to_bytes_checked`'s
    /// `type_name` grammar rejection.
    #[test]
    fn build_rejects_entry_with_invalid_type_name_grammar() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let bad_entry = RecipientEntry {
            type_name: "X25519".to_owned(),
            recipient_flags: 0,
            body: vec![0u8; crate::recipient::native::x25519::BODY_LENGTH],
        };
        let err = build_encrypted_header(
            &[bad_entry],
            b"",
            [0u8; STREAM_NONCE_SIZE],
            payload_key,
            &header_key,
        )
        .unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::MalformedTypeName) => {}
            other => panic!("expected MalformedTypeName, got {other:?}"),
        }
    }

    /// `build_encrypted_header` propagates `to_bytes_checked`'s
    /// reserved-flag-bit rejection.
    #[test]
    fn build_rejects_entry_with_reserved_recipient_flags() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let bad_entry = RecipientEntry {
            type_name: crate::recipient::native::x25519::TYPE_NAME.to_owned(),
            recipient_flags: 1u16 << 5,
            body: vec![0u8; crate::recipient::native::x25519::BODY_LENGTH],
        };
        let err = build_encrypted_header(
            &[bad_entry],
            b"",
            [0u8; STREAM_NONCE_SIZE],
            payload_key,
            &header_key,
        )
        .unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::RecipientFlagsReserved) => {}
            other => panic!("expected RecipientFlagsReserved, got {other:?}"),
        }
    }

    #[test]
    fn build_rejects_ext_above_structural_cap() {
        // `EXT_LEN_MAX = 65_536`. One byte over fires `ExtTooLarge`
        // (the precise diagnostic), not generic `MalformedHeader`.
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let oversize = vec![0u8; format::EXT_LEN_MAX as usize + 1];
        let err = build_encrypted_header(
            &[entry],
            &oversize,
            [0u8; STREAM_NONCE_SIZE],
            payload_key,
            &header_key,
        )
        .unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::ExtTooLarge { .. }) => {}
            other => panic!("expected ExtTooLarge, got {other:?}"),
        }
    }

    #[test]
    fn read_rejects_header_len_above_local_cap() {
        // Build a legitimate header with one large `ext_bytes` region so
        // header_len exceeds the small cap we'll set.
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let big_ext = vec![0u8; 4096];
        let built =
            build_encrypted_header(&[entry], &big_ext, stream_nonce, payload_key, &header_key)
                .unwrap();

        let bytes = on_disk_bytes(&built);
        let tight_limits = HeaderReadLimits {
            max_header_len: 256,
            ..HeaderReadLimits::default()
        };
        let err = read_encrypted_header(&mut bytes.as_slice(), tight_limits).unwrap_err();
        match err {
            CryptoError::HeaderLenCapExceeded { local_cap: 256, .. } => {}
            other => panic!("expected HeaderLenCapExceeded, got {other:?}"),
        }
    }

    #[test]
    fn read_reports_undersized_header_without_mac_bytes_as_truncated() {
        // `header_len = 0` and nothing after the prefix: the MAC framing
        // read fails first, so the file is reported as truncated.
        let bytes = Prefix::for_encrypted(0).to_bytes();
        match read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()) {
            Err(CryptoError::InvalidFormat(FormatDefect::Truncated)) => {}
            other => panic!("expected Truncated, got {other:?}"),
        }
    }

    #[test]
    fn read_rejects_undersized_header_with_full_mac_as_malformed() {
        // `header_len = 0` with all 32 MAC bytes present: framing is
        // complete, so a header too small to hold `header_fixed` is
        // the structural defect.
        let mut bytes = Prefix::for_encrypted(0).to_bytes().to_vec();
        bytes.extend_from_slice(&[0u8; HEADER_MAC_SIZE]);
        match read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedHeader)) => {}
            other => panic!("expected MalformedHeader, got {other:?}"),
        }
    }

    #[test]
    fn read_rejects_undersized_nonzero_header_with_full_framing_as_malformed() {
        let header_len = (HEADER_FIXED_SIZE as u32) - 1;
        let mut bytes = Prefix::for_encrypted(header_len).to_bytes().to_vec();
        bytes.extend_from_slice(&vec![0u8; header_len as usize]);
        bytes.extend_from_slice(&[0u8; HEADER_MAC_SIZE]);
        match read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedHeader)) => {}
            other => panic!("expected MalformedHeader, got {other:?}"),
        }
    }

    /// Direct boundary unit on [`HeaderReadLimits::enforce_header_len`]:
    /// the comparison must be `>`, not `>=`, so a `header_len` exactly
    /// at the cap is admissible and only `cap + 1` rejects.
    #[test]
    fn enforce_header_len_boundary() {
        let limits = HeaderReadLimits::default().max_header_len(256);
        limits.enforce_header_len(256).expect("at-cap must succeed");
        match limits.enforce_header_len(257) {
            Err(CryptoError::HeaderLenCapExceeded {
                header_len: 257,
                local_cap: 256,
            }) => {}
            other => panic!("expected HeaderLenCapExceeded(257, 256), got {other:?}"),
        }
    }

    /// Direct boundary unit on
    /// [`HeaderReadLimits::enforce_recipient_count`]: same `>` not
    /// `>=` semantics, plus confirm the typed error fields carry
    /// `count` and `local_cap` correctly.
    #[test]
    fn enforce_recipient_count_boundary() {
        let limits = HeaderReadLimits::default().max_recipient_count(2);
        limits
            .enforce_recipient_count(2)
            .expect("at-cap must succeed");
        match limits.enforce_recipient_count(3) {
            Err(CryptoError::RecipientCountCapExceeded {
                count: 3,
                local_cap: 2,
            }) => {}
            other => panic!("expected RecipientCountCapExceeded(3, 2), got {other:?}"),
        }
    }

    /// Builder methods preserve normal in-range values and produce a
    /// struct equal to the chained construction. Pins the field-by-field
    /// effect of each setter.
    #[test]
    fn header_read_limits_builder_round_trips_normal_values() {
        let limits = HeaderReadLimits::default()
            .max_header_len(2 * 1024 * 1024)
            .max_recipient_count(128)
            .max_recipient_body_len(16 * 1024)
            .max_header_mac_work_bytes(1 << 30);
        assert_eq!(limits.max_header_len, 2 * 1024 * 1024);
        assert_eq!(limits.max_recipient_count, 128);
        assert_eq!(limits.max_recipient_body_len, 16 * 1024);
        assert_eq!(limits.max_header_mac_work_bytes, 1 << 30);
    }

    /// Builder methods clamp at the structural maximum so a caller
    /// cannot raise a cap above what the structural parser would
    /// accept. Locks in the security guarantee that the public API
    /// cannot be used to bypass the structural ceilings declared in
    /// `FORMAT.md` §3.1 / §3.2 / §3.3.
    #[test]
    fn header_read_limits_builder_clamps_at_structural_max() {
        let clamped = HeaderReadLimits::default()
            .max_header_len(u32::MAX)
            .max_recipient_count(u16::MAX)
            .max_recipient_body_len(u32::MAX)
            .max_header_mac_work_bytes(u64::MAX);
        assert_eq!(
            clamped.max_header_len,
            HeaderReadLimits::HEADER_LEN_STRUCTURAL_MAX
        );
        assert_eq!(
            clamped.max_recipient_count,
            HeaderReadLimits::RECIPIENT_COUNT_STRUCTURAL_MAX
        );
        assert_eq!(
            clamped.max_recipient_body_len,
            HeaderReadLimits::RECIPIENT_BODY_LEN_STRUCTURAL_MAX
        );
        assert_eq!(
            clamped.max_header_mac_work_bytes,
            HeaderReadLimits::HEADER_MAC_WORK_BYTES_STRUCTURAL_MAX
        );
    }

    /// The aggregate cap bounds the product of the other two
    /// dimensions, so the worst case they already permit together must
    /// still pass. Otherwise adding the cap would refuse files the
    /// previous defaults accepted.
    ///
    /// Driven through [`HeaderReadLimits::enforce_header_mac_work`]
    /// rather than by re-deriving the constant, so the check compares
    /// two independently written expressions of the same rule: if the
    /// enforcement formula and
    /// [`format::HEADER_MAC_WORK_LOCAL_CAP_DEFAULT`] ever disagree —
    /// one starts counting the MAC tag, say — this fails.
    #[test]
    fn default_header_mac_work_cap_covers_every_default_cap_file() {
        HeaderReadLimits::default()
            .enforce_header_mac_work(
                HeaderReadLimits::RECIPIENT_COUNT_DEFAULT as usize,
                HeaderReadLimits::HEADER_LEN_DEFAULT,
            )
            .expect(
                "the default work budget must admit the worst case the recipient-count \
                 and header-length defaults already allow",
            );
    }

    /// The cap admits a file sitting exactly on the budget and refuses
    /// the next byte, reporting both the work the file demands and the
    /// configured limit.
    #[test]
    fn enforce_header_mac_work_boundary_is_inclusive() {
        let header_len = 1_000u32;
        let per_candidate = PREFIX_SIZE as u64 + header_len as u64;
        let limits = HeaderReadLimits::default().max_header_mac_work_bytes(per_candidate * 4);

        limits.enforce_header_mac_work(4, header_len).unwrap();
        match limits.enforce_header_mac_work(5, header_len) {
            Err(CryptoError::HeaderMacWorkCapExceeded {
                work_bytes,
                local_cap,
            }) => {
                assert_eq!(work_bytes, per_candidate * 5);
                assert_eq!(local_cap, per_candidate * 4);
            }
            other => panic!("expected HeaderMacWorkCapExceeded, got {other:?}"),
        }
    }

    /// A candidate count and header length far beyond anything the
    /// structural parser could produce must still be rejected rather
    /// than wrap around into a small product.
    #[test]
    fn enforce_header_mac_work_saturates_instead_of_overflowing() {
        let limits = HeaderReadLimits::default();
        match limits.enforce_header_mac_work(usize::MAX, u32::MAX) {
            Err(CryptoError::HeaderMacWorkCapExceeded { work_bytes, .. }) => {
                assert_eq!(work_bytes, u64::MAX);
            }
            other => panic!("expected HeaderMacWorkCapExceeded, got {other:?}"),
        }
    }

    /// The three default local caps
    /// ([`HeaderReadLimits::RECIPIENT_COUNT_DEFAULT`],
    /// [`HeaderReadLimits::RECIPIENT_BODY_LEN_DEFAULT`],
    /// [`HeaderReadLimits::HEADER_LEN_DEFAULT`]) plus the structural
    /// maxima [`EXT_LEN_MAX`] / [`HEADER_FIXED_SIZE`] /
    /// [`crate::recipient::entry::ENTRY_HEADER_SIZE`] /
    /// [`crate::recipient::name::TYPE_NAME_MAX_LEN`] must stay mutually
    /// consistent: the worst-case `header_len` a default-cap reader
    /// would still accept entry-by-entry (every recipient slot at the
    /// per-entry body cap, every type-name at the grammar ceiling,
    /// `ext_bytes` at its structural max) must fit inside the
    /// `HEADER_LEN_DEFAULT` envelope. Otherwise the three caps would
    /// silently refuse files the per-cap rules individually allow.
    ///
    /// Pins the inequality so a future cap bump (e.g. raising
    /// `RECIPIENT_BODY_LEN_DEFAULT` for a fat-body post-quantum
    /// recipient body) cannot silently break default round-trip
    /// without surfacing on CI.
    #[test]
    fn default_local_caps_are_mutually_consistent() {
        use crate::format::{EXT_LEN_MAX, HEADER_FIXED_SIZE};
        use crate::recipient::entry::ENTRY_HEADER_SIZE;
        use crate::recipient::name::TYPE_NAME_MAX_LEN;

        // Maximum on-wire bytes a single recipient entry can occupy
        // under the per-entry default cap with the type-name at its
        // grammar ceiling.
        let per_entry_max = ENTRY_HEADER_SIZE as u64
            + TYPE_NAME_MAX_LEN as u64
            + HeaderReadLimits::RECIPIENT_BODY_LEN_DEFAULT as u64;

        // Worst-case header a default-cap reader would individually
        // accept: every slot full, every type-name full, `ext_bytes`
        // at the structural max.
        let worst_case_header = (HeaderReadLimits::RECIPIENT_COUNT_DEFAULT as u64) * per_entry_max
            + EXT_LEN_MAX as u64
            + HEADER_FIXED_SIZE as u64;

        let header_len_default = HeaderReadLimits::HEADER_LEN_DEFAULT as u64;
        assert!(
            worst_case_header <= header_len_default,
            "Default local caps allow a worst-case header of {worst_case_header} bytes, \
             which exceeds HeaderReadLimits::HEADER_LEN_DEFAULT ({header_len_default}). \
             Either lower one of the per-cap defaults or raise \
             HeaderReadLimits::HEADER_LEN_DEFAULT to keep default round-trip viable."
        );
    }

    /// A file with a recipient count above the conservative default
    /// (`RECIPIENT_COUNT_LOCAL_CAP_DEFAULT = 64`) but below the
    /// structural max (`RECIPIENT_COUNT_MAX = 4096`) is rejected by
    /// default and accepted when the caller raises the cap via
    /// [`HeaderReadLimits::max_recipient_count`]. Pins that a caller
    /// can opt into reading a structurally valid file the conservative
    /// defaults would refuse.
    #[test]
    fn read_accepts_when_caller_raises_recipient_count_cap() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        // 80 entries: above the 64-entry default local cap, below the
        // 4096-entry structural max.
        let entries: Vec<_> = (0..80)
            .map(|_| dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH))
            .collect();
        let built =
            build_encrypted_header(&entries, b"", stream_nonce, payload_key, &header_key).unwrap();

        let bytes = on_disk_bytes(&built);

        // Default caps: rejected.
        match read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()) {
            Err(CryptoError::RecipientCountCapExceeded { count: 80, .. }) => {}
            other => panic!("expected RecipientCountCapExceeded with default cap, got {other:?}"),
        }

        // Caller raises the cap: accepted.
        let raised = HeaderReadLimits::default().max_recipient_count(128);
        let parsed = read_encrypted_header(&mut bytes.as_slice(), raised)
            .expect("raised recipient_count cap must accept the file");
        assert_eq!(parsed.recipient_entries.len(), 80);
    }

    /// A file with a per-entry `body_len` above the conservative
    /// default (`BODY_LEN_LOCAL_CAP_DEFAULT = 8 KiB`) but below the
    /// structural max (`BODY_LEN_MAX = 16 MiB`) is rejected by default
    /// and accepted when the caller raises the cap via
    /// [`HeaderReadLimits::max_recipient_body_len`]. Companion to
    /// [`read_accepts_when_caller_raises_recipient_count_cap`].
    #[test]
    fn read_accepts_when_caller_raises_body_len_cap() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        // 10 KiB body: above the 8 KiB default cap, below the 16 MiB
        // structural max.
        let oversize_body_len: usize = 10 * 1024;
        let entry = dummy_entry(argon2id::TYPE_NAME, oversize_body_len);
        let built =
            build_encrypted_header(&[entry], b"", stream_nonce, payload_key, &header_key).unwrap();

        let bytes = on_disk_bytes(&built);

        // Default caps: rejected.
        match read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()) {
            Err(CryptoError::RecipientBodyCapExceeded { body_len, .. })
                if body_len as usize == oversize_body_len => {}
            other => panic!(
                "expected RecipientBodyCapExceeded({oversize_body_len}, ..) with default cap, got {other:?}"
            ),
        }

        // Caller raises the cap: accepted.
        let raised = HeaderReadLimits::default().max_recipient_body_len(16 * 1024);
        let parsed = read_encrypted_header(&mut bytes.as_slice(), raised)
            .expect("raised body_len cap must accept the file");
        assert_eq!(parsed.recipient_entries.len(), 1);
        assert_eq!(parsed.recipient_entries[0].body.len(), oversize_body_len);
    }

    #[test]
    fn read_rejects_recipient_count_above_local_cap() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entries: Vec<_> = (0..3)
            .map(|_| dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH))
            .collect();
        let built =
            build_encrypted_header(&entries, b"", stream_nonce, payload_key, &header_key).unwrap();

        let bytes = on_disk_bytes(&built);
        let tight_limits = HeaderReadLimits {
            max_recipient_count: 2,
            ..HeaderReadLimits::default()
        };
        let err = read_encrypted_header(&mut bytes.as_slice(), tight_limits).unwrap_err();
        match err {
            CryptoError::RecipientCountCapExceeded {
                count: 3,
                local_cap: 2,
            } => {}
            other => panic!("expected RecipientCountCapExceeded(3, 2), got {other:?}"),
        }
    }

    #[test]
    fn read_rejects_recipient_body_above_local_cap() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        // Build an entry larger than the per-entry cap we'll set.
        let oversize_body_len = argon2id::BODY_LENGTH + 84;
        let local_body_cap: u32 = (argon2id::BODY_LENGTH + 12) as u32;
        let entry = dummy_entry(argon2id::TYPE_NAME, oversize_body_len);
        let built =
            build_encrypted_header(&[entry], b"", stream_nonce, payload_key, &header_key).unwrap();

        let bytes = on_disk_bytes(&built);
        let tight_limits = HeaderReadLimits {
            max_recipient_body_len: local_body_cap,
            ..HeaderReadLimits::default()
        };
        let err = read_encrypted_header(&mut bytes.as_slice(), tight_limits).unwrap_err();
        match err {
            CryptoError::RecipientBodyCapExceeded {
                body_len,
                local_cap,
            } if body_len as usize == oversize_body_len && local_cap == local_body_cap => {}
            other => panic!(
                "expected RecipientBodyCapExceeded({oversize_body_len}, {local_body_cap}), got {other:?}"
            ),
        }
    }

    /// A header whose length lands exactly on the structural maximum is
    /// built rather than refused. The rejection one byte above it is already
    /// covered; without this, a writer that placed the boundary one byte low
    /// would satisfy that rejection and still be unable to emit a header the
    /// reader accepts.
    #[test]
    fn build_accepts_a_header_at_the_structural_maximum() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        // One entry with a one-byte type name and no extension region, sized
        // so the fixed header plus the entry lands exactly on the maximum.
        let type_name = "a";
        let body_len = format::HEADER_LEN_MAX as usize
            - HEADER_FIXED_SIZE
            - crate::recipient::entry::ENTRY_HEADER_SIZE
            - type_name.len();
        let entry = RecipientEntry {
            type_name: type_name.to_string(),
            recipient_flags: 0,
            body: vec![0u8; body_len],
        };

        let built = build_encrypted_header(
            &[entry],
            b"",
            [0x07u8; STREAM_NONCE_SIZE],
            payload_key,
            &header_key,
        )
        .expect("a header at the structural maximum must build");
        assert_eq!(
            built.header_bytes.len(),
            format::HEADER_LEN_MAX as usize,
            "the built header must land exactly on the maximum"
        );
    }

    /// A file that carries a complete, well-formed `header` region but
    /// stops before the 32-byte MAC tag must reject as
    /// `InvalidFormat(Truncated)`. Pins the framing-vs-structural-parse
    /// ordering required by `FORMAT.md` §3.7 step 3: both the `header`
    /// and `header_mac` reads are framing reads and complete before any
    /// structural parse runs.
    #[test]
    fn read_rejects_missing_mac_tag_as_truncated() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let built =
            build_encrypted_header(&[entry], b"", stream_nonce, payload_key, &header_key).unwrap();

        // Prefix + header, but the 32-byte MAC tag is missing.
        let mut bytes = Vec::with_capacity(built.prefix_bytes.len() + built.header_bytes.len());
        bytes.extend_from_slice(&built.prefix_bytes);
        bytes.extend_from_slice(&built.header_bytes);

        match read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()) {
            Err(CryptoError::InvalidFormat(FormatDefect::Truncated)) => {}
            other => panic!("expected InvalidFormat(Truncated), got {other:?}"),
        }
    }

    /// If a file's `header` region is structurally malformed AND the
    /// MAC tag is missing, the framing-level `Truncated` diagnostic must
    /// fire before the structural `MalformedHeader` defect. Otherwise the
    /// reader would report the downstream parse error instead,
    /// contradicting `FORMAT.md` §3.7 step 3.
    #[test]
    fn read_returns_truncated_before_structural_error_when_mac_missing() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let built =
            build_encrypted_header(&[entry], b"", stream_nonce, payload_key, &header_key).unwrap();

        // Tamper the high byte of `header_flags` (offset 0 inside
        // `header_fixed`) so a non-zero value is read. If the structural
        // parse ever ran, this would surface as
        // `InvalidFormat(MalformedHeader)` via `check_header_flags`.
        let mut header_bytes = built.header_bytes.clone();
        header_bytes[0] = 0x01;

        let mut bytes = Vec::with_capacity(built.prefix_bytes.len() + header_bytes.len());
        bytes.extend_from_slice(&built.prefix_bytes);
        bytes.extend_from_slice(&header_bytes);
        // No MAC tag appended.

        match read_encrypted_header(&mut bytes.as_slice(), HeaderReadLimits::default()) {
            Err(CryptoError::InvalidFormat(FormatDefect::Truncated)) => {}
            other => panic!(
                "expected InvalidFormat(Truncated) (framing precedes structural parse), got {other:?}"
            ),
        }
    }

    #[test]
    fn mac_verify_rejects_tampered_header_byte() {
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = dummy_subkeys();
        let stream_nonce = [0x07u8; STREAM_NONCE_SIZE];
        let entry = dummy_entry(argon2id::TYPE_NAME, argon2id::BODY_LENGTH);
        let built =
            build_encrypted_header(&[entry], b"", stream_nonce, payload_key, &header_key).unwrap();

        // Flip a byte inside header_bytes; MAC must reject.
        let mut tampered = built.header_bytes.clone();
        tampered[20] ^= 0xFF;

        format::verify_header_mac(
            &built.prefix_bytes,
            &tampered,
            &header_key,
            &built.header_mac,
        )
        .unwrap_err();
    }
}