exarch-core 0.12.0

Memory-safe archive extraction library with security validation
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
//! Typed security-policy refusals.
//!
//! [`Violation`] is the payload of [`ArchiveError::SecurityViolation`]. Each
//! kind fixes its own message, its [`SecurityViolationSubCode`] and the
//! `SecurityConfig` setting that relaxes it, so none of the three can be
//! supplied next to a kind that contradicts it.
//!
//! [`ArchiveError::SecurityViolation`]: super::ArchiveError::SecurityViolation

use std::fmt;

use super::messages::SecurityViolationSubCode;
use super::types::PolicySetting;
use crate::closed_enum::closed_enum;
use crate::inspection::ManifestEntryType;
use crate::security::fs_view::LinkKind;
use crate::security::fs_view::PathModel;

/// A Unix file type that exarch never creates.
///
/// # Examples
///
/// ```
/// use exarch_core::SpecialFile;
///
/// assert_eq!(SpecialFile::Fifo.noun(), "FIFO");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SpecialFile {
    /// A named pipe.
    Fifo,
    /// A character device node.
    CharDevice,
    /// A block device node.
    BlockDevice,
    /// A Unix domain socket.
    Socket,
}

impl SpecialFile {
    /// The noun used in refusal messages.
    #[must_use]
    pub const fn noun(self) -> &'static str {
        match self {
            Self::Fifo => "FIFO",
            Self::CharDevice => "character device",
            Self::BlockDevice => "block device",
            Self::Socket => "socket",
        }
    }
}

/// Why a path component is hazardous on some supported platform but not
/// necessarily on the host.
///
/// # Examples
///
/// ```
/// use exarch_core::PortableHazard;
///
/// assert_eq!(
///     PortableHazard::Backslash.to_string(),
///     "contains a backslash"
/// );
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PortableHazard {
    /// Not valid UTF-8, so UTF-16 and UTF-8 filesystems would read it
    /// differently.
    NotUtf8,
    /// `\` separates components on Windows.
    Backslash,
    /// One of `<>"|?*` or a control character, which Windows refuses.
    ForbiddenCharacter,
}

impl fmt::Display for PortableHazard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NotUtf8 => "not valid UTF-8",
            Self::Backslash => "contains a backslash",
            Self::ForbiddenCharacter => "contains a character Windows refuses",
        })
    }
}

/// The typeflag byte of a TAR header, independent of the `tar` crate's entry
/// type enumeration.
///
/// Displays as `'D' (0x44)` for a graphic ASCII byte and as `0x00` for any
/// other, so a refusal names the flag the archive holds.
///
/// # Examples
///
/// ```
/// use exarch_core::TarTypeflag;
///
/// assert_eq!(TarTypeflag::new(b'D').to_string(), "'D' (0x44)");
/// assert_eq!(TarTypeflag::new(0).to_string(), "0x00");
/// assert_eq!(TarTypeflag::new(b'V').get(), b'V');
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TarTypeflag(u8);

impl TarTypeflag {
    /// Wraps a typeflag byte.
    #[must_use]
    pub const fn new(byte: u8) -> Self {
        Self(byte)
    }

    /// The raw typeflag byte.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

impl fmt::Display for TarTypeflag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0.is_ascii_graphic() {
            write!(f, "'{}' (0x{:02X})", char::from(self.0), self.0)
        } else {
            write!(f, "0x{:02X}", self.0)
        }
    }
}

/// What a 7z header itself says an entry is: a directory has no stream and is
/// not flagged as an empty file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NativeKind {
    /// Holds data or is an empty file.
    File,
    /// Has no stream and is not an empty file.
    Directory,
}

impl NativeKind {
    const fn noun(self) -> &'static str {
        match self {
            Self::File => "file",
            Self::Directory => "directory",
        }
    }

    const fn opposite(self) -> &'static str {
        match self {
            Self::File => "directory",
            Self::Directory => "regular file",
        }
    }
}

/// Where a claim about a 7z entry's kind was recorded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum KindSource {
    /// The Unix mode in the high 16 bits of the attributes.
    UnixMode,
    /// The Windows `FILE_ATTRIBUTE_DIRECTORY` bit.
    WindowsAttribute,
}

impl KindSource {
    const fn noun(self) -> &'static str {
        match self {
            Self::UnixMode => "Unix mode",
            Self::WindowsAttribute => "Windows attributes",
        }
    }
}

