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
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
//! High-level FerroCrypt operation flow.
//!
//! This is the only module that may coordinate all of:
//!
//! 1. running the writer-side cap and KDF preflight,
//! 2. generating a file key,
//! 3. generating the stream nonce,
//! 4. calling recipient schemes to wrap the file key,
//! 5. building the authenticated header,
//! 6. calling archive encoding/decoding,
//! 7. constructing payload stream encryptors/decryptors,
//! 8. finalising staged output,
//! 9. emitting progress events.
//!
//! Algorithm-specific logic plugs in via the [`RecipientScheme`] /
//! [`DecryptionCredential`] traits — both `pub(crate)`. Recipient modules
//! produce / consume opaque [`RecipientBody`] bytes; only this module
//! constructs full headers or verifies the header MAC.
//!
//! ## Decryption order (`FORMAT.md` §3.7)
//!
//! 1. Read and validate the prefix; apply the header-length cap.
//! 2. Read the header and MAC, then parse the fixed fields and recipient
//!    entries under the count and body-length caps.
//! 3. Reject unknown critical recipients, native structural defects, and
//!    incompatible recipient combinations; apply the aggregate MAC-work cap.
//! 4. Try supported slots in order, applying KDF limits before derivation.
//!    For each successful unwrap, derive subkeys and verify the header MAC.
//!    Select the first MAC-verified key while continuing supported attempts.
//! 5. Validate authenticated header TLVs, then decrypt the payload and
//!    validate the archive manifest before staging extracted content.
//! 6. Verify the complete payload and archive before promotion, then perform
//!    post-commit checks before returning the output path.
//!
//! No refactor may move TLV interpretation, archive writes, or payload
//! plaintext release before the relevant authentication step.

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

use crate::archive::{ArchiveLimits, IncompleteOutputPolicy, prepare_archive, unarchive};
use crate::container::{
    HeaderReadLimits, ParsedEncryptedHeader, build_encrypted_header, read_encrypted_header,
    resolve_encrypted_output_path, write_encrypted_file,
};
use crate::crypto::keys::{DerivedSubkeys, FileKey, derive_subkeys, random_bytes};
use crate::crypto::stream::{STREAM_NONCE_SIZE, payload_decryptor};
use crate::crypto::tlv::validate_tlv;
use crate::error::{CryptoError, append_report};
use crate::format;
use crate::fs::paths::{
    KEY_FILE_LABEL, OUTPUT_LABEL, encryption_base_name, open_input_file, reject_occupied,
};
use crate::key::files::{PRIVATE_KEY_FILENAME, PUBLIC_KEY_FILENAME};
use crate::recipient::entry::{RecipientBody, RecipientEntry};
#[cfg(test)]
use crate::recipient::policy::MixingPolicy;
use crate::recipient::policy::{
    NativeMixingRule, NativeRecipientType, classify_recipient_mode, count_supported_recipients,
};
use crate::{ProgressEvent, UnauthenticatedRecipientMode};

/// Encrypt-side scheme: turn a [`FileKey`] into a recipient body of
/// scheme-specific bytes.
///
/// `TYPE_NAME` and `MIXING_RULE` are associated constants so the
/// multi-recipient `encrypt` orchestrator can enforce the mixing rule
/// before any KDF runs. Implementations must not build full
/// [`RecipientEntry`] framing or compute the header MAC — those
/// concerns live in this module.
///
/// `on_event` lets schemes whose wrap step is expensive (today only
/// `argon2id`) emit [`ProgressEvent::DerivingPassphraseWrapKey`] at the
/// actual KDF call site. Schemes whose wrap is cheap (X25519: one
/// scalar mult + one HKDF, sub-millisecond) must ignore the parameter
/// — emitting from them would lie about a long pause that never
/// happens.
pub(crate) trait RecipientScheme {
    const TYPE_NAME: &'static str;
    const MIXING_RULE: NativeMixingRule;

    /// Writer-side preflight for scheme-carried parameters, run by
    /// [`encrypt`] on every recipient before any filesystem, archive,
    /// or key work. `argon2id` validates its caller-supplied
    /// [`crate::KdfParams`] against shared structural bounds and resource
    /// policy, plus the writer-only memory floor;
    /// `x25519` carries no such parameters and accepts. Required
    /// rather than defaulted so a future scheme must decide
    /// explicitly.
    fn validate_for_write(&self) -> Result<(), CryptoError>;

    fn wrap_file_key(
        &self,
        file_key: &FileKey,
        on_event: &dyn Fn(&ProgressEvent),
    ) -> Result<RecipientBody, CryptoError>;
}

/// Decrypt-side scheme: try to unwrap a candidate [`FileKey`] from a
/// recipient body whose `type_name` already matched
/// `DecryptionCredential::TYPE_NAME` — the orchestrator pre-filters slots
/// before calling this.
///
/// Return shape:
///
/// - `Ok(Some(file_key))` — AEAD authentication succeeded; the caller
///   now must verify the header MAC under the derived `header_key`
///   before accepting the candidate (`FORMAT.md` §3.7 step 8).
/// - `Ok(None)` — AEAD authentication failed on a structurally-valid
///   body. Caller skips this slot and tries the next supported one.
///   This is the ONLY meaning of `Ok(None)`; hard failures (KDF cap
///   exceeded, malformed embedded KDF params, structural defects in
///   the body shape) are `Err(CryptoError::*)`.
///
/// `on_event` lets schemes whose unwrap step is expensive (today only
/// `argon2id`) emit [`ProgressEvent::DerivingPassphraseWrapKey`] at the
/// actual KDF call site. Schemes whose unwrap is cheap (X25519: one
/// scalar mult + one HKDF, sub-millisecond) must ignore the parameter.
pub(crate) trait DecryptionCredential {
    const TYPE_NAME: &'static str;
    /// File mode this credential scheme can decrypt. Used by the
    /// orchestrator to surface a typed
    /// [`CryptoError::DecryptorModeMismatch`] when a caller drives
    /// `decrypt` with the wrong credential for the file's recipient list.
    const EXPECTED_MODE: UnauthenticatedRecipientMode;

    fn unwrap_file_key(
        &self,
        body: &[u8],
        on_event: &dyn Fn(&ProgressEvent),
    ) -> Result<Option<FileKey>, CryptoError>;
}

// ─── Encrypt ───────────────────────────────────────────────────────────────

/// The extension region current writers emit: none. The preflight
/// receives this region and [`encrypt`] hands the same one to
/// [`build_encrypted_header`], so the header length the caps are
/// checked against and the bytes actually sealed cannot drift apart.
pub(crate) const WRITE_EXT_BYTES: &[u8] = b"";

/// Encrypts `input_path` under one or more recipients of a single
/// scheme. Wire format is the `.fcr` container with `recipients.len()`
/// entries whose type matches `R::TYPE_NAME`. Every entry seals the same
/// per-file `file_key` for its respective recipient.
///
/// Defense-in-depth checks (run by this function regardless of caller):
///
/// - `recipients` must be non-empty (the public API enforces this at
///   construction time; the orchestrator double-checks).
/// - If `R::MIXING_RULE.requires_single_entry()` then `recipients.len()`
///   must be exactly 1. The public API can only reach this code with a
///   single passphrase, but the assertion stops a future caller bypass
///   from emitting an `argon2id` file with two bodies (`FORMAT.md` §4.1
///   forbids it).
///
/// # Writer/reader lockstep
///
/// The emitted header shape is checked against `header_read_limits`
/// through [`preflight_header_write_limits`] — the same
/// [`HeaderReadLimits`] checks the reader applies — and every recipient
/// runs [`RecipientScheme::validate_for_write`], all before any
/// filesystem, archive, or key work. A `.fcr` this function writes is
/// therefore readable under the limits it was checked against; no
/// caller can skip the gates. [`crate::Encryptor::write`] runs the same
/// checks earlier at the public API boundary. Public keys have already
/// been resolved by their constructors. After header assembly, the header-length
/// and header-MAC-work caps run once more against the sealed bytes —
/// the backstop that keeps the preflight's computed length from
/// drifting from what is written. The fixed passphrase byte-length
/// bound is enforced inside the wrap path
/// (`crypto::kdf::check_passphrase_len`) before Argon2id runs.
pub(crate) fn encrypt<R: RecipientScheme>(
    recipients: Vec<R>,
    archive_limits: ArchiveLimits,
    header_read_limits: HeaderReadLimits,
    input_path: &Path,
    output_dir: &Path,
    output_file: Option<&Path>,
    on_event: &dyn Fn(&ProgressEvent),
) -> Result<PathBuf, CryptoError> {
    if recipients.is_empty() {
        return Err(CryptoError::EmptyRecipientList);
    }
    if R::MIXING_RULE.requires_single_entry() && recipients.len() > 1 {
        return Err(CryptoError::IncompatibleRecipients {
            type_name: R::TYPE_NAME.to_string(),
            policy: R::MIXING_RULE.diagnostic_policy(),
        });
    }

    // The same header-cap and KDF gates the reader applies, enforced
    // here so no in-crate caller can emit a file the same-configured
    // reader rejects. `api::Encryptor::write` runs them earlier too,
    // so misconfiguration fails before recipient key files are read.
    let native_type = NativeRecipientType::from_type_name(R::TYPE_NAME)
        .ok_or(crate::error::internal_invariant!("unknown native scheme"))?;
    preflight_header_write_limits(
        header_read_limits,
        recipients.len(),
        native_type,
        WRITE_EXT_BYTES,
    )?;
    for recipient in &recipients {
        recipient.validate_for_write()?;
    }

    // Resolve the destination and reject an existing entry before
    // expensive key work. The final no-clobber rename still prevents
    // replacement if the path becomes occupied after this check.
    // `reject_occupied` also detects dangling symlinks.
    let base_name = encryption_base_name(input_path)?;
    let output_path = resolve_encrypted_output_path(output_dir, output_file, &base_name);
    reject_occupied(&output_path, OUTPUT_LABEL)?;

    // Prepare the complete archive before cipher work or output
    // staging. Archive validation then fails before an expensive KDF,
    // and a staging file created inside the input tree cannot be
    // recorded as source content.
    let prepared = prepare_archive(input_path, archive_limits)?;

    // No early progress event here. Each recipient scheme emits its
    // own work-boundary event from inside `wrap_file_key`. For the
    // passphrase-only case, that's exactly one
    // `DerivingPassphraseWrapKey` immediately before Argon2id; for
    // pure X25519 wrapping (sub-millisecond), no event fires until
    // `Encrypting` below — which is what the orchestrator wants:
    // signal what the user can perceive, stay silent for what they
    // can't.

    // Generate per-file random material first so the rest of the build
    // is a pure function of (file_key, recipient input, stream_nonce,
    // input bytes). file_key is held in `Zeroizing` inside the typed
    // newtype, so an early return wipes it.
    let file_key = FileKey::generate()?;
    let stream_nonce = random_bytes::<STREAM_NONCE_SIZE>()?;
    let DerivedSubkeys {
        payload_key,
        header_key,
    } = derive_subkeys(&file_key, &stream_nonce)?;

    // Wrap the file_key for each recipient under the same scheme. After
    // the bodies are built, the raw file_key is no longer needed; drop
    // it immediately so the plaintext window in memory is minimal.
    let mut entries = Vec::with_capacity(recipients.len());
    for recipient in &recipients {
        let body = recipient.wrap_file_key(&file_key, on_event)?;
        entries.push(build_native_entry(R::TYPE_NAME, body)?);
    }
    drop(file_key);
    // Wrapping was the recipients' last use. Everything below runs on the
    // derived keys alone, so a long-lived secret a scheme carries — the
    // `argon2id` passphrase — is scrubbed here rather than surviving the
    // whole payload stream, whose length the input tree decides.
    drop(recipients);

    // Assemble prefix + header + MAC. `build_encrypted_header` owns the
    // single byte-arithmetic implementation; encrypt and decrypt share
    // its MAC scope.
    let built = build_encrypted_header(
        &entries,
        WRITE_EXT_BYTES,
        stream_nonce,
        payload_key,
        &header_key,
    )?;
    drop(header_key);

    // The preflight bounded a computed header length; a reader
    // measures the sealed bytes. Enforcing the same caps against the
    // assembled header is the backstop that keeps the two from
    // drifting apart.
    let header_len = u32::try_from(built.header_bytes.len()).unwrap_or(u32::MAX);
    header_read_limits.enforce_header_len(header_len)?;
    header_read_limits.enforce_header_mac_work(entries.len(), header_len)?;

    on_event(&ProgressEvent::Encrypting);

    write_encrypted_file(prepared, output_dir, output_file, &base_name, &built)
}

/// Builds a `RecipientEntry` from a scheme-produced body, validating
/// that the declared scheme is one of the recognised native types.
/// `RecipientEntry::native` enforces the canonical body length for the
/// type, so a scheme that returns the wrong number of bytes fails here.
fn build_native_entry(
    type_name: &'static str,
    body: RecipientBody,
) -> Result<RecipientEntry, CryptoError> {
    debug_assert_eq!(body.type_name, type_name);
    let ty = NativeRecipientType::from_type_name(type_name)
        .ok_or(crate::error::internal_invariant!("unknown native scheme"))?;
    RecipientEntry::native(ty, body.bytes)
}

/// Enforces the exact `.fcr` header shape the writer will emit against
/// the caller-supplied [`HeaderReadLimits`]. Mirrors the reader-side cap
/// checks in `container::read_encrypted_header`, but runs before any KDF,
/// ECDH, or output-file work. Called by [`encrypt`] on every write, and
/// earlier by [`crate::Encryptor::write`] at the public API boundary.
///
/// Takes a [`NativeRecipientType`] rather than a `(type_name, body_len)`
/// pair so the type-name / body-length pair is bound by the registry
/// (impossible for a caller to mix `argon2id`'s name with `x25519`'s
/// body length), and so adding a future native recipient updates the
/// preflight automatically through the registry's accessors. Takes the
/// extension region itself rather than a length for the same reason: a
/// writer that starts emitting `ext_bytes` must hand the region to the
/// preflight, so the header length the caps are checked against cannot
/// drift from the bytes [`build_encrypted_header`] assembles.
pub(crate) fn preflight_header_write_limits(
    limits: HeaderReadLimits,
    recipient_count: usize,
    native: NativeRecipientType,
    ext_bytes: &[u8],
) -> Result<(), CryptoError> {
    let type_name = native.type_name();
    let body_len = native.body_len();

    // `RECIPIENT_COUNT_MAX = 4096` fits u16; saturating cast keeps the
    // cap diagnostic honest in the theoretical case of an in-memory
    // list above u16::MAX, while still surfacing the cap-exceeded
    // variant before later structural checks.
    let count_u16: u16 = u16::try_from(recipient_count).unwrap_or(u16::MAX);
    limits.enforce_recipient_count(count_u16)?;

    // body_len is bounded by the canonical native `BODY_LENGTH` (≤ 116
    // today), so the saturating cast cannot fire. Defensive
    // fallback for a hypothetical future plugin recipient with a body
    // above `u32::MAX`: `enforce_recipient_body_len` rejects against
    // the per-entry cap (≤ `BODY_LEN_STRUCTURAL_MAX = 16 MiB`), so
    // `u32::MAX` always trips the cap.
    let body_len_u32: u32 = u32::try_from(body_len).unwrap_or(u32::MAX);
    limits.enforce_recipient_body_len(body_len_u32)?;

    // Compute the exact `header_len` the writer will emit
    // (`header_fixed + recipient_count * per_entry + ext_len`) and
    // check it against the cap. All checked arithmetic funnels into
    // one shared overflow error.
    let overflow_err = || CryptoError::HeaderLenCapExceeded {
        header_len: u32::MAX,
        local_cap: limits.max_header_len,
    };
    let per_entry = (crate::recipient::entry::ENTRY_HEADER_SIZE as u64)
        .checked_add(type_name.len() as u64)
        .and_then(|v| v.checked_add(body_len as u64))
        .ok_or_else(overflow_err)?;
    let total_entries = (recipient_count as u64)
        .checked_mul(per_entry)
        .ok_or_else(overflow_err)?;
    let ext_len = u64::try_from(ext_bytes.len()).unwrap_or(u64::MAX);
    let header_len_u64 = (format::HEADER_FIXED_SIZE as u64)
        .checked_add(total_entries)
        .and_then(|v| v.checked_add(ext_len))
        .ok_or_else(overflow_err)?;
    let header_len = u32::try_from(header_len_u64).unwrap_or(u32::MAX);
    limits.enforce_header_len(header_len)?;

    // Every entry names the same native type, so every one of them is a
    // candidate the reader may have to try. Counting all of them against
    // the budget is what keeps the sealed file inside the aggregate
    // header-MAC bound for any credential.
    limits.enforce_header_mac_work(recipient_count, header_len)?;

    Ok(())
}

