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
//! Archive verification implementation.

use std::path::Path;

use crate::ArchiveError;
use crate::IntegrityCheck;
use crate::Result;
use crate::SecurityConfig;
use crate::VerificationOptions;
use crate::config::Validated;
use crate::formats::SevenZArchive;
use crate::formats::ZipArchive;
use crate::formats::detect::FormatFamily;
use crate::formats::detect::detect_format;
use crate::formats::traits::ArchiveFormat;
use crate::inspection::integrity::IntegrityOutcome;
use crate::inspection::integrity::IntegrityPass;
use crate::inspection::list::ListPass;
use crate::inspection::list::list_detected;
use crate::inspection::manifest::ArchiveEntry;
use crate::inspection::manifest::ArchiveManifest;
use crate::inspection::manifest::LinkTarget;
use crate::inspection::manifest::ManifestEntryKind;
use crate::inspection::manifest::ManifestEntryType;
use crate::inspection::manifest::OversizedEntry;
use crate::inspection::report::ArchiveStructure;
use crate::inspection::report::IntegrityScope;
use crate::inspection::report::IssueCategory;
use crate::inspection::report::IssueSeverity;
use crate::inspection::report::VerificationIssue;
use crate::inspection::report::VerificationReport;
use crate::security::fs_view::CollisionKind;
use crate::security::fs_view::Conflict;
use crate::security::fs_view::FsView;
use crate::security::fs_view::LinkKind;
use crate::security::fs_view::NameCollision;
use crate::security::fs_view::Node;
use crate::security::fs_view::Occupant;
use crate::security::fs_view::VirtualTree;
use crate::security::fs_view::check_link_target_length;
use crate::security::fs_view::check_name_lengths;
use crate::security::fs_view::name_too_long;
use crate::security::hardlink::HardlinkTracker;
use crate::security::hardlink::hardlink_target_missing;
use crate::security::permissions::sanitize_permissions;
use crate::security::quota::QuotaTracker;
use crate::security::zipbomb::validate_entry_compression;
use crate::types::DestDir;
use crate::types::SafePath;
use crate::types::SafeSymlink;
use crate::types::safe_symlink::require_symlinks_allowed;

/// Verifies an already-listed manifest against the security config.
///
/// Used by `ArchiveFormat::verify()` to avoid re-opening the archive.
/// Performs the same checks as `verify_archive` but starts from a manifest
/// produced by `ArchiveFormat::list()`.
///
/// Entries are validated against an in-memory [`VirtualTree`] of what
/// extraction would create, so nothing is written to disk. Hardlinks are
/// materialized after every other entry, so their path and target are
/// validated against the final tree.
pub(crate) fn verify_manifest(
    manifest: &ArchiveManifest,
    config: &SecurityConfig<Validated>,
    integrity: Option<IntegrityOutcome>,
) -> Result<VerificationReport> {
    verify_manifest_with_structure(
        manifest,
        config,
        &ArchiveStructure::of_manifest(manifest),
        integrity,
    )
}

/// Like [`verify_manifest`], for a format that also reports structural
/// findings and a record count of its own.
pub(crate) fn verify_manifest_with_structure(
    manifest: &ArchiveManifest,
    config: &SecurityConfig<Validated>,
    structure: &ArchiveStructure<'_>,
    integrity: Option<IntegrityOutcome>,
) -> Result<VerificationReport> {
    verify_with_tree(manifest, config, structure, integrity, VirtualTree::new)
}

/// Verifies against a tree built by `make_tree`, which lets tests choose how
/// names are folded instead of taking the host's rule.
fn verify_with_tree(
    manifest: &ArchiveManifest,
    config: &SecurityConfig<Validated>,
    structure: &ArchiveStructure<'_>,
    integrity: Option<IntegrityOutcome>,
    make_tree: impl FnOnce(&Path) -> VirtualTree,
) -> Result<VerificationReport> {
    let temp_dir = tempfile::TempDir::new()?;
    let temp_dest = DestDir::new(temp_dir.path())?;

    let mut tree = make_tree(temp_dest.as_path());
    let mut quota_tracker = QuotaTracker::new();
    let mut hardlink_tracker = HardlinkTracker::new();

    let mut lists = Vec::with_capacity(manifest.entries().len());
    let mut deferred = Vec::new();
    for (index, entry) in manifest.entries().iter().enumerate() {
        let outcome = verify_entry(
            entry,
            config,
            &temp_dest,
            &mut tree,
            &mut quota_tracker,
            &mut hardlink_tracker,
        );
        if outcome.hardlink_pending {
            deferred.push(index);
        }
        let mut issues = outcome.issues;
        issues.extend(check_heuristics(entry));
        lists.push(issues);
    }

    for index in deferred {
        let entry = &manifest.entries()[index];
        let materialized =
            verify_deferred_hardlink(entry, config, &temp_dest, &mut tree, &mut hardlink_tracker);
        lists[index].extend(collision_issues(&mut tree));
        if let Err(issue) = materialized {
            lists[index].push(issue);
        }
    }

    let mut archive_issues = structure.refusals().to_vec();
    archive_issues.extend(oversized_entry_issues(manifest.oversized_entries()));
    archive_issues.extend(unread_targets_issue(manifest, config));
    let scope = match integrity {
        Some(outcome) => {
            debug_assert_eq!(outcome.entry_issues.len(), lists.len());
            for (list, extra) in lists.iter_mut().zip(outcome.entry_issues) {
                list.extend(extra);
            }
            archive_issues.extend(outcome.archive_issues);
            IntegrityScope::Requested(outcome.gaps)
        }
        None => IntegrityScope::NotRequested,
    };

    lists.extend(
        tree.take_empty_merges()
            .into_iter()
            .map(|collision| vec![collision_issue(collision)]),
    );

    Ok(VerificationReport::from_entry_issue_lists(
        manifest,
        lists,
        archive_issues,
        structure,
        scope,
    ))
}

/// A manifest listed for verification, with the integrity pass outcome when
/// one was requested.
pub(crate) struct ListedForVerify {
    pub(crate) manifest: ArchiveManifest,
    pub(crate) integrity: Option<IntegrityOutcome>,
}

/// Runs `list` as the verify pre-flight, decoding payloads when `options`
/// asks for it.
///
/// `list` is the only format-specific part of verification, so
/// `verify_archive` and every `ArchiveFormat::verify` share the rest.
pub(crate) fn list_for_verify<F>(
    config: &SecurityConfig<Validated>,
    options: VerificationOptions,
    list: F,
) -> Result<ListedForVerify>
where
    F: FnOnce(&mut ListPass<'_, '_>) -> Result<ArchiveManifest>,
{
    match options.integrity {
        IntegrityCheck::Skip => Ok(ListedForVerify {
            manifest: list(&mut ListPass::VerifyPreflight(None))?,
            integrity: None,
        }),
        IntegrityCheck::DecodeToEof(budget) => {
            let mut pass = IntegrityPass::new(config, budget);
            let manifest = list(&mut ListPass::VerifyPreflight(Some(&mut pass)))?;
            Ok(ListedForVerify {
                manifest,
                integrity: Some(pass.finish()),
            })
        }
    }
}

/// Lists with `list` and verifies the manifest, for formats whose manifest is
/// their whole content.
pub(crate) fn verify_with<F>(
    config: &SecurityConfig<Validated>,
    options: VerificationOptions,
    list: F,
) -> Result<VerificationReport>
where
    F: FnOnce(&mut ListPass<'_, '_>) -> Result<ArchiveManifest>,
{
    let listed = list_for_verify(config, options, list)?;
    verify_manifest(&listed.manifest, config, listed.integrity)
}

