ferrocrypt 0.3.0-beta.2

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
/// Integration tests for ferrocrypt library
mod common;

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

use ferrocrypt::secrecy::SecretString;
use ferrocrypt::{
    CryptoError, ENCRYPTED_EXTENSION, PublicKey, decode_recipient_string, probe_recipient_mode,
    validate_private_key_file,
};

use common::{generate_key_pair, passphrase_auto, recipient_auto};

const TEST_WORKSPACE: &str = "tests/workspace";

fn setup_test_dir(test_name: &str) -> PathBuf {
    let test_dir = PathBuf::from(TEST_WORKSPACE).join(test_name);
    if test_dir.exists() {
        fs::remove_dir_all(&test_dir).expect("Failed to clean test directory");
    }
    fs::create_dir_all(&test_dir).expect("Failed to create test directory");
    test_dir
}

fn create_test_file(path: &Path, content: &str) -> PathBuf {
    fs::write(path, content).expect("Failed to write test file");
    path.to_path_buf()
}

fn create_test_directory(base: &Path) -> PathBuf {
    let test_dir = base.join("test_folder");
    fs::create_dir_all(&test_dir).expect("Failed to create test directory");

    create_test_file(&test_dir.join("file1.txt"), "Content of file 1");
    create_test_file(&test_dir.join("file2.txt"), "Content of file 2");

    let subdir = test_dir.join("subdir");
    fs::create_dir_all(&subdir).expect("Failed to create subdirectory");
    create_test_file(&subdir.join("file3.txt"), "Content of file 3");

    test_dir
}

fn cleanup_test_workspace() {
    if Path::new(TEST_WORKSPACE).exists() {
        let _ = fs::remove_dir_all(TEST_WORKSPACE);
    }
}

#[test]
fn test_passphrase_encrypt_decrypt_single_file() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("passphrase_single_file");
    let input_file = test_dir.join("input.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let original_content = "This is a test file with sensitive data.";
    create_test_file(&input_file, original_content);

    let passphrase = SecretString::from("test_password_123".to_string());

    // Encrypt
    let encrypt_result =
        passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    assert!(encrypt_result.exists());
    assert!(encrypt_dir.join("input.fcr").exists());

    // Decrypt
    let decrypt_result = passphrase_auto(
        encrypt_dir.join("input.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    assert!(decrypt_result.exists());

    // Verify content
    let decrypted_content = fs::read_to_string(decrypt_dir.join("input.txt"))?;
    assert_eq!(original_content, decrypted_content);

    Ok(())
}

#[test]
fn test_passphrase_encrypt_decrypt_directory() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("passphrase_directory");
    let input_dir = create_test_directory(&test_dir);
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let passphrase = SecretString::from("directory_password".to_string());

    // Encrypt directory
    let encrypt_result =
        passphrase_auto(&input_dir, &encrypt_dir, &passphrase, None, None, |_| {})?;

    assert!(encrypt_result.exists());
    assert!(encrypt_dir.join("test_folder.fcr").exists());

    // Decrypt directory
    let decrypt_result = passphrase_auto(
        encrypt_dir.join("test_folder.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    assert!(decrypt_result.exists());

    // Verify directory structure and content
    let decrypted_dir = decrypt_dir.join("test_folder");
    assert!(decrypted_dir.exists());
    assert!(decrypted_dir.join("file1.txt").exists());
    assert!(decrypted_dir.join("file2.txt").exists());
    assert!(decrypted_dir.join("subdir/file3.txt").exists());

    let content1 = fs::read_to_string(decrypted_dir.join("file1.txt"))?;
    assert_eq!("Content of file 1", content1);

    let content3 = fs::read_to_string(decrypted_dir.join("subdir/file3.txt"))?;
    assert_eq!("Content of file 3", content3);

    Ok(())
}

#[test]
fn test_passphrase_wrong_password() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("passphrase_wrong_password");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Secret content");

    let correct_pass = SecretString::from("correct_password".to_string());
    let wrong_pass = SecretString::from("wrong_password".to_string());

    // Encrypt with correct password
    passphrase_auto(&input_file, &encrypt_dir, &correct_pass, None, None, |_| {})?;

    // Try to decrypt with wrong password - should fail
    let result = passphrase_auto(
        encrypt_dir.join("secret.fcr"),
        &decrypt_dir,
        &wrong_pass,
        None,
        None,
        |_| {},
    );

    assert!(result.is_err());
    match result {
        Err(CryptoError::RecipientUnwrapFailed { ref type_name }) if type_name == "argon2id" => {}
        other => panic!(
            "Expected RecipientUnwrapFailed {{ type_name: \"argon2id\" }}, got {:?}",
            other
        ),
    }

    Ok(())
}

/// Appending bytes to a finished `.fcr` file must fail closed at the
/// public API level. STREAM-BE32's per-chunk nonce binding rejects the
/// append as a tampered final chunk, so the user-visible variant is
/// `PayloadTampered`. The dedicated `ExtraDataAfterPayload` variant
/// covers the orthogonal "pathological reader signals EOF then yields
/// more bytes" case, which is unreachable through a path-based API
/// (`File`'s `Read` impl does not violate the trait contract that way)
/// — that branch is exercised by `streaming_aead_extra_data_after_final_chunk_rejected`
/// in `common.rs::tests` via a custom `Read` wrapper, and the
/// `From<io::Error>` mapping is locked in by
/// `stream_error_markers_map_to_typed_variants` in `error.rs::tests`.
/// Together these three tests form the regression coverage for the
/// trailing-data probe wiring; this integration test pins the
/// realistic file-with-appended-bytes shape through the public API.
#[test]
fn test_passphrase_appended_bytes_fail_closed_at_public_api() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("passphrase_appended_bytes");
    let input_file = test_dir.join("payload.bin");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // Multi-chunk plaintext so the final partial chunk is short and
    // the appended bytes land alongside it inside `decrypt_last`'s
    // input buffer (the realistic on-disk shape for an attacker
    // tacking bytes onto a finished `.fcr`).
    let big_data: Vec<u8> = (0..200_000u32).map(|i| (i % 256) as u8).collect();
    fs::write(&input_file, &big_data)?;

    let passphrase = SecretString::from("appended_pass".to_string());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("payload.fcr");
    let mut ct = fs::read(&encrypted_path)?;
    ct.extend_from_slice(b"garbage-appended-by-attacker");
    fs::write(&encrypted_path, &ct)?;

    match passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    ) {
        Err(CryptoError::PayloadTampered) => Ok(()),
        other => panic!("expected PayloadTampered for appended bytes, got {other:?}"),
    }
}

#[test]
fn test_passphrase_payload_tamper_mid_chunk() -> Result<(), CryptoError> {
    // Flipping a byte inside a ciphertext chunk (not the header) must
    // surface as PayloadTampered, not as a generic Io error.
    let test_dir = setup_test_dir("passphrase_payload_tamper");
    let input_file = test_dir.join("payload.bin");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // Big enough to span multiple AEAD chunks so the tamper lands well
    // past the header region.
    let big_data: Vec<u8> = (0..200_000u32).map(|i| (i % 256) as u8).collect();
    fs::write(&input_file, &big_data)?;

    let passphrase = SecretString::from("tamper_pass".to_string());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("payload.fcr");
    let mut ct = fs::read(&encrypted_path)?;
    // Flip a byte deep into the ciphertext, far past the header region.
    let flip_offset = ct.len() / 2;
    ct[flip_offset] ^= 0xFF;
    fs::write(&encrypted_path, &ct)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    match result {
        Err(CryptoError::PayloadTampered) => {}
        other => panic!("Expected PayloadTampered, got {:?}", other),
    }

    Ok(())
}

#[test]
fn test_passphrase_decrypt_delete_on_error_removes_incomplete_after_payload_tamper()
-> Result<(), CryptoError> {
    use ferrocrypt::{Decryptor, IncompleteOutputPolicy};

    let test_dir = setup_test_dir("decrypt_delete_on_error");
    let input_file = test_dir.join("payload.bin");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // Multi-chunk plaintext so the tamper-byte at ct.len()/2 lands
    // inside a non-first STREAM chunk. Earlier chunks succeed and
    // stream their bytes into `.incomplete`; the tampered chunk fails
    // mid-extract, so cleanup has to handle a partially-populated
    // `.incomplete` working tree.
    let big_data: Vec<u8> = (0..200_000u32).map(|i| (i % 256) as u8).collect();
    fs::write(&input_file, &big_data)?;

    let passphrase = SecretString::from("delete-pass".to_string());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("payload.fcr");
    let mut ct = fs::read(&encrypted_path)?;
    let flip_offset = ct.len() / 2;
    ct[flip_offset] ^= 0xFF;
    fs::write(&encrypted_path, &ct)?;

    let Decryptor::Passphrase(decryptor) = Decryptor::open(&encrypted_path)? else {
        panic!("expected passphrase-sealed file");
    };
    let result = decryptor
        .incomplete_output_policy(IncompleteOutputPolicy::DeleteOnError)
        .decrypt(passphrase, &decrypt_dir, |_| {});
    match result {
        Err(CryptoError::PayloadTampered) => {}
        other => panic!("expected PayloadTampered, got {other:?}"),
    }

    let working_path = decrypt_dir.join("payload.bin.incomplete");
    assert!(
        fs::symlink_metadata(&working_path).is_err(),
        "DeleteOnError must remove .incomplete; still present: {}",
        working_path.display()
    );
    let final_path = decrypt_dir.join("payload.bin");
    assert!(
        fs::symlink_metadata(&final_path).is_err(),
        "final name must not exist after a failed decrypt"
    );
    Ok(())
}