// ─── Decrypt ───────────────────────────────────────────────────────────────

/// Runs the reader-side recipient preflight over a structurally parsed
/// header and returns the file's classified recipient mode.
///
/// Covers `FORMAT.md` §3.7 steps 6-9 via [`classify_recipient_mode`],
/// then the aggregate header-MAC bound that sits between steps 9 and
/// 10. Nothing here unlocks a key, derives one, or authenticates
/// anything.
///
/// Every reader entry point reaches this one function through
/// [`DecryptSession::from_file`] — decryption, [`crate::Decryptor::open`],
/// and [`crate::probe_recipient_mode_with_limits`] — so neither the probe
/// nor `open` can report a file as classifiable that the decrypt path would
/// refuse under the same limits, and a preflight rule added later cannot
/// reach one path but not the others.
pub(crate) fn classify_recipients_within_limits(
    parsed: &ParsedEncryptedHeader,
    limits: HeaderReadLimits,
) -> Result<UnauthenticatedRecipientMode, CryptoError> {
    let mode = classify_recipient_mode(&parsed.recipient_entries)?;

    // Bound what the slot loop can be made to hash. Every candidate
    // that unwraps re-authenticates the whole header, so the cost is
    // count times header size. Checked here, a file over the budget is
    // refused before any private-key unlock.
    limits.enforce_header_mac_work(
        count_supported_recipients(&parsed.recipient_entries),
        parsed.header_len(),
    )?;

    Ok(mode)
}

/// An encrypted input prepared for decryption. It contains the opened file,
/// its structurally parsed header, and its classified recipient mode.
///
/// [`DecryptSession::from_file`] performs the non-cryptographic steps from
/// `FORMAT.md` §3.7: bounded header reading, structural parsing, resource-limit
/// checks, and recipient classification. [`DecryptSession::open`] opens a path
/// and hands the file to it. The file remains open at the first
/// payload byte, so [`decrypt_session`] continues from the same file. This is
/// important when credential work occurs between validation and decryption,
/// such as unlocking a private key with Argon2id: replacing the path during
/// that work cannot change the input being decrypted.
pub(crate) struct DecryptSession {
    encrypted_file: fs::File,
    parsed: ParsedEncryptedHeader,
    mode: UnauthenticatedRecipientMode,
}

impl DecryptSession {
    /// Opens `input_path`, reads its header under `header_read_limits`, and
    /// classifies its recipients without performing key operations.
    pub(crate) fn open(
        input_path: &Path,
        header_read_limits: HeaderReadLimits,
    ) -> Result<Self, CryptoError> {
        // `open_input_file` rejects FIFOs, sockets, and device nodes
        // without waiting. Encryption rejects the same input types.
        Self::from_file(open_input_file(input_path)?, header_read_limits)
    }

    /// Reads the header of `encrypted_file` from its first byte, whatever
    /// the file's position, under `header_read_limits`, and classifies its
    /// recipients without performing key operations. The caller opens the file
    /// through `open_input_file`, which refuses FIFOs, sockets, and device nodes
    /// without blocking. Every reader entry point goes through this function:
    /// decryption, `Decryptor::open`, and `probe_recipient_mode_with_limits`.
    pub(crate) fn from_file(
        mut encrypted_file: fs::File,
        header_read_limits: HeaderReadLimits,
    ) -> Result<Self, CryptoError> {
        use std::io::{Seek, SeekFrom};

        encrypted_file
            .seek(SeekFrom::Start(0))
            .map_err(CryptoError::Io)?;

        // Steps 1–4: read and parse the header without cryptographic
        // work, enforcing local limits before allocation.
        let parsed = read_encrypted_header(&mut encrypted_file, header_read_limits)?;

        // Steps 6-9 plus the aggregate work bound: reject unsupported
        // critical recipients, native entries with invalid flags, body
        // lengths, or body contents, invalid recipient combinations, and a
        // recipient list that would cost too much to verify — all before
        // any private-key, key-agreement, or KDF work.
        let mode = classify_recipients_within_limits(&parsed, header_read_limits)?;

        Ok(Self {
            encrypted_file,
            parsed,
            mode,
        })
    }

    /// Returns the recipient mode derived from the unverified header. This is
    /// structural classification only and is not an authentication result.
    pub(crate) fn mode(&self) -> UnauthenticatedRecipientMode {
        self.mode
    }
}

/// Opens `input_path` as a [`DecryptSession`] and decrypts it. Callers that
/// need to perform credential work after structural validation can open the
/// session separately and pass it to [`decrypt_session`].
pub(crate) fn decrypt<I: DecryptionCredential>(
    credential: I,
    input_path: &Path,
    output_dir: &Path,
    archive_limits: ArchiveLimits,
    header_read_limits: HeaderReadLimits,
    incomplete_output_policy: IncompleteOutputPolicy,
    on_event: &dyn Fn(&ProgressEvent),
) -> Result<PathBuf, CryptoError> {
    let session = DecryptSession::open(input_path, header_read_limits)?;
    decrypt_session(
        credential,
        session,
        output_dir,
        archive_limits,
        incomplete_output_policy,
        on_event,
    )
}

/// Decrypts a prepared [`DecryptSession`] with the supplied credential.
///
/// Iterates every supported recipient slot in declared order before
/// emitting a final verdict. The slot loop is identical for the
/// single-candidate (passphrase) and multi-candidate (X25519) cases —
/// the passphrase path is just a slot loop of length 1. Visiting every
/// supported slot, rather than short-circuiting on the first MAC
/// match, reduces disclosure of the matching slot's position through timing
/// (`FORMAT.md` §3.7). This is not a constant-time operation: successful
/// unwraps incur additional subkey derivation and MAC work, and fatal errors
/// stop processing.
///
/// The credential is taken by value and dropped as soon as the slot loop
/// ends, so the long-lived secret it holds — a passphrase or a private
/// scalar — is scrubbed before the attacker-supplied payload is decrypted
/// and extracted. Only the derived payload key outlives that point.
pub(crate) fn decrypt_session<I: DecryptionCredential>(
    credential: I,
    session: DecryptSession,
    output_dir: &Path,
    archive_limits: ArchiveLimits,
    incomplete_output_policy: IncompleteOutputPolicy,
    on_event: &dyn Fn(&ProgressEvent),
) -> Result<PathBuf, CryptoError> {
    let DecryptSession {
        encrypted_file,
        parsed,
        mode,
    } = session;

    // A credential for the wrong recipient mode returns the dedicated
    // mismatch error. `PrivateKeyDecryptor::decrypt` checks before
    // unlocking the private key; this check also covers internal and
    // future callers.
    check_mode_matches_scheme::<I>(mode)?;

    // No early progress event here. Progress events fire at the actual
    // KDF call boundary inside each scheme's `unwrap_file_key`. For the
    // passphrase mode, that means the slot-loop Argon2id emission lives
    // inside `recipient::native::argon2id::unwrap`, which fires
    // `DerivingPassphraseWrapKey` only after the per-slot structural /
    // resource-cap checks have passed. For the recipient (X25519) mode,
    // the heaviest KDF (the `private.key` Argon2id unlock) already ran
    // *before* this function was entered — `PrivateKeyDecryptor::decrypt`
    // calls `open_x25519_private_key` first, and that call emits
    // `UnlockingPrivateKey` at its own work boundary inside
    // `key::private::open_private_key`.

    // 7-8. Iterate supported recipient slots. Per FORMAT.md §3.7 the
    //      candidate `file_key` is not final until the header MAC also
    //      verifies under the derived `header_key`.
    let stream_nonce = parsed.fixed.stream_nonce;
    let mut had_successful_unwrap = false;
    let mut selected_payload_key: Option<crate::crypto::keys::PayloadKey> = None;

    for entry in parsed.recipient_entries.iter() {
        if entry.type_name != I::TYPE_NAME {
            // Unknown non-critical entries: skipped. Critical unknowns
            // were rejected in step 5.
            continue;
        }
        // Native recipients do not use the critical bit — the
        // reader handles them natively. A native entry with the bit
        // set is structurally malformed and aborts the whole file.
        if entry.recipient_flags != 0 {
            return Err(CryptoError::InvalidFormat(
                crate::error::FormatDefect::MalformedRecipientEntry,
            ));
        }
        let file_key = match credential.unwrap_file_key(&entry.body, on_event)? {
            Some(k) => k,
            None => continue,
        };
        had_successful_unwrap = true;

        let DerivedSubkeys {
            payload_key,
            header_key,
        } = derive_subkeys(&file_key, &stream_nonce)?;
        drop(file_key);

        // Header MAC is the final acceptance gate. The first slot
        // whose MAC verifies wins; the loop does NOT short-circuit
        // there — every supported slot still attempts unwrap, so wall
        // time does not betray which MAC-verified slot matched
        // (FORMAT.md §3.7 SHOULD-level mitigation). Slots whose AEAD
        // unwrap fails (`Ok(None)`) skip the `derive_subkeys` and the
        // `verify_header_mac` below, so a residual delta of
        // ~one HKDF + one HMAC remains per AEAD-passing slot. The goal
        // §3.7 protects is position anonymity: the delta does NOT depend
        // on which slot matched, so wall time cannot reveal the
        // matching recipient's place in the list. It does scale with the
        // number of slots that pass AEAD under this private key. A file
        // may legitimately carry the same recipient more than once
        // (`Encryptor::with_public_keys` accepts duplicates), so that
        // count can exceed one; the header's cleartext `recipient_count`
        // already bounds it, and no §3.7 goal requires hiding it. Hiding
        // the count would need unconditional derive_subkeys +
        // verify_header_mac on every supported slot, which the format
        // does not mandate.
        if format::verify_header_mac(
            &parsed.prefix_bytes,
            &parsed.header_bytes,
            &header_key,
            &parsed.header_mac,
        )
        .is_ok()
            && selected_payload_key.is_none()
        {
            selected_payload_key = Some(payload_key);
        }
        drop(header_key);
    }

    // The slot loop was the credential's last use. Everything below runs on
    // attacker-supplied bytes and needs only the payload key, so the
    // passphrase or private scalar is scrubbed here rather than whenever the
    // caller happens to return.
    drop(credential);

    let Some(payload_key) = selected_payload_key else {
        // No slot MAC-verified. [`failure_for`]'s `(mode × had_unwrap)`
        // matrix picks the surfaced variant.
        return Err(failure_for(mode, I::TYPE_NAME, had_successful_unwrap));
    };

    // 9. TLV validation runs AFTER MAC verify, so the validator is
    //    operating on authenticated bytes.
    validate_tlv(&parsed.ext_bytes)?;

    // 10-12. STREAM payload decrypt + unarchive. Path / resource caps
    //        are enforced inside `unarchive` before any write.
    on_event(&ProgressEvent::Decrypting);
    let decrypt_reader = payload_decryptor(&payload_key, &stream_nonce, encrypted_file);
    unarchive(
        decrypt_reader,
        output_dir,
        archive_limits,
        incomplete_output_policy,
    )
}

/// Verifies that the classified file mode matches the credential scheme's
/// declared [`DecryptionCredential::EXPECTED_MODE`]. On mismatch, returns a
/// typed [`CryptoError::DecryptorModeMismatch`] carrying both modes so
/// the caller can pattern-match without comparing strings.
fn check_mode_matches_scheme<I: DecryptionCredential>(
    mode: UnauthenticatedRecipientMode,
) -> Result<(), CryptoError> {
    if mode == I::EXPECTED_MODE {
        return Ok(());
    }
    Err(CryptoError::DecryptorModeMismatch {
        expected: I::EXPECTED_MODE,
        found: mode,
    })
}

/// No slot MAC-verified. Indexed by `(mode × had_unwrap)`:
///
/// | mode       | had_unwrap | error                                       |
/// |------------|-----------:|---------------------------------------------|
/// | any        | false      | `RecipientUnwrapFailed { type_name }`       |
/// | Passphrase | true       | `HeaderTampered`                            |
/// | PublicKey  | true       | `HeaderMacFailedAfterUnwrap { type_name }`  |
///
/// `had_unwrap == false` means the file has at least one supported slot, but
/// none opened with this credential. That is the `FORMAT.md` §12
/// wrong-passphrase/key class (`RecipientUnwrapFailed`), not
/// `NoSupportedRecipient` (no supported recipient type in the file). The
/// rendered message keeps the credential-or-modified-file ambiguity for the
/// recipient type involved.
fn failure_for(
    mode: UnauthenticatedRecipientMode,
    type_name: &'static str,
    had_unwrap: bool,
) -> CryptoError {
    match (mode, had_unwrap) {
        // No slot opened, yet classification proved that the file has a
        // supported recipient. This is the wrong-credential-or-modified-body
        // class, not `NoSupportedRecipient`.
        (_, false) => CryptoError::RecipientUnwrapFailed {
            type_name: type_name.to_string(),
        },
        (UnauthenticatedRecipientMode::Passphrase, true) => CryptoError::HeaderTampered,
        (UnauthenticatedRecipientMode::PublicKey, true) => {
            CryptoError::HeaderMacFailedAfterUnwrap {
                type_name: type_name.to_string(),
            }
        }
    }
}

// ─── Key-pair generation ───────────────────────────────────────────────────

/// Generates an X25519 key pair and writes both files to `output_dir`.
/// Returns `(private_key_path, public_key_path, recipient_string,
/// fingerprint)`. The recipient string and the fingerprint are both
/// derived from the key material this call generated, never from a
/// re-read of `public.key`, so the two always describe one key.
///
/// - `private.key` is the passphrase-wrapped binary keyfile.
///   `key::private::seal_private_key` owns the byte layout (cleartext
///   header → AEAD-AAD-bound → wrapped secret). Permissions: `0o600`
///   on Unix.
/// - `public.key` is a UTF-8 text file containing the canonical
///   `fcr1…` Bech32 recipient string. Permissions: `0o644` on Unix
///   (public keys are not secret).
///
/// Both files are staged and synced before either receives its final name.
/// `private.key` is committed first, and the output directory is flushed after
/// each commit. This prevents process interruption from leaving `public.key`
/// without its matching `private.key`. Power-loss ordering also requires the
/// filesystem and storage device to support and honor directory flushing.
///
/// # Writer/reader lockstep
///
/// The caller-supplied [`crate::KdfParams`] are validated here against
/// shared structural bounds and [`crate::KdfLimit`] resource policy, plus
/// the writer-only memory floor, so a `private.key` sealed here meets the
/// same policy; no caller can skip the gate. `kdf_limit = None`
/// applies [`crate::KdfLimit::default`]. The fixed passphrase
/// byte-length bound is enforced inside the sealing path
/// (`crypto::kdf::check_passphrase_len`) before Argon2id runs.
pub(crate) fn generate_key_pair(
    passphrase: crate::passphrase::Passphrase,
    kdf_params: &crate::crypto::kdf::KdfParams,
    kdf_limit: Option<&crate::crypto::kdf::KdfLimit>,
    output_dir: &Path,
    on_event: &dyn Fn(&ProgressEvent),
) -> Result<(PathBuf, PathBuf, String, String), CryptoError> {
    generate_key_pair_with_seams(
        passphrase,
        kdf_params,
        kdf_limit,
        output_dir,
        on_event,
        |_, _| Ok(()),
        |_, _| Ok(()),
    )
}