closed_enum! {
    /// Why an encrypted archive or entry was refused.
    ///
    /// Distinguishing a wrong password from tampered data is deliberate:
    /// whoever holds the archive can guess passwords offline anyway, so a
    /// caller may retry on [`WrongPassword`](Self::WrongPassword) and
    /// quarantine on [`AuthenticationFailed`](Self::AuthenticationFailed).
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::EncryptionRefusal;
    ///
    /// assert_eq!(EncryptionRefusal::PasswordRequired.as_str(), "password_required");
    /// assert!(EncryptionRefusal::ALL.contains(&EncryptionRefusal::KdfCostExceeded));
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum EncryptionRefusal {
        /// The archive or entry is encrypted and no password was supplied.
        PasswordRequired => "password_required",
        /// The `WinZip` AES password verifier did not match.
        WrongPassword => "wrong_password",
        /// The authentication code did not match: the data was altered, or a
        /// wrong password passed the short verifier.
        AuthenticationFailed => "authentication_failed",
        /// A 7z archive has no verifier: the supplied password plus a CRC or
        /// decoder failure means a wrong password or corrupt data.
        WrongPasswordOrCorrupt => "wrong_password_or_corrupt",
        /// `ZipCrypto`, or the 7z raw-key mode, which exarch refuses as too
        /// weak.
        WeakEncryptionRefused => "weak_encryption_refused",
        /// Deriving the keys would exceed `SecurityConfig::max_kdf_work`.
        KdfCostExceeded => "kdf_cost_exceeded",
        /// A 7z archive needs a password and the one supplied is not UTF-8 text,
        /// so it cannot match any 7z key.
        UnusablePassword => "unusable_password",
    }
}

impl EncryptionRefusal {
    /// The fixed sentence that states this refusal.
    #[must_use]
    pub const fn message(self) -> &'static str {
        match self {
            Self::PasswordRequired => {
                "the archive is encrypted (password-protected) and no password was supplied"
            }
            Self::WrongPassword => "the password is wrong",
            Self::AuthenticationFailed => {
                "encrypted data failed authentication: it was altered, or the password is wrong"
            }
            Self::WrongPasswordOrCorrupt => {
                "the password is wrong or the encrypted data is corrupt"
            }
            Self::WeakEncryptionRefused => {
                "the encryption is too weak to accept (ZipCrypto or raw-key 7z)"
            }
            Self::KdfCostExceeded => {
                "key derivation would exceed the max_kdf_work budget of this operation"
            }
            Self::UnusablePassword => "the password is not valid UTF-8 text, which 7z requires",
        }
    }
}