#[test]
fn test_passphrase_decrypt_retain_on_error_keeps_incomplete_after_payload_tamper()
-> Result<(), CryptoError> {
    use ferrocrypt::{Decryptor, IncompleteOutputPolicy};

    let test_dir = setup_test_dir("decrypt_retain_on_error");
    let input_file = test_dir.join("payload.bin");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let big_data: Vec<u8> = (0..200_000u32).map(|i| (i % 256) as u8).collect();
    fs::write(&input_file, &big_data)?;

    let passphrase = SecretString::from("retain-pass".to_string());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("payload.fcr");
    let mut ct = fs::read(&encrypted_path)?;
    let flip_offset = ct.len() / 2;
    ct[flip_offset] ^= 0xFF;
    fs::write(&encrypted_path, &ct)?;

    let Decryptor::Passphrase(decryptor) = Decryptor::open(&encrypted_path)? else {
        panic!("expected passphrase-sealed file");
    };
    let result = decryptor
        .incomplete_output_policy(IncompleteOutputPolicy::RetainOnError)
        .decrypt(passphrase, &decrypt_dir, |_| {});
    assert!(matches!(result, Err(CryptoError::PayloadTampered)));

    let working_path = decrypt_dir.join("payload.bin.incomplete");
    let meta = fs::symlink_metadata(&working_path).expect("RetainOnError must keep .incomplete");
    assert!(
        meta.is_file(),
        "expected staged file at {}",
        working_path.display()
    );
    Ok(())
}

#[test]
fn test_passphrase_decrypt_default_policy_removes_incomplete() -> Result<(), CryptoError> {
    use ferrocrypt::Decryptor;

    // Confirms the implicit default (no `.incomplete_output_policy`
    // call) matches `IncompleteOutputPolicy::DeleteOnError`.
    let test_dir = setup_test_dir("decrypt_default_policy");
    let input_file = test_dir.join("payload.bin");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let big_data: Vec<u8> = (0..200_000u32).map(|i| (i % 256) as u8).collect();
    fs::write(&input_file, &big_data)?;

    let passphrase = SecretString::from("default-pass".to_string());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("payload.fcr");
    let mut ct = fs::read(&encrypted_path)?;
    let flip_offset = ct.len() / 2;
    ct[flip_offset] ^= 0xFF;
    fs::write(&encrypted_path, &ct)?;

    let Decryptor::Passphrase(decryptor) = Decryptor::open(&encrypted_path)? else {
        panic!("expected passphrase-sealed file");
    };
    let result = decryptor.decrypt(passphrase, &decrypt_dir, |_| {});
    assert!(matches!(result, Err(CryptoError::PayloadTampered)));

    let working_path = decrypt_dir.join("payload.bin.incomplete");
    assert!(
        fs::symlink_metadata(&working_path).is_err(),
        "default policy must match DeleteOnError; still present: {}",
        working_path.display()
    );
    Ok(())
}