/// Implementation seam for two intervals a test needs to reach: after
/// both key files are staged and before either commits, and after both
/// commit and before their paths are returned. Production supplies
/// no-ops; tests substitute the output directory in the first, and in the
/// second replace, move, or hide what the returned paths lead to. Each hook
/// receives the private and the public path of its interval, in that order.
fn generate_key_pair_with_seams(
    passphrase: crate::passphrase::Passphrase,
    kdf_params: &crate::crypto::kdf::KdfParams,
    kdf_limit: Option<&crate::crypto::kdf::KdfLimit>,
    output_dir: &Path,
    on_event: &dyn Fn(&ProgressEvent),
    before_commit: impl FnOnce(&Path, &Path) -> std::io::Result<()>,
    after_commit: impl FnOnce(&Path, &Path) -> std::io::Result<()>,
) -> Result<(PathBuf, PathBuf, String, String), CryptoError> {
    use std::io::Write as _;

    use crate::fs::atomic;
    use crate::key::private::seal_private_key;
    use crate::key::public::{encode_recipient_string, fingerprint_hex};
    use crate::recipient::native::x25519;

    // Writer caps mirror reader defaults via the same structural +
    // resource KDF validation the reader uses, so the sealed
    // `private.key` is unlocked by a default `PrivateKeyDecryptor`.
    // To go above default, the caller raises both sides explicitly.
    kdf_params.validate_for_write(kdf_limit)?;

    fs::create_dir_all(output_dir)?;

    // Check both final names before Argon2id so an existing entry fails
    // immediately. `reject_occupied` uses `symlink_metadata`, so it also
    // detects dangling symlinks. The final no-clobber renames still
    // prevent replacement if either name becomes occupied later.
    let private_key_path = output_dir.join(PRIVATE_KEY_FILENAME);
    let public_key_path = output_dir.join(PUBLIC_KEY_FILENAME);
    reject_occupied(&private_key_path, KEY_FILE_LABEL)?;
    reject_occupied(&public_key_path, KEY_FILE_LABEL)?;

    on_event(&ProgressEvent::GeneratingKeyPair);

    // Generate the X25519 keypair via the recipient module. The secret
    // material is returned in `Zeroizing` so it's wiped from memory
    // when this stack frame unwinds, regardless of whether the
    // subsequent seal/write succeeds.
    let (secret_material, public_material) = x25519::generate_keypair()?;

    // Hand off all `private.key` byte-layout, AEAD, and AAD scope to
    // `key/private.rs` — the single source of truth.
    let private_key_bytes = seal_private_key(
        secret_material.as_ref(),
        x25519::TYPE_NAME,
        &public_material,
        &[], // no ext_bytes for the X25519 case
        &passphrase,
        kdf_params,
    )?;
    drop(secret_material);
    // Sealing was the passphrase's last use. What follows is staging,
    // flushing, committing, and fingerprinting — filesystem work whose
    // duration the output device decides — so the credential is scrubbed
    // before any of it rather than at the end of the call.
    drop(passphrase);

    // Encode the canonical `fcr1…` recipient string via `key/public.rs`
    // (validates type-name grammar, computes the internal SHA3-256
    // checksum, emits BIP 173 lowercase Bech32).
    let recipient_string = encode_recipient_string(x25519::TYPE_NAME, &public_material)?;

    // Computed from the in-memory key material the recipient string encodes,
    // so it matches `PublicKey::from_key_file(..).fingerprint()` without
    // reading the file back, and before either commit, so it cannot fail once
    // a key file is on disk.
    let fingerprint = fingerprint_hex(x25519::TYPE_NAME, &public_material)?;

    // Retain the output directory before the first temporary exists. On Linux
    // and macOS both commits, their rollbacks, and their durability barriers
    // resolve through it, so a later path replacement cannot redirect them.
    // Other targets retain their established path-based commit and barrier;
    // the handle still anchors rollback (and the compatibility fallback on
    // other Unix targets), while Windows also prevents the directory itself
    // from being renamed because the handle denies delete sharing.
    let committed_dir = crate::fs::atomic::OutputDir::open(output_dir).map_err(CryptoError::Io)?;

    // Stage and sync both key files before either receives its final
    // name. Any failure before the commit step removes both temporary
    // files and publishes nothing. On Unix, each staged file is confirmed to
    // be an entry of the anchored directory before it receives content.
    let mut private_builder = tempfile::Builder::new();
    private_builder
        .prefix(".ferrocrypt-private_key-")
        .suffix(".tmp");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        private_builder.permissions(fs::Permissions::from_mode(0o600));
    }
    let mut private_tmp = private_builder.tempfile_in(output_dir)?;
    committed_dir.confirm_staged(&private_tmp)?;
    private_tmp.as_file_mut().write_all(&private_key_bytes)?;
    atomic::sync_file_durable(private_tmp.as_file())?;

    // `public.key` is the text form `fcr1…\n`. It is not secret, so
    // Unix permissions are 0o644.
    let mut public_builder = tempfile::Builder::new();
    public_builder
        .prefix(".ferrocrypt-public_key-")
        .suffix(".tmp");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        public_builder.permissions(fs::Permissions::from_mode(0o644));
    }
    let mut public_tmp = public_builder.tempfile_in(output_dir)?;
    committed_dir.confirm_staged(&public_tmp)?;
    public_tmp
        .as_file_mut()
        .write_all(recipient_string.as_bytes())?;
    public_tmp.as_file_mut().write_all(b"\n")?;
    atomic::sync_file_durable(public_tmp.as_file())?;
    before_commit(private_tmp.path(), public_tmp.path())?;

    let (private_finalized, public_finalized) = commit_key_pair_files(
        private_tmp,
        public_tmp,
        &private_key_path,
        &public_key_path,
        &committed_dir,
    )?;

    after_commit(&private_key_path, &public_key_path)?;

    // Retain both committed handles until the last possible moment and
    // confirm that the paths returned to the caller still denote those files.
    // Each error already says that its own file is complete. The other file
    // is named as complete only if its path was confirmed as well; otherwise
    // its own error is reported beside the first.
    let private_confirmed = private_finalized.confirm_reported_path(&private_key_path);
    let public_confirmed = public_finalized.confirm_reported_path(&public_key_path);
    match (private_confirmed, public_confirmed) {
        (Ok(()), Ok(())) => {}
        (Err(error), Ok(())) => {
            return Err(append_report(
                error,
                &also_complete_report(PUBLIC_KEY_FILENAME),
            ));
        }
        (Ok(()), Err(error)) => {
            return Err(append_report(
                error,
                &also_complete_report(PRIVATE_KEY_FILENAME),
            ));
        }
        (Err(private), Err(public)) => {
            return Err(append_report(private, &public.to_string()));
        }
    }

    Ok((
        private_key_path,
        public_key_path,
        recipient_string,
        fingerprint,
    ))
}

/// Commits two fully staged key files without overwriting existing files.
/// `private.key` is committed first, followed by a directory flush; then
/// `public.key` is committed and the directory is flushed again.
///
/// The order is required because `public.key` allows others to encrypt to the
/// key pair. It must not become durable unless the matching `private.key` is
/// already durable. The first directory flush establishes that order across
/// power loss. Where directory flushing is supported, the second flush ensures
/// that a successful return means both final names are durable. On filesystems
/// that do not support directory flushing, the private-first order still
/// protects against process interruption, but power-loss ordering depends on
/// the filesystem.
///
/// Failure handling preserves a safe result:
///
/// - If the `private.key` commit fails before publication, neither file is
///   published. A post-commit verification or staged-unlink failure preserves
///   the committed private key and reports that it is complete.
/// - If the first directory flush fails, `private.key` is removed best-effort.
///   The still-staged public file is removed through the same retained output
///   directory, and a result that does not prove it gone is reported.
/// - If the `public.key` commit fails before publication, `private.key` is
///   removed best-effort. A post-commit failure preserves both committed
///   final names rather than manufacturing a public-only pair, and reports
///   both files as complete.
/// - If the final directory flush fails, removal of `public.key` is attempted and
///   `private.key` is kept. Removing both without a working directory flush
///   could leave only `public.key` after power loss. The error says that the
///   private key was kept; it is safe to delete.
/// - A removal that cannot confirm the key file is gone — the entry was
///   replaced, its identity could not be read, or the file had other
///   names — is reported in the returned error.
///
/// Every removal above resolves inside the retained output-directory handle
/// rather than through the key-file path. On Linux and macOS both commits and
/// directory flushes resolve through that handle as well, so a renamed or
/// replaced output path cannot split publication, rollback, and durability
/// across directories. Other targets retain their path-based primary commit
/// and barrier; both commits still thread the handle into the other-Unix
/// compatibility fallback, and rollback remains anchored on every target.
fn commit_key_pair_files(
    private_tmp: tempfile::NamedTempFile,
    public_tmp: tempfile::NamedTempFile,
    private_key_path: &Path,
    public_key_path: &Path,
    committed_dir: &crate::fs::atomic::OutputDir,
) -> Result<
    (
        crate::fs::atomic::FinalizedFile,
        crate::fs::atomic::FinalizedFile,
    ),
    CryptoError,
> {
    commit_key_pair_files_with_barrier(
        private_tmp,
        public_tmp,
        private_key_path,
        public_key_path,
        committed_dir,
        flush_committed_dir,
    )
}

/// Production barrier for [`commit_key_pair_files_with_barrier`]: the
/// handle-relative flush where the platform has one, so the barrier
/// follows the directory the entries were committed to across a path
/// swap. Windows and other targets keep the path-based flush — a
/// handle-relative directory flush there needs a write-access reopen
/// that is not implemented — matching how the promotion itself is
/// split per platform.
fn flush_committed_dir(
    committed_dir: &crate::fs::atomic::OutputDir,
    output_dir: &Path,
) -> std::io::Result<()> {
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        let _ = output_dir;
        committed_dir.flush_durable()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        let _ = committed_dir;
        crate::fs::atomic::sync_dir_durable(output_dir)
    }
}

/// Implementation of [`commit_key_pair_files`] with an injectable
/// directory flush so tests can fail either flush point
/// deterministically. The flush receives the retained handle and the
/// ambient path; production ([`flush_committed_dir`]) picks the
/// handle-relative flush where the platform has one.
fn commit_key_pair_files_with_barrier(
    private_tmp: tempfile::NamedTempFile,
    public_tmp: tempfile::NamedTempFile,
    private_key_path: &Path,
    public_key_path: &Path,
    committed_dir: &crate::fs::atomic::OutputDir,
    sync_output_dir: impl Fn(&crate::fs::atomic::OutputDir, &Path) -> std::io::Result<()>,
) -> Result<
    (
        crate::fs::atomic::FinalizedFile,
        crate::fs::atomic::FinalizedFile,
    ),
    CryptoError,
> {
    commit_key_pair_files_with_barrier_and_public_finalizer(
        private_tmp,
        public_tmp,
        private_key_path,
        public_key_path,
        committed_dir,
        sync_output_dir,
        crate::fs::atomic::finalize_file,
    )
}

/// Testable implementation of [`commit_key_pair_files_with_barrier`]. The
/// public-key finalizer is injectable because its error can occur after the
/// final name exists, which changes whether the private key may be rolled back.
fn commit_key_pair_files_with_barrier_and_public_finalizer(
    private_tmp: tempfile::NamedTempFile,
    public_tmp: tempfile::NamedTempFile,
    private_key_path: &Path,
    public_key_path: &Path,
    committed_dir: &crate::fs::atomic::OutputDir,
    sync_output_dir: impl Fn(&crate::fs::atomic::OutputDir, &Path) -> std::io::Result<()>,
    finalize_public: impl FnOnce(
        tempfile::NamedTempFile,
        &Path,
        &str,
        &crate::fs::atomic::OutputDir,
    ) -> Result<
        crate::fs::atomic::FinalizedFile,
        crate::fs::atomic::FinalizeFileError,
    >,
) -> Result<
    (
        crate::fs::atomic::FinalizedFile,
        crate::fs::atomic::FinalizedFile,
    ),
    CryptoError,
> {
    use crate::fs::atomic::{self};
    use crate::fs::paths::parent_or_cwd;

    // Both final paths name entries in the same output directory: one
    // flush covers both, and both rollbacks resolve there.
    let output_dir = parent_or_cwd(private_key_path);

    let private_finalized =
        match atomic::finalize_file(private_tmp, private_key_path, KEY_FILE_LABEL, committed_dir) {
            Ok(finalized) => finalized,
            Err(error) => {
                let committed = error.committed();
                let error = error.into_crypto_error();
                if committed {
                    // `private.key` reached its final name, so an ambient-path
                    // destructor for the still-staged public file is no longer
                    // safe: the output directory may have moved, which would
                    // send that destructor into its replacement. Remove the
                    // sibling through the retained anchor and report any
                    // outcome that does not prove it gone.
                    let public_tmp_path = public_tmp.path().to_path_buf();
                    let cleanup = committed_dir.remove_staged_if_retained(public_tmp);
                    return Err(atomic::with_rollback_report(
                        error,
                        cleanup,
                        &public_tmp_path,
                    ));
                }
                // Before publication, keep `NamedTempFile`'s existing cleanup
                // behaviour. In particular, a staged file deliberately moved
                // with a replacement output directory is still removed at the
                // path its handle records.
                return Err(error);
            }
        };
    if let Err(e) = sync_output_dir(committed_dir, output_dir) {
        let rollback =
            committed_dir.remove_published_if_retained(private_key_path, private_finalized);
        let error = atomic::with_rollback_report(CryptoError::Io(e), rollback, private_key_path);
        let public_tmp_path = public_tmp.path().to_path_buf();
        let cleanup = committed_dir.remove_staged_if_retained(public_tmp);
        return Err(atomic::with_rollback_report(
            error,
            cleanup,
            &public_tmp_path,
        ));
    }
    let public_finalized =
        match finalize_public(public_tmp, public_key_path, KEY_FILE_LABEL, committed_dir) {
            Ok(finalized) => finalized,
            Err(error) => {
                // Roll private.key back only while public.key definitely did
                // not commit. A post-commit error can leave a complete public
                // key at its final name, and deleting the private half would
                // create the unsafe public-only state this ordering prevents.
                if error.committed() {
                    return Err(append_report(
                        error.into_crypto_error(),
                        &sibling_report(
                            &private_finalized,
                            private_key_path,
                            also_complete_report(PRIVATE_KEY_FILENAME),
                        ),
                    ));
                }
                let rollback =
                    committed_dir.remove_published_if_retained(private_key_path, private_finalized);
                return Err(atomic::with_rollback_report(
                    error.into_crypto_error(),
                    rollback,
                    private_key_path,
                ));
            }
        };
    if let Err(e) = sync_output_dir(committed_dir, output_dir) {
        let rollback =
            committed_dir.remove_published_if_retained(public_key_path, public_finalized);
        let kept = sibling_report(
            &private_finalized,
            private_key_path,
            kept_report(PRIVATE_KEY_FILENAME),
        );
        return Err(atomic::with_rollback_report(
            append_report(CryptoError::Io(e), &kept),
            rollback,
            public_key_path,
        ));
    }
    Ok((private_finalized, public_finalized))
}