/// Verifies archive security without extracting.
///
/// Performs metadata-only validation:
/// - Security checks (path traversal, zip bombs, CVEs)
/// - Policy checks (file types, permissions)
///
/// Payload integrity (checksums, decode-to-end) is not verified: the report's
/// `integrity_status` is
/// [`IntegrityStatus::Skipped`](crate::IntegrityStatus::Skipped).
/// Use [`verify_archive_with_options`] to request it.
///
/// # Arguments
///
/// * `archive_path` - Path to archive file
/// * `config` - Security configuration for validation
///
/// # Errors
///
/// Returns error if:
/// - Archive file cannot be opened
/// - Archive is severely corrupted (cannot read structure)
/// - Declared compressed sizes exceed the archive length
/// - A ZIP central directory holds more records than `max_file_count`, counting
///   records the `zip` crate collapses or the end record does not count
/// - An entry name is a path traversal (`..` component, or an absolute path
///   unless `allowed.absolute_paths` is set): the listing step rejects it with
///   [`ArchiveError::PathTraversal`] before a report exists
///
/// The targets of 7z symlinks are stored in compressed entry data, so they are
/// validated only when an integrity check decodes the archive. Without one,
/// each such target stays unread and the report carries a single Medium issue
/// counting them (status at least `WARNING`); entries that would land beneath
/// an unread link are still reported. With an integrity check whose budget
/// cannot cover a link, the target stays unread in the same way.
///
/// Other security violations are reported in `VerificationReport::issues`
/// instead: disallowed links, link targets that escape the destination,
/// hardlinks whose target never appears, quota and compression-ratio
/// violations, NUL bytes, banned components, unsafe permissions and, for ZIP
/// under `zip_consistency = Enforce`, headers that disagree with the central
/// directory, duplicate names, overlapping entries and hidden records or
/// headers. The report's total is the ZIP's raw central directory count.
///
/// # Limitations
///
/// Verification models only the archive's own entries; it cannot account for
/// files, directories or links already present in the extraction destination,
/// so a PASS does not guarantee that extraction into a non-empty destination
/// succeeds. Symlink chains are cut off after a per-OS number of hops that
/// matches `std::fs::canonicalize` on macOS (33), glibc (40) and musl (39)
/// hosts; Windows (63) is unverified and other Unix hosts assume 32, where a
/// low guess can only give a false FAIL.
///
/// On macOS entry names are compared after NFD and a per-character case fold,
/// on Windows after the same fold without normalisation, and elsewhere
/// exactly. Two names that differ exactly but compare equal under that fold
/// are reported as a [`IssueCategory::NameCollision`] (High when the kinds
/// differ or a symlink is involved, Medium for two files or for directories
/// that hold entries, Low for two directories that hold none), so a merge is
/// never silent. The fold approximates the host
/// table, so a pair it merges that the host keeps apart is reported too.
/// Windows component checks (reserved names, `:`, trailing dot or space) run
/// only on Windows hosts.
///
/// Verification models extraction that skips an existing entry. With
/// overwrite semantics extraction keeps the last entry at a path, which
/// verification cannot model. A symlink entry over a path an earlier entry
/// created as a file is reported as a security finding, since overwriting
/// replaces the file and changes what the path resolves to. Where overwriting
/// fails closed and replaces nothing (a symlink over a symlink or directory,
/// a file over a directory or symlink, a hardlink over any earlier entry; a
/// symlink repeating an earlier symlink's target is not noted at all) the
/// entry is only noted as a Low [`IssueCategory::InvalidArchive`] issue, so the
/// status stays `PASS`.
///
/// Hardlinks are materialized after every other entry, so their path and
/// target are validated against the final tree.
///
/// # Limitations
///
/// Name lengths are checked on the entry's relative path. Extraction adds the
/// destination prefix, so a long destination can make extraction fail with
/// `File name too long` for an entry `verify` accepted.
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::VerificationStatus;
/// use exarch_core::verify_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let report = verify_archive("archive.tar.gz", &config)?;
///
/// if report.status() == VerificationStatus::Pass {
///     println!("Archive is safe to extract");
/// } else {
///     eprintln!("Security issues found:");
///     for issue in report.issues() {
///         eprintln!("  [{}] {}", issue.severity, issue.message);
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub fn verify_archive<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
) -> Result<VerificationReport> {
    verify_archive_with_options(archive_path, config, &VerificationOptions::default())
}

/// Verifies archive security, optionally checking payload integrity.
///
/// With [`IntegrityCheck::Skip`] this is [`verify_archive`]. With
/// [`IntegrityCheck::DecodeToEof`] the payload is decoded to the decoder's EOF
/// during listing, so codec framing and checksums are verified, and
/// `integrity_status` becomes `OK`, `FAILED` or `INCOMPLETE`.
///
/// # What a status means
///
/// | Format | Verified |
/// |---|---|
/// | ZIP | per-entry CRC-32 and exact declared size; entries are independent, so a corrupt entry does not stop the scan |
/// | TAR | header checksums and that every declared data byte is present; no payload checksum |
/// | tar.gz, tar.bz2, tar.xz, tar.zst | the above plus the codec's own framing and checksums (zstd only if the frame carries one) |
/// | 7z | per-entry CRC-32 where the archive stores one, else the block CRC |
///
/// `OK` means every payload byte was decoded and every checksum the format has
/// matched. Formats without payload checksums (plain TAR, 7z entries without
/// CRC, zstd frames without a content checksum) report the weaker guarantee
/// that the data was complete and decodable. "Decode to EOF" means the
/// decoder's EOF: every gzip member, bzip2 stream and xz stream is decoded, and
/// a non-zero tail after the last one is an error.
///
/// `INCOMPLETE` means part of the payload was not verified (decompression
/// budget, a resource limit, a solid 7z archive while `allow_solid_archives`
/// is off, or a TAR stream without an end-of-archive marker). It comes with a
/// Medium issue, so the overall status is at least `WARNING`; exit code 0 does
/// not mean integrity `OK`.
///
/// # Errors
///
/// As [`verify_archive`]. With integrity requested, a TAR entry whose content
/// fails to decode, or whose data is cut short, is an
/// [`ArchiveError::InvalidArchive`]: the
/// scan cannot continue past it, and a report over the entries read so far
/// would let security look fine for entries never inspected. Corruption in a
/// TAR trailer (a gzip CRC, an xz index) is a `FAILED` report instead.
///
/// # Examples
///
/// ```no_run
/// use exarch_core::DecompressionBudget;
/// use exarch_core::IntegrityCheck;
/// use exarch_core::IntegrityStatus;
/// use exarch_core::SecurityConfig;
/// use exarch_core::VerificationOptions;
/// use exarch_core::verify_archive_with_options;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let options = VerificationOptions::default()
///     .with_integrity(IntegrityCheck::DecodeToEof(DecompressionBudget::DEFAULT));
/// let report = verify_archive_with_options("archive.zip", &SecurityConfig::default(), &options)?;
/// if report.integrity_status() == IntegrityStatus::Fail {
///     eprintln!("archive is corrupt");
/// }
/// # Ok(())
/// # }
/// ```
pub fn verify_archive_with_options<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
    options: &VerificationOptions,
) -> Result<VerificationReport> {
    let validated_config = config.clone().validate()?;
    let archive_path = archive_path.as_ref();
    let format = detect_format(archive_path)?;
    match format.family() {
        FormatFamily::Zip => {
            let file = std::fs::File::open(archive_path)?;
            return ZipArchive::new(file)?.verify(&validated_config, options);
        }
        FormatFamily::SevenZ => {
            let file = std::fs::File::open(archive_path)?;
            return SevenZArchive::new(file)?.verify(&validated_config, options);
        }
        FormatFamily::Tar(_) => {}
    }
    verify_with(&validated_config, *options, |listing| {
        list_detected(archive_path, format, &validated_config, listing)
    })
}

struct EntryOutcome {
    issues: Vec<VerificationIssue>,
    /// A hardlink that passed phase-one validation and awaits phase two.
    hardlink_pending: bool,
}

fn verify_entry(
    entry: &ArchiveEntry,
    config: &SecurityConfig<Validated>,
    dest: &DestDir,
    tree: &mut VirtualTree,
    quota_tracker: &mut QuotaTracker,
    hardlink_tracker: &mut HardlinkTracker,
) -> EntryOutcome {
    let mut issues = Vec::new();
    let mut hardlink_pending = false;

    // Path validation — result cached to avoid repeated syscalls for
    // symlink/hardlink checks
    let path_result = check_name_lengths(&entry.path)
        .map_err(ArchiveError::Io)
        .and_then(|()| SafePath::validate_in(&entry.path, dest, config, tree));
    if let Err(ref e) = path_result {
        issues.push(VerificationIssue::from_error(e, Some(entry.path.clone())));
    }

    // Quota validation using reserve (combines all checks)
    if let Err(e) = quota_tracker.reserve(entry.size, config) {
        issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
    }

    // Compression ratio validation (zip bomb detection)
    if let Err(e) = validate_entry_compression(&entry.compression, entry.size, config) {
        issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
    }

    if let Ok(ref safe_path) = path_result {
        let link_result = match &entry.kind {
            ManifestEntryKind::Symlink { target } => Some(
                // A target that is not read is never read when symlinks are
                // disallowed, so the policy is the reason to report.
                (if matches!(target, LinkTarget::Unread | LinkTarget::Unreadable) {
                    require_symlinks_allowed(config)
                } else {
                    Ok(())
                })
                .and_then(|()| match target {
                    // Counted once by `unread_targets_issue`; the tree keeps
                    // the link opaque.
                    LinkTarget::Unread => Ok(()),
                    _ => usable_link_target(target, ManifestEntryType::Symlink).and_then(|t| {
                        check_target_lengths(t, LinkKind::Symlink)?;
                        SafeSymlink::validate_in(safe_path, t, dest, config, tree).map(drop)
                    }),
                }),
            ),
            ManifestEntryKind::Hardlink { target } => Some(
                usable_link_target(target, ManifestEntryType::Hardlink).and_then(|t| {
                    check_target_lengths(t, LinkKind::Hardlink)?;
                    hardlink_tracker.validate_hardlink_in(safe_path, t, dest, config, tree)
                }),
            ),
            ManifestEntryKind::File | ManifestEntryKind::Directory => None,
        };
        match link_result {
            Some(Err(e)) => {
                issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
            }
            Some(Ok(())) if matches!(entry.kind, ManifestEntryKind::Hardlink { .. }) => {
                hardlink_pending = true;
            }
            _ => {
                let recorded = record_entry(tree, safe_path.as_path(), &entry.kind);
                issues.extend(collision_issues(tree));
                if let Err(conflict) = recorded {
                    issues.push(placement_issue(
                        tree,
                        dest,
                        entry,
                        safe_path.as_path(),
                        conflict,
                    ));
                }
            }
        }
    }

    // Extraction never applies a link entry's own recorded mode.
    if let Some(mode) = entry.mode
        && !entry.kind.is_link()
        && let Err(e) = check_permissions(&entry.path, mode, config)
    {
        issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
    }

    EntryOutcome {
        issues,
        hardlink_pending,
    }
}

