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
//! Verification report types for security checks.

use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;

use crate::closed_enum::closed_enum;
use crate::error::ArchiveError;
use crate::error::ZipInconsistency;
use crate::formats::detect::ArchiveType;
use crate::inspection::manifest::ArchiveEntry;
use crate::inspection::manifest::ArchiveManifest;

/// Result of archive verification.
///
/// Generated by `verify_archive()`, contains the result of the security checks
/// performed without extracting files to disk. Payload integrity is checked
/// only when requested through
/// [`VerificationOptions`](crate::VerificationOptions); otherwise
/// `integrity_status()` is [`IntegrityStatus::Skipped`]. Fields are private:
/// the overall, security and integrity statuses are derived from the issue
/// list, so a report can never contradict its own issues.
///
/// # 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(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct VerificationReport {
    issues: Vec<VerificationIssue>,
    integrity: IntegrityScope,
    total_entries: usize,
    suspicious_entries: usize,
    total_size: u64,
    format: ArchiveType,
}

impl VerificationReport {
    /// Builds a report by running `issues_for` over every manifest entry.
    ///
    /// Totals and format come from the manifest. An entry counts as
    /// suspicious when it has at least one issue of [`IssueSeverity::Medium`]
    /// or higher. `status() == Pass` holds exactly when no issue is Medium or
    /// higher. Issues are sorted from most to least severe.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// use exarch_core::ArchiveEntry;
    /// use exarch_core::ArchiveManifest;
    /// use exarch_core::ManifestEntryKind;
    /// use exarch_core::VerificationReport;
    /// use exarch_core::VerificationStatus;
    /// use exarch_core::formats::detect::ArchiveType;
    ///
    /// let mut manifest = ArchiveManifest::new(ArchiveType::Tar);
    /// let entry = ArchiveEntry::new(PathBuf::from("a.txt"), ManifestEntryKind::File, 1);
    /// manifest.add_entry(entry)?;
    ///
    /// let report = VerificationReport::from_entry_issues(&manifest, |_| Vec::new());
    /// assert_eq!(report.status(), VerificationStatus::Pass);
    /// assert_eq!(report.total_entries(), 1);
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    #[must_use]
    pub fn from_entry_issues<F>(manifest: &ArchiveManifest, issues_for: F) -> Self
    where
        F: FnMut(&ArchiveEntry) -> Vec<VerificationIssue>,
    {
        let lists = manifest.entries().iter().map(issues_for).collect();
        Self::from_entry_issue_lists(
            manifest,
            lists,
            Vec::new(),
            &ArchiveStructure::of_manifest(manifest),
            IntegrityScope::NotRequested,
        )
    }

    /// Builds a report from one precomputed issue list per manifest entry,
    /// issues that belong to the archive as a whole, and the structure of the
    /// archive the manifest came from.
    ///
    /// `lists` holds one list per manifest entry, optionally followed by
    /// lists of archive-level issues. A structural finding bound to an entry
    /// joins that entry's list, so an entry with several issues still counts
    /// once; any other finding is an archive-level list. Only entries count
    /// as suspicious, so `suspicious_entries()` never exceeds the manifest,
    /// while archive-level issues still decide `status()`.
    pub(crate) fn from_entry_issue_lists(
        manifest: &ArchiveManifest,
        mut lists: Vec<Vec<VerificationIssue>>,
        archive_issues: Vec<VerificationIssue>,
        structure: &ArchiveStructure<'_>,
        integrity: IntegrityScope,
    ) -> Self {
        for finding in structure.findings {
            let bound_entry = match finding {
                ZipInconsistency::HeaderMismatch { entry, .. }
                | ZipInconsistency::HeaderUncomparable { entry, .. }
                | ZipInconsistency::DescriptorOverrun { entry, .. }
                | ZipInconsistency::XlTypeDivergence { entry, .. } => {
                    manifest.position_of_zip_entry(*entry)
                }
                ZipInconsistency::DuplicateName { .. }
                | ZipInconsistency::OverlappingEntries
                | ZipInconsistency::HiddenLocalHeader { .. }
                | ZipInconsistency::IgnoredEndRecord { .. }
                | ZipInconsistency::StrayCentralRecord { .. }
                | ZipInconsistency::StrayEndRecord { .. }
                | ZipInconsistency::UncountedCentralRecords { .. } => None,
            };
            let mut issue = VerificationIssue::from_error(
                &ArchiveError::ZipInconsistency(finding.clone()),
                None,
            );
            match bound_entry {
                Some(position) => {
                    issue.entry_path = Some(manifest.entries()[position].path.clone());
                    lists[position].push(issue);
                }
                None => lists.push(vec![issue]),
            }
        }

        if structure.omitted > 0 {
            lists.push(vec![VerificationIssue::new(
                IssueSeverity::Info,
                IssueCategory::InvalidArchive,
                format!(
                    "{} further ZIP structure findings are not listed",
                    structure.omitted
                ),
            )]);
        }

        let mut issues = archive_issues;
        let mut suspicious_entries = 0;

        for (index, entry_issues) in lists.into_iter().enumerate() {
            if index < manifest.total_entries()
                && entry_issues
                    .iter()
                    .any(|i| i.severity >= IssueSeverity::Medium)
            {
                suspicious_entries += 1;
            }
            issues.extend(entry_issues);
        }

        issues.sort_by(|a, b| a.severity.cmp(&b.severity).reverse());

        Self {
            issues,
            integrity,
            total_entries: structure.total_entries,
            suspicious_entries,
            total_size: manifest.total_size(),
            format: manifest.format(),
        }
    }

    /// Returns the overall status, derived from the issue severities.
    #[must_use]
    pub fn status(&self) -> VerificationStatus {
        determine_status(&self.issues)
    }

    /// Returns the security check result, derived from security-category
    /// issues. A [`IssueCategory::NameCollision`] of Low severity (two
    /// directories without contents merging) is reported but not counted.
    #[must_use]
    pub fn security_status(&self) -> CheckStatus {
        determine_security_status(&self.issues)
    }