/// Why an operation was denied by security policy.
///
/// Text payloads are already rendered (escaped where an attacker controls
/// them), so a `Violation` never holds a crate-private type.
/// [`Self::relaxable_by`] and [`Self::sub_code`] are derived from the kind.
///
/// # Examples
///
/// ```
/// use exarch_core::ArchiveError;
/// use exarch_core::PolicySetting;
/// use exarch_core::SecurityViolationSubCode;
/// use exarch_core::Violation;
///
/// let kind = Violation::BannedComponent {
///     component: ".git".into(),
/// };
/// assert_eq!(kind.relaxable_by(), Some(PolicySetting::BannedComponents));
/// assert_eq!(kind.sub_code(), SecurityViolationSubCode::PathName);
/// assert_eq!(kind.to_string(), "banned path component: .git");
///
/// let err = ArchiveError::from(kind);
/// assert_eq!(err.relaxable_by(), Some(PolicySetting::BannedComponents));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Violation {
    /// An entry or argument path is empty.
    EmptyPath,
    /// An entry path contains a NUL byte.
    NulInPath {
        /// The path, rendered for display.
        path: Box<str>,
    },
    /// A caller-supplied path argument contains a NUL byte.
    NulInPathArgument,
    /// A caller-supplied path argument exceeds the length limit.
    PathTooLong {
        /// Length of the path in bytes.
        len: usize,
        /// The limit in bytes.
        max: usize,
    },
    /// A path component is on the banned list.
    BannedComponent {
        /// The component.
        component: Box<str>,
    },
    /// A path component holds a character no supported platform accepts.
    UnsafeComponent {
        /// What makes the component hazardous.
        hazard: PortableHazard,
        /// The rule set that found it.
        model: PathModel,
        /// The component, escaped.
        component: Box<str>,
    },
    /// A path component is a Windows reserved device name.
    ReservedDeviceName {
        /// The component, escaped.
        component: Box<str>,
    },
    /// A path component ends with a dot or a space.
    TrailingDotOrSpace {
        /// The component, escaped.
        component: Box<str>,
    },
    /// An existing entry is named by an alternate 8.3 spelling.
    ShortNameAlias {
        /// The component, escaped.
        component: Box<str>,
    },
    /// A path component contains `:`.
    StreamSeparator {
        /// The component, escaped.
        component: Box<str>,
    },
    /// An entry path is deeper than the limit.
    PathDepth {
        /// Depth of the path.
        depth: usize,
        /// The limit.
        max: usize,
    },
    /// A symlink target is deeper than the limit.
    SymlinkTargetDepth {
        /// Depth of the target.
        depth: usize,
        /// The limit.
        max: usize,
    },
    /// A link target is empty.
    LinkTargetEmpty(LinkKind),
    /// A link target contains a NUL byte.
    LinkTargetNul(LinkKind),
    /// A symlink or hardlink target contains a banned path component.
    LinkTargetBannedComponent {
        /// Whether the link is a symlink or a hardlink.
        kind: LinkKind,
        /// The component.
        component: Box<str>,
    },
    /// A symlink target stored as entry data is above the host limit.
    LinkTargetTooLarge {
        /// Size of the stored target in bytes.
        size: u64,
        /// The limit in bytes.
        max: u64,
    },
    /// A link entry has no target.
    LinkTargetMissing(LinkKind),
    /// A link target was not read, so it cannot be validated.
    LinkTargetUnread(LinkKind),
    /// A link target could not be read, so it cannot be validated.
    LinkTargetUnreadable(LinkKind),
    /// A Windows reparse point, whose target cannot be read.
    ReparsePointTarget {
        /// The entry name.
        name: Box<str>,
    },
    /// The kind of link is disabled by the configuration.
    LinksNotAllowed(LinkKind),
    /// A path component below the destination is a symlink the policy refuses.
    SymlinkComponent {
        /// The walked path up to and including the symlink.
        walked: Box<str>,
        /// Who made the symlink.
        by: super::types::OccupiedBy,
    },
    /// A parent of the entry is a symlink that does not resolve to a
    /// directory.
    SymlinkParent {
        /// The entry that would be created.
        entry: Box<str>,
        /// The blocking parent.
        parent: Box<str>,
        /// Who made the symlink.
        by: super::types::OccupiedBy,
    },
    /// The destination changed between the check that vetted it and the
    /// replace that acts on it.
    DestinationChanged,
    /// The entry would replace an existing symlink.
    ReplacesSymlink {
        /// The entry path.
        rel: Box<str>,
        /// Who made the symlink.
        by: super::types::OccupiedBy,
    },
    /// A device node, FIFO or socket.
    SpecialEntry {
        /// Which special file.
        kind: SpecialFile,
        /// The entry name, when the format reports it.
        name: Option<Box<str>>,
    },
    /// A TAR typeflag that is not a file, directory or link.
    UnsupportedTarType {
        /// The typeflag the header holds.
        typeflag: TarTypeflag,
    },
    /// A 7z Unix mode whose type bits name no defined file type.
    UndefinedUnixType {
        /// The type bits, shifted down.
        bits: u8,
        /// The entry name.
        name: Box<str>,
    },
    /// A 7z entry whose recorded kind contradicts its native kind.
    KindContradiction {
        /// What the 7z header says.
        native: NativeKind,
        /// Where the contradicting claim was recorded.
        claimed_by: KindSource,
        /// The entry name.
        name: Box<str>,
    },
    /// A root entry that is not a directory.
    RootEntryNotDirectory,
    /// A ZIP root entry that is neither a directory nor an empty file.
    RootEntryNotDirectoryOrEmptyFile,
    /// An encrypted archive or entry that exarch refuses.
    Encrypted {
        /// Why it was refused.
        reason: EncryptionRefusal,
        /// The entry, or `None` when the whole archive is the subject.
        name: Option<Box<str>>,
    },
    /// A ZIP compression method exarch does not read.
    UnsupportedCompressionMethod {
        /// The method, rendered.
        method: Box<str>,
    },
    /// A solid 7z archive while solid archives are disabled.
    SolidArchive,
    /// A stream decompressed past its declared size.
    DeclaredSizeExceeded {
        /// The declared uncompressed size in bytes.
        declared: u64,
    },
    /// A stream ended before its declared size.
    DeclaredSizeMismatch {
        /// The declared uncompressed size in bytes.
        declared: u64,
        /// The bytes actually produced.
        actual: u64,
    },
    /// A hardlink target changed while it was being copied.
    HardlinkTargetChanged,
    /// A TAR read passed the metadata budget.
    TarMetadataBudget {
        /// The budget in bytes.
        limit: u64,
    },
    /// A TAR archive drained more synthesized bytes than the cross-entry cap.
    TarSyntheticBudget {
        /// The cap in bytes.
        limit: u64,
    },
    /// The host cannot create symlinks.
    SymlinksUnsupported,
    /// Extraction can fail at an entry unless duplicates are skipped.
    ConflictUnlessSkipped {
        /// The entry path.
        rel: Box<str>,
        /// The filesystem error, rendered.
        cause: Box<str>,
    },
    /// Extraction fails at an entry.
    ConflictFails {
        /// The entry path.
        rel: Box<str>,
        /// The filesystem error, rendered.
        cause: Box<str>,
    },
    /// A hardlink whose target entry the extraction does not write.
    HardlinkTargetNotExtracted {
        /// The hardlink entry path.
        link: Box<str>,
        /// The target path, as the archive names it.
        target: Box<str>,
    },
    /// A hardlink whose target path is the landing of several entries, after
    /// stripping or flattening made them collide.
    HardlinkTargetAmbiguous {
        /// The hardlink entry path.
        link: Box<str>,
        /// The landing several entries map to.
        target: Box<str>,
    },
    /// A symlink or hardlink entry under a flattening rewrite.
    LinkUnderFlatten {
        /// Which kind of link the entry is.
        kind: LinkKind,
        /// The entry path.
        name: Box<str>,
    },
    /// A source path to archive lies outside the archive root.
    SourceOutsideRoot {
        /// The source path.
        path: Box<str>,
        /// The root directory.
        root: Box<str>,
    },
    /// A landing named by more than one entry while repeated paths are
    /// refused.
    RepeatedPath {
        /// The landing, as displayed.
        path: Box<str>,
        /// The kind of the copy that came first.
        earlier: ManifestEntryType,
        /// The kind of the entry that arrived later.
        later: ManifestEntryType,
    },
}