#[test]
fn test_passphrase_encrypt_decrypt_multi_chunk_file() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("passphrase_multi_chunk");
    let input_file = test_dir.join("multi_chunk.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let content = "Multi chunk content. ".repeat(500);
    create_test_file(&input_file, &content);

    let passphrase = SecretString::from("multi_chunk_password".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    assert!(encrypt_dir.join("multi_chunk.fcr").exists());

    passphrase_auto(
        encrypt_dir.join("multi_chunk.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    let decrypted_content = fs::read_to_string(decrypt_dir.join("multi_chunk.txt"))?;
    assert_eq!(content, decrypted_content);

    Ok(())
}

#[test]
fn test_recipient_keygen_rejects_empty_passphrase() {
    let test_dir = setup_test_dir("keygen_empty_pass");
    let empty = SecretString::from("".to_string());

    let err = generate_key_pair(&empty, &test_dir, |_| {}).unwrap_err();
    assert!(
        err.to_string().contains("empty"),
        "expected empty-passphrase error, got: {err}"
    );
}

/// M-3 regression: `PrivateKeyDecryptor::decrypt` must reject an empty
/// passphrase at the top of the function, before `open_x25519_private_key`
/// and any KDF work runs. Pre-restructure the hybrid path was a
/// consistency gap that let an empty passphrase burn an Argon2id cycle
/// on the private-key file before failing.
#[test]
fn test_recipient_decrypt_rejects_empty_passphrase_before_kdf() {
    use ferrocrypt::{Decryptor, Encryptor, PrivateKey, ProgressEvent, PublicKey};
    use ferrocrypt_test_support::fast_keypair_generator;
    use std::cell::Cell;

    let test_dir = setup_test_dir("recipient_decrypt_empty_pass");
    let keys_dir = test_dir.join("keys");
    fs::create_dir_all(&keys_dir).unwrap();

    // Build a real recipient `.fcr` so `Decryptor::open` returns the
    // `PrivateKey` variant. Setup events fire here, before we install
    // the observing closure.
    let setup_pass = SecretString::from("setup-pass".to_string());
    let kg = fast_keypair_generator(setup_pass)
        .write(&keys_dir, |_| {})
        .expect("generate fixture key pair");
    let input = test_dir.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let encrypted_dir = test_dir.join("encrypted");
    fs::create_dir_all(&encrypted_dir).unwrap();
    let outcome = Encryptor::with_public_key(PublicKey::from_key_file(&kg.public_key_path))
        .write(&input, &encrypted_dir, |_| {})
        .expect("encrypt fixture file");

    let restore_dir = test_dir.join("restored");
    fs::create_dir_all(&restore_dir).unwrap();
    let saw_kdf_event = Cell::new(false);
    let err = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::PrivateKey(d) => d
            .decrypt(
                PrivateKey::from_key_file(&kg.private_key_path),
                SecretString::from(String::new()),
                &restore_dir,
                |ev| {
                    if matches!(
                        ev,
                        ProgressEvent::UnlockingPrivateKey
                            | ProgressEvent::DerivingPassphraseWrapKey
                    ) {
                        saw_kdf_event.set(true);
                    }
                },
            )
            .unwrap_err(),
        other => panic!("expected PrivateKey decryptor, got {other:?}"),
    };

    assert!(
        err.to_string().contains("empty"),
        "expected empty-passphrase error, got: {err}"
    );
    assert!(
        !saw_kdf_event.get(),
        "no KDF event must fire before the empty-passphrase check"
    );
}

/// M-4 regression: `Encryptor::write` must reject a symlink input with
/// a typed `InvalidInput` error *before* kicking off Argon2id. Pre-audit
/// the rejection happened inside `archive::archive`, which runs after
/// the KDF — an accidental symlink cost the user seconds and up to 1 GiB
/// of RAM. Observes the `DerivingPassphraseWrapKey` progress event to
/// prove the rejection short-circuits the KDF path.
#[cfg(unix)]
#[test]
fn test_passphrase_encrypt_rejects_symlink_before_kdf() {
    use ferrocrypt::{Encryptor, ProgressEvent};
    use std::cell::Cell;
    use std::os::unix::fs::symlink;

    let test_dir = setup_test_dir("passphrase_encrypt_symlink");
    let target = create_test_file(&test_dir.join("real.txt"), "data");
    let link = test_dir.join("link.txt");
    symlink(&target, &link).expect("failed to create symlink");

    let output_dir = test_dir.join("out");
    fs::create_dir_all(&output_dir).unwrap();
    let passphrase = SecretString::from("pass".to_string());

    let saw_kdf_event = Cell::new(false);
    let err = Encryptor::with_passphrase(passphrase)
        .write(&link, &output_dir, |ev| {
            if matches!(ev, ProgressEvent::DerivingPassphraseWrapKey) {
                saw_kdf_event.set(true);
            }
        })
        .unwrap_err();

    match err {
        CryptoError::InvalidInput(ref msg) => {
            assert!(
                msg.contains("symlink"),
                "expected symlink error, got: {msg}"
            );
        }
        other => panic!("expected InvalidInput, got: {other:?}"),
    }
    assert!(
        !saw_kdf_event.get(),
        "no KDF event must fire before the symlink check"
    );
}

/// L-2 regression: on a successful public-key decrypt, `UnlockingPrivateKey`
/// fires before the private-key Argon2id runs and `Decrypting` fires only after
/// the envelope/HMAC checks pass (just before streaming unarchive). Pre-audit
/// the path emitted `Decrypting` immediately at the top of `hybrid::decrypt_file`
/// and never emitted any KDF event, so a UI would mislabel the multi-second KDF
/// window as "decrypting". (Post-#7: the legacy single `DerivingKey` event was
/// split into `UnlockingPrivateKey` for the `private.key` Argon2id boundary
/// and `DerivingPassphraseWrapKey` for the passphrase recipient.)
#[test]
fn test_recipient_decrypt_progress_events_in_order() -> Result<(), CryptoError> {
    use ferrocrypt::ProgressEvent;
    use std::sync::Mutex;

    let test_dir = setup_test_dir("recipient_decrypt_progress");
    let keys_dir = test_dir.join("keys");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let passphrase = SecretString::from("pass".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    let input_file = test_dir.join("data.txt");
    create_test_file(&input_file, "hybrid progress order");

    let public_key_path = keys_dir.join("public.key");
    recipient_auto(
        &input_file,
        &encrypt_dir,
        &public_key_path,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    let encrypted_path = encrypt_dir.join("data.fcr");
    let events: Mutex<Vec<ProgressEvent>> = Mutex::new(Vec::new());
    recipient_auto(
        &encrypted_path,
        &decrypt_dir,
        keys_dir.join("private.key"),
        &passphrase,
        None,
        None,
        |ev| events.lock().unwrap().push(*ev),
    )?;

    let events = events.into_inner().unwrap();
    let unlocking_at = events
        .iter()
        .position(|e| matches!(e, ProgressEvent::UnlockingPrivateKey));
    let decrypting_at = events
        .iter()
        .position(|e| matches!(e, ProgressEvent::Decrypting));
    let unlocking_at = unlocking_at.expect("UnlockingPrivateKey must fire on public-key decrypt");
    let decrypting_at = decrypting_at.expect("Decrypting must fire on public-key decrypt");
    assert!(
        unlocking_at < decrypting_at,
        "UnlockingPrivateKey ({unlocking_at}) must fire before Decrypting ({decrypting_at}); events: {events:?}"
    );
    // Recipient (X25519) decrypt MUST NOT fire `DerivingPassphraseWrapKey`
    // — that event belongs to the passphrase-recipient slot loop, not
    // to the X25519 unwrap path.
    assert!(
        !events
            .iter()
            .any(|e| matches!(e, ProgressEvent::DerivingPassphraseWrapKey)),
        "public-key decrypt must not emit DerivingPassphraseWrapKey; events: {events:?}"
    );

    Ok(())
}

/// Companion of `test_recipient_decrypt_progress_events_in_order` for
/// the passphrase mode: a successful passphrase encrypt followed by a
/// successful passphrase decrypt must emit exactly one
/// `DerivingPassphraseWrapKey` per operation (paired with `Encrypting`
/// or `Decrypting`), and zero `UnlockingPrivateKey` events at any
/// point — the passphrase path never opens a `private.key`. Pinned
/// after #7 to guarantee the work-boundary contract for the
/// passphrase recipient stays honest end to end.
#[test]
fn test_passphrase_decrypt_progress_events_in_order() -> Result<(), CryptoError> {
    use ferrocrypt::ProgressEvent;
    use std::sync::Mutex;

    let test_dir = setup_test_dir("passphrase_decrypt_progress");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let passphrase = SecretString::from("passphrase progress order".to_string());
    let input_file = test_dir.join("data.txt");
    create_test_file(&input_file, "passphrase progress order");

    let encrypt_events: Mutex<Vec<ProgressEvent>> = Mutex::new(Vec::new());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |ev| {
        encrypt_events.lock().unwrap().push(*ev)
    })?;

    let encrypted_path = encrypt_dir.join("data.fcr");
    let decrypt_events: Mutex<Vec<ProgressEvent>> = Mutex::new(Vec::new());
    passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |ev| decrypt_events.lock().unwrap().push(*ev),
    )?;

    let encrypt_events = encrypt_events.into_inner().unwrap();
    let decrypt_events = decrypt_events.into_inner().unwrap();

    let count =
        |evs: &[ProgressEvent], target: ProgressEvent| evs.iter().filter(|e| **e == target).count();

    assert_eq!(
        count(&encrypt_events, ProgressEvent::DerivingPassphraseWrapKey),
        1,
        "passphrase encrypt must emit exactly one DerivingPassphraseWrapKey; events: {encrypt_events:?}"
    );
    assert_eq!(
        count(&encrypt_events, ProgressEvent::UnlockingPrivateKey),
        0,
        "passphrase encrypt must not emit UnlockingPrivateKey; events: {encrypt_events:?}"
    );

    assert_eq!(
        count(&decrypt_events, ProgressEvent::DerivingPassphraseWrapKey),
        1,
        "passphrase decrypt must emit exactly one DerivingPassphraseWrapKey; events: {decrypt_events:?}"
    );
    assert_eq!(
        count(&decrypt_events, ProgressEvent::UnlockingPrivateKey),
        0,
        "passphrase decrypt must not emit UnlockingPrivateKey; events: {decrypt_events:?}"
    );

    let deriving_at = encrypt_events
        .iter()
        .position(|e| matches!(e, ProgressEvent::DerivingPassphraseWrapKey))
        .unwrap();
    let encrypting_at = encrypt_events
        .iter()
        .position(|e| matches!(e, ProgressEvent::Encrypting))
        .expect("Encrypting must fire");
    assert!(
        deriving_at < encrypting_at,
        "DerivingPassphraseWrapKey ({deriving_at}) must precede Encrypting ({encrypting_at}); events: {encrypt_events:?}"
    );

    let deriving_at = decrypt_events
        .iter()
        .position(|e| matches!(e, ProgressEvent::DerivingPassphraseWrapKey))
        .unwrap();
    let decrypting_at = decrypt_events
        .iter()
        .position(|e| matches!(e, ProgressEvent::Decrypting))
        .expect("Decrypting must fire");
    assert!(
        deriving_at < decrypting_at,
        "DerivingPassphraseWrapKey ({deriving_at}) must precede Decrypting ({decrypting_at}); events: {decrypt_events:?}"
    );

    Ok(())
}

/// Pure-X25519 encrypt MUST emit zero KDF events (no
/// `DerivingPassphraseWrapKey`, no `UnlockingPrivateKey`) — every
/// recipient is wrapped via X25519, which is sub-millisecond. Pre-#7
/// the orchestrator emitted a generic `DerivingKey` here, lying about
/// a multi-second pause that never happened.
#[test]
fn test_recipient_encrypt_emits_no_kdf_events() -> Result<(), CryptoError> {
    use ferrocrypt::ProgressEvent;
    use std::sync::Mutex;

    let test_dir = setup_test_dir("recipient_encrypt_no_kdf_events");
    let keys_dir = test_dir.join("keys");
    let encrypt_dir = test_dir.join("encrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;

    let passphrase = SecretString::from("pass".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    let input_file = test_dir.join("data.txt");
    create_test_file(&input_file, "x25519 encrypt no kdf events");

    let public_key_path = keys_dir.join("public.key");
    let events: Mutex<Vec<ProgressEvent>> = Mutex::new(Vec::new());
    recipient_auto(
        &input_file,
        &encrypt_dir,
        &public_key_path,
        &passphrase,
        None,
        None,
        |ev| events.lock().unwrap().push(*ev),
    )?;

    let events = events.into_inner().unwrap();
    assert!(
        !events
            .iter()
            .any(|e| matches!(e, ProgressEvent::DerivingPassphraseWrapKey)),
        "X25519 encrypt must not emit DerivingPassphraseWrapKey; events: {events:?}"
    );
    assert!(
        !events
            .iter()
            .any(|e| matches!(e, ProgressEvent::UnlockingPrivateKey)),
        "X25519 encrypt must not emit UnlockingPrivateKey; events: {events:?}"
    );
    assert!(
        events
            .iter()
            .any(|e| matches!(e, ProgressEvent::Encrypting)),
        "X25519 encrypt must emit Encrypting; events: {events:?}"
    );

    Ok(())
}

#[cfg(unix)]
#[test]
fn test_recipient_keygen_private_key_permissions() -> Result<(), CryptoError> {
    use std::os::unix::fs::PermissionsExt;

    let test_dir = setup_test_dir("keygen_permissions");
    let passphrase = SecretString::from("pass".to_string());

    generate_key_pair(&passphrase, &test_dir, |_| {})?;

    let private_key_path = test_dir.join("private.key");
    let pub_key = test_dir.join("public.key");
    let priv_mode = fs::metadata(&private_key_path)?.permissions().mode() & 0o777;
    let pub_mode = fs::metadata(&pub_key)?.permissions().mode() & 0o777;

    assert_eq!(priv_mode, 0o600, "private key should be owner-only");
    assert_ne!(pub_mode, 0o600, "public key should not be restricted");

    Ok(())
}

#[test]
fn test_recipient_keygen_encrypt_decrypt_file() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_full_workflow");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let original_content = "Hybrid encryption test data";
    create_test_file(&input_file, original_content);

    let key_passphrase = SecretString::from("key_protection_password".to_string());

    // Generate key pair
    let keygen_result = generate_key_pair(&key_passphrase, &keys_dir, |_| {})?;

    assert!(keygen_result.private_key_path.exists());
    assert!(keygen_result.public_key_path.exists());
    assert_eq!(keygen_result.fingerprint.len(), 64);

    // Encrypt with public key
    let pub_key_path = keys_dir.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    let encrypt_result = recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key_path,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    assert!(encrypt_result.exists());
    assert!(encrypt_dir.join("data.fcr").exists());

    // Decrypt with private key
    let private_key_path = keys_dir.join("private.key");

    let decrypt_result = recipient_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &private_key_path,
        &key_passphrase,
        None,
        None,
        |_| {},
    )?;

    assert!(decrypt_result.exists());

    // Verify content
    let decrypted_content = fs::read_to_string(decrypt_dir.join("data.txt"))?;
    assert_eq!(original_content, decrypted_content);

    Ok(())
}

#[test]
fn test_recipient_encrypt_decrypt_directory() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_directory");
    let keys_dir = test_dir.join("keys");
    let input_dir = create_test_directory(&test_dir);
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let key_passphrase = SecretString::from("hybrid_dir_key_pass".to_string());

    // Generate keys
    generate_key_pair(&key_passphrase, &keys_dir, |_| {})?;

    // Encrypt directory
    let pub_key_path = keys_dir.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    recipient_auto(
        &input_dir,
        &encrypt_dir,
        &pub_key_path,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    assert!(encrypt_dir.join("test_folder.fcr").exists());

    // Decrypt directory
    let private_key_path = keys_dir.join("private.key");

    recipient_auto(
        encrypt_dir.join("test_folder.fcr"),
        &decrypt_dir,
        &private_key_path,
        &key_passphrase,
        None,
        None,
        |_| {},
    )?;

    // Verify directory structure
    let decrypted_dir = decrypt_dir.join("test_folder");
    assert!(decrypted_dir.exists());
    assert!(decrypted_dir.join("file1.txt").exists());
    assert!(decrypted_dir.join("subdir/file3.txt").exists());

    Ok(())
}

#[test]
fn test_recipient_wrong_key_passphrase() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_wrong_passphrase");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Sensitive data");

    let correct_pass = SecretString::from("correct_key_pass".to_string());
    let wrong_pass = SecretString::from("wrong_key_pass".to_string());

    // Generate keys with correct passphrase
    generate_key_pair(&correct_pass, &keys_dir, |_| {})?;

    // Encrypt
    let pub_key_path = keys_dir.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key_path,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    // Try to decrypt with wrong passphrase for the private key file.
    // The passphrase protects the private key file itself, so a wrong
    // passphrase fails at the key-file unlock stage.
    let private_key_path = keys_dir.join("private.key");

    let result = recipient_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &private_key_path,
        &wrong_pass,
        None,
        None,
        |_| {},
    );

    assert!(result.is_err());
    match result {
        Err(CryptoError::KeyFileUnlockFailed) => {}
        other => panic!("Expected KeyFileUnlockFailed, got {:?}", other),
    }

    Ok(())
}

