exarch-core 0.7.0

Memory-safe archive extraction library with security validation
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
//! Archive listing implementation.

use std::fs::File;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;

use crate::ArchiveError;
use crate::ListOptions;
use crate::Result;
use crate::SecurityConfig;
use crate::StoredTargets;
use crate::config::Validated;
#[cfg(test)]
use crate::error::QuotaResource;
use crate::formats::ZipArchive;
use crate::formats::common::encrypted_archive_error;
use crate::formats::common::normalize_entry_name;
use crate::formats::common::symlink_target_too_large;
use crate::formats::compression::CompressionCodec;
use crate::formats::detect::ArchiveType;
use crate::formats::detect::FormatFamily;
use crate::formats::detect::detect_format;
use crate::formats::sevenz::LinkCapture;
use crate::formats::sevenz::LinkOutcome;
use crate::formats::sevenz::LinkTable;
use crate::formats::sevenz::SevenZClass;
use crate::formats::sevenz::SevenZHeader;
use crate::formats::sevenz::SevenZKind;
use crate::formats::sevenz::StoredLinkTarget;
use crate::formats::sevenz::deliver_undecoded_links;
use crate::formats::sevenz::read_sevenz_header;
use crate::formats::sevenz::sevenz_entry_compression;
use crate::formats::sevenz::verify_sevenz_blocks;
use crate::formats::sevenz::walk_sevenz_links;
use crate::formats::tar::TarNode;
use crate::formats::tar::effective_entry_type;
use crate::formats::tar::is_metadata_type;
use crate::formats::tar::open_tar_stream;
use crate::formats::tar::tar_node;
use crate::formats::tar_metadata_limit::TarEntryGuard;
use crate::formats::tar_metadata_limit::TarReadBudget;
use crate::formats::tar_metadata_limit::budget_violation;
use crate::formats::tar_metadata_limit::budgeted_reader;
use crate::formats::tar_metadata_limit::budgeted_tar_entries;
use crate::formats::zip::ZipEntryKind;
use crate::formats::zip::is_password_required;
use crate::formats::zip::parse_zip_entry_name;
use crate::formats::zip::read_zip_symlink_target;
use crate::formats::zip::read_zip_symlink_target_checked;
use crate::formats::zip::resolve_zip_entry_path;
use crate::formats::zip::zip_entry_kind;
use crate::formats::zip::zip_node_kind;
use crate::formats::zip_tail::DescriptorTail;
use crate::inspection::integrity::Charge;
use crate::inspection::integrity::DecodeOutcome;
use crate::inspection::integrity::IntegrityPass;
use crate::inspection::integrity::Slot;
use crate::inspection::integrity::TarTrailer;
use crate::inspection::manifest::ArchiveEntry;
use crate::inspection::manifest::ArchiveManifest;
use crate::inspection::manifest::EntryCompression;
use crate::inspection::manifest::EntryPosition;
use crate::inspection::manifest::LinkTarget;
use crate::inspection::manifest::ManifestEntryKind;
use crate::inspection::manifest::ManifestEntryType;
use crate::inspection::report::UnverifiedReason;
use crate::security::fs_view::LinkKind;
use crate::security::fs_view::MAX_SYMLINK_TARGET_BYTES;
use crate::security::fs_view::check_name_lengths;
use crate::security::fs_view::name_too_long;
use crate::security::quota::QuotaPermit;
use crate::security::quota::QuotaTracker;
use crate::security::validator::EntryPath;
use crate::security::validator::NodeKind;
use crate::security::validator::require_non_empty_name;
use crate::types::safe_path::has_null_bytes;

/// Lists archive contents without extracting.
///
/// Returns a manifest containing metadata for all entries in the archive.
/// No files are written to disk during this operation.
///
/// # Arguments
///
/// * `archive_path` - Path to archive file
/// * `config` - Security configuration (quota limits apply)
///
/// # Errors
///
/// Returns error if:
/// - Archive file cannot be opened
/// - Archive format is unsupported or corrupted
/// - Quota limits exceeded (file count, total size, single file size)
/// - A ZIP archive's structure is read differently by different tools
///   ([`ArchiveError::ZipInconsistency`], unless `zip_consistency` is `Ignore`)
/// - A link target exceeds the host's name limits
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::list_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let manifest = list_archive("archive.tar.gz", &config)?;
///
/// println!("Archive contains {} files", manifest.total_entries());
/// for entry in manifest.entries() {
///     println!("{}: {} bytes", entry.path.display(), entry.size);
/// }
/// # Ok(())
/// # }
/// ```
pub fn list_archive<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
) -> Result<ArchiveManifest> {
    list_archive_with_options(archive_path, config, &ListOptions::default())
}

/// Lists archive contents without extracting, with [`ListOptions`].
///
/// See [`list_archive`] for the manifest and the failures listing reports.
/// [`ListOptions::stored_targets`] set to [`StoredTargets::Read`] reads 7z
/// symlink targets, which decodes the blocks that hold them; by default they
/// stay unread, so listing decodes no entry data. Other formats always report
/// their targets.
///
/// # Errors
///
/// Same as [`list_archive`].
///
/// # Examples
///
/// ```
/// use exarch_core::LinkTarget;
/// use exarch_core::ListOptions;
/// use exarch_core::ManifestEntryKind;
/// use exarch_core::SecurityConfig;
/// use exarch_core::StoredTargets;
/// use exarch_core::list_archive_with_options;
/// use sevenz_rust2::ArchiveEntry;
/// use sevenz_rust2::ArchiveWriter;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let dir = tempfile::tempdir()?;
/// # let archive = dir.path().join("links.7z");
/// # let mut writer = ArchiveWriter::new(std::io::Cursor::new(Vec::new()))?;
/// # let mut link = ArchiveEntry::new_file("link");
/// # link.has_stream = true;
/// # link.size = 6;
/// # link.has_windows_attributes = true;
/// # link.windows_attributes = 0x8000 | (0o120_777 << 16);
/// # writer.push_archive_entry(link, Some(std::io::Cursor::new(b"target".to_vec())))?;
/// # std::fs::write(&archive, writer.finish()?.into_inner())?;
/// let config = SecurityConfig::default();
///
/// let manifest = list_archive_with_options(&archive, &config, &ListOptions::default())?;
/// assert!(matches!(
///     &manifest.entries()[0].kind,
///     ManifestEntryKind::Symlink {
///         target: LinkTarget::Unread
///     }
/// ));
///
/// let options = ListOptions::default().with_stored_targets(StoredTargets::Read);
/// let manifest = list_archive_with_options(&archive, &config, &options)?;
/// assert!(matches!(
///     &manifest.entries()[0].kind,
///     ManifestEntryKind::Symlink {
///         target: LinkTarget::Recorded(_)
///     }
/// ));
/// # Ok(())
/// # }
/// ```
pub fn list_archive_with_options<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
    options: &ListOptions,
) -> Result<ArchiveManifest> {
    let config = config.clone().validate()?;
    list_validated(
        archive_path.as_ref(),
        &config,
        &mut ListPass::Strict(options.stored_targets),
    )
}

/// Which listing runs: the bare `list_archive`, or `verify`'s pre-flight.
///
/// The pre-flight defers rejections that `verify_entry` reports as issues, and
/// may decode payloads through an integrity pass. Only the pre-flight can carry
/// a pass, so a strict listing that decodes is unrepresentable.
pub(crate) enum ListPass<'a, 'c> {
    /// Bare listing: every policy violation fails the listing. Carries whether
    /// link targets kept in entry data are read.
    Strict(StoredTargets),
    /// `verify`'s pre-flight, optionally decoding payloads through the pass.
    VerifyPreflight(Option<&'a mut IntegrityPass<'c>>),
}

impl<'c> ListPass<'_, 'c> {
    /// A bare listing with the default [`StoredTargets`], which leaves 7z link
    /// targets unread.
    pub(crate) const fn strict() -> Self {
        Self::Strict(StoredTargets::Skip)
    }

    /// Returns the integrity pass, which only the pre-flight can carry.
    pub(crate) fn integrity(&mut self) -> Option<&mut IntegrityPass<'c>> {
        match self {
            Self::Strict(_) => None,
            Self::VerifyPreflight(pass) => pass.as_deref_mut(),
        }
    }

    const fn mode(&self) -> ListMode {
        match self {
            Self::Strict(_) => ListMode::Strict,
            Self::VerifyPreflight(_) => ListMode::VerifyPreflight,
        }
    }
}

/// Borrow-free projection of [`ListPass`] for checks that must not hold the
/// integrity pass.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ListMode {
    /// See [`ListPass::Strict`].
    Strict,
    /// See [`ListPass::VerifyPreflight`].
    VerifyPreflight,
}

/// Reserves quota for a listed entry; the pre-flight lifts only the per-file
/// size limit.
fn reserve_entry(
    quota: &mut QuotaTracker,
    size: u64,
    config: &SecurityConfig<Validated>,
    mode: ListMode,
) -> Result<QuotaPermit> {
    match mode {
        ListMode::Strict => quota.reserve(size, config),
        ListMode::VerifyPreflight => quota.reserve_without_file_limit(size, config),
    }
}

/// Lists an archive with an already validated config, decoding payloads when
/// `listing` carries an integrity pass.
pub(crate) fn list_validated(
    archive_path: &Path,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
    list_detected(archive_path, detect_format(archive_path)?, config, listing)
}

/// Lists an archive whose format is already known.
pub(crate) fn list_detected(
    archive_path: &Path,
    format: ArchiveType,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
    match format.family() {
        FormatFamily::Tar(codec) => list_tar(archive_path, codec, format, config, listing),
        FormatFamily::Zip => list_zip(archive_path, config, listing),
        FormatFamily::SevenZ => list_sevenz(archive_path, config, listing),
    }
}

fn list_tar(
    archive_path: &Path,
    codec: Option<CompressionCodec>,
    format: ArchiveType,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
    let stream = open_tar_stream(archive_path, codec, config.max_decoder_memory)?;
    let (budgeted, budget) = budgeted_reader(stream, config.max_tar_metadata_bytes);
    let archive = tar::Archive::new(budgeted);
    let trailer = if codec.is_some() {
        TarTrailer::DrainToDecoderEof
    } else {
        TarTrailer::Probe
    };
    list_tar_entries(archive, budget, format, config, listing, trailer)
}