/// The clause naming a key file committed before the one an error
/// describes. `confirmed` is used only while `path` still denotes the file
/// `finalized` retains; otherwise that confirmation's own error takes its
/// place, which says the file is complete without claiming that the entry now
/// at `path` is that file.
fn sibling_report(
    finalized: &crate::fs::atomic::FinalizedFile,
    path: &Path,
    confirmed: String,
) -> String {
    match finalized.confirm_reported_path(path) {
        Ok(()) => confirmed,
        Err(error) => error.to_string(),
    }
}

/// The clause appended to an error raised once both key files are
/// committed, naming the one the error does not already describe.
fn also_complete_report(file_name: &str) -> String {
    format!("{file_name} is also complete")
}

/// The clause appended when the directory flush after the `public.key`
/// commit fails: the rollback removes `public.key`, and the committed
/// `private.key` stays.
fn kept_report(file_name: &str) -> String {
    format!("{file_name} is complete and was kept")
}

#[cfg(test)]
mod tests {
    //! Forward-compat multi-recipient tests (FORMAT.md §3.4 / §3.5).
    //!
    //! These tests build headers with unknown or deliberately malformed
    //! recipients that the public encryption API cannot emit. They use
    //! `container::build_encrypted_header` and exercise
    //! the decrypt path against the resulting fixtures. They lock in:
    //! list iteration on `x25519`, skip unknown non-critical, reject
    //! unknown critical, reject argon2id mixing before any KDF runs,
    //! enforce the local body cap on unknown entries, and the
    //! attempt-all-slots timing-leak mitigation.
    //!
    //! Round-trip and basic tampering coverage lives in the
    //! integration test suite (`tests/integration_tests.rs`) plus the
    //! fixture-stability suite (`tests/fixture_stability.rs`).
    use super::*;
    use crate::container::build_encrypted_header;
    use crate::crypto::stream::payload_encryptor;
    use crate::error::FormatDefect;
    use crate::format;
    use crate::key::limits::KeyReadLimits;
    use crate::key::public::read_public_key;
    use crate::passphrase::Passphrase;
    use crate::recipient::entry::RECIPIENT_FLAG_CRITICAL;
    use crate::recipient::native::{argon2id, x25519};
    use crate::recipient::policy::NativeRecipientType;

    /// Builds a complete `.fcr` file whose authenticated plaintext payload is
    /// exactly `payload`, without adding an FCA archive. Tests use it to create
    /// authenticated files with invalid FCA structure that production writers
    /// cannot emit.
    fn build_fcr_with_raw_payload(
        entries: &[RecipientEntry],
        file_key: &FileKey,
        payload: &[u8],
        path: &Path,
    ) -> Result<(), CryptoError> {
        use std::io::Write;

        let stream_nonce = random_bytes::<STREAM_NONCE_SIZE>()?;
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = derive_subkeys(file_key, &stream_nonce)?;

        let built = build_encrypted_header(entries, b"", stream_nonce, payload_key, &header_key)?;

        let mut payload_buf: Vec<u8> = Vec::new();
        let mut writer =
            payload_encryptor(&built.payload_key, &built.stream_nonce, &mut payload_buf);
        writer.write_all(payload).map_err(CryptoError::Io)?;
        let _ = writer.finish()?;

        let mut buf: Vec<u8> = Vec::new();
        buf.extend_from_slice(&built.prefix_bytes);
        buf.extend_from_slice(&built.header_bytes);
        buf.extend_from_slice(&built.header_mac);
        buf.extend_from_slice(&payload_buf);
        fs::write(path, &buf)?;
        Ok(())
    }

    /// Builds a complete `.fcr` file with the supplied recipient entries and
    /// plaintext. The caller has already wrapped `file_key` for entries that
    /// must decrypt; unknown or intentionally invalid entries are preserved.
    fn build_multi_recipient_fcr(
        entries: &[RecipientEntry],
        file_key: &FileKey,
        plaintext: &[u8],
        path: &Path,
    ) -> Result<(), CryptoError> {
        // Construct an FCA archive containing one file named
        // `data.txt`, matching the production writer's output.
        let fca_bytes = {
            use crate::archive::ArchiveLimits;
            use crate::archive::format::{serialize_manifest, write_fca_header};
            use crate::archive::model::{ArchiveEntryKind, Manifest, make_entry};
            use std::ffi::OsString;

            let manifest = Manifest {
                entries: vec![make_entry(
                    "data.txt",
                    ArchiveEntryKind::File,
                    plaintext.len() as u64,
                    0o644,
                )],
                total_file_bytes: plaintext.len() as u64,
                root_name: OsString::from("data.txt"),
                root_is_file: true,
                root_mode: 0o644,
            };
            let manifest_bytes = serialize_manifest(&manifest, ArchiveLimits::default())?;

            let mut fca = write_fca_header(
                Vec::new(),
                1,
                0,
                manifest_bytes.len() as u32,
                plaintext.len() as u64,
            )?;
            fca.extend_from_slice(&manifest_bytes);
            fca.extend_from_slice(plaintext);
            fca
        };

        build_fcr_with_raw_payload(entries, file_key, &fca_bytes, path)
    }

    /// Generates an X25519 keypair, persists a `private.key` for it,
    /// and returns `(public_bytes, private_key_path, passphrase)`.
    fn keypair_fixture(
        keys_dir: &Path,
        label: &str,
        pass: &str,
    ) -> Result<([u8; 32], PathBuf, Passphrase), CryptoError> {
        let dir = keys_dir.join(label);
        fs::create_dir_all(&dir)?;
        // `generate_key_pair` consumes its passphrase, and `Passphrase` cannot
        // be duplicated, so the value handed back for the matching decrypt is
        // built from the same source text.
        let (private_key_path, public_key_path, _recipient, _fingerprint) = generate_key_pair(
            Passphrase::new(pass),
            &crate::crypto::kdf::KdfParams::test_fast_default(),
            None,
            &dir,
            &|_| {},
        )?;
        let pub_bytes = read_public_key(&public_key_path, KeyReadLimits::default())?.bytes;
        Ok((pub_bytes, private_key_path, Passphrase::new(pass)))
    }

    /// Decrypt helper: opens the X25519 `private.key`, builds an
    /// `X25519Credential`, and runs the orchestrator's slot loop directly
    /// (mirrors what `PrivateKeyDecryptor::decrypt` does in `api.rs` but
    /// preserves raw error variants for assertion).
    fn recipient_decrypt(
        fcr: &Path,
        dec_dir: &Path,
        private_key_path: &Path,
        pass: &Passphrase,
    ) -> Result<PathBuf, CryptoError> {
        let private_key_bytes = x25519::open_x25519_private_key(
            private_key_path,
            pass,
            None,
            KeyReadLimits::default(),
            &|_| {},
        )?;
        let credential = x25519::X25519Credential { private_key_bytes };
        decrypt(
            credential,
            fcr,
            dec_dir,
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            IncompleteOutputPolicy::default(),
            &|_| {},
        )
    }

    /// The credential — a passphrase or a private scalar — must be scrubbed
    /// once the recipient slot loop is over, before the attacker-supplied
    /// payload is decrypted and extracted. Only the derived payload key is
    /// needed from that point on.
    ///
    /// `ProgressEvent::Decrypting` is emitted at the start of the payload
    /// phase, so a credential whose `Drop` records itself proves the ordering:
    /// the flag must already be set when that event fires. The drop lives in
    /// the generic slot-loop code, so this covers the X25519 credential too.
    #[test]
    fn credential_is_dropped_before_the_payload_phase() -> Result<(), CryptoError> {
        use std::cell::Cell;
        use std::rc::Rc;

        /// Delegates to the real passphrase credential and records its drop.
        struct DropRecording<'a> {
            inner: argon2id::PassphraseCredential<'a>,
            dropped: Rc<Cell<bool>>,
        }