/// Most over-long entries reported one by one; the rest are counted in a
/// closing issue so a hostile archive cannot inflate the report.
const OVERSIZED_ISSUE_CAP: usize = 16;

fn oversized_entry_issues(oversized: &[OversizedEntry]) -> Vec<VerificationIssue> {
    let name_too_long_issue = |detail: String| {
        let error = ArchiveError::Io(std::io::Error::new(
            name_too_long().kind(),
            format!("{}: {detail}", name_too_long()),
        ));
        VerificationIssue::from_error(&error, None)
    };
    let mut issues: Vec<_> = oversized
        .iter()
        .take(OVERSIZED_ISSUE_CAP)
        .map(|entry| {
            name_too_long_issue(format!(
                "entry {} has a path of {} bytes",
                entry.index, entry.bytes
            ))
        })
        .collect();
    let omitted = oversized.len().saturating_sub(OVERSIZED_ISSUE_CAP);
    if omitted > 0 {
        issues.push(name_too_long_issue(format!(
            "{omitted} more entries have over-long paths (first {OVERSIZED_ISSUE_CAP} listed)"
        )));
    }
    issues
}

fn check_target_lengths(target: &Path, kind: LinkKind) -> Result<()> {
    check_link_target_length(target, kind).map_err(ArchiveError::Io)
}

/// Returns the target to validate, or the error a missing or oversized
/// target is reported as.
fn usable_link_target(target: &LinkTarget, kind: ManifestEntryType) -> Result<&Path> {
    match target {
        LinkTarget::Recorded(path) => Ok(path),
        LinkTarget::Missing => Err(missing_link_target(kind)),
        LinkTarget::Unread => Err(unread_link_target(kind)),
        LinkTarget::Unreadable => Err(unreadable_link_target(kind)),
        LinkTarget::Oversized { .. } => Err(ArchiveError::Io(name_too_long())),
    }
}

/// Drains the name collisions the tree recorded since the last call into
/// report issues, so none is lost whichever insert produced it.
fn collision_issues(tree: &mut VirtualTree) -> Vec<VerificationIssue> {
    tree.take_collisions()
        .into_iter()
        .map(collision_issue)
        .collect()
}

/// Spells a path with combining marks and control characters escaped, so two
/// canonically equivalent names do not read as the same text.
fn escaped(path: &Path) -> String {
    path.to_string_lossy()
        .chars()
        .flat_map(char::escape_debug)
        .collect()
}

fn collision_issue(collision: NameCollision) -> VerificationIssue {
    let severity = match collision.kind {
        CollisionKind::Directories => IssueSeverity::Low,
        CollisionKind::DirectoriesWithContents | CollisionKind::Files => IssueSeverity::Medium,
        CollisionKind::Mixed => IssueSeverity::High,
    };
    VerificationIssue {
        severity,
        category: IssueCategory::NameCollision,
        message: format!(
            "Names \"{}\" and \"{}\" are the same name on case-insensitive or normalizing \
             filesystems",
            escaped(&collision.existing),
            escaped(&collision.incoming)
        ),
        entry_path: Some(collision.incoming),
        context: None,
    }
}

/// Records a successfully validated non-hardlink entry in the tree.
fn record_entry(
    tree: &mut VirtualTree,
    path: &Path,
    kind: &ManifestEntryKind,
) -> std::result::Result<(), Conflict> {
    let node = match kind {
        ManifestEntryKind::File => Node::File,
        ManifestEntryKind::Directory => Node::Dir,
        ManifestEntryKind::Symlink {
            target: LinkTarget::Recorded(t),
        } => Node::Symlink(t.clone()),
        ManifestEntryKind::Symlink {
            target: LinkTarget::Unread,
        } => Node::OpaqueSymlink,
        ManifestEntryKind::Symlink { .. } | ManifestEntryKind::Hardlink { .. } => {
            return Ok(());
        }
    };
    tree.try_insert(path, node)
}

/// Phase two for a hardlink: re-validates its link path and target against the
/// final tree, requires the target to exist, then materializes the link.
fn verify_deferred_hardlink(
    entry: &ArchiveEntry,
    config: &SecurityConfig<Validated>,
    dest: &DestDir,
    tree: &mut VirtualTree,
    hardlink_tracker: &mut HardlinkTracker,
) -> std::result::Result<(), VerificationIssue> {
    let ManifestEntryKind::Hardlink {
        target: LinkTarget::Recorded(target),
    } = &entry.kind
    else {
        return Ok(());
    };
    let issue = |e: ArchiveError| VerificationIssue::from_error(&e, Some(entry.path.clone()));
    let link_path = SafePath::validate_in(&entry.path, dest, config, tree).map_err(issue)?;
    hardlink_tracker
        .validate_hardlink_in(&link_path, target, dest, config, tree)
        .map_err(issue)?;
    let target_full = dest.as_path().join(target);
    if !tree.exists(&target_full) {
        return Err(issue(hardlink_target_missing(target)));
    }
    if tree.resolves_to_dir(&target_full) {
        return Err(issue(ArchiveError::InvalidArchive(format!(
            "hardlink target is a directory: {}",
            target.display()
        ))));
    }
    // A file over a file is accepted by the tree, but a hardlink cannot
    // replace one: it is created exclusively.
    let occupant = tree.occupant(link_path.as_path());
    let conflict = match (tree.try_insert(link_path.as_path(), Node::File), occupant) {
        (Err(conflict), _) => conflict,
        (Ok(()), Some(occupant)) => Conflict::already_exists(occupant),
        (Ok(()), None) => return Ok(()),
    };
    Err(placement_issue(
        tree,
        dest,
        entry,
        link_path.as_path(),
        conflict,
    ))
}

/// What extraction does at a path an earlier entry already holds.
enum Placement {
    /// Fails with every option set, or the failure is in the parent chain.
    FailsAlways,
    /// Skipped by default, but overwriting replaces a file with a symlink and
    /// changes what the path resolves to.
    ReplacesUnderOverwrite,
    /// Skipped by default; overwriting fails closed and replaces nothing.
    RefusedUnderOverwrite(Occupant),
}

impl Placement {
    fn of(kind: &ManifestEntryKind, conflict: &Conflict) -> Self {
        match (kind, conflict.occupant) {
            (ManifestEntryKind::Directory, _) | (_, None) => Self::FailsAlways,
            (ManifestEntryKind::Symlink { .. }, Some(Occupant::File)) => {
                Self::ReplacesUnderOverwrite
            }
            (_, Some(occupant)) => Self::RefusedUnderOverwrite(occupant),
        }
    }
}