    /// Returns the integrity check result, derived from the issue list.
    ///
    /// Any [`IssueCategory::CorruptData`] issue gives
    /// [`IntegrityStatus::Fail`]. Otherwise a report built without an
    /// integrity request is [`IntegrityStatus::Skipped`], and a requested check
    /// with an [`IssueCategory::IntegrityIncomplete`] issue is
    /// [`IntegrityStatus::Incomplete`]: some payload was not verified. Only a
    /// requested check with neither is [`IntegrityStatus::Pass`], which for
    /// formats without payload checksums (plain TAR, 7z entries without CRC)
    /// means the data was decodable and complete, not checksum-verified.
    #[must_use]
    pub fn integrity_status(&self) -> IntegrityStatus {
        determine_integrity_status(&self.issues, &self.integrity)
    }

    /// What the requested integrity check left unverified, or `None` when no
    /// integrity check was requested.
    ///
    /// A requested check that verified everything returns an empty
    /// [`IntegrityGaps`].
    #[must_use]
    pub const fn integrity_gaps(&self) -> Option<&IntegrityGaps> {
        match &self.integrity {
            IntegrityScope::Requested(gaps) => Some(gaps),
            IntegrityScope::NotRequested => None,
        }
    }

    /// Returns all issues found, sorted from most to least severe.
    #[must_use]
    pub fn issues(&self) -> &[VerificationIssue] {
        &self.issues
    }

    /// Consumes the report and returns its issues.
    #[must_use]
    pub fn into_issues(self) -> Vec<VerificationIssue> {
        self.issues
    }

    /// Returns the total number of entries scanned.
    #[must_use]
    pub const fn total_entries(&self) -> usize {
        self.total_entries
    }

    /// Returns the number of entries with a Medium-or-higher issue. Issues
    /// that belong to the archive as a whole (a hidden ZIP header, a repeated
    /// name) are not entries and are not counted here, but they fail
    /// [`status`](Self::status).
    #[must_use]
    pub const fn suspicious_entries(&self) -> usize {
        self.suspicious_entries
    }

    /// Returns the total uncompressed size in bytes.
    #[must_use]
    pub const fn total_size(&self) -> u64 {
        self.total_size
    }

    /// Returns the archive format.
    #[must_use]
    pub const fn format(&self) -> ArchiveType {
        self.format
    }

    /// Returns true if the archive is safe (no Medium-or-higher severity
    /// issues).
    #[must_use]
    pub fn is_safe(&self) -> bool {
        self.status() == VerificationStatus::Pass
    }

    /// Returns true if there are any critical severity issues.
    #[must_use]
    pub fn has_critical_issues(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Critical)
    }

    /// Returns issues of a specific severity level.
    #[must_use]
    pub fn issues_by_severity(&self, severity: IssueSeverity) -> Vec<&VerificationIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == severity)
            .collect()
    }
}

/// What an archive's format reports about its own structure, beyond the
/// manifest of the entries it lists.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ArchiveStructure<'a> {
    total_entries: usize,
    findings: &'a [ZipInconsistency],
    omitted: usize,
    refusals: &'a [VerificationIssue],
}

impl<'a> ArchiveStructure<'a> {
    /// A structure with `total_entries` records and the findings to report.
    pub(crate) const fn new(
        total_entries: usize,
        findings: &'a [ZipInconsistency],
        omitted: usize,
    ) -> Self {
        Self {
            total_entries,
            findings,
            omitted,
            refusals: &[],
        }
    }

    /// Adds archive-level issues for what extraction refuses in the archive.
    pub(crate) const fn with_refusals(mut self, refusals: &'a [VerificationIssue]) -> Self {
        self.refusals = refusals;
        self
    }

    /// Archive-level issues for what extraction refuses in the archive.
    pub(crate) const fn refusals(&self) -> &'a [VerificationIssue] {
        self.refusals
    }

    /// The structure of a format whose manifest is its whole content.
    pub(crate) fn of_manifest(manifest: &ArchiveManifest) -> Self {
        Self::new(manifest.total_entries(), &[], 0)
    }
}

fn determine_status(issues: &[VerificationIssue]) -> VerificationStatus {
    let has_critical = issues.iter().any(|i| i.severity == IssueSeverity::Critical);
    let has_high = issues.iter().any(|i| i.severity == IssueSeverity::High);
    let has_medium = issues.iter().any(|i| i.severity == IssueSeverity::Medium);

    if has_critical || has_high {
        VerificationStatus::Fail
    } else if has_medium {
        VerificationStatus::Warning
    } else {
        VerificationStatus::Pass
    }
}

fn determine_integrity_status(
    issues: &[VerificationIssue],
    scope: &IntegrityScope,
) -> IntegrityStatus {
    let has = |category| issues.iter().any(|i| i.category == category);
    if has(IssueCategory::CorruptData) {
        IntegrityStatus::Fail
    } else if matches!(scope, IntegrityScope::NotRequested) {
        IntegrityStatus::Skipped
    } else if has(IssueCategory::IntegrityIncomplete) {
        IntegrityStatus::Incomplete
    } else {
        IntegrityStatus::Pass
    }
}

/// Whether the caller asked for a payload integrity check, and what the check
/// left unverified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum IntegrityScope {
    NotRequested,
    Requested(IntegrityGaps),
}

closed_enum! {
    /// Why part of the payload was not verified by the integrity check.
    ///
    /// `#[non_exhaustive]` so a future reason is not a breaking change for
    /// downstream matches. The string form is stable and shared by the CLI
    /// JSON output and the language bindings.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    #[non_exhaustive]
    pub enum UnverifiedReason {
        /// The decompression budget could not cover it.
        OverBudget => "over_budget",

        /// Quota, ratio or decoder-memory admission refused it.
        ResourceLimit => "resource_limit",

        /// A solid 7z block while `allow_solid_archives` is off.
        SolidPolicy => "solid_policy",

        /// The stream outgrew its declared size.
        SizeCeiling => "size_ceiling",

        /// A 7z block checksum that the entries do not cover.
        UncoveredBlockCrc => "uncovered_block_crc",

        /// An unsupported or unparseable 7z coder.
        NotDecodable => "not_decodable",

        /// A TAR stream that ends without an end-of-archive marker.
        NoEndMarker => "no_end_marker",

        /// An entry dropped from the manifest because its path exceeds the
        /// host limits.
        PathTooLong => "path_too_long",

        /// The data-descriptor tail of a ZIP entry was not searched.
        DescriptorTail => "descriptor_tail",
    }
}