#[test]
fn test_empty_file_encryption() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("empty_file");
    let input_file = test_dir.join("empty.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // Create empty file
    create_test_file(&input_file, "");

    let passphrase = SecretString::from("empty_test".to_string());

    // Encrypt empty file
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    // Decrypt
    passphrase_auto(
        encrypt_dir.join("empty.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    // Verify empty file was preserved
    let decrypted_content = fs::read_to_string(decrypt_dir.join("empty.txt"))?;
    assert_eq!("", decrypted_content);

    Ok(())
}

#[test]
fn test_unicode_content() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("unicode_content");
    let input_file = test_dir.join("unicode.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let unicode_content = "Hello 世界! Привет мир! مرحبا بالعالم! 🔐🚀";
    create_test_file(&input_file, unicode_content);

    let passphrase = SecretString::from("unicode_pass".to_string());

    // Encrypt
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    // Decrypt
    passphrase_auto(
        encrypt_dir.join("unicode.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    // Verify unicode content
    let decrypted_content = fs::read_to_string(decrypt_dir.join("unicode.txt"))?;
    assert_eq!(unicode_content, decrypted_content);

    Ok(())
}

#[test]
fn test_special_characters_in_filename() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("special_filenames");
    let input_file = test_dir.join("file-with_special.chars.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Content with special filename");

    let passphrase = SecretString::from("special_pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    passphrase_auto(
        encrypt_dir.join("file-with_special.chars.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    assert!(decrypt_dir.join("file-with_special.chars.txt").exists());

    Ok(())
}

#[test]
fn test_nonexistent_output_dir() {
    let passphrase = SecretString::from("test".to_string());

    let result = passphrase_auto(
        "Cargo.toml",
        "/nonexistent/path/output",
        &passphrase,
        None,
        None,
        |_| {},
    );

    assert!(result.is_err());
}

#[test]
fn test_decrypt_nonexistent_fcr_file() {
    let test_dir = setup_test_dir("decrypt_nonexistent");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&decrypt_dir).unwrap();

    let passphrase = SecretString::from("test".to_string());

    let result = passphrase_auto(
        "/nonexistent/missing.fcr",
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );

    assert!(result.is_err());
}

#[test]
fn test_binary_file_content() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("binary_content");
    let input_file = test_dir.join("data.bin");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // Binary data with null bytes and all byte values
    let binary_content: Vec<u8> = (0..=255).cycle().take(1024).collect();
    fs::write(&input_file, &binary_content)?;

    let passphrase = SecretString::from("binary_pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    passphrase_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    let decrypted = fs::read(decrypt_dir.join("data.bin"))?;
    assert_eq!(binary_content, decrypted);

    Ok(())
}

#[test]
fn test_passphrase_streaming_wrong_password() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("streaming_wrong_password");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let content = "Large mode wrong password test. ".repeat(100);
    create_test_file(&input_file, &content);

    let correct_pass = SecretString::from("correct".to_string());
    let wrong_pass = SecretString::from("wrong".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &correct_pass, None, None, |_| {})?;

    // Decrypt with wrong password
    let result = passphrase_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &wrong_pass,
        None,
        None,
        |_| {},
    );

    assert!(result.is_err());
    match result {
        Err(CryptoError::RecipientUnwrapFailed { ref type_name }) if type_name == "argon2id" => {}
        other => panic!(
            "Expected RecipientUnwrapFailed {{ type_name: \"argon2id\" }}, got {:?}",
            other
        ),
    }

    Ok(())
}

#[test]
fn test_passphrase_encrypt_decrypt_directory_streaming() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("directory_streaming");
    let input_dir = create_test_directory(&test_dir);
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let passphrase = SecretString::from("dir_streaming_pass".to_string());

    passphrase_auto(&input_dir, &encrypt_dir, &passphrase, None, None, |_| {})?;

    assert!(encrypt_dir.join("test_folder.fcr").exists());

    passphrase_auto(
        encrypt_dir.join("test_folder.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    let decrypted_dir = decrypt_dir.join("test_folder");
    assert!(decrypted_dir.exists());
    assert_eq!(
        fs::read_to_string(decrypted_dir.join("file1.txt"))?,
        "Content of file 1"
    );
    assert_eq!(
        fs::read_to_string(decrypted_dir.join("subdir/file3.txt"))?,
        "Content of file 3"
    );

    Ok(())
}

#[test]
fn test_passphrase_empty_password_rejected() {
    let test_dir = setup_test_dir("empty_password");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");

    fs::create_dir_all(&encrypt_dir).unwrap();
    create_test_file(&input_file, "Protected with empty password");

    let empty_pass = SecretString::from("".to_string());

    let result = passphrase_auto(&input_file, &encrypt_dir, &empty_pass, None, None, |_| {});

    assert!(result.is_err());
    match result {
        Err(CryptoError::InvalidInput(msg)) => {
            assert!(msg.contains("empty"));
        }
        other => panic!(
            "Expected Message error about empty passphrase, got {:?}",
            other
        ),
    }
}

#[test]
fn test_recipient_wrong_key_pair() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_wrong_keypair");
    let keys_a = test_dir.join("keys_a");
    let keys_b = test_dir.join("keys_b");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_a)?;
    fs::create_dir_all(&keys_b)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Sensitive data");

    let pass_a = SecretString::from("pass_a".to_string());
    let pass_b = SecretString::from("pass_b".to_string());

    // Generate two different key pairs
    generate_key_pair(&pass_a, &keys_a, |_| {})?;
    generate_key_pair(&pass_b, &keys_b, |_| {})?;

    // Encrypt with key pair A's public key
    let pub_key_a = keys_a.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key_a,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    // Decrypt with key pair B's private key. private.key unlocks fine
    // (right passphrase), but every x25519 slot AEAD-fails because
    // ECDH was performed against A's public key. List exhaustion
    // surfaces as `NoSupportedRecipient`.
    let private_key_b = keys_b.join("private.key");

    let result = recipient_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &private_key_b,
        &pass_b,
        None,
        None,
        |_| {},
    );

    match result {
        Err(CryptoError::NoSupportedRecipient) => {}
        other => panic!("Expected NoSupportedRecipient, got {:?}", other),
    }

    Ok(())
}

#[test]
fn test_recipient_key_round_trip() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_key_round_trip");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let original_content = "X25519 round-trip test";
    create_test_file(&input_file, original_content);

    let key_passphrase = SecretString::from("keypass".to_string());

    generate_key_pair(&key_passphrase, &keys_dir, |_| {})?;

    // Encrypt
    let pub_key_path = keys_dir.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key_path,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    assert!(encrypt_dir.join("data.fcr").exists());

    // Decrypt
    let private_key_path = keys_dir.join("private.key");

    recipient_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &private_key_path,
        &key_passphrase,
        None,
        None,
        |_| {},
    )?;

    let decrypted_content = fs::read_to_string(decrypt_dir.join("data.txt"))?;
    assert_eq!(original_content, decrypted_content);

    Ok(())
}

#[test]
fn test_recipient_binary_file() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_binary");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("data.bin");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let binary_content: Vec<u8> = (0..=255).cycle().take(2048).collect();
    fs::write(&input_file, &binary_content)?;

    let key_passphrase = SecretString::from("hybrid_bin_pass".to_string());
    generate_key_pair(&key_passphrase, &keys_dir, |_| {})?;

    let pub_key_path = keys_dir.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key_path,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    let private_key_path = keys_dir.join("private.key");

    recipient_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &private_key_path,
        &key_passphrase,
        None,
        None,
        |_| {},
    )?;

    let decrypted = fs::read(decrypt_dir.join("data.bin"))?;
    assert_eq!(binary_content, decrypted);

    Ok(())
}

#[test]
fn test_nonexistent_input_path_encrypt() {
    let test_dir = setup_test_dir("nonexistent_input_encrypt");
    let encrypt_dir = test_dir.join("encrypted");
    fs::create_dir_all(&encrypt_dir).unwrap();

    let passphrase = SecretString::from("test".to_string());

    let result = passphrase_auto(
        "/nonexistent/path/file.txt",
        &encrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );

    assert!(result.is_err());
    match result {
        Err(CryptoError::InputPath) => {}
        other => panic!("Expected InputPath error, got {:?}", other),
    }
}

#[test]
fn test_truncated_passphrase_file() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("truncated_passphrase");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // Encrypt a real file, then truncate so the header prefix is intact
    // (magic bytes detected) but the rest of the header is missing.
    let input_file = test_dir.join("data.txt");
    create_test_file(&input_file, "truncation test data");
    let passphrase = SecretString::from("test".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("data.fcr");
    let data = fs::read(&encrypted_path)?;

    // Keep only 30 bytes: enough for the 27-byte encoded prefix but not a full header
    let truncated = &data[..30];
    fs::write(&encrypted_path, truncated)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());

    Ok(())
}

#[test]
fn test_truncated_recipient_file() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("truncated_recipient");
    let keys_dir = test_dir.join("keys");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let key_passphrase = SecretString::from("pass".to_string());
    generate_key_pair(&key_passphrase, &keys_dir, |_| {})?;

    let public_key = keys_dir.join("public.key");
    let private_key_path = keys_dir.join("private.key");

    // Encrypt a real file, then truncate so the header prefix is intact
    // (magic bytes detected) but the rest of the header is missing.
    let input_file = test_dir.join("data.txt");
    create_test_file(&input_file, "truncation test");
    let empty_pass = SecretString::from("".to_string());
    recipient_auto(
        &input_file,
        &encrypt_dir,
        &public_key,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    let encrypted_path = encrypt_dir.join("data.fcr");
    let data = fs::read(&encrypted_path)?;
    let truncated = &data[..30];
    fs::write(&encrypted_path, truncated)?;

    let result = recipient_auto(
        &encrypted_path,
        &decrypt_dir,
        &private_key_path,
        &key_passphrase,
        None,
        None,
        |_| {},
    );

    assert!(result.is_err());

    Ok(())
}