/// Lists entries from a TAR archive already wrapped in a [`budgeted_reader`].
///
/// `budget` must be the handle returned alongside the reader that `archive`
/// wraps — passed explicitly (rather than re-derived) so the reader and the
/// budget used to arm/disarm around it can never be a mismatched pair.
fn list_tar_entries<R: std::io::Read>(
    mut archive: tar::Archive<crate::formats::tar_metadata_limit::BudgetedReader<R>>,
    budget: TarReadBudget,
    format: ArchiveType,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
    trailer: TarTrailer,
) -> Result<ArchiveManifest> {
    let list_mode = listing.mode();
    let mut manifest = ArchiveManifest::new(format);
    let mut quota = QuotaTracker::new();

    let mut entries = budgeted_tar_entries(&mut archive, budget)
        .map_err(|e| ArchiveError::InvalidArchive(format!("failed to read TAR entries: {e}")))?;

    while let Some(entry_result) = entries.next_entry() {
        let mut entry = entry_result.map_err(|e| {
            budget_violation(&e).unwrap_or_else(|| {
                ArchiveError::InvalidArchive(format!("failed to read TAR entry: {e}"))
            })
        })?;

        // Skip TAR metadata entries (PAX headers, GNU long names/links)
        if is_metadata_type(entry.header().entry_type()) {
            continue;
        }

        let size = entry.size();

        // Route through the same QuotaTracker used by extraction: per-file
        // size, file count, and total size (with checked arithmetic) are all
        // enforced here using the same logic. Note this doesn't make listing
        // and extraction fully equivalent — extraction's QuotaTracker does not
        // record directories, while listing records every entry type, a
        // pre-existing divergence.
        //
        // A quota rejection here (the `?`) aborts the loop without an
        // explicit `entry.abandon()`; harmless — the guard's bounded drain
        // on drop is pointless I/O in that case, not a correctness
        // requirement (see `TarEntryGuard::abandon`).
        let _permit = reserve_entry(&mut quota, size, config, list_mode)?;

        let path = entry
            .path()
            .map_err(|e| ArchiveError::InvalidArchive(format!("invalid path: {e}")))?
            .into_owned();

        if list_mode == ListMode::Strict && has_null_bytes(&path) {
            return Err(ArchiveError::violation(format!(
                "path contains null bytes: {}",
                path.display()
            )));
        }

        if contains_traversal(&path, config) {
            return Err(ArchiveError::PathTraversal { path });
        }

        require_non_empty_name(&path)?;
        let tar_type = effective_entry_type(&entry)?;
        let kind = NodeKind::directory_if(tar_type == tar::EntryType::Directory);
        if !admit_path(&path, kind, &mut manifest, listing)? {
            continue;
        }

        let entry_type = convert_tar_entry_type(tar_type)?;
        let mode = crate::formats::tar::tar_permission_bits(entry.header());
        let modified =
            entry.header().mtime().ok().and_then(|t| {
                SystemTime::UNIX_EPOCH.checked_add(std::time::Duration::from_secs(t))
            });

        let target = match entry.header().entry_type() {
            tar::EntryType::Symlink | tar::EntryType::Link => {
                let target = entry
                    .link_name()
                    .map_err(|e| ArchiveError::InvalidArchive(format!("invalid link target: {e}")))?
                    .map(std::borrow::Cow::into_owned);
                let is_symlink = entry.header().entry_type() == tar::EntryType::Symlink;
                let kind = if is_symlink {
                    LinkKind::Symlink
                } else {
                    LinkKind::Hardlink
                };

                match target {
                    Some(t) => classify_link_target(t, kind, list_mode)?,
                    // `link_name()` returns `None` when neither the ustar
                    // linkname field nor a PAX `linkpath` override is
                    // present — a structurally different case from an
                    // empty-string target (see `validate_link_target`).
                    // `extract` rejects this via `to_entry_type`
                    // (formats/tar.rs) with the same message; mirrored here
                    // for list/extract parity; skipped in verify's pre-flight
                    // since `verify_entry` reports a missing target.
                    None if list_mode == ListMode::Strict => {
                        return Err(ArchiveError::InvalidArchive(format!(
                            "{kind} missing target"
                        )));
                    }
                    None => LinkTarget::Missing,
                }
            }
            _ => LinkTarget::Missing,
        };

        let archive_entry = ArchiveEntry {
            path,
            kind: manifest_entry_kind(entry_type, target),
            size,
            compression: EntryCompression::Unknown,
            mode,
            modified,
        };

        if let Some(pass) = listing.integrity() {
            let slot = pass.begin_entry(size, &archive_entry.compression);
            if entry_type == ManifestEntryType::File && size > 0 {
                verify_tar_payload(pass, slot, &mut entry, &archive_entry.path)?;
            }
        }

        manifest.add_entry(archive_entry)?;
    }

    drop(entries);
    if let Some(pass) = listing.integrity() {
        pass.check_tar_trailer(&mut archive.into_inner(), trailer)?;
    }

    Ok(manifest)
}

/// Reads one TAR entry's content to its end so the codec and the tar framing
/// are exercised.
///
/// A decode failure inside entry content is a hard error: the scan cannot
/// continue past it, and a report over the entries read so far would let
/// security look fine for entries that were never inspected. Listing already
/// decodes every entry through the guard's drain, so only GNU sparse entries
/// (whose synthesized zeros the drain caps) are charged to the budget.
fn verify_tar_payload<R: Read>(
    pass: &mut IntegrityPass<'_>,
    slot: Slot,
    entry: &mut TarEntryGuard<'_, '_, R>,
    path: &Path,
) -> Result<()> {
    let charge = if entry.header().entry_type() == tar::EntryType::GNUSparse {
        Charge::Declared
    } else {
        Charge::Free
    };
    let declared = entry.size();
    match pass.decode(slot, &mut **entry, declared, charge) {
        DecodeOutcome::Failed(failure) => {
            entry.abandon();
            Err(failure.into_tar_error(path))
        }
        outcome => pass.record(slot, path, outcome),
    }
}

fn list_zip(
    archive_path: &Path,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
    let file = File::open(archive_path)?;
    ZipArchive::new(file)?.list_with(config, listing)
}

/// Lists entries from an already budget-wrapped TAR reader.
///
/// Used by `ArchiveFormat::list()` implementations to avoid re-opening the
/// archive. `format` is passed through into `ArchiveManifest` as-is. `budget`
/// must be the handle returned alongside `reader` from the same
/// `budgeted_reader` call.
pub(crate) fn list_tar_reader<R: Read>(
    reader: crate::formats::tar_metadata_limit::BudgetedReader<R>,
    budget: TarReadBudget,
    format: ArchiveType,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
    trailer: TarTrailer,
) -> Result<ArchiveManifest> {
    let archive = tar::Archive::new(reader);
    list_tar_entries(archive, budget, format, config, listing, trailer)
}

/// Lists entries from an already-opened ZIP archive.
///
/// Used by `ArchiveFormat::list()` and `verify()`. Taking the crate's own
/// handler rather than the raw reader proves that opening already ran the
/// admission checks (encryption, method, declared sizes) and the structural
/// census, so listing does not repeat them.
pub(crate) fn list_zip_reader<R: Read + Seek>(
    archive: &mut ZipArchive<R>,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
    let list_mode = listing.mode();
    let mut manifest = ArchiveManifest::new(ArchiveType::Zip);
    let mut quota = QuotaTracker::new();
    let archive = archive.reader_mut();

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i).map_err(|e| {
            if is_password_required(&e) {
                return encrypted_archive_error();
            }
            ArchiveError::InvalidArchive(format!("failed to read ZIP entry: {e}"))
        })?;

        // Route through the same QuotaTracker used by extraction: per-file
        // size, file count, and total size (with checked arithmetic) are all
        // enforced here using the same logic. Note this doesn't make listing
        // and extraction fully equivalent — extraction's QuotaTracker does not
        // record directories, while listing records every entry type, a
        // pre-existing divergence.
        let _permit = reserve_entry(&mut quota, entry.size(), config, list_mode)?;

        let raw_name = entry
            .name()
            .map_err(|e| ArchiveError::InvalidArchive(format!("invalid entry name: {e}")))?
            .into_owned();
        let path = match list_mode {
            ListMode::Strict => resolve_zip_entry_path(&raw_name, config)?,
            ListMode::VerifyPreflight => {
                parse_zip_entry_name(&raw_name, config)?.into_preflight_path()
            }
        };
        let kind = zip_node_kind(&path, &entry)?;
        if !admit_path(&path, kind, &mut manifest, listing)? {
            continue;
        }

        let entry_type = convert_zip_entry_type(&entry, kind);
        let size = entry.size();
        let compression = EntryCompression::Entry(entry.compressed_size());
        let mode = entry.unix_mode().map(|m| m & 0o7777);
        #[expect(
            clippy::cast_sign_loss,
            reason = "the value is non-negative at this point"
        )]
        let modified = entry.last_modified().and_then(|dt| {
            time::PrimitiveDateTime::try_from(dt).ok().and_then(|t| {
                let timestamp = t.assume_utc().unix_timestamp().max(0) as u64;
                SystemTime::UNIX_EPOCH.checked_add(std::time::Duration::from_secs(timestamp))
            })
        });

        let mut tracked = listing.integrity().map(|pass| {
            let slot = pass.begin_entry(size, &compression);
            (pass, slot)
        });
        // Symlink targets are decoded below, through the target read.
        let has_payload = entry_type != ManifestEntryType::Symlink
            && (entry_type != ManifestEntryType::Directory || size > 0);
        let mut descriptor_tail = None;
        if has_payload && let Some((pass, slot)) = tracked.as_mut() {
            let outcome = pass.decode(*slot, &mut entry, size, Charge::Declared);
            if matches!(outcome, DecodeOutcome::Verified) {
                descriptor_tail = DescriptorTail::of(&entry);
            }
            pass.record(*slot, &path, outcome)?;
        }

        // Drop `entry` before conditionally re-opening the archive for symlink
        // target data: the borrow checker requires the mutable borrow to end.
        drop(entry);

        if let (Some(tail), Some((pass, slot))) = (descriptor_tail, tracked.as_mut()) {
            tail.check(archive, i, pass, *slot, &path)?;
        }

        let target = if entry_type == ManifestEntryType::Symlink {
            let mut sym_entry = archive.by_index(i).map_err(|e| {
                ArchiveError::InvalidArchive(format!("failed to re-read ZIP entry {i}: {e}"))
            })?;
            let declared = sym_entry.size();
            if list_mode == ListMode::VerifyPreflight && declared > MAX_SYMLINK_TARGET_BYTES as u64
            {
                LinkTarget::Oversized {
                    bytes: usize::try_from(declared).unwrap_or(usize::MAX),
                }
            } else {
                let target = match tracked.as_mut() {
                    Some((pass, slot)) => {
                        read_zip_symlink_target_checked(&mut sym_entry, pass, *slot, &path)?
                    }
                    None => read_zip_symlink_target(&mut sym_entry)?,
                };
                classify_link_target(target, LinkKind::Symlink, list_mode)?
            }
        } else {
            LinkTarget::Missing
        };

        let archive_entry = ArchiveEntry {
            path,
            kind: manifest_entry_kind(entry_type, target),
            size,
            compression,
            mode,
            modified,
        };

        manifest.add_entry(archive_entry)?;
    }

    Ok(manifest)
}

/// Lists entries from an already-opened 7z source reader.
///
/// Used by `ArchiveFormat::list()` to avoid re-opening the archive. The reader
/// must be positioned at the beginning of the 7z stream.
pub(crate) fn list_sevenz_reader<R: Read + Seek>(
    mut source: R,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
    let header = read_sevenz_header(&mut source)?;
    list_sevenz_parsed(&header, source, config, listing)
}

/// Lists an already-parsed 7z archive, decoding its blocks when `listing`
/// carries an integrity pass.
pub(crate) fn list_sevenz_parsed<R: Read + Seek>(
    header: &SevenZHeader,
    mut source: R,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
    let source_len = source.seek(SeekFrom::End(0))?;
    let ListedSevenZ {
        mut manifest,
        slots,
        compression,
        links,
    } = list_sevenz_archive(header, source_len, config, listing)?;
    let list_mode = listing.mode();
    let targets = SevenZTargets::of(listing, config.allowed.symlinks);
    let settle_header_targets = |manifest: &mut ArchiveManifest| {
        deliver_undecoded_links(header, links.indices(), &mut |index, outcome| {
            record_link_target(manifest, &links, list_mode, index, outcome)
        })
        .map(drop)
    };

    match targets {
        SevenZTargets::Leave(pass) => {
            if let Some(pass) = pass {
                verify_sevenz_blocks(header, &mut source, pass, &slots, None)?;
            }
        }
        SevenZTargets::Free => settle_header_targets(&mut manifest)?,
        SevenZTargets::Walk => walk_sevenz_links(
            header,
            &mut source,
            &compression,
            config,
            &links,
            &mut |index, outcome| {
                record_link_target(&mut manifest, &links, list_mode, index, outcome)
            },
        )?,
        SevenZTargets::Capture(pass) => {
            settle_header_targets(&mut manifest)?;
            let capture = LinkCapture {
                links: &links,
                set: &mut |position, target| manifest.set_link_target(position, target),
            };
            verify_sevenz_blocks(header, &mut source, pass, &slots, Some(capture))?;
        }
    }
    Ok(manifest)
}

/// How a 7z listing settles the targets of its Unix symlinks, which every
/// entry starts without ([`LinkTarget::Unread`]).
///
/// A variant carries the integrity pass exactly when it uses one, so a mode
/// and a pass that do not go together cannot be built.
enum SevenZTargets<'p, 'c> {
    /// Settle none: a verification that disallows symlinks reports the policy
    /// and never needs a target. Still decodes for integrity when requested.
    Leave(Option<&'p mut IntegrityPass<'c>>),
    /// Settle only the targets the file table gives (empty or oversized), with
    /// no decoding.
    Free,
    /// Decode the blocks holding links, stopping after each block's last link.
    Walk,
    /// Settle the header targets, then read the others in the integrity pass's
    /// own decode.
    Capture(&'p mut IntegrityPass<'c>),
}

impl<'p, 'c> SevenZTargets<'p, 'c> {
    fn of(listing: &'p mut ListPass<'_, 'c>, symlinks_allowed: bool) -> Self {
        match listing {
            ListPass::Strict(StoredTargets::Read) => Self::Walk,
            ListPass::Strict(StoredTargets::Skip) => Self::Free,
            ListPass::VerifyPreflight(pass) => match (pass.as_deref_mut(), symlinks_allowed) {
                (pass, false) => Self::Leave(pass),
                (None, true) => Self::Free,
                (Some(pass), true) => Self::Capture(pass),
            },
        }
    }
}