impl UnverifiedReason {
    /// A short human-readable description, used in report messages.
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Self::OverBudget => "over budget",
            Self::ResourceLimit => "resource limit",
            Self::SolidPolicy => "solid archive with allow_solid_archives off",
            Self::SizeCeiling => "declared size exceeded",
            Self::UncoveredBlockCrc => "block checksum not reachable",
            Self::NotDecodable => "not decodable",
            Self::NoEndMarker => "no end-of-archive marker",
            Self::PathTooLong => "path too long for the host",
            Self::DescriptorTail => {
                "data-descriptor tail not searched (budget, or raw decode disagrees with the zip crate)"
            }
        }
    }
}

/// Most unverified entries an [`IntegrityGaps`] lists by path; the rest are
/// only counted.
pub(crate) const MAX_LISTED_UNVERIFIED: usize = 256;

/// One entry the integrity check could not verify, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnverifiedEntry {
    path: PathBuf,
    reason: UnverifiedReason,
}

impl UnverifiedEntry {
    /// The entry's path inside the archive.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Why the entry was not verified.
    #[must_use]
    pub const fn reason(&self) -> UnverifiedReason {
        self.reason
    }
}

/// What a requested integrity check left unverified.
///
/// The counts, the listed entries and the `IntegrityIncomplete` issue message
/// all come from this one value, so they cannot disagree. Items that belong to
/// no single entry (a TAR stream without an end marker) are only counted;
/// entries past a fixed cap (256 today; rely on [`omitted`](Self::omitted), not
/// the number) are counted in [`omitted`](Self::omitted) instead of listed. The
/// `counts` shape differs per surface: an iterator in Rust, a map in the CLI
/// JSON, a dict in Python and an array of `{reason, count}` in Node.
///
/// # Examples
///
/// ```no_run
/// use exarch_core::DecompressionBudget;
/// use exarch_core::IntegrityCheck;
/// 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("a.7z", &SecurityConfig::default(), &options)?;
/// if let Some(gaps) = report.integrity_gaps() {
///     for (reason, count) in gaps.counts() {
///         println!("{reason}: {count}");
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IntegrityGaps {
    counts: BTreeMap<UnverifiedReason, u64>,
    entries: Vec<UnverifiedEntry>,
    omitted: u64,
}

impl IntegrityGaps {
    /// Counts of unverified items per reason, in reason order; reasons with no
    /// items are absent.
    pub fn counts(&self) -> impl Iterator<Item = (UnverifiedReason, u64)> + '_ {
        self.counts.iter().map(|(&reason, &count)| (reason, count))
    }

    /// Number of items left unverified for `reason`.
    #[must_use]
    pub fn count(&self, reason: UnverifiedReason) -> u64 {
        self.counts.get(&reason).copied().unwrap_or_default()
    }

    /// Total number of unverified items.
    #[must_use]
    pub fn total(&self) -> u64 {
        self.counts.values().sum()
    }

    /// Returns true when nothing was left unverified.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.counts.is_empty()
    }

    /// The unverified entries that could be listed by path, up to a fixed cap;
    /// further ones are counted in [`omitted`](Self::omitted).
    #[must_use]
    pub fn entries(&self) -> &[UnverifiedEntry] {
        &self.entries
    }

    /// Number of unverified entries that had a path but were not listed
    /// because the list was full.
    #[must_use]
    pub const fn omitted(&self) -> u64 {
        self.omitted
    }

    pub(crate) fn count_items(&mut self, reason: UnverifiedReason, items: u64) {
        if items > 0 {
            *self.counts.entry(reason).or_default() += items;
        }
    }

    pub(crate) fn mark_entry(&mut self, reason: UnverifiedReason, path: &Path) {
        self.count_items(reason, 1);
        if self.entries.len() < MAX_LISTED_UNVERIFIED {
            self.entries.push(UnverifiedEntry {
                path: path.to_path_buf(),
                reason,
            });
        } else {
            self.omitted += 1;
        }
    }

    /// The `IntegrityIncomplete` issue message; `None` when nothing is
    /// unverified.
    pub(crate) fn message(&self) -> Option<String> {
        if self.is_empty() {
            return None;
        }
        let detail = self
            .counts()
            .map(|(reason, count)| format!("{}: {count}", reason.description()))
            .collect::<Vec<_>>()
            .join(", ");
        Some(format!(
            "Integrity check incomplete: {} item(s) not verified ({detail})",
            self.total()
        ))
    }
}

fn determine_security_status(issues: &[VerificationIssue]) -> CheckStatus {
    let mut security_issues = issues
        .iter()
        .filter(|i| i.category.is_security() && !i.is_harmless_collision())
        .peekable();

    if security_issues.peek().is_none() {
        return CheckStatus::Pass;
    }

    let fails = security_issues
        .any(|i| i.severity == IssueSeverity::Critical || i.severity == IssueSeverity::High);

    if fails {
        CheckStatus::Fail
    } else {
        CheckStatus::Warning
    }
}

closed_enum! {
    /// Overall verification status.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum VerificationStatus {
        /// All checks passed
        Pass => "PASS",

        /// One or more checks failed
        Fail => "FAIL",

        /// Checks completed with warnings
        Warning => "WARNING",
    }
}

closed_enum! {
    /// Status of a specific check category.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum CheckStatus {
        /// Check passed
        Pass => "OK",

        /// Check failed
        Fail => "FAILED",

        /// Check completed with warnings
        Warning => "WARNING",

        /// Check was skipped
        Skipped => "SKIPPED",
    }
}

closed_enum! {
    /// Result of the payload integrity check.
    ///
    /// `#[non_exhaustive]` so a future outcome is not a breaking change for
    /// downstream matches.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum IntegrityStatus {
        /// Every payload byte was decoded without error. For formats with
        /// payload checksums this includes the checksum; plain TAR, 7z entries
        /// without CRC and zstd frames without a content checksum carry none.
        Pass => "OK",

        /// A checksum or decoder error proved the payload corrupt.
        Fail => "FAILED",

        /// The check ran but some payload was not verified (budget, resource
        /// limit, solid policy, missing end marker).
        Incomplete => "INCOMPLETE",

        /// The check was not requested.
        Skipped => "SKIPPED",
    }
}

/// Single verification issue.
///
/// Construct with [`VerificationIssue::new`] or
/// [`VerificationIssue::from_error`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct VerificationIssue {
    /// Issue severity level
    pub severity: IssueSeverity,

    /// Issue category
    pub category: IssueCategory,

    /// Entry path that triggered issue (if applicable)
    pub entry_path: Option<PathBuf>,

    /// Human-readable description
    pub message: String,

    /// Optional context (compression ratio, target path, etc.)
    pub context: Option<String>,
}