#[test]
fn test_passphrase_header_tamper_detection() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("passphrase_tamper");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Tamper detection test");

    let passphrase = SecretString::from("tamper_pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    // Flip one byte in the authenticated stream_nonce. The recipient
    // body still unwraps, but the header MAC no longer matches, so
    // decrypt must fail at the post-unwrap tamper check.
    // stream_nonce sits inside HEADER_FIXED at offset 12 (after
    // header_flags(2) + recipient_count(2) + recipient_entries_len(4)
    // + ext_len(4)); file offset = PREFIX_SIZE(12) + 12 = 24.
    let encrypted_path = encrypt_dir.join("secret.fcr");
    let mut data = fs::read(&encrypted_path)?;
    const NONCE_OFFSET: usize = 12 + 12;
    data[NONCE_OFFSET] ^= 0xFF;
    fs::write(&encrypted_path, &data)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );

    match result {
        Err(CryptoError::HeaderTampered) => {}
        other => panic!("expected HeaderTampered, got {other:?}"),
    }

    Ok(())
}

#[test]
fn test_recipient_header_tamper_detection() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_tamper");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Hybrid tamper test");

    let key_passphrase = SecretString::from("tamper_key_pass".to_string());
    generate_key_pair(&key_passphrase, &keys_dir, |_| {})?;

    let pub_key_path = keys_dir.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key_path,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    // Flip one byte in the authenticated stream_nonce. The x25519
    // recipient body can still unwrap, but the header MAC must fail
    // afterwards. stream_nonce sits inside HEADER_FIXED at offset 12;
    // file offset = PREFIX_SIZE(12) + 12 = 24. For a single-recipient
    // recipient file the post-unwrap MAC failure surfaces as
    // `HeaderMacFailedAfterUnwrap` per FORMAT.md §3.7 (the loop's
    // per-candidate variant; the loop has no further candidates).
    let encrypted_path = encrypt_dir.join("secret.fcr");
    let mut data = fs::read(&encrypted_path)?;
    const NONCE_OFFSET: usize = 12 + 12;
    data[NONCE_OFFSET] ^= 0xFF;
    fs::write(&encrypted_path, &data)?;

    let private_key_path = keys_dir.join("private.key");

    let result = recipient_auto(
        &encrypted_path,
        &decrypt_dir,
        &private_key_path,
        &key_passphrase,
        None,
        None,
        |_| {},
    );

    match result {
        Err(CryptoError::HeaderMacFailedAfterUnwrap { ref type_name }) if type_name == "x25519" => {
        }
        Err(CryptoError::HeaderTampered) => {}
        Err(CryptoError::NoSupportedRecipient) => {}
        other => {
            panic!("expected HeaderMacFailedAfterUnwrap(x25519) or HeaderTampered, got {other:?}")
        }
    }

    Ok(())
}

/// Any flip in the 12-byte prefix MUST be caught at structural parse
/// before any cryptographic work runs. Pins the version-byte case so
/// a future change that softens the prefix parse fails the regression.
#[test]
fn test_passphrase_prefix_byte_tamper_detected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("passphrase_prefix_byte_tamper");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Prefix tamper test");

    let passphrase = SecretString::from("prefix_tamper_pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    // Flip the version byte (offset 4 in the 12-byte prefix) so the
    // file claims an unsupported version. v1 readers must reject
    // before any recipient unwrap or KDF work runs.
    let encrypted_path = encrypt_dir.join("secret.fcr");
    let mut data = fs::read(&encrypted_path)?;
    data[4] ^= 0x10;
    fs::write(&encrypted_path, &data)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );

    match result {
        Err(CryptoError::UnsupportedVersion(_)) | Err(CryptoError::InvalidFormat(_)) => {}
        other => panic!(
            "expected UnsupportedVersion or InvalidFormat for tampered version byte, got {other:?}"
        ),
    }

    Ok(())
}

#[test]
fn test_non_ferrocrypt_fcr_file_can_be_encrypted() {
    let test_dir = setup_test_dir("not_ferrocrypt");
    let fake_file = test_dir.join("photo.fcr");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir).unwrap();
    fs::create_dir_all(&decrypt_dir).unwrap();

    // A JPEG header renamed to .fcr — routing by magic bytes only means
    // this is treated as a normal file and can be encrypted.
    let content = b"\xFF\xD8\xFF\xE0fake jpeg data padding!!";
    fs::write(&fake_file, content).unwrap();

    let passphrase = SecretString::from("test".to_string());
    let result = passphrase_auto(&fake_file, &encrypt_dir, &passphrase, None, None, |_| {});
    assert!(
        result.is_ok(),
        "Expected encryption to succeed, got: {:?}",
        result
    );

    // Verify round-trip: decrypt the encrypted file and compare
    let encrypted_path = encrypt_dir.join("photo.fcr");
    assert!(encrypted_path.exists());

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_ok());

    let decrypted = fs::read(decrypt_dir.join("photo.fcr")).unwrap();
    assert_eq!(decrypted, content);
}

#[test]
fn test_wrong_format_type_recipient_as_passphrase() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("wrong_format_type");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "format type test");
    let key_passphrase = SecretString::from("pass".to_string());
    generate_key_pair(&key_passphrase, &keys_dir, |_| {})?;

    // Encrypt as recipient (x25519)
    let pub_key_path = keys_dir.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key_path,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    // Try to decrypt a recipient `.fcr` file via the passphrase path — format type mismatch
    let encrypted_path = encrypt_dir.join("data.fcr");
    let passphrase = SecretString::from("pass".to_string());
    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );

    // v1 has no per-file mode byte: a file's mode is derived from its
    // recipient list (one `argon2id` => `Passphrase`; one or more
    // `x25519` => `PrivateKey`). Asking `passphrase_auto` to decrypt a
    // recipient file therefore fails because the recipient list
    // contains no `argon2id` slot the passphrase path could unwrap.
    // Per `FORMAT.md` §3.4 / §3.5 the canonical surfaced error is
    // `NoSupportedRecipient`, but `RecipientUnwrapFailed` /
    // `IncompatibleRecipients` are also acceptable depending on the
    // implementation's iteration order.
    assert!(result.is_err());
    match &result {
        Err(CryptoError::NoSupportedRecipient)
        | Err(CryptoError::IncompatibleRecipients { .. })
        | Err(CryptoError::RecipientUnwrapFailed { .. })
        | Err(CryptoError::InvalidFormat(_)) => {}
        other => panic!("Expected mode-mismatch rejection, got {:?}", other),
    }

    Ok(())
}

#[test]
fn test_recipient_empty_file() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_empty_file");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("empty.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "");
    let key_passphrase = SecretString::from("hybrid_empty".to_string());
    generate_key_pair(&key_passphrase, &keys_dir, |_| {})?;

    let pub_key = keys_dir.join("public.key");
    let empty_pass = SecretString::from("".to_string());

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    let private_key_path = keys_dir.join("private.key");

    recipient_auto(
        encrypt_dir.join("empty.fcr"),
        &decrypt_dir,
        &private_key_path,
        &key_passphrase,
        None,
        None,
        |_| {},
    )?;

    let decrypted = fs::read_to_string(decrypt_dir.join("empty.txt"))?;
    assert_eq!("", decrypted);

    Ok(())
}

#[test]
fn test_two_encryptions_produce_different_output() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("nonce_uniqueness");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir_a = test_dir.join("encrypted_a");
    let encrypt_dir_b = test_dir.join("encrypted_b");

    fs::create_dir_all(&encrypt_dir_a)?;
    fs::create_dir_all(&encrypt_dir_b)?;

    create_test_file(&input_file, "Same content encrypted twice");
    let passphrase = SecretString::from("same_pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir_a, &passphrase, None, None, |_| {})?;

    passphrase_auto(&input_file, &encrypt_dir_b, &passphrase, None, None, |_| {})?;

    let file_a = fs::read(encrypt_dir_a.join("data.fcr"))?;
    let file_b = fs::read(encrypt_dir_b.join("data.fcr"))?;

    // Same plaintext + same password must produce different ciphertext (unique salt + nonce)
    assert_ne!(file_a, file_b);

    Ok(())
}

#[test]
fn test_passphrase_output_file_override() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("passphrase_output_file_override");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "custom output path test");
    let passphrase = SecretString::from("test_password_123".to_string());

    let custom_output = encrypt_dir.join("custom_name.fcr");
    let result = passphrase_auto(
        &input_file,
        &encrypt_dir,
        &passphrase,
        Some(custom_output.as_path()),
        None,
        |_| {},
    )?;

    assert_eq!(result, custom_output);
    assert!(custom_output.exists());
    // Default name should not exist
    assert!(!encrypt_dir.join("data.fcr").exists());

    // Decrypt the custom-named file
    let decrypt_result = passphrase_auto(
        &custom_output,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    assert!(decrypt_result.exists());
    let content = fs::read_to_string(decrypt_dir.join("data.txt"))?;
    assert_eq!("custom output path test", content);

    Ok(())
}

#[test]
fn test_recipient_output_file_override() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_output_file_override");
    let input_file = test_dir.join("data.txt");
    let key_dir = test_dir.join("keys");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");

    fs::create_dir_all(&key_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "hybrid custom output test");
    let passphrase = SecretString::from("key_pass_123".to_string());

    generate_key_pair(&passphrase, &key_dir, |_| {})?;

    let pub_key = key_dir.join("public.key");
    let private_key_path = key_dir.join("private.key");
    let custom_output = encrypt_dir.join("my_vault.fcr");
    let empty = SecretString::from("".to_string());

    let result = recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key,
        &empty,
        Some(custom_output.as_path()),
        None,
        |_| {},
    )?;

    assert_eq!(result, custom_output);
    assert!(custom_output.exists());
    assert!(!encrypt_dir.join("data.fcr").exists());

    // Decrypt the custom-named file
    let decrypt_result = recipient_auto(
        &custom_output,
        &decrypt_dir,
        &private_key_path,
        &passphrase,
        None,
        None,
        |_| {},
    )?;

    assert!(decrypt_result.exists());
    let content = fs::read_to_string(decrypt_dir.join("data.txt"))?;
    assert_eq!("hybrid custom output test", content);

    Ok(())
}