/// Reports a failed tree insert. A failure that involves a link (the entry is
/// one, or the path crosses or lands on one) depends on how extraction
/// resolves the link, so it is a security finding; any other failure is a
/// structural problem of the archive. A failure that only overwriting causes,
/// and that replaces nothing, is a Low note: default extraction skips the
/// entry.
fn placement_issue(
    tree: &VirtualTree,
    dest: &DestDir,
    entry: &ArchiveEntry,
    rel: &Path,
    conflict: Conflict,
) -> VerificationIssue {
    let kind = &entry.kind;
    let entry_path = Some(entry.path.clone());
    let error = match Placement::of(kind, &conflict) {
        Placement::RefusedUnderOverwrite(occupant) => {
            let mut issue = VerificationIssue::new(
                IssueSeverity::Low,
                IssueCategory::InvalidArchive,
                format!(
                    "extraction with overwrite fails at {}: an earlier entry is a {} (default \
                     extraction skips this entry)",
                    rel.display(),
                    occupant.noun()
                ),
            );
            issue.entry_path = entry_path;
            return issue;
        }
        Placement::ReplacesUnderOverwrite => ArchiveError::violation(format!(
            "extraction can fail at {} unless duplicates are skipped: {}",
            rel.display(),
            conflict.error
        )),
        Placement::FailsAlways => {
            let crosses_link = || {
                rel.ancestors()
                    .take_while(|p| !p.is_empty())
                    .any(|p| tree.is_symlink(&dest.as_path().join(p)).unwrap_or(false))
            };
            if kind.is_link() || crosses_link() {
                ArchiveError::violation(format!(
                    "extraction fails at {}: {}",
                    rel.display(),
                    conflict.error
                ))
            } else {
                ArchiveError::Io(conflict.error)
            }
        }
    };
    VerificationIssue::from_error(&error, entry_path)
}

fn missing_link_target(kind: ManifestEntryType) -> ArchiveError {
    ArchiveError::violation(format!(
        "{} target is missing",
        kind.as_str().to_ascii_lowercase()
    ))
}

fn unread_link_target(kind: ManifestEntryType) -> ArchiveError {
    ArchiveError::violation(format!(
        "{} target was not read, so it cannot be validated",
        kind.as_str().to_ascii_lowercase()
    ))
}

fn unreadable_link_target(kind: ManifestEntryType) -> ArchiveError {
    ArchiveError::violation(format!(
        "{} target could not be read, so it cannot be validated",
        kind.as_str().to_ascii_lowercase()
    ))
}

/// The one issue for the symlinks whose targets were not read although
/// symlinks are allowed, which `verify_entry` could not validate.
fn unread_targets_issue(
    manifest: &ArchiveManifest,
    config: &SecurityConfig<Validated>,
) -> Option<VerificationIssue> {
    if !config.allowed.symlinks {
        return None;
    }
    let unread = manifest
        .entries()
        .iter()
        .filter(|entry| {
            matches!(
                entry.kind,
                ManifestEntryKind::Symlink {
                    target: LinkTarget::Unread
                }
            )
        })
        .count();
    let (subject, validated) = match unread {
        0 => return None,
        1 => ("symlink target was", "it was"),
        _ => ("symlink targets were", "they were"),
    };
    Some(VerificationIssue::new(
        IssueSeverity::Medium,
        IssueCategory::SecurityPolicy,
        format!(
            "{unread} {subject} not read, so {validated} not validated; entries beneath or \
             through an unread link are reported as failures (an integrity check with a \
             decompression budget that covers the link blocks reads the targets)"
        ),
    ))
}

fn check_permissions(path: &Path, mode: u32, config: &SecurityConfig<Validated>) -> Result<()> {
    let sanitized = sanitize_permissions(mode, config);
    (sanitized.as_u32() == mode).ok_or_else(|| ArchiveError::InvalidPermissions {
        path: path.to_path_buf(),
        mode,
    })
}

fn check_heuristics(entry: &ArchiveEntry) -> Vec<VerificationIssue> {
    let mut issues = Vec::new();

    // Executable file detection
    if let Some(mode) = entry.mode
        && mode & 0o111 != 0
        && entry.kind == ManifestEntryKind::File
    {
        issues.push(VerificationIssue {
            severity: IssueSeverity::Low,
            category: IssueCategory::ExecutableFile,
            entry_path: Some(entry.path.clone()),
            message: format!("Executable file: {}", entry.path.display()),
            context: Some(format!("mode: {mode:#o}")),
        });
    }

    // Suspicious extension detection
    if is_suspicious_extension(&entry.path) {
        issues.push(VerificationIssue {
            severity: IssueSeverity::Info,
            category: IssueCategory::SuspiciousPath,
            entry_path: Some(entry.path.clone()),
            message: format!("Suspicious extension: {}", entry.path.display()),
            context: None,
        });
    }

    // Non-UTF8 name detection: TAR entry names are stored byte-exact, so a
    // name that isn't valid UTF-8 is a portability risk — it extracts fine
    // on filesystems that accept arbitrary byte-string names (e.g. Linux
    // ext4/xfs/btrfs) but can fail on ones that require valid UTF-8 (e.g.
    // APFS, NTFS). This check is host-agnostic by design: `verify` is also
    // used to vet archives before shipping them to a different host, so the
    // warning must not depend on which filesystem happens to be running it.
    if entry.path.to_str().is_none() {
        issues.push(VerificationIssue {
            severity: IssueSeverity::Medium,
            category: IssueCategory::SuspiciousPath,
            entry_path: Some(entry.path.clone()),
            message: format!(
                "Entry name is not valid UTF-8; extraction may fail on filesystems that require \
                 UTF-8 names (e.g. APFS, NTFS): {}",
                entry.path.display()
            ),
            context: None,
        });
    }

    issues
}

const SUSPICIOUS_EXTENSIONS: [&str; 5] = ["exe", "dll", "sh", "bat", "cmd"];