impl VerificationIssue {
    /// The one Low-severity security finding: two directories that merge
    /// without either holding an entry, which changes nothing on disk.
    fn is_harmless_collision(&self) -> bool {
        self.category == IssueCategory::NameCollision && self.severity == IssueSeverity::Low
    }

    /// Creates an issue with no entry path or context attached.
    #[must_use]
    pub const fn new(severity: IssueSeverity, category: IssueCategory, message: String) -> Self {
        Self {
            severity,
            category,
            entry_path: None,
            message,
            context: None,
        }
    }

    /// Creates a verification issue from an extraction error.
    #[must_use]
    pub fn from_error(error: &ArchiveError, entry_path: Option<PathBuf>) -> Self {
        let (severity, category, message) = match error {
            ArchiveError::PathTraversal { path } => (
                IssueSeverity::Critical,
                IssueCategory::PathTraversal,
                format!("Path traversal detected: {}", path.display()),
            ),
            ArchiveError::SymlinkEscape { path } => (
                IssueSeverity::Critical,
                IssueCategory::SymlinkEscape,
                format!("Symlink escape: {}", path.display()),
            ),
            ArchiveError::HardlinkEscape { path } => (
                IssueSeverity::Critical,
                IssueCategory::HardlinkEscape,
                format!("Hardlink escape: {}", path.display()),
            ),
            ArchiveError::ZipBomb(details) => (
                IssueSeverity::Critical,
                IssueCategory::ZipBomb,
                format!("Potential zip bomb: {details}"),
            ),
            ArchiveError::ZipInconsistency(finding) => (
                IssueSeverity::High,
                IssueCategory::from_zip_inconsistency(finding),
                error.to_string(),
            ),
            ArchiveError::QuotaExceeded { resource } => (
                IssueSeverity::High,
                IssueCategory::QuotaExceeded,
                resource.to_string(),
            ),
            ArchiveError::InvalidPermissions { path, mode } => (
                IssueSeverity::Medium,
                IssueCategory::InvalidPermissions,
                format!(
                    "Invalid permissions: {} (mode: {:#o})",
                    path.display(),
                    mode
                ),
            ),
            ArchiveError::Io(io_err) => (
                IssueSeverity::High,
                IssueCategory::InvalidArchive,
                format!("I/O error: {io_err}"),
            ),
            ArchiveError::InvalidArchive(msg) => (
                IssueSeverity::High,
                IssueCategory::InvalidArchive,
                format!("Invalid archive: {msg}"),
            ),
            ArchiveError::SecurityViolation { reason, .. } => (
                IssueSeverity::High,
                IssueCategory::SecurityPolicy,
                format!("Security violation: {reason}"),
            ),
            ArchiveError::SourceNotFound { path } => (
                IssueSeverity::High,
                IssueCategory::InvalidArchive,
                format!("Source not found: {}", path.display()),
            ),
            ArchiveError::SourceNotAccessible { path } => (
                IssueSeverity::High,
                IssueCategory::InvalidArchive,
                format!("Source not accessible: {}", path.display()),
            ),
            ArchiveError::OutputExists { path } => (
                IssueSeverity::Medium,
                IssueCategory::InvalidArchive,
                format!("Output already exists: {}", path.display()),
            ),
            ArchiveError::InvalidCompressionLevel { level } => (
                IssueSeverity::Medium,
                IssueCategory::InvalidArchive,
                format!("Invalid compression level: {level}"),
            ),
            ArchiveError::UnknownFormat { path } => (
                IssueSeverity::High,
                IssueCategory::InvalidArchive,
                format!("Unknown format: {}", path.display()),
            ),
            ArchiveError::InvalidConfiguration { reason } => (
                IssueSeverity::High,
                IssueCategory::InvalidArchive,
                format!("Invalid configuration: {reason}"),
            ),
            ArchiveError::PartialExtraction { source, .. } => {
                return Self::from_error(source, entry_path);
            }
        };

        Self {
            severity,
            category,
            entry_path,
            message,
            context: None,
        }
    }
}

closed_enum! {
    /// Issue severity levels (ordered from least to most severe for Ord).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
    pub enum IssueSeverity {
        /// Informational
        Info => "INFO",

        /// Policy violation
        Low => "LOW",

        /// Security concern
        Medium => "MEDIUM",

        /// Exploitable security issue
        High => "HIGH",

        /// CVE-level vulnerability
        Critical => "CRITICAL",
    }
}

closed_enum! {
    /// Issue categories (maps to security checks).
    ///
    /// `#[non_exhaustive]` so a future security check is not a breaking change
    /// for downstream matches.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum IssueCategory {
        /// Path traversal attack
        PathTraversal => "Path Traversal",

        /// Symlink escape attack
        SymlinkEscape => "Symlink Escape",

        /// Hardlink escape attack
        HardlinkEscape => "Hardlink Escape",

        /// Zip bomb (excessive compression)
        ZipBomb => "Zip Bomb",

        /// Invalid or unsafe permissions
        InvalidPermissions => "Invalid Permissions",

        /// Quota exceeded (file count or size)
        QuotaExceeded => "Quota Exceeded",

        /// Entry rejected by the security policy (links disallowed, NUL bytes,
        /// banned component, ...)
        SecurityPolicy => "Security Policy",

        /// Invalid or corrupted archive
        InvalidArchive => "Invalid Archive",

        /// Suspicious path or filename
        SuspiciousPath => "Suspicious Path",

        /// Executable file detected
        ExecutableFile => "Executable File",

        /// A checksum or decoder error proved the payload corrupt
        CorruptData => "Corrupt Data",

        /// Integrity check could not cover part of the payload
        IntegrityIncomplete => "Integrity Incomplete",

        /// ZIP local header disagrees with its central directory record
        HeaderMismatch => "Header Mismatch",

        /// ZIP central directory repeats an entry name
        DuplicateEntry => "Duplicate Entry",

        /// ZIP entry data ranges intersect
        OverlappingEntries => "Overlapping Entries",

        /// ZIP entry that the central directory does not account for
        HiddenEntry => "Hidden Entry",

        /// Two entry names the host filesystem treats as one
        NameCollision => "Name Collision",

        /// Informational note that needs no action, such as 7z anti-items that
        /// are skipped
        ArchiveNote => "Archive Note",
    }
}

