ferrocrypt 0.3.0

Recipient-oriented file and directory encryption: passphrase (Argon2id) and X25519 public-key recipients, XChaCha20-Poly1305 STREAM payloads, HKDF-SHA3-256 / HMAC-SHA3-256 key derivation and authentication.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
//! Atomic output finalization helpers.
//!
//! This module centralizes the "write under a temporary name,
//! promote to the final name only on success" pattern used throughout
//! the crate for encrypted-file output, generated key files, and the
//! Windows / other-target decrypt-promotion fallback.
//!
//! Linux and macOS archive decrypt promotion is deliberately not owned
//! here: `archive::platform::rename_at_no_clobber` performs that commit
//! handle-relative to the extraction directory, so a mid-run path swap
//! cannot redirect it.
//!
//! Four primitives are provided:
//!
//! - [`finalize_file`] — promote a [`tempfile::NamedTempFile`] through a
//!   caller-retained output-directory anchor. Used by key generation on every
//!   target and by encrypted output on Linux/macOS.
//! - `finalize_file_path_based` — keep encrypted output's existing
//!   path-based commit on the other targets, without adding a directory-open
//!   requirement their primary backend cannot use.
//! - [`promote_single_file_no_clobber`] — promote a staged single-file
//!   `.incomplete` path to its final name with atomic no-clobber semantics
//!   on every supported platform, Windows included. Used by archive
//!   extraction only on Windows / other non-Linux/macOS targets; Linux and
//!   macOS use `archive::platform::rename_at_no_clobber` instead.
//! - [`rename_no_clobber`] — path-based rename of a staged `.incomplete`
//!   entry (directory or regular file) to its final name with no-clobber
//!   semantics. Used by archive extraction for directory roots only on
//!   Windows / other non-Linux/macOS targets; Linux and macOS decrypt
//!   promotion is handle-relative in `archive::platform`.
//!
//! Durability helpers support these operations. [`sync_file_durable`]
//! flushes staged encrypted output and key files before promotion; archive
//! extraction flushes its own files. [`sync_dir_durable`] flushes directory
//! entries and reports failures; it is key generation's required barrier on
//! Windows and the other targets. On Linux and macOS that barrier is
//! `OutputDir::flush_durable`, which flushes through the handle the key
//! files were committed through with `sync_dir_durable_at`, the required
//! flush the macOS extraction barrier also uses. [`sync_parent_dir`] remains
//! best-effort for outputs whose loss can be recovered.
//!
//! [`OutputDir`] retains a handle to the directory an operation publishes
//! into. Cleanup after a failed commit goes through that handle, so it
//! removes the entry the operation created rather than whatever its path
//! happens to name once the operation is already under way.
//!
//! **Zero in-repo unsafe.** On Linux and macOS the file cases issue
//! `rustix::renameat_with(..., RenameFlags::NOREPLACE)` themselves
//! through [`crate::fs::commit`], relative to one retained
//! [`OutputDir`]; Windows and the other Unix targets delegate to
//! `tempfile`, which is atomic-no-replace on Windows (`MoveFileExW`
//! without the replace flag). Where the filesystem cannot perform a
//! no-replace rename, the Unix fallback is [`crate::fs::commit`]'s
//! handle-relative link, claim, and rename operations, anchored to that
//! same handle. The directory rename case in [`rename_no_clobber`]
//! delegates to `rustix` directly on Linux and macOS, and on Windows uses
//! `symlink_metadata()` + `std::fs::rename`, which keeps the crate
//! zero-unsafe but offers a narrower best-effort no-clobber guarantee
//! for directory promotion on that target.

use std::io;
use std::path::Path;

use tempfile::NamedTempFile;

use crate::CryptoError;
use crate::error::sanitize_path_for_display;
#[cfg(unix)]
use crate::fs::commit::{CommitFailure, CommitKind, CommitRoute};
use crate::fs::paths::already_exists_error;

/// A file whose commit completed, keeping the committed handle alive. It
/// is used, on every platform, to confirm immediately before returning
/// that the reported path still denotes this object and that the commit
/// left exactly one name for the committed file — `tempfile`'s own
/// persist can fall back on Unix to a hard link whose staged-name unlink
/// result it discards, and a link a local writer creates against the
/// staged temporary before the commit survives it anywhere — and by a
/// key-generation rollback to confirm that the entry it removes is still
/// this file. On Windows the rollback deletes the file through this
/// handle, which relies on `tempfile` opening a named temporary with the
/// default sharing mode; that mode admits the delete-access reopen, unlike
/// the exclusive mode of its unnamed temporaries.
#[derive(Debug)]
pub(crate) struct FinalizedFile {
    file: std::fs::File,
}

impl FinalizedFile {
    fn new(file: std::fs::File) -> Self {
        Self { file }
    }

    /// Confirms that `path`, the value a writer is about to report, still
    /// denotes this committed file. A final-entry replacement, or a
    /// directory swap where the platform permits one while the handle is
    /// open, can otherwise make the returned path lead to
    /// attacker-controlled bytes. A path that no longer leads to an entry —
    /// one missing, a non-directory where the path needs a directory, or a
    /// symlink cycle — counts as changed too: the commit created an entry
    /// there, so the name no longer denotes the output. The decrypt side
    /// applies the same rule to its destination directory.
    ///
    /// Runs only after the commit, so every error says that the output is
    /// complete. A changed path is [`CryptoError::InvalidInput`]. A read that
    /// fails is [`CryptoError::Io`] with that failure's kind, reporting the
    /// path as unconfirmed rather than as a bare filesystem error a caller
    /// could take to mean that nothing was written.
    pub(crate) fn confirm_reported_path(&self, path: &Path) -> Result<(), CryptoError> {
        let committed = cap_std::fs::Metadata::from_file(&self.file)
            .map_err(|e| reported_path_unconfirmed(path, e))?;
        let reported = reported_entry_metadata(path).map_err(|e| reported_entry_error(path, e))?;
        if !reported.is_file() || identities_differ(&reported, &committed) {
            return Err(reported_output_changed(path));
        }
        Ok(())
    }

    /// The number of names this file has, read through the retained handle,
    /// so no rename or replacement of a directory entry can change which file
    /// is counted.
    fn link_count(&self) -> io::Result<u64> {
        use cap_fs_ext::MetadataExt;

        Ok(cap_std::fs::Metadata::from_file(&self.file)?.nlink())
    }

    /// Ends every commit route that holds the committed file's handle.
    /// `finding` is what the route found wrong after the commit, if anything;
    /// the file is returned only if there is no finding and it has exactly one
    /// name. Every error says that the output is complete, including one for a
    /// count that could not be read.
    ///
    /// The count is read even beside a finding, because no finding accounts
    /// for every extra name: a staged name left behind is one, not
    /// necessarily the only one. It is then reported without naming `path`,
    /// which the finding may have shown no longer leads to this file.
    fn into_confirmed(
        self,
        path: &Path,
        finding: Option<CryptoError>,
    ) -> Result<Self, FinalizeFileError> {
        let error = match (finding, self.link_count()) {
            (None, Ok(1)) => return Ok(self),
            (None, Ok(link_count)) => {
                committed_link_count_error(&sanitize_path_for_display(path), link_count)
            }
            (None, Err(source)) => link_count_unreadable(path, source),
            (Some(finding), Ok(1)) => finding,
            (Some(finding), Ok(link_count)) => crate::error::append_report(
                finding,
                &format!("the output {}", link_count_clause(link_count)),
            ),
            (Some(finding), Err(source)) => crate::error::append_report(
                finding,
                &format!("the output's {}", link_count_unreadable_clause(&source)),
            ),
        };
        Err(FinalizeFileError::after_commit(error))
    }
}

/// Identity of a filesystem object: the device and inode number on Unix,
/// the volume serial number and the 64-bit file index on Windows.
/// Comparing the object behind a retained handle with the entry under a
/// name catches a final-name replacement, and a parent-directory swap
/// where the platform permits one, before an operation reports that
/// path. The decrypt side reads the same pair through
/// `archive::platform::ObjectId`.
///
/// `None` where the inode number or file index is zero: a filesystem
/// that assigns none reports zero for every object, so the value says
/// nothing about which object was read. Every comparison in this crate
/// treats that as evidence it does not have — it skips the comparison
/// where skipping only forgoes a check, and reports an action it cannot
/// confirm where acting would mean removing an entry — never as a
/// match (`THREAT_MODEL.md` §7.4).
///
/// Commit comparisons retain a handle or link to the recorded object because
/// filesystems may reuse identifiers after an object is removed. The archive
/// writer's descendant-source check is an exception: it records metadata
/// without retaining each file and can miss inode reuse between passes (see
/// `archive::encode::require_same_source_file`). Other limitations are
/// documented in `SECURITY.md`: ReFS reports a
/// 64-bit truncation of a wider identifier, and a filesystem that
/// assigns one non-zero identifier to every object — some network
/// redirectors — makes every comparison hold, so these checks detect
/// nothing there rather than fail.
///
/// `metadata` must come from an open handle —
/// [`cap_std::fs::Metadata::from_file`], or a cap-std stat, which opens
/// the entry itself — or, on Unix, from a `std` stat converted with
/// `from_just_metadata`. cap-std fills the Windows fields only from an
/// open handle, and its accessors panic where they are absent; the crate
/// never reads an identity out of a directory listing.
pub(crate) fn file_identity(metadata: &cap_std::fs::Metadata) -> Option<FileIdentity> {
    use cap_fs_ext::MetadataExt;

    identity_pair(metadata.dev(), metadata.ino())
}

/// The pair [`file_identity`] reads: device and inode number on Unix,
/// volume serial number and file index on Windows.
pub(crate) type FileIdentity = (u64, u64);

/// The rule behind [`file_identity`]: a zero inode number or file index
/// is no identity.
fn identity_pair(dev: u64, ino: u64) -> Option<FileIdentity> {
    (ino != 0).then_some((dev, ino))
}

/// Whether two metadata values are shown to describe different objects
/// by their [`file_identity`]. Where either carries none the objects
/// cannot be told apart, and this answers `false`, so a check that only
/// refuses on a difference is skipped; a caller that would act on a
/// match reads the identities itself.
pub(crate) fn identities_differ(a: &cap_std::fs::Metadata, b: &cap_std::fs::Metadata) -> bool {
    match (file_identity(a), file_identity(b)) {
        (Some(a), Some(b)) => a != b,
        _ => false,
    }
}

/// Metadata of the entry at `path` without following a final symlink,
/// carrying its identity. Unix reads it with `lstat`, which needs only
/// search permission on the parent.
#[cfg(unix)]
fn reported_entry_metadata(path: &Path) -> io::Result<cap_std::fs::Metadata> {
    std::fs::symlink_metadata(path).map(cap_std::fs::Metadata::from_just_metadata)
}

/// Windows counterpart of the Unix `lstat`: the entry is opened without
/// following a symlink or reparse point, requesting no access — the open
/// `std` performs for `symlink_metadata`, which needs only traversal of
/// the parent — and its identity is read from that handle, because a
/// `std` metadata value carries none on stable Rust. A symlink or
/// junction at the path is the reparse point itself, which the caller's
/// regular-file test rejects.
#[cfg(windows)]
fn reported_entry_metadata(path: &Path) -> io::Result<cap_std::fs::Metadata> {
    use std::os::windows::fs::OpenOptionsExt;

    let entry = std::fs::OpenOptions::new()
        .access_mode(0)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
        .open(path)?;
    cap_std::fs::Metadata::from_file(&entry)
}

/// `CreateFileW` flag without which a directory cannot be opened.
#[cfg(windows)]
pub(crate) const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;

/// `CreateFileW` flag that opens a symlink or other reparse point itself
/// instead of following it.
#[cfg(windows)]
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;

fn reported_output_changed(path: &Path) -> CryptoError {
    CryptoError::InvalidInput(format!(
        "Output is complete but its reported path changed: {}",
        sanitize_path_for_display(path)
    ))
}

/// Maps a failed read of the committed entry at `path`. A path that no longer
/// leads to an entry ([`crate::fs::paths::path_no_longer_resolves`]) no longer
/// denotes the output ([`reported_output_changed`]); any other failure leaves
/// the path unconfirmed ([`reported_path_unconfirmed`]).
fn reported_entry_error(path: &Path, error: io::Error) -> CryptoError {
    if crate::fs::paths::path_no_longer_resolves(&error) {
        reported_output_changed(path)
    } else {
        reported_path_unconfirmed(path, error)
    }
}

/// Post-commit failure for a reported-path check that could not run. The
/// output is complete, but whether `path` still denotes it is unknown, so the
/// message names the path without claiming that the output is there. The
/// error keeps `source`'s kind.
fn reported_path_unconfirmed(path: &Path, source: io::Error) -> CryptoError {
    CryptoError::Io(io::Error::new(
        source.kind(),
        format!(
            "Output is complete, but its reported path could not be confirmed: {}: {source}",
            sanitize_path_for_display(path)
        ),
    ))
}

/// Post-commit failure for a committed file whose link count could not be
/// read. Raised only once the reported path has been confirmed, so the
/// message names the output by it. The error keeps `source`'s kind.
fn link_count_unreadable(path: &Path, source: io::Error) -> CryptoError {
    CryptoError::Io(io::Error::new(
        source.kind(),
        format!(
            "Output {} is complete, but its {}",
            sanitize_path_for_display(path),
            link_count_unreadable_clause(&source),
        ),
    ))
}

/// The clause stating that a committed file's link count could not be read,
/// shared by [`link_count_unreadable`] and the report
/// [`FinalizedFile::into_confirmed`] appends beside another finding.
fn link_count_unreadable_clause(source: &io::Error) -> String {
    format!("number of filesystem names could not be read: {source}")
}

/// Post-commit failure for a committed file with a link count other than
/// one. The retained handle, rather than either mutable name, supplies the
/// count. The message reports the count alone, because the operation cannot
/// tell a name its own hard-link fallback left from one a local writer made
/// against the staged file before the commit. `display_name` must already be
/// safe to render. Shared with archive extraction so the writer and the
/// reader report this condition in the same words.
pub(crate) fn committed_link_count_error(display_name: &str, link_count: u64) -> CryptoError {
    CryptoError::Io(io::Error::other(format!(
        "Output {display_name} is complete, but {}",
        link_count_clause(link_count),
    )))
}

/// The clause stating a link count other than one, shared by
/// [`committed_link_count_error`] and the report
/// [`FinalizedFile::into_confirmed`] appends beside another finding.
fn link_count_clause(link_count: u64) -> String {
    format!("has {link_count} filesystem names (expected 1)")
}

/// What an identity-checked removal did with a file this operation wrote,
/// either an already committed key file or its still-staged sibling. Only
/// [`Self::Removed`] needs no report: every other outcome means that file may
/// still exist, and the returned error says so since nothing else reaches the
/// caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RollbackOutcome {
    /// The retained file was removed, and its name was the only one it had.
    Removed,
    /// The retained file's name was removed, but the file had `link_count`
    /// names at that moment, so it survives under the others.
    RemovedButLinked { link_count: u64 },
    /// The entry under the name is no longer the retained file and was left
    /// in place; the retained file survives under whatever name it was moved
    /// to, if any.
    Replaced,
    /// Nothing was removed: the name is gone, an identity could not be
    /// read, or the removal itself failed.
    Unconfirmed,
}

impl RollbackOutcome {
    /// The clause appended to the operation's error, or `None` when the
    /// rollback removed the file completely. For a committed file the clause
    /// first states that a complete file was committed under the name: the
    /// operation's error alone would read as if nothing had been written
    /// (`THREAT_MODEL.md` TM-06). That statement is about the commit, not
    /// about the entry now at the name, which [`Self::Replaced`] shows is
    /// another file.
    fn report(self, path: &Path, file: RemovedFile) -> Option<String> {
        use RemovedFile::{Committed, Staged};

        let shown = final_component_for_display(path);
        Some(match (file, self) {
            (_, Self::Removed) => return None,
            (Committed, Self::RemovedButLinked { link_count }) => format!(
                "a complete {shown} was committed and then removed, but it had {link_count} filesystem names, so a copy may remain under another name"
            ),
            (Staged, Self::RemovedButLinked { link_count }) => format!(
                "the removed {shown} had {link_count} filesystem names, so a copy may remain under another name"
            ),
            (Committed, Self::Replaced) => format!(
                "a complete {shown} was committed, but the entry at its name was replaced and left in place, and the committed file may remain under another name"
            ),
            (Staged, Self::Replaced) => format!(
                "{shown} was replaced during the operation and left in place, and the file this run wrote may remain under another name"
            ),
            (Committed, Self::Unconfirmed) => {
                format!("a complete {shown} was committed, and its removal could not be confirmed")
            }
            (Staged, Self::Unconfirmed) => format!("the removal of {shown} could not be confirmed"),
        })
    }
}

/// Which file an identity-checked removal was asked to take away. It decides
/// how the removal's [`RollbackOutcome`] is reported.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RemovedFile {
    /// A key file already committed at its final name. Its report says that
    /// a complete file was committed there before saying what the removal
    /// left, because the error it joins otherwise reads as if nothing had
    /// been written.
    Committed,
    /// The sibling still under its staged name, never committed to its final
    /// name. Its report says only what may remain under that staged name.
    Staged,
}

/// An identity-checked removal's outcome together with the file it was asked
/// to take away. Only the removals in this module build one, so a report can
/// never describe a committed file as staged or a staged file as committed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Rollback {
    outcome: RollbackOutcome,
    file: RemovedFile,
}

/// The final component of `path`, escaped and bounded for a message.
/// Both failure reports in this module name a file that way: the caller
/// chose the directory and knows it already.
fn final_component_for_display(path: &Path) -> String {
    let name = path.file_name().unwrap_or(path.as_os_str());
    crate::error::sanitize_for_display(&name.to_string_lossy())
}

/// Appends a removal's report to the error the operation is already
/// returning, through [`crate::error::append_report`]; a removal that
/// took the file away completely returns `error` unchanged. Serves the
/// rollback of a committed key file and the removal of its still-staged
/// sibling alike: `rollback` carries which of the two it was, set by the
/// removal that produced it. Both reports say whether a file this run wrote
/// may remain, and a committed file's report also says that a complete file
/// was committed under its name.
pub(crate) fn with_rollback_report(
    error: CryptoError,
    rollback: Rollback,
    path: &Path,
) -> CryptoError {
    match rollback.outcome.report(path, rollback.file) {
        Some(report) => crate::error::append_report(error, &report),
        None => error,
    }
}

/// Failure from [`finalize_file`], retaining whether the file reached a final
/// name before the error. Key generation needs that distinction: if
/// `public.key` committed and only a post-commit verification failed, rolling
/// back `private.key` would leave an unsafe public-only pair. An error raised
/// after the commit says in its message that the output is complete
/// (`THREAT_MODEL.md` TM-06).
#[derive(Debug)]
pub(crate) struct FinalizeFileError {
    error: CryptoError,
    committed: bool,
}

impl FinalizeFileError {
    fn before_commit(error: CryptoError) -> Self {
        Self {
            error,
            committed: false,
        }
    }

    /// Marks `error` as raised after the commit. Every post-commit error
    /// passes through here, so this crate's tests assert at this point that it
    /// says the output is complete. Other builds leave the assertion out: a
    /// caller must receive the error, never a panic after its output was
    /// committed.
    fn after_commit(error: CryptoError) -> Self {
        #[cfg(test)]
        assert!(
            says_output_is_complete(&error),
            "a post-commit error must say that the output is complete: {error}"
        );
        Self {
            error,
            committed: true,
        }
    }