/// Sets the manifest target of the listed link at archive file `index` from
/// what reading it yielded.
fn record_link_target(
    manifest: &mut ArchiveManifest,
    links: &LinkTable<EntryPosition>,
    mode: ListMode,
    index: usize,
    outcome: LinkOutcome,
) -> Result<()> {
    if let Some(&position) = links.get(index) {
        manifest.set_link_target(position, link_target_of(outcome, mode)?);
    }
    Ok(())
}

/// What a link target that was asked for becomes in the manifest.
///
/// A bare listing refuses an oversized target (as ZIP does) and checks the
/// target; the verify pre-flight records both for `verify_entry` to report. A
/// target that could not be read is [`LinkTarget::Unreadable`] in both:
/// corrupt or refused data never fails the listing.
fn link_target_of(outcome: LinkOutcome, mode: ListMode) -> Result<LinkTarget> {
    match outcome {
        Ok(StoredLinkTarget::Read(target)) => classify_link_target(target, LinkKind::Symlink, mode),
        Ok(StoredLinkTarget::Oversized { bytes }) => match mode {
            ListMode::Strict => Err(symlink_target_too_large(bytes)),
            ListMode::VerifyPreflight => Ok(LinkTarget::Oversized {
                bytes: usize::try_from(bytes).unwrap_or(usize::MAX),
            }),
        },
        Err(_) => Ok(LinkTarget::Unreadable),
    }
}