#[test]
fn test_output_file_none_uses_default_name() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("output_file_none_default");
    let input_file = test_dir.join("report.txt");
    let encrypt_dir = test_dir.join("encrypted");

    fs::create_dir_all(&encrypt_dir)?;

    create_test_file(&input_file, "default naming test");
    let passphrase = SecretString::from("test_password_123".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let expected = encrypt_dir.join(format!("report.{}", ENCRYPTED_EXTENSION));
    assert!(expected.exists());

    Ok(())
}

// ---------------------------------------------------------------------------
// Malformed-header tests
// ---------------------------------------------------------------------------

#[test]
fn test_passphrase_empty_file_rejected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("pass_empty_file");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // Encrypt a real file, then replace its content with just the prefix
    // (enough for magic-byte detection) but no actual header payload.
    let input_file = test_dir.join("data.txt");
    create_test_file(&input_file, "payload");
    let passphrase = SecretString::from("test".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("data.fcr");
    let data = fs::read(&encrypted_path)?;

    // Keep only the 27-byte encoded prefix — enough for detection, no payload
    let prefix_only = &data[..27];
    fs::write(&encrypted_path, prefix_only)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());

    Ok(())
}

#[test]
fn test_recipient_empty_file_rejected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("rec_empty_file");
    let keys_dir = test_dir.join("keys");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let key_pass = SecretString::from("kp".to_string());
    generate_key_pair(&key_pass, &keys_dir, |_| {})?;

    let public_key = keys_dir.join("public.key");
    let private_key_path = keys_dir.join("private.key");

    // Encrypt a real file, then truncate to prefix-only so magic-byte
    // detection routes to decrypt, which then fails on the empty payload.
    let input_file = test_dir.join("data.txt");
    create_test_file(&input_file, "payload");
    let empty_pass = SecretString::from("".to_string());
    recipient_auto(
        &input_file,
        &encrypt_dir,
        &public_key,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    let encrypted_path = encrypt_dir.join("data.fcr");
    let data = fs::read(&encrypted_path)?;
    let prefix_only = &data[..27];
    fs::write(&encrypted_path, prefix_only)?;

    let result = recipient_auto(
        &encrypted_path,
        &decrypt_dir,
        &private_key_path,
        &key_pass,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());
    Ok(())
}

#[test]
fn test_passphrase_truncated_mid_header() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("pass_truncated_mid_header");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Truncation mid-header test");
    let passphrase = SecretString::from("pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("secret.fcr");
    let data = fs::read(&encrypted_path)?;

    // Truncate after the 27-byte encoded prefix (enough for magic-byte detection)
    // but before the header ends — in the middle of the salt field
    let truncated = &data[..30];
    fs::write(&encrypted_path, truncated)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());
    Ok(())
}

#[test]
fn test_passphrase_oversized_ext_len() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("pass_oversized_ext_len");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Oversized ext_len test");
    let passphrase = SecretString::from("pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    // Set ext_len to 0xFFFF in all 3 replicated copies of the prefix.
    // Encoded prefix: [pad(3)] [copy0(8)] [copy1(8)] [copy2(8)]
    // ext_len lives at offsets 6..=7 inside each 8-byte copy.
    let encrypted_path = encrypt_dir.join("secret.fcr");
    let mut data = fs::read(&encrypted_path)?;
    const EXT_HI: usize = 6;
    const EXT_LO: usize = 7;
    for copy_start in [3, 11, 19] {
        data[copy_start + EXT_HI] = 0xFF;
        data[copy_start + EXT_LO] = 0xFF;
    }
    fs::write(&encrypted_path, &data)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());
    Ok(())
}

#[test]
fn test_recipient_truncated_mid_header() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("rec_truncated_mid_header");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let key_pass = SecretString::from("kp".to_string());
    generate_key_pair(&key_pass, &keys_dir, |_| {})?;

    let pub_key = keys_dir.join("public.key");
    let private_key_path = keys_dir.join("private.key");
    let empty_pass = SecretString::from("".to_string());

    create_test_file(&input_file, "Hybrid truncation mid-header");

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    let encrypted_path = encrypt_dir.join("secret.fcr");
    let data = fs::read(&encrypted_path)?;

    // Truncate after the 27-byte encoded prefix (enough for magic-byte detection)
    // but before the header ends — in the middle of the envelope field
    let truncated = &data[..30];
    fs::write(&encrypted_path, truncated)?;

    let result = recipient_auto(
        &encrypted_path,
        &decrypt_dir,
        &private_key_path,
        &key_pass,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());

    Ok(())
}

#[test]
fn test_recipient_oversized_ext_len() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("rec_oversized_ext_len");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let key_pass = SecretString::from("kp".to_string());
    generate_key_pair(&key_pass, &keys_dir, |_| {})?;

    let pub_key = keys_dir.join("public.key");
    let private_key_path = keys_dir.join("private.key");
    let empty_pass = SecretString::from("".to_string());

    create_test_file(&input_file, "Hybrid oversized ext_len");

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    // Set ext_len to 0xFFFF in all 3 replicated copies of the prefix.
    // ext_len lives at offsets 6..=7 inside each 8-byte copy.
    let encrypted_path = encrypt_dir.join("secret.fcr");
    let mut data = fs::read(&encrypted_path)?;
    const EXT_HI: usize = 6;
    const EXT_LO: usize = 7;
    for copy_start in [3, 11, 19] {
        data[copy_start + EXT_HI] = 0xFF;
        data[copy_start + EXT_LO] = 0xFF;
    }
    fs::write(&encrypted_path, &data)?;

    let result = recipient_auto(
        &encrypted_path,
        &decrypt_dir,
        &private_key_path,
        &key_pass,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());

    Ok(())
}

// ---------------------------------------------------------------------------
// Ciphertext mutation tests
// ---------------------------------------------------------------------------

#[test]
fn test_passphrase_ciphertext_bit_flip_detected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("pass_ciphertext_flip");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "AEAD ciphertext integrity test");
    let passphrase = SecretString::from("ct_flip_pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("secret.fcr");
    let mut data = fs::read(&encrypted_path)?;

    // Flip a byte well past the header, in the ciphertext body
    let flip_offset = data.len() - 10;
    data[flip_offset] ^= 0xFF;
    fs::write(&encrypted_path, &data)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());
    Ok(())
}

#[test]
fn test_recipient_ciphertext_bit_flip_detected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("rec_ciphertext_flip");
    let keys_dir = test_dir.join("keys");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let key_pass = SecretString::from("ct_flip_key".to_string());
    generate_key_pair(&key_pass, &keys_dir, |_| {})?;

    let pub_key = keys_dir.join("public.key");
    let private_key_path = keys_dir.join("private.key");
    let empty_pass = SecretString::from("".to_string());

    create_test_file(&input_file, "Hybrid AEAD ciphertext integrity test");

    recipient_auto(
        &input_file,
        &encrypt_dir,
        &pub_key,
        &empty_pass,
        None,
        None,
        |_| {},
    )?;

    let encrypted_path = encrypt_dir.join("secret.fcr");
    let mut data = fs::read(&encrypted_path)?;

    // Flip a byte in the ciphertext body (well past the header)
    let flip_offset = data.len() - 10;
    data[flip_offset] ^= 0xFF;
    fs::write(&encrypted_path, &data)?;

    let result = recipient_auto(
        &encrypted_path,
        &decrypt_dir,
        &private_key_path,
        &key_pass,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());
    Ok(())
}

#[test]
fn test_passphrase_ciphertext_truncation_detected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("pass_ciphertext_trunc");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // Use enough data to span multiple 64 KiB chunks
    let content = "A".repeat(128 * 1024);
    create_test_file(&input_file, &content);
    let passphrase = SecretString::from("trunc_pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("secret.fcr");
    let data = fs::read(&encrypted_path)?;

    // Truncate after the first ciphertext chunk but before the final chunk
    let half = data.len() / 2;
    fs::write(&encrypted_path, &data[..half])?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());
    Ok(())
}

#[test]
fn test_passphrase_ciphertext_appended_bytes_detected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("pass_ciphertext_append");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_file, "Append detection test");
    let passphrase = SecretString::from("append_pass".to_string());

    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("secret.fcr");
    let mut data = fs::read(&encrypted_path)?;

    // Append extra bytes after the ciphertext
    data.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
    fs::write(&encrypted_path, &data)?;

    let result = passphrase_auto(
        &encrypted_path,
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());
    Ok(())
}

#[test]
fn test_public_key_fingerprint() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("fingerprint");
    let keys_dir = test_dir.join("keys");
    fs::create_dir_all(&keys_dir)?;

    let passphrase = SecretString::from("fp_test_pass".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    let pub_key = keys_dir.join("public.key");
    let fp = PublicKey::from_key_file(&pub_key).fingerprint()?;

    assert_eq!(fp.len(), 64);
    assert!(fp.chars().all(|c| c.is_ascii_hexdigit()));

    // Deterministic: same key always produces the same fingerprint
    let fp2 = PublicKey::from_key_file(&pub_key).fingerprint()?;
    assert_eq!(fp, fp2);

    // Rejects private key files
    let private_key_path = keys_dir.join("private.key");
    assert!(
        PublicKey::from_key_file(&private_key_path)
            .fingerprint()
            .is_err()
    );

    Ok(())
}

#[test]
fn test_different_keys_different_fingerprints() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("fingerprint_diff");
    let keys_a = test_dir.join("keys_a");
    let keys_b = test_dir.join("keys_b");
    fs::create_dir_all(&keys_a)?;
    fs::create_dir_all(&keys_b)?;

    let passphrase = SecretString::from("fp_diff_pass".to_string());
    generate_key_pair(&passphrase, &keys_a, |_| {})?;
    generate_key_pair(&passphrase, &keys_b, |_| {})?;

    let fp_a = PublicKey::from_key_file(keys_a.join("public.key")).fingerprint()?;
    let fp_b = PublicKey::from_key_file(keys_b.join("public.key")).fingerprint()?;

    assert_ne!(fp_a, fp_b);

    Ok(())
}