impl Violation {
    /// The `SecurityConfig` setting whose current value refused the entry, or
    /// `None` when no setting relaxes this refusal.
    #[must_use]
    pub const fn relaxable_by(&self) -> Option<PolicySetting> {
        match self {
            Self::BannedComponent { .. } | Self::LinkTargetBannedComponent { .. } => {
                Some(PolicySetting::BannedComponents)
            }
            Self::ReservedDeviceName { .. } => Some(PolicySetting::WindowsReservedNames),
            Self::PathDepth { .. } | Self::SymlinkTargetDepth { .. } => {
                Some(PolicySetting::MaxPathDepth)
            }
            Self::LinksNotAllowed(LinkKind::Symlink) | Self::SymlinkComponent { .. } => {
                Some(PolicySetting::Symlinks)
            }
            Self::LinksNotAllowed(LinkKind::Hardlink) => Some(PolicySetting::Hardlinks),
            Self::SolidArchive => Some(PolicySetting::SolidArchives),
            Self::TarMetadataBudget { .. } => Some(PolicySetting::MaxTarMetadataBytes),
            Self::RepeatedPath { .. } => Some(PolicySetting::RepeatedPaths),
            Self::EmptyPath
            | Self::NulInPath { .. }
            | Self::NulInPathArgument
            | Self::PathTooLong { .. }
            | Self::UnsafeComponent { .. }
            | Self::TrailingDotOrSpace { .. }
            | Self::ShortNameAlias { .. }
            | Self::StreamSeparator { .. }
            | Self::LinkTargetEmpty(_)
            | Self::LinkTargetNul(_)
            | Self::LinkTargetTooLarge { .. }
            | Self::LinkTargetMissing(_)
            | Self::LinkTargetUnread(_)
            | Self::LinkTargetUnreadable(_)
            | Self::ReparsePointTarget { .. }
            | Self::SymlinkParent { .. }
            | Self::ReplacesSymlink { .. }
            | Self::SpecialEntry { .. }
            | Self::UnsupportedTarType { .. }
            | Self::UndefinedUnixType { .. }
            | Self::KindContradiction { .. }
            | Self::RootEntryNotDirectory
            | Self::RootEntryNotDirectoryOrEmptyFile
            | Self::Encrypted { .. }
            | Self::UnsupportedCompressionMethod { .. }
            | Self::DeclaredSizeExceeded { .. }
            | Self::DeclaredSizeMismatch { .. }
            | Self::HardlinkTargetChanged
            | Self::DestinationChanged
            | Self::TarSyntheticBudget { .. }
            | Self::SymlinksUnsupported
            | Self::ConflictUnlessSkipped { .. }
            | Self::ConflictFails { .. }
            | Self::HardlinkTargetNotExtracted { .. }
            | Self::HardlinkTargetAmbiguous { .. }
            | Self::LinkUnderFlatten { .. }
            | Self::SourceOutsideRoot { .. } => None,
        }
    }

    /// The family this kind belongs to.
    #[must_use]
    pub const fn sub_code(&self) -> SecurityViolationSubCode {
        use SecurityViolationSubCode as C;
        match self {
            Self::EmptyPath
            | Self::NulInPath { .. }
            | Self::NulInPathArgument
            | Self::PathTooLong { .. }
            | Self::BannedComponent { .. }
            | Self::UnsafeComponent { .. }
            | Self::ReservedDeviceName { .. }
            | Self::TrailingDotOrSpace { .. }
            | Self::ShortNameAlias { .. }
            | Self::StreamSeparator { .. } => C::PathName,
            Self::PathDepth { .. } | Self::SymlinkTargetDepth { .. } => C::PathDepth,
            Self::LinkTargetEmpty(_)
            | Self::LinkTargetNul(_)
            | Self::LinkTargetBannedComponent { .. }
            | Self::LinkTargetTooLarge { .. }
            | Self::LinkTargetMissing(_)
            | Self::LinkTargetUnread(_)
            | Self::LinkTargetUnreadable(_)
            | Self::HardlinkTargetNotExtracted { .. }
            | Self::HardlinkTargetAmbiguous { .. }
            | Self::ReparsePointTarget { .. } => C::LinkTarget,
            Self::LinksNotAllowed(_) | Self::LinkUnderFlatten { .. } => C::LinkPolicy,
            Self::SymlinkComponent { .. }
            | Self::SymlinkParent { .. }
            | Self::ReplacesSymlink { .. } => C::ExistingSymlink,
            Self::SpecialEntry { .. }
            | Self::UnsupportedTarType { .. }
            | Self::UndefinedUnixType { .. }
            | Self::KindContradiction { .. } => C::EntryType,
            Self::RootEntryNotDirectory | Self::RootEntryNotDirectoryOrEmptyFile => C::RootEntry,
            Self::Encrypted { .. } => C::Encrypted,
            Self::UnsupportedCompressionMethod { .. } => C::CompressionMethod,
            Self::SolidArchive => C::SolidArchive,
            Self::DeclaredSizeExceeded { .. } | Self::DeclaredSizeMismatch { .. } => {
                C::DeclaredSize
            }
            Self::HardlinkTargetChanged | Self::DestinationChanged => C::ConcurrentChange,
            Self::TarMetadataBudget { .. } | Self::TarSyntheticBudget { .. } => C::TarMetadata,
            Self::SymlinksUnsupported => C::Platform,
            Self::ConflictUnlessSkipped { .. } | Self::ConflictFails { .. } => C::OutputConflict,
            Self::SourceOutsideRoot { .. } => C::SourcePath,
            Self::RepeatedPath { .. } => C::RepeatedPath,
        }
    }
}