/// Builds a manifest from a parsed 7z archive structure.
///
/// No NUL-byte check is applied to `entry.name`, unlike `list_tar_entries`
/// and `list_zip_reader`: `sevenz_rust2::Archive::read` decodes each name as
/// UTF-16 and stops at the first zero code unit while parsing the header
/// (see `sevenz-rust2::reader`'s `NamesReader`), so an embedded NUL cannot
/// survive into `entry.name` here. This is a format-parser guarantee, not a
/// scope decision — it would need re-checking if `sevenz-rust2` ever changes
/// that truncation behavior.
fn list_sevenz_archive(
    header: &SevenZHeader,
    source_len: u64,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ListedSevenZ> {
    let list_mode = listing.mode();
    let mut manifest = ArchiveManifest::new(ArchiveType::SevenZ);
    let mut quota = QuotaTracker::new();
    let compression = sevenz_entry_compression(header, source_len)?;
    // One element per archive file: the integrity slot of the manifest entry it
    // became, or `None` for an anti item (never listed), an entry dropped for
    // its path, or without a pass.
    let mut slots = Vec::with_capacity(header.files().len());
    let mut links = LinkTable::default();

    for (index, (entry, compression)) in header
        .files()
        .iter()
        .zip(compression.iter().copied())
        .enumerate()
    {
        let Some(kind) = SevenZClass::of(entry).present(&entry.name)? else {
            slots.push(None);
            continue;
        };

        // Route through the same QuotaTracker used by extraction: per-file
        // size, file count, and total size (with checked arithmetic) are all
        // enforced here using the same logic. Note this doesn't make listing
        // and extraction fully equivalent — extraction's QuotaTracker does not
        // record directories, while listing records every entry type, a
        // pre-existing divergence.
        let _permit = reserve_entry(&mut quota, entry.size, config, list_mode)?;

        let path = PathBuf::from(normalize_entry_name(&entry.name));

        if contains_traversal(&path, config) {
            return Err(ArchiveError::PathTraversal { path });
        }

        require_non_empty_name(&path)?;
        let entry_type = kind.manifest_type();
        if !admit_path(&path, kind.node_kind(), &mut manifest, listing)? {
            slots.push(None);
            continue;
        }

        let size = entry.size;
        let modified = entry
            .has_last_modified_date
            .then(|| SystemTime::from(entry.last_modified_date));

        slots.push(
            listing
                .integrity()
                .map(|pass| pass.begin_entry(size, &compression)),
        );

        let target = if kind == SevenZKind::ReparsePoint {
            LinkTarget::Unreadable
        } else {
            LinkTarget::Unread
        };
        let archive_entry = ArchiveEntry {
            path,
            kind: manifest_entry_kind(entry_type, target),
            size,
            compression,
            mode: None,
            modified,
        };

        if kind == SevenZKind::UnixSymlink {
            links.push(index, manifest.next_position())?;
        }
        manifest.add_entry(archive_entry)?;
    }

    Ok(ListedSevenZ {
        manifest,
        slots,
        compression,
        links,
    })
}

/// A 7z manifest built from the file table, before link targets are read.
struct ListedSevenZ {
    manifest: ArchiveManifest,
    /// One element per archive file; see [`list_sevenz_archive`].
    slots: Vec<Option<Slot>>,
    /// How each archive file's data is compressed, 1:1 with the files.
    compression: Vec<EntryCompression>,
    /// The manifest position of every listed Unix symlink; their targets are
    /// still [`LinkTarget::Unread`].
    links: LinkTable<EntryPosition>,
}

fn list_sevenz(
    archive_path: &Path,
    config: &SecurityConfig<Validated>,
    listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
    let mut file = File::open(archive_path)?;
    list_sevenz_reader(&mut file, config, listing)
}

/// Returns whether the entry at `path` is kept.
///
/// An entry the host cannot create fails the listing; the verify pre-flight
/// instead records only its length on `manifest` and drops it, so the report
/// can flag it without the manifest growing with the path. When the verify
/// pass decodes content, the dropped entry is also counted as unverified.
///
/// # Errors
///
/// A root entry (`.`) whose `kind` is not a directory fails the listing in
/// either mode, so no list handler can skip the root-entry rule.
fn admit_path(
    path: &Path,
    kind: NodeKind,
    manifest: &mut ArchiveManifest,
    listing: &mut ListPass<'_, '_>,
) -> Result<bool> {
    EntryPath::of(path).require_directory_root(kind)?;
    if check_name_lengths(path).is_ok() {
        return Ok(true);
    }
    if listing.mode() == ListMode::Strict {
        return Err(ArchiveError::Io(name_too_long()));
    }
    manifest.add_oversized(path.as_os_str().len());
    if let Some(pass) = listing.integrity() {
        pass.count_unverified(UnverifiedReason::PathTooLong, 1);
    }
    Ok(false)
}

fn manifest_entry_kind(entry_type: ManifestEntryType, target: LinkTarget) -> ManifestEntryKind {
    match entry_type {
        ManifestEntryType::File => ManifestEntryKind::File,
        ManifestEntryType::Directory => ManifestEntryKind::Directory,
        ManifestEntryType::Symlink => ManifestEntryKind::Symlink { target },
        ManifestEntryType::Hardlink => ManifestEntryKind::Hardlink { target },
    }
}

/// Checks a symlink/hardlink target parsed during listing for emptiness and
/// NUL bytes — the same two conditions `SafeSymlink::validate` and
/// `HardlinkTracker::validate_hardlink` reject during extraction (#424).
/// `kind` is `"symlink"` or `"hardlink"`, matching the wording used by those
/// extraction-side checks.
///
/// This does not give `list` full parity with `extract`: unlike the
/// extraction-side validators, it does not check
/// `config.allowed.symlinks`/`hardlinks`, reject absolute targets, or detect
/// traversal within the target — only emptiness and NUL bytes. Skipped
/// entirely in the verify pre-flight, so `verify_archive` can defer to
/// `verify_entry`'s own equivalent checks and report a graceful
/// `VerificationIssue` instead of aborting.
fn validate_link_target(target: &Path, kind: LinkKind, mode: ListMode) -> Result<()> {
    if mode == ListMode::VerifyPreflight {
        return Ok(());
    }
    if target.is_empty() {
        return Err(ArchiveError::violation(format!("{kind} target is empty")));
    }
    if has_null_bytes(target) {
        return Err(ArchiveError::violation(format!(
            "{kind} target contains null bytes"
        )));
    }
    Ok(())
}

/// Validates a link target found during listing and classifies it once.
///
/// A target beyond the host's name limits is never retained: bare listing
/// rejects it, and the verify pre-flight keeps only its length so the report
/// can flag it without the manifest growing with the target.
fn classify_link_target(target: PathBuf, kind: LinkKind, mode: ListMode) -> Result<LinkTarget> {
    validate_link_target(&target, kind, mode)?;
    match LinkTarget::classify(target, kind) {
        LinkTarget::Oversized { bytes } if mode == ListMode::Strict => Err(
            ArchiveError::InvalidArchive(format!("{kind} target too long: {bytes} bytes")),
        ),
        classified => Ok(classified),
    }
}

/// Returns `true` if the path contains traversal attempts.
///
/// `ParentDir` (`..`) is always rejected. `RootDir` and `Prefix` (Windows drive
/// paths such as `C:\`) are rejected only when `config.allowed.absolute_paths`
/// is false, matching the behaviour of `SafePath::validate`.
fn contains_traversal(path: &Path, config: &SecurityConfig<Validated>) -> bool {
    use std::path::Component;
    path.components().any(|c| match c {
        Component::ParentDir => true,
        Component::Prefix(_) | Component::RootDir => !config.allowed.absolute_paths,
        _ => false,
    })
}

fn convert_tar_entry_type(tar_type: tar::EntryType) -> Result<ManifestEntryType> {
    Ok(match tar_node(tar_type)? {
        TarNode::File => ManifestEntryType::File,
        TarNode::Directory => ManifestEntryType::Directory,
        TarNode::Symlink => ManifestEntryType::Symlink,
        TarNode::Hardlink => ManifestEntryType::Hardlink,
    })
}

fn convert_zip_entry_type<R: std::io::Read + std::io::Seek>(
    entry: &zip::read::ZipFile<'_, R>,
    kind: NodeKind,
) -> ManifestEntryType {
    match zip_entry_kind(kind == NodeKind::Directory, entry.unix_mode()) {
        ZipEntryKind::Directory => ManifestEntryType::Directory,
        ZipEntryKind::Symlink => ManifestEntryType::Symlink,
        ZipEntryKind::Regular => ManifestEntryType::File,
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::assert_matches;

    use crate::OversizedEntry;
    use crate::raw_zip::RawEntry;
    use crate::raw_zip::RawZip;
    use crate::raw_zip::extra_field;
    use crate::test_utils::HOST_PATH_LIMIT;
    use crate::test_utils::create_raw_zip_entry;
    use crate::test_utils::path_of_len;
    use crate::test_utils::tar_with_pax_linkpath;
    use crate::test_utils::tar_with_pax_nul_path;
    use flate2::write::GzEncoder;
    use std::io::Write;
    use tempfile::NamedTempFile;

    /// Builds a raw TAR archive containing a single entry with the given path
    /// string.
    ///
    /// The `tar` crate's `set_path()` rejects `..` components and absolute
    /// paths for safety, so we write the name directly into the 512-byte
    /// header block to create adversarial archives for testing path
    /// traversal detection.
    fn tar_with_raw_path(path: &str) -> Vec<u8> {
        // A TAR header is exactly 512 bytes. The name field is bytes 0..100.
        // We start with a zeroed block and fill in the minimal fields:
        // name (0), mode (100), uid (108), gid (116), size (124), mtime (136),
        // checksum (148), typeflag (156). All numeric fields are NUL-terminated
        // octal strings as per the POSIX ustar spec.
        let mut block = [0u8; 512];

        // Name field: first 100 bytes, NUL-terminated.
        let name_bytes = path.as_bytes();
        debug_assert!(
            name_bytes.len() <= 99,
            "tar_with_raw_path: path exceeds POSIX TAR name field limit (99 bytes)"
        );
        let name_len = name_bytes.len().min(99);
        block[..name_len].copy_from_slice(&name_bytes[..name_len]);

        // Mode: 0000644
        block[100..107].copy_from_slice(b"0000644");
        // UID: 0000000
        block[108..115].copy_from_slice(b"0000000");
        // GID: 0000000
        block[116..123].copy_from_slice(b"0000000");
        // Size: 0 bytes (empty file)
        block[124..135].copy_from_slice(b"00000000000");
        // Mtime: 0
        block[136..147].copy_from_slice(b"00000000000");
        // Typeflag: '0' (regular file)
        block[156] = b'0';

        // Checksum: sum of all bytes in the header (checksum field treated as
        // spaces).
        block[148..156].copy_from_slice(b"        ");
        let checksum: u32 = block.iter().map(|&b| u32::from(b)).sum();
        let checksum_str = format!("{checksum:06o}\0 ");
        block[148..156].copy_from_slice(checksum_str.as_bytes());

        // Two 512-byte zero blocks mark end-of-archive.
        let mut tar = block.to_vec();
        tar.extend_from_slice(&[0u8; 1024]);
        tar
    }

    /// Writes a minimal single-file ZIP archive where `external_attributes`
    /// encodes a full Unix stat(2) mode (file-type bits + permission bits)
    /// in the high 16 bits, as produced by system `zip(1)`, Python's
    /// `zipfile`, and other Unix-aware tools.
    ///
    /// `unix_mode` is what `ZipFile::unix_mode()` should return (i.e.
    /// `external_attributes >> 16`). The zip crate's write API masks
    /// `unix_permissions` to 0o777, so we construct the binary ZIP
    /// structure directly to reproduce archives from external tools.
    /// The entry is empty.
    fn zip_with_raw_unix_mode(filename: &str, unix_mode: u32) -> Vec<u8> {
        let entry = RawEntry {
            date: 0,
            external_attributes: unix_mode << 16,
            ..RawEntry::stored(filename, b"")
        };
        RawZip::new(vec![entry]).build().bytes
    }

    #[test]
    fn test_list_archive_empty_tar() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let builder = tar::Builder::new(Vec::new());
        let data = builder.into_inner().unwrap();
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 0);
        assert_eq!(manifest.total_size(), 0);
        assert_eq!(manifest.entries().len(), 0);
        assert_eq!(manifest.format(), ArchiveType::Tar);
    }

    #[test]
    fn test_list_archive_tar_gz() {
        let mut temp_file = NamedTempFile::with_suffix(".tar.gz").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let data = b"test content";
        let mut header = tar::Header::new_gnu();
        header.set_path("file.txt").unwrap();
        header.set_size(data.len() as u64);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();

        let tar_data = builder.into_inner().unwrap();
        let mut encoder = GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        let compressed = encoder.finish().unwrap();

        temp_file.write_all(&compressed).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.format(), ArchiveType::TarGz);
        assert_eq!(manifest.entries()[0].path, PathBuf::from("file.txt"));
        assert_eq!(
            manifest.entries()[0].kind.entry_type(),
            ManifestEntryType::File
        );
    }

    #[test]
    fn test_list_archive_zip() {
        let temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        let file = std::fs::File::create(temp_file.path()).unwrap();
        let mut zip = zip::ZipWriter::new(file);

        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated);
        zip.start_file("test.txt", options).unwrap();
        zip.write_all(b"test content").unwrap();
        zip.finish().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.format(), ArchiveType::Zip);
        assert_eq!(manifest.entries()[0].path, PathBuf::from("test.txt"));
        assert_eq!(
            manifest.entries()[0].kind.entry_type(),
            ManifestEntryType::File
        );
    }

    #[test]
    fn test_list_archive_with_entries() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let file1_data = b"content1";
        let mut header1 = tar::Header::new_gnu();
        header1.set_path("dir/file1.txt").unwrap();
        header1.set_size(file1_data.len() as u64);
        header1.set_cksum();
        builder.append(&header1, &file1_data[..]).unwrap();

        let file2_data = b"content2";
        let mut header2 = tar::Header::new_gnu();
        header2.set_path("dir/file2.txt").unwrap();
        header2.set_size(file2_data.len() as u64);
        header2.set_cksum();
        builder.append(&header2, &file2_data[..]).unwrap();

        let data = builder.into_inner().unwrap();
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 2);
        assert_eq!(manifest.total_size(), 16);
        assert_eq!(manifest.entries().len(), 2);
        assert_eq!(manifest.entries()[0].path, PathBuf::from("dir/file1.txt"));
        assert_eq!(manifest.entries()[1].path, PathBuf::from("dir/file2.txt"));
    }

    #[test]
    fn test_list_archive_with_symlink() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let mut header = tar::Header::new_gnu();
        header.set_path("link").unwrap();
        header.set_size(0);
        header.set_entry_type(tar::EntryType::Symlink);
        header.set_link_name("target.txt").unwrap();
        header.set_cksum();
        builder.append(&header, &[][..]).unwrap();

        let data = builder.into_inner().unwrap();
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(
            manifest.entries()[0].kind.entry_type(),
            ManifestEntryType::Symlink
        );
        assert_eq!(
            manifest.entries()[0].kind.symlink_target(),
            Some(Path::new("target.txt"))
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_list_zip_symlink_target_is_actual_target() {
        use crate::test_utils::create_zip_with_symlink;
        use std::io::Cursor;

        let zip_bytes = create_zip_with_symlink("link", "target.txt");
        let mut archive = ZipArchive::new(Cursor::new(zip_bytes)).unwrap();
        let config = SecurityConfig::default().validate().expect("valid config");
        let manifest = list_zip_reader(&mut archive, &config, &mut ListPass::strict()).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(
            manifest.entries()[0].kind.entry_type(),
            ManifestEntryType::Symlink
        );
        assert_eq!(
            manifest.entries()[0].kind.symlink_target(),
            Some(Path::new("target.txt")),
            "symlink_target must be the actual link target, not the entry path"
        );
        assert_eq!(
            manifest.entries()[0].kind.hardlink_target(),
            None,
            "ZIP has no hardlink concept — hardlink_target must always be None"
        );
    }

    #[test]
    fn test_list_archive_with_hardlink() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let mut header = tar::Header::new_gnu();
        header.set_path("link").unwrap();
        header.set_size(0);
        header.set_entry_type(tar::EntryType::Link);
        header.set_link_name("original.txt").unwrap();
        header.set_cksum();
        builder.append(&header, &[][..]).unwrap();

        let data = builder.into_inner().unwrap();
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(
            manifest.entries()[0].kind.entry_type(),
            ManifestEntryType::Hardlink
        );
        assert_eq!(
            manifest.entries()[0].kind.hardlink_target(),
            Some(Path::new("original.txt"))
        );
    }

    #[test]
    fn test_list_archive_quota_exceeded() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        // Create 2 entries
        let data = b"test data";
        let mut header = tar::Header::new_gnu();
        header.set_path("file1.txt").unwrap();
        header.set_size(data.len() as u64);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();

        let mut header2 = tar::Header::new_gnu();
        header2.set_path("file2.txt").unwrap();
        header2.set_size(data.len() as u64);
        header2.set_cksum();
        builder.append(&header2, &data[..]).unwrap();

        let archive_data = builder.into_inner().unwrap();
        temp_file.write_all(&archive_data).unwrap();
        temp_file.flush().unwrap();

        // Set quota to 1 file
        let config = SecurityConfig::default().with_max_file_count(1);

        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::FileCount { current, max },
            }) => {
                assert_eq!(max, 1);
                assert_eq!(current, 2, "current must be max+1 (off-by-one fix)");
            }
            other => panic!("expected FileCount quota error, got {other:?}"),
        }
    }

    #[test]
    fn test_list_zip_quota_exceeded_file_count() {
        let temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        let file = std::fs::File::create(temp_file.path()).unwrap();
        let mut zip = zip::ZipWriter::new(file);
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        zip.start_file("a.txt", options).unwrap();
        zip.start_file("b.txt", options).unwrap();
        zip.finish().unwrap();

        let config = SecurityConfig::default().with_max_file_count(1);

        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::FileCount { current, max },
            }) => {
                assert_eq!(max, 1);
                assert_eq!(current, 2, "current must be max+1 (off-by-one fix)");
            }
            other => panic!("expected FileCount quota error, got {other:?}"),
        }
    }

    #[test]
    fn test_zip_mode_strips_s_ifreg_bits() {
        // Archives from Unix tools store the full stat(2) mode in
        // external_attributes. 0o100644 = S_IFREG (0o100000) | 0o644.
        // After listing, only 0o644 must remain.
        let zip_bytes = zip_with_raw_unix_mode("file.txt", 0o100_644);
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.entries()[0].mode, Some(0o644));
    }

    #[test]
    fn test_zip_mode_strips_s_ifdir_bits() {
        // 0o040755 = S_IFDIR (0o040000) | 0o755. After listing, only 0o755 must
        // remain.
        let zip_bytes = zip_with_raw_unix_mode("mydir/", 0o040_755);
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.entries()[0].mode, Some(0o755));
    }

    #[test]
    fn test_zip_mode_permission_bits_unchanged() {
        // When no file-type bits are present, permission bits must be preserved
        // as-is.
        let zip_bytes = zip_with_raw_unix_mode("file.txt", 0o644);
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.entries()[0].mode, Some(0o644));
    }

    #[test]
    fn test_list_zip_encrypted_returns_security_violation() {
        use std::io::Cursor;
        use zip::ZipWriter;
        use zip::unstable::write::FileOptionsExt;
        use zip::write::SimpleFileOptions;

        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
        let options = SimpleFileOptions::default()
            .with_deprecated_encryption(b"password")
            .unwrap();
        writer.start_file("secret.txt", options).unwrap();
        writer.write_all(b"secret data").unwrap();
        let zip_data = writer.finish().unwrap().into_inner();

        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert!(
                    reason.contains("password-protected"),
                    "expected 'password-protected' in reason: {reason}"
                );
            }
            other => panic!("expected SecurityViolation, got: {other:?}"),
        }
    }

    #[test]
    fn test_list_archive_tar_bz2() {
        use bzip2::Compression as BzCompression;
        use bzip2::write::BzEncoder;
        use std::io::Write;

        let mut temp_file = NamedTempFile::with_suffix(".tar.bz2").unwrap();

        let mut builder = tar::Builder::new(Vec::new());
        let data = b"bzip2 content";
        let mut header = tar::Header::new_gnu();
        header.set_path("file.txt").unwrap();
        header.set_size(data.len() as u64);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();
        let tar_data = builder.into_inner().unwrap();

        let mut encoder = BzEncoder::new(Vec::new(), BzCompression::default());
        encoder.write_all(&tar_data).unwrap();
        let compressed = encoder.finish().unwrap();

        temp_file.write_all(&compressed).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.format(), ArchiveType::TarBz2);
        assert_eq!(manifest.entries()[0].path, PathBuf::from("file.txt"));
    }

    #[test]
    fn test_list_archive_tar_xz() {
        use std::io::Write;
        use xz2::write::XzEncoder;

        let mut temp_file = NamedTempFile::with_suffix(".tar.xz").unwrap();

        let mut builder = tar::Builder::new(Vec::new());
        let data = b"xz content";
        let mut header = tar::Header::new_gnu();
        header.set_path("file.txt").unwrap();
        header.set_size(data.len() as u64);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();
        let tar_data = builder.into_inner().unwrap();

        let mut encoder = XzEncoder::new(Vec::new(), 1);
        encoder.write_all(&tar_data).unwrap();
        let compressed = encoder.finish().unwrap();

        temp_file.write_all(&compressed).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.format(), ArchiveType::TarXz);
    }

    #[test]
    fn test_list_archive_tar_zst() {
        use std::io::Write;
        use zstd::stream::write::Encoder as ZstdEncoder;

        let mut temp_file = NamedTempFile::with_suffix(".tar.zst").unwrap();

        let mut builder = tar::Builder::new(Vec::new());
        let data = b"zstd content";
        let mut header = tar::Header::new_gnu();
        header.set_path("file.txt").unwrap();
        header.set_size(data.len() as u64);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();
        let tar_data = builder.into_inner().unwrap();

        let mut encoder = ZstdEncoder::new(Vec::new(), 1).unwrap();
        encoder.write_all(&tar_data).unwrap();
        let compressed = encoder.finish().unwrap();

        temp_file.write_all(&compressed).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let manifest = list_archive(temp_file.path(), &config).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.format(), ArchiveType::TarZst);
    }

    #[test]
    fn test_list_sevenz_corrupt() {
        // A truncated 7z header (valid magic, invalid body) must return
        // InvalidArchive.
        let mut temp_file = NamedTempFile::with_suffix(".7z").unwrap();
        temp_file.write_all(b"7z\xbc\xaf\x27\x1c\x00\x04").unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::InvalidArchive(_)),
            "expected InvalidArchive for truncated 7z, got: {result:?}"
        );
    }

    #[test]
    fn test_list_tar_special_file_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let mut header = tar::Header::new_gnu();
        header.set_path("chardev").unwrap();
        header.set_size(0);
        header.set_entry_type(tar::EntryType::Char);
        header.set_cksum();
        builder.append(&header, &[][..]).unwrap();

        let data = builder.into_inner().unwrap();
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::SecurityViolation { .. }),
            "expected SecurityViolation for char device entry, got: {result:?}"
        );
    }

    #[test]
    fn test_list_zip_quota_exceeded_total_size() {
        let temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        let file = std::fs::File::create(temp_file.path()).unwrap();
        let mut zip = zip::ZipWriter::new(file);
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        zip.start_file("big.bin", options).unwrap();
        zip.write_all(&vec![0u8; 600]).unwrap();
        zip.finish().unwrap();

        let config = SecurityConfig::default().with_max_total_size(100);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::QuotaExceeded {
                resource: crate::error::QuotaResource::TotalSize { .. }
            }),
            "expected TotalSize quota error, got: {result:?}"
        );
    }

    #[test]
    fn test_list_tar_quota_exceeded_total_size() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let data = vec![0u8; 600];
        let mut header = tar::Header::new_gnu();
        header.set_path("big.bin").unwrap();
        header.set_size(data.len() as u64);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();

        let archive_data = builder.into_inner().unwrap();
        temp_file.write_all(&archive_data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_max_total_size(100);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::QuotaExceeded {
                resource: crate::error::QuotaResource::TotalSize { .. }
            }),
            "expected TotalSize quota error, got: {result:?}"
        );
    }

    #[test]
    fn test_list_zip_path_traversal() {
        // ZIP with ../etc/passwd entry — resolve_zip_entry_path rejects the
        // `..` component with PathTraversal.
        let temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        let file = std::fs::File::create(temp_file.path()).unwrap();
        let mut zip = zip::ZipWriter::new(file);
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        zip.start_file("../etc/passwd", options).unwrap();
        zip.write_all(b"malicious").unwrap();
        zip.finish().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "expected PathTraversal error, got: {result:?}"
        );
    }

    #[test]
    fn test_list_tar_path_traversal_dotdot() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_raw_path("../escape.txt"))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            &result,
            Err(ArchiveError::PathTraversal { path }) if path == &PathBuf::from("../escape.txt"),
            "expected PathTraversal {{ path: ../escape.txt }}, got: {result:?}"
        );
    }

    #[test]
    fn test_list_tar_path_traversal_nested() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_raw_path("foo/../../escape.txt"))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "expected PathTraversal error for nested ../ in TAR, got: {result:?}"
        );
    }

    #[test]
    fn test_list_tar_path_traversal_absolute() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_raw_path("/etc/passwd"))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "expected PathTraversal error for absolute path in TAR, got: {result:?}"
        );
    }

    #[test]
    fn test_list_tar_absolute_path_allowed_when_flag_set() {
        // Regression for #318: allow_absolute_paths must also take effect
        // during the listing phase, not only during extraction.
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_raw_path("/etc/passwd"))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_allow_absolute_paths(true);
        let result = list_archive(temp_file.path(), &config);
        assert!(
            result.is_ok(),
            "list_archive must accept absolute paths when allow_absolute_paths=true, got: {result:?}"
        );
        let manifest = result.unwrap();
        assert_eq!(manifest.total_entries(), 1);
    }

    #[test]
    fn test_list_sevenz_absolute_path_allowed_when_flag_set() {
        // Regression for #318: allow_absolute_paths must propagate to 7z
        // listing.
        let archive_bytes = make_sevenz_archive(&[("/absolute/path.txt", b"data")]);
        let mut temp_file = NamedTempFile::with_suffix(".7z").unwrap();
        temp_file.write_all(&archive_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_allow_absolute_paths(true);
        let result = list_archive(temp_file.path(), &config);
        assert!(
            result.is_ok(),
            "list_archive must accept absolute paths in 7z when allow_absolute_paths=true, got: {result:?}"
        );
    }

    /// Unit test for `contains_traversal` — verifies that `Prefix` (Windows
    /// drive paths) is gated by `allow_absolute_paths`, matching
    /// `SafePath::validate`. On Unix there is no native way to produce a
    /// `Prefix` component via the filesystem, so we test the function logic
    /// directly with a crafted `PathBuf`.
    #[test]
    fn test_contains_traversal_prefix_gated_by_flag() {
        // A path whose string representation starts with a Windows-style drive
        // prefix. On Windows this produces Component::Prefix; on Unix the
        // entire string is treated as a relative path component (no
        // Prefix produced), so this test exercises the flag-gating
        // logic via the RootDir path instead. The critical invariant —
        // Prefix and RootDir share the same gate — is verified by the
        // match arm `Component::Prefix(_) | Component::RootDir`.
        let absolute = PathBuf::from("/absolute/path.txt");

        let config_deny = SecurityConfig::default().validate().expect("valid config"); // absolute_paths = false
        assert!(
            contains_traversal(&absolute, &config_deny),
            "absolute path must be rejected when allow_absolute_paths=false"
        );

        let config_allow = SecurityConfig::default()
            .with_allow_absolute_paths(true)
            .validate()
            .expect("valid config");
        assert!(
            !contains_traversal(&absolute, &config_allow),
            "absolute path must be accepted when allow_absolute_paths=true"
        );

        // ParentDir must always be rejected regardless of the flag.
        let dotdot = PathBuf::from("../escape.txt");
        assert!(
            contains_traversal(&dotdot, &config_allow),
            "ParentDir must be rejected even when allow_absolute_paths=true"
        );
    }

    #[test]
    fn test_list_tar_gz_path_traversal() {
        let mut temp_file = NamedTempFile::with_suffix(".tar.gz").unwrap();
        let tar_data = tar_with_raw_path("../escape.txt");
        let mut encoder = GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        let compressed = encoder.finish().unwrap();

        temp_file.write_all(&compressed).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "expected PathTraversal error for tar.gz with ../ entry, got: {result:?}"
        );
    }

    #[test]
    fn test_list_tar_path_traversal_mixed_entries_fail_fast() {
        // A safe entry followed by a traversal entry — verifies fail-fast
        // behavior: error must be returned immediately on the traversal
        // entry, not after accumulating the safe entry into a partial
        // manifest.
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let safe_data = b"safe content";
        let mut header = tar::Header::new_gnu();
        header.set_path("hello.txt").unwrap();
        header.set_size(safe_data.len() as u64);
        header.set_cksum();
        builder.append(&header, &safe_data[..]).unwrap();
        let safe_tar = builder.into_inner().unwrap();

        // safe_tar ends with the two zero-block end-of-archive marker. Strip it
        // and append the raw traversal entry + end-of-archive to create
        // a two-entry archive. The tar crate always writes exactly two
        // 512-byte zero blocks (1024 bytes total) as the end-of-archive
        // marker per POSIX ustar §3.4. Verified with tar 0.4.x; a
        // future major version bump should re-check this.
        let eof_marker_len = 1024;
        let tar_body = &safe_tar[..safe_tar.len() - eof_marker_len];
        let traversal_entry = tar_with_raw_path("../escape.txt");
        // tar_with_raw_path includes end-of-archive, so use it as-is after the
        // body.
        let mut combined = tar_body.to_vec();
        combined.extend_from_slice(&traversal_entry);

        temp_file.write_all(&combined).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "expected PathTraversal error for mixed-entry TAR, got: {result:?}"
        );
    }

    #[test]
    fn test_list_zip_by_index_encrypted_error_path() {
        // Cover the encrypted entry check at list.rs line 260
        // (entry.encrypted() == true). ZipCrypto entries succeed at
        // by_index() time but are flagged as encrypted by the entry
        // metadata, triggering SecurityViolation::EncryptedArchive.
        use std::io::Write;
        use zip::ZipWriter;
        use zip::unstable::write::FileOptionsExt;
        use zip::write::SimpleFileOptions;

        let mut writer = ZipWriter::new(std::io::Cursor::new(Vec::new()));
        let options = SimpleFileOptions::default()
            .with_deprecated_encryption(b"password")
            .unwrap();
        writer.start_file("secret.txt", options).unwrap();
        writer.write_all(b"secret data").unwrap();
        let zip_data = writer.finish().unwrap().into_inner();

        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::SecurityViolation { .. }),
            "expected SecurityViolation for encrypted ZIP in list, got: {result:?}"
        );
    }

    #[test]
    fn test_tar_and_zip_mode_consistent() {
        // TAR and ZIP must both store only permission bits in
        // ArchiveEntry.mode.
        let tar_file = NamedTempFile::with_suffix(".tar").unwrap();
        {
            let mut builder = tar::Builder::new(std::fs::File::create(tar_file.path()).unwrap());
            let data = b"content";
            let mut header = tar::Header::new_gnu();
            header.set_path("file.txt").unwrap();
            header.set_size(data.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder.append(&header, &data[..]).unwrap();
            builder.into_inner().unwrap();
        }

        // ZIP with full S_IFREG mode, as written by an external Unix tool.
        let zip_bytes = zip_with_raw_unix_mode("file.txt", 0o100_644);
        let zip_file = NamedTempFile::with_suffix(".zip").unwrap();
        {
            let mut f = std::fs::File::create(zip_file.path()).unwrap();
            f.write_all(&zip_bytes).unwrap();
        }

        let config = SecurityConfig::default();
        let tar_manifest = list_archive(tar_file.path(), &config).unwrap();
        let zip_manifest = list_archive(zip_file.path(), &config).unwrap();

        assert_eq!(
            tar_manifest.entries()[0].mode,
            zip_manifest.entries()[0].mode
        );
        assert_eq!(tar_manifest.entries()[0].mode, Some(0o644));
    }

    #[test]
    fn test_list_sevenz_simple() {
        let path = std::path::Path::new("../../tests/fixtures/simple.7z");
        let config = SecurityConfig::default();
        let manifest = list_archive(path, &config).unwrap();
        assert!(
            manifest.total_entries() > 0,
            "simple.7z should have entries"
        );
        for entry in manifest.entries() {
            assert!(!entry.path.is_empty(), "entry path should not be empty");
        }
    }

    #[test]
    fn test_list_sevenz_empty() {
        let path = std::path::Path::new("../../tests/fixtures/empty.7z");
        let config = SecurityConfig::default();
        let manifest = list_archive(path, &config).unwrap();
        assert_eq!(
            manifest.total_entries(),
            0,
            "empty.7z should have no entries"
        );
        assert_eq!(
            manifest.total_size(),
            0,
            "empty.7z should have zero total size"
        );
    }

    #[test]
    fn test_list_sevenz_nested_dirs() {
        let path = std::path::Path::new("../../tests/fixtures/nested-dirs.7z");
        let config = SecurityConfig::default();
        let manifest = list_archive(path, &config).unwrap();
        assert!(manifest.total_entries() > 0);
        let has_dir = manifest
            .entries()
            .iter()
            .any(|e| e.kind.entry_type() == ManifestEntryType::Directory);
        assert!(has_dir, "nested-dirs.7z should contain directory entries");
    }

    #[test]
    fn test_list_sevenz_encrypted_rejected() {
        let path = std::path::Path::new("../../tests/fixtures/encrypted.7z");
        let config = SecurityConfig::default();
        let result = list_archive(path, &config);
        assert!(result.is_err(), "encrypted archive should return an error");
        let err_str = result.unwrap_err().to_string().to_lowercase();
        assert!(
            err_str.contains("encrypt") || err_str.contains("password"),
            "error should mention encryption, got: {err_str}"
        );
    }

    #[test]
    fn test_list_sevenz_solid() {
        // Solid archives are safe to list (no decompression needed for
        // metadata).
        let path = std::path::Path::new("../../tests/fixtures/solid.7z");
        let config = SecurityConfig::default();
        let manifest = list_archive(path, &config).unwrap();
        assert!(manifest.total_entries() > 0, "solid.7z should have entries");
    }

    #[test]
    fn test_verify_sevenz_simple() {
        let path = std::path::Path::new("../../tests/fixtures/simple.7z");
        let config = SecurityConfig::default();
        let report = crate::verify_archive(path, &config).unwrap();
        assert_ne!(
            report.status(),
            crate::inspection::report::VerificationStatus::Fail,
            "simple.7z should not fail verification"
        );
    }

    #[test]
    fn test_list_sevenz_format_field() {
        let path = std::path::Path::new("../../tests/fixtures/simple.7z");
        let config = SecurityConfig::default();
        let manifest = list_archive(path, &config).unwrap();
        assert_eq!(
            manifest.format(),
            crate::formats::detect::ArchiveType::SevenZ,
            "manifest format should be SevenZ"
        );
    }

    /// Creates a minimal in-memory 7z archive with a single file entry
    /// and returns the archive bytes. Uses stored (no compression) method
    /// to keep test archives fast.
    fn make_sevenz_archive(entries: &[(&str, &[u8])]) -> Vec<u8> {
        use sevenz_rust2::ArchiveEntry;
        use sevenz_rust2::ArchiveWriter;
        use sevenz_rust2::EncoderConfiguration;
        use sevenz_rust2::EncoderMethod;
        use std::io::Cursor;

        let buf = Cursor::new(Vec::new());
        let mut writer = ArchiveWriter::new(buf).unwrap();
        writer.set_content_methods(vec![EncoderConfiguration::new(EncoderMethod::COPY)]);
        for (name, data) in entries {
            let mut entry = ArchiveEntry::new_file(name);
            entry.has_stream = true;
            entry.size = data.len() as u64;
            writer
                .push_archive_entry(entry, Some(std::io::Cursor::new(*data)))
                .unwrap();
        }
        writer.finish().unwrap().into_inner()
    }

    #[test]
    fn test_list_sevenz_path_traversal_dotdot() {
        // Create an archive with a traversal entry name; list should reject it.
        let archive_bytes = make_sevenz_archive(&[("../escape.txt", b"evil")]);
        let mut temp_file = NamedTempFile::with_suffix(".7z").unwrap();
        temp_file.write_all(&archive_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "expected PathTraversal error for ../ entry, got: {result:?}"
        );
    }

    #[test]
    fn test_list_sevenz_quota_file_count() {
        // Create an archive with 3 files and set a quota of 2.
        let archive_bytes =
            make_sevenz_archive(&[("a.txt", b"a"), ("b.txt", b"b"), ("c.txt", b"c")]);
        let mut temp_file = NamedTempFile::with_suffix(".7z").unwrap();
        temp_file.write_all(&archive_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_max_file_count(2);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::QuotaExceeded {
                resource: crate::error::QuotaResource::FileCount { .. }
            }),
            "expected FileCount QuotaExceeded, got: {result:?}"
        );
    }

    #[test]
    fn test_list_sevenz_quota_total_size() {
        // Create a file with 100 bytes and set a total-size quota of 50 bytes.
        let data = vec![0u8; 100];
        let archive_bytes = make_sevenz_archive(&[("big.bin", &data)]);
        let mut temp_file = NamedTempFile::with_suffix(".7z").unwrap();
        temp_file.write_all(&archive_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_max_total_size(50);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::QuotaExceeded {
                resource: crate::error::QuotaResource::TotalSize { .. }
            }),
            "expected TotalSize QuotaExceeded, got: {result:?}"
        );
    }

    #[test]
    fn test_list_sevenz_hardlink_reported_as_file() {
        // 7z has no hardlink concept — entries appear as regular files.
        let path = std::path::Path::new("../../tests/fixtures/hardlink.7z");
        let config = SecurityConfig::default();
        let manifest = list_archive(path, &config).unwrap();
        assert!(
            manifest.total_entries() > 0,
            "hardlink.7z should have entries"
        );
        for entry in manifest.entries() {
            assert_ne!(
                entry.kind.entry_type(),
                ManifestEntryType::Hardlink,
                "7z format never produces Hardlink entries (no API support)"
            );
        }
    }

    #[test]
    fn test_list_sevenz_solid_compressed_size() {
        // Entries in solid archives should not have compressed_size=Some(0)
        // with size>0. That combination would trigger a false positive
        // in zip bomb detection.
        let path = std::path::Path::new("../../tests/fixtures/solid.7z");
        let config = SecurityConfig::default();
        let manifest = list_archive(path, &config).unwrap();
        for entry in manifest.entries() {
            if entry.size > 0 {
                assert_ne!(
                    entry.compressed_size(),
                    Some(0),
                    "entry {:?} has compressed_size=Some(0) with size={}, which is a false positive trigger",
                    entry.path,
                    entry.size
                );
            }
        }
    }

    // Regression for #166: caller-supplied max_total_size must not be silently
    // discarded.
    #[test]
    fn test_list_archive_custom_max_total_size_honoured_tar() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let data = vec![0u8; 600];
        let mut header = tar::Header::new_gnu();
        header.set_path("file.bin").unwrap();
        header.set_size(data.len() as u64);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();
        temp_file.write_all(&builder.into_inner().unwrap()).unwrap();
        temp_file.flush().unwrap();

        // Small limit — must reject.
        let small = SecurityConfig::default().with_max_total_size(100);
        assert_matches!(
            list_archive(temp_file.path(), &small),
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::TotalSize { .. }
            }),
            "expected TotalSize quota error with limit=100"
        );

        // Large limit (simulates --max-total-size 1G) — must succeed.
        let large = SecurityConfig::default().with_max_total_size(1024 * 1024 * 1024);
        assert!(
            list_archive(temp_file.path(), &large).is_ok(),
            "list_archive must succeed when caller supplies a large max_total_size (regression #166)"
        );
    }

    #[test]
    fn test_list_archive_custom_max_total_size_honoured_zip() {
        let temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        {
            let file = std::fs::File::create(temp_file.path()).unwrap();
            let mut zip = zip::ZipWriter::new(file);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            zip.start_file("file.bin", options).unwrap();
            zip.write_all(&vec![0u8; 600]).unwrap();
            zip.finish().unwrap();
        }

        let small = SecurityConfig::default().with_max_total_size(100);
        assert_matches!(
            list_archive(temp_file.path(), &small),
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::TotalSize { .. }
            }),
            "expected TotalSize quota error with limit=100"
        );

        let large = SecurityConfig::default().with_max_total_size(1024 * 1024 * 1024);
        assert!(
            list_archive(temp_file.path(), &large).is_ok(),
            "list_archive must succeed when caller supplies a large max_total_size (regression #166)"
        );
    }

    #[test]
    fn test_list_archive_custom_max_total_size_honoured_sevenz() {
        let data = vec![0u8; 600];
        let archive_bytes = make_sevenz_archive(&[("file.bin", &data)]);
        let mut temp_file = NamedTempFile::with_suffix(".7z").unwrap();
        temp_file.write_all(&archive_bytes).unwrap();
        temp_file.flush().unwrap();

        let small = SecurityConfig::default().with_max_total_size(100);
        assert_matches!(
            list_archive(temp_file.path(), &small),
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::TotalSize { .. }
            }),
            "expected TotalSize quota error with limit=100"
        );

        let large = SecurityConfig::default().with_max_total_size(1024 * 1024 * 1024);
        assert!(
            list_archive(temp_file.path(), &large).is_ok(),
            "list_archive must succeed when caller supplies a large max_total_size (regression #166)"
        );
    }

    #[test]
    fn test_list_sevenz_regular_mode_entry_reported_as_file() {
        // The fixture's link.txt has a regular-file Unix mode, so it is
        // reported as ManifestEntryType::File.
        let path = std::path::Path::new("../../tests/fixtures/symlink-unix.7z");
        let config = SecurityConfig::default();
        let manifest = list_archive(path, &config).unwrap();
        assert!(
            manifest.total_entries() > 0,
            "symlink-unix.7z should have entries"
        );
        // All entries should be File or Directory — no Symlink (API
        // limitation).
        for entry in manifest.entries() {
            assert_ne!(
                entry.kind.entry_type(),
                ManifestEntryType::Symlink,
                "regular-mode entries are reported as File: {}",
                entry.path.display()
            );
        }
    }

    #[test]
    fn test_verify_sevenz_solid_no_false_positive() {
        use crate::inspection::report::IssueSeverity;

        let path = std::path::Path::new("../../tests/fixtures/solid.7z");
        let config = SecurityConfig::default().with_allow_solid_archives(true);
        let report = crate::verify_archive(path, &config).unwrap();
        assert_ne!(
            report.status(),
            crate::inspection::report::VerificationStatus::Fail,
            "solid.7z should not fail verification when solid archives are allowed"
        );
        let has_false_positive = report.issues().iter().any(|issue| {
            issue.severity == IssueSeverity::High
                && issue.message.to_lowercase().contains("compressed_size")
        });
        assert!(
            !has_false_positive,
            "solid.7z verification should not produce High-severity compressed_size issue"
        );
    }

    #[test]
    fn list_archive_rejects_invalid_security_config() {
        let config = SecurityConfig::default().with_max_file_size(0);
        let result = crate::list_archive("any.tar.gz", &config);
        assert_matches!(
            result,
            Err(crate::ArchiveError::InvalidConfiguration { .. }),
            "list_archive must return InvalidConfiguration for zero max_file_size"
        );
    }

    // --- Regression tests for #325: allow_absolute_paths for ZIP listing ---

    // The absolute-path policy is enforced on the raw name by
    // `resolve_zip_entry_path` (issue #631).
    #[test]
    fn test_list_zip_absolute_path_rejected_by_default() {
        let zip_bytes = create_raw_zip_entry("/etc/passwd", b"");
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "absolute ZIP name must be rejected by default like TAR, got: {result:?}"
        );
    }

    #[test]
    fn test_list_zip_absolute_path_allowed_when_configured() {
        let zip_bytes = create_raw_zip_entry("/etc/passwd", b"");
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_allow_absolute_paths(true);
        let manifest = list_archive(temp_file.path(), &config).unwrap();
        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.entries()[0].path, PathBuf::from("etc/passwd"));
    }

    #[test]
    fn test_list_zip_traversal_absolute_path_rejected_by_default() {
        // /../etc/passwd: traversal after root.
        // allow_absolute_paths is false, so the entry is rejected with
        // PathTraversal.
        let zip_bytes = create_raw_zip_entry("/../etc/passwd", b"");
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "absolute path with traversal must be rejected by default, got: {result:?}"
        );
    }

    #[test]
    fn test_list_zip_traversal_absolute_path_still_rejected_when_allowed() {
        // Even with allow_absolute_paths, /../etc/passwd must be rejected
        // because after stripping `/` the remaining `../etc/passwd` still
        // contains `..` which contains_traversal() catches.
        let zip_bytes = create_raw_zip_entry("/../etc/passwd", b"");
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_allow_absolute_paths(true);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "traversal inside absolute path must still be rejected even when allowed, got: {result:?}"
        );
    }

    #[test]
    fn test_list_zip_absolute_path_with_traversal_still_rejected() {
        // /foo/../../../etc/passwd: goes above root. The `..` components are
        // rejected even though the leading `/` is stripped.
        let zip_bytes = create_raw_zip_entry("/foo/../../../etc/passwd", b"");
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_allow_absolute_paths(true);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::PathTraversal { .. }),
            "traversal inside absolute path must still be rejected, got: {result:?}"
        );
    }

    #[test]
    fn test_list_zip_parent_glued_to_prefix_rejected_with_allow_absolute_paths() {
        for name in ["\\\\?\\C:..\\x", "/\\?\\C:.."] {
            let zip_bytes = create_raw_zip_entry(name, b"");
            let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
            temp_file.write_all(&zip_bytes).unwrap();
            temp_file.flush().unwrap();

            let config = SecurityConfig::default().with_allow_absolute_paths(true);
            let result = list_archive(temp_file.path(), &config);
            assert_matches!(result, Err(ArchiveError::PathTraversal { .. }), "{name:?}");
        }
    }

    // --- Regression tests for #430: list() must reject NUL bytes in entry
    // paths, matching extract()/verify() ---

    #[test]
    fn test_list_tar_pax_path_nul_byte_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_pax_nul_path(b"foo\0bar.txt", b"hello"))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert!(reason.contains("null bytes"), "reason: {reason}");
            }
            other => {
                panic!("expected SecurityViolation for NUL byte in PAX path, got: {other:?}")
            }
        }
    }

    #[test]
    fn test_list_zip_nul_byte_rejected_as_security_violation_by_default() {
        let zip_bytes = create_raw_zip_entry("foo\0bar.txt", b"");
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert!(reason.contains("null bytes"), "reason: {reason}");
            }
            other => {
                panic!("expected SecurityViolation for NUL byte in ZIP filename, got: {other:?}")
            }
        }
    }

    #[test]
    fn test_list_zip_nul_byte_rejected_with_allow_absolute_paths() {
        // The actual bypass closed by #430: allow_absolute_paths routes
        // through the raw name, so only the NUL check in
        // resolve_zip_entry_path catches it.
        let zip_bytes = create_raw_zip_entry("foo\0bar.txt", b"");
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&zip_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_allow_absolute_paths(true);
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert!(reason.contains("null bytes"), "reason: {reason}");
            }
            other => panic!(
                "expected SecurityViolation for NUL byte in ZIP filename with allow_absolute_paths, got: {other:?}"
            ),
        }
    }

    // --- Regression tests for #430 follow-up: list() must reject NUL bytes
    // and emptiness in symlink/hardlink targets, matching extract()'s
    // SafeSymlink/HardlinkTracker checks (#424) ---

    #[test]
    fn test_list_tar_symlink_target_nul_byte_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_pax_linkpath(b"foo\0bar", b'2'))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert_eq!(reason, "symlink target contains null bytes");
            }
            other => {
                panic!("expected SecurityViolation for NUL byte in symlink target, got: {other:?}")
            }
        }
    }

    #[test]
    fn test_list_tar_symlink_target_empty_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_pax_linkpath(b"", b'2'))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert_eq!(reason, "symlink target is empty");
            }
            other => panic!("expected SecurityViolation for empty symlink target, got: {other:?}"),
        }
    }

    #[test]
    fn test_list_tar_hardlink_target_nul_byte_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_pax_linkpath(b"foo\0bar", b'1'))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert_eq!(reason, "hardlink target contains null bytes");
            }
            other => {
                panic!("expected SecurityViolation for NUL byte in hardlink target, got: {other:?}")
            }
        }
    }

    #[test]
    fn test_list_tar_hardlink_target_empty_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_pax_linkpath(b"", b'1'))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert_eq!(reason, "hardlink target is empty");
            }
            other => panic!("expected SecurityViolation for empty hardlink target, got: {other:?}"),
        }
    }

    #[test]
    #[cfg(unix)]
    fn test_list_zip_symlink_target_nul_byte_rejected() {
        use crate::test_utils::create_zip_with_symlink;
        use std::io::Cursor;

        let zip_bytes = create_zip_with_symlink("link", "foo\0bar");
        let mut archive = ZipArchive::new(Cursor::new(zip_bytes)).unwrap();
        let config = SecurityConfig::default().validate().expect("valid config");
        let result = list_zip_reader(&mut archive, &config, &mut ListPass::strict());
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert_eq!(reason, "symlink target contains null bytes");
            }
            other => panic!(
                "expected SecurityViolation for NUL byte in ZIP symlink target, got: {other:?}"
            ),
        }
    }

    #[test]
    #[cfg(unix)]
    fn test_list_zip_symlink_target_empty_rejected() {
        use crate::test_utils::create_zip_with_symlink;
        use std::io::Cursor;

        let zip_bytes = create_zip_with_symlink("link", "");
        let mut archive = ZipArchive::new(Cursor::new(zip_bytes)).unwrap();
        let config = SecurityConfig::default().validate().expect("valid config");
        let result = list_zip_reader(&mut archive, &config, &mut ListPass::strict());
        match result {
            Err(ArchiveError::SecurityViolation { reason, .. }) => {
                assert_eq!(reason, "symlink target is empty");
            }
            other => {
                panic!("expected SecurityViolation for empty ZIP symlink target, got: {other:?}")
            }
        }
    }

    // --- Regression tests for #430 follow-up (round 3): a symlink/hardlink
    // entry with no link target at all (no ustar linkname field, no PAX
    // `linkpath` override — `entry.link_name()` returns `None`) must be
    // rejected by bare `list`, matching extract's `to_entry_type` wording,
    // while `ListPass::VerifyPreflight` must skip this check (and the
    // entry-path NUL and link-target emptiness/NUL checks) so verify's
    // pre-flight listing pass can defer to `verify_entry`'s own graceful
    // checks instead of aborting ---

    #[test]
    fn test_list_tar_symlink_missing_target_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let mut header = tar::Header::new_gnu();
        header.set_path("link").unwrap();
        header.set_size(0);
        header.set_entry_type(tar::EntryType::Symlink);
        // Deliberately no `set_link_name()` call: the raw linkname field
        // stays all-zero, so `entry.link_name()` returns `None` rather than
        // `Some(empty)`.
        header.set_cksum();
        builder.append(&header, &[][..]).unwrap();

        let data = builder.into_inner().unwrap();
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::InvalidArchive(msg)) => {
                assert_eq!(msg, "symlink missing target");
            }
            other => panic!("expected InvalidArchive for missing symlink target, got: {other:?}"),
        }
    }

    #[test]
    fn test_list_tar_hardlink_missing_target_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let mut header = tar::Header::new_gnu();
        header.set_path("link").unwrap();
        header.set_size(0);
        header.set_entry_type(tar::EntryType::Link);
        header.set_cksum();
        builder.append(&header, &[][..]).unwrap();

        let data = builder.into_inner().unwrap();
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let result = list_archive(temp_file.path(), &config);
        match result {
            Err(ArchiveError::InvalidArchive(msg)) => {
                assert_eq!(msg, "hardlink missing target");
            }
            other => panic!("expected InvalidArchive for missing hardlink target, got: {other:?}"),
        }
    }

    fn tar_with_paths(paths: &[&str]) -> NamedTempFile {
        let mut builder = tar::Builder::new(Vec::new());
        for path in paths {
            let mut header = tar::Header::new_gnu();
            header.set_size(1);
            header.set_cksum();
            builder.append_data(&mut header, path, &b"x"[..]).unwrap();
        }
        let mut file = NamedTempFile::with_suffix(".tar").unwrap();
        file.write_all(&builder.into_inner().unwrap()).unwrap();
        file.flush().unwrap();
        file
    }

    fn zip_with_names(names: &[&str]) -> NamedTempFile {
        let file = NamedTempFile::with_suffix(".zip").unwrap();
        let mut zip = zip::ZipWriter::new(std::fs::File::create(file.path()).unwrap());
        let options = zip::write::SimpleFileOptions::default();
        for name in names {
            zip.start_file(*name, options).unwrap();
            zip.write_all(b"x").unwrap();
        }
        zip.finish().unwrap();
        file
    }

    fn list_preflight(path: &Path, config: SecurityConfig) -> Result<ArchiveManifest> {
        list_validated(
            path,
            &config.validate()?,
            &mut ListPass::VerifyPreflight(None),
        )
    }

    fn assert_name_too_long(result: &Result<ArchiveManifest>) {
        assert!(
            matches!(result, Err(ArchiveError::Io(e)) if e.to_string() == "file name too long"),
            "expected name-too-long error, got {result:?}"
        );
    }

    #[test]
    fn test_list_tar_entry_path_limit_boundary() {
        let at_limit = path_of_len(HOST_PATH_LIMIT);
        let over = path_of_len(HOST_PATH_LIMIT + 1);
        let config = SecurityConfig::default();

        let ok = tar_with_paths(&[&at_limit]);
        assert_eq!(list_archive(ok.path(), &config).unwrap().total_entries(), 1);

        let bad = tar_with_paths(&[&over]);
        assert_name_too_long(&list_archive(bad.path(), &config));
    }

    #[test]
    fn test_list_tar_entry_component_limit() {
        let long_component = "a".repeat(255 + 1);
        let bad = tar_with_paths(&[&long_component]);
        assert_name_too_long(&list_archive(bad.path(), &SecurityConfig::default()));
    }

    #[test]
    fn test_list_tar_verify_preflight_records_oversized_entry() {
        let over = path_of_len(HOST_PATH_LIMIT + 1);
        let file = tar_with_paths(&["first.txt", &over, "last.txt"]);
        let manifest = list_preflight(file.path(), SecurityConfig::default()).unwrap();

        assert_eq!(manifest.total_entries(), 2);
        assert_eq!(
            manifest.oversized_entries(),
            &[OversizedEntry::new(1, HOST_PATH_LIMIT + 1)]
        );
        assert_eq!(manifest.entries()[1].path, PathBuf::from("last.txt"));
    }

    #[test]
    fn test_list_zip_entry_path_limit() {
        let at_limit = path_of_len(HOST_PATH_LIMIT);
        let over = path_of_len(HOST_PATH_LIMIT + 1);
        let config = SecurityConfig::default();

        let ok = zip_with_names(&[&at_limit]);
        assert_eq!(list_archive(ok.path(), &config).unwrap().total_entries(), 1);

        let bad = zip_with_names(&[&over]);
        assert_name_too_long(&list_archive(bad.path(), &config));
    }

    #[test]
    fn test_list_zip_verify_preflight_records_oversized_entry() {
        let over = path_of_len(HOST_PATH_LIMIT + 1);
        let file = zip_with_names(&[&over, "last.txt"]);
        let manifest = list_preflight(file.path(), SecurityConfig::default()).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(
            manifest.oversized_entries(),
            &[OversizedEntry::new(0, HOST_PATH_LIMIT + 1)]
        );
    }

    #[test]
    fn test_verify_reports_one_high_issue_per_oversized_entry() {
        let over = path_of_len(HOST_PATH_LIMIT + 1);
        let way_over = path_of_len(HOST_PATH_LIMIT * 3);
        let file = tar_with_paths(&["ok.txt", &over, &way_over]);

        let report = crate::verify_archive(file.path(), &SecurityConfig::default()).unwrap();

        assert_eq!(report.status(), crate::VerificationStatus::Fail);
        let issues: Vec<_> = report
            .issues()
            .iter()
            .filter(|i| i.message.contains("file name too long"))
            .collect();
        assert_eq!(issues.len(), 2);
        assert!(
            issues
                .iter()
                .all(|i| { i.severity == crate::IssueSeverity::High && i.entry_path.is_none() })
        );
        assert!(issues[0].message.contains("entry 1"));
        assert!(
            issues[1]
                .message
                .contains(&format!("{} bytes", HOST_PATH_LIMIT * 3))
        );
    }

    #[test]
    fn test_list_sevenz_entry_path_limit() {
        let over = path_of_len(HOST_PATH_LIMIT + 1);
        let data = make_sevenz_archive(&[(&over, b"x"), ("last.txt", b"x")]);
        let mut file = NamedTempFile::with_suffix(".7z").unwrap();
        file.write_all(&data).unwrap();
        file.flush().unwrap();

        assert_name_too_long(&list_archive(file.path(), &SecurityConfig::default()));

        let manifest = list_preflight(file.path(), SecurityConfig::default()).unwrap();
        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.oversized_entries().len(), 1);
    }

    #[cfg(not(windows))]
    #[test]
    fn test_list_tar_pax_path_of_5000_bytes_errors() {
        let file = tar_with_paths(&[&path_of_len(5000)]);
        assert_name_too_long(&list_archive(file.path(), &SecurityConfig::default()));

        let manifest = list_preflight(file.path(), SecurityConfig::default()).unwrap();
        assert_eq!(manifest.total_entries(), 0);
        assert_eq!(
            manifest.oversized_entries(),
            &[OversizedEntry::new(0, 5000)]
        );
    }

    #[test]
    fn test_list_zip_name_of_65535_bytes_errors() {
        let mut file = NamedTempFile::with_suffix(".zip").unwrap();
        file.write_all(&create_raw_zip_entry(&path_of_len(65535), b""))
            .unwrap();
        file.flush().unwrap();
        assert_name_too_long(&list_archive(file.path(), &SecurityConfig::default()));

        let manifest = list_preflight(file.path(), SecurityConfig::default()).unwrap();
        assert_eq!(manifest.total_entries(), 0);
        assert_eq!(
            manifest.oversized_entries(),
            &[OversizedEntry::new(0, 65535)]
        );
    }

    #[test]
    fn test_verify_caps_oversized_entry_issues() {
        let over = path_of_len(HOST_PATH_LIMIT + 1);
        let paths = vec![over.as_str(); 20];
        let file = tar_with_paths(&paths);

        let report = crate::verify_archive(file.path(), &SecurityConfig::default()).unwrap();

        let issues: Vec<_> = report
            .issues()
            .iter()
            .filter(|i| i.message.contains("file name too long"))
            .collect();
        assert_eq!(issues.len(), 17);
        assert!(issues[16].message.contains("4 more entries"));
    }

    #[test]
    fn test_list_tar_verify_preflight_allows_nul_byte_path() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_pax_nul_path(b"foo\0bar.txt", b"hello"))
            .unwrap();
        temp_file.flush().unwrap();

        let manifest = list_preflight(temp_file.path(), SecurityConfig::default())
            .expect("the pre-flight must let a NUL-byte entry path through");

        assert_eq!(manifest.total_entries(), 1);
        assert!(
            has_null_bytes(&manifest.entries()[0].path),
            "the raw NUL-byte path must reach the manifest unmodified"
        );
    }

    #[test]
    fn test_list_tar_verify_preflight_allows_missing_link_target() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let mut header = tar::Header::new_gnu();
        header.set_path("link").unwrap();
        header.set_size(0);
        header.set_entry_type(tar::EntryType::Symlink);
        header.set_cksum();
        builder.append(&header, &[][..]).unwrap();

        let data = builder.into_inner().unwrap();
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        let manifest = list_preflight(temp_file.path(), SecurityConfig::default())
            .expect("the pre-flight must let a missing symlink target through");

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.entries()[0].kind.symlink_target(), None);
    }

    #[test]
    fn test_list_tar_verify_preflight_allows_nul_byte_link_target() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_pax_linkpath(b"foo\0bar", b'2'))
            .unwrap();
        temp_file.flush().unwrap();

        let manifest = list_preflight(temp_file.path(), SecurityConfig::default())
            .expect("the pre-flight must let a NUL-byte symlink target through");

        assert_eq!(manifest.total_entries(), 1);
        assert!(
            manifest.entries()[0]
                .kind
                .symlink_target()
                .is_some_and(has_null_bytes),
            "the raw NUL-byte target must reach the manifest unmodified"
        );
    }

    #[test]
    fn test_list_zip_verify_preflight_allows_nul_byte_path() {
        let zip_bytes = create_raw_zip_entry("foo\0bar.txt", b"");
        let mut archive = ZipArchive::new(std::io::Cursor::new(zip_bytes)).unwrap();
        let config = SecurityConfig::default()
            .with_allow_absolute_paths(true)
            .validate()
            .unwrap();
        let manifest = list_zip_reader(&mut archive, &config, &mut ListPass::VerifyPreflight(None))
            .expect("the pre-flight must let a NUL-byte ZIP entry path through");

        assert_eq!(manifest.total_entries(), 1);
        assert!(
            has_null_bytes(&manifest.entries()[0].path),
            "the raw NUL-byte path must reach the manifest unmodified"
        );
    }

    // --- Regression tests for #396: list_archive() must route through
    // QuotaTracker instead of reimplementing quota checks ---

    #[test]
    fn test_list_tar_quota_exceeded_file_size() {
        // Previously list_tar_entries never checked max_file_size per entry —
        // only max_file_count/max_total_size. A single oversized entry must now
        // be rejected even when total size and file count are within limits.
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let data = vec![0u8; 1000];
        let mut header = tar::Header::new_gnu();
        header.set_path("big.bin").unwrap();
        header.set_size(data.len() as u64);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();

        let archive_data = builder.into_inner().unwrap();
        temp_file.write_all(&archive_data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_max_file_size(500);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::FileSize {
                    size: 1000,
                    max: 500
                }
            }),
            "expected FileSize quota error, got: {result:?}"
        );
    }

    #[test]
    fn test_list_zip_quota_exceeded_file_size() {
        let temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        let file = std::fs::File::create(temp_file.path()).unwrap();
        let mut zip = zip::ZipWriter::new(file);
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        zip.start_file("big.bin", options).unwrap();
        zip.write_all(&vec![0u8; 1000]).unwrap();
        zip.finish().unwrap();

        let config = SecurityConfig::default().with_max_file_size(500);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::FileSize {
                    size: 1000,
                    max: 500
                }
            }),
            "expected FileSize quota error, got: {result:?}"
        );
    }

    #[test]
    fn test_list_sevenz_quota_exceeded_file_size() {
        let data = vec![0u8; 1000];
        let archive_bytes = make_sevenz_archive(&[("big.bin", &data)]);
        let mut temp_file = NamedTempFile::with_suffix(".7z").unwrap();
        temp_file.write_all(&archive_bytes).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default().with_max_file_size(500);
        let result = list_archive(temp_file.path(), &config);
        assert_matches!(
            result,
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::FileSize {
                    size: 1000,
                    max: 500
                }
            }),
            "expected FileSize quota error, got: {result:?}"
        );
    }

    /// Builds a raw ZIP archive whose central directory declares entry sizes
    /// via the ZIP64 extended-information extra field (id `0x0001`),
    /// independent of the actual (empty) local file data. This lets tests
    /// exercise declared sizes that would be implausible to back with real
    /// bytes (e.g. near `u64::MAX`), which is exactly what `QuotaTracker`'s
    /// checked arithmetic must guard against.
    fn zip_with_zip64_declared_sizes(entries: &[(&str, u64)]) -> Vec<u8> {
        let raw = entries
            .iter()
            .map(|(name, declared)| {
                let mut zip64 = declared.to_le_bytes().to_vec();
                zip64.extend_from_slice(&0u64.to_le_bytes());
                RawEntry {
                    date: 0,
                    crc: 0,
                    size: u64::from(u32::MAX),
                    declared_compressed: Some(u64::from(u32::MAX)),
                    local_sizes: Some((0, 0)),
                    made_by: 0x032d,
                    central_version: 45,
                    external_attributes: 0,
                    central_extra: extra_field(1, &zip64),
                    data: Vec::new(),
                    ..RawEntry::stored(name, b"")
                }
            })
            .collect();
        RawZip::new(raw).build().bytes
    }

    #[test]
    fn test_list_zip_total_size_overflow_rejected_not_wrapped() {
        // Two entries whose declared sizes sum past u64::MAX. With unchecked
        // addition (the pre-fix behaviour) `total_size` would silently wrap
        // and bypass max_total_size entirely. QuotaTracker's checked_add must
        // reject this with IntegerOverflow instead.
        use std::io::Cursor;

        let zip_bytes = zip_with_zip64_declared_sizes(&[("a.bin", u64::MAX - 100), ("b.bin", 200)]);
        let mut archive = ZipArchive::new(Cursor::new(zip_bytes)).unwrap();

        let config = SecurityConfig::default()
            .with_max_file_size(u64::MAX)
            .with_max_file_count(usize::MAX)
            .with_max_total_size(u64::MAX)
            .validate()
            .expect("valid config");
        let result = list_zip_reader(&mut archive, &config, &mut ListPass::strict());
        assert_matches!(
            result,
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::IntegerOverflow
            }),
            "expected IntegerOverflow quota error instead of a silently wrapped total, got: {result:?}"
        );
    }

    fn oversized_hardlink_tar(count: usize) -> Vec<u8> {
        let one = tar_with_pax_linkpath(&vec![b'a'; 100_000], b'1');
        let entry = &one[..one.len() - 1024];
        let mut tar = entry.repeat(count);
        tar.extend(std::iter::repeat_n(0u8, 1024));
        tar
    }

    #[test]
    fn test_list_tar_oversized_link_target_rejected() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file.write_all(&oversized_hardlink_tar(1)).unwrap();
        temp_file.flush().unwrap();

        let result = list_archive(temp_file.path(), &SecurityConfig::default());
        assert_matches!(
            result,
            Err(ArchiveError::InvalidArchive(msg)) if msg == "hardlink target too long: 100000 bytes"
        );
    }

    #[test]
    fn test_list_tar_preflight_keeps_only_the_length_of_oversized_targets() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file.write_all(&oversized_hardlink_tar(3)).unwrap();
        temp_file.flush().unwrap();

        let manifest = list_preflight(temp_file.path(), SecurityConfig::default()).unwrap();

        assert_eq!(manifest.total_entries(), 3);
        for entry in manifest.entries() {
            assert_matches!(
                &entry.kind,
                ManifestEntryKind::Hardlink {
                    target: LinkTarget::Oversized { bytes: 100_000 }
                }
            );
        }
    }

    fn tar_with_sizes(sizes: &[usize]) -> NamedTempFile {
        let mut builder = tar::Builder::new(Vec::new());
        for (i, size) in sizes.iter().enumerate() {
            let mut header = tar::Header::new_gnu();
            header.set_size(*size as u64);
            header.set_cksum();
            builder
                .append_data(&mut header, format!("f{i}.bin"), &vec![0u8; *size][..])
                .unwrap();
        }
        let mut file = NamedTempFile::with_suffix(".tar").unwrap();
        file.write_all(&builder.into_inner().unwrap()).unwrap();
        file.flush().unwrap();
        file
    }

    #[test]
    fn test_list_preflight_lifts_only_file_size_limit() {
        let file = tar_with_sizes(&[100, 10]);
        let config = SecurityConfig::default().with_max_file_size(50);

        assert_matches!(
            list_archive(file.path(), &config),
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::FileSize { size: 100, max: 50 }
            })
        );
        let manifest = list_preflight(file.path(), config.clone()).unwrap();
        assert_eq!(manifest.total_entries(), 2);

        assert_matches!(
            list_preflight(file.path(), config.clone().with_max_file_count(1)),
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::FileCount { current: 2, max: 1 }
            })
        );
        assert_matches!(
            list_preflight(file.path(), config.with_max_total_size(105)),
            Err(ArchiveError::QuotaExceeded {
                resource: QuotaResource::TotalSize {
                    current: 110,
                    max: 105
                }
            })
        );
    }

    fn assert_verify_reports_oversized_file(path: &Path) {
        let config = SecurityConfig::default().with_max_file_size(500);
        let report = crate::verify_archive(path, &config)
            .expect("verify must report an oversized entry, not error out");

        assert_eq!(report.status(), crate::VerificationStatus::Fail);
        assert!(
            report.issues().iter().any(|i| {
                i.category == crate::IssueCategory::QuotaExceeded
                    && i.message.contains("single file size")
            }),
            "expected a FileSize issue, got: {:?}",
            report.issues()
        );
    }

    #[test]
    fn test_verify_zip_reports_oversized_entry_not_error() {
        let mut file = NamedTempFile::with_suffix(".zip").unwrap();
        let bytes = crate::test_utils::create_test_zip(vec![("big.bin", &[0u8; 1000])]);
        file.write_all(&bytes).unwrap();
        file.flush().unwrap();

        assert_verify_reports_oversized_file(file.path());
    }

    #[test]
    fn test_verify_sevenz_reports_oversized_entry_not_error() {
        let mut file = NamedTempFile::with_suffix(".7z").unwrap();
        file.write_all(&make_sevenz_archive(&[("big.bin", &[0u8; 1000])]))
            .unwrap();
        file.flush().unwrap();

        assert_verify_reports_oversized_file(file.path());
    }

    #[test]
    fn test_list_zip_oversized_symlink_target() {
        use crate::test_utils::HOST_SYMLINK_TARGET_BYTES;
        use crate::test_utils::create_zip_with_symlink;
        use std::io::Cursor;

        let zip_bytes = create_zip_with_symlink("link", &"a".repeat(HOST_SYMLINK_TARGET_BYTES + 1));

        let mut archive = ZipArchive::new(Cursor::new(zip_bytes.clone())).unwrap();
        let strict = SecurityConfig::default().validate().unwrap();
        assert_matches!(
            list_zip_reader(&mut archive, &strict, &mut ListPass::strict()),
            Err(ArchiveError::SecurityViolation { .. })
        );

        let mut archive = ZipArchive::new(Cursor::new(zip_bytes)).unwrap();
        let manifest =
            list_zip_reader(&mut archive, &strict, &mut ListPass::VerifyPreflight(None)).unwrap();
        assert_matches!(
            &manifest.entries()[0].kind,
            ManifestEntryKind::Symlink {
                target: LinkTarget::Oversized { bytes }
            } if *bytes == HOST_SYMLINK_TARGET_BYTES + 1
        );
    }

    #[test]
    fn test_list_zip_symlink_with_a_huge_declared_target_is_never_read() {
        use crate::raw_zip::RawEntry;
        use crate::raw_zip::RawZip;
        use crate::raw_zip::deflate_zeros;
        use std::io::Cursor;

        const DECLARED: u64 = 64 * 1024 * 1024;
        let mut link = RawEntry::stored("link", b"");
        link.data = deflate_zeros(DECLARED);
        link.method = 8;
        link.size = DECLARED;
        link.external_attributes = 0o120_777 << 16;
        let bytes = RawZip::new(vec![link]).build().bytes;

        let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap();
        let config = SecurityConfig::default().validate().unwrap();
        let manifest =
            list_zip_reader(&mut archive, &config, &mut ListPass::VerifyPreflight(None)).unwrap();
        assert_matches!(
            &manifest.entries()[0].kind,
            ManifestEntryKind::Symlink {
                target: LinkTarget::Oversized { bytes }
            } if *bytes == usize::try_from(DECLARED).unwrap()
        );
    }
}