/// `PublicKey::validate` succeeds on a well-formed key file, succeeds
/// unconditionally on the bytes source, and fails with a structural
/// error (not a panic) when pointed at a file that does not exist.
#[test]
fn test_public_key_validate() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("public_key_validate");
    let keys_dir = test_dir.join("keys");
    fs::create_dir_all(&keys_dir)?;

    let passphrase = SecretString::from("vp".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    // Valid file: validate passes.
    PublicKey::from_key_file(keys_dir.join("public.key")).validate()?;

    // Raw bytes: `from_bytes` already structurally rejects degenerate
    // (e.g. all-zero) inputs at construction, so any successfully
    // constructed `PublicKey::from_bytes` value passes `validate()`.
    PublicKey::from_bytes([0xAB; 32])?.validate()?;

    // Nonexistent file: validate returns an I/O error, not a panic.
    let missing = keys_dir.join("does_not_exist.key");
    assert!(PublicKey::from_key_file(&missing).validate().is_err());

    // Pointing at a private-key file: the public-key parser rejects the
    // wrong key-file kind instead of leaking secret material.
    let private_key_path = keys_dir.join("private.key");
    assert!(
        PublicKey::from_key_file(&private_key_path)
            .validate()
            .is_err()
    );

    Ok(())
}

/// The `FromStr` impl routes through `PublicKey::from_recipient_string`,
/// so `"fcr1…".parse::<PublicKey>()` must accept a valid recipient
/// string and round-trip back through `to_recipient_string`, and must
/// reject Bech32 with the wrong HRP.
#[test]
fn test_public_key_from_str_round_trip() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("public_key_from_str");
    let keys_dir = test_dir.join("keys");
    fs::create_dir_all(&keys_dir)?;

    let passphrase = SecretString::from("fs".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    let encoded = PublicKey::from_key_file(keys_dir.join("public.key")).to_recipient_string()?;
    let parsed: PublicKey = encoded
        .parse()
        .expect("valid recipient string must parse via FromStr");
    assert_eq!(parsed.to_recipient_string()?, encoded);

    // Wrong HRP must fail to parse.
    let wrong_hrp =
        bech32::encode::<bech32::Bech32>(bech32::Hrp::parse_unchecked("age"), &[0xCC; 32]).unwrap();
    assert!(wrong_hrp.parse::<PublicKey>().is_err());

    Ok(())
}

#[cfg(unix)]
#[test]
fn test_passphrase_encrypt_cleans_up_on_failure() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("pass_encrypt_cleanup");
    let real_file = test_dir.join("real.txt");
    let symlink_path = test_dir.join("link.txt");
    let encrypt_dir = test_dir.join("encrypted");
    fs::create_dir_all(&encrypt_dir)?;
    create_test_file(&real_file, "target content");
    std::os::unix::fs::symlink(&real_file, &symlink_path).unwrap();

    let passphrase = SecretString::from("cleanup_pass".to_string());
    let result = passphrase_auto(&symlink_path, &encrypt_dir, &passphrase, None, None, |_| {});
    assert!(result.is_err());

    let would_be_output = encrypt_dir.join(format!("link.{}", ENCRYPTED_EXTENSION));
    assert!(
        !would_be_output.exists(),
        "partial .fcr file should have been cleaned up"
    );

    Ok(())
}

#[cfg(unix)]
#[test]
fn test_recipient_encrypt_cleans_up_on_failure() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("rec_encrypt_cleanup");
    let keys_dir = test_dir.join("keys");
    let real_file = test_dir.join("real.txt");
    let symlink_path = test_dir.join("link.txt");
    let encrypt_dir = test_dir.join("encrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    create_test_file(&real_file, "target content");
    std::os::unix::fs::symlink(&real_file, &symlink_path).unwrap();

    let key_pass = SecretString::from("cleanup_key".to_string());
    generate_key_pair(&key_pass, &keys_dir, |_| {})?;

    let result = recipient_auto(
        &symlink_path,
        &encrypt_dir,
        keys_dir.join("public.key"),
        &key_pass,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());

    let would_be_output = encrypt_dir.join(format!("link.{}", ENCRYPTED_EXTENSION));
    assert!(
        !would_be_output.exists(),
        "partial .fcr file should have been cleaned up"
    );

    Ok(())
}

#[test]
fn test_passphrase_decrypt_marks_incomplete_file() -> Result<(), CryptoError> {
    use ferrocrypt::{Decryptor, IncompleteOutputPolicy};

    let test_dir = setup_test_dir("pass_decrypt_incomplete_file");
    let input_file = test_dir.join("bigfile.bin");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    // 200 KB file — spans multiple 64 KB encryption chunks
    let big_data: Vec<u8> = (0..204_800u32).map(|i| (i % 256) as u8).collect();
    fs::write(&input_file, &big_data)?;

    let passphrase = SecretString::from("incomplete_pass".to_string());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("bigfile.fcr");
    let mut data = fs::read(&encrypted_path)?;
    // Corrupt a byte in a late chunk (well past the first 64 KB)
    let flip_offset = data.len() - 50;
    data[flip_offset] ^= 0xFF;
    fs::write(&encrypted_path, &data)?;

    let Decryptor::Passphrase(decryptor) = Decryptor::open(&encrypted_path)? else {
        panic!("expected passphrase-sealed file");
    };
    let result = decryptor
        .incomplete_output_policy(IncompleteOutputPolicy::RetainOnError)
        .decrypt(passphrase, &decrypt_dir, |_| {});
    assert!(result.is_err());

    let incomplete_path = decrypt_dir.join("bigfile.bin.incomplete");
    assert!(
        incomplete_path.exists(),
        "RetainOnError should leave the partial output as .incomplete"
    );
    // Original name should not exist
    assert!(!decrypt_dir.join("bigfile.bin").exists());

    Ok(())
}

#[test]
fn test_passphrase_decrypt_marks_incomplete_directory() -> Result<(), CryptoError> {
    use ferrocrypt::{Decryptor, IncompleteOutputPolicy};

    let test_dir = setup_test_dir("pass_decrypt_incomplete_dir");
    let input_dir = test_dir.join("mydir");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&input_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    create_test_file(&input_dir.join("small.txt"), "small file content");
    // Large file to span multiple chunks
    let big_data: Vec<u8> = (0..204_800u32).map(|i| (i % 256) as u8).collect();
    fs::write(input_dir.join("bigfile.bin"), &big_data)?;

    let passphrase = SecretString::from("incomplete_dir_pass".to_string());
    passphrase_auto(&input_dir, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let encrypted_path = encrypt_dir.join("mydir.fcr");
    let mut data = fs::read(&encrypted_path)?;
    let flip_offset = data.len() - 50;
    data[flip_offset] ^= 0xFF;
    fs::write(&encrypted_path, &data)?;

    let Decryptor::Passphrase(decryptor) = Decryptor::open(&encrypted_path)? else {
        panic!("expected passphrase-sealed file");
    };
    let result = decryptor
        .incomplete_output_policy(IncompleteOutputPolicy::RetainOnError)
        .decrypt(passphrase, &decrypt_dir, |_| {});
    assert!(result.is_err());

    let incomplete_path = decrypt_dir.join("mydir.incomplete");
    assert!(
        incomplete_path.exists(),
        "RetainOnError should leave the partial directory as .incomplete"
    );
    assert!(incomplete_path.is_dir());
    assert!(!decrypt_dir.join("mydir").exists());

    Ok(())
}

#[test]
fn test_successful_decrypt_produces_final_name_not_incomplete() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("decrypt_final_name");
    let input_file = test_dir.join("payload.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;
    fs::write(&input_file, "clean decryption")?;

    let passphrase = SecretString::from("final_name_pass".to_string());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    let output = passphrase_auto(
        encrypt_dir.join("payload.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    )?;
    assert!(output.exists());
    assert_eq!(output, decrypt_dir.join("payload.txt"));
    assert!(!decrypt_dir.join("payload.txt.incomplete").exists());

    Ok(())
}

#[test]
fn test_existing_incomplete_blocks_retry() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("incomplete_blocks_retry");
    let input_file = test_dir.join("data.txt");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;
    fs::write(&input_file, "some content")?;

    let passphrase = SecretString::from("retry_pass".to_string());
    passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    // Simulate leftover .incomplete from a previous failed attempt
    fs::write(decrypt_dir.join("data.txt.incomplete"), "stale partial")?;

    let result = passphrase_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(result.is_err());
    match result {
        Err(CryptoError::InvalidInput(msg)) => {
            assert!(msg.contains("Previous .incomplete exists"), "got: {msg}");
        }
        other => panic!("expected InvalidInput about incomplete, got: {other:?}"),
    }

    // Stale .incomplete must not be overwritten
    let stale = fs::read_to_string(decrypt_dir.join("data.txt.incomplete"))?;
    assert_eq!(stale, "stale partial");

    Ok(())
}

#[test]
fn test_encrypt_produces_final_name_not_incomplete() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("encrypt_final_name");
    let input_file = test_dir.join("secret.txt");
    let encrypt_dir = test_dir.join("encrypted");
    fs::create_dir_all(&encrypt_dir)?;
    fs::write(&input_file, "secret data")?;

    let passphrase = SecretString::from("enc_final".to_string());
    let output = passphrase_auto(&input_file, &encrypt_dir, &passphrase, None, None, |_| {})?;

    assert!(output.exists());
    assert_eq!(output, encrypt_dir.join("secret.fcr"));
    assert!(!encrypt_dir.join("secret.fcr.incomplete").exists());

    Ok(())
}

#[test]
fn test_keygen_no_partial_state_on_existing_key() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("keygen_no_partial");
    let passphrase = SecretString::from("atomic_pass".to_string());

    // First keygen succeeds
    generate_key_pair(&passphrase, &test_dir, |_| {})?;
    assert!(test_dir.join("private.key").exists());
    assert!(test_dir.join("public.key").exists());

    // Second keygen to the same dir fails — keys already exist
    let result = generate_key_pair(&passphrase, &test_dir, |_| {});
    assert!(result.is_err());

    Ok(())
}