    #[cfg(test)]
    pub(crate) fn after_commit_for_test(error: CryptoError) -> Self {
        Self::after_commit(error)
    }

    /// Whether a final name was created before this error.
    pub(crate) fn committed(&self) -> bool {
        self.committed
    }

    /// Returns the caller-visible error.
    pub(crate) fn into_crypto_error(self) -> CryptoError {
        self.error
    }
}

/// Whether `error`'s message says that the output is complete, as every error
/// raised after a commit must (`THREAT_MODEL.md` TM-06).
#[cfg(test)]
fn says_output_is_complete(error: &CryptoError) -> bool {
    let message = error.to_string();
    message.starts_with("Output ") && message.contains(" is complete")
}

/// Best-effort parent-directory sync used after a successful file persist or
/// directory rename. This slightly improves durability after the final path
/// becomes visible.
///
/// Routes through [`sync_dir_durable`] and drops its result. Sharing that
/// helper keeps the open hardened: the parent is opened as a directory, so a
/// path replaced by a FIFO or a device node between publication and this call
/// is refused rather than opened. Opening such an object for reading would
/// otherwise wait for a writer, and there is no error for a best-effort
/// helper to swallow while the open itself is still blocked.
///
/// Failures are intentionally ignored here:
/// - not every filesystem supports syncing directories cleanly
/// - finalization has already succeeded by the time this runs
/// - returning an error after the final path is visible would be more
///   confusing to callers than helpful
///
/// Callers that require directory-flush failures to be reported call
/// [`sync_dir_durable`] directly.
#[cfg(any(unix, windows))]
fn sync_parent_dir(path: &Path) {
    let _ = sync_dir_durable(crate::fs::paths::parent_or_cwd(path));
}

#[cfg(not(any(unix, windows)))]
fn sync_parent_dir(_path: &Path) {}

/// Promotes a `NamedTempFile` to its final path with no-clobber semantics.
/// Linux and macOS resolve the commit through the destination-directory
/// anchor the caller retained before staging. Other targets retain their
/// path-based primary persist; key generation still supplies its readable
/// anchor for rollback, durability, and the other-Unix compatibility
/// fallback. An occupied final path rejects with the same typed
/// `InvalidInput("<label> already exists: …")` message the pre-write
/// occupancy check emits, so a path that becomes occupied between the
/// preflight and this rename reports the same error class. Other
/// failures surface as [`CryptoError::Io`]. A failure before publication
/// removes the temp file best-effort. A failure after publication is marked
/// by [`FinalizeFileError::committed`], and its message says that the output
/// is complete; the final entry is kept because a bare-name rollback could
/// delete a concurrent replacement.
///
/// On Linux and macOS the anchor is a parameter rather than something opened
/// here because its lifetime is the guarantee: a handle opened at the commit
/// would denote whatever occupies the output path by then, and a local writer
/// who moves the staged entry into a directory of their own and installs it at
/// that path would have the commit land there. Held from before staging, the
/// handle stays bound to the directory the operation began in, and a staged
/// entry moved out of it is refused.
///
/// The promotion is a single atomic no-replace rename wherever the
/// filesystem supports one: handle-relative through the anchor on Linux
/// and macOS (`finalize_file_at`), by ambient path through `tempfile`
/// elsewhere. Where the filesystem supports no such rename (see
/// `no_replace_rename_unsupported`), the Unix fallback commits by
/// linking or, on a filesystem without hard links, by claiming the name
/// and renaming over the claim ([`crate::fs::commit`]). Every route keeps
/// the no-clobber guarantee against entries that predate the commit.
///
/// Callers are expected to have already flushed and synced the temp file
/// before calling this function. Every anchored route requires the temp file
/// to be an entry of the anchored directory; [`OutputDir::confirm_staged`]
/// establishes that at staging time and the route confirms it again here.
pub(crate) fn finalize_file(
    tmp: NamedTempFile,
    final_path: &Path,
    label: &str,
    anchor: &OutputDir,
) -> Result<FinalizedFile, FinalizeFileError> {
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        finalize_file_at(tmp, final_path, label, anchor)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        finalize_by_persist(tmp, final_path, label, Some(anchor))
    }
}

/// Path-based encrypted-output commit for targets whose production backend
/// deliberately remains path-based. Unlike [`finalize_file`], this route does
/// not make the caller open and retain a directory handle that the primary
/// commit cannot use. That preserves the pre-existing output-directory access
/// requirements on Windows and on the other non-Linux/macOS targets.
///
/// A Unix filesystem that rejects `tempfile`'s one-step no-replace persist
/// still reaches the shared link-or-claim compatibility fallback. Only that
/// exceptional route opens the readable directory anchor it needs, matching
/// the behaviour before writer commits became handle-relative on Linux and
/// macOS.
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub(crate) fn finalize_file_path_based(
    tmp: NamedTempFile,
    final_path: &Path,
    label: &str,
) -> Result<FinalizedFile, FinalizeFileError> {
    finalize_by_persist(tmp, final_path, label, None)
}

/// `tempfile`'s one-step no-replace persist, the primary route off Linux
/// and macOS. `anchor` is the directory handle the caller retains, where
/// it holds one: the Unix compatibility fallback commits through it, and
/// opens a readable handle of its own where the caller holds none.
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn finalize_by_persist(
    tmp: NamedTempFile,
    final_path: &Path,
    label: &str,
    anchor: Option<&OutputDir>,
) -> Result<FinalizedFile, FinalizeFileError> {
    match tmp.persist_noclobber(final_path) {
        Ok(file) => finalized_from_persist(file, final_path),
        Err(e) => finalize_persist_failure(e, final_path, label, anchor),
    }
}

/// The Linux and macOS commit: a no-replace rename resolved through
/// `anchor` ([`crate::fs::commit::rename_no_replace_at`]), falling back
/// to the link-or-claim commit where the filesystem cannot perform one.
///
/// Both endpoints resolve through the retained handle, so a rename or
/// replacement of the output path between staging and the commit cannot
/// redirect it — the same anchoring archive extraction has committed
/// through since it gained one. The staged temporary is confirmed to be
/// the entry under its name in that directory before any step runs, so
/// a temporary moved out of the anchored directory can never commit a
/// same-named entry of some other directory's in its place.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn finalize_file_at(
    tmp: NamedTempFile,
    final_path: &Path,
    label: &str,
    anchor: &OutputDir,
) -> Result<FinalizedFile, FinalizeFileError> {
    use crate::fs::commit::{FlaggedRename, commit_by_link_or_claim, rename_no_replace_at};

    finalize_file_commit(
        tmp,
        final_path,
        label,
        anchor,
        |anchor, staged, final_name| match rename_no_replace_at(anchor, staged, final_name) {
            Ok(FlaggedRename::Committed) => Ok(CommitRoute::Renamed),
            Ok(FlaggedRename::Unsupported) => {
                commit_by_link_or_claim(anchor, staged, final_name, CommitKind::File)
            }
            Err(error) => Err(CommitFailure::plain(error)),
        },
    )
}

/// Completes a successful one-step persist: parent flush, retained
/// committed handle, and the reported-path and single-link confirmations.
///
/// Windows and the other Unix targets only: Linux and macOS commit
/// through `finalize_file_at` instead.
///
/// The link count is required even on this arm because `tempfile` retries
/// a rejected no-replace rename on Unix through a hard link of its own and
/// discards the unlink of the staged name, so its `Ok` alone does not
/// prove the staged name is gone; and on every platform a link a local
/// writer created against the staged temporary before the commit
/// survives it.
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn finalized_from_persist(
    file: std::fs::File,
    final_path: &Path,
) -> Result<FinalizedFile, FinalizeFileError> {
    sync_parent_dir(final_path);
    let finalized = FinalizedFile::new(file);
    let finding = finalized.confirm_reported_path(final_path).err();
    finalized.into_confirmed(final_path, finding)
}

/// Failure arm of [`finalize_by_persist`] on the Unix targets outside
/// Linux and macOS. A filesystem that cannot perform the flagged rename
/// reaches the shared link-or-claim fallback — through `anchor` where the
/// caller holds one, otherwise through a readable handle opened for it —
/// and every other failure is mapped and returned.
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn finalize_persist_failure(
    e: tempfile::PersistError,
    final_path: &Path,
    label: &str,
    anchor: Option<&OutputDir>,
) -> Result<FinalizedFile, FinalizeFileError> {
    if no_replace_rename_unsupported(&e.error) {
        return match anchor {
            Some(anchor) => finalize_file_via_link_or_claim_in(e.file, final_path, label, anchor),
            None => finalize_file_via_link_or_claim(e.file, final_path, label),
        };
    }
    Err(FinalizeFileError::before_commit(map_persist_error(
        e.error, final_path, label,
    )))
}

/// No compatibility fallback exists off Unix, so the anchor has no route
/// to serve. In particular, Windows keeps `tempfile`'s path-based atomic
/// no-replace move without first opening the output directory for read
/// access.
#[cfg(not(unix))]
fn finalize_persist_failure(
    e: tempfile::PersistError,
    final_path: &Path,
    label: &str,
    _anchor: Option<&OutputDir>,
) -> Result<FinalizedFile, FinalizeFileError> {
    Err(FinalizeFileError::before_commit(map_persist_error(
        e.error, final_path, label,
    )))
}

/// Maps a failed promotion to the caller-visible error: an occupied
/// final path becomes the typed already-exists message, everything
/// else passes through as [`CryptoError::Io`].
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn map_persist_error(error: io::Error, final_path: &Path, label: &str) -> CryptoError {
    if error.kind() == io::ErrorKind::AlreadyExists {
        already_exists_error(label, final_path)
    } else {
        CryptoError::Io(error)
    }
}

/// Whether an operation failed because the kernel or filesystem does
/// not support it at all, as opposed to an ordinary failure of a
/// supported operation: [`fs_operation_unsupported`], or
/// [`io::ErrorKind::Unsupported`], which covers `ENOSYS` (kernels without
/// the syscall) and synthesized non-OS errors of that kind.
#[cfg(unix)]
pub(crate) fn errno_not_supported(e: &io::Error) -> bool {
    e.kind() == io::ErrorKind::Unsupported || fs_operation_unsupported(e)
}

/// Whether `e` is `ENOTSUP` or `EOPNOTSUPP`, the errors a filesystem returns
/// for an operation it does not support. Unlike [`errno_not_supported`], a
/// missing system call (`ENOSYS`) and a synthesized error do not count:
/// they are a kernel or sandbox refusing a call and say nothing about the
/// filesystem. Whether a required directory flush counts as done builds on
/// this narrower check.
///
/// The raw errno values are matched, not [`io::ErrorKind`], because the
/// std mapping does not cover them on every platform — macOS `ENOTSUP`
/// (45), the error its exFAT and smbfs drivers return for unsupported
/// operations, surfaces as an uncategorized kind. `ENOTSUP` and
/// `EOPNOTSUPP` share a value on Linux but differ on macOS; both are listed
/// and the duplicate arm collapses where equal.
#[cfg(unix)]
fn fs_operation_unsupported(e: &io::Error) -> bool {
    matches!(
        e.raw_os_error(),
        Some(code) if code == libc::ENOTSUP || code == libc::EOPNOTSUPP
    )
}

/// Whether a failed no-replace rename means the kernel or filesystem
/// cannot perform one at all, as opposed to an ordinary failure of a
/// supported rename.
///
/// Beyond [`errno_not_supported`] (macOS `renameatx_np(RENAME_EXCL)`
/// on filesystems without the operation — exFAT and smbfs among them —
/// and `hard_link`-based emulation on filesystems without hard links),
/// raw `EINVAL` is included: Linux `renameat2` reports an unsupported
/// `RENAME_NOREPLACE` flag on some filesystems (network and FUSE
/// mounts) as an invalid-flag error. A genuine invalid-argument
/// failure that slips through simply fails again inside the fallback,
/// so the wide trigger cannot weaken the no-clobber guarantee.
///
/// The `EINVAL` arm is load-bearing for every caller that issues the
/// flagged rename itself: [`crate::fs::commit::rename_no_replace_at`],
/// which both the encrypted-output commit and the archive promotion go
/// through on Linux and macOS. Only where `tempfile` performs the
/// rename — Windows and the other Unix targets — is that arm
/// unreachable, because `tempfile` retries `EINVAL` itself through its
/// hard-link emulation.
#[cfg(unix)]
pub(crate) fn no_replace_rename_unsupported(e: &io::Error) -> bool {
    errno_not_supported(e) || e.raw_os_error() == Some(libc::EINVAL)
}

/// Flushes `fd` with `fsync(2)`, retrying on `EINTR`.
///
/// Every flush that calls `fsync` directly, rather than through
/// `File::sync_all`, goes through this function. `File::sync_all` retries
/// internally, but `rustix` reports a signal-interrupted call as `EINTR`.
/// Without the retry, a signal arriving during the flush would fail the
/// operation, or leave it silently unflushed where the caller discards
/// the error.
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn fsync_uninterrupted<Fd: std::os::fd::AsFd>(fd: Fd) -> io::Result<()> {
    rustix::io::retry_on_intr(|| rustix::fs::fsync(&fd)).map_err(io::Error::from)
}

/// Flushes `fd` with the strongest flush the platform offers, retrying on
/// `EINTR`: `F_FULLFSYNC` on macOS, which also asks the drive to commit its
/// volatile cache, and `fsync(2)` on Linux. On these two targets every
/// flush rule starts with this call rather than `File::sync_all`, whose
/// documentation does not say which call it makes on macOS. On Linux it is
/// the same call as the plain flush a rule falls back to.
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn full_fsync_uninterrupted<Fd: std::os::fd::AsFd>(fd: Fd) -> io::Result<()> {
    #[cfg(target_os = "macos")]
    {
        rustix::io::retry_on_intr(|| rustix::fs::fcntl_fullfsync(&fd)).map_err(io::Error::from)
    }
    #[cfg(target_os = "linux")]
    {
        fsync_uninterrupted(fd)
    }
}

/// Flushes `file` to stable storage with the strongest primitive the
/// filesystem supports. On Linux and macOS the full flush
/// (`full_fsync_uninterrupted`, `F_FULLFSYNC` on macOS) is the primary; a
/// filesystem that reports it as unsupported (macOS smbfs does, on some
/// servers) falls back to plain `fsync(2)`, which such filesystems do honor.
/// Genuine sync failures surface unchanged; only the capability gap
/// downgrades. `flush_file_with_fallback` holds that rule. Other targets use
/// `File::sync_all`.
///
/// Directory extraction deliberately does not use this helper per file:
/// it applies `archive::platform::sync_file_standard` to each staged
/// file, then pays for one operation-level full barrier through
/// `sync_extraction_barrier`. Single-file extraction keeps the strongest
/// flush through `archive::platform::sync_single_file_durable`.
pub(crate) fn sync_file_durable(file: &std::fs::File) -> io::Result<()> {
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        flush_file_with_fallback(
            || full_fsync_uninterrupted(file),
            || fsync_uninterrupted(file),
        )
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        file.sync_all()
    }
}

/// Flushes the directory entries in `dir` to stable storage and reports
/// failures. Flushing a file makes its contents durable, but not the directory
/// entry that names it. A rename or removal is durable only after the
/// directory is flushed.
///
/// Unlike [`sync_parent_dir`], this function returns genuine open or flush
/// failures so callers can stop when durability is required. If the filesystem
/// does not support directory flushing, which [`flush_opened_dir`] decides,
/// that condition counts as success because no stronger operation is
/// available. In that case, protection from power loss depends on the
/// filesystem; key generation still retains its private-first protection
/// against process interruption.
#[cfg(unix)]
pub(crate) fn sync_dir_durable(dir: &Path) -> io::Result<()> {
    use std::os::unix::fs::OpenOptionsExt;

    // `O_DIRECTORY` ensures that `dir` is a directory. A regular file
    // therefore returns `NotADirectory` instead of being flushed, and a
    // substituted FIFO or device node is refused rather than opened.
    // `O_NONBLOCK` keeps that refusal immediate on a platform that
    // checks the directory requirement only after opening the object.
    flush_opened_dir(
        std::fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_DIRECTORY | libc::O_NONBLOCK)
            .open(dir),
    )
}

/// Flushes the entries of the directory `dir` refers to and reports
/// failures, as [`sync_dir_durable`] does for a path. The directory is
/// reopened through the handle ([`reopen_dir_for_flush`]), so the flush
/// covers it even if its path was renamed since.
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn sync_dir_durable_at<Fd: std::os::fd::AsFd>(dir: Fd) -> io::Result<()> {
    flush_opened_dir(reopen_dir_for_flush(dir).map(std::fs::File::from))
}

/// Flushes the directory `opened` holds, given the result of opening it.
/// Every required directory flush on Unix goes through this function.
///
/// A failed open counts as a filesystem without directory flushing, and so
/// as a completed flush, only when the filesystem reports the operation as
/// unsupported ([`fs_operation_unsupported`]). Every other failure is
/// returned, a missing system call (`ENOSYS`) included. An ordinary
/// directory open that fails with `EINVAL` or `EBADF` reports a broken call
/// or handle, not a missing capability; the wider [`dir_sync_unsupported`]
/// applies only to the flush, where some network and FUSE filesystems return
/// those errors when directory `fsync` is unavailable.
///
/// Permission denial (`EACCES`) is not a missing capability either. A
/// write-only directory refuses the read handle that directory flushing
/// needs, so the barrier is denied, and the operation that requires it must
/// stop rather than report success without making the entries durable.
#[cfg(unix)]
fn flush_opened_dir(opened: io::Result<std::fs::File>) -> io::Result<()> {
    match opened {
        Ok(handle) => flush_dir_handle(&handle),
        Err(e) if fs_operation_unsupported(&e) => Ok(()),
        Err(e) => Err(e),
    }
}

/// Flushes an already-open directory handle with the strongest flush the
/// filesystem supports, and counts a filesystem that provides no directory
/// flushing as flushed, because no stronger operation exists there. On
/// Linux and macOS the full flush is `full_fsync_uninterrupted`, and
/// `flush_dir_with_fallback` decides when plain `fsync` takes over; other
/// targets have `File::sync_all` alone. Directory flushing has a wider set
/// of unsupported errors than file flushing ([`dir_sync_unsupported`]).
#[cfg(unix)]
fn flush_dir_handle(handle: &std::fs::File) -> io::Result<()> {
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        flush_dir_with_fallback(
            || full_fsync_uninterrupted(handle),
            || fsync_uninterrupted(handle),
        )
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        match handle.sync_all() {
            Ok(()) => Ok(()),
            Err(e) if dir_sync_unsupported(&e) => Ok(()),
            Err(e) => Err(e),
        }
    }
}

/// The file-flush fallback rule: runs `full`, the strongest flush, and runs
/// `plain` instead when `full` reports the operation as unsupported
/// ([`errno_not_supported`]), returning what `plain` returns. Any other
/// failure of `full` is returned without attempting `plain`.
///
/// [`sync_file_durable`] and `archive::platform::sync_single_file_durable`
/// both apply this rule. The two flushes are passed in so that tests can
/// drive every branch with injected errors.
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn flush_file_with_fallback(
    full: impl FnOnce() -> io::Result<()>,
    plain: impl FnOnce() -> io::Result<()>,
) -> io::Result<()> {
    match full() {
        Ok(()) => Ok(()),
        Err(e) if errno_not_supported(&e) => plain(),
        Err(e) => Err(e),
    }
}