fn is_suspicious_extension(path: &Path) -> bool {
    path.extension().is_some_and(|ext| {
        SUSPICIOUS_EXTENSIONS
            .iter()
            .any(|s| ext.eq_ignore_ascii_case(s))
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::inspection::manifest::EntryCompression;
    use crate::inspection::report::CheckStatus;
    use crate::inspection::report::VerificationStatus;
    use crate::test_utils::tar_with_pax_nul_path;
    use std::assert_matches;
    use std::io::Write;
    use std::path::PathBuf;
    use tempfile::NamedTempFile;

    fn manifest_of(entries: Vec<(&str, ManifestEntryKind)>) -> ArchiveManifest {
        let mut manifest = ArchiveManifest::new(crate::formats::detect::ArchiveType::Tar);
        for (path, kind) in entries {
            manifest
                .add_entry(ArchiveEntry::new(PathBuf::from(path), kind, 0))
                .unwrap();
        }
        manifest
    }

    fn link_config() -> SecurityConfig<Validated> {
        SecurityConfig::default()
            .with_allow_symlinks(true)
            .with_allow_hardlinks(true)
            .validate()
            .unwrap()
    }

    fn symlink_to(target: &str) -> ManifestEntryKind {
        ManifestEntryKind::Symlink {
            target: LinkTarget::Recorded(PathBuf::from(target)),
        }
    }

    fn hardlink_to(target: &str) -> ManifestEntryKind {
        ManifestEntryKind::Hardlink {
            target: LinkTarget::Recorded(PathBuf::from(target)),
        }
    }

    fn assert_link_placement_finding(entries: Vec<(&str, ManifestEntryKind)>, expected: &str) {
        let report = verify_manifest(&manifest_of(entries), &link_config(), None).unwrap();
        assert_ne!(report.security_status(), CheckStatus::Pass);
        let issue = report
            .issues()
            .iter()
            .find(|i| i.category == IssueCategory::SecurityPolicy)
            .unwrap_or_else(|| panic!("no SecurityPolicy issue: {:?}", report.issues()));
        assert_eq!(issue.severity, IssueSeverity::High);
        assert!(issue.message.contains(expected), "{}", issue.message);
    }

    #[test]
    fn dangling_link_used_as_a_parent_fails_the_security_status() {
        assert_link_placement_finding(
            vec![("d", symlink_to("sub")), ("d/f", ManifestEntryKind::File)],
            "extraction fails at d/f:",
        );
    }

    fn assert_overwrite_note(entries: Vec<(&str, ManifestEntryKind)>, expected: &str) {
        let report = verify_manifest(&manifest_of(entries), &link_config(), None).unwrap();
        assert_eq!(report.security_status(), CheckStatus::Pass, "{report:?}");
        let note: Vec<_> = report
            .issues()
            .iter()
            .filter(|i| i.severity == IssueSeverity::Low)
            .collect();
        assert_eq!(note.len(), 1, "{:?}", report.issues());
        assert_eq!(note[0].category, IssueCategory::InvalidArchive);
        assert!(note[0].message.contains(expected), "{}", note[0].message);
    }

    #[test]
    fn symlink_over_an_implicit_dir_is_an_overwrite_note() {
        assert_overwrite_note(
            vec![
                ("sub", ManifestEntryKind::Directory),
                ("d/f", ManifestEntryKind::File),
                ("d", symlink_to("sub")),
            ],
            "extraction with overwrite fails at d: an earlier entry is a directory",
        );
    }

    #[test]
    fn symlink_over_a_symlink_is_an_overwrite_note() {
        assert_overwrite_note(
            vec![("d", symlink_to("sub")), ("d", symlink_to("other"))],
            "fails at d: an earlier entry is a symlink",
        );
    }

    #[test]
    fn symlink_repeating_the_same_target_is_not_noted() {
        let report = verify_manifest(
            &manifest_of(vec![("d", symlink_to("sub")), ("d", symlink_to("sub"))]),
            &link_config(),
            None,
        )
        .unwrap();
        assert_eq!(report.status(), VerificationStatus::Pass);
        assert!(report.issues().is_empty(), "{:?}", report.issues());
    }

    #[test]
    fn file_over_a_dir_or_symlink_is_an_overwrite_note() {
        assert_overwrite_note(
            vec![
                ("d/f", ManifestEntryKind::File),
                ("d", ManifestEntryKind::File),
            ],
            "fails at d: an earlier entry is a directory",
        );
        assert_overwrite_note(
            vec![("s", symlink_to("t")), ("s", ManifestEntryKind::File)],
            "fails at s: an earlier entry is a symlink",
        );
    }

    #[test]
    fn hardlink_over_any_earlier_entry_is_an_overwrite_note() {
        let target = ("t", ManifestEntryKind::File);
        for (earlier, noun) in [
            (ManifestEntryKind::File, "file"),
            (ManifestEntryKind::Directory, "directory"),
            (symlink_to("t"), "symlink"),
        ] {
            assert_overwrite_note(
                vec![target.clone(), ("h", earlier), ("h", hardlink_to("t"))],
                &format!("fails at h: an earlier entry is a {noun}"),
            );
        }
    }

    #[test]
    fn symlink_over_a_file_stays_a_security_finding() {
        assert_link_placement_finding(
            vec![("d", ManifestEntryKind::File), ("d", symlink_to("sub"))],
            "extraction can fail at d unless duplicates are skipped:",
        );
    }

    #[test]
    fn repointing_a_link_an_earlier_link_resolved_through_is_an_overwrite_note() {
        assert_overwrite_note(
            vec![
                ("sub", ManifestEntryKind::Directory),
                ("sub/deep", ManifestEntryKind::Directory),
                ("d", symlink_to("sub/deep")),
                ("e", symlink_to("d/../..")),
                ("d", symlink_to("sub")),
            ],
            "fails at d: an earlier entry is a symlink",
        );
    }

    #[test]
    fn hardlink_below_a_dangling_link_fails_the_security_status() {
        assert_link_placement_finding(
            vec![
                ("d", symlink_to("sub")),
                ("t", ManifestEntryKind::File),
                ("d/h", hardlink_to("t")),
            ],
            "extraction fails at d/h:",
        );
    }

    #[test]
    fn directory_over_a_file_is_not_a_security_finding() {
        let manifest = manifest_of(vec![
            ("a", ManifestEntryKind::File),
            ("a", ManifestEntryKind::Directory),
        ]);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        assert_eq!(report.security_status(), CheckStatus::Pass);
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::InvalidArchive)
        );
    }

    fn manifest_with_mode(path: &str, kind: ManifestEntryKind, mode: u32) -> ArchiveManifest {
        let mut manifest = ArchiveManifest::new(crate::formats::detect::ArchiveType::Tar);
        let mut entry = ArchiveEntry::new(PathBuf::from(path), kind, 0);
        entry.mode = Some(mode);
        manifest.add_entry(entry).unwrap();
        manifest
    }

    #[test]
    fn symlink_mode_is_not_a_permission_finding() {
        let manifest = manifest_with_mode("l", symlink_to("t"), 0o777);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        assert_eq!(report.status(), VerificationStatus::Pass);
        assert!(
            report
                .issues()
                .iter()
                .all(|i| i.category != IssueCategory::InvalidPermissions),
            "{:?}",
            report.issues()
        );
    }

    #[test]
    fn hardlink_mode_is_not_a_permission_finding() {
        let mut manifest = ArchiveManifest::new(crate::formats::detect::ArchiveType::Tar);
        manifest
            .add_entry(ArchiveEntry::new(
                PathBuf::from("t"),
                ManifestEntryKind::File,
                0,
            ))
            .unwrap();
        let mut link = ArchiveEntry::new(PathBuf::from("h"), hardlink_to("t"), 0);
        link.mode = Some(0o777);
        manifest.add_entry(link).unwrap();

        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        assert_eq!(report.status(), VerificationStatus::Pass);
        assert!(
            report
                .issues()
                .iter()
                .all(|i| i.category != IssueCategory::InvalidPermissions),
            "{:?}",
            report.issues()
        );
    }

    #[test]
    fn world_writable_regular_file_is_still_a_permission_finding() {
        let manifest = manifest_with_mode("f", ManifestEntryKind::File, 0o666);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::InvalidPermissions),
            "{:?}",
            report.issues()
        );
    }

    #[test]
    fn overlong_link_targets_are_reported_without_resolution() {
        let long = "a".repeat(1 << 20);
        let manifest = manifest_of(vec![
            ("s", symlink_to(&long)),
            ("t", ManifestEntryKind::File),
            ("h", hardlink_to(&long)),
        ]);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        let too_long = report
            .issues()
            .iter()
            .filter(|i| i.category == IssueCategory::InvalidArchive)
            .count();
        assert_eq!(too_long, 2, "{:?}", report.issues());
    }

    fn unread_symlink() -> ManifestEntryKind {
        ManifestEntryKind::Symlink {
            target: LinkTarget::Unread,
        }
    }

    #[test]
    fn unread_symlinks_warn_once_and_report_what_runs_through_them() {
        let alone = manifest_of(vec![("d", unread_symlink()), ("e", unread_symlink())]);
        let report = verify_manifest(&alone, &link_config(), None).unwrap();
        assert_eq!(report.status(), VerificationStatus::Warning);
        assert_eq!(report.issues().len(), 1, "{:?}", report.issues());

        for entries in [
            vec![("d", unread_symlink()), ("d/f", ManifestEntryKind::File)],
            vec![("d", unread_symlink()), ("l", symlink_to("d/x"))],
            vec![("d", unread_symlink()), ("l", symlink_to("d"))],
        ] {
            let manifest = manifest_of(entries);
            let report = verify_manifest(&manifest, &link_config(), None).unwrap();
            assert_eq!(report.status(), VerificationStatus::Fail, "{manifest:?}");
        }
    }

    #[test]
    fn unread_symlinks_are_a_policy_failure_when_symlinks_are_disallowed() {
        let manifest = manifest_of(vec![("d", unread_symlink())]);
        let config = SecurityConfig::default().validate().unwrap();
        let report = verify_manifest(&manifest, &config, None).unwrap();
        assert_eq!(report.status(), VerificationStatus::Fail);
        assert_eq!(report.issues().len(), 1, "{:?}", report.issues());
    }

    #[test]
    fn unreadable_symlinks_fail_without_a_warning_count() {
        let manifest = manifest_of(vec![(
            "d",
            ManifestEntryKind::Symlink {
                target: LinkTarget::Unreadable,
            },
        )]);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        assert_eq!(report.status(), VerificationStatus::Fail);
        assert_eq!(report.issues().len(), 1, "{:?}", report.issues());
        assert!(report.issues()[0].message.contains("could not be read"));
    }

    #[test]
    fn oversized_link_targets_from_the_preflight_are_reported() {
        let manifest = manifest_of(vec![
            (
                "s",
                ManifestEntryKind::Symlink {
                    target: LinkTarget::Oversized { bytes: 100_000 },
                },
            ),
            (
                "h",
                ManifestEntryKind::Hardlink {
                    target: LinkTarget::Oversized { bytes: 100_000 },
                },
            ),
        ]);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        let too_long = report
            .issues()
            .iter()
            .filter(|i| i.category == IssueCategory::InvalidArchive)
            .count();
        assert_eq!(too_long, 2, "{:?}", report.issues());
        assert_eq!(report.status(), VerificationStatus::Fail);
    }

    #[test]
    fn collision_severity_follows_the_kinds_involved() {
        let collision = |kind| NameCollision {
            existing: PathBuf::from("a"),
            incoming: PathBuf::from("A"),
            kind,
        };
        let severity = |kind| collision_issue(collision(kind)).severity;
        assert_eq!(severity(CollisionKind::Directories), IssueSeverity::Low);
        assert_eq!(
            severity(CollisionKind::DirectoriesWithContents),
            IssueSeverity::Medium
        );
        assert_eq!(severity(CollisionKind::Files), IssueSeverity::Medium);
        assert_eq!(severity(CollisionKind::Mixed), IssueSeverity::High);
    }

    fn ascii_upper(name: &std::ffi::OsStr) -> std::borrow::Cow<'_, std::ffi::OsStr> {
        std::borrow::Cow::Owned(name.to_string_lossy().to_ascii_uppercase().into())
    }

    /// Verifies as a host that compares names case-insensitively would.
    fn verify_folding(entries: Vec<(&str, ManifestEntryKind)>) -> VerificationReport {
        let manifest = manifest_of(entries);
        verify_with_tree(
            &manifest,
            &link_config(),
            &ArchiveStructure::of_manifest(&manifest),
            None,
            |root| VirtualTree::with_fold(root, ascii_upper),
        )
        .unwrap()
    }

    fn collisions(report: &VerificationReport) -> Vec<IssueSeverity> {
        report
            .issues()
            .iter()
            .filter(|i| i.category == IssueCategory::NameCollision)
            .map(|i| i.severity)
            .collect()
    }

    #[test]
    fn hardlink_over_differently_spelled_file_is_not_a_pass() {
        let report = verify_folding(vec![
            ("a.txt", ManifestEntryKind::File),
            ("A.txt", hardlink_to("a.txt")),
        ]);
        assert_ne!(report.status(), VerificationStatus::Pass);
        assert_eq!(collisions(&report), [IssueSeverity::Medium]);
    }

    #[test]
    fn symlink_over_differently_spelled_file_is_reported_as_mixed() {
        let report = verify_folding(vec![("a", ManifestEntryKind::File), ("A", symlink_to("x"))]);
        assert!(collisions(&report).contains(&IssueSeverity::High));
        assert_eq!(report.status(), VerificationStatus::Fail);
    }

    #[test]
    fn differently_spelled_files_and_directories_with_contents_are_reported() {
        let report = verify_folding(vec![
            ("Images/x", ManifestEntryKind::File),
            ("images/y", ManifestEntryKind::File),
            ("f", ManifestEntryKind::File),
            ("F", ManifestEntryKind::File),
        ]);
        assert_eq!(
            collisions(&report),
            [IssueSeverity::Medium, IssueSeverity::Medium]
        );
        assert_eq!(report.status(), VerificationStatus::Warning);
    }

    #[test]
    fn merged_directories_with_colliding_children_are_never_a_pass() {
        let entries: Vec<_> = (0..50)
            .flat_map(|i| {
                [
                    (format!("a/f{i}"), ManifestEntryKind::File),
                    (format!("A/f{i}"), ManifestEntryKind::File),
                ]
            })
            .collect();
        let manifest = manifest_of(
            entries
                .iter()
                .map(|(p, k)| (p.as_str(), k.clone()))
                .collect(),
        );
        let report = verify_with_tree(
            &manifest,
            &link_config(),
            &ArchiveStructure::of_manifest(&manifest),
            None,
            |root| VirtualTree::with_fold(root, ascii_upper),
        )
        .unwrap();
        assert_eq!(report.status(), VerificationStatus::Warning);
        assert_eq!(report.security_status(), crate::CheckStatus::Warning);
        assert_eq!(
            collisions(&report),
            [IssueSeverity::Medium],
            "reported once"
        );
    }

    #[test]
    fn merged_empty_directories_are_low_and_keep_security_ok() {
        let report = verify_folding(vec![
            ("Dir", ManifestEntryKind::Directory),
            ("dir", ManifestEntryKind::Directory),
        ]);
        assert_eq!(collisions(&report), [IssueSeverity::Low]);
        assert_eq!(report.status(), VerificationStatus::Pass);
        assert_eq!(report.security_status(), crate::CheckStatus::Pass);
    }

    #[test]
    fn empty_directory_merge_is_upgraded_when_an_entry_lands_in_it() {
        let report = verify_folding(vec![
            ("Dir", ManifestEntryKind::Directory),
            ("dir", ManifestEntryKind::Directory),
            ("Dir/f", ManifestEntryKind::File),
        ]);
        assert_eq!(collisions(&report), [IssueSeverity::Medium]);
        assert_eq!(report.status(), VerificationStatus::Warning);
    }

    #[test]
    fn phase_two_resolves_link_path_through_tree() {
        let manifest = manifest_of(vec![
            ("real", ManifestEntryKind::Directory),
            ("alias", symlink_to("real")),
            ("real/t", ManifestEntryKind::File),
            ("alias/h", hardlink_to("real/t")),
            ("again", hardlink_to("real/h")),
        ]);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        assert!(report.issues().is_empty(), "{:?}", report.issues());
    }

    #[test]
    fn phase_two_reports_absent_hardlink_target() {
        let manifest = manifest_of(vec![("h", hardlink_to("missing"))]);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        assert_eq!(report.status(), VerificationStatus::Fail);
        assert!(report.issues().iter().any(|i| {
            i.category == IssueCategory::InvalidArchive
                && i.message.contains("hardlink target does not exist")
        }));
    }

    #[test]
    fn phase_two_accepts_target_declared_later() {
        let manifest = manifest_of(vec![
            ("h", hardlink_to("later")),
            ("later", ManifestEntryKind::File),
        ]);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        assert!(report.issues().is_empty(), "{:?}", report.issues());
    }

    #[test]
    fn phase_one_failure_is_not_reported_again_in_phase_two() {
        let manifest = manifest_of(vec![
            ("t", ManifestEntryKind::File),
            ("h", hardlink_to("../outside")),
        ]);
        let report = verify_manifest(&manifest, &link_config(), None).unwrap();
        let escapes = report
            .issues()
            .iter()
            .filter(|i| i.category == IssueCategory::HardlinkEscape)
            .count();
        assert_eq!(escapes, 1);
    }

    #[test]
    fn test_is_suspicious_extension() {
        assert!(is_suspicious_extension(Path::new("file.exe")));
        assert!(is_suspicious_extension(Path::new("file.dll")));
        assert!(is_suspicious_extension(Path::new("file.sh")));
        assert!(is_suspicious_extension(Path::new("file.bat")));
        assert!(is_suspicious_extension(Path::new("FILE.EXE")));
        assert!(is_suspicious_extension(Path::new("run.Bat")));
        assert!(is_suspicious_extension(Path::new("x.CMD")));
        assert!(!is_suspicious_extension(Path::new("file.txt")));
        assert!(!is_suspicious_extension(Path::new("file.rs")));
    }

    #[test]
    fn test_check_heuristics_executable() {
        let entry = crate::inspection::manifest::ArchiveEntry {
            path: PathBuf::from("test.sh"),
            kind: ManifestEntryKind::File,
            size: 100,
            compression: EntryCompression::Unknown,
            mode: Some(0o755),
            modified: None,
        };

        let issues = check_heuristics(&entry);
        assert!(!issues.is_empty());
        assert!(
            issues
                .iter()
                .any(|i| i.category == IssueCategory::ExecutableFile)
        );
    }

    #[test]
    fn test_check_heuristics_suspicious_extension() {
        let entry = crate::inspection::manifest::ArchiveEntry {
            path: PathBuf::from("malware.exe"),
            kind: ManifestEntryKind::File,
            size: 100,
            compression: EntryCompression::Unknown,
            mode: Some(0o644),
            modified: None,
        };

        let issues = check_heuristics(&entry);
        assert!(!issues.is_empty());
        assert!(
            issues
                .iter()
                .any(|i| i.category == IssueCategory::SuspiciousPath)
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_check_heuristics_non_utf8_name() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        let entry = crate::inspection::manifest::ArchiveEntry {
            path: PathBuf::from(OsStr::from_bytes(b"weird-\xFF\xFE-name.txt")),
            kind: ManifestEntryKind::File,
            size: 100,
            compression: EntryCompression::Unknown,
            mode: Some(0o644),
            modified: None,
        };

        let issues = check_heuristics(&entry);
        assert!(!issues.is_empty());
        assert!(issues.iter().any(|i| {
            i.category == IssueCategory::SuspiciousPath && i.severity == IssueSeverity::Medium
        }));
    }

    // False-positive guard for #528: a plain, valid-UTF8, non-suspicious
    // entry name must not trigger the new non-UTF8-name heuristic.
    #[test]
    fn test_check_heuristics_valid_utf8_name_no_warning() {
        let entry = crate::inspection::manifest::ArchiveEntry {
            path: PathBuf::from("safe/file.txt"),
            kind: ManifestEntryKind::File,
            size: 100,
            compression: EntryCompression::Unknown,
            mode: Some(0o644),
            modified: None,
        };

        let issues = check_heuristics(&entry);
        assert!(
            issues.is_empty(),
            "valid UTF-8 name must not trigger any heuristic issue, got: {issues:?}"
        );
    }

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

        let data = b"safe file content";
        let mut header = tar::Header::new_gnu();
        header.set_path("safe/file.txt").unwrap();
        header.set_size(data.len() as u64);
        header.set_mode(0o644);
        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();
        let report = verify_archive(temp_file.path(), &config).unwrap();

        assert_eq!(
            report.status(),
            VerificationStatus::Pass,
            "Safe archive should pass verification"
        );
        assert_eq!(report.total_entries(), 1);
        assert_eq!(report.suspicious_entries(), 0);
        assert!(
            report.issues().is_empty(),
            "Safe archive should have no issues"
        );
    }

    #[test]
    fn xl_type_divergence_is_bound_to_its_manifest_entry() {
        use crate::raw_zip::RawEntry;
        use crate::raw_zip::RawZip;
        use crate::raw_zip::SYMLINK_MODE;
        use crate::raw_zip::XL_FIELD_ID;
        use crate::raw_zip::xl_unix_attributes;

        let built = RawZip::new(vec![
            RawEntry::stored("a.txt", b"../../../../tmp/pwned")
                .with_local_unix_host()
                .with_local_extra_field(XL_FIELD_ID, &xl_unix_attributes(SYMLINK_MODE)),
            RawEntry::stored("b.txt", b"plain b\n"),
        ])
        .build();
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&built.bytes).unwrap();
        temp_file.flush().unwrap();

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

        assert_eq!(report.suspicious_entries(), 1);
        let issue = report
            .issues()
            .iter()
            .find(|i| i.message.contains("xl extra field"))
            .unwrap();
        assert_eq!(issue.entry_path.as_deref(), Some(Path::new("a.txt")));
    }

    #[test]
    fn zip_finding_after_a_dropped_oversized_entry_names_its_own_entry() {
        use crate::raw_zip::RawEntry;
        use crate::raw_zip::RawZip;
        use crate::raw_zip::SYMLINK_MODE;
        use crate::raw_zip::XL_FIELD_ID;
        use crate::raw_zip::xl_unix_attributes;

        let long_name = "n".repeat(304);
        let built = RawZip::new(vec![
            RawEntry::stored(&long_name, b"long"),
            RawEntry::stored("a.txt", b"../../../../tmp/pwned")
                .with_local_unix_host()
                .with_local_extra_field(XL_FIELD_ID, &xl_unix_attributes(SYMLINK_MODE)),
            RawEntry::stored("b.txt", b"plain b\n"),
        ])
        .build();
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&built.bytes).unwrap();
        temp_file.flush().unwrap();

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

        let issue = report
            .issues()
            .iter()
            .find(|i| i.message.contains("xl extra field"))
            .unwrap();
        assert_eq!(issue.entry_path.as_deref(), Some(Path::new("a.txt")));
    }

    #[test]
    fn descriptor_overrun_is_bound_to_its_manifest_entry() {
        use crate::raw_zip::RawEntry;
        use crate::raw_zip::RawZip;

        let built = RawZip::new(vec![
            RawEntry::stored("p.txt", b"plain p\n"),
            RawEntry::stored("a.txt", b"stored a\n").with_descriptor(false, false),
            RawEntry::stored("b.txt", b"stored b\n"),
            RawEntry::stored("c.txt", b"stored c\n"),
        ])
        .build();
        let mut temp_file = NamedTempFile::with_suffix(".zip").unwrap();
        temp_file.write_all(&built.bytes).unwrap();
        temp_file.flush().unwrap();

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

        assert_eq!(report.suspicious_entries(), 1);
        let issue = report
            .issues()
            .iter()
            .find(|i| i.message.contains("data descriptor of entry 1"))
            .unwrap();
        assert_eq!(issue.entry_path.as_deref(), Some(Path::new("a.txt")));
    }

    // Regression test: verify_archive() must report an oversized entry as a
    // graceful VerificationIssue (Fail status with an itemized report), not
    // abort with a bare error during its internal pre-flight list_archive()
    // call. Before the pre-flight lifted the per-file limit, list_archive()
    // enforcing max_file_size (#396) made this scenario an Err with no
    // report, bypassing verify_entry's existing FileSize handling.
    #[test]
    fn test_verify_archive_oversized_entry_reports_issue_not_error() {
        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_mode(0o644);
        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 report = verify_archive(temp_file.path(), &config)
            .expect("verify_archive must report oversized entries, not error out");

        assert_eq!(
            report.status(),
            VerificationStatus::Fail,
            "oversized entry must fail verification via a report, not a hard error"
        );
        assert_eq!(report.suspicious_entries(), 1);
        assert!(
            report.issues().iter().any(|i| {
                i.severity == IssueSeverity::High
                    && i.category == IssueCategory::QuotaExceeded
                    && i.message.contains("single file size")
            }),
            "expected a High-severity QuotaExceeded FileSize issue, got: {:?}",
            report.issues()
        );
    }

    // #430: a NUL-byte entry path must surface as a VerificationIssue, not a
    // hard `Err` from the verify pre-flight listing.
    #[test]
    fn test_verify_archive_nul_byte_path_reports_issue_not_error() {
        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 report = verify_archive(temp_file.path(), &config)
            .expect("verify_archive must report a NUL-byte entry path, not error out");

        assert_eq!(
            report.status(),
            VerificationStatus::Fail,
            "NUL-byte entry path must fail verification via a report, not a hard error"
        );
        assert_eq!(report.suspicious_entries(), 1);
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.message.contains("null bytes")),
            "expected an issue mentioning null bytes, got: {:?}",
            report.issues()
        );
    }

    // Regression test for #528: a TAR entry name that is not valid UTF-8 is
    // stored byte-exact in the manifest and may fail to extract on this
    // filesystem, but previously nothing in the verification pipeline
    // checked for it, so `verify` reported `Pass` for an archive that
    // `extract` would later fail on.
    //
    // Unix-only: the `tar` crate's `bytes2path` requires valid UTF-8 on
    // non-Unix targets (see `tar::header::bytes2path`), so on Windows
    // `entry.path()` itself errors out during listing and `verify_archive`
    // returns `Err` before ever reaching `check_heuristics` — a different,
    // pre-existing cross-platform divergence outside this fix's scope.
    #[cfg(unix)]
    #[test]
    fn test_verify_archive_non_utf8_name_reports_warning_not_pass() {
        use crate::test_utils::tar_with_nonutf8_name;

        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        temp_file
            .write_all(&tar_with_nonutf8_name(b"weird-\xFF\xFE-name.txt", b"hello"))
            .unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let report = verify_archive(temp_file.path(), &config)
            .expect("verify_archive must report a non-UTF8 entry name, not error out");

        assert_eq!(
            report.status(),
            VerificationStatus::Warning,
            "non-UTF8 entry name must surface as a Warning, not silently Pass"
        );
        assert_eq!(
            report.suspicious_entries(),
            1,
            "a Medium+ heuristic issue must be reflected in suspicious_entries, \
             or the report is self-contradictory (Warning with 0 suspicious entries)"
        );
        assert!(
            report.issues().iter().any(|i| {
                i.category == IssueCategory::SuspiciousPath && i.message.contains("not valid UTF-8")
            }),
            "expected a SuspiciousPath issue mentioning UTF-8, got: {:?}",
            report.issues()
        );
    }

    // Regression test for #430 follow-up (round 3, item 2): a hardlink entry
    // with no link target at all must still surface as a graceful
    // VerificationIssue from verify_archive, not the InvalidArchive hard
    // error that bare `list_archive` now raises (see
    // `test_list_tar_hardlink_missing_target_rejected` in
    // `inspection::list::tests`). `ListPass::VerifyPreflight` lets the
    // missing target through the pre-flight listing pass as `None`;
    // `verify_entry` reports it as a SecurityPolicy issue.
    #[test]
    fn test_verify_archive_hardlink_missing_target_reports_issue_not_error() {
        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 archive_data = builder.into_inner().unwrap();
        temp_file.write_all(&archive_data).unwrap();
        temp_file.flush().unwrap();

        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;
        let report = verify_archive(temp_file.path(), &config)
            .expect("verify_archive must report a missing hardlink target, not error out");

        assert_eq!(
            report.status(),
            VerificationStatus::Fail,
            "missing hardlink target must fail verification via a report, not a hard error"
        );
        assert_eq!(report.suspicious_entries(), 1);
        assert!(
            report.issues().iter().any(|i| {
                i.category == IssueCategory::SecurityPolicy
                    && i.message.contains("hardlink target is missing")
            }),
            "expected a SecurityPolicy issue citing the missing target, got: {:?}",
            report.issues()
        );
    }

    fn link_tar(
        entry_type: tar::EntryType,
        names_and_targets: &[(&str, Option<&str>)],
    ) -> NamedTempFile {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());
        for (name, target) in names_and_targets {
            let mut header = tar::Header::new_gnu();
            header.set_path(name).unwrap();
            header.set_size(0);
            header.set_entry_type(entry_type);
            if let Some(target) = target {
                header.set_link_name(target).unwrap();
            }
            header.set_cksum();
            builder.append(&header, &[][..]).unwrap();
        }
        temp_file.write_all(&builder.into_inner().unwrap()).unwrap();
        temp_file.flush().unwrap();
        temp_file
    }

    fn hardlink_config(allowed: bool) -> SecurityConfig {
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = allowed;
        config
    }

    #[test]
    fn test_verify_hardlink_rejected_when_not_allowed() {
        let archive = link_tar(tar::EntryType::Link, &[("link", Some("target.txt"))]);
        let report = verify_archive(archive.path(), &hardlink_config(false)).unwrap();

        assert_eq!(report.status(), VerificationStatus::Fail);
        assert_eq!(report.security_status(), crate::CheckStatus::Fail);
        assert!(report.issues().iter().any(|i| {
            i.category == IssueCategory::SecurityPolicy
                && i.message.contains("hardlinks not allowed")
        }));
    }

    #[test]
    fn test_verify_hardlink_inside_dest_passes_when_allowed() {
        let archive = link_tar(tar::EntryType::Link, &[("link", Some("target.txt"))]);
        let report = verify_archive(archive.path(), &hardlink_config(true)).unwrap();

        assert!(
            !report.issues().iter().any(|i| i.category.is_security()),
            "got: {:?}",
            report.issues()
        );
    }

    #[test]
    fn test_verify_hardlink_duplicate_target_passes_when_allowed() {
        let archive = link_tar(
            tar::EntryType::Link,
            &[("a", Some("target.txt")), ("b", Some("target.txt"))],
        );
        let report = verify_archive(archive.path(), &hardlink_config(true)).unwrap();

        assert!(!report.issues().iter().any(|i| i.category.is_security()));
    }

    #[test]
    fn test_verify_hardlink_target_escaping_dest_flagged() {
        let archive = link_tar(tar::EntryType::Link, &[("link", Some("../outside.txt"))]);
        let report = verify_archive(archive.path(), &hardlink_config(true)).unwrap();

        assert_eq!(report.status(), VerificationStatus::Fail);
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::HardlinkEscape),
            "got: {:?}",
            report.issues()
        );
    }

    #[test]
    fn test_verify_hardlink_absolute_target_flagged() {
        let archive = link_tar(tar::EntryType::Link, &[("link", Some("/etc/passwd"))]);
        let report = verify_archive(archive.path(), &hardlink_config(true)).unwrap();

        assert_eq!(report.status(), VerificationStatus::Fail);
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::HardlinkEscape),
            "got: {:?}",
            report.issues()
        );
    }

    #[test]
    fn test_verify_symlink_missing_target_reports_policy_issue() {
        for allowed in [false, true] {
            let archive = link_tar(tar::EntryType::Symlink, &[("link", None)]);
            let mut config = SecurityConfig::default();
            config.allowed.symlinks = allowed;
            let report = verify_archive(archive.path(), &config).unwrap();

            assert_eq!(report.status(), VerificationStatus::Fail);
            assert!(
                report.issues().iter().any(|i| {
                    i.category == IssueCategory::SecurityPolicy
                        && i.message.contains("symlink target is missing")
                }),
                "allowed={allowed}, got: {:?}",
                report.issues()
            );
        }
    }

    // Note: Full CVE regression tests for path traversal require real malicious
    // archives that cannot be created using the tar crate (it validates paths).
    // Those tests should be added in crates/exarch-core/tests/security/ with
    // pre-built malicious fixtures. This test verifies the workflow works with
    // archives that tar crate accepts.

    #[test]
    fn test_verify_archive_symlink_escape() {
        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("evil_link").unwrap();
        header.set_size(0);
        header.set_mode(0o777);
        header.set_entry_type(tar::EntryType::Symlink);
        header.set_link_name("/etc/passwd").unwrap();
        header.set_cksum();
        builder.append(&header, &[][..]).unwrap();

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

        // Default config blocks ALL symlinks, so check that the issue is
        // detected
        let config = SecurityConfig::default();
        let report = verify_archive(temp_file.path(), &config).unwrap();

        assert_eq!(
            report.status(),
            VerificationStatus::Fail,
            "Symlink should fail verification with default config"
        );
        assert_eq!(report.total_entries(), 1);
        assert_eq!(report.suspicious_entries(), 1);
        assert!(!report.issues().is_empty(), "Should detect symlink");

        let has_symlink_issue = report.issues().iter().any(|i| {
            matches!(i.category, IssueCategory::SecurityPolicy) && i.message.contains("symlink")
        });

        assert!(
            has_symlink_issue,
            "Should have symlink-related issue, got: {:?}",
            report.issues()
        );
    }

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

        let data = b"fake binary";
        let mut header = tar::Header::new_gnu();
        header.set_path("bin/setuid_prog").unwrap();
        header.set_size(data.len() as u64);
        header.set_mode(0o4755);
        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();
        let report = verify_archive(temp_file.path(), &config).unwrap();

        assert!(
            !report.issues().is_empty(),
            "Should detect setuid permission issue"
        );
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::InvalidPermissions),
            "Should have InvalidPermissions issue for setuid"
        );
    }

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

        let data = b"#!/bin/bash\necho 'hello'";
        let mut header = tar::Header::new_gnu();
        header.set_path("script.sh").unwrap();
        header.set_size(data.len() as u64);
        header.set_mode(0o755);
        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();
        let report = verify_archive(temp_file.path(), &config).unwrap();

        assert!(!report.issues().is_empty(), "Should detect executable file");
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::ExecutableFile),
            "Should have ExecutableFile issue"
        );
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::SuspiciousPath),
            "Should have SuspiciousPath issue for .sh extension"
        );
        assert_eq!(
            report.suspicious_entries(),
            0,
            "Info/Low-severity heuristic issues (executable, suspicious extension) must not \
             count toward suspicious_entries — only Medium+ issues do"
        );
    }

    fn cloaked_zip_file() -> NamedTempFile {
        use crate::raw_zip::RawEntry;
        use crate::raw_zip::RawZip;

        let bytes = RawZip::new(vec![
            RawEntry::stored("cron_worker.sh", b"payload").with_central_name("doc_report.pdf"),
        ])
        .build()
        .bytes;
        let mut file = NamedTempFile::with_suffix(".zip").unwrap();
        file.write_all(&bytes).unwrap();
        file.flush().unwrap();
        file
    }

    #[test]
    fn verify_archive_fails_a_cloaked_zip_under_the_default_policy() {
        let file = cloaked_zip_file();
        let report = verify_archive(file.path(), &SecurityConfig::default()).unwrap();
        assert_eq!(report.status(), VerificationStatus::Fail);
        assert_eq!(report.security_status(), crate::CheckStatus::Fail);
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::HeaderMismatch)
        );
        assert_eq!(report.total_entries(), 1);
    }

    #[test]
    fn verify_archive_passes_a_cloaked_zip_when_ignored() {
        use crate::ZipConsistencyPolicy;

        let file = cloaked_zip_file();
        let config = SecurityConfig::default().with_zip_consistency(ZipConsistencyPolicy::Ignore);
        let report = verify_archive(file.path(), &config).unwrap();
        assert_eq!(report.status(), VerificationStatus::Pass);
    }

    #[test]
    fn permissive_config_enforces_zip_consistency_too() {
        let file = cloaked_zip_file();
        let report = verify_archive(file.path(), &SecurityConfig::permissive()).unwrap();
        assert_eq!(report.status(), VerificationStatus::Fail);
    }

    #[test]
    fn verify_archive_reports_an_oversized_zip_symlink_target() {
        use crate::test_utils::HOST_SYMLINK_TARGET_BYTES;
        use crate::test_utils::create_zip_with_symlink;

        let bytes = create_zip_with_symlink("link", &"a".repeat(HOST_SYMLINK_TARGET_BYTES + 1));
        let mut file = NamedTempFile::with_suffix(".zip").unwrap();
        file.write_all(&bytes).unwrap();
        file.flush().unwrap();

        let config = SecurityConfig::default().with_allow_symlinks(true);
        let report = verify_archive(file.path(), &config)
            .expect("an oversized target is a report issue, not an error");
        assert_eq!(report.status(), VerificationStatus::Fail);
        assert!(
            report
                .issues()
                .iter()
                .any(|i| i.category == IssueCategory::InvalidArchive
                    && i.message.contains("file name too long")),
            "{:?}",
            report.issues()
        );
    }

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