impl IssueCategory {
    /// Category under which a ZIP structure finding is reported.
    pub(crate) const fn from_zip_inconsistency(finding: &ZipInconsistency) -> Self {
        match finding {
            ZipInconsistency::HeaderMismatch { .. }
            | ZipInconsistency::HeaderUncomparable { .. } => Self::HeaderMismatch,
            ZipInconsistency::DuplicateName { .. } => Self::DuplicateEntry,
            ZipInconsistency::OverlappingEntries => Self::OverlappingEntries,
            ZipInconsistency::HiddenLocalHeader { .. }
            | ZipInconsistency::StrayCentralRecord { .. }
            | ZipInconsistency::StrayEndRecord { .. }
            | ZipInconsistency::DescriptorOverrun { .. }
            | ZipInconsistency::XlTypeDivergence { .. }
            | ZipInconsistency::UncountedCentralRecords { .. }
            | ZipInconsistency::IgnoredEndRecord { .. } => Self::HiddenEntry,
        }
    }

    /// Whether issues of this category come from a security check, and so
    /// count towards [`VerificationReport::security_status`].
    ///
    /// The match is exhaustive on purpose: a new category must be classified.
    #[must_use]
    pub const fn is_security(self) -> bool {
        match self {
            Self::PathTraversal
            | Self::SymlinkEscape
            | Self::HardlinkEscape
            | Self::ZipBomb
            | Self::InvalidPermissions
            | Self::QuotaExceeded
            | Self::SecurityPolicy
            | Self::HeaderMismatch
            | Self::DuplicateEntry
            | Self::OverlappingEntries
            | Self::HiddenEntry
            | Self::NameCollision => true,
            Self::InvalidArchive
            | Self::SuspiciousPath
            | Self::ExecutableFile
            | Self::CorruptData
            | Self::IntegrityIncomplete
            | Self::ArchiveNote => false,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::ZipBombDetails;
    use crate::ZipBombScope;
    use std::io;

    use crate::inspection::manifest::ManifestEntryKind;

    fn spellings<T: Copy>(all: &[T], text: impl Fn(T) -> &'static str) -> Vec<&'static str> {
        all.iter().map(|v| text(*v)).collect()
    }

    #[test]
    fn test_enum_as_str_spellings_and_display() {
        assert_eq!(
            spellings(VerificationStatus::ALL, VerificationStatus::as_str),
            ["PASS", "FAIL", "WARNING"]
        );
        assert_eq!(
            spellings(CheckStatus::ALL, CheckStatus::as_str),
            ["OK", "FAILED", "WARNING", "SKIPPED"]
        );
        assert_eq!(
            spellings(IssueSeverity::ALL, IssueSeverity::as_str),
            ["INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL"]
        );
        assert_eq!(
            spellings(IssueCategory::ALL, IssueCategory::as_str),
            [
                "Path Traversal",
                "Symlink Escape",
                "Hardlink Escape",
                "Zip Bomb",
                "Invalid Permissions",
                "Quota Exceeded",
                "Security Policy",
                "Invalid Archive",
                "Suspicious Path",
                "Executable File",
                "Corrupt Data",
                "Integrity Incomplete",
                "Header Mismatch",
                "Duplicate Entry",
                "Overlapping Entries",
                "Hidden Entry",
                "Name Collision",
                "Archive Note",
            ]
        );
        assert_eq!(
            spellings(IntegrityStatus::ALL, IntegrityStatus::as_str),
            ["OK", "FAILED", "INCOMPLETE", "SKIPPED"]
        );
        for category in IssueCategory::ALL {
            assert_eq!(category.to_string(), category.as_str());
        }
        for severity in IssueSeverity::ALL {
            assert_eq!(severity.to_string(), severity.as_str());
        }
    }

    #[test]
    fn test_zip_inconsistency_maps_to_security_issue_categories() {
        use crate::CentralRecordOrdinal;
        use crate::ZipEntryIndex;
        use crate::ZipHeaderField;

        let cases = [
            (
                ZipInconsistency::HeaderMismatch {
                    entry: ZipEntryIndex::new(0),
                    field: ZipHeaderField::FileName,
                    name: "a".to_string(),
                },
                IssueCategory::HeaderMismatch,
            ),
            (
                ZipInconsistency::HeaderUncomparable {
                    entry: ZipEntryIndex::new(0),
                    name: "a".to_string(),
                    reason: crate::ZipUncomparable::Unparseable,
                },
                IssueCategory::HeaderMismatch,
            ),
            (
                ZipInconsistency::DuplicateName {
                    record: CentralRecordOrdinal::new(1),
                    name: "a".to_string(),
                },
                IssueCategory::DuplicateEntry,
            ),
            (
                ZipInconsistency::OverlappingEntries,
                IssueCategory::OverlappingEntries,
            ),
            (
                ZipInconsistency::HiddenLocalHeader {
                    offset: 9,
                    region: crate::HiddenRegion::Gap,
                },
                IssueCategory::HiddenEntry,
            ),
            (
                ZipInconsistency::IgnoredEndRecord { offset: 9 },
                IssueCategory::HiddenEntry,
            ),
            (
                ZipInconsistency::StrayCentralRecord { offset: 9 },
                IssueCategory::HiddenEntry,
            ),
            (
                ZipInconsistency::StrayEndRecord {
                    offset: 9,
                    kind: crate::EndRecordKind::Classic,
                },
                IssueCategory::HiddenEntry,
            ),
            (
                ZipInconsistency::DescriptorOverrun {
                    entry: ZipEntryIndex::new(0),
                    offset: 9,
                },
                IssueCategory::HiddenEntry,
            ),
            (
                ZipInconsistency::XlTypeDivergence {
                    entry: ZipEntryIndex::new(0),
                    offset: 9,
                },
                IssueCategory::HiddenEntry,
            ),
            (
                ZipInconsistency::UncountedCentralRecords {
                    counted: 1,
                    found: 2,
                },
                IssueCategory::HiddenEntry,
            ),
        ];
        for (finding, category) in cases {
            let issue =
                VerificationIssue::from_error(&ArchiveError::ZipInconsistency(finding), None);
            assert_eq!(issue.category, category);
            assert_eq!(issue.severity, IssueSeverity::High);
            assert!(issue.category.is_security());
        }
    }

    #[test]
    fn test_low_severity_issue_of_another_security_category_still_counts() {
        let low = VerificationIssue::new(
            IssueSeverity::Low,
            IssueCategory::SecurityPolicy,
            "policy".to_string(),
        );
        assert_eq!(determine_security_status(&[low]), CheckStatus::Warning);
    }

    #[test]
    fn test_low_severity_security_issue_does_not_taint_security_status() {
        let low = VerificationIssue::new(
            IssueSeverity::Low,
            IssueCategory::NameCollision,
            "directories merge".to_string(),
        );
        assert_eq!(
            determine_security_status(std::slice::from_ref(&low)),
            CheckStatus::Pass
        );
        let medium = VerificationIssue::new(
            IssueSeverity::Medium,
            IssueCategory::NameCollision,
            "files collide".to_string(),
        );
        assert_eq!(
            determine_security_status(&[low, medium]),
            CheckStatus::Warning
        );
    }

    #[test]
    fn test_severity_all_is_ascending() {
        assert!(IssueSeverity::ALL.is_sorted());
    }

    #[test]
    fn test_determine_status_pass() {
        let issues = vec![];
        assert_eq!(determine_status(&issues), VerificationStatus::Pass);
    }

    #[test]
    fn test_determine_status_fail_critical() {
        let issues = vec![VerificationIssue {
            severity: IssueSeverity::Critical,
            category: IssueCategory::PathTraversal,
            entry_path: None,
            message: "Test".to_string(),
            context: None,
        }];
        assert_eq!(determine_status(&issues), VerificationStatus::Fail);
    }

    #[test]
    fn test_determine_status_fail_high() {
        let issues = vec![VerificationIssue {
            severity: IssueSeverity::High,
            category: IssueCategory::QuotaExceeded,
            entry_path: None,
            message: "Test".to_string(),
            context: None,
        }];
        assert_eq!(determine_status(&issues), VerificationStatus::Fail);
    }

    #[test]
    fn test_determine_status_warning() {
        let issues = vec![VerificationIssue {
            severity: IssueSeverity::Medium,
            category: IssueCategory::InvalidPermissions,
            entry_path: None,
            message: "Test".to_string(),
            context: None,
        }];
        assert_eq!(determine_status(&issues), VerificationStatus::Warning);
    }

    #[test]
    fn test_verification_issue_from_path_traversal() {
        let error = ArchiveError::PathTraversal {
            path: PathBuf::from("../../etc/passwd"),
        };
        let issue = VerificationIssue::from_error(&error, None);

        assert_eq!(issue.severity, IssueSeverity::Critical);
        assert_eq!(issue.category, IssueCategory::PathTraversal);
        assert!(issue.message.contains("Path traversal"));
    }

    #[test]
    fn test_verification_issue_from_symlink_escape() {
        let error = ArchiveError::SymlinkEscape {
            path: PathBuf::from("link"),
        };
        let issue = VerificationIssue::from_error(&error, Some(PathBuf::from("link")));

        assert_eq!(issue.severity, IssueSeverity::Critical);
        assert_eq!(issue.category, IssueCategory::SymlinkEscape);
        assert!(issue.message.contains("Symlink escape"));
    }

    #[test]
    fn test_verification_issue_from_zip_bomb() {
        let error =
            ArchiveError::ZipBomb(ZipBombDetails::new(ZipBombScope::Entry, 1000, 1_000_000));
        let issue = VerificationIssue::from_error(&error, None);

        assert_eq!(issue.severity, IssueSeverity::Critical);
        assert_eq!(issue.category, IssueCategory::ZipBomb);
        assert!(issue.message.contains("zip bomb"));
    }

    #[test]
    fn test_verification_issue_from_io_error() {
        let error = ArchiveError::Io(io::Error::new(io::ErrorKind::NotFound, "not found"));
        let issue = VerificationIssue::from_error(&error, None);

        assert_eq!(issue.severity, IssueSeverity::High);
        assert_eq!(issue.category, IssueCategory::InvalidArchive);
    }

    fn issue(severity: IssueSeverity, category: IssueCategory) -> VerificationIssue {
        VerificationIssue::new(severity, category, "Test".to_string())
    }

    fn report_with(issues: Vec<VerificationIssue>) -> VerificationReport {
        let mut manifest = ArchiveManifest::new(ArchiveType::TarGz);
        let entry = ArchiveEntry::new(PathBuf::from("a"), ManifestEntryKind::File, 1024);
        manifest.add_entry(entry).unwrap();
        let mut issues = Some(issues);
        VerificationReport::from_entry_issues(&manifest, |_| issues.take().unwrap_or_default())
    }

    #[test]
    fn test_verification_report_is_safe() {
        let report = report_with(Vec::new());

        assert!(report.is_safe());
        assert_eq!(report.total_entries(), 1);
        assert_eq!(report.total_size(), 1024);
        assert_eq!(report.format(), ArchiveType::TarGz);
        assert_eq!(report.suspicious_entries(), 0);
    }

    #[test]
    fn test_verification_report_not_safe() {
        let report = report_with(vec![issue(
            IssueSeverity::Critical,
            IssueCategory::PathTraversal,
        )]);

        assert!(!report.is_safe());
        assert!(report.has_critical_issues());
        assert_eq!(report.status(), VerificationStatus::Fail);
        assert_eq!(report.security_status(), CheckStatus::Fail);
        assert_eq!(report.suspicious_entries(), 1);
    }

    #[test]
    fn test_status_pass_iff_no_suspicious_entries() {
        for severity in IssueSeverity::ALL {
            let report = report_with(vec![issue(*severity, IssueCategory::SuspiciousPath)]);
            assert_eq!(
                report.status() == VerificationStatus::Pass,
                report.suspicious_entries() == 0,
                "{severity}"
            );
        }
    }

    #[test]
    fn test_issues_sorted_most_severe_first() {
        let report = report_with(vec![
            issue(IssueSeverity::Low, IssueCategory::ExecutableFile),
            issue(IssueSeverity::Critical, IssueCategory::PathTraversal),
            issue(IssueSeverity::Medium, IssueCategory::InvalidPermissions),
        ]);
        let severities: Vec<_> = report.issues().iter().map(|i| i.severity).collect();
        assert_eq!(
            severities,
            [
                IssueSeverity::Critical,
                IssueSeverity::Medium,
                IssueSeverity::Low
            ]
        );
    }

    #[test]
    fn test_verification_issue_from_hardlink_escape() {
        let error = ArchiveError::HardlinkEscape {
            path: PathBuf::from("link"),
        };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::Critical);
        assert_eq!(issue.category, IssueCategory::HardlinkEscape);
        assert!(issue.message.contains("Hardlink escape"));
    }

    #[test]
    fn test_verification_issue_from_quota_exceeded() {
        let error = ArchiveError::QuotaExceeded {
            resource: crate::error::QuotaResource::FileCount {
                current: 11,
                max: 10,
            },
        };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::High);
        assert_eq!(issue.category, IssueCategory::QuotaExceeded);
    }

    #[test]
    fn test_verification_issue_from_invalid_permissions() {
        let error = ArchiveError::InvalidPermissions {
            path: PathBuf::from("file.txt"),
            mode: 0o777,
        };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::Medium);
        assert_eq!(issue.category, IssueCategory::InvalidPermissions);
        assert!(issue.message.contains("Invalid permissions"));
    }