/// The directory-flush fallback rule: runs `full`, and runs `plain` when
/// `full` is not available ([`errno_not_supported`], a missing system call
/// included) or reports directory flushing as unsupported
/// ([`dir_sync_unsupported`]). If `plain` reports directory flushing as
/// unsupported as well, the filesystem provides no directory flushing at
/// all, which counts as success because no stronger operation exists there.
/// Any other failure of either flush is returned, a missing `plain` call
/// included.
///
/// Every directory flush on Linux and macOS that reports failures applies
/// this rule through [`flush_dir_handle`]. As for
/// [`flush_file_with_fallback`], the two flushes are passed in so that tests
/// can drive every branch with injected errors.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn flush_dir_with_fallback(
    full: impl FnOnce() -> io::Result<()>,
    plain: impl FnOnce() -> io::Result<()>,
) -> io::Result<()> {
    match full() {
        Ok(()) => Ok(()),
        Err(e) if errno_not_supported(&e) || dir_sync_unsupported(&e) => match plain() {
            Ok(()) => Ok(()),
            Err(again) if dir_sync_unsupported(&again) => Ok(()),
            Err(again) => Err(again),
        },
        Err(e) => Err(e),
    }
}

/// Opens `.` through the directory handle `dir`, giving a handle that a
/// flush can use.
///
/// cap-std may hold a directory as an `O_PATH` handle on Linux, which
/// `fsync` refuses with `EBADF`. The new handle can be flushed whether or
/// not `dir` is such a handle, and no ambient path is resolved, so the flush
/// covers the directory `dir` refers to even if its path was renamed since.
/// The open is retried on `EINTR`, so a signal cannot fail or skip a
/// durability barrier. A required flush goes through
/// [`sync_dir_durable_at`], which applies the rule of [`flush_opened_dir`]
/// to the result.
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn reopen_dir_for_flush<Fd: std::os::fd::AsFd>(
    dir: Fd,
) -> io::Result<std::os::fd::OwnedFd> {
    use rustix::fs::{Mode, OFlags, openat};

    rustix::io::retry_on_intr(|| {
        openat(
            dir.as_fd(),
            ".",
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
            Mode::empty(),
        )
    })
    .map_err(io::Error::from)
}

/// Windows implementation of [`sync_dir_durable`]. Opening a directory
/// requires the backup-semantics flag, and `FlushFileBuffers` requires write
/// access. The metadata check rejects a non-directory path, matching the Unix
/// `O_DIRECTORY` behavior.
#[cfg(windows)]
pub(crate) fn sync_dir_durable(dir: &Path) -> io::Result<()> {
    use std::os::windows::fs::OpenOptionsExt;

    let handle = match std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
        .open(dir)
    {
        Ok(handle) => handle,
        Err(e) if dir_sync_unsupported(&e) => return Ok(()),
        Err(e) => return Err(e),
    };
    if !handle.metadata()?.is_dir() {
        return Err(io::Error::new(
            io::ErrorKind::NotADirectory,
            "Path to flush is not a directory",
        ));
    }
    match handle.sync_all() {
        Ok(()) => Ok(()),
        Err(e) if dir_sync_unsupported(&e) => Ok(()),
        Err(e) => Err(e),
    }
}

/// Returns whether a directory flush failed because the filesystem does not
/// provide directory flushing, rather than because a supported flush failed.
///
/// - [`fs_operation_unsupported`] covers a filesystem that reports the
///   operation as unsupported; a missing system call (`ENOSYS`) does not
///   count.
/// - `EINVAL` and `EBADF` are returned by some network and FUSE filesystems
///   when directory `fsync` is unavailable.
///
/// The open that precedes a required flush follows the narrower rule of
/// [`flush_opened_dir`].
#[cfg(unix)]
fn dir_sync_unsupported(e: &io::Error) -> bool {
    fs_operation_unsupported(e)
        || matches!(
            e.raw_os_error(),
            Some(code) if code == libc::EINVAL || code == libc::EBADF
        )
}

/// Windows counterpart of the Unix classification. The Windows
/// [`sync_dir_durable`] applies it to the directory open as well as to the
/// flush. `ERROR_INVALID_FUNCTION`, `ERROR_NOT_SUPPORTED`, and
/// `ERROR_INVALID_PARAMETER` indicate that the volume or network provider
/// cannot flush directory entries.
///
/// Access denial is deliberately excluded, matching the Unix treatment of
/// `EACCES`. A directory that cannot be opened with the write access
/// `FlushFileBuffers` needs is a denied barrier, not a missing capability, so
/// key generation must fail rather than report success without making its
/// directory entries durable.
#[cfg(windows)]
fn dir_sync_unsupported(e: &io::Error) -> bool {
    const ERROR_INVALID_FUNCTION: i32 = 1;
    const ERROR_NOT_SUPPORTED: i32 = 50;
    const ERROR_INVALID_PARAMETER: i32 = 87;

    e.kind() == io::ErrorKind::Unsupported
        || matches!(
            e.raw_os_error(),
            Some(ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED | ERROR_INVALID_PARAMETER)
        )
}

/// A retained handle to the directory an operation publishes into.
///
/// An operation that commits more than one entry, or that has to undo a
/// commit it already made, performs those later steps once its own first
/// write is already visible on disk. Resolving them through the ambient
/// output path again lets a rename, or a symlink substituted at that
/// path, send a removal into a different directory, where it can unlink
/// a file the operation never created. Removals therefore stay inside this
/// handle's directory. On Unix the final identity check and unlink remain two
/// operations, with the substitution instant documented in `SECURITY.md`; on
/// Windows deletion is bound to the retained file handle itself.
///
/// The handle does not make the chosen directory trustworthy. The
/// caller's choice of output directory IS the trust boundary, and a path
/// already substituted before the handle is opened simply anchors the
/// whole operation there. What the handle removes is the mismatch
/// between the directory an operation wrote to and the directory it
/// later cleans up in.
///
/// `cap_std::fs::Dir` is the same capability primitive the archive
/// extractor anchors to. On Linux and macOS its removals are
/// handle-relative. On Windows, cap-std resolves the handle to the
/// directory's current path for every name-based operation; the
/// anchored directory itself cannot be renamed or removed while this
/// handle is open, because cap-std opens directories without delete
/// sharing, so that path denotes it. The rollback's removal there does
/// not go by name at all: it deletes through the retained committed
/// handle, so it can only ever delete the file that handle refers to.
pub(crate) struct OutputDir {
    dir: cap_std::fs::Dir,
}

impl OutputDir {
    /// Opens `path` as the anchor for the operation's own cleanup, and
    /// for anything else it has to read there. Needs a readable output
    /// directory; `SECURITY.md` records that requirement.
    pub(crate) fn open(path: &Path) -> io::Result<Self> {
        let dir = cap_std::fs::Dir::open_ambient_dir(path, cap_std::ambient_authority())?;
        Ok(Self { dir })
    }

    /// Opens `path` as the anchor for a commit alone, preferring the
    /// narrowest access a commit needs
    /// ([`crate::fs::commit::open_commit_anchor`]). An output directory
    /// that grants write and search but not read therefore still
    /// receives encrypted output on Linux and macOS, and a filesystem
    /// that refuses the narrow open still commits through an ordinary
    /// directory handle. Production encrypted output calls this only on
    /// those two targets; its other-target backend remains path-based.
    ///
    /// Not for key generation, which reopens its anchor for a required
    /// durability barrier and so keeps the readable requirement of
    /// [`Self::open`].
    #[cfg(any(test, target_os = "linux", target_os = "macos"))]
    pub(crate) fn open_for_commit(path: &Path) -> io::Result<Self> {
        Ok(Self {
            dir: crate::fs::commit::open_commit_anchor(path)?,
        })
    }

    /// Requires `tmp` to be the entry under its own name in this
    /// directory, before a caller writes any content into it.
    ///
    /// A commit resolves the staged name through this handle, so the
    /// staged file must be an entry of the anchored directory. Checking
    /// it at staging time rather than only at the commit means a
    /// destination replaced in the window between opening this handle
    /// and creating the temporary is refused before the operation pays
    /// for the whole write. Off Unix the commit does not resolve
    /// through the handle, so there is nothing to confirm.
    #[cfg(unix)]
    pub(crate) fn confirm_staged(&self, tmp: &NamedTempFile) -> Result<(), CryptoError> {
        let Some(name) = tmp.path().file_name() else {
            return Err(CryptoError::Io(no_final_component_error()));
        };
        require_staged_temp_in_output_dir(tmp, self, name)
    }

    #[cfg(not(unix))]
    pub(crate) fn confirm_staged(&self, _tmp: &NamedTempFile) -> Result<(), CryptoError> {
        Ok(())
    }

    /// Removes a still-staged key-file temporary only while the entry under
    /// its random name in this anchored directory is still the file whose
    /// handle the caller retained. The `NamedTempFile` destructor is disarmed
    /// first: after the output directory has been renamed, its recorded
    /// ambient path can lead to a replacement directory and must not drive
    /// cleanup there.
    ///
    /// The returned rollback, tagged [`RemovedFile::Staged`], must be reported
    /// unless its outcome is [`RollbackOutcome::Removed`]. On Unix, removal is
    /// by name inside this anchor after the identity comparison; on Windows it
    /// is through the retained file handle, matching committed-key rollback.
    #[must_use = "the outcome says whether the staged file is gone; report it"]
    pub(crate) fn remove_staged_if_retained(&self, tmp: NamedTempFile) -> Rollback {
        let outcome = match tmp.path().file_name().map(|name| name.to_os_string()) {
            Some(name) => {
                let (retained, temp_path) = tmp.into_parts();
                let _ = temp_path.keep();
                self.remove_if_retained(&name, retained)
            }
            None => {
                let _ = tmp.into_temp_path().keep();
                RollbackOutcome::Unconfirmed
            }
        };
        Rollback {
            outcome,
            file: RemovedFile::Staged,
        }
    }

    /// Removes the entry named by `path`'s final component, resolved
    /// inside the anchored directory, but only while that entry is still
    /// the committed file `finalized` retains, compared by identity
    /// without following symlinks. A rollback runs once its commit is
    /// already visible, so an entry replaced in that window must be left
    /// in place rather than deleted; the committed file then survives
    /// under whatever name it was moved to. An entry or handle whose
    /// identity cannot be read is left in place on the same terms: an
    /// unconfirmed entry is not this operation's to remove. The returned
    /// [`Rollback`], tagged [`RemovedFile::Committed`], says whether the file
    /// is gone, so the caller can report a rollback that left the file, or
    /// another name for it, behind. The link count is read through the
    /// retained handle before the removal; a name added after that read is
    /// not counted. The identity, and what it cannot distinguish, is
    /// [`file_identity`]'s.
    ///
    /// The committed handle is consumed and closed here, so the removal
    /// is complete when this returns. What the removal acts on is
    /// [`remove_retained`]'s: on Unix the name, unlinked inside the
    /// anchored directory; on Windows the retained handle itself.
    #[must_use = "the outcome says whether the committed file is gone; report it"]
    pub(crate) fn remove_published_if_retained(
        &self,
        path: &Path,
        finalized: FinalizedFile,
    ) -> Rollback {
        let outcome = match path.file_name() {
            Some(name) => self.remove_if_retained(name, finalized.file),
            None => RollbackOutcome::Unconfirmed,
        };
        Rollback {
            outcome,
            file: RemovedFile::Committed,
        }
    }

    /// The identity-checked removal behind
    /// [`Self::remove_published_if_retained`]: an entry of the anchored
    /// directory whose creator still holds a handle to it, which here
    /// is a committed key file.
    fn remove_if_retained(
        &self,
        name: &std::ffi::OsStr,
        retained: std::fs::File,
    ) -> RollbackOutcome {
        self.remove_if_retained_with(name, retained, || {})
    }

    /// Testable [`Self::remove_if_retained`]: `between` runs after the
    /// identity check and before the removal, where a local writer's
    /// replacement would land.
    fn remove_if_retained_with(
        &self,
        name: &std::ffi::OsStr,
        retained: std::fs::File,
        between: impl FnOnce(),
    ) -> RollbackOutcome {
        use cap_fs_ext::MetadataExt;

        let Ok(committed) = cap_std::fs::Metadata::from_file(&retained) else {
            return RollbackOutcome::Unconfirmed;
        };
        let Ok(entry) = self.dir.symlink_metadata(name) else {
            return RollbackOutcome::Unconfirmed;
        };
        if !entry.is_file() {
            return RollbackOutcome::Replaced;
        }
        // Removing needs a match, and an identity that carries no
        // information cannot supply one.
        match (file_identity(&entry), file_identity(&committed)) {
            (Some(entry_id), Some(committed_id)) if entry_id == committed_id => {}
            (Some(_), Some(_)) => return RollbackOutcome::Replaced,
            _ => return RollbackOutcome::Unconfirmed,
        }
        between();
        if remove_retained(&self.dir, name, retained).is_err() {
            return RollbackOutcome::Unconfirmed;
        }
        match committed.nlink() {
            1 => RollbackOutcome::Removed,
            link_count => RollbackOutcome::RemovedButLinked { link_count },
        }
    }

    /// Flushes the anchored directory's entries through the held handle
    /// ([`sync_dir_durable_at`]), so the barrier covers the directory the
    /// entries were committed to even if the ambient path was renamed
    /// since. Genuine open and flush failures are reported so a caller
    /// that requires durability can stop.
    ///
    /// The reopen needs read permission, exactly what the path-based
    /// flush needs, so restrictive directories refuse both the same way.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub(crate) fn flush_durable(&self) -> io::Result<()> {
        sync_dir_durable_at(&self.dir)
    }
}

/// Removes the object `retained` refers to, once its identity has been
/// confirmed under `name` in `dir`, and closes the handle. Unix has no
/// removal by descriptor, so the name is unlinked inside the anchored
/// directory; an entry replaced in the instant between the check and the
/// unlink is what that removal then reaches, a bound `SECURITY.md`
/// states.
#[cfg(unix)]
fn remove_retained(
    dir: &cap_std::fs::Dir,
    name: &std::ffi::OsStr,
    retained: std::fs::File,
) -> io::Result<()> {
    let result = dir.remove_file(name);
    drop(retained);
    result
}

/// Windows removes through the handle itself: the file is reopened from
/// `retained` — a relative open of the same object, no path involved —
/// with the delete-on-close flag, and the deletion takes effect when the
/// last handle closes, which happens here. An entry replaced in the
/// instant between the identity check and this call therefore survives:
/// the removal can only ever delete the file the handle refers to. The
/// reopen relies on `tempfile` opening its named temporaries with the
/// default sharing mode, which permits a delete-access open of the same
/// file, and requires the original handle to have been opened for
/// writing, as every committed file here was.
#[cfg(windows)]
fn remove_retained(
    _dir: &cap_std::fs::Dir,
    _name: &std::ffi::OsStr,
    retained: std::fs::File,
) -> io::Result<()> {
    use cap_fs_ext::Reopen;
    use cap_std::fs::OpenOptionsExt;

    let mut options = cap_std::fs::OpenOptions::new();
    options
        .access_mode(DELETE | FILE_READ_ATTRIBUTES)
        .custom_flags(FILE_FLAG_DELETE_ON_CLOSE);
    let marked_for_deletion = retained.reopen(&options)?;
    drop(marked_for_deletion);
    drop(retained);
    Ok(())
}

/// Access right to delete an object, from `WinNT.h`.
#[cfg(windows)]
const DELETE: u32 = 0x0001_0000;

/// Access right to read an object's attributes, from `WinNT.h`.
#[cfg(windows)]
const FILE_READ_ATTRIBUTES: u32 = 0x0080;

/// `CreateFileW` flag that deletes the file when its last handle closes.
#[cfg(windows)]
const FILE_FLAG_DELETE_ON_CLOSE: u32 = 0x0400_0000;

/// Error for a path with no final component: there is no name to link,
/// claim, or rename to, so the commit rejects rather than falling back
/// to some other entry.
#[cfg(unix)]
fn no_final_component_error() -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidInput,
        "Output path has no final component",
    )
}

/// Commits `tmp` to `final_path` where `tempfile` could not perform an
/// atomic no-replace rename, keeping the no-clobber guarantee against
/// entries that predate the commit.
///
/// The whole fallback commit is anchored. Linux/macOS encryption and key
/// generation receive the [`OutputDir`] their caller opened before staging;
/// path-based encryption on the other Unix targets opens one here only after
/// the primary persist proves unsupported. The link, claim, rename, and every
/// removal then resolve through that handle. The staged temp file must be an
/// entry of the same directory, and the route refuses to start until the entry
/// under its name is confirmed by identity to be the staged file itself.
/// Linux/macOS encryption's anchor requires search but not permission to list
/// the directory; key generation and the ordinary-handle fallback on other
/// Unix targets retain the readable-directory requirement documented in
/// `SECURITY.md`.
///
/// Which route reaches the final name is
/// [`crate::fs::commit::commit_by_link_or_claim`]'s, the same commit
/// archive extraction reaches on these filesystems: a link where the
/// filesystem has hard links, a claim over which the staged entry is
/// renamed where it has none. `tempfile` does not retry the
/// unsupported-operation error that leads here: its own link fallback
/// answers only a no-replace flag reported as unknown or invalid, and
/// discards that fallback's unlink result — which is why the persist
/// arm requires the single-link confirmation as well.
///
/// What is finished here is the route's post-condition. If the
/// staged-name unlink fails after a link commit, the operation reports a
/// post-commit error and preserves both complete links; it never removes
/// the final name after a potentially delayed failure. A successful or
/// missing-name unlink is accepted only when the retained committed
/// handle reports one link, which catches a concurrent move of the
/// staged link and a successful unlink of a planted replacement.
/// The wrapper below is production code only for path-based encryption on the
/// other Unix targets; Linux/macOS tests also use it to exercise a fallback
/// their ordinary filesystem may not select.
#[cfg(all(unix, any(test, not(any(target_os = "linux", target_os = "macos")))))]
fn finalize_file_via_link_or_claim(
    tmp: NamedTempFile,
    final_path: &Path,
    label: &str,
) -> Result<FinalizedFile, FinalizeFileError> {
    let output_dir = OutputDir::open(crate::fs::paths::parent_or_cwd(final_path))
        .map_err(CryptoError::Io)
        .map_err(FinalizeFileError::before_commit)?;
    finalize_file_via_link_or_claim_in(tmp, final_path, label, &output_dir)
}

/// Commits through the link-or-claim fallback using an already-open anchor.
// Reached in production only on the Unix targets without a
// handle-relative commit; elsewhere the tests drive it to exercise
// the route a filesystem with a working no-replace rename never takes.
#[cfg_attr(any(target_os = "linux", target_os = "macos"), allow(dead_code))]
#[cfg(unix)]
fn finalize_file_via_link_or_claim_in(
    tmp: NamedTempFile,
    final_path: &Path,
    label: &str,
    output_dir: &OutputDir,
) -> Result<FinalizedFile, FinalizeFileError> {
    finalize_file_commit(
        tmp,
        final_path,
        label,
        output_dir,
        |anchor, staged, final_name| {
            crate::fs::commit::commit_by_link_or_claim(anchor, staged, final_name, CommitKind::File)
        },
    )
}