/// Flipping a byte in the cleartext salt region of a v1 `private.key`
/// file must cause decryption to fail. v1 binds every cleartext byte
/// before `wrapped_private_key` (header + argon2_salt + kdf_params +
/// wrap_nonce + ext_bytes) as AEAD associated data, so any header or
/// body tamper fails authentication on unlock.
#[test]
fn test_private_key_salt_tamper_rejected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("private_key_salt_tamper");
    let keys_dir = test_dir.join("keys");
    let encrypt_dir = test_dir.join("encrypted");
    let decrypt_dir = test_dir.join("decrypted");
    fs::create_dir_all(&keys_dir)?;
    fs::create_dir_all(&encrypt_dir)?;
    fs::create_dir_all(&decrypt_dir)?;

    let passphrase = SecretString::from("aad_salt_pass".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    let input_file = test_dir.join("data.txt");
    create_test_file(&input_file, "confidential");
    let empty = SecretString::from("".to_string());
    recipient_auto(
        &input_file,
        &encrypt_dir,
        keys_dir.join("public.key"),
        &empty,
        None,
        None,
        |_| {},
    )?;

    // Flip one byte inside the 32-byte Argon2 salt region. v1 body layout:
    //   [argon2_salt(32)][kdf_params(12)][wrap_nonce(24)][ext_bytes(0)][wrapped_private_key(48)]
    // The salt region starts directly after the 9-byte cleartext header.
    let private_key_path = keys_dir.join("private.key");
    let mut key_data = fs::read(&private_key_path)?;
    let salt_offset = 9;
    key_data[salt_offset] ^= 0x01;
    fs::write(&private_key_path, &key_data)?;

    let result = recipient_auto(
        encrypt_dir.join("data.fcr"),
        &decrypt_dir,
        &private_key_path,
        &passphrase,
        None,
        None,
        |_| {},
    );
    assert!(
        result.is_err(),
        "tampered salt must not decrypt even with the correct passphrase"
    );

    Ok(())
}

/// Setting a reserved key-file flag bit must be rejected by the
/// structural validator before the KDF is even attempted. The flags
/// field is also part of the AEAD AAD on decrypt — even if the
/// validator were bypassed, AEAD authentication would also reject the
/// tampered file — but the cheap structural check comes first.
#[test]
fn test_private_key_ext_len_tamper_rejected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("private_key_ext_len_tamper");
    let keys_dir = test_dir.join("keys");
    fs::create_dir_all(&keys_dir)?;

    let passphrase = SecretString::from("ext_len_pass".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    // Flipping a bit in the `ext_len` field (u32 BE at bytes 14..=17)
    // of the `private.key` cleartext header makes the declared length
    // no longer match the on-disk body — surfaces as
    // `MalformedPrivateKey`.
    let private_key_path = keys_dir.join("private.key");
    let mut key_data = fs::read(&private_key_path)?;
    key_data[14] |= 0x01;
    fs::write(&private_key_path, &key_data)?;

    match validate_private_key_file(&private_key_path) {
        Err(ferrocrypt::CryptoError::InvalidFormat(
            ferrocrypt::FormatDefect::MalformedPrivateKey,
        )) => {}
        other => panic!("expected MalformedPrivateKey, got {:?}", other),
    }

    Ok(())
}

// ─── probe_recipient_mode: fail-closed on malformed headers ──────────────

#[test]
fn test_probe_plaintext_file_returns_none() -> Result<(), CryptoError> {
    let dir = setup_test_dir("probe_plaintext");
    let path = dir.join("hello.txt");
    fs::write(&path, "just plain text")?;
    assert!(probe_recipient_mode(&path)?.is_none());
    Ok(())
}

#[test]
fn test_probe_empty_file_returns_none() -> Result<(), CryptoError> {
    let dir = setup_test_dir("probe_empty");
    let path = dir.join("empty.bin");
    fs::write(&path, b"")?;
    assert!(probe_recipient_mode(&path)?.is_none());
    Ok(())
}

/// A directory is unambiguously "not an encrypted file." Unix lets us open a
/// directory fd and only fails at `read()` with `IsADirectory`; Windows'
/// `CreateFile` rejects directories outright with `ERROR_ACCESS_DENIED`.
/// Regardless of platform, `probe_recipient_mode` must classify a directory
/// as `Ok(None)` so that auto-routing wrappers take the encrypt branch rather
/// than surfacing a permission error. Covers both populated and empty roots.
#[test]
fn test_probe_directory_returns_none() -> Result<(), CryptoError> {
    let dir = setup_test_dir("probe_directory");

    let populated = dir.join("populated");
    fs::create_dir_all(&populated)?;
    create_test_file(&populated.join("inside.txt"), "content");
    assert!(probe_recipient_mode(&populated)?.is_none());

    let empty = dir.join("empty");
    fs::create_dir_all(&empty)?;
    assert!(probe_recipient_mode(&empty)?.is_none());

    Ok(())
}

#[test]
fn test_probe_valid_passphrase_file() -> Result<(), CryptoError> {
    let dir = setup_test_dir("probe_passphrase");
    let input = dir.join("data.txt");
    fs::write(&input, "payload")?;
    let pass = SecretString::from("pw".to_string());
    let encrypted = passphrase_auto(&input, &dir, &pass, None, None, |_| {})?;
    let mode = probe_recipient_mode(&encrypted)?;
    assert_eq!(
        mode,
        Some(ferrocrypt::UnauthenticatedRecipientMode::Passphrase)
    );
    Ok(())
}

/// L-4 regression: a short random file with `0xFC` at bytes 3 and 11 (the
/// first two replication-copy positions) must not be misclassified as a
/// truncated `.fcr`. The detector requires every copy position to be
/// within the read-in region before voting, so a file shorter than 20
/// bytes returns `Ok(None)` regardless of which bytes happen to match.
#[test]
fn test_probe_short_file_with_two_magic_bytes_returns_none() {
    let dir = setup_test_dir("probe_two_magic_coincidence");
    let path = dir.join("coincidence.bin");
    let mut data = vec![0u8; 15];
    data[3] = 0xFC;
    data[11] = 0xFC;
    fs::write(&path, &data).unwrap();
    assert!(
        probe_recipient_mode(&path).unwrap().is_none(),
        "a sub-20-byte file cannot be classified as a truncated `.fcr`"
    );
}

#[test]
fn test_probe_short_file_with_single_magic_byte_returns_none() {
    let dir = setup_test_dir("probe_single_magic");
    let path = dir.join("coincidence.bin");
    // A short file with 0xFC at position 3 by coincidence — only one copy
    // position matches, so majority vote says "not ferrocrypt."
    let mut data = vec![0u8; 10];
    data[3] = 0xFC;
    fs::write(&path, &data).unwrap();
    let result = probe_recipient_mode(&path);
    assert!(
        result.unwrap().is_none(),
        "single magic byte should not trigger false positive"
    );
}

#[test]
fn test_detect_corrupted_fcr_not_silently_encrypted() {
    let dir = setup_test_dir("detect_no_reencrypt");
    let input = dir.join("corrupted.fcr");
    // Minimal v1 prefix only: magic + version + kind 'E' (encrypted)
    // + zero prefix_flags + header_len = 0. Detection must route
    // this file to decrypt, where the missing rest-of-header fails
    // closed — rather than the helper treating it as plaintext and
    // re-encrypting it (which would produce a path collision and
    // mask the structural failure).
    let mut prefix = vec![b'F', b'C', b'R', 0, ferrocrypt::FCR_FILE_VERSION]; // magic + current wire version
    prefix.push(b'E'); // KIND_ENCRYPTED
    prefix.extend_from_slice(&0u16.to_be_bytes()); // prefix_flags = 0
    prefix.extend_from_slice(&0u32.to_be_bytes()); // header_len = 0 (truncated)
    fs::write(&input, &prefix).unwrap();
    let pass = SecretString::from("pw".to_string());
    let result = passphrase_auto(&input, &dir, &pass, None, None, |_| {});
    assert!(
        matches!(result, Err(CryptoError::InvalidFormat(_))),
        "corrupted .fcr should fail closed, got: {:?}",
        result
    );
}

// ─── Bech32 recipient tests ──────────────────────────────────────────────

#[test]
fn test_recipient_round_trip() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_roundtrip");
    let keys_dir = test_dir.join("keys");
    let passphrase = SecretString::from("rp".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    let encoded = PublicKey::from_key_file(keys_dir.join("public.key")).to_recipient_string()?;
    assert!(encoded.starts_with("fcr1"));

    let decoded = decode_recipient_string(&encoded)?;
    let re_encoded = PublicKey::from_bytes(decoded)?.to_recipient_string()?;
    assert_eq!(encoded, re_encoded);

    Ok(())
}

#[test]
fn test_recipient_malformed_bech32_rejected() {
    let result = decode_recipient_string("fcr1not-valid-bech32!!!");
    assert!(result.is_err());
}

#[test]
fn test_recipient_uppercase_rejected() -> Result<(), CryptoError> {
    let test_dir = setup_test_dir("recipient_uppercase");
    let keys_dir = test_dir.join("keys");
    let passphrase = SecretString::from("uc".to_string());
    generate_key_pair(&passphrase, &keys_dir, |_| {})?;

    let encoded = PublicKey::from_key_file(keys_dir.join("public.key")).to_recipient_string()?;
    let uppercased = encoded.to_uppercase();
    assert!(
        decode_recipient_string(&uppercased).is_err(),
        "uppercase-only recipient strings are non-canonical and must be rejected"
    );

    Ok(())
}

#[ctor::dtor]
fn cleanup() {
    cleanup_test_workspace();
}