    #[test]
    fn test_verification_issue_from_invalid_archive() {
        let error = ArchiveError::InvalidArchive("bad header".into());
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::High);
        assert_eq!(issue.category, IssueCategory::InvalidArchive);
        assert!(issue.message.contains("Invalid archive"));
    }

    #[test]
    fn test_verification_issue_from_security_violation() {
        let error = ArchiveError::violation("encrypted".into());
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::High);
        assert_eq!(issue.category, IssueCategory::SecurityPolicy);
        assert!(issue.message.contains("Security violation"));
    }

    #[test]
    fn test_security_violation_fails_security_status() {
        let error = ArchiveError::violation("symlinks not allowed".into());
        let report = report_with(vec![VerificationIssue::from_error(&error, None)]);
        assert_eq!(report.status(), VerificationStatus::Fail);
        assert_eq!(report.security_status(), CheckStatus::Fail);
    }

    #[test]
    fn test_is_security_classification() {
        let non_security: Vec<_> = IssueCategory::ALL
            .iter()
            .copied()
            .filter(|c| !c.is_security())
            .collect();
        assert_eq!(
            non_security,
            [
                IssueCategory::InvalidArchive,
                IssueCategory::SuspiciousPath,
                IssueCategory::ExecutableFile,
                IssueCategory::CorruptData,
                IssueCategory::IntegrityIncomplete,
                IssueCategory::ArchiveNote,
            ]
        );
    }

    fn integrity_report(
        issues: Vec<VerificationIssue>,
        scope: IntegrityScope,
    ) -> VerificationReport {
        let mut manifest = ArchiveManifest::new(ArchiveType::TarGz);
        let entry = ArchiveEntry::new(PathBuf::from("a"), ManifestEntryKind::File, 1024);
        manifest.add_entry(entry).unwrap();
        VerificationReport::from_entry_issue_lists(
            &manifest,
            vec![Vec::new()],
            issues,
            &ArchiveStructure::of_manifest(&manifest),
            scope,
        )
    }

    #[test]
    fn test_integrity_not_requested_is_skipped() {
        let report = integrity_report(Vec::new(), IntegrityScope::NotRequested);
        assert_eq!(report.integrity_status(), IntegrityStatus::Skipped);
    }

    #[test]
    fn test_integrity_requested_without_issues_is_pass() {
        let report = integrity_report(
            Vec::new(),
            IntegrityScope::Requested(IntegrityGaps::default()),
        );
        assert_eq!(report.integrity_status(), IntegrityStatus::Pass);
    }

    #[test]
    fn test_corrupt_data_fails_even_when_not_requested() {
        let issues = vec![issue(IssueSeverity::High, IssueCategory::CorruptData)];
        let report = integrity_report(issues, IntegrityScope::NotRequested);
        assert_eq!(report.integrity_status(), IntegrityStatus::Fail);
    }

    #[test]
    fn test_corrupt_data_wins_over_incomplete() {
        let issues = vec![
            issue(IssueSeverity::Medium, IssueCategory::IntegrityIncomplete),
            issue(IssueSeverity::High, IssueCategory::CorruptData),
        ];
        let report = integrity_report(issues, IntegrityScope::Requested(IntegrityGaps::default()));
        assert_eq!(report.integrity_status(), IntegrityStatus::Fail);
    }

    #[test]
    fn test_incomplete_issue_gives_incomplete_and_warning() {
        let issues = vec![issue(
            IssueSeverity::Medium,
            IssueCategory::IntegrityIncomplete,
        )];
        let report = integrity_report(issues, IntegrityScope::Requested(IntegrityGaps::default()));
        assert_eq!(report.integrity_status(), IntegrityStatus::Incomplete);
        assert_eq!(report.status(), VerificationStatus::Warning);
        assert_eq!(report.security_status(), CheckStatus::Pass);
    }

    #[test]
    fn test_archive_level_issues_do_not_count_as_suspicious_entries() {
        let issues = vec![issue(IssueSeverity::High, IssueCategory::CorruptData)];
        let report = integrity_report(issues, IntegrityScope::Requested(IntegrityGaps::default()));
        assert_eq!(report.suspicious_entries(), 0);
        assert_eq!(report.status(), VerificationStatus::Fail);
    }

    fn two_file_manifest() -> ArchiveManifest {
        let mut manifest = ArchiveManifest::new(ArchiveType::Zip);
        for name in ["a.txt", "b.txt"] {
            let entry = ArchiveEntry::new(PathBuf::from(name), ManifestEntryKind::File, 1);
            manifest.add_entry(entry).unwrap();
        }
        manifest
    }

    fn report_of_findings(findings: &[ZipInconsistency]) -> VerificationReport {
        let manifest = two_file_manifest();
        VerificationReport::from_entry_issue_lists(
            &manifest,
            vec![Vec::new(), Vec::new()],
            Vec::new(),
            &ArchiveStructure::new(2, findings, 0),
            IntegrityScope::NotRequested,
        )
    }

    #[test]
    fn test_entry_bound_findings_name_their_entry_and_count_it_once() {
        use crate::ZipEntryIndex;

        let findings = [
            ZipInconsistency::XlTypeDivergence {
                entry: ZipEntryIndex::new(1),
                offset: 40,
            },
            ZipInconsistency::DescriptorOverrun {
                entry: ZipEntryIndex::new(1),
                offset: 60,
            },
        ];
        let report = report_of_findings(&findings);
        assert_eq!(report.suspicious_entries(), 1);
        assert_eq!(report.issues().len(), 2);
        for issue in report.issues() {
            assert_eq!(issue.entry_path.as_deref(), Some(Path::new("b.txt")));
            assert_eq!(issue.category, IssueCategory::HiddenEntry);
        }
    }

    fn overrun_of(index: usize) -> [ZipInconsistency; 1] {
        [ZipInconsistency::DescriptorOverrun {
            entry: crate::ZipEntryIndex::new(index),
            offset: 9,
        }]
    }

    fn report_after_dropped(
        dropped_before: usize,
        findings: &[ZipInconsistency],
    ) -> VerificationReport {
        let mut manifest = ArchiveManifest::new(ArchiveType::Zip);
        for _ in 0..dropped_before {
            manifest.add_oversized(300);
        }
        for name in ["a.txt", "b.txt"] {
            let entry = ArchiveEntry::new(PathBuf::from(name), ManifestEntryKind::File, 1);
            manifest.add_entry(entry).unwrap();
        }
        VerificationReport::from_entry_issue_lists(
            &manifest,
            vec![Vec::new(), Vec::new()],
            Vec::new(),
            &ArchiveStructure::new(2 + dropped_before, findings, 0),
            IntegrityScope::NotRequested,
        )
    }

    #[test]
    fn test_finding_index_skips_entries_dropped_before_it() {
        let report = report_after_dropped(1, &overrun_of(2));
        assert_eq!(report.suspicious_entries(), 1);
        assert_eq!(
            report.issues()[0].entry_path.as_deref(),
            Some(Path::new("b.txt"))
        );
    }

    #[test]
    fn test_finding_of_a_dropped_entry_is_archive_level() {
        let report = report_after_dropped(1, &overrun_of(0));
        assert_eq!(report.suspicious_entries(), 0);
        assert_eq!(report.issues().len(), 1);
        assert!(report.issues()[0].entry_path.is_none());
    }

    #[test]
    fn test_archive_level_findings_stay_unbound() {
        let findings = [
            ZipInconsistency::OverlappingEntries,
            ZipInconsistency::StrayCentralRecord { offset: 9 },
        ];
        let report = report_of_findings(&findings);
        assert_eq!(report.suspicious_entries(), 0);
        assert_eq!(report.issues().len(), 2);
        assert!(report.issues().iter().all(|i| i.entry_path.is_none()));
    }

    #[test]
    fn test_verification_issue_from_source_not_found() {
        let error = ArchiveError::SourceNotFound {
            path: PathBuf::from("/missing"),
        };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::High);
        assert_eq!(issue.category, IssueCategory::InvalidArchive);
        assert!(issue.message.contains("Source not found"));
    }

    #[test]
    fn test_verification_issue_from_source_not_accessible() {
        let error = ArchiveError::SourceNotAccessible {
            path: PathBuf::from("/restricted"),
        };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::High);
        assert_eq!(issue.category, IssueCategory::InvalidArchive);
        assert!(issue.message.contains("Source not accessible"));
    }

    #[test]
    fn test_verification_issue_from_output_exists() {
        let error = ArchiveError::OutputExists {
            path: PathBuf::from("out/"),
        };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::Medium);
        assert_eq!(issue.category, IssueCategory::InvalidArchive);
        assert!(issue.message.contains("Output already exists"));
    }

    #[test]
    fn test_verification_issue_from_invalid_compression_level() {
        let error = ArchiveError::InvalidCompressionLevel { level: 0 };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::Medium);
        assert_eq!(issue.category, IssueCategory::InvalidArchive);
        assert!(issue.message.contains("Invalid compression level"));
    }

    #[test]
    fn test_verification_issue_from_unknown_format() {
        let error = ArchiveError::UnknownFormat {
            path: PathBuf::from("archive.rar"),
        };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::High);
        assert_eq!(issue.category, IssueCategory::InvalidArchive);
        assert!(issue.message.contains("Unknown format"));
    }

    #[test]
    fn test_verification_issue_from_invalid_configuration() {
        let error = ArchiveError::InvalidConfiguration {
            reason: "bad config".into(),
        };
        let issue = VerificationIssue::from_error(&error, None);
        assert_eq!(issue.severity, IssueSeverity::High);
        assert_eq!(issue.category, IssueCategory::InvalidArchive);
        assert!(issue.message.contains("Invalid configuration"));
    }

    #[test]
    fn test_verification_report_issues_by_severity() {
        let report = report_with(vec![
            issue(IssueSeverity::Critical, IssueCategory::PathTraversal),
            issue(IssueSeverity::Low, IssueCategory::ExecutableFile),
        ]);

        assert_eq!(report.issues_by_severity(IssueSeverity::Critical).len(), 1);
        assert_eq!(report.issues_by_severity(IssueSeverity::Low).len(), 1);
        assert_eq!(report.status(), VerificationStatus::Fail);
    }

    proptest::proptest! {
        /// The pass reports every unverified item as a Medium issue, so
        /// INCOMPLETE can never sit next to an overall PASS.
        #[test]
        fn prop_incomplete_integrity_never_coexists_with_overall_pass(
            raw in proptest::collection::vec(
                (0..IssueSeverity::ALL.len(), 0..IssueCategory::ALL.len()),
                0..8,
            ),
            requested in proptest::bool::ANY,
        ) {
            let issues = raw
                .into_iter()
                .map(|(severity, category)| {
                    let category = IssueCategory::ALL[category];
                    let severity = IssueSeverity::ALL[severity];
                    let severity = if category == IssueCategory::IntegrityIncomplete {
                        severity.max(IssueSeverity::Medium)
                    } else {
                        severity
                    };
                    issue(severity, category)
                })
                .collect();
            let scope = if requested {
                IntegrityScope::Requested(IntegrityGaps::default())
            } else {
                IntegrityScope::NotRequested
            };

            let report = integrity_report(issues, scope);
            if report.integrity_status() == IntegrityStatus::Incomplete {
                proptest::prop_assert_ne!(report.status(), VerificationStatus::Pass);
            }
        }
    }
}