/// The part of a fallback commit that does not depend on which route
/// reached the final name: confirm the staged temporary against the
/// anchor, run `commit`, and finish the route it reports.
///
/// `commit` is a parameter so a test can drive the claim route directly
/// on a filesystem whose hard links would always win the link-first
/// entry point above.
#[cfg(unix)]
fn finalize_file_commit(
    tmp: NamedTempFile,
    final_path: &Path,
    label: &str,
    output_dir: &OutputDir,
    commit: impl FnOnce(
        &cap_std::fs::Dir,
        &std::ffi::OsStr,
        &std::ffi::OsStr,
    ) -> Result<CommitRoute, CommitFailure>,
) -> Result<FinalizedFile, FinalizeFileError> {
    // Owned, because the arms below consume `tmp` while the staged
    // name is still needed.
    let Some(tmp_name) = tmp.path().file_name().map(|name| name.to_os_string()) else {
        // With no staged name to verify against the anchor, retain the
        // existing best-effort destructor behaviour. It attempts the recorded
        // ambient path, which may no longer lead to the original directory.
        return Err(FinalizeFileError::before_commit(CryptoError::Io(
            no_final_component_error(),
        )));
    };
    // Verified before any removal resolves through the anchor, so a
    // same-named entry there is never unlinked in place of a temp that
    // was staged somewhere else.
    if let Err(error) = require_staged_temp_in_output_dir(&tmp, output_dir, &tmp_name) {
        // `tmp` drops here and its destructor attempts cleanup through the
        // recorded ambient path. This is the pre-existing staging policy; a
        // parent rename can make that path differ from the anchored directory.
        return Err(FinalizeFileError::before_commit(error));
    }
    let Some(final_name) = final_path.file_name() else {
        let _ = remove_staged_temp(tmp, output_dir);
        return Err(FinalizeFileError::before_commit(CryptoError::Io(
            no_final_component_error(),
        )));
    };
    match commit(&output_dir.dir, &tmp_name, final_name) {
        Ok(CommitRoute::Linked) => {
            finish_link_commit(tmp, output_dir, final_path, final_name, &tmp_name)
        }
        Ok(CommitRoute::Renamed) => finish_renamed_commit(tmp, output_dir, final_path),
        Err(failure) => {
            let _ = remove_staged_temp(tmp, output_dir);
            let error = if failure.error.kind() == io::ErrorKind::AlreadyExists {
                already_exists_error(label, final_path)
            } else {
                CryptoError::Io(failure.error)
            };
            // A final name the commit claimed is left in place and may
            // still be occupied, where it blocks the next attempt, so it
            // is reported. No content from this run's staged file reached
            // that name: the commit failed before it could be moved there.
            Err(FinalizeFileError::before_commit(if failure.claim_left {
                crate::error::append_report(error, &claim_left_report(final_path))
            } else {
                error
            }))
        }
    }
}

/// Finishes a commit a rename reached — the flagged no-replace rename,
/// or the claim route's rename over its own placeholder. Either moved
/// the staged file's inode to the final name, so the handle held since
/// staging is the committed one and needs no reopen.
#[cfg(unix)]
fn finish_renamed_commit(
    tmp: NamedTempFile,
    output_dir: &OutputDir,
    final_path: &Path,
) -> Result<FinalizedFile, FinalizeFileError> {
    // The rename moved the staged entry away, so disarm the destructor:
    // its unlink could only ever reach an entry another process creates
    // at the freed temp name afterwards. Not [`remove_staged_temp`], for
    // the same reason.
    let (file, temp_path) = tmp.into_parts();
    let _ = temp_path.keep();
    sync_committed_parent(output_dir, final_path);

    let finalized = FinalizedFile::new(file);
    let finding = finalized.confirm_reported_path(final_path).err();
    finalized.into_confirmed(final_path, finding)
}

/// Requires the entry under the staged name in the anchored destination
/// directory to be the staged file itself, before any fallback commit step
/// runs. Both routes resolve the staged name through the anchor, so the
/// commit must be refused when that entry is missing or is another
/// object — whether a caller staged the temporary in some other
/// directory, or a local writer deleted or replaced the staged entry
/// while the operation ran. The entry is read without following
/// symlinks, so a link planted under the staged name cannot satisfy the
/// comparison either.
#[cfg(unix)]
fn require_staged_temp_in_output_dir(
    tmp: &NamedTempFile,
    output_dir: &OutputDir,
    tmp_name: &std::ffi::OsStr,
) -> Result<(), CryptoError> {
    let staged = cap_std::fs::Metadata::from_file(tmp.as_file()).map_err(CryptoError::Io)?;
    let entry = match output_dir.dir.symlink_metadata(tmp_name) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            return Err(staged_temp_not_in_output_dir(tmp_name));
        }
        Err(error) => return Err(CryptoError::Io(error)),
    };
    if !entry.is_file() || identities_differ(&entry, &staged) {
        return Err(staged_temp_not_in_output_dir(tmp_name));
    }
    Ok(())
}

/// Rejection from [`require_staged_temp_in_output_dir`]: the entry under
/// the staged name is missing or is not the staged file. A local writer
/// deleting or replacing the staged entry reaches this in ordinary
/// operation on the filesystems that use the fallback route, so the
/// error reports a filesystem condition rather than a library bug.
#[cfg(unix)]
fn staged_temp_not_in_output_dir(staged_name: &std::ffi::OsStr) -> CryptoError {
    CryptoError::InvalidInput(format!(
        "Staged temporary file {} is not the entry under its name in the destination directory",
        sanitize_path_for_display(Path::new(staged_name)),
    ))
}

/// Finishes a link commit after the final link exists. A staged name that
/// could not be removed is a second complete name for the output, so it is
/// reported even when a later check fails as well. The unlink is injectable
/// one level down so tests can exercise the post-commit failure policy
/// without a filesystem that selectively refuses it.
#[cfg(unix)]
fn finish_link_commit(
    tmp: NamedTempFile,
    output_dir: &OutputDir,
    final_path: &Path,
    final_name: &std::ffi::OsStr,
    tmp_name: &std::ffi::OsStr,
) -> Result<FinalizedFile, FinalizeFileError> {
    finish_link_commit_with_remove(
        tmp,
        output_dir,
        final_path,
        final_name,
        tmp_name,
        |dir, name| dir.remove_file(name),
    )
}

#[cfg(unix)]
fn finish_link_commit_with_remove(
    tmp: NamedTempFile,
    output_dir: &OutputDir,
    final_path: &Path,
    final_name: &std::ffi::OsStr,
    tmp_name: &std::ffi::OsStr,
    remove_staged: impl FnOnce(&cap_std::fs::Dir, &std::ffi::OsStr) -> io::Result<()>,
) -> Result<FinalizedFile, FinalizeFileError> {
    let (committed_identity, staged_unlink) =
        unlink_staged_temp_with_remove(tmp, output_dir, tmp_name, remove_staged);
    sync_committed_parent(output_dir, final_path);

    let reopened = committed_identity
        .map_err(|e| reported_path_unconfirmed(final_path, e))
        .and_then(|identity| reopen_committed_file(output_dir, final_name, identity, final_path));
    let finalized = match reopened {
        Ok(finalized) => finalized,
        // Without the committed file's handle there is nothing to count through.
        Err(error) => {
            return Err(FinalizeFileError::after_commit(with_staged_link_report(
                error,
                tmp_name,
                staged_unlink,
            )));
        }
    };
    let finding = match (finalized.confirm_reported_path(final_path), staged_unlink) {
        (Ok(()), Ok(())) => None,
        (Ok(()), Err(unlink)) => Some(staged_temp_link_retained(final_path, tmp_name, unlink)),
        (Err(error), unlink) => Some(with_staged_link_report(error, tmp_name, unlink)),
    };
    finalized.into_confirmed(final_path, finding)
}

/// `error`, with the clause for a staged name the commit could not remove
/// appended when `unlink` failed.
#[cfg(unix)]
fn with_staged_link_report(
    error: CryptoError,
    staged_name: &std::ffi::OsStr,
    unlink: io::Result<()>,
) -> CryptoError {
    match unlink {
        Ok(()) => error,
        Err(unlink) => {
            crate::error::append_report(error, &staged_link_report(staged_name, &unlink))
        }
    }
}

/// The clause appended when the claim route left the name it claimed in
/// place. No content from this run's staged file reached that name, because
/// the commit failed before it could be moved there, but a further attempt may
/// find the name occupied. The wording does not say whose the entry is or
/// whether it contains anything: the claim ran with its entry already visible,
/// and a failed commit removes nothing from the final name.
///
/// The decrypt side reports the same condition in its own words
/// (`archive::decode::claim_left_report`): the two share the commit and
/// the flag that raises this, not the sentence. That side names the
/// whole working path, because a failed decrypt is where the caller goes
/// looking for what was left behind.
#[cfg(unix)]
fn claim_left_report(final_path: &Path) -> String {
    format!(
        "{} may still be occupied by an entry this run did not remove",
        final_component_for_display(final_path)
    )
}

/// Disarms the destructor's ambient-path removal, records the open file's
/// identity, closes that handle, and unlinks the staged name through the
/// anchor. Closing first preserves compatibility with filesystems that refuse
/// to unlink a name while the client still has the file open. The final link
/// is reopened and checked against the recorded identity afterwards; its
/// retained handle then supplies the authoritative link-count post-condition.
#[cfg(unix)]
fn unlink_staged_temp(
    tmp: NamedTempFile,
    output_dir: &OutputDir,
    name: &std::ffi::OsStr,
) -> (io::Result<Option<FileIdentity>>, io::Result<()>) {
    unlink_staged_temp_with_remove(tmp, output_dir, name, |dir, name| dir.remove_file(name))
}

#[cfg(unix)]
fn unlink_staged_temp_with_remove(
    tmp: NamedTempFile,
    output_dir: &OutputDir,
    name: &std::ffi::OsStr,
    remove_staged: impl FnOnce(&cap_std::fs::Dir, &std::ffi::OsStr) -> io::Result<()>,
) -> (io::Result<Option<FileIdentity>>, io::Result<()>) {
    let (file, temp_path) = tmp.into_parts();
    let identity = cap_std::fs::Metadata::from_file(&file).map(|metadata| file_identity(&metadata));
    drop(file);
    let _ = temp_path.keep();
    let result = match remove_staged(&output_dir.dir, name) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error),
    };
    (identity, result)
}

/// Best-effort pre-commit cleanup through the retained directory anchor.
#[cfg(unix)]
fn remove_staged_temp(tmp: NamedTempFile, output_dir: &OutputDir) -> io::Result<()> {
    let Some(name) = tmp.path().file_name().map(|name| name.to_os_string()) else {
        let _ = tmp.into_temp_path().keep();
        return Err(no_final_component_error());
    };
    let (_, result) = unlink_staged_temp(tmp, output_dir, &name);
    result
}

/// Reopens a linked commit through the same directory anchor and requires it
/// to be the regular file whose identity was recorded before the staged name
/// was removed. This supplies the retained handle without keeping the staged
/// handle open across an unlink on restrictive network filesystems. Where
/// either identity is absent the comparison is skipped; the link-count and
/// reported-path checks that follow still run. The commit has already
/// happened, so a failed reopen is reported the way
/// [`FinalizedFile::confirm_reported_path`] reports the entry it reads
/// ([`reopen_failure`]).
#[cfg(unix)]
fn reopen_committed_file(
    output_dir: &OutputDir,
    final_name: &std::ffi::OsStr,
    expected: Option<FileIdentity>,
    final_path: &Path,
) -> Result<FinalizedFile, CryptoError> {
    use cap_fs_ext::{FollowSymlinks, OpenOptionsFollowExt, OpenOptionsSyncExt};

    let mut options = cap_std::fs::OpenOptions::new();
    options.read(true).follow(FollowSymlinks::No).nonblock(true);
    let file = output_dir
        .dir
        .open_with(final_name, &options)
        .map_err(|e| reopen_failure(output_dir, final_name, final_path, e))?
        .into_std();
    let metadata = cap_std::fs::Metadata::from_file(&file)
        .map_err(|e| reported_path_unconfirmed(final_path, e))?;
    if !metadata.is_file() {
        return Err(reported_output_changed(final_path));
    }
    if matches!(
        (file_identity(&metadata), expected),
        (Some(found), Some(expected)) if found != expected
    ) {
        return Err(reported_output_changed(final_path));
    }
    Ok(FinalizedFile::new(file))
}

/// Maps a failed reopen of the committed name. The no-follow, non-blocking
/// open fails outright where the name now holds a symlink or a socket, so the
/// entry is read without following it: one that is not a regular file no
/// longer denotes the output, the rule
/// [`FinalizedFile::confirm_reported_path`] also applies. Any other failure is
/// mapped as that check maps a failed read.
#[cfg(unix)]
fn reopen_failure(
    output_dir: &OutputDir,
    final_name: &std::ffi::OsStr,
    final_path: &Path,
    error: io::Error,
) -> CryptoError {
    match output_dir.dir.symlink_metadata(final_name) {
        Ok(entry) if !entry.is_file() => reported_output_changed(final_path),
        _ => reported_entry_error(final_path, error),
    }
}

/// Best-effort durability barrier for a fallback commit. Linux and macOS
/// flush the exact directory handle the commit used; other Unix targets keep
/// the existing path-based fallback because no handle-relative implementation
/// is available there.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn sync_committed_parent(output_dir: &OutputDir, _final_path: &Path) {
    let _ = output_dir.flush_durable();
}

#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn sync_committed_parent(_output_dir: &OutputDir, final_path: &Path) {
    sync_parent_dir(final_path);
}

/// Reports a post-commit staged-name unlink failure without withdrawing the
/// final name. Both entries may still be hard links to the same complete file.
#[cfg(unix)]
fn staged_temp_link_retained(
    final_path: &Path,
    staged_name: &std::ffi::OsStr,
    source: io::Error,
) -> CryptoError {
    CryptoError::Io(io::Error::new(
        source.kind(),
        format!(
            "Output {} is complete, but {}",
            sanitize_path_for_display(final_path),
            staged_link_report(staged_name, &source),
        ),
    ))
}

/// The clause naming a staged name the commit could not remove.
#[cfg(unix)]
fn staged_link_report(staged_name: &std::ffi::OsStr, source: &io::Error) -> String {
    format!(
        "temporary name {} could not be removed: {source}",
        sanitize_path_for_display(Path::new(staged_name)),
    )
}

/// Promotes a staged single-file path `from` to the final name `to`
/// with atomic no-clobber semantics on every supported platform.
/// Fails with [`io::ErrorKind::AlreadyExists`] if `to` is already taken.
///
/// The underlying primitive is `tempfile::TempPath::persist_noclobber`,
/// which dispatches to:
///
/// - **Windows:** `MoveFileExW(from, to, 0)` — the kernel performs the
///   test-and-set in one call, closing the check-then-rename race that
///   [`rename_no_clobber`] still has on this target for the directory
///   case.
/// - **Linux / macOS / iOS / Android:**
///   `rustix::renameat_with(..., RenameFlags::NOREPLACE)`, falling back
///   to `hard_link` + `unlink` if the kernel or filesystem rejects the
///   flag (very old Linux, some FUSE / NFS). The fallback preserves
///   no-clobber (`hard_link` itself refuses an existing target); only
///   atomicity is briefly relaxed.
/// - **Other Unix targets:** `hard_link` + `unlink` unconditionally.
///
/// The link fallback discards its unlink result, so success alone does
/// not prove the staged name is gone. Archive extraction accounts for
/// that by reporting the link outcome (`platform::PromotionOutcome`)
/// and requiring one link through its retained staged handle.
///
/// Intended for **single-file** promotions only. Directory promotion on
/// Windows still goes through [`rename_no_clobber`] because no
/// equivalent safe atomic primitive is available there for directories.
///
/// On failure, `from` is left in place so the
/// `IncompleteOutputPolicy::RetainOnError` contract — "keep the staged
/// `.incomplete` on disk after a failed decrypt" — continues to hold
/// when promotion itself is what failed.
///
/// Archive promotion calls this on Windows and other non-Linux/macOS
/// targets; on Linux and macOS the archive layer promotes
/// handle-relative via `archive::platform::rename_at_no_clobber`, so the
/// production caller here is `cfg`'d away and the dead-code check fires
/// in a non-test build on those targets. The `allow` keeps the helper
/// (and its cross-platform tests) compiled everywhere.
#[cfg_attr(any(target_os = "linux", target_os = "macos"), allow(dead_code))]
pub(crate) fn promote_single_file_no_clobber(from: &Path, to: &Path) -> io::Result<()> {
    let temp_path = tempfile::TempPath::try_from_path(from)?;
    match temp_path.persist_noclobber(to) {
        Ok(()) => {
            sync_parent_dir(to);
            Ok(())
        }
        Err(e) => {
            // Recover the staging file: disable cleanup on the
            // returned TempPath so its destructor does not `remove_file`
            // it when this match arm ends. RetainOnError relies on
            // `from` still being on disk after a refused promotion.
            let mut recovered = e.path;
            recovered.disable_cleanup(true);
            Err(e.error)
        }
    }
}

/// Renames `from` to `to`, refusing if `to` already exists. Works for
/// files and directories.
///
/// - **Linux / macOS:** atomic —
///   `rustix::renameat_with(..., RenameFlags::NOREPLACE)`.
/// - **Windows:** best-effort. `symlink_metadata()` + `std::fs::rename`.
///   A small race window exists between the two: a process that
///   creates `to` in that window has its file silently overwritten by
///   ours. Plaintext is never redirected (Windows renames replace the
///   directory entry, not the link target), so the failure mode is
///   integrity, not confidentiality. Closing this fully needs Win32
///   FFI, which the zero-`unsafe` invariant rules out. See
///   `SECURITY.md`.
/// - **Other targets:** unsupported.
///
/// Single-file promotions should prefer [`promote_single_file_no_clobber`],
/// which is atomic no-clobber on Windows too.
///
/// Build-time-unused on Linux and macOS for the same reason as
/// [`promote_single_file_no_clobber`]: archive promotion there is
/// handle-relative. The `allow` keeps it (and its tests) compiled on
/// every platform.
#[cfg_attr(any(target_os = "linux", target_os = "macos"), allow(dead_code))]
pub(crate) fn rename_no_clobber(from: &Path, to: &Path) -> io::Result<()> {
    rename_no_clobber_impl(from, to)?;
    sync_parent_dir(to);
    Ok(())
}

// Reached only through `rename_no_clobber`, which is itself build-time-
// unused on Linux/macOS (archive promotion is handle-relative there).
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[allow(dead_code)]
fn rename_no_clobber_impl(from: &Path, to: &Path) -> io::Result<()> {
    use rustix::fs::{CWD, RenameFlags, renameat_with};
    renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE).map_err(io::Error::from)
}