        impl Drop for DropRecording<'_> {
            fn drop(&mut self) {
                self.dropped.set(true);
            }
        }

        impl DecryptionCredential for DropRecording<'_> {
            const TYPE_NAME: &'static str = argon2id::TYPE_NAME;
            const EXPECTED_MODE: UnauthenticatedRecipientMode =
                UnauthenticatedRecipientMode::Passphrase;

            fn unwrap_file_key(
                &self,
                body: &[u8],
                on_event: &dyn Fn(&ProgressEvent),
            ) -> Result<Option<FileKey>, CryptoError> {
                self.inner.unwrap_file_key(body, on_event)
            }
        }

        let tmp = tempfile::TempDir::new()?;
        let input = tmp.path().join("data.txt");
        fs::write(&input, b"payload phase must not hold the credential")?;
        const DROP_ORDER_PASSPHRASE: &str = "drop-order-test-passphrase";
        let pass = Passphrase::new(DROP_ORDER_PASSPHRASE);
        let fcr = encrypt(
            vec![argon2id::PassphraseRecipient {
                passphrase: Passphrase::new(DROP_ORDER_PASSPHRASE),
                kdf_params: crate::crypto::kdf::KdfParams::test_fast_default(),
                kdf_limit: crate::KdfLimit::default(),
            }],
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            &input,
            tmp.path(),
            None,
            &|_| {},
        )?;

        let dropped = Rc::new(Cell::new(false));
        let dropped_at_payload_start = Rc::new(Cell::new(false));
        let credential = DropRecording {
            inner: argon2id::PassphraseCredential {
                passphrase: pass,
                kdf_limit: None,
            },
            dropped: Rc::clone(&dropped),
        };

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        let observer = {
            let dropped = Rc::clone(&dropped);
            let observed = Rc::clone(&dropped_at_payload_start);
            move |event: &ProgressEvent| {
                if matches!(event, ProgressEvent::Decrypting) {
                    observed.set(dropped.get());
                }
            }
        };
        decrypt(
            credential,
            &fcr,
            &dec_dir,
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            IncompleteOutputPolicy::default(),
            &observer,
        )?;

        assert!(
            dropped_at_payload_start.get(),
            "the credential must be scrubbed before the payload is decrypted"
        );
        Ok(())
    }

    /// Encrypt-side counterpart of
    /// [`credential_is_dropped_before_the_payload_phase`]: a recipient scheme
    /// that carries a long-lived secret — today only the `argon2id`
    /// passphrase — must be scrubbed once its body is wrapped, before the
    /// input tree's content is read and streamed. The caller sizes that
    /// content, so holding the credential across it makes the exposure window
    /// as long as the caller likes. The metadata pass that precedes wrapping
    /// still runs with the credential live: `prepare_archive` is ordered
    /// first on purpose, so an unusable tree is refused before the KDF.
    ///
    /// `ProgressEvent::Encrypting` marks the start of the payload phase, so a
    /// recipient whose `Drop` records itself proves the ordering: the flag must
    /// already be set when that event fires. The drop lives in the generic
    /// recipient-list code, so it covers every present and future scheme.
    #[test]
    fn recipients_are_dropped_before_the_payload_phase() -> Result<(), CryptoError> {
        use std::cell::Cell;
        use std::rc::Rc;

        /// Delegates to the real passphrase recipient and records its drop.
        struct DropRecording {
            inner: argon2id::PassphraseRecipient,
            dropped: Rc<Cell<bool>>,
        }

        impl Drop for DropRecording {
            fn drop(&mut self) {
                self.dropped.set(true);
            }
        }

        impl RecipientScheme for DropRecording {
            const TYPE_NAME: &'static str = argon2id::TYPE_NAME;
            const MIXING_RULE: NativeMixingRule =
                <argon2id::PassphraseRecipient as RecipientScheme>::MIXING_RULE;

            fn validate_for_write(&self) -> Result<(), CryptoError> {
                self.inner.validate_for_write()
            }

            fn wrap_file_key(
                &self,
                file_key: &FileKey,
                on_event: &dyn Fn(&ProgressEvent),
            ) -> Result<RecipientBody, CryptoError> {
                self.inner.wrap_file_key(file_key, on_event)
            }
        }

        let tmp = tempfile::TempDir::new()?;
        let input = tmp.path().join("data.txt");
        fs::write(&input, b"payload phase must not hold the credential")?;

        let dropped = Rc::new(Cell::new(false));
        let dropped_at_payload_start = Rc::new(Cell::new(false));
        let recipient = DropRecording {
            inner: argon2id::PassphraseRecipient {
                passphrase: Passphrase::new("encrypt-drop-order-test-passphrase"),
                kdf_params: crate::crypto::kdf::KdfParams::test_fast_default(),
                kdf_limit: crate::KdfLimit::default(),
            },
            dropped: Rc::clone(&dropped),
        };

        let observer = {
            let dropped = Rc::clone(&dropped);
            let observed = Rc::clone(&dropped_at_payload_start);
            move |event: &ProgressEvent| {
                if matches!(event, ProgressEvent::Encrypting) {
                    observed.set(dropped.get());
                }
            }
        };
        encrypt(
            vec![recipient],
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            &input,
            tmp.path(),
            None,
            &observer,
        )?;

        assert!(
            dropped_at_payload_start.get(),
            "the recipient must be scrubbed before the payload is encrypted"
        );
        Ok(())
    }

    /// Two `x25519` recipients in one file: the decrypt loop must
    /// iterate the list and accept whichever slot the caller's
    /// private key matches.
    #[test]
    fn multi_x25519_decrypts_via_either_recipient() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;
        let (pub_b, priv_b, pass_b) = keypair_fixture(&keys_dir, "bob", "bob-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let body_b = x25519::wrap(&file_key, &pub_b)?;
        let entries = [
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
            RecipientEntry::native(NativeRecipientType::X25519, body_b.to_vec())?,
        ];

        let payload = b"two-x25519 round trip";
        let fcr = tmp.path().join("multi.fcr");
        build_multi_recipient_fcr(&entries, &file_key, payload, &fcr)?;

        for (label, private_key, pass) in [("alice", &priv_a, &pass_a), ("bob", &priv_b, &pass_b)] {
            let dec_dir = tmp.path().join(format!("decrypted-{label}"));
            fs::create_dir_all(&dec_dir)?;
            recipient_decrypt(&fcr, &dec_dir, private_key, pass)?;
            let restored = fs::read(dec_dir.join("data.txt"))?;
            assert_eq!(
                restored, payload,
                "{label} should decrypt the same plaintext"
            );
        }
        Ok(())
    }

    /// Verifies end-to-end classification of incomplete FCA regions. Each
    /// `.fcr` file has a valid outer header and an authenticated payload, but
    /// its FCA plaintext ends inside the fixed header, extension region, or
    /// manifest. Decryption must return `MalformedArchive` with the matching
    /// region reason rather than `Io`.
    #[test]
    fn truncated_fca_payload_rejects_as_malformed_archive() -> Result<(), CryptoError> {
        use crate::archive::format::{FCA_MAGIC, FCA_VERSION, write_fca_header};
        use crate::archive::reasons::{
            ARCHIVE_EXT_REGION_TRUNCATED, FIXED_HEADER_TRUNCATED, MANIFEST_REGION_TRUNCATED,
        };

        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body = x25519::wrap(&file_key, &pub_a)?;
        let entries = [RecipientEntry::native(
            NativeRecipientType::X25519,
            body.to_vec(),
        )?];

        // Valid prefix through the flags field, followed by only three
        // bytes of `entry_count`.
        let short_header = {
            let mut fca = Vec::new();
            fca.extend_from_slice(FCA_MAGIC);
            fca.push(FCA_VERSION);
            fca.extend_from_slice(&0u16.to_be_bytes());
            fca.extend_from_slice(&[0u8; 3]);
            fca
        };
        // Valid header declaring an 8-byte `archive_ext` region, then
        // the payload ends three bytes in.
        let short_ext = {
            let mut fca = write_fca_header(Vec::new(), 1, 8, 50, 10)?;
            fca.extend_from_slice(&[0u8; 3]);
            fca
        };
        // Valid header declaring a 50-byte manifest, then the payload
        // ends twenty bytes in.
        let short_manifest = {
            let mut fca = write_fca_header(Vec::new(), 1, 0, 50, 10)?;
            fca.extend_from_slice(&[0u8; 20]);
            fca
        };

        let cases: [(&str, Vec<u8>, &str); 3] = [
            ("fixed-header", short_header, FIXED_HEADER_TRUNCATED),
            ("archive-ext", short_ext, ARCHIVE_EXT_REGION_TRUNCATED),
            ("manifest", short_manifest, MANIFEST_REGION_TRUNCATED),
        ];
        for (label, fca_payload, want_reason) in cases {
            let fcr = tmp.path().join(format!("{label}.fcr"));
            build_fcr_with_raw_payload(&entries, &file_key, &fca_payload, &fcr)?;

            let dec_dir = tmp.path().join(format!("decrypted-{label}"));
            fs::create_dir_all(&dec_dir)?;
            let err = recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a).unwrap_err();
            match err {
                CryptoError::MalformedArchive { reason } => {
                    assert_eq!(reason, want_reason, "wrong truncation reason for {label}");
                }
                other => panic!("{label}: expected MalformedArchive, got {other:?}"),
            }
        }
        Ok(())
    }

    /// FORMAT.md §3.7 step 8: a wrong-length `x25519` slot hiding
    /// behind a well-shaped slot must reject the whole file during the
    /// structural preflight, before any slot unwrap can run — even
    /// though the first slot alone would decrypt.
    #[test]
    fn multi_x25519_wrong_length_second_slot_rejects_in_preflight() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let valid_slot = RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?;
        // Bypass `RecipientEntry::native`'s body-length validation —
        // the parser accepts any body_len within the local cap, so an
        // attacker-forged file can carry a wrong-length `x25519` slot
        // that we must reject.
        let malformed_slot = RecipientEntry {
            type_name: x25519::TYPE_NAME.to_string(),
            recipient_flags: 0,
            body: vec![0u8; x25519::BODY_LENGTH - 4],
        };
        let entries = [valid_slot, malformed_slot];

        let fcr = tmp.path().join("multi-wrong-length.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        let err = recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a).unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry) => Ok(()),
            other => panic!(
                "expected MalformedRecipientEntry from the preflight for slot 2; got {other:?}"
            ),
        }
    }

    /// FORMAT.md §4.2: an all-zero `ephemeral_public_key_bytes` is a
    /// credential-independent structural defect, checked during the
    /// step 8 preflight. Even though the earlier valid slot alone
    /// would decrypt, the whole file is rejected before any unwrap.
    #[test]
    fn multi_x25519_all_zero_ephemeral_after_valid_is_file_fatal() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let valid_slot = RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?;

        // Hand-craft a malformed `x25519` body: an all-zero ephemeral
        // public key. The rest of the body is filler — the preflight
        // rejects the entry before any key work could see it.
        let mut malformed_body = vec![0u8; x25519::BODY_LENGTH];
        malformed_body[x25519::BODY_LENGTH - 1] = 0xAB;
        let malformed_slot = RecipientEntry::native(NativeRecipientType::X25519, malformed_body)?;

        let entries = [valid_slot, malformed_slot];
        let fcr = tmp.path().join("zero-ephemeral-after.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => Ok(()),
            other => panic!("all-zero ephemeral in slot 2 must be file-fatal, got {other:?}"),
        }
    }

    /// FORMAT.md §4.2: the all-zero-shared-secret check stays mandatory
    /// during X25519 for a preflight-valid ephemeral. A small-order,
    /// canonical, non-zero ephemeral public key cannot be screened
    /// structurally, and every clamped private scalar maps it to an
    /// all-zero shared secret, so the slot loop must reject the whole
    /// file — even when an earlier valid slot has already MAC-verified.
    #[test]
    fn multi_x25519_small_order_ephemeral_after_valid_is_file_fatal() -> Result<(), CryptoError> {
        // u-coordinate of a known small-order Curve25519 point:
        // canonical and non-zero, so it passes the structural
        // preflight, while X25519 with any clamped scalar yields an
        // all-zero shared secret.
        const SMALL_ORDER_U: [u8; x25519::PUBLIC_KEY_SIZE] = [
            0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3, 0xfa, 0xf1, 0x9f,
            0xc4, 0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32, 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16,
            0x5f, 0x49, 0xb8, 0x00,
        ];

        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let valid_slot = RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?;

        let mut malformed_body = vec![0xABu8; x25519::BODY_LENGTH];
        malformed_body[..x25519::PUBLIC_KEY_SIZE].copy_from_slice(&SMALL_ORDER_U);
        let malformed_slot = RecipientEntry::native(NativeRecipientType::X25519, malformed_body)?;

        let entries = [valid_slot, malformed_slot];
        let fcr = tmp.path().join("small-order-ephemeral-after.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => Ok(()),
            other => {
                panic!("small-order ephemeral in slot 2 must be file-fatal, got {other:?}")
            }
        }
    }

    /// Same property as
    /// [`multi_x25519_all_zero_ephemeral_after_valid_is_file_fatal`] but
    /// with the malformed slot first. The preflight walks every entry,
    /// so slot order does not change the verdict.
    #[test]
    fn multi_x25519_all_zero_ephemeral_before_valid_is_file_fatal() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let valid_slot = RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?;

        let mut malformed_body = vec![0u8; x25519::BODY_LENGTH];
        malformed_body[x25519::BODY_LENGTH - 1] = 0xAB;
        let malformed_slot = RecipientEntry::native(NativeRecipientType::X25519, malformed_body)?;

        let entries = [malformed_slot, valid_slot];
        let fcr = tmp.path().join("zero-ephemeral-before.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => Ok(()),
            other => panic!("all-zero shared secret in slot 1 must be file-fatal, got {other:?}"),
        }
    }

    /// Single-recipient case: an `x25519` file with a single
    /// all-zero-ephemeral slot must also be file-fatal. Confirms the
    /// preflight verdict is independent of recipient cardinality.
    #[test]
    fn single_x25519_all_zero_ephemeral_is_file_fatal() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (_pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let mut malformed_body = vec![0u8; x25519::BODY_LENGTH];
        malformed_body[x25519::BODY_LENGTH - 1] = 0xAB;
        let entries = [RecipientEntry::native(
            NativeRecipientType::X25519,
            malformed_body,
        )?];

        let fcr = tmp.path().join("single-zero-ephemeral.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => Ok(()),
            other => panic!("single all-zero-ephemeral file must be file-fatal, got {other:?}"),
        }
    }

    /// One supported `x25519` recipient plus one unknown non-critical
    /// recipient: the decrypt loop must skip the unknown entry and
    /// decrypt via the supported one. Entry order matters here — we
    /// place the unknown FIRST.
    #[test]
    fn multi_x25519_plus_unknown_non_critical_skips_unknown() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let unknown_entry = RecipientEntry {
            type_name: "example.com/unknown".to_string(),
            recipient_flags: 0,
            body: vec![0xCDu8; 64],
        };
        let entries = [
            unknown_entry,
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
        ];

        let payload = b"skip unknown non-critical";
        let fcr = tmp.path().join("skip.fcr");
        build_multi_recipient_fcr(&entries, &file_key, payload, &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a)?;
        let restored = fs::read(dec_dir.join("data.txt"))?;
        assert_eq!(restored, payload);
        Ok(())
    }

    /// One supported `x25519` recipient plus one unknown CRITICAL
    /// recipient: the file must be rejected as
    /// `UnknownCriticalRecipient` before any recipient unwrap or KDF
    /// runs.
    #[test]
    fn multi_unknown_critical_rejected_before_any_unwrap() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let unknown_critical = RecipientEntry {
            type_name: "example.com/critical".to_string(),
            recipient_flags: RECIPIENT_FLAG_CRITICAL,
            body: vec![0u8; 32],
        };
        let entries = [
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
            unknown_critical,
        ];

        let fcr = tmp.path().join("critical.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::UnknownCriticalRecipient { ref type_name })
                if type_name == "example.com/critical" =>
            {
                Ok(())
            }
            other => {
                panic!("expected UnknownCriticalRecipient(example.com/critical), got {other:?}")
            }
        }
    }

    /// Mixing `argon2id` with any other recipient (here `x25519`) must
    /// be rejected as `IncompatibleRecipients { type_name: "argon2id", .. }`
    /// BEFORE Argon2id runs.
    #[test]
    fn multi_argon2id_plus_x25519_rejected_as_mixed() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_x = x25519::wrap(&file_key, &pub_a)?;
        let synthetic_argon2id = RecipientEntry {
            type_name: argon2id::TYPE_NAME.to_string(),
            recipient_flags: 0,
            body: argon2id::test_body_with_valid_kdf_params(),
        };
        let entries = [
            synthetic_argon2id,
            RecipientEntry::native(NativeRecipientType::X25519, body_x.to_vec())?,
        ];

        let fcr = tmp.path().join("mixed.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::IncompatibleRecipients { type_name, policy })
                if type_name == argon2id::TYPE_NAME && policy == MixingPolicy::Exclusive =>
            {
                Ok(())
            }
            other => panic!("expected IncompatibleRecipients(argon2id, Exclusive), got {other:?}"),
        }
    }

    /// An unknown non-critical recipient whose body sits at the local
    /// cap must be accepted (and skipped); above the cap must be
    /// rejected as a resource-cap violation.
    #[test]
    fn multi_unknown_body_at_local_cap_decrypts() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let unknown_at_cap = RecipientEntry {
            type_name: "example.com/at-cap".to_string(),
            recipient_flags: 0,
            body: vec![0xAB; format::BODY_LEN_LOCAL_CAP_DEFAULT as usize],
        };
        let entries = [
            unknown_at_cap,
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
        ];

        let fcr = tmp.path().join("at-cap.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"at-cap payload", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a)?;
        Ok(())
    }

    /// When the caller's private key AEAD-unwraps no slot of a public-key
    /// `.fcr`, the error is `RecipientUnwrapFailed`, not
    /// `NoSupportedRecipient` (reserved for a file with no supported recipient
    /// type). File targets alice; decrypt with bob.
    #[test]
    fn multi_x25519_no_matching_recipient_surfaces_recipient_unwrap_failed()
    -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, _priv_a, _pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;
        let (_pub_b, priv_b, pass_b) = keypair_fixture(&keys_dir, "bob", "bob-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let entries = [RecipientEntry::native(
            NativeRecipientType::X25519,
            body_a.to_vec(),
        )?];

        let fcr = tmp.path().join("alice-only.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"payload", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_b, &pass_b) {
            Err(CryptoError::RecipientUnwrapFailed { ref type_name })
                if type_name == x25519::TYPE_NAME =>
            {
                Ok(())
            }
            other => panic!("expected RecipientUnwrapFailed(x25519), got {other:?}"),
        }
    }

    /// Decoy-unwrap test: slot A wraps a *decoy* `file_key`; the file's
    /// MAC and payload are keyed off a *different* real `file_key`.
    /// Alice's private key unwraps slot A successfully (yielding the
    /// decoy), but the resulting `header_key` does not verify the MAC.
    /// Slot B targets bob, so alice's private_key fails to unwrap it. The
    /// decrypt loop must surface `HeaderMacFailedAfterUnwrap`.
    #[test]
    fn multi_x25519_decoy_unwrap_returns_mac_failed_after_unwrap() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;
        let (pub_b, _priv_b, _pass_b) = keypair_fixture(&keys_dir, "bob", "bob-pass")?;

        let real_file_key = FileKey::generate().unwrap();
        let decoy_file_key = FileKey::generate().unwrap();

        let body_a = x25519::wrap(&decoy_file_key, &pub_a)?;
        let body_b = x25519::wrap(&decoy_file_key, &pub_b)?;
        let entries = [
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
            RecipientEntry::native(NativeRecipientType::X25519, body_b.to_vec())?,
        ];

        let fcr = tmp.path().join("decoy-unwrap.fcr");
        build_multi_recipient_fcr(&entries, &real_file_key, b"payload", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::HeaderMacFailedAfterUnwrap { ref type_name })
                if type_name == x25519::TYPE_NAME =>
            {
                Ok(())
            }
            other => panic!("expected HeaderMacFailedAfterUnwrap(x25519), got {other:?}"),
        }
    }

    /// FORMAT.md §3.7 step 13 — "If HMAC verification fails, continue
    /// trying other candidate recipients." Slot 1 wraps a decoy file key
    /// (alice unwraps it, but the derived header key does not verify the
    /// MAC); slot 2 wraps the real file key for alice. Decrypt must not
    /// stop at slot 1's MAC failure — it must reach slot 2 and succeed. A
    /// "fail fast on first MAC failure" regression turns this into an error.
    #[test]
    fn multi_x25519_continues_past_mac_failure_to_later_slot() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let real_file_key = FileKey::generate().unwrap();
        let decoy_file_key = FileKey::generate().unwrap();

        // Both slots target alice, but slot 1 seals the decoy key.
        let body_decoy = x25519::wrap(&decoy_file_key, &pub_a)?;
        let body_real = x25519::wrap(&real_file_key, &pub_a)?;
        let entries = [
            RecipientEntry::native(NativeRecipientType::X25519, body_decoy.to_vec())?,
            RecipientEntry::native(NativeRecipientType::X25519, body_real.to_vec())?,
        ];

        let payload = b"decrypt must reach slot 2";
        let fcr = tmp.path().join("mac-fail-then-ok.fcr");
        build_multi_recipient_fcr(&entries, &real_file_key, payload, &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a)?;
        assert_eq!(
            fs::read(dec_dir.join("data.txt"))?,
            payload,
            "slot 2 must decrypt after slot 1's MAC failure"
        );
        Ok(())
    }

    /// Order mirror of
    /// [`multi_x25519_continues_past_mac_failure_to_later_slot`]: the REAL
    /// slot is first and the decoy second. The first slot MAC-verifies, so
    /// decrypt succeeds via it; the later decoy slot's MAC failure must not
    /// undo that success.
    #[test]
    fn multi_x25519_later_mac_failure_does_not_undo_earlier_success() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let real_file_key = FileKey::generate().unwrap();
        let decoy_file_key = FileKey::generate().unwrap();

        let body_real = x25519::wrap(&real_file_key, &pub_a)?;
        let body_decoy = x25519::wrap(&decoy_file_key, &pub_a)?;
        let entries = [
            RecipientEntry::native(NativeRecipientType::X25519, body_real.to_vec())?,
            RecipientEntry::native(NativeRecipientType::X25519, body_decoy.to_vec())?,
        ];

        let payload = b"first slot wins";
        let fcr = tmp.path().join("ok-then-mac-fail.fcr");
        build_multi_recipient_fcr(&entries, &real_file_key, payload, &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a)?;
        assert_eq!(fs::read(dec_dir.join("data.txt"))?, payload);
        Ok(())
    }

    /// Defense-in-depth: an exclusive scheme (`argon2id`) must not be
    /// emitted with more than one recipient. The public API has no path
    /// to construct that, but a future caller bypass would break the
    /// `FORMAT.md` §4.1 mixing rule before any output bytes are
    /// written. The orchestrator catches this before any KDF runs.
    #[test]
    fn encrypt_rejects_multi_passphrase_recipient_list() -> Result<(), CryptoError> {
        let kdf_params = crate::crypto::kdf::KdfParams::test_fast_default();
        let recipient = |text: &str| argon2id::PassphraseRecipient {
            passphrase: Passphrase::new(text),
            kdf_params,
            kdf_limit: crate::crypto::kdf::KdfLimit::default(),
        };
        let recipients = vec![recipient("pass"), recipient("pass")];

        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("data.txt");
        fs::write(&input, b"x")?;
        let out_dir = tmp.path().join("out");
        fs::create_dir_all(&out_dir)?;

        let err = encrypt(
            recipients,
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            &input,
            &out_dir,
            None,
            &|_| {},
        )
        .unwrap_err();
        match err {
            CryptoError::IncompatibleRecipients {
                ref type_name,
                policy: MixingPolicy::Exclusive,
            } if type_name == argon2id::TYPE_NAME => Ok(()),
            other => panic!("expected IncompatibleRecipients(argon2id, Exclusive), got {other:?}"),
        }
    }

    /// Cross-mode mismatch: a passphrase-only file is opened with an
    /// `X25519Credential`. The orchestrator must surface
    /// `DecryptorModeMismatch { expected: PublicKey, found: Passphrase }`
    /// before any slot loop runs — never the legacy
    /// `NoSupportedRecipient`, which would imply "the loop iterated and
    /// found nothing." The public Decryptor::open routes by mode and so
    /// can't reach this branch; the test invokes `protocol::decrypt`
    /// directly to lock in the wording for internal/plugin callers.
    #[test]
    fn decrypt_rejects_passphrase_file_with_x25519_credential() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (_pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        // Single argon2id recipient with a synthetic body. The body has
        // to pass the step-8 structural preflight, so its `kdf_params`
        // are valid; the cross-mode check then fires before any AEAD or
        // KDF runs.
        let synthetic = RecipientEntry::native(
            NativeRecipientType::Argon2id,
            argon2id::test_body_with_valid_kdf_params(),
        )?;
        let file_key = FileKey::generate().unwrap();
        let fcr = tmp.path().join("passphrase.fcr");
        build_multi_recipient_fcr(&[synthetic], &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::DecryptorModeMismatch { expected, found })
                if expected == UnauthenticatedRecipientMode::PublicKey
                    && found == UnauthenticatedRecipientMode::Passphrase =>
            {
                Ok(())
            }
            other => panic!(
                "expected DecryptorModeMismatch(expected=PublicKey, found=Passphrase), got {other:?}"
            ),
        }
    }

    /// Cross-mode mismatch in the reverse direction: a recipient-sealed
    /// file opened with a `PassphraseCredential`. Symmetric assertion to
    /// [`decrypt_rejects_passphrase_file_with_x25519_credential`].
    #[test]
    fn decrypt_rejects_recipient_file_with_passphrase_credential() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, _priv_a, _pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let entries = [RecipientEntry::native(
            NativeRecipientType::X25519,
            body_a.to_vec(),
        )?];
        let fcr = tmp.path().join("recipient.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        let pass = Passphrase::new("doesn't-matter");
        let credential = argon2id::PassphraseCredential {
            passphrase: pass,
            kdf_limit: None,
        };
        let err = decrypt(
            credential,
            &fcr,
            &dec_dir,
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            IncompleteOutputPolicy::default(),
            &|_| {},
        )
        .unwrap_err();
        match err {
            CryptoError::DecryptorModeMismatch { expected, found }
                if expected == UnauthenticatedRecipientMode::Passphrase
                    && found == UnauthenticatedRecipientMode::PublicKey =>
            {
                Ok(())
            }
            other => panic!(
                "expected DecryptorModeMismatch(expected=Passphrase, found=PublicKey), got {other:?}"
            ),
        }
    }

    /// Defense-in-depth: empty recipient list rejected before any
    /// allocation or KDF. The public API gates this at construction
    /// time (`with_public_keys` returns `EmptyRecipientList`), but the
    /// orchestrator re-checks so a callable internal short-circuit
    /// can't bypass the contract.
    #[test]
    fn encrypt_rejects_empty_recipient_list() -> Result<(), CryptoError> {
        let recipients: Vec<argon2id::PassphraseRecipient> = Vec::new();
        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("data.txt");
        fs::write(&input, b"x")?;
        let out_dir = tmp.path().join("out");
        fs::create_dir_all(&out_dir)?;

        let err = encrypt(
            recipients,
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            &input,
            &out_dir,
            None,
            &|_| {},
        )
        .unwrap_err();
        match err {
            CryptoError::EmptyRecipientList => Ok(()),
            other => panic!("expected EmptyRecipientList, got {other:?}"),
        }
    }

    /// The recipient-count cap gate lives in `encrypt` itself: a list
    /// above the default `HeaderReadLimits` cap rejects before any
    /// ECDH or output work, so no in-crate caller can emit a header
    /// the default reader refuses.
    #[test]
    fn encrypt_rejects_recipient_count_above_local_cap() -> Result<(), CryptoError> {
        let (_secret, public) = x25519::generate_keypair()?;
        let over = HeaderReadLimits::RECIPIENT_COUNT_DEFAULT + 1;
        let recipients: Vec<x25519::X25519Recipient> = (0..over)
            .map(|_| x25519::X25519Recipient {
                recipient_public_key_bytes: &public,
            })
            .collect();

        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("data.txt");
        fs::write(&input, b"x")?;
        let out_dir = tmp.path().join("out");
        fs::create_dir_all(&out_dir)?;

        let err = encrypt(
            recipients,
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            &input,
            &out_dir,
            None,
            &|_| {},
        )
        .unwrap_err();
        match err {
            CryptoError::RecipientCountCapExceeded { count, local_cap } => {
                assert_eq!(count, over);
                assert_eq!(local_cap, HeaderReadLimits::RECIPIENT_COUNT_DEFAULT);
                Ok(())
            }
            other => panic!("expected RecipientCountCapExceeded, got {other:?}"),
        }
    }

    /// The KDF write gate lives in `encrypt` itself: passphrase
    /// parameters above the default `KdfLimit` memory policy reject
    /// before any Argon2id run, so no in-crate caller can emit an
    /// `argon2id` body the default reader refuses.
    #[test]
    fn encrypt_rejects_kdf_memory_above_write_policy() -> Result<(), CryptoError> {
        use crate::crypto::kdf::{KdfLimit, KdfParams};

        let recipient = argon2id::PassphraseRecipient {
            passphrase: Passphrase::new("pass"),
            kdf_params: KdfParams {
                mem_cost: KdfLimit::MEM_COST_KIB_STRUCTURAL_MAX,
                time_cost: 1,
                lanes: 1,
            },
            kdf_limit: KdfLimit::default(),
        };

        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("data.txt");
        fs::write(&input, b"x")?;
        let out_dir = tmp.path().join("out");
        fs::create_dir_all(&out_dir)?;

        let err = encrypt(
            vec![recipient],
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            &input,
            &out_dir,
            None,
            &|_| {},
        )
        .unwrap_err();
        match err {
            CryptoError::KdfResourceCapExceeded {
                mem_cost_kib,
                local_cap_kib,
            } => {
                assert_eq!(mem_cost_kib, KdfLimit::MEM_COST_KIB_STRUCTURAL_MAX);
                assert_eq!(local_cap_kib, KdfLimit::MEM_COST_KIB_DEFAULT);
                Ok(())
            }
            other => panic!("expected KdfResourceCapExceeded, got {other:?}"),
        }
    }

    /// The preflight counts the extension region in the header length,
    /// so a future writer that emits `ext_bytes` cannot pass the caps
    /// with a length the sealed header would exceed.
    #[test]
    fn preflight_counts_the_extension_region_in_the_header_length() {
        let exact = u32::try_from(
            format::HEADER_FIXED_SIZE
                + crate::recipient::entry::ENTRY_HEADER_SIZE
                + argon2id::TYPE_NAME.len()
                + NativeRecipientType::Argon2id.body_len(),
        )
        .unwrap();
        let limits = crate::HeaderReadLimits::default().max_header_len(exact);

        preflight_header_write_limits(limits, 1, NativeRecipientType::Argon2id, b"")
            .expect("the exact header length must be accepted");
        let err = preflight_header_write_limits(limits, 1, NativeRecipientType::Argon2id, b"x")
            .expect_err("one extension byte must exceed the exact cap");
        assert!(
            matches!(err, CryptoError::HeaderLenCapExceeded { .. }),
            "got: {err:?}"
        );
    }

    /// The KDF write gate lives in `generate_key_pair` itself:
    /// below-floor memory rejects before the output directory is even
    /// created, so no in-crate caller can seal a weak `private.key`.
    #[test]
    fn generate_key_pair_rejects_kdf_memory_below_write_floor() {
        use crate::crypto::kdf::KdfParams;

        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let pass = Passphrase::new("pass");
        let weak = KdfParams {
            mem_cost: KdfParams::MIN_WRITE_MEM_COST - 1,
            time_cost: 1,
            lanes: 1,
        };
        let err = generate_key_pair(pass, &weak, None, &keys_dir, &|_| {}).unwrap_err();
        match err {
            CryptoError::KdfBelowWriteFloor { .. } => {}
            other => panic!("expected KdfBelowWriteFloor, got {other:?}"),
        }
        assert!(
            !keys_dir.exists(),
            "gate must fire before the output directory is created"
        );
    }

    /// Key generation checks both reported paths after all commit work. A
    /// replacement of either final entry in that interval must turn the call
    /// into an error while leaving the committed key and the replacement
    /// untouched.
    #[cfg(unix)]
    #[test]
    fn keygen_rejects_either_key_path_replaced_after_commit() {
        use crate::crypto::kdf::KdfParams;

        let tmp = tempfile::TempDir::new().unwrap();
        let kdf_params = KdfParams::test_fast_default();

        for target in [PRIVATE_KEY_FILENAME, PUBLIC_KEY_FILENAME] {
            let output_dir = tmp.path().join(target);
            let target_path = output_dir.join(target);
            let committed_path = output_dir.join(format!("{target}.committed"));

            let err = generate_key_pair_with_seams(
                Passphrase::new("passphrase"),
                &kdf_params,
                None,
                &output_dir,
                &|_| {},
                |_, _| Ok(()),
                |private_path, public_path| {
                    let path = if target == PRIVATE_KEY_FILENAME {
                        private_path
                    } else {
                        public_path
                    };
                    fs::rename(path, &committed_path)?;
                    fs::write(path, b"replacement")
                },
            )
            .expect_err("a replaced key path must not be returned");

            let other = if target == PRIVATE_KEY_FILENAME {
                PUBLIC_KEY_FILENAME
            } else {
                PRIVATE_KEY_FILENAME
            };
            assert!(
                matches!(
                    &err,
                    CryptoError::InvalidInput(message)
                        if message.contains("reported path changed")
                            && message.ends_with(&format!("; {other} is also complete"))
                ),
                "{target} replacement must be reported explicitly, with {other} as complete, got: {err}"
            );
            assert_ne!(
                fs::read(&committed_path).unwrap(),
                b"replacement",
                "the committed {target} must survive under its new name"
            );
            assert_eq!(fs::read(&target_path).unwrap(), b"replacement");
        }
    }

    /// A reported-path check that cannot run once both key files are
    /// committed fails the call with an error that says both files are
    /// complete, and neither file is removed. The output directory becomes
    /// untraversable after the commits, so the check's read by path is
    /// refused while the retained handles still work. The second file's
    /// path cannot be confirmed either, so it is reported as unconfirmed
    /// rather than simply as complete.
    #[cfg(unix)]
    #[test]
    fn keygen_reports_both_keys_as_complete_when_a_path_cannot_be_confirmed() {
        use std::os::unix::fs::PermissionsExt;

        use crate::crypto::kdf::KdfParams;

        let tmp = tempfile::TempDir::new().unwrap();
        let output_dir = tmp.path().join("keys");
        let private_key_path = output_dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = output_dir.join(PUBLIC_KEY_FILENAME);

        let outcome = generate_key_pair_with_seams(
            Passphrase::new("passphrase"),
            &KdfParams::test_fast_default(),
            None,
            &output_dir,
            &|_| {},
            |_, _| Ok(()),
            |_, _| fs::set_permissions(&output_dir, fs::Permissions::from_mode(0o000)),
        );
        fs::set_permissions(&output_dir, fs::Permissions::from_mode(0o755)).unwrap();

        match outcome {
            // A privileged runner reads the paths despite the mode.
            Ok(_) => {}
            Err(CryptoError::Io(error)) => {
                assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
                let message = error.to_string();
                let unconfirmed = |path: &Path| {
                    format!(
                        "Output is complete, but its reported path could not be confirmed: {}: ",
                        crate::error::sanitize_path_for_display(path)
                    )
                };
                assert!(
                    message.starts_with(&unconfirmed(&private_key_path))
                        && message.contains(&format!("; {}", unconfirmed(&public_key_path)))
                        && !message.contains("is also complete"),
                    "both key files must be reported as complete and unconfirmed, got: {message}"
                );
            }
            Err(other) => panic!("the denial must be reported as I/O, got: {other}"),
        }
        for name in [PRIVATE_KEY_FILENAME, PUBLIC_KEY_FILENAME] {
            assert!(
                output_dir.join(name).is_file(),
                "the committed {name} must stay"
            );
        }
    }

    /// Key generation holds its output-directory anchor from before
    /// either key file is staged, so a local writer who moves both
    /// staged files into a directory of their own and installs it at the
    /// output path cannot have the key pair committed there: the commit
    /// refuses, and neither directory receives a key file. Driven through
    /// the pre-commit seam rather than a timing race.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn keygen_refuses_an_output_directory_swapped_in_after_staging() {
        use crate::crypto::kdf::KdfParams;

        let tmp = tempfile::TempDir::new().unwrap();
        let output_dir = tmp.path().join("keys");
        let replacement = tmp.path().join("replacement");
        let moved = tmp.path().join("keys.moved");
        fs::create_dir(&replacement).unwrap();

        let err = generate_key_pair_with_seams(
            Passphrase::new("passphrase"),
            &KdfParams::test_fast_default(),
            None,
            &output_dir,
            &|_| {},
            |private_staged, public_staged| {
                for staged in [private_staged, public_staged] {
                    let name = staged.file_name().expect("a staged file has a name");
                    fs::rename(staged, replacement.join(name))?;
                }
                fs::rename(&output_dir, &moved)?;
                fs::rename(&replacement, &output_dir)
            },
            |_, _| Ok(()),
        )
        .expect_err("staged files moved out of the anchored directory must refuse the commit");

        for dir in [&output_dir, &moved] {
            for name in [PRIVATE_KEY_FILENAME, PUBLIC_KEY_FILENAME] {
                assert!(
                    !dir.join(name).exists(),
                    "{} must receive no {name}: {err}",
                    dir.display()
                );
            }
        }
    }

    /// The same swap with the staged files left where they are:
    /// `private.key` commits into the directory the run began in, the
    /// substituted directory receives nothing, and the run stops at the
    /// reported-path check that follows — before `public.key` commits.
    /// The still-staged public file is removed through the original
    /// directory anchor, so what remains is exactly one private key,
    /// which is safe to delete.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn keygen_commits_into_the_directory_it_began_in_across_a_swap() {
        use crate::crypto::kdf::KdfParams;

        let tmp = tempfile::TempDir::new().unwrap();
        let output_dir = tmp.path().join("keys");
        let replacement = tmp.path().join("replacement");
        let moved = tmp.path().join("keys.moved");
        fs::create_dir(&replacement).unwrap();

        let err = generate_key_pair_with_seams(
            Passphrase::new("passphrase"),
            &KdfParams::test_fast_default(),
            None,
            &output_dir,
            &|_| {},
            |_, _| {
                fs::rename(&output_dir, &moved)?;
                fs::rename(&replacement, &output_dir)
            },
            |_, _| Ok(()),
        )
        .expect_err("the reported paths no longer name the key files");

        assert!(
            matches!(&err, CryptoError::InvalidInput(message) if message.contains("reported path changed")),
            "the path change must be reported explicitly, got: {err}"
        );
        assert_eq!(
            leftover_entries(&output_dir, ""),
            Vec::<std::ffi::OsString>::new(),
            "the substituted directory must receive nothing"
        );
        assert!(
            moved.join(PRIVATE_KEY_FILENAME).is_file(),
            "the private key belongs in the directory the run began in"
        );
        assert_eq!(
            leftover_entries(&moved, PRIVATE_KEY_FILENAME),
            Vec::<std::ffi::OsString>::new(),
            "the original directory must contain only the committed private key"
        );
    }

    /// If the public temporary is moved out of the retained directory before
    /// `private.key` commits, the post-commit cleanup must not fall back to its
    /// now-stale ambient path. It leaves the unconfirmed staged file in place
    /// and appends that fact to the path-change error instead.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn keygen_reports_a_public_staging_file_it_cannot_remove_through_the_anchor() {
        use crate::crypto::kdf::KdfParams;

        let tmp = tempfile::TempDir::new().unwrap();
        let output_dir = tmp.path().join("keys");
        let replacement = tmp.path().join("replacement");
        let moved = tmp.path().join("keys.moved");
        fs::create_dir(&replacement).unwrap();

        let err = generate_key_pair_with_seams(
            Passphrase::new("passphrase"),
            &KdfParams::test_fast_default(),
            None,
            &output_dir,
            &|_| {},
            |_, public_staged| {
                let public_name = public_staged
                    .file_name()
                    .expect("a staged public key has a name");
                fs::rename(public_staged, replacement.join(public_name))?;
                fs::rename(&output_dir, &moved)?;
                fs::rename(&replacement, &output_dir)
            },
            |_, _| Ok(()),
        )
        .expect_err("an unconfirmed staged sibling must be reported");

        let message = err.to_string();
        assert!(
            message.contains("reported path changed"),
            "the committed private key's path change must remain the primary error: {message}"
        );
        assert!(
            message.contains("could not be confirmed"),
            "the surviving staged public key must be reported: {message}"
        );
        assert!(moved.join(PRIVATE_KEY_FILENAME).is_file());
        assert!(!moved.join(PUBLIC_KEY_FILENAME).exists());

        let replacement_entries = leftover_entries(&output_dir, "");
        assert_eq!(replacement_entries.len(), 1, "got: {replacement_entries:?}");
        let staged_name = replacement_entries[0].to_string_lossy();
        assert!(
            staged_name.starts_with(".ferrocrypt-public_key-") && staged_name.ends_with(".tmp"),
            "the reported survivor must be the staged public key, got: {staged_name}"
        );
    }

    /// Creates a staged key-file temporary file in `dir` containing `bytes`.
    fn staged_key_tempfile(dir: &Path, bytes: &[u8]) -> tempfile::NamedTempFile {
        use std::io::Write as _;
        let mut tmp = tempfile::Builder::new()
            .prefix(".ferrocrypt-keygen-test-")
            .suffix(".tmp")
            .tempfile_in(dir)
            .unwrap();
        tmp.as_file_mut().write_all(bytes).unwrap();
        tmp
    }

    /// Returns the entry names in `dir`, excluding `keep`. Commit-failure
    /// tests use this to verify that no temporary files remain.
    fn leftover_entries(dir: &Path, keep: &str) -> Vec<std::ffi::OsString> {
        fs::read_dir(dir)
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .filter(|name| name != keep)
            .collect()
    }

    /// If the `public.key` commit fails after preflight, the newly committed
    /// `private.key` is removed and the existing `public.key` entry is left
    /// unchanged.
    #[test]
    fn keygen_public_commit_failure_removes_private_key() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path();
        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        fs::write(&public_key_path, b"occupant").unwrap();

        let private_tmp = staged_key_tempfile(dir, b"private bytes");
        let public_tmp = staged_key_tempfile(dir, b"public bytes");

        let err = commit_key_pair_files(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &crate::fs::atomic::OutputDir::open(dir).unwrap(),
        )
        .expect_err("occupied public.key name must fail the commit");
        assert!(
            matches!(err, CryptoError::InvalidInput(_)),
            "expected the typed already-exists rejection, got {err:?}"
        );
        assert!(
            !private_key_path.exists(),
            "private.key must not remain after the public.key commit failed"
        );
        assert_eq!(
            fs::read(&public_key_path).unwrap(),
            b"occupant",
            "pre-existing occupant of the public.key name must be untouched"
        );
        let leftovers = leftover_entries(dir, PUBLIC_KEY_FILENAME);
        assert!(
            leftovers.is_empty(),
            "no staged tempfiles may remain, found {leftovers:?}"
        );
    }

    /// If the `private.key` commit fails after preflight, `public.key` is not
    /// published, the existing entry remains unchanged, and no temporary files
    /// remain.
    #[test]
    fn keygen_private_commit_failure_publishes_nothing() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path();
        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        fs::write(&private_key_path, b"occupant").unwrap();

        let private_tmp = staged_key_tempfile(dir, b"private bytes");
        let public_tmp = staged_key_tempfile(dir, b"public bytes");

        let err = commit_key_pair_files(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &crate::fs::atomic::OutputDir::open(dir).unwrap(),
        )
        .expect_err("occupied private.key name must fail the commit");
        assert!(
            matches!(err, CryptoError::InvalidInput(_)),
            "expected the typed already-exists rejection, got {err:?}"
        );
        assert!(
            !public_key_path.exists(),
            "public.key must never appear when the private.key commit failed"
        );
        assert_eq!(
            fs::read(&private_key_path).unwrap(),
            b"occupant",
            "pre-existing occupant of the private.key name must be untouched"
        );
        let leftovers = leftover_entries(dir, PRIVATE_KEY_FILENAME);
        assert!(
            leftovers.is_empty(),
            "no staged tempfiles may remain, found {leftovers:?}"
        );
    }

    /// Records one directory-flush call: the directory and whether each final
    /// key-file name existed at that time.
    #[derive(Debug, PartialEq, Eq)]
    struct BarrierCall {
        dir: PathBuf,
        private_committed: bool,
        public_committed: bool,
    }

    /// Directory-flush test function. It records every call and optionally
    /// returns an injected I/O error on the selected one-based call number.
    fn counting_barrier(
        fail_on: Option<u32>,
        seen: std::rc::Rc<std::cell::RefCell<Vec<BarrierCall>>>,
    ) -> impl Fn(&crate::fs::atomic::OutputDir, &Path) -> std::io::Result<()> {
        move |_committed_dir, dir| {
            seen.borrow_mut().push(BarrierCall {
                dir: dir.to_path_buf(),
                private_committed: dir.join(PRIVATE_KEY_FILENAME).exists(),
                public_committed: dir.join(PUBLIC_KEY_FILENAME).exists(),
            });
            if Some(seen.borrow().len() as u32) == fail_on {
                Err(std::io::Error::other("injected directory flush failure"))
            } else {
                Ok(())
            }
        }
    }

    /// If the directory flush after committing `private.key` fails, the
    /// private key is removed, `public.key` is never published, the original
    /// error is returned, and no temporary files remain.
    #[test]
    fn keygen_barrier_failure_after_private_commit_publishes_nothing() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path();
        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        let private_tmp = staged_key_tempfile(dir, b"private bytes");
        let public_tmp = staged_key_tempfile(dir, b"public bytes");
        let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));

        let err = commit_key_pair_files_with_barrier(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &crate::fs::atomic::OutputDir::open(dir).unwrap(),
            counting_barrier(Some(1), seen.clone()),
        )
        .expect_err("a failed directory flush after private.key must fail the commit");
        assert_eq!(
            err.to_string(),
            "injected directory flush failure",
            "the directory flush error must surface unchanged, got {err:?}"
        );
        assert!(
            matches!(err, CryptoError::Io(_)),
            "directory flush failure must map to the I/O error class, got {err:?}"
        );
        assert!(
            !private_key_path.exists(),
            "private.key must be removed when its directory flush failed"
        );
        assert!(
            !public_key_path.exists(),
            "public.key must never appear when the private.key directory flush failed"
        );
        let leftovers = leftover_entries(dir, "");
        assert!(
            leftovers.is_empty(),
            "no key files or staged tempfiles may remain, found {leftovers:?}"
        );
    }

    /// If the output path is swapped inside the first durability barrier, both
    /// the private-key rollback and cleanup of the still-staged public key stay
    /// in the retained original directory. The replacement receives nothing.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn keygen_first_barrier_failure_cleans_the_original_directory_after_a_swap() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("keys");
        let replacement = tmp.path().join("replacement");
        let moved = tmp.path().join("keys.moved");
        fs::create_dir(&dir).unwrap();
        fs::create_dir(&replacement).unwrap();

        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        let private_tmp = staged_key_tempfile(&dir, b"private bytes");
        let public_tmp = staged_key_tempfile(&dir, b"public bytes");
        let anchor = crate::fs::atomic::OutputDir::open(&dir).unwrap();

        let err = commit_key_pair_files_with_barrier(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &anchor,
            |_, _| {
                fs::rename(&dir, &moved)?;
                fs::rename(&replacement, &dir)?;
                Err(std::io::Error::other("injected directory flush failure"))
            },
        )
        .expect_err("the injected first-barrier failure must fail key generation");

        assert_eq!(err.to_string(), "injected directory flush failure");
        assert_eq!(
            leftover_entries(&dir, ""),
            Vec::<std::ffi::OsString>::new(),
            "the replacement directory must receive nothing"
        );
        assert_eq!(
            leftover_entries(&moved, ""),
            Vec::<std::ffi::OsString>::new(),
            "both files this run wrote must be removed from the original directory"
        );
    }

    /// If the directory flush after committing `public.key` fails, only
    /// `public.key` is removed. `private.key` remains because, without a
    /// working directory flush, removing both could be persisted in an order
    /// that leaves only `public.key`.
    #[test]
    fn keygen_barrier_failure_after_public_commit_keeps_only_private_key() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path();
        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        let private_tmp = staged_key_tempfile(dir, b"private bytes");
        let public_tmp = staged_key_tempfile(dir, b"public bytes");
        let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));

        let err = commit_key_pair_files_with_barrier(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &crate::fs::atomic::OutputDir::open(dir).unwrap(),
            counting_barrier(Some(2), seen.clone()),
        )
        .expect_err("a failed directory flush after public.key must fail the commit");
        assert!(
            matches!(err, CryptoError::Io(_)),
            "directory flush failure must map to the I/O error class, got {err:?}"
        );
        assert_eq!(
            err.to_string(),
            "injected directory flush failure; private.key is complete and was kept",
            "the error must say which key file remains"
        );
        assert!(
            !public_key_path.exists(),
            "public.key must be removed when the final directory flush failed"
        );
        assert_eq!(
            fs::read(&private_key_path).unwrap(),
            b"private bytes",
            "private.key must be kept when the final directory flush failed"
        );
        let leftovers = leftover_entries(dir, PRIVATE_KEY_FILENAME);
        assert!(
            leftovers.is_empty(),
            "nothing besides private.key may remain, found {leftovers:?}"
        );
    }

    /// A public-key finalization error after publication must preserve both
    /// final names. Rolling the private half back would leave a public key that
    /// others can use without a matching decryption key.
    #[test]
    fn keygen_post_commit_public_failure_preserves_both_keys() {
        use crate::fs::atomic;

        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path();
        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        let private_tmp = staged_key_tempfile(dir, b"private bytes");
        let public_tmp = staged_key_tempfile(dir, b"public bytes");

        let err = commit_key_pair_files_with_barrier_and_public_finalizer(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &crate::fs::atomic::OutputDir::open(dir).unwrap(),
            |_, _| Ok(()),
            |tmp, path, label, anchor| {
                let _committed = atomic::finalize_file(tmp, path, label, anchor)
                    .expect("the injected error must follow a real commit");
                Err(atomic::FinalizeFileError::after_commit_for_test(
                    CryptoError::Io(std::io::Error::other(
                        "Output is complete, but an injected check failed",
                    )),
                ))
            },
        )
        .expect_err("the injected post-commit failure must be returned");

        assert_eq!(
            err.to_string(),
            "Output is complete, but an injected check failed; private.key is also complete"
        );
        assert_eq!(fs::read(&private_key_path).unwrap(), b"private bytes");
        assert_eq!(fs::read(&public_key_path).unwrap(), b"public bytes");
        assert_eq!(
            fs::read_dir(dir).unwrap().count(),
            2,
            "only the two committed key files may remain"
        );
    }

    /// What a local writer can do to a committed key file before its
    /// rollback runs. Each makes the identity-checked removal report a
    /// different outcome without needing a privilege the test runner may
    /// lack: a moved name leaves nothing to confirm, a replaced entry is
    /// left in place, and a second link makes the removal leave a copy.
    /// The outcomes have distinct wording, so the message proves which
    /// branch the removal took: a replacement left in place shows that the
    /// identity comparison ran and declined. The tests run on Windows too,
    /// where NTFS has hard links, so the second-link report is needed there
    /// as well.
    #[derive(Clone, Copy, Debug)]
    enum Interference {
        Moved,
        Replaced,
        Linked,
    }

    impl Interference {
        const ALL: [Self; 3] = [Self::Moved, Self::Replaced, Self::Linked];

        /// Applies the interference to the committed key file at `key`.
        fn apply(self, key: &Path) -> std::io::Result<()> {
            match self {
                Self::Moved => fs::rename(key, key.with_extension("moved")),
                Self::Replaced => {
                    fs::rename(key, key.with_extension("moved"))?;
                    fs::write(key, SWAPPED_KEY_BYTES)
                }
                Self::Linked => fs::hard_link(key, key.with_extension("link")),
            }
        }

        /// The clause the rollback of the committed key file `name` must
        /// report after this interference.
        fn expected_clause(self, name: &str) -> String {
            match self {
                Self::Moved => {
                    format!(
                        "a complete {name} was committed, and its removal could not be confirmed"
                    )
                }
                Self::Replaced => format!(
                    "a complete {name} was committed, but the entry at its name was replaced and left in place, and the committed file may remain under another name"
                ),
                Self::Linked => format!(
                    "a complete {name} was committed and then removed, but it had 2 filesystem names, so a copy may remain under another name"
                ),
            }
        }

        /// Asserts what the rollback left: the complete key file holding
        /// `bytes` survives under its moved or linked name, a planted
        /// replacement stays in place, and otherwise the final name holds
        /// nothing.
        fn assert_left(self, key: &Path, bytes: &[u8]) {
            let other_name = match self {
                Self::Moved | Self::Replaced => key.with_extension("moved"),
                Self::Linked => key.with_extension("link"),
            };
            assert_eq!(
                fs::read(&other_name).unwrap(),
                bytes,
                "{self:?}: the complete key file must survive under its other name"
            );
            match self {
                Self::Replaced => assert_eq!(
                    fs::read(key).unwrap(),
                    SWAPPED_KEY_BYTES,
                    "the replacement must be left in place"
                ),
                Self::Moved | Self::Linked => {
                    assert!(!key.exists(), "{self:?}: the final name must hold nothing");
                }
            }
        }
    }

    /// Asserts that no staged temporary remains in `dir`.
    fn assert_no_staged_temporary(dir: &Path) {
        let staged: Vec<_> = leftover_entries(dir, "")
            .into_iter()
            .filter(|name| name.to_string_lossy().starts_with(".ferrocrypt-"))
            .collect();
        assert!(
            staged.is_empty(),
            "no staged temporary may remain, found {staged:?}"
        );
    }

    /// When the flush after `private.key` fails and the rollback of that
    /// complete key file cannot confirm its removal, the error says that a
    /// complete `private.key` was committed before saying what the removal
    /// left. The staged public key is still removed, so it needs no report.
    #[test]
    fn keygen_first_barrier_failure_reports_a_committed_private_key_it_could_not_remove() {
        for interference in Interference::ALL {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path();
            let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
            let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
            let private_tmp = staged_key_tempfile(dir, b"private bytes");
            let public_tmp = staged_key_tempfile(dir, b"public bytes");

            let err = commit_key_pair_files_with_barrier(
                private_tmp,
                public_tmp,
                &private_key_path,
                &public_key_path,
                &crate::fs::atomic::OutputDir::open(dir).unwrap(),
                |_, _| {
                    assert!(
                        private_key_path.is_file(),
                        "the flush must run after private.key is committed, or this test proves nothing"
                    );
                    interference.apply(&private_key_path)?;
                    Err(std::io::Error::other("injected directory flush failure"))
                },
            )
            .expect_err("a failed directory flush after private.key must fail the commit");

            assert!(
                matches!(err, CryptoError::Io(_)),
                "{interference:?}: the I/O class must be kept, got {err:?}"
            );
            assert_eq!(
                err.to_string(),
                format!(
                    "injected directory flush failure; {}",
                    interference.expected_clause(PRIVATE_KEY_FILENAME)
                ),
                "{interference:?}"
            );
            interference.assert_left(&private_key_path, b"private bytes");
            assert!(
                !public_key_path.exists(),
                "{interference:?}: public.key must never appear"
            );
            assert_no_staged_temporary(dir);
        }
    }

    /// When the `public.key` commit fails before that file commits and the
    /// rollback of the complete `private.key` cannot confirm its removal,
    /// the error says that a complete `private.key` was committed before
    /// saying what the removal left. The occupant of the public name is
    /// untouched.
    #[test]
    fn keygen_public_commit_failure_reports_a_committed_private_key_it_could_not_remove() {
        for interference in Interference::ALL {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path();
            let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
            let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
            fs::write(&public_key_path, b"occupant").unwrap();
            let private_tmp = staged_key_tempfile(dir, b"private bytes");
            let public_tmp = staged_key_tempfile(dir, b"public bytes");

            let err = commit_key_pair_files_with_barrier(
                private_tmp,
                public_tmp,
                &private_key_path,
                &public_key_path,
                &crate::fs::atomic::OutputDir::open(dir).unwrap(),
                |_, _| interference.apply(&private_key_path),
            )
            .expect_err("occupied public.key name must fail the commit");

            assert!(
                matches!(err, CryptoError::InvalidInput(_)),
                "{interference:?}: the already-exists class must be kept, got {err:?}"
            );
            let message = err.to_string();
            let clause = interference.expected_clause(PRIVATE_KEY_FILENAME);
            assert!(
                message.starts_with("Key file already exists")
                    && message.ends_with(&format!("; {clause}")),
                "{interference:?}: the cause and the rollback report must both be stated, got: {message}"
            );
            interference.assert_left(&private_key_path, b"private bytes");
            assert_eq!(
                fs::read(&public_key_path).unwrap(),
                b"occupant",
                "{interference:?}: the occupant of the public.key name must be untouched"
            );
            assert_no_staged_temporary(dir);
        }
    }

    /// When the flush after `public.key` fails and the rollback of that
    /// complete key file cannot confirm its removal, the error says that a
    /// complete `public.key` was committed before saying what the removal
    /// left, beside the kept `private.key`.
    #[test]
    fn keygen_final_barrier_failure_reports_a_committed_public_key_it_could_not_remove() {
        for interference in Interference::ALL {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path();
            let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
            let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
            let private_tmp = staged_key_tempfile(dir, b"private bytes");
            let public_tmp = staged_key_tempfile(dir, b"public bytes");
            let calls = std::cell::Cell::new(0);

            let err = commit_key_pair_files_with_barrier(
                private_tmp,
                public_tmp,
                &private_key_path,
                &public_key_path,
                &crate::fs::atomic::OutputDir::open(dir).unwrap(),
                |_, _| {
                    calls.set(calls.get() + 1);
                    if calls.get() == 1 {
                        return Ok(());
                    }
                    interference.apply(&public_key_path)?;
                    Err(std::io::Error::other("injected directory flush failure"))
                },
            )
            .expect_err("a failed directory flush after public.key must fail the commit");

            assert!(
                matches!(err, CryptoError::Io(_)),
                "{interference:?}: the I/O class must be kept, got {err:?}"
            );
            assert_eq!(
                err.to_string(),
                format!(
                    "injected directory flush failure; private.key is complete and was kept; {}",
                    interference.expected_clause(PUBLIC_KEY_FILENAME)
                ),
                "{interference:?}"
            );
            assert_eq!(
                fs::read(&private_key_path).unwrap(),
                b"private bytes",
                "{interference:?}: private.key must be kept"
            );
            interference.assert_left(&public_key_path, b"public bytes");
            assert_no_staged_temporary(dir);
        }
    }

    /// Moves `dir` to `moved` and plants a directory at `dir` holding a
    /// replacement for each of `names`: what a local writer with access to
    /// the parent can do once a key file is committed.
    #[cfg(unix)]
    fn swap_output_dir(dir: &Path, moved: &Path, names: &[&str]) -> std::io::Result<()> {
        fs::rename(dir, moved)?;
        fs::create_dir(dir)?;
        for name in names {
            fs::write(dir.join(name), SWAPPED_KEY_BYTES)?;
        }
        Ok(())
    }

    /// Contents of a key file planted in place of a committed one, by
    /// [`Interference::Replaced`] or [`swap_output_dir`].
    const SWAPPED_KEY_BYTES: &[u8] = b"replacement";

    /// The message for a reported key path that now names another entry.
    #[cfg(unix)]
    fn changed_path_report(path: &Path) -> String {
        format!(
            "Output is complete but its reported path changed: {}",
            crate::error::sanitize_path_for_display(path)
        )
    }

    /// An output directory swapped after both commits leaves neither
    /// returned path leading to a key file this run wrote. The error must
    /// say so for both, rather than calling the second file complete by a
    /// path that now names a replacement.
    #[cfg(unix)]
    #[test]
    fn keygen_does_not_vouch_for_either_key_path_after_a_directory_swap() {
        use crate::crypto::kdf::KdfParams;

        let tmp = tempfile::TempDir::new().unwrap();
        let output_dir = tmp.path().join("keys");
        let moved = tmp.path().join("keys.moved");
        let names = [PRIVATE_KEY_FILENAME, PUBLIC_KEY_FILENAME];

        let err = generate_key_pair_with_seams(
            Passphrase::new("passphrase"),
            &KdfParams::test_fast_default(),
            None,
            &output_dir,
            &|_| {},
            |_, _| Ok(()),
            |_, _| swap_output_dir(&output_dir, &moved, &names),
        )
        .expect_err("a swapped output directory must not be reported as success");

        let message = err.to_string();
        for name in names {
            assert!(
                message.contains(&changed_path_report(&output_dir.join(name))),
                "{name} must be reported at a changed path, got: {message}"
            );
            assert_ne!(fs::read(moved.join(name)).unwrap(), SWAPPED_KEY_BYTES);
        }
        assert!(
            !message.contains("is also complete"),
            "a replaced path must not be vouched for, got: {message}"
        );
    }

    /// A post-commit `public.key` failure names `private.key` as complete
    /// only while its path still leads to it. After a directory swap the
    /// error reports that path as changed instead.
    #[cfg(unix)]
    #[test]
    fn keygen_post_commit_public_failure_does_not_vouch_for_a_swapped_private_path() {
        use crate::fs::atomic;

        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("keys");
        fs::create_dir(&dir).unwrap();
        let moved = tmp.path().join("keys.moved");
        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        let private_tmp = staged_key_tempfile(&dir, b"private bytes");
        let public_tmp = staged_key_tempfile(&dir, b"public bytes");

        let err = commit_key_pair_files_with_barrier_and_public_finalizer(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &atomic::OutputDir::open(&dir).unwrap(),
            |_, _| Ok(()),
            |tmp, path, label, anchor| {
                let _committed = atomic::finalize_file(tmp, path, label, anchor)
                    .expect("the injected error must follow a real commit");
                swap_output_dir(&dir, &moved, &[PRIVATE_KEY_FILENAME])
                    .expect("the output directory must be swapped");
                Err(atomic::FinalizeFileError::after_commit_for_test(
                    CryptoError::Io(std::io::Error::other(
                        "Output is complete, but an injected check failed",
                    )),
                ))
            },
        )
        .expect_err("the injected post-commit failure must be returned");

        assert_eq!(
            err.to_string(),
            format!(
                "Output is complete, but an injected check failed; {}",
                changed_path_report(&private_key_path)
            )
        );
        assert_eq!(
            fs::read(moved.join(PRIVATE_KEY_FILENAME)).unwrap(),
            b"private bytes"
        );
        assert_eq!(
            fs::read(moved.join(PUBLIC_KEY_FILENAME)).unwrap(),
            b"public bytes"
        );
    }

    /// When the final directory flush fails, the error says `private.key`
    /// was kept only while its path still leads to it. After a directory
    /// swap the error reports that path as changed instead; `public.key` is
    /// still removed from the directory it was committed in.
    #[cfg(unix)]
    #[test]
    fn keygen_barrier_failure_after_public_commit_does_not_vouch_for_a_swapped_private_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("keys");
        fs::create_dir(&dir).unwrap();
        let moved = tmp.path().join("keys.moved");
        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        let private_tmp = staged_key_tempfile(&dir, b"private bytes");
        let public_tmp = staged_key_tempfile(&dir, b"public bytes");
        let calls = std::cell::Cell::new(0);

        let err = commit_key_pair_files_with_barrier(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &crate::fs::atomic::OutputDir::open(&dir).unwrap(),
            |_, _| {
                calls.set(calls.get() + 1);
                if calls.get() == 1 {
                    return Ok(());
                }
                swap_output_dir(&dir, &moved, &[PRIVATE_KEY_FILENAME])?;
                Err(std::io::Error::other("injected directory flush failure"))
            },
        )
        .expect_err("a failed directory flush after public.key must fail the commit");

        assert_eq!(
            err.to_string(),
            format!(
                "injected directory flush failure; {}",
                changed_path_report(&private_key_path)
            )
        );
        assert_eq!(
            fs::read(moved.join(PRIVATE_KEY_FILENAME)).unwrap(),
            b"private bytes"
        );
        assert!(!moved.join(PUBLIC_KEY_FILENAME).exists());
    }

    /// A rollback must remove the key file this run committed, not
    /// whatever the output path names by the time the rollback runs. The
    /// barrier renames the output directory aside and leaves a symlink to
    /// an unrelated directory in its place — what a local writer with
    /// access to the parent can do between the two commits. The unrelated
    /// `private.key` must survive, and the committed one must still go.
    #[cfg(unix)]
    #[test]
    fn keygen_rollback_removes_the_committed_key_not_a_substituted_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        let out = tmp.path().join("out");
        let unrelated = tmp.path().join("elsewhere");
        let moved_out = tmp.path().join("out.moved");
        fs::create_dir(&out).unwrap();
        fs::create_dir(&unrelated).unwrap();
        fs::write(unrelated.join(PRIVATE_KEY_FILENAME), b"unrelated key").unwrap();

        let private_key_path = out.join(PRIVATE_KEY_FILENAME);
        let public_key_path = out.join(PUBLIC_KEY_FILENAME);
        let private_tmp = staged_key_tempfile(&out, b"private bytes");
        let public_tmp = staged_key_tempfile(&out, b"public bytes");

        // Records that `private.key` really was committed before the
        // substitution, so the removal assertion below cannot pass just
        // because nothing was ever published.
        let committed_before_swap = std::rc::Rc::new(std::cell::Cell::new(false));
        let substitute_output_dir = {
            let (out, unrelated, moved_out) = (out.clone(), unrelated.clone(), moved_out.clone());
            let committed = committed_before_swap.clone();
            move |_: &crate::fs::atomic::OutputDir, _: &Path| -> std::io::Result<()> {
                committed.set(out.join(PRIVATE_KEY_FILENAME).exists());
                fs::rename(&out, &moved_out)?;
                std::os::unix::fs::symlink(&unrelated, &out)?;
                Err(std::io::Error::other("injected directory flush failure"))
            }
        };

        commit_key_pair_files_with_barrier(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &crate::fs::atomic::OutputDir::open(&out).unwrap(),
            substitute_output_dir,
        )
        .expect_err("the injected directory flush failure must fail the commit");

        assert!(
            committed_before_swap.get(),
            "the flush must run after private.key is committed, or this test proves nothing"
        );
        assert_eq!(
            fs::read(unrelated.join(PRIVATE_KEY_FILENAME)).unwrap(),
            b"unrelated key",
            "a same-named file in a substituted directory must not be removed"
        );
        assert!(
            !moved_out.join(PRIVATE_KEY_FILENAME).exists(),
            "the private.key this run committed must still be removed"
        );
    }

    /// A successful commit flushes the output directory after each key-file
    /// commit. The first flush must observe only `private.key`; the second must
    /// observe both files. This verifies the private-first order.
    #[test]
    fn keygen_commit_flushes_output_directory_after_each_commit() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path();
        let private_key_path = dir.join(PRIVATE_KEY_FILENAME);
        let public_key_path = dir.join(PUBLIC_KEY_FILENAME);
        let private_tmp = staged_key_tempfile(dir, b"private bytes");
        let public_tmp = staged_key_tempfile(dir, b"public bytes");
        let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));

        commit_key_pair_files_with_barrier(
            private_tmp,
            public_tmp,
            &private_key_path,
            &public_key_path,
            &crate::fs::atomic::OutputDir::open(dir).unwrap(),
            counting_barrier(None, seen.clone()),
        )
        .expect("commit must succeed when directory flushing succeeds");
        assert_eq!(
            *seen.borrow(),
            vec![
                BarrierCall {
                    dir: dir.to_path_buf(),
                    private_committed: true,
                    public_committed: false,
                },
                BarrierCall {
                    dir: dir.to_path_buf(),
                    private_committed: true,
                    public_committed: true,
                },
            ],
            "the output directory must be flushed after each of the two \
             commits, and private.key must commit before public.key"
        );
        assert_eq!(fs::read(&private_key_path).unwrap(), b"private bytes");
        assert_eq!(fs::read(&public_key_path).unwrap(), b"public bytes");
    }
}