pub(crate) fn fmt_tar_read_budget(f: &mut fmt::Formatter<'_>, limit: u64) -> fmt::Result {
    write!(
        f,
        "TAR metadata read budget exceeded: more than {limit} bytes read while searching for \
         the next archive entry (long-name/long-link/PAX headers, or a run of GNU sparse \
         extension blocks)"
    )
}

pub(crate) fn fmt_tar_synthetic_budget(f: &mut fmt::Formatter<'_>, limit: u64) -> fmt::Result {
    write!(
        f,
        "TAR cumulative synthetic-byte drain budget exceeded: more than {limit} bytes of \
         synthesized (unbacked) padding drained from unread entries across this archive"
    )
}

impl fmt::Display for Violation {
    #[expect(
        clippy::too_many_lines,
        reason = "one flat match over every kind keeps each message next to its kind"
    )]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyPath => f.write_str(crate::types::safe_path::EMPTY_PATH_REASON),
            Self::NulInPath { path } => write!(f, "path contains null bytes: {path}"),
            Self::NulInPathArgument => {
                f.write_str("path contains null bytes - potential security issue")
            }
            Self::PathTooLong { len, max } => write!(
                f,
                "path exceeds maximum length of {max} bytes (got {len} bytes)"
            ),
            Self::BannedComponent { component } => {
                write!(f, "banned path component: {component}")
            }
            Self::UnsafeComponent {
                hazard,
                model: PathModel::Portable,
                component,
            } => write!(f, "path component is not portable ({hazard}): {component}"),
            Self::UnsafeComponent {
                hazard, component, ..
            } => write!(f, "path component {hazard}: {component}"),
            Self::KindContradiction {
                native,
                claimed_by,
                name,
            } => write!(
                f,
                "7z entry is a {} but its {} says {}: {name}",
                native.noun(),
                claimed_by.noun(),
                native.opposite()
            ),
            Self::ReservedDeviceName { component } => {
                write!(f, "Windows reserved device name: {component}")
            }
            Self::TrailingDotOrSpace { component } => {
                write!(f, "path component ends with '.' or ' ': {component}")
            }
            Self::ShortNameAlias { component } => {
                write!(
                    f,
                    "path component is an alternate 8.3 spelling: {component}"
                )
            }
            Self::StreamSeparator { component } => {
                write!(f, "path component contains ':': {component}")
            }
            Self::PathDepth { depth, max } => {
                write!(f, "path depth {depth} exceeds maximum {max}")
            }
            Self::SymlinkTargetDepth { depth, max } => {
                write!(f, "symlink target depth {depth} exceeds maximum {max}")
            }
            Self::LinkTargetEmpty(kind) => write!(f, "{kind} target is empty"),
            Self::LinkTargetNul(kind) => write!(f, "{kind} target contains null bytes"),
            Self::LinkTargetBannedComponent { kind, component } => {
                write!(f, "{kind} target contains banned component: {component}")
            }
            Self::LinkTargetTooLarge { size, max } => {
                write!(f, "symlink target too large: {size} bytes (max {max})")
            }
            Self::LinkTargetMissing(kind) => write!(f, "{kind} target is missing"),
            Self::LinkTargetUnread(kind) => {
                write!(f, "{kind} target was not read, so it cannot be validated")
            }
            Self::LinkTargetUnreadable(kind) => write!(
                f,
                "{kind} target could not be read, so it cannot be validated"
            ),
            Self::ReparsePointTarget { name } => write!(
                f,
                "symlink detected in 7z archive: {name} (Windows reparse point attribute set). \
                 Its target cannot be read due to sevenz-rust2 API limitations."
            ),
            Self::LinksNotAllowed(kind) => write!(f, "{kind}s not allowed"),
            Self::SymlinkComponent { walked, .. } => {
                write!(f, "path component is a symlink: {walked}")
            }
            Self::SymlinkParent { entry, parent, .. } => write!(
                f,
                "refusing to create {entry} under the existing symlink at {parent}"
            ),
            Self::ReplacesSymlink { rel, .. } => {
                write!(f, "refusing to replace the existing symlink at {rel}")
            }
            Self::SpecialEntry { kind, name: None } => {
                write!(f, "{} entries not supported", kind.noun())
            }
            Self::SpecialEntry {
                kind,
                name: Some(name),
            } => write!(f, "{} entries not supported: {name}", kind.noun()),
            Self::UnsupportedTarType { typeflag } => {
                write!(f, "unsupported entry type: {typeflag}")
            }
            Self::UndefinedUnixType { bits, name } => write!(
                f,
                "7z entry has an undefined Unix file type ({bits:#x}): {name}"
            ),
            Self::RootEntryNotDirectory => {
                f.write_str("archive root entry '.' must be a directory")
            }
            Self::RootEntryNotDirectoryOrEmptyFile => {
                f.write_str("archive root entry '.' must be a directory or an empty regular file")
            }
            Self::Encrypted { reason, name: None } => f.write_str(reason.message()),
            Self::Encrypted {
                reason,
                name: Some(name),
            } => write!(f, "{}: {name}", reason.message()),
            Self::UnsupportedCompressionMethod { method } => {
                write!(f, "unsupported compression method: {method}")
            }
            Self::SolidArchive => {
                f.write_str("solid 7z archives are not allowed (enable allow_solid_archives)")
            }
            Self::DeclaredSizeExceeded { declared } => write!(
                f,
                "decompressed size exceeded the declared uncompressed size of {declared} bytes"
            ),
            Self::DeclaredSizeMismatch { declared, actual } => write!(
                f,
                "decompressed size ({actual} bytes) does not match the declared uncompressed \
                 size ({declared} bytes)"
            ),
            Self::HardlinkTargetChanged => {
                f.write_str("hardlink target changed while it was being copied")
            }
            Self::DestinationChanged => {
                f.write_str("the destination changed while it was being replaced")
            }
            Self::TarMetadataBudget { limit } => fmt_tar_read_budget(f, *limit),
            Self::TarSyntheticBudget { limit } => fmt_tar_synthetic_budget(f, *limit),
            Self::SymlinksUnsupported => f.write_str("symlinks are not supported on this platform"),
            Self::ConflictUnlessSkipped { rel, cause } => write!(
                f,
                "extraction can fail at {rel} unless duplicates are skipped: {cause}"
            ),
            Self::ConflictFails { rel, cause } => {
                write!(f, "extraction fails at {rel}: {cause}")
            }
            Self::HardlinkTargetNotExtracted { link, target } => write!(
                f,
                "hardlink {link} points at {target}, which the selection does not extract"
            ),
            Self::HardlinkTargetAmbiguous { link, target } => write!(
                f,
                "hardlink {link} points at {target}, which several entries map to"
            ),
            Self::LinkUnderFlatten { kind, name } => {
                write!(f, "flattening refuses {kind} entries: {name}")
            }
            Self::SourceOutsideRoot { path, root } => {
                write!(f, "path {path} is not under root directory: {root}")
            }
            Self::RepeatedPath {
                path,
                earlier,
                later,
            } => write!(
                f,
                "path {path} is named twice: a {earlier} entry, then a {later} entry"
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn text(s: &str) -> Box<str> {
        s.into()
    }

    #[expect(
        clippy::too_many_lines,
        reason = "a table with one row per Violation kind"
    )]
    fn one_of_each() -> Vec<(Violation, SecurityViolationSubCode, Option<PolicySetting>)> {
        use SecurityViolationSubCode as C;
        let link = LinkKind::Symlink;
        vec![
            (Violation::EmptyPath, C::PathName, None),
            (Violation::NulInPath { path: text("p") }, C::PathName, None),
            (Violation::NulInPathArgument, C::PathName, None),
            (Violation::PathTooLong { len: 2, max: 1 }, C::PathName, None),
            (
                Violation::BannedComponent {
                    component: text("c"),
                },
                C::PathName,
                Some(PolicySetting::BannedComponents),
            ),
            (
                Violation::UnsafeComponent {
                    hazard: PortableHazard::Backslash,
                    model: PathModel::Portable,
                    component: text("c"),
                },
                C::PathName,
                None,
            ),
            (
                Violation::ReservedDeviceName {
                    component: text("c"),
                },
                C::PathName,
                Some(PolicySetting::WindowsReservedNames),
            ),
            (
                Violation::TrailingDotOrSpace {
                    component: text("c"),
                },
                C::PathName,
                None,
            ),
            (
                Violation::ShortNameAlias {
                    component: text("c"),
                },
                C::PathName,
                None,
            ),
            (
                Violation::StreamSeparator {
                    component: text("c"),
                },
                C::PathName,
                None,
            ),
            (
                Violation::PathDepth { depth: 2, max: 1 },
                C::PathDepth,
                Some(PolicySetting::MaxPathDepth),
            ),
            (
                Violation::SymlinkTargetDepth { depth: 2, max: 1 },
                C::PathDepth,
                Some(PolicySetting::MaxPathDepth),
            ),
            (Violation::LinkTargetEmpty(link), C::LinkTarget, None),
            (Violation::LinkTargetNul(link), C::LinkTarget, None),
            (
                Violation::LinkTargetBannedComponent {
                    kind: link,
                    component: text("c"),
                },
                C::LinkTarget,
                Some(PolicySetting::BannedComponents),
            ),
            (
                Violation::LinkTargetTooLarge { size: 2, max: 1 },
                C::LinkTarget,
                None,
            ),
            (Violation::LinkTargetMissing(link), C::LinkTarget, None),
            (Violation::LinkTargetUnread(link), C::LinkTarget, None),
            (Violation::LinkTargetUnreadable(link), C::LinkTarget, None),
            (
                Violation::ReparsePointTarget { name: text("n") },
                C::LinkTarget,
                None,
            ),
            (
                Violation::LinksNotAllowed(LinkKind::Symlink),
                C::LinkPolicy,
                Some(PolicySetting::Symlinks),
            ),
            (
                Violation::LinksNotAllowed(LinkKind::Hardlink),
                C::LinkPolicy,
                Some(PolicySetting::Hardlinks),
            ),
            (
                Violation::SymlinkComponent {
                    walked: text("w"),
                    by: crate::OccupiedBy::Existing,
                },
                C::ExistingSymlink,
                Some(PolicySetting::Symlinks),
            ),
            (
                Violation::SymlinkParent {
                    entry: text("e"),
                    parent: text("p"),
                    by: crate::OccupiedBy::Existing,
                },
                C::ExistingSymlink,
                None,
            ),
            (
                Violation::ReplacesSymlink {
                    rel: text("r"),
                    by: crate::OccupiedBy::Existing,
                },
                C::ExistingSymlink,
                None,
            ),
            (
                Violation::SpecialEntry {
                    kind: SpecialFile::Fifo,
                    name: None,
                },
                C::EntryType,
                None,
            ),
            (
                Violation::UnsupportedTarType {
                    typeflag: TarTypeflag::new(b'k'),
                },
                C::EntryType,
                None,
            ),
            (
                Violation::UndefinedUnixType {
                    bits: 1,
                    name: text("n"),
                },
                C::EntryType,
                None,
            ),
            (
                Violation::KindContradiction {
                    native: NativeKind::File,
                    claimed_by: KindSource::UnixMode,
                    name: text("n"),
                },
                C::EntryType,
                None,
            ),
            (Violation::RootEntryNotDirectory, C::RootEntry, None),
            (
                Violation::RootEntryNotDirectoryOrEmptyFile,
                C::RootEntry,
                None,
            ),
            (
                Violation::Encrypted {
                    reason: EncryptionRefusal::PasswordRequired,
                    name: None,
                },
                C::Encrypted,
                None,
            ),
            (
                Violation::Encrypted {
                    reason: EncryptionRefusal::WrongPassword,
                    name: Some(text("n")),
                },
                C::Encrypted,
                None,
            ),
            (
                Violation::UnsupportedCompressionMethod { method: text("m") },
                C::CompressionMethod,
                None,
            ),
            (
                Violation::SolidArchive,
                C::SolidArchive,
                Some(PolicySetting::SolidArchives),
            ),
            (
                Violation::DeclaredSizeExceeded { declared: 1 },
                C::DeclaredSize,
                None,
            ),
            (
                Violation::DeclaredSizeMismatch {
                    declared: 1,
                    actual: 2,
                },
                C::DeclaredSize,
                None,
            ),
            (Violation::HardlinkTargetChanged, C::ConcurrentChange, None),
            (Violation::DestinationChanged, C::ConcurrentChange, None),
            (
                Violation::TarMetadataBudget { limit: 1 },
                C::TarMetadata,
                Some(PolicySetting::MaxTarMetadataBytes),
            ),
            (
                Violation::TarSyntheticBudget { limit: 1 },
                C::TarMetadata,
                None,
            ),
            (Violation::SymlinksUnsupported, C::Platform, None),
            (
                Violation::ConflictUnlessSkipped {
                    rel: text("r"),
                    cause: text("c"),
                },
                C::OutputConflict,
                None,
            ),
            (
                Violation::ConflictFails {
                    rel: text("r"),
                    cause: text("c"),
                },
                C::OutputConflict,
                None,
            ),
            (
                Violation::HardlinkTargetNotExtracted {
                    link: text("l"),
                    target: text("t"),
                },
                C::LinkTarget,
                None,
            ),
            (
                Violation::HardlinkTargetAmbiguous {
                    link: text("l"),
                    target: text("t"),
                },
                C::LinkTarget,
                None,
            ),
            (
                Violation::LinkUnderFlatten {
                    kind: link,
                    name: text("n"),
                },
                C::LinkPolicy,
                None,
            ),
            (
                Violation::SourceOutsideRoot {
                    path: text("p"),
                    root: text("r"),
                },
                C::SourcePath,
                None,
            ),
            (
                Violation::RepeatedPath {
                    path: text("p"),
                    earlier: ManifestEntryType::File,
                    later: ManifestEntryType::Symlink,
                },
                C::RepeatedPath,
                Some(PolicySetting::RepeatedPaths),
            ),
        ]
    }

    #[test]
    fn test_every_kind_has_family_setting_and_text() {
        for (kind, code, setting) in one_of_each() {
            assert_eq!(kind.sub_code(), code, "{kind:?}");
            assert_eq!(kind.relaxable_by(), setting, "{kind:?}");
            assert!(!kind.to_string().is_empty(), "{kind:?}");
        }
    }

    /// The text of each `one_of_each` row, in order; byte-identical to the
    /// pre-typing messages (verified by the security audit), and callers match
    /// on them, so a wording change must be a deliberate edit here.
    const EXPECTED_TEXT: [&str; 49] = [
        "empty path not allowed",
        "path contains null bytes: p",
        "path contains null bytes - potential security issue",
        "path exceeds maximum length of 1 bytes (got 2 bytes)",
        "banned path component: c",
        "path component is not portable (contains a backslash): c",
        "Windows reserved device name: c",
        "path component ends with '.' or ' ': c",
        "path component is an alternate 8.3 spelling: c",
        "path component contains ':': c",
        "path depth 2 exceeds maximum 1",
        "symlink target depth 2 exceeds maximum 1",
        "symlink target is empty",
        "symlink target contains null bytes",
        "symlink target contains banned component: c",
        "symlink target too large: 2 bytes (max 1)",
        "symlink target is missing",
        "symlink target was not read, so it cannot be validated",
        "symlink target could not be read, so it cannot be validated",
        "symlink detected in 7z archive: n (Windows reparse point attribute set). Its target cannot be read due to sevenz-rust2 API limitations.",
        "symlinks not allowed",
        "hardlinks not allowed",
        "path component is a symlink: w",
        "refusing to create e under the existing symlink at p",
        "refusing to replace the existing symlink at r",
        "FIFO entries not supported",
        "unsupported entry type: 'k' (0x6B)",
        "7z entry has an undefined Unix file type (0x1): n",
        "7z entry is a file but its Unix mode says directory: n",
        "archive root entry '.' must be a directory",
        "archive root entry '.' must be a directory or an empty regular file",
        "the archive is encrypted (password-protected) and no password was supplied",
        "the password is wrong: n",
        "unsupported compression method: m",
        "solid 7z archives are not allowed (enable allow_solid_archives)",
        "decompressed size exceeded the declared uncompressed size of 1 bytes",
        "decompressed size (2 bytes) does not match the declared uncompressed size (1 bytes)",
        "hardlink target changed while it was being copied",
        "the destination changed while it was being replaced",
        "TAR metadata read budget exceeded: more than 1 bytes read while searching for the next archive entry (long-name/long-link/PAX headers, or a run of GNU sparse extension blocks)",
        "TAR cumulative synthetic-byte drain budget exceeded: more than 1 bytes of synthesized (unbacked) padding drained from unread entries across this archive",
        "symlinks are not supported on this platform",
        "extraction can fail at r unless duplicates are skipped: c",
        "extraction fails at r: c",
        "hardlink l points at t, which the selection does not extract",
        "hardlink l points at t, which several entries map to",
        "flattening refuses symlink entries: n",
        "path p is not under root directory: r",
        "path p is named twice: a File entry, then a Symlink entry",
    ];

    #[test]
    fn test_every_kind_renders_its_pinned_text() {
        let kinds = one_of_each();
        assert_eq!(kinds.len(), EXPECTED_TEXT.len());
        for ((kind, ..), expected) in kinds.iter().zip(EXPECTED_TEXT) {
            assert_eq!(kind.to_string(), expected, "{kind:?}");
        }
    }

    #[test]
    fn test_typeflag_renders_the_character_and_the_hex_byte() {
        for (byte, expected) in [
            (b'D', "'D' (0x44)"),
            (b'Z', "'Z' (0x5A)"),
            (b'V', "'V' (0x56)"),
            (0x00, "0x00"),
            (0x1F, "0x1F"),
            (0x20, "0x20"),
            (0xFF, "0xFF"),
        ] {
            assert_eq!(TarTypeflag::new(byte).to_string(), expected);
        }
    }

    #[test]
    fn test_unsupported_tar_type_names_the_typeflag() {
        let violation = Violation::UnsupportedTarType {
            typeflag: TarTypeflag::new(b'D'),
        };
        assert_eq!(violation.to_string(), "unsupported entry type: 'D' (0x44)");
    }

    #[test]
    fn test_every_family_has_a_kind() {
        let seen: Vec<_> = one_of_each().iter().map(|(k, ..)| k.sub_code()).collect();
        for code in SecurityViolationSubCode::ALL {
            assert!(
                *code == SecurityViolationSubCode::TarTrailer || seen.contains(code),
                "{code} has no Violation kind"
            );
        }
    }

    #[test]
    fn test_link_policy_text_names_the_link_kind() {
        assert_eq!(
            Violation::LinksNotAllowed(LinkKind::Symlink).to_string(),
            "symlinks not allowed"
        );
        assert_eq!(
            Violation::LinksNotAllowed(LinkKind::Hardlink).to_string(),
            "hardlinks not allowed"
        );
    }
}