#[cfg(target_os = "windows")]
fn rename_no_clobber_impl(from: &Path, to: &Path) -> io::Result<()> {
    // `symlink_metadata` does not follow links, so a dangling symlink
    // at `to` reports `Ok(_)` and rejects here instead of falling
    // through `Path::try_exists()` (which follows the link to a
    // missing target and returns `Ok(false)`). Closes the gap that
    // `MoveFileExW(..., MOVEFILE_REPLACE_EXISTING)` would otherwise
    // exploit by replacing the dangling link with the staged file.
    match std::fs::symlink_metadata(to) {
        Ok(_) => {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                "Target already exists",
            ));
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
        Err(e) => return Err(e),
    }
    std::fs::rename(from, to)
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn rename_no_clobber_impl(_from: &Path, _to: &Path) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "Atomic rename is not supported on this target",
    ))
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::io::Write;

    use super::*;

    /// Takes read permission away from a directory, leaving write and search
    /// (`0o333`), and restores `0o755` when dropped, also after a failed
    /// assertion, so that `TempDir` cleanup can still list and remove it.
    #[cfg(unix)]
    struct ReadDenied<'a>(&'a Path);

    #[cfg(unix)]
    impl<'a> ReadDenied<'a> {
        fn lock(dir: &'a Path) -> Self {
            use std::os::unix::fs::PermissionsExt;

            fs::set_permissions(dir, fs::Permissions::from_mode(0o333)).unwrap();
            Self(dir)
        }

        /// Asserts that `result`, a required flush of the locked directory,
        /// was refused for the missing read permission. A privileged process
        /// (such as root) bypasses the check, and the flush then legitimately
        /// succeeds, so nothing is asserted where the denial did not take
        /// effect.
        fn assert_refused(&self, result: io::Result<()>) {
            if fs::File::open(self.0).is_ok() {
                return;
            }
            let err = result.expect_err("a read-denied directory must fail the required flush");
            assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
        }
    }

    #[cfg(unix)]
    impl Drop for ReadDenied<'_> {
        fn drop(&mut self) {
            use std::os::unix::fs::PermissionsExt;

            let _ = fs::set_permissions(self.0, fs::Permissions::from_mode(0o755));
        }
    }

    /// An occupied final path rejects with the same typed message the
    /// pre-write occupancy check emits, so a conflict that appears in
    /// the window between the preflight and this rename reports the
    /// same error class. The destination stays untouched and the temp
    /// file is removed.
    #[test]
    fn finalize_file_refuses_to_overwrite() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        fs::write(&final_path, "existing").unwrap();

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"new").unwrap();
        let tmp_path = tmp.path().to_path_buf();

        let error = commit_to(tmp, &final_path, "Output")
            .expect_err("an occupied output must fail before commit");
        assert!(!error.committed());
        match error.into_crypto_error() {
            CryptoError::InvalidInput(msg) => {
                assert!(msg.starts_with("Output already exists: "), "got: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "existing");
        assert!(!tmp_path.exists(), "temp file must be removed on failure");
    }

    #[test]
    fn finalize_file_succeeds_when_target_missing() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();

        commit_to(tmp, &final_path, "Output").unwrap();
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "payload");
    }

    /// The ordinary one-step persist also retains the committed handle. If
    /// the parent directory is replaced before the caller reports its path,
    /// the final check rejects that path while leaving both the real output
    /// and the replacement untouched. Unix only: NTFS refuses to rename a
    /// directory while a handle is open anywhere beneath it, so the retained
    /// handle itself rules this swap out there.
    #[cfg(unix)]
    #[test]
    fn finalized_file_rejects_a_reported_path_after_parent_replacement() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let out = tmp_dir.path().join("out");
        fs::create_dir(&out).unwrap();
        let final_path = out.join("out.txt");

        let mut tmp = tempfile::Builder::new().tempfile_in(&out).unwrap();
        tmp.write_all(b"payload").unwrap();
        let finalized = commit_to(tmp, &final_path, "Output").unwrap();

        let moved = tmp_dir.path().join("out.moved");
        fs::rename(&out, &moved).unwrap();
        fs::create_dir(&out).unwrap();
        fs::write(&final_path, b"replacement").unwrap();

        let err = finalized
            .confirm_reported_path(&final_path)
            .expect_err("the returned path no longer denotes the committed file");
        assert!(
            matches!(
                err,
                CryptoError::InvalidInput(message)
                    if message.contains("reported path changed")
            ),
            "the path mismatch must be explicit"
        );
        assert_eq!(fs::read(moved.join("out.txt")).unwrap(), b"payload");
        assert_eq!(fs::read(&final_path).unwrap(), b"replacement");
    }

    /// A replacement of the final entry itself — the committed file moved
    /// aside and another file planted under its name, which a local writer
    /// can do on every platform while the handle is retained — is rejected
    /// the same way, and both files are left where they are.
    #[test]
    fn finalized_file_rejects_a_reported_path_after_entry_replacement() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let finalized = commit_to(tmp, &final_path, "Output").unwrap();

        let moved = tmp_dir.path().join("out.moved");
        fs::rename(&final_path, &moved).unwrap();
        fs::write(&final_path, b"replacement").unwrap();

        let err = finalized
            .confirm_reported_path(&final_path)
            .expect_err("the returned path no longer denotes the committed file");
        assert!(
            matches!(
                err,
                CryptoError::InvalidInput(message)
                    if message.contains("reported path changed")
            ),
            "the entry mismatch must be explicit"
        );
        assert_eq!(fs::read(&moved).unwrap(), b"payload");
        assert_eq!(fs::read(&final_path).unwrap(), b"replacement");
    }

    /// Creates a file symlink `link` → `target`. Windows needs a privilege
    /// the local account may lack; that failure is returned so the caller
    /// can skip, unless `FERROCRYPT_REQUIRE_WINDOWS_SYMLINK_TESTS` demands
    /// the assertion, as the extraction tests do.
    fn plant_file_symlink(target: &Path, link: &Path) -> io::Result<()> {
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(target, link)
        }
        #[cfg(windows)]
        {
            let result = std::os::windows::fs::symlink_file(target, link);
            if let Err(e) = &result {
                if std::env::var_os("FERROCRYPT_REQUIRE_WINDOWS_SYMLINK_TESTS").is_some() {
                    panic!("symlink creation required by CI but failed: {e}");
                }
            }
            result
        }
    }

    /// A symlink planted at the reported name, pointing at the committed
    /// file moved aside, must be rejected: the entry is read without
    /// following it, so a name the writer can retarget later is never
    /// confirmed even while it currently leads to the right bytes.
    #[test]
    fn finalized_file_rejects_a_symlink_planted_at_the_reported_path() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let finalized = commit_to(tmp, &final_path, "Output").unwrap();

        let moved = tmp_dir.path().join("out.moved");
        fs::rename(&final_path, &moved).unwrap();
        if let Err(e) = plant_file_symlink(&moved, &final_path) {
            eprintln!("symlink creation unavailable ({e}); skipping");
            return;
        }

        let err = finalized
            .confirm_reported_path(&final_path)
            .expect_err("a symlink at the reported name is not the committed entry");
        assert!(
            matches!(
                err,
                CryptoError::InvalidInput(message)
                    if message.contains("reported path changed")
            ),
            "the planted symlink must report as a path mismatch"
        );
        assert_eq!(fs::read(&moved).unwrap(), b"payload");
    }

    /// A final name that is gone — here moved away — counts as changed,
    /// exactly like one that holds another object: the commit created an
    /// entry there.
    #[test]
    fn finalized_file_rejects_a_reported_path_that_no_longer_exists() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let finalized = commit_to(tmp, &final_path, "Output").unwrap();

        fs::rename(&final_path, tmp_dir.path().join("out.moved")).unwrap();

        let err = finalized
            .confirm_reported_path(&final_path)
            .expect_err("a missing final name no longer denotes the output");
        assert!(
            matches!(
                err,
                CryptoError::InvalidInput(message)
                    if message.contains("reported path changed")
            ),
            "the missing name must report as a path mismatch"
        );
    }

    /// A reported path that no longer leads to an entry counts as changed
    /// whichever way it stopped: the directory holding the output replaced by
    /// a file, or by a symlink cycle. Neither is a check that could not run.
    #[cfg(unix)]
    #[test]
    fn finalized_file_rejects_a_reported_path_that_no_longer_resolves() {
        type Plant = fn(&Path) -> io::Result<()>;
        let plants: [(&str, Plant); 2] = [
            ("file", |dir| fs::write(dir, b"not a directory")),
            ("symlink cycle", |dir| std::os::unix::fs::symlink(dir, dir)),
        ];
        for (substitute, plant) in plants {
            let tmp_dir = tempfile::TempDir::new().unwrap();
            let out = tmp_dir.path().join("out");
            fs::create_dir(&out).unwrap();
            let final_path = out.join("out.txt");

            let mut tmp = tempfile::Builder::new().tempfile_in(&out).unwrap();
            tmp.write_all(b"payload").unwrap();
            let finalized = commit_to(tmp, &final_path, "Output").unwrap();
            fs::rename(&out, tmp_dir.path().join("out.moved")).unwrap();
            plant(&out).unwrap();

            let err = finalized
                .confirm_reported_path(&final_path)
                .expect_err("a path that no longer resolves no longer denotes the output");
            assert!(
                matches!(
                    &err,
                    CryptoError::InvalidInput(message) if message.contains("reported path changed")
                ),
                "a {substitute} in place of the directory must report as changed, got: {err}"
            );
        }
    }

    /// A reported path that cannot be read is neither confirmed nor shown to
    /// have changed. The error keeps its kind and says the output is complete,
    /// so it cannot be taken to mean that nothing was written.
    #[cfg(unix)]
    #[test]
    fn finalized_file_reports_an_unreadable_reported_path_as_complete() {
        use std::os::unix::fs::PermissionsExt;

        let tmp_dir = tempfile::TempDir::new().unwrap();
        let out = tmp_dir.path().join("out");
        fs::create_dir(&out).unwrap();
        let final_path = out.join("out.txt");

        let mut tmp = tempfile::Builder::new().tempfile_in(&out).unwrap();
        tmp.write_all(b"payload").unwrap();
        let finalized = commit_to(tmp, &final_path, "Output").unwrap();

        fs::set_permissions(&out, fs::Permissions::from_mode(0o000)).unwrap();
        let outcome = finalized.confirm_reported_path(&final_path);
        fs::set_permissions(&out, fs::Permissions::from_mode(0o755)).unwrap();

        match outcome {
            // A privileged runner reads the path despite the mode.
            Ok(()) => {}
            Err(CryptoError::Io(error)) => {
                assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
                assert_unconfirmed_path(&error.to_string(), &final_path);
            }
            Err(other) => panic!("the denial must be reported as I/O, got: {other}"),
        }
        assert_eq!(fs::read(&final_path).unwrap(), b"payload");
    }

    /// Asserts that `message` reports the output as complete and `path` as
    /// unconfirmed.
    #[cfg(unix)]
    fn assert_unconfirmed_path(message: &str, path: &Path) {
        let expected = format!(
            "Output is complete, but its reported path could not be confirmed: {}: ",
            sanitize_path_for_display(path)
        );
        assert!(
            message.starts_with(&expected),
            "expected a message starting with {expected:?}, got: {message}"
        );
    }

    /// Every error raised after a commit says that the output is complete,
    /// including those for a check that could not run, which no test can
    /// provoke through a live handle. One that reports a failed read keeps
    /// that failure's kind.
    #[test]
    fn every_post_commit_error_says_the_output_is_complete() {
        let path = Path::new("out.fcr");
        let denied = || io::Error::from(io::ErrorKind::PermissionDenied);
        let read_failed = Some(io::ErrorKind::PermissionDenied);
        let cases = [
            (reported_output_changed(path), None),
            (
                reported_entry_error(path, io::Error::from(io::ErrorKind::NotFound)),
                None,
            ),
            (reported_entry_error(path, denied()), read_failed),
            (reported_path_unconfirmed(path, denied()), read_failed),
            (link_count_unreadable(path, denied()), read_failed),
            (committed_link_count_error("out.fcr", 2), None),
            #[cfg(unix)]
            (
                staged_temp_link_retained(path, std::ffi::OsStr::new(".staged"), denied()),
                read_failed,
            ),
        ];
        for (error, kind) in cases {
            assert!(
                says_output_is_complete(&error),
                "a post-commit error must say the output is complete, got: {error}"
            );
            if let Some(kind) = kind {
                assert!(
                    matches!(&error, CryptoError::Io(source) if source.kind() == kind),
                    "the failure's kind must survive, got: {error:?}"
                );
            }
        }
        let unreadable = link_count_unreadable(path, denied()).to_string();
        assert!(
            unreadable.contains("its number of filesystem names could not be read: "),
            "an unreadable count must say what could not be read, got: {unreadable}"
        );
    }

    /// This crate's tests refuse a post-commit error that does not say the
    /// output is complete, whichever constructor built it.
    #[test]
    #[should_panic(expected = "a post-commit error must say that the output is complete")]
    fn a_post_commit_error_without_the_wording_fails_the_tests() {
        let _ = FinalizeFileError::after_commit(CryptoError::Io(io::Error::other(
            "Output out.fcr could not be checked",
        )));
    }

    /// `tempfile` can persist through a hard link of its own on Unix and
    /// discard the staged-name unlink result, and a local writer can link
    /// the staged temporary before the commit anywhere, so the persist arm
    /// must not report success while a second complete link to the
    /// committed file exists. Runs on Windows too: NTFS has hard links, and
    /// the check is load-bearing there.
    ///
    /// Only where the persist arm is the commit. Linux and macOS commit
    /// through the handle-relative rename instead, and the end-to-end
    /// test below pins the same rule for it.
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    #[test]
    fn persist_arm_rejects_a_second_link_to_the_committed_file() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        fs::write(&final_path, "payload").unwrap();
        let leftover = tmp_dir.path().join(".tmpleftover.incomplete");
        fs::hard_link(&final_path, &leftover).unwrap();

        let file = fs::File::open(&final_path).unwrap();
        let error = finalized_from_persist(file, &final_path)
            .expect_err("a surviving second link must fail after commit");
        assert!(error.committed());
        let message = error.into_crypto_error().to_string();
        assert!(message.contains("has 2 filesystem names"), "got: {message}");
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "payload");
        assert_eq!(fs::read_to_string(&leftover).unwrap(), "payload");
    }

    /// An output directory that grants write and search but not read
    /// still receives encrypted output on Linux and macOS: the commit
    /// resolves through an anchor opened for path resolution alone. Key
    /// generation is deliberately not covered — it opens a readable
    /// anchor for a durability barrier it must be able to report on.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn finalize_file_commits_into_a_write_and_search_only_directory() {
        let out = crate::fs::commit::SearchOnlyDir::new();
        let final_path = out.path().join("out.txt");

        let mut tmp = tempfile::Builder::new().tempfile_in(out.path()).unwrap();
        tmp.write_all(b"payload").unwrap();
        out.close_reading();

        let finalized = commit_to(tmp, &final_path, "Output")
            .map_err(FinalizeFileError::into_crypto_error)
            .expect("a write-and-search-only directory must still receive the output");
        finalized.confirm_reported_path(&final_path).unwrap();
        assert_eq!(fs::read(&final_path).unwrap(), b"payload");
    }

    /// The no-clobber refusal is unchanged there: an entry that predates
    /// the commit is still never replaced, and reports the typed
    /// already-exists error rather than a bare permission failure.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn finalize_file_still_refuses_an_occupied_name_in_a_search_only_directory() {
        let out = crate::fs::commit::SearchOnlyDir::new();
        let final_path = out.path().join("out.txt");
        fs::write(&final_path, "existing").unwrap();

        let mut tmp = tempfile::Builder::new().tempfile_in(out.path()).unwrap();
        tmp.write_all(b"payload").unwrap();
        out.close_reading();

        let error = commit_to(tmp, &final_path, "Output")
            .expect_err("an occupied final name must refuse the commit");
        assert!(!error.committed());
        match error.into_crypto_error() {
            CryptoError::InvalidInput(message) => {
                assert!(
                    message.starts_with("Output already exists: "),
                    "got: {message}"
                );
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "existing");
    }

    /// The anchor is held from before staging, so a local writer who
    /// moves the output directory aside and installs another at that
    /// path does not redirect the commit: the output lands in the
    /// directory the write began in, their directory is untouched, and
    /// the caller is told the reported path no longer names the output.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn a_directory_swapped_in_after_staging_receives_nothing() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let chosen = tmp_dir.path().join("out");
        let substituted = tmp_dir.path().join("theirs");
        fs::create_dir(&chosen).unwrap();
        fs::create_dir(&substituted).unwrap();

        let anchor = OutputDir::open_for_commit(&chosen).unwrap();
        let mut tmp = tempfile::Builder::new().tempfile_in(&chosen).unwrap();
        anchor.confirm_staged(&tmp).unwrap();
        tmp.write_all(b"payload").unwrap();

        fs::rename(&chosen, tmp_dir.path().join("out.moved")).unwrap();
        fs::rename(&substituted, &chosen).unwrap();

        let error = finalize_file(tmp, &chosen.join("out.txt"), "Output", &anchor)
            .expect_err("the reported path no longer names the output");
        assert!(
            error.committed(),
            "the output is committed; only the reported path is wrong"
        );
        assert!(
            !chosen.join("out.txt").exists(),
            "nothing may reach the substituted directory"
        );
        assert_eq!(
            fs::read(tmp_dir.path().join("out.moved").join("out.txt")).unwrap(),
            b"payload",
            "the output belongs in the directory the write began in"
        );
    }

    /// The same swap, with the staged file moved into the replacement
    /// first. Opening the anchor at the commit would find the staged
    /// inode there and commit into the replacement; an anchor held from
    /// before staging refuses, because the staged file is no longer an
    /// entry of the directory the write began in.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn a_staged_file_moved_into_a_swapped_in_directory_refuses_the_commit() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let chosen = tmp_dir.path().join("out");
        let replacement = tmp_dir.path().join("replacement");
        fs::create_dir(&chosen).unwrap();
        fs::create_dir(&replacement).unwrap();

        let anchor = OutputDir::open_for_commit(&chosen).unwrap();
        let mut tmp = tempfile::Builder::new().tempfile_in(&chosen).unwrap();
        anchor.confirm_staged(&tmp).unwrap();
        tmp.write_all(b"payload").unwrap();
        let staged_name = tmp.path().file_name().unwrap().to_os_string();

        // The local writer moves the staged file into a directory of
        // their own, then installs that directory at the chosen path.
        fs::rename(chosen.join(&staged_name), replacement.join(&staged_name)).unwrap();
        fs::rename(&chosen, tmp_dir.path().join("out.moved")).unwrap();
        fs::rename(&replacement, &chosen).unwrap();

        let error = finalize_file(tmp, &chosen.join("out.txt"), "Output", &anchor)
            .expect_err("a staged file outside the anchor must refuse the commit");
        assert!(!error.committed(), "nothing may be committed");
        assert!(
            !chosen.join("out.txt").exists(),
            "the replacement directory must receive nothing"
        );
        assert!(
            !tmp_dir.path().join("out.moved").join("out.txt").exists(),
            "the original directory must receive nothing either"
        );
    }

    /// The same guarantee end to end through `finalize_file`: a hard link
    /// a local writer created against the staged temporary before the
    /// commit survives the one-step persist as a second name for the
    /// committed file, so the commit fails after the final name exists and
    /// keeps both complete names.
    #[test]
    fn finalize_file_rejects_a_link_planted_against_the_staged_temporary() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let planted = tmp_dir.path().join("planted.txt");
        fs::hard_link(tmp.path(), &planted).unwrap();

        let error = commit_to(tmp, &final_path, "Output")
            .expect_err("a second link to the committed file must fail after commit");
        assert!(error.committed());
        let message = error.into_crypto_error().to_string();
        assert!(message.contains("has 2 filesystem names"), "got: {message}");
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "payload");
        assert_eq!(fs::read_to_string(&planted).unwrap(), "payload");
    }

    /// The fallback trigger fires only for "the filesystem cannot do a
    /// no-replace rename" errors, never for ordinary failures such as
    /// an occupied target.
    #[cfg(unix)]
    #[test]
    fn no_replace_rename_unsupported_matches_capability_errors_only() {
        // Raw ENOTSUP is the exact shape the macOS exFAT driver
        // produces; it must match even though std leaves its kind
        // uncategorized on macOS.
        assert!(no_replace_rename_unsupported(
            &io::Error::from_raw_os_error(libc::ENOTSUP)
        ));
        assert!(no_replace_rename_unsupported(
            &io::Error::from_raw_os_error(libc::EOPNOTSUPP)
        ));
        assert!(no_replace_rename_unsupported(
            &io::Error::from_raw_os_error(libc::EINVAL)
        ));
        assert!(no_replace_rename_unsupported(&io::Error::new(
            io::ErrorKind::Unsupported,
            "flag not supported",
        )));
        assert!(!no_replace_rename_unsupported(
            &io::Error::from_raw_os_error(libc::EEXIST)
        ));
        assert!(!no_replace_rename_unsupported(&io::Error::new(
            io::ErrorKind::NotFound,
            "missing",
        )));
    }

    /// `EINVAL` means "flag not supported" only for the flagged rename;
    /// the shared not-supported predicate must not treat it as a
    /// capability gap (a plain file `fsync` that fails with `EINVAL` is a
    /// real error, not a missing feature).
    #[cfg(unix)]
    #[test]
    fn errno_not_supported_excludes_einval() {
        assert!(errno_not_supported(&io::Error::from_raw_os_error(
            libc::ENOTSUP
        )));
        assert!(!errno_not_supported(&io::Error::from_raw_os_error(
            libc::EINVAL
        )));
    }

    /// On a filesystem with full sync support a writable regular file
    /// can be durably synced.
    #[test]
    fn sync_file_durable_succeeds_on_regular_file() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let path = tmp_dir.path().join("synced.txt");
        fs::write(&path, b"bytes").unwrap();
        let file = fs::OpenOptions::new().write(true).open(&path).unwrap();
        sync_file_durable(&file).unwrap();
    }

    /// Flushing an ordinary directory succeeds when the filesystem supports
    /// directory synchronization, including after a new entry is created.
    #[test]
    fn sync_dir_durable_succeeds_on_regular_directory() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        fs::write(tmp_dir.path().join("entry.txt"), b"bytes").unwrap();
        sync_dir_durable(tmp_dir.path()).unwrap();
    }

    /// A missing directory is a real failure, not an unsupported operation.
    /// The caller must be told that the target directory has disappeared.
    #[test]
    fn sync_dir_durable_reports_missing_directory() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let gone = tmp_dir.path().join("vanished");
        let err =
            sync_dir_durable(&gone).expect_err("missing directory must fail the directory flush");
        assert_eq!(err.kind(), io::ErrorKind::NotFound);
    }

    /// A regular file at the supplied path is an error. The function must not
    /// treat it as the directory whose entries should be flushed.
    #[test]
    fn sync_dir_durable_rejects_regular_file() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let file_path = tmp_dir.path().join("not-a-directory");
        fs::write(&file_path, b"bytes").unwrap();
        let err =
            sync_dir_durable(&file_path).expect_err("regular file must fail the directory flush");
        assert_eq!(err.kind(), io::ErrorKind::NotADirectory);
    }

    /// A directory with no read permission (write-and-execute only) fails the
    /// required flush instead of being treated as unsupported: the read handle
    /// that directory `fsync` needs is denied, and key generation must fail
    /// rather than skip the barrier. Reproduces the audited `0o333` case.
    /// Where a privileged process bypasses the check,
    /// `required_dir_flush_tolerates_only_an_unsupported_open` still pins the
    /// decision.
    #[cfg(unix)]
    #[test]
    fn sync_dir_durable_reports_permission_denied_directory() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let dir = tmp_dir.path().join("writeonly");
        fs::create_dir(&dir).unwrap();
        let locked = ReadDenied::lock(&dir);
        locked.assert_refused(sync_dir_durable(&dir));
    }

    /// The flush classifier treats only errors that mean the filesystem
    /// cannot flush a directory as unsupported. A missing system call
    /// (`ENOSYS`), a synthesized error, and every other error, such as a
    /// device I/O error, must remain genuine failures, so a required barrier
    /// is never silently skipped.
    #[cfg(unix)]
    #[test]
    fn dir_sync_unsupported_classifies_unix_errnos() {
        for unavailable in [libc::ENOTSUP, libc::EOPNOTSUPP, libc::EINVAL, libc::EBADF] {
            assert!(
                dir_sync_unsupported(&io::Error::from_raw_os_error(unavailable)),
                "errno {unavailable} must classify as directory-flush unsupported"
            );
        }
        assert!(!dir_sync_unsupported(&io::Error::new(
            io::ErrorKind::Unsupported,
            "synthesized unsupported"
        )));
        for genuine in [
            libc::ENOSYS,
            libc::EIO,
            libc::ENOENT,
            libc::ENOTDIR,
            libc::ENOSPC,
            libc::EACCES,
        ] {
            assert!(
                !dir_sync_unsupported(&io::Error::from_raw_os_error(genuine)),
                "errno {genuine} must propagate as a genuine failure"
            );
        }
    }

    /// One case for a flush-fallback rule: the errno the full flush fails
    /// with, the errno the plain flush fails with, the errno the rule must
    /// return (`None` meaning success in each place), and whether the plain
    /// flush must run.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    type FallbackCase = (Option<i32>, Option<i32>, Option<i32>, bool);

    /// A flush that the fallback tests inject.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    type InjectedFlush<'a> = &'a dyn Fn() -> io::Result<()>;

    /// Runs `rule` on every case with injected flushes, and checks its result
    /// and whether it ran the plain flush.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    fn check_flush_fallback(
        rule: impl Fn(InjectedFlush<'_>, InjectedFlush<'_>) -> io::Result<()>,
        cases: &[FallbackCase],
    ) {
        let outcome = |errno: Option<i32>| {
            errno.map_or(Ok(()), |code| Err(io::Error::from_raw_os_error(code)))
        };
        for &(full, plain, expected, plain_runs) in cases {
            let ran = std::cell::Cell::new(false);
            let result = rule(&|| outcome(full), &|| {
                ran.set(true);
                outcome(plain)
            });
            let case = format!("full flush {full:?}, plain flush {plain:?}");
            let expected = expected.map_or(Ok(()), |code| Err(Some(code)));
            assert_eq!(result.map_err(|e| e.raw_os_error()), expected, "{case}");
            assert_eq!(ran.get(), plain_runs, "{case}");
        }
    }

    /// The file-flush rule runs the plain flush only when the full flush
    /// reports the operation as unsupported, and then returns the plain
    /// flush's own result. Any other failure of the full flush is returned
    /// without running the plain flush.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn file_flush_falls_back_only_when_the_full_flush_is_unsupported() {
        check_flush_fallback(
            |full, plain| flush_file_with_fallback(full, plain),
            &[
                (None, None, None, false),
                (Some(libc::ENOTSUP), None, None, true),
                (Some(libc::EOPNOTSUPP), None, None, true),
                (Some(libc::ENOTSUP), Some(libc::EIO), Some(libc::EIO), true),
                (
                    Some(libc::ENOTSUP),
                    Some(libc::ENOTSUP),
                    Some(libc::ENOTSUP),
                    true,
                ),
                (Some(libc::EIO), None, Some(libc::EIO), false),
                (Some(libc::EINVAL), None, Some(libc::EINVAL), false),
                (Some(libc::EACCES), None, Some(libc::EACCES), false),
            ],
        );
    }

    /// The directory-flush rule runs the plain flush when the full flush is
    /// not available or reports directory flushing as unsupported. Where the
    /// plain flush is unsupported too, the filesystem has no directory
    /// flushing, which counts as success. Every genuine failure of either
    /// flush is returned. A missing full flush (`ENOSYS`) still leads to the
    /// plain flush, but a missing plain flush is a failure, not a filesystem
    /// without directory flushing.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn dir_flush_falls_back_and_accepts_a_filesystem_without_directory_flushing() {
        check_flush_fallback(
            |full, plain| flush_dir_with_fallback(full, plain),
            &[
                (None, None, None, false),
                (Some(libc::ENOTSUP), None, None, true),
                (Some(libc::EOPNOTSUPP), None, None, true),
                (Some(libc::EINVAL), None, None, true),
                (Some(libc::EBADF), None, None, true),
                (Some(libc::ENOTSUP), Some(libc::ENOTSUP), None, true),
                (Some(libc::ENOTSUP), Some(libc::EINVAL), None, true),
                (Some(libc::ENOTSUP), Some(libc::EIO), Some(libc::EIO), true),
                (
                    Some(libc::ENOTSUP),
                    Some(libc::EACCES),
                    Some(libc::EACCES),
                    true,
                ),
                (
                    Some(libc::ENOTSUP),
                    Some(libc::ENOSYS),
                    Some(libc::ENOSYS),
                    true,
                ),
                (Some(libc::EIO), None, Some(libc::EIO), false),
                (Some(libc::EACCES), None, Some(libc::EACCES), false),
                (Some(libc::ENOSYS), None, None, true),
                (
                    Some(libc::ENOSYS),
                    Some(libc::ENOSYS),
                    Some(libc::ENOSYS),
                    true,
                ),
            ],
        );
    }

    /// Every required directory flush tolerates one open failure: the
    /// filesystem reporting the operation as unsupported, which counts as a
    /// filesystem without directory flushing. A missing system call
    /// (`ENOSYS`), a synthesized error, `EINVAL` and `EBADF` (which the flush
    /// rule accepts), permission denial, and path and device errors are
    /// returned, so a required barrier cannot report success over them.
    #[cfg(unix)]
    #[test]
    fn required_dir_flush_tolerates_only_an_unsupported_open() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        flush_opened_dir(fs::File::open(tmp_dir.path())).expect("an opened directory must flush");
        for unsupported in [libc::ENOTSUP, libc::EOPNOTSUPP] {
            let flushed = flush_opened_dir(Err(io::Error::from_raw_os_error(unsupported)));
            assert!(flushed.is_ok(), "errno {unsupported}");
        }
        let synthesized = io::Error::new(io::ErrorKind::Unsupported, "synthesized unsupported");
        assert!(flush_opened_dir(Err(synthesized)).is_err());
        for genuine in [
            libc::ENOSYS,
            libc::EINVAL,
            libc::EBADF,
            libc::EACCES,
            libc::ENOENT,
            libc::ENOTDIR,
            libc::EIO,
        ] {
            let flushed = flush_opened_dir(Err(io::Error::from_raw_os_error(genuine)));
            assert_eq!(flushed.map_err(|e| e.raw_os_error()), Err(Some(genuine)));
        }
    }

    /// Windows counterpart to the Unix error-classification test.
    #[cfg(windows)]
    #[test]
    fn dir_sync_unsupported_classifies_windows_errors() {
        // ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER.
        for unavailable in [1, 50, 87] {
            assert!(
                dir_sync_unsupported(&io::Error::from_raw_os_error(unavailable)),
                "code {unavailable} must classify as directory-flush unsupported"
            );
        }
        // ERROR_FILE_NOT_FOUND, ERROR_IO_DEVICE, and ERROR_ACCESS_DENIED (5)
        // stay genuine: permission denial must fail the required barrier.
        for genuine in [2, 1117, 5] {
            assert!(
                !dir_sync_unsupported(&io::Error::from_raw_os_error(genuine)),
                "code {genuine} must propagate as a genuine failure"
            );
        }
    }

    /// Runs `f` on a worker thread and returns its result, failing the
    /// test if it has not finished within five seconds. A helper that
    /// opens a substituted FIFO without the directory flag waits for a
    /// writer that never arrives, which would hang the whole suite
    /// instead of reporting a failure.
    #[cfg(unix)]
    fn within_timeout<T: Send + 'static>(what: &str, f: impl FnOnce() -> T + Send + 'static) -> T {
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let _ = tx.send(f());
        });
        match rx.recv_timeout(std::time::Duration::from_secs(5)) {
            Ok(value) => value,
            Err(_) => panic!("{what} blocked instead of refusing a non-directory path"),
        }
    }

    /// A required directory flush must refuse a FIFO immediately. The
    /// open would otherwise wait for a writer, turning a durability
    /// barrier into an indefinite stall.
    #[cfg(unix)]
    #[test]
    fn sync_dir_durable_rejects_fifo_without_blocking() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let fifo = tmp_dir.path().join("pipe");
        crate::fs::paths::make_fifo(&fifo);

        let err = within_timeout("sync_dir_durable", move || sync_dir_durable(&fifo))
            .expect_err("a FIFO must fail the directory flush");
        assert_eq!(err.kind(), io::ErrorKind::NotADirectory);
    }

    /// The best-effort barrier re-resolves the parent path after the
    /// final name is already visible, so a local writer can substitute a
    /// FIFO for it in between. Opening that FIFO for reading would block
    /// until a writer appears, and there is no error to swallow while
    /// the open itself is stuck. The helper must return regardless.
    #[cfg(unix)]
    #[test]
    fn sync_parent_dir_does_not_block_on_a_fifo_parent() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let fifo = tmp_dir.path().join("parent");
        crate::fs::paths::make_fifo(&fifo);
        let child = fifo.join("committed.txt");

        within_timeout("sync_parent_dir", move || sync_parent_dir(&child));
    }

    /// Cleanup after a failed commit must resolve inside the directory
    /// the handle was opened on. Renaming that directory aside and
    /// leaving a symlink to an unrelated one in its place — what a local
    /// writer with access to the parent can do — must not redirect the
    /// removal onto the same-named file there.
    #[cfg(unix)]
    #[test]
    fn output_dir_removal_stays_in_the_anchored_directory() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let anchored = tmp_dir.path().join("out");
        let substituted = tmp_dir.path().join("elsewhere");
        fs::create_dir(&anchored).unwrap();
        fs::create_dir(&substituted).unwrap();
        fs::write(substituted.join("key"), "unrelated").unwrap();

        let handle = OutputDir::open(&anchored).unwrap();
        let ours = crate::fs::commit::create_file_at(
            &handle.dir,
            std::ffi::OsStr::new("key"),
            crate::fs::commit::STAGED_FILE_MODE,
        )
        .unwrap()
        .into_std();
        fs::rename(&anchored, tmp_dir.path().join("out.moved")).unwrap();
        std::os::unix::fs::symlink(&substituted, &anchored).unwrap();

        assert_eq!(
            handle.remove_if_retained(std::ffi::OsStr::new("key"), ours),
            RollbackOutcome::Removed
        );

        assert_eq!(
            fs::read_to_string(substituted.join("key")).unwrap(),
            "unrelated",
            "a substituted directory's file must not be removed"
        );
        assert!(
            !tmp_dir.path().join("out.moved").join("key").exists(),
            "the anchored directory's own entry must still be removed"
        );
    }

    /// Commits `b"committed"` under `name` in `dir` through `anchor` and
    /// returns the final path with the retained committed handle.
    fn commit_through_anchor(
        dir: &Path,
        anchor: &OutputDir,
        name: &str,
    ) -> (std::path::PathBuf, FinalizedFile) {
        let mut tmp = tempfile::Builder::new().tempfile_in(dir).unwrap();
        tmp.write_all(b"committed").unwrap();
        let path = dir.join(name);
        let finalized = finalize_file(tmp, &path, "Key file", anchor)
            .expect("the commit must succeed on a fresh name");
        (path, finalized)
    }

    /// The rollback tells its caller what it left behind: a file removed
    /// with its only name needs no report, a file with a second name
    /// survives under it, an entry that is no longer the committed file is
    /// left in place, and a name that is already gone cannot be confirmed.
    /// The rollback consumes the committed handle, so the on-disk state is
    /// final when it returns on every platform. The second-name case runs
    /// on Windows too, where NTFS has hard links and the report is
    /// load-bearing.
    #[test]
    fn rollback_reports_a_removed_linked_replaced_or_missing_file() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let dir = tmp_dir.path();
        let anchor = OutputDir::open(dir).unwrap();

        let committed = |outcome| Rollback {
            outcome,
            file: RemovedFile::Committed,
        };

        let (removed, finalized) = commit_through_anchor(dir, &anchor, "removed");
        assert_eq!(
            anchor.remove_published_if_retained(&removed, finalized),
            committed(RollbackOutcome::Removed)
        );
        assert!(!removed.exists(), "a file with one name must be gone");

        let (linked, finalized) = commit_through_anchor(dir, &anchor, "linked");
        let other_name = dir.join("linked.other");
        fs::hard_link(&linked, &other_name).unwrap();
        assert_eq!(
            anchor.remove_published_if_retained(&linked, finalized),
            committed(RollbackOutcome::RemovedButLinked { link_count: 2 })
        );
        assert!(!linked.exists(), "the committed name must still be removed");
        assert_eq!(
            fs::read(&other_name).unwrap(),
            b"committed",
            "the other name is not this operation's to remove"
        );

        let (replaced, finalized) = commit_through_anchor(dir, &anchor, "replaced");
        let moved = dir.join("replaced.moved");
        fs::rename(&replaced, &moved).unwrap();
        fs::write(&replaced, b"planted").unwrap();
        assert_eq!(
            anchor.remove_published_if_retained(&replaced, finalized),
            committed(RollbackOutcome::Replaced)
        );
        assert_eq!(fs::read(&replaced).unwrap(), b"planted");
        assert_eq!(fs::read(&moved).unwrap(), b"committed");

        let (missing, finalized) = commit_through_anchor(dir, &anchor, "missing");
        fs::remove_file(&missing).unwrap();
        assert_eq!(
            anchor.remove_published_if_retained(&missing, finalized),
            committed(RollbackOutcome::Unconfirmed)
        );
    }

    /// The identity check and the removal are two steps, and a local
    /// writer can replace the entry between them. On Windows the removal
    /// acts on the retained handle, so the replacement survives and the
    /// committed file is the one removed — wherever it was moved to. Unix
    /// unlinks by name and cannot make this promise; `SECURITY.md` records
    /// that bound.
    #[cfg(windows)]
    #[test]
    fn rollback_removal_acts_on_the_committed_file_not_on_the_name() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let dir = tmp_dir.path();
        let anchor = OutputDir::open(dir).unwrap();
        let (path, finalized) = commit_through_anchor(dir, &anchor, "private.key");
        let moved = dir.join("private.moved");

        let outcome =
            anchor.remove_if_retained_with(path.file_name().unwrap(), finalized.file, || {
                fs::rename(&path, &moved).unwrap();
                fs::write(&path, b"planted").unwrap();
            });

        assert_eq!(outcome, RollbackOutcome::Removed);
        assert_eq!(
            fs::read(&path).unwrap(),
            b"planted",
            "an entry planted after the identity check must survive"
        );
        assert!(
            !moved.exists(),
            "the committed file must be removed under whatever name it holds"
        );
    }

    /// Only a complete removal leaves the operation's error unchanged.
    /// Every other outcome appends its report, and the error keeps its
    /// class so callers matching on it see what they saw before.
    #[test]
    fn rollback_report_is_appended_without_changing_the_error_class() {
        let path = Path::new("out/private.key");
        let io_error = || CryptoError::Io(io::Error::new(io::ErrorKind::TimedOut, "flush failed"));
        let staged = |outcome| Rollback {
            outcome,
            file: RemovedFile::Staged,
        };

        let unchanged = with_rollback_report(io_error(), staged(RollbackOutcome::Removed), path);
        assert_eq!(unchanged.to_string(), "flush failed");

        let linked = with_rollback_report(
            io_error(),
            staged(RollbackOutcome::RemovedButLinked { link_count: 2 }),
            path,
        );
        assert_eq!(
            linked.to_string(),
            "flush failed; the removed private.key had 2 filesystem names, so a copy may remain under another name"
        );
        match linked {
            CryptoError::Io(e) => assert_eq!(e.kind(), io::ErrorKind::TimedOut),
            other => panic!("the I/O class must be kept, got {other:?}"),
        }

        let replaced = with_rollback_report(
            CryptoError::InvalidInput("Key file already exists: out/public.key".into()),
            staged(RollbackOutcome::Replaced),
            path,
        );
        assert_eq!(
            replaced.to_string(),
            "Key file already exists: out/public.key; private.key was replaced during the operation and left in place, and the file this run wrote may remain under another name"
        );
        assert!(matches!(replaced, CryptoError::InvalidInput(_)));

        let unconfirmed =
            with_rollback_report(io_error(), staged(RollbackOutcome::Unconfirmed), path);
        assert_eq!(
            unconfirmed.to_string(),
            "flush failed; the removal of private.key could not be confirmed"
        );
    }

    /// The rollback of a committed file reports that a complete file was
    /// committed before saying what the removal left, so the error cannot
    /// read as if nothing had been written. It says so as a fact about the
    /// commit: a replaced entry is not called the file, and a file that is
    /// gone is not called present. A complete removal still reports nothing.
    #[test]
    fn a_committed_file_rollback_reports_the_commit_beside_its_outcome() {
        let path = Path::new("out/private.key");
        let io_error = || CryptoError::Io(io::Error::new(io::ErrorKind::TimedOut, "flush failed"));
        let committed = |outcome| {
            let rollback = Rollback {
                outcome,
                file: RemovedFile::Committed,
            };
            with_rollback_report(io_error(), rollback, path)
        };

        assert_eq!(
            committed(RollbackOutcome::Removed).to_string(),
            "flush failed"
        );
        assert_eq!(
            committed(RollbackOutcome::Unconfirmed).to_string(),
            "flush failed; a complete private.key was committed, and its removal could not be confirmed"
        );
        assert_eq!(
            committed(RollbackOutcome::Replaced).to_string(),
            "flush failed; a complete private.key was committed, but the entry at its name was replaced and left in place, and the committed file may remain under another name"
        );
        let linked = committed(RollbackOutcome::RemovedButLinked { link_count: 2 });
        assert_eq!(
            linked.to_string(),
            "flush failed; a complete private.key was committed and then removed, but it had 2 filesystem names, so a copy may remain under another name"
        );
        match linked {
            CryptoError::Io(e) => assert_eq!(e.kind(), io::ErrorKind::TimedOut),
            other => panic!("the I/O class must be kept, got {other:?}"),
        }
    }

    /// The durability barrier must flush the directory the handle was
    /// opened on, not whatever its path names later. After the
    /// directory is renamed aside, the handle-relative flush still
    /// succeeds against the moved directory, while the path-based
    /// flush of the old path has nothing left to open.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn output_dir_flush_durable_follows_the_handle_after_a_path_swap() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let anchored = tmp_dir.path().join("out");
        fs::create_dir(&anchored).unwrap();
        let handle = OutputDir::open(&anchored).unwrap();

        fs::rename(&anchored, tmp_dir.path().join("out.moved")).unwrap();

        handle
            .flush_durable()
            .expect("the flush must follow the handle, not the path");
        assert!(
            sync_dir_durable(&anchored).is_err(),
            "the old path no longer names a directory to flush"
        );
    }

    /// The handle-relative barrier fails, as the path-based one does, once
    /// the directory no longer grants the read access its flush needs: the
    /// denied reopen is returned, not taken for a filesystem without
    /// directory flushing.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn output_dir_flush_durable_reports_a_read_denied_directory() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let dir = tmp_dir.path().join("out");
        fs::create_dir(&dir).unwrap();
        let handle = OutputDir::open(&dir).unwrap();
        let locked = ReadDenied::lock(&dir);
        locked.assert_refused(handle.flush_durable());
    }

    // Neither fallback can be reached through `finalize_file` on the
    // filesystems that host `cargo test` (they support the atomic
    // no-replace rename), so both are exercised directly. The fs-matrix
    // exFAT lane covers the errno-driven dispatch end to end.

    /// A zero inode number or file index is what a filesystem without
    /// identifiers reports for every object, so it is read as no
    /// identity rather than as one every object shares.
    #[test]
    fn a_zero_inode_is_no_identity() {
        assert_eq!(identity_pair(7, 0), None);
        assert_eq!(identity_pair(0, 0), None);
        assert_eq!(identity_pair(7, 1), Some((7, 1)));
        assert_eq!(identity_pair(0, 1), Some((0, 1)));
    }

    /// The link route commits the staged content under the final name
    /// and leaves no staged name behind. It is the route taken wherever
    /// the filesystem has hard links, which is the case for the
    /// filesystems hosting `cargo test`.
    ///
    /// The committed file must be the staged file itself, not a copy of
    /// it: callers pin the staged mode for a `.fcr` file and for
    /// `private.key`, so a commit that reproduced the content under
    /// fresh permissions would widen both.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_commits_and_drops_the_staged_name() {
        use std::os::unix::fs::PermissionsExt;

        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .permissions(fs::Permissions::from_mode(0o600))
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_path = tmp.path().to_path_buf();

        finalize_file_via_link_or_claim(tmp, &final_path, "Output").unwrap();
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "payload");
        assert!(
            !tmp_path.exists(),
            "staged name must not survive the commit"
        );
        assert_eq!(
            fs::metadata(&final_path).unwrap().permissions().mode() & 0o777,
            0o600,
            "the staged file's mode must survive the commit"
        );
    }

    /// A temp file staged outside the destination directory violates the
    /// [`finalize_file`] contract. The fallback must refuse it by identity
    /// before creating anything at the final name, rather than let the
    /// mismatch surface later as placeholder churn and an orphaned staged
    /// file. The same rejection covers a staged entry deleted or replaced
    /// by a local writer, so it reports as a filesystem condition, not an
    /// internal error. The refused temp is removed by its own destructor
    /// at the path it was actually created.
    #[cfg(unix)]
    #[test]
    fn fallback_refuses_a_temp_staged_outside_the_destination_directory() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let elsewhere = tmp_dir.path().join("elsewhere");
        let out = tmp_dir.path().join("out");
        fs::create_dir(&elsewhere).unwrap();
        fs::create_dir(&out).unwrap();
        let final_path = out.join("out.txt");

        let mut tmp = tempfile::Builder::new().tempfile_in(&elsewhere).unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_path = tmp.path().to_path_buf();

        let error = finalize_file_via_link_or_claim(tmp, &final_path, "Output")
            .expect_err("a temp staged elsewhere must be refused");
        assert!(!error.committed());
        assert!(
            matches!(
                error.into_crypto_error(),
                CryptoError::InvalidInput(message)
                    if message.contains("is not the entry under its name")
            ),
            "the refusal must name the staged-entry mismatch"
        );
        assert_eq!(
            fs::read_dir(&out).unwrap().count(),
            0,
            "the refusal must precede any entry at the final name"
        );
        assert!(
            !tmp_path.exists(),
            "the refused temp is cleaned up at its own path"
        );
    }

    /// The staged-entry verification precedes every removal on the fallback
    /// route. With the temp staged elsewhere and a final path with no last
    /// component, the refusal must be the identity one, and a same-named
    /// entry in the anchored directory must survive.
    #[cfg(unix)]
    #[test]
    fn fallback_verifies_the_staged_temp_before_any_removal() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let elsewhere = tmp_dir.path().join("elsewhere");
        let out = tmp_dir.path().join("out");
        fs::create_dir(&elsewhere).unwrap();
        fs::create_dir(&out).unwrap();

        let mut tmp = tempfile::Builder::new().tempfile_in(&elsewhere).unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_path = tmp.path().to_path_buf();
        let planted = out.join(tmp_path.file_name().unwrap());
        fs::write(&planted, b"unrelated").unwrap();

        let error = finalize_file_via_link_or_claim_in(
            tmp,
            Path::new("/"),
            "Output",
            &OutputDir::open(&out).unwrap(),
        )
        .expect_err("an unverified staged temp must be refused");
        assert!(!error.committed());
        assert!(
            matches!(
                error.into_crypto_error(),
                CryptoError::InvalidInput(message)
                    if message.contains("is not the entry under its name")
            ),
            "the identity refusal must come before the missing-name error"
        );
        assert_eq!(
            fs::read(&planted).unwrap(),
            b"unrelated",
            "the same-named entry in the anchor must survive"
        );
        assert!(!tmp_path.exists(), "the temp is removed at its own path");
    }

    /// A final path with no last component still refuses, and the staged
    /// temp — verified as the anchored entry by then — is removed through
    /// the anchor.
    #[cfg(unix)]
    #[test]
    fn fallback_removes_a_verified_temp_when_the_final_path_has_no_name() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_path = tmp.path().to_path_buf();

        let error = finalize_file_via_link_or_claim_in(
            tmp,
            Path::new("/"),
            "Output",
            &OutputDir::open(tmp_dir.path()).unwrap(),
        )
        .expect_err("a final path with no last component must be refused");
        assert!(!error.committed());
        match error.into_crypto_error() {
            CryptoError::Io(e) => assert_eq!(e.kind(), io::ErrorKind::InvalidInput),
            other => panic!("expected an I/O error, got {other:?}"),
        }
        assert!(!tmp_path.exists(), "the staged temp must be removed");
    }

    /// Once the final hard link exists, a failure to remove the staged name is
    /// reported, never ignored. It is a post-commit error, reported with the
    /// count because the staged name need not be the only extra one, and both
    /// complete links are kept, so no rollback by name can delete a concurrent
    /// replacement.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_reports_a_retained_staging_link() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(tmp_dir.path()).unwrap();
        output_dir
            .dir
            .hard_link(&tmp_name, &output_dir.dir, final_path.file_name().unwrap())
            .unwrap();

        let error = finish_link_commit_with_remove(
            tmp,
            &output_dir,
            &final_path,
            final_path.file_name().unwrap(),
            &tmp_name,
            |_, _| {
                Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "injected staged unlink failure",
                ))
            },
        )
        .expect_err("a retained temporary name must not report success");

        assert!(error.committed());
        let rendered = error.into_crypto_error().to_string();
        assert!(
            rendered.contains("temporary name") && rendered.contains("could not be removed"),
            "the retained link must be explicit, got: {rendered}"
        );
        assert!(
            rendered.contains("has 2 filesystem names"),
            "the retained link must not hide the count, got: {rendered}"
        );
        assert_eq!(fs::read(&final_path).unwrap(), b"payload");
        assert_eq!(fs::read(tmp_dir.path().join(tmp_name)).unwrap(), b"payload");
    }

    /// Once the final hard link exists, a final name that cannot be reopened
    /// is reported as an unconfirmed path of a complete output, marked as a
    /// post-commit failure, and the committed file stays.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_reports_an_unopenable_final_name_as_complete() {
        use std::os::unix::fs::PermissionsExt;

        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(tmp_dir.path()).unwrap();
        output_dir
            .dir
            .hard_link(&tmp_name, &output_dir.dir, final_path.file_name().unwrap())
            .unwrap();

        let outcome = finish_link_commit_with_remove(
            tmp,
            &output_dir,
            &final_path,
            final_path.file_name().unwrap(),
            &tmp_name,
            |dir, name| {
                fs::set_permissions(&final_path, fs::Permissions::from_mode(0o000))?;
                dir.remove_file(name)
            },
        );
        fs::set_permissions(&final_path, fs::Permissions::from_mode(0o600)).unwrap();

        match outcome {
            // A privileged runner reopens the file despite its mode.
            Ok(_) => {}
            Err(error) => {
                assert!(error.committed());
                match error.into_crypto_error() {
                    CryptoError::Io(error) => {
                        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
                        assert_unconfirmed_path(&error.to_string(), &final_path);
                    }
                    other => panic!("the denial must be reported as I/O, got: {other}"),
                }
            }
        }
        assert_eq!(fs::read(&final_path).unwrap(), b"payload");
        assert!(!tmp_dir.path().join(tmp_name).exists());
    }

    /// A staged name that could not be removed is a second complete name for
    /// the output, so it is reported even when a check after the link fails
    /// first. Here the final name is moved away, which the reopen reports as
    /// a changed path, and the staged name is left in place.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_reports_a_retained_staging_link_beside_a_failed_check() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        let moved = tmp_dir.path().join("out.moved");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(tmp_dir.path()).unwrap();
        output_dir
            .dir
            .hard_link(&tmp_name, &output_dir.dir, final_path.file_name().unwrap())
            .unwrap();

        let error = finish_link_commit_with_remove(
            tmp,
            &output_dir,
            &final_path,
            final_path.file_name().unwrap(),
            &tmp_name,
            |_, _| {
                fs::rename(&final_path, &moved)?;
                Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "injected staged unlink failure",
                ))
            },
        )
        .expect_err("a moved final name must not report success");

        assert!(error.committed());
        let message = error.into_crypto_error().to_string();
        assert!(
            message.contains("reported path changed")
                && message.contains("temporary name")
                && message.contains("could not be removed"),
            "both conditions must be reported, got: {message}"
        );
        assert_eq!(fs::read(&moved).unwrap(), b"payload");
        assert_eq!(fs::read(tmp_dir.path().join(tmp_name)).unwrap(), b"payload");
    }

    /// Stages a file in `dir` and links it at `outsider` as well: a name a
    /// local writer made for the staged file before the commit.
    #[cfg(unix)]
    fn staged_with_outsider_link(dir: &Path, outsider: &Path) -> NamedTempFile {
        let mut tmp = tempfile::Builder::new().tempfile_in(dir).unwrap();
        tmp.write_all(b"payload").unwrap();
        fs::hard_link(tmp.path(), outsider).unwrap();
        tmp
    }

    /// Asserts that `error` reports `path` as changed and, beside it, the two
    /// names the committed file has, without naming `path` a second time as
    /// the complete output.
    #[cfg(unix)]
    fn assert_changed_path_with_count(error: FinalizeFileError, path: &Path) {
        assert!(error.committed());
        let error = error.into_crypto_error();
        let shown = sanitize_path_for_display(path);
        assert!(
            matches!(
                &error,
                CryptoError::InvalidInput(message)
                    if message.contains(&format!("reported path changed: {shown}"))
                        && message.contains("; the output has 2 filesystem names (expected 1)")
                        && message.matches(&shown).count() == 1
            ),
            "a changed path must not hide the count or be named as the output, got: {error}"
        );
    }

    /// A reported path that changed after a link commit does not skip the
    /// count. The output directory is swapped out once the staged name is
    /// removed, and a local writer had linked the staged file beforehand.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_reports_the_count_beside_a_changed_path() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let out = tmp_dir.path().join("out");
        fs::create_dir(&out).unwrap();
        let moved = tmp_dir.path().join("out.moved");
        let final_path = out.join("out.txt");

        let tmp = staged_with_outsider_link(&out, &out.join("outsider"));
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(&out).unwrap();
        output_dir
            .dir
            .hard_link(&tmp_name, &output_dir.dir, final_path.file_name().unwrap())
            .unwrap();

        let error = finish_link_commit_with_remove(
            tmp,
            &output_dir,
            &final_path,
            final_path.file_name().unwrap(),
            &tmp_name,
            |dir, name| {
                dir.remove_file(name)?;
                fs::rename(&out, &moved)?;
                fs::create_dir(&out)
            },
        )
        .expect_err("a changed path must not report success");

        assert_changed_path_with_count(error, &final_path);
        assert_eq!(fs::read(moved.join("out.txt")).unwrap(), b"payload");
        assert_eq!(fs::read(moved.join("outsider")).unwrap(), b"payload");
    }

    /// The rename route reads the count beside a changed path as well.
    #[cfg(unix)]
    #[test]
    fn finish_renamed_commit_reports_the_count_beside_a_changed_path() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let out = tmp_dir.path().join("out");
        fs::create_dir(&out).unwrap();
        let moved = tmp_dir.path().join("out.moved");
        let final_path = out.join("out.txt");

        let tmp = staged_with_outsider_link(&out, &out.join("outsider"));
        let output_dir = OutputDir::open(&out).unwrap();
        fs::rename(tmp.path(), &final_path).unwrap();
        fs::rename(&out, &moved).unwrap();
        fs::create_dir(&out).unwrap();

        let error = finish_renamed_commit(tmp, &output_dir, &final_path)
            .expect_err("a changed path must not report success");

        assert_changed_path_with_count(error, &final_path);
        assert_eq!(fs::read(moved.join("out.txt")).unwrap(), b"payload");
        assert_eq!(fs::read(moved.join("outsider")).unwrap(), b"payload");
    }

    /// Once the final hard link exists, a final name that now holds a symlink
    /// or a socket makes the no-follow reopen fail outright. Either is a
    /// substitution, reported as a changed path like every other entry that
    /// is not the committed regular file, rather than as a check that could
    /// not run.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_reports_a_substituted_final_name_as_changed() {
        // Plants the substitute at the final name, given where the committed
        // file was moved.
        type Plant = fn(&Path, &Path) -> io::Result<()>;
        let plants: [(&str, Plant); 2] = [
            ("symlink", |moved, name| {
                std::os::unix::fs::symlink(moved, name)
            }),
            ("socket", |_, name| {
                std::os::unix::net::UnixListener::bind(name).map(drop)
            }),
        ];
        for (substitute, plant) in plants {
            let tmp_dir = tempfile::TempDir::new().unwrap();
            let final_path = tmp_dir.path().join("out.txt");
            let moved = tmp_dir.path().join("out.moved");

            let mut tmp = tempfile::Builder::new()
                .tempfile_in(tmp_dir.path())
                .unwrap();
            tmp.write_all(b"payload").unwrap();
            let tmp_name = tmp.path().file_name().unwrap().to_os_string();
            let output_dir = OutputDir::open(tmp_dir.path()).unwrap();
            output_dir
                .dir
                .hard_link(&tmp_name, &output_dir.dir, final_path.file_name().unwrap())
                .unwrap();

            let error = finish_link_commit_with_remove(
                tmp,
                &output_dir,
                &final_path,
                final_path.file_name().unwrap(),
                &tmp_name,
                |dir, name| {
                    fs::rename(&final_path, &moved)?;
                    plant(&moved, &final_path)?;
                    dir.remove_file(name)
                },
            )
            .expect_err("a substituted final name must not report success");

            assert!(error.committed(), "{substitute}");
            assert!(
                matches!(
                    error.into_crypto_error(),
                    CryptoError::InvalidInput(message)
                        if message.contains("reported path changed")
                ),
                "a {substitute} at the final name must report as a changed path"
            );
            assert_eq!(fs::read(&moved).unwrap(), b"payload", "{substitute}");
        }
    }

    /// A concurrent directory writer can rename the staged link after the
    /// final link exists. The attempted unlink then reports `NotFound`, which
    /// is harmless only when the committed inode actually has one link left.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_rejects_a_renamed_staging_link_after_not_found() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        let hidden_name = std::ffi::OsString::from("moved-staging-link");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(tmp_dir.path()).unwrap();
        output_dir
            .dir
            .hard_link(&tmp_name, &output_dir.dir, final_path.file_name().unwrap())
            .unwrap();

        let error = finish_link_commit_with_remove(
            tmp,
            &output_dir,
            &final_path,
            final_path.file_name().unwrap(),
            &tmp_name,
            |dir, name| {
                dir.rename(name, dir, &hidden_name)?;
                dir.remove_file(name)
            },
        )
        .expect_err("a renamed second link must not report success");

        assert!(error.committed());
        let rendered = error.into_crypto_error().to_string();
        assert!(
            rendered.contains("has 2 filesystem names"),
            "the retained inode link must be explicit, got: {rendered}"
        );
        assert_eq!(fs::read(&final_path).unwrap(), b"payload");
        assert_eq!(
            fs::read(tmp_dir.path().join(hidden_name)).unwrap(),
            b"payload"
        );
        assert!(!tmp_dir.path().join(tmp_name).exists());
    }

    /// Renaming the staged link aside and planting a replacement at its old
    /// name can make the unlink itself succeed. The inode link count must still
    /// expose the retained original rather than trusting that return value.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_rejects_a_hidden_link_when_replacement_unlink_succeeds() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        let hidden_name = std::ffi::OsString::from("moved-staging-link");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(tmp_dir.path()).unwrap();
        output_dir
            .dir
            .hard_link(&tmp_name, &output_dir.dir, final_path.file_name().unwrap())
            .unwrap();

        let error = finish_link_commit_with_remove(
            tmp,
            &output_dir,
            &final_path,
            final_path.file_name().unwrap(),
            &tmp_name,
            |dir, name| {
                dir.rename(name, dir, &hidden_name)?;
                let mut options = cap_std::fs::OpenOptions::new();
                options.write(true).create_new(true);
                let mut replacement = dir.open_with(name, &options)?;
                replacement.write_all(b"replacement")?;
                drop(replacement);
                dir.remove_file(name)
            },
        )
        .expect_err("a hidden second link must not report success");

        assert!(error.committed());
        let rendered = error.into_crypto_error().to_string();
        assert!(
            rendered.contains("has 2 filesystem names"),
            "the retained inode link must be explicit, got: {rendered}"
        );
        assert_eq!(fs::read(&final_path).unwrap(), b"payload");
        assert_eq!(
            fs::read(tmp_dir.path().join(hidden_name)).unwrap(),
            b"payload"
        );
        assert!(!tmp_dir.path().join(tmp_name).exists());
    }

    /// The link route refuses an occupied final path with the same typed
    /// message as the atomic path, without creating a placeholder first.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_refuses_to_overwrite() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        fs::write(&final_path, "existing").unwrap();

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"new").unwrap();
        let tmp_path = tmp.path().to_path_buf();

        let error = finalize_file_via_link_or_claim(tmp, &final_path, "Output")
            .expect_err("an occupied output must fail before commit");
        assert!(!error.committed());
        match error.into_crypto_error() {
            CryptoError::InvalidInput(msg) => {
                assert!(msg.starts_with("Output already exists: "), "got: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "existing");
        assert!(!tmp_path.exists(), "temp file must be removed on failure");
    }

    /// A dangling symlink at the final path counts as occupied for the
    /// link route as well: `link` does not follow the target name, so it
    /// refuses rather than committing through the link.
    #[cfg(unix)]
    #[test]
    fn finalize_via_link_refuses_dangling_symlink_at_target() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        std::os::unix::fs::symlink(tmp_dir.path().join("nowhere"), &final_path).unwrap();

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"new").unwrap();

        let error = finalize_file_via_link_or_claim(tmp, &final_path, "Output")
            .expect_err("a dangling final symlink must fail before commit");
        assert!(!error.committed());
        match error.into_crypto_error() {
            CryptoError::InvalidInput(msg) => {
                assert!(msg.starts_with("Output already exists: "), "got: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
        let meta = fs::symlink_metadata(&final_path).unwrap();
        assert!(meta.file_type().is_symlink(), "symlink must be left as-is");
        assert!(
            !tmp_dir.path().join("nowhere").exists(),
            "the link target must not have been created"
        );
    }

    /// Commits `tmp` the way a caller does: through an anchor opened on
    /// the destination directory. Tests that exercise the anchor's own
    /// lifetime open and hold their own.
    fn commit_to(
        tmp: NamedTempFile,
        final_path: &Path,
        label: &str,
    ) -> Result<FinalizedFile, FinalizeFileError> {
        let anchor = OutputDir::open_for_commit(crate::fs::paths::parent_or_cwd(final_path))
            .expect("the destination directory must open as a commit anchor");
        finalize_file(tmp, final_path, label, &anchor)
    }

    /// Drives the claim route the way `finalize_file_via_link_or_claim_in`
    /// does, skipping the link the entry point would take first: a
    /// filesystem with hard links never reaches the claim through it.
    #[cfg(unix)]
    fn claim_commit(
        tmp: NamedTempFile,
        final_path: &Path,
        label: &str,
        output_dir: &OutputDir,
    ) -> Result<FinalizedFile, FinalizeFileError> {
        claim_commit_with(tmp, final_path, label, output_dir, |_| {})
    }

    /// [`claim_commit`] with the window between the claim and the rename
    /// over it, where a local writer's replacement would land.
    #[cfg(unix)]
    fn claim_commit_with(
        tmp: NamedTempFile,
        final_path: &Path,
        label: &str,
        output_dir: &OutputDir,
        after_claim: impl FnOnce(&cap_std::fs::Dir),
    ) -> Result<FinalizedFile, FinalizeFileError> {
        finalize_file_commit(
            tmp,
            final_path,
            label,
            output_dir,
            |anchor, staged, final_name| {
                crate::fs::commit::commit_by_claim_with(
                    anchor,
                    staged,
                    final_name,
                    CommitKind::File,
                    after_claim,
                )
            },
        )
    }

    /// Claim fallback commits the temp file when the final name is
    /// free; no placeholder survives.
    #[cfg(unix)]
    #[test]
    fn finalize_via_claim_succeeds_when_target_missing() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_path = tmp.path().to_path_buf();

        claim_commit(
            tmp,
            &final_path,
            "Output",
            &OutputDir::open(tmp_dir.path()).unwrap(),
        )
        .unwrap();
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "payload");
        assert!(!tmp_path.exists());
    }

    /// A hard link planted against the staged temp file survives the claim
    /// commit as a second name for the committed inode, so the route must
    /// report it after commit instead of succeeding.
    #[cfg(unix)]
    #[test]
    fn finalize_via_claim_rejects_a_second_link_to_the_committed_file() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let planted = tmp_dir.path().join("planted.txt");
        fs::hard_link(tmp.path(), &planted).unwrap();

        let error = claim_commit(
            tmp,
            &final_path,
            "Output",
            &OutputDir::open(tmp_dir.path()).unwrap(),
        )
        .expect_err("a second link to the committed inode must fail after commit");
        assert!(error.committed());
        let message = error.into_crypto_error().to_string();
        assert!(message.contains("has 2 filesystem names"), "got: {message}");
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "payload");
        assert_eq!(fs::read_to_string(&planted).unwrap(), "payload");
    }

    /// Claim fallback refuses an occupied final path with the same
    /// typed message as the atomic path, leaves the existing content
    /// untouched, and removes the temp file.
    #[cfg(unix)]
    #[test]
    fn finalize_via_claim_refuses_to_overwrite() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        fs::write(&final_path, "existing").unwrap();

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"new").unwrap();
        let tmp_path = tmp.path().to_path_buf();

        let error = claim_commit(
            tmp,
            &final_path,
            "Output",
            &OutputDir::open(tmp_dir.path()).unwrap(),
        )
        .expect_err("an occupied output must fail before commit");
        assert!(!error.committed());
        match error.into_crypto_error() {
            CryptoError::InvalidInput(msg) => {
                assert!(msg.starts_with("Output already exists: "), "got: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
        assert_eq!(fs::read_to_string(&final_path).unwrap(), "existing");
        assert!(!tmp_path.exists(), "temp file must be removed on failure");
    }

    /// A dangling symlink at the final path counts as occupied for the
    /// claim (`create_new` refuses to follow or replace it), matching
    /// the no-clobber contract of the atomic path.
    #[cfg(unix)]
    #[test]
    fn finalize_via_claim_refuses_dangling_symlink_at_target() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        std::os::unix::fs::symlink(tmp_dir.path().join("nowhere"), &final_path).unwrap();

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"new").unwrap();

        let error = claim_commit(
            tmp,
            &final_path,
            "Output",
            &OutputDir::open(tmp_dir.path()).unwrap(),
        )
        .expect_err("a dangling final symlink must fail before commit");
        assert!(!error.committed());
        match error.into_crypto_error() {
            CryptoError::InvalidInput(msg) => {
                assert!(msg.starts_with("Output already exists: "), "got: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
        let meta = fs::symlink_metadata(&final_path).unwrap();
        assert!(meta.file_type().is_symlink(), "symlink must be left as-is");
    }

    /// A failed rename step leaves the placeholder at the final name and
    /// reports it, because the empty file then holds that name against a
    /// further attempt. Forced by removing the staged file once the
    /// claim exists, which leaves the rename nothing to move.
    #[cfg(unix)]
    #[test]
    fn finalize_via_claim_leaves_the_claim_and_reports_it_when_the_rename_fails() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");

        let tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(tmp_dir.path()).unwrap();

        let err = claim_commit_with(tmp, &final_path, "Output", &output_dir, |dir| {
            dir.remove_file(&tmp_name).unwrap();
        })
        .expect_err("a rename with no staged file must fail the commit");
        assert!(!err.committed());
        let message = match err.into_crypto_error() {
            CryptoError::Io(e) => e.to_string(),
            other => panic!("expected an I/O failure, got {other:?}"),
        };
        assert!(
            message.contains("out.txt") && message.contains("may still be occupied"),
            "the name left occupied must be reported, got: {message}"
        );
        let left = fs::metadata(&final_path).expect("the placeholder stays at the final name");
        assert!(left.is_file() && left.len() == 0, "{left:?}");
    }

    /// A local writer can remove the placeholder and plant an entry of
    /// its own before the rename. When the rename then fails — the staged
    /// file is removed in the same window — that planted entry must be
    /// left where it is: a failed commit removes nothing from the final
    /// name.
    #[cfg(unix)]
    #[test]
    fn finalize_via_claim_leaves_a_replaced_claim_in_place() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let final_path = tmp_dir.path().join("out.txt");
        let final_name = final_path.file_name().unwrap();

        let mut tmp = tempfile::Builder::new()
            .tempfile_in(tmp_dir.path())
            .unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(tmp_dir.path()).unwrap();

        let err = claim_commit_with(tmp, &final_path, "Output", &output_dir, |dir| {
            dir.remove_file(final_name).unwrap();
            dir.write(final_name, b"planted").unwrap();
            dir.remove_file(&tmp_name).unwrap();
        })
        .expect_err("a rename with no staged file must fail the commit");
        assert!(!err.committed());
        assert_eq!(
            fs::read(&final_path).unwrap(),
            b"planted",
            "an entry planted in place of the placeholder must survive"
        );
    }

    /// An anchor threaded in by the caller is the directory the fallback
    /// commits in. Swap the output path after that anchor is opened and mint
    /// a same-named victim at the old path: the commit must land in the
    /// anchored (moved) directory, the victim must survive, and the final
    /// identity check must report a post-commit path-change error. Pins what
    /// the caller-threaded `anchor` argument guarantees for this fallback:
    /// the directory that receives the commit is also the one key-generation
    /// rollback acts on. Linux and macOS use the anchor for their directory
    /// barrier as well.
    #[cfg(unix)]
    #[test]
    fn anchored_fallback_commits_in_the_threaded_anchor_across_a_path_swap() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let orig = tmp_dir.path().join("orig");
        fs::create_dir(&orig).unwrap();
        let final_path = orig.join("out.txt");

        let mut tmp = tempfile::Builder::new().tempfile_in(&orig).unwrap();
        tmp.write_all(b"payload").unwrap();
        let anchor = OutputDir::open(&orig).unwrap();

        let moved = tmp_dir.path().join("moved");
        fs::rename(&orig, &moved).unwrap();
        fs::create_dir(&orig).unwrap();
        fs::write(&final_path, "victim").unwrap();

        let error = finalize_file_via_link_or_claim_in(tmp, &final_path, "Output", &anchor)
            .expect_err("the ambient path no longer names the committed file");
        assert!(error.committed());
        assert!(
            matches!(
                error.into_crypto_error(),
                CryptoError::InvalidInput(message)
                    if message.contains("reported path changed")
            ),
            "the path mismatch must be reported explicitly"
        );
        assert_eq!(
            fs::read_to_string(moved.join("out.txt")).unwrap(),
            "payload",
            "the commit must land in the anchored directory"
        );
        assert_eq!(
            fs::read_to_string(&final_path).unwrap(),
            "victim",
            "the entry at the old path must survive"
        );
    }

    /// The claim route commits through its retained anchor, but must not report
    /// the old ambient path after that directory is swapped. The real output
    /// lands in the moved directory, the substituted victim survives, and the
    /// final identity check reports a post-commit path-change error.
    #[cfg(unix)]
    #[test]
    fn finalize_via_claim_rejects_the_reported_path_after_a_directory_swap() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let orig = tmp_dir.path().join("orig");
        fs::create_dir(&orig).unwrap();
        let final_path = orig.join("out.txt");

        let mut tmp = tempfile::Builder::new().tempfile_in(&orig).unwrap();
        tmp.write_all(b"payload").unwrap();
        let tmp_name = tmp.path().file_name().unwrap().to_os_string();
        let output_dir = OutputDir::open(&orig).unwrap();

        // Swap: move the anchored directory aside and mint a
        // replacement holding a same-named victim.
        let moved = tmp_dir.path().join("moved");
        fs::rename(&orig, &moved).unwrap();
        fs::create_dir(&orig).unwrap();
        fs::write(&final_path, "victim").unwrap();

        let error = claim_commit(tmp, &final_path, "Output", &output_dir)
            .expect_err("the ambient path no longer names the committed file");
        assert!(error.committed());
        assert!(
            matches!(
                error.into_crypto_error(),
                CryptoError::InvalidInput(message)
                    if message.contains("reported path changed")
            ),
            "the path mismatch must be reported explicitly"
        );

        assert_eq!(
            fs::read_to_string(moved.join("out.txt")).unwrap(),
            "payload",
            "the commit must land in the anchored directory"
        );
        assert_eq!(
            fs::read_to_string(&final_path).unwrap(),
            "victim",
            "the entry at the swapped-in path must survive the commit"
        );
        assert!(
            !moved.join(&tmp_name).exists(),
            "the staged entry must not survive the commit"
        );
    }

    #[test]
    fn rename_no_clobber_refuses_to_overwrite_dir() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let from = tmp_dir.path().join("src");
        let to = tmp_dir.path().join("dst");
        fs::create_dir(&from).unwrap();
        fs::write(from.join("inner.txt"), "new").unwrap();
        fs::create_dir(&to).unwrap();
        fs::write(to.join("existing.txt"), "existing").unwrap();

        let err = rename_no_clobber(&from, &to).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert!(from.exists(), "source should not have been moved");
        assert!(
            to.join("existing.txt").exists(),
            "destination should be untouched"
        );
    }

    #[test]
    fn rename_no_clobber_succeeds_when_target_missing_dir() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let from = tmp_dir.path().join("src");
        let to = tmp_dir.path().join("dst");
        fs::create_dir(&from).unwrap();
        fs::write(from.join("payload.txt"), "hello").unwrap();

        rename_no_clobber(&from, &to).unwrap();

        assert!(!from.exists(), "source should have been moved");
        assert!(to.is_dir(), "destination should exist as a directory");
        assert_eq!(fs::read_to_string(to.join("payload.txt")).unwrap(), "hello",);
    }

    #[test]
    fn rename_no_clobber_handles_regular_file() {
        // The helper supports both directory entries and regular files;
        // prove the file case works with both the success path and the
        // refuse-to-overwrite path even though archive single-file
        // promotion prefers `promote_single_file_no_clobber` on the
        // targets that still route through this module.
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let from = tmp_dir.path().join("staged.txt");
        let to = tmp_dir.path().join("final.txt");
        fs::write(&from, "payload").unwrap();

        rename_no_clobber(&from, &to).unwrap();
        assert!(!from.exists());
        assert_eq!(fs::read_to_string(&to).unwrap(), "payload");

        // Re-stage and confirm the no-clobber branch also fires on files.
        fs::write(&from, "second").unwrap();
        let err = rename_no_clobber(&from, &to).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert_eq!(fs::read_to_string(&to).unwrap(), "payload");
        assert_eq!(fs::read_to_string(&from).unwrap(), "second");
    }

    #[test]
    fn promote_single_file_succeeds_when_target_missing() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let from = tmp_dir.path().join("staged.txt");
        let to = tmp_dir.path().join("final.txt");
        fs::write(&from, "payload").unwrap();

        promote_single_file_no_clobber(&from, &to).unwrap();
        assert!(!from.exists(), "Source should have been moved");
        assert_eq!(fs::read_to_string(&to).unwrap(), "payload");
    }

    #[test]
    fn promote_single_file_refuses_existing_target() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let from = tmp_dir.path().join("staged.txt");
        let to = tmp_dir.path().join("final.txt");
        fs::write(&from, "new").unwrap();
        fs::write(&to, "existing").unwrap();

        let err = promote_single_file_no_clobber(&from, &to).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert_eq!(fs::read_to_string(&to).unwrap(), "existing");
    }

    /// Pins the RetainOnError contract at the helper level: when the
    /// kernel refuses promotion (final name already taken), the staging
    /// file `from` must remain on disk. Regression-protects the
    /// `disable_cleanup` step inside `promote_single_file_no_clobber`
    /// against an inadvertent revert that would let `TempPath`'s
    /// destructor `remove_file(from)` after the failure path returns.
    #[test]
    fn promote_single_file_leaves_source_in_place_after_refusal() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let from = tmp_dir.path().join("staged.txt");
        let to = tmp_dir.path().join("final.txt");
        fs::write(&from, "new").unwrap();
        fs::write(&to, "existing").unwrap();

        let _ = promote_single_file_no_clobber(&from, &to).unwrap_err();
        assert!(
            from.exists(),
            "RetainOnError contract: source must remain after refused promotion"
        );
        assert_eq!(fs::read_to_string(&from).unwrap(), "new");
    }

    /// `sync_parent_dir` is a best-effort durability hint — it must
    /// swallow every failure so a callsite (`finalize_file`,
    /// `rename_no_clobber`) returning success is not retroactively
    /// flipped to an error after the final path is already visible.
    /// Pin the swallow with a missing parent: opening the parent dirfd
    /// fails, but the helper still returns `()` so finalization stays
    /// successful.
    #[test]
    fn sync_parent_dir_swallows_missing_parent() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let phantom_parent = tmp_dir.path().join("does-not-exist");
        let phantom_child = phantom_parent.join("child.txt");
        // No `unwrap` — `sync_parent_dir` returns `()` even though
        // `parent_or_cwd(phantom_child) = phantom_parent` is missing.
        sync_parent_dir(&phantom_child);
    }
}