Skip to main content

exarch_core/error/
violation.rs

1//! Typed security-policy refusals.
2//!
3//! [`Violation`] is the payload of [`ArchiveError::SecurityViolation`]. Each
4//! kind fixes its own message, its [`SecurityViolationSubCode`] and the
5//! `SecurityConfig` setting that relaxes it, so none of the three can be
6//! supplied next to a kind that contradicts it.
7//!
8//! [`ArchiveError::SecurityViolation`]: super::ArchiveError::SecurityViolation
9
10use std::fmt;
11
12use super::messages::SecurityViolationSubCode;
13use super::types::PolicySetting;
14use crate::security::fs_view::LinkKind;
15use crate::security::fs_view::PathModel;
16
17/// A Unix file type that exarch never creates.
18///
19/// # Examples
20///
21/// ```
22/// use exarch_core::SpecialFile;
23///
24/// assert_eq!(SpecialFile::Fifo.noun(), "FIFO");
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum SpecialFile {
29    /// A named pipe.
30    Fifo,
31    /// A character device node.
32    CharDevice,
33    /// A block device node.
34    BlockDevice,
35    /// A Unix domain socket.
36    Socket,
37}
38
39impl SpecialFile {
40    /// The noun used in refusal messages.
41    #[must_use]
42    pub const fn noun(self) -> &'static str {
43        match self {
44            Self::Fifo => "FIFO",
45            Self::CharDevice => "character device",
46            Self::BlockDevice => "block device",
47            Self::Socket => "socket",
48        }
49    }
50}
51
52/// Why a path component is hazardous on some supported platform but not
53/// necessarily on the host.
54///
55/// # Examples
56///
57/// ```
58/// use exarch_core::PortableHazard;
59///
60/// assert_eq!(
61///     PortableHazard::Backslash.to_string(),
62///     "contains a backslash"
63/// );
64/// ```
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66#[non_exhaustive]
67pub enum PortableHazard {
68    /// Not valid UTF-8, so UTF-16 and UTF-8 filesystems would read it
69    /// differently.
70    NotUtf8,
71    /// `\` separates components on Windows.
72    Backslash,
73    /// One of `<>"|?*` or a control character, which Windows refuses.
74    ForbiddenCharacter,
75}
76
77impl fmt::Display for PortableHazard {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.write_str(match self {
80            Self::NotUtf8 => "not valid UTF-8",
81            Self::Backslash => "contains a backslash",
82            Self::ForbiddenCharacter => "contains a character Windows refuses",
83        })
84    }
85}
86
87/// What a 7z header itself says an entry is: a directory has no stream and is
88/// not flagged as an empty file.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90#[non_exhaustive]
91pub enum NativeKind {
92    /// Holds data or is an empty file.
93    File,
94    /// Has no stream and is not an empty file.
95    Directory,
96}
97
98impl NativeKind {
99    const fn noun(self) -> &'static str {
100        match self {
101            Self::File => "file",
102            Self::Directory => "directory",
103        }
104    }
105
106    const fn opposite(self) -> &'static str {
107        match self {
108            Self::File => "directory",
109            Self::Directory => "regular file",
110        }
111    }
112}
113
114/// Where a claim about a 7z entry's kind was recorded.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116#[non_exhaustive]
117pub enum KindSource {
118    /// The Unix mode in the high 16 bits of the attributes.
119    UnixMode,
120    /// The Windows `FILE_ATTRIBUTE_DIRECTORY` bit.
121    WindowsAttribute,
122}
123
124impl KindSource {
125    const fn noun(self) -> &'static str {
126        match self {
127            Self::UnixMode => "Unix mode",
128            Self::WindowsAttribute => "Windows attributes",
129        }
130    }
131}
132
133/// Why an operation was denied by security policy.
134///
135/// Text payloads are already rendered (escaped where an attacker controls
136/// them), so a `Violation` never holds a crate-private type.
137/// [`Self::relaxable_by`] and [`Self::sub_code`] are derived from the kind.
138///
139/// # Examples
140///
141/// ```
142/// use exarch_core::ArchiveError;
143/// use exarch_core::PolicySetting;
144/// use exarch_core::SecurityViolationSubCode;
145/// use exarch_core::Violation;
146///
147/// let kind = Violation::BannedComponent {
148///     component: ".git".into(),
149/// };
150/// assert_eq!(kind.relaxable_by(), Some(PolicySetting::BannedComponents));
151/// assert_eq!(kind.sub_code(), SecurityViolationSubCode::PathName);
152/// assert_eq!(kind.to_string(), "banned path component: .git");
153///
154/// let err = ArchiveError::from(kind);
155/// assert_eq!(err.relaxable_by(), Some(PolicySetting::BannedComponents));
156/// ```
157#[derive(Debug, Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub enum Violation {
160    /// An entry or argument path is empty.
161    EmptyPath,
162    /// An entry path contains a NUL byte.
163    NulInPath {
164        /// The path, rendered for display.
165        path: Box<str>,
166    },
167    /// A caller-supplied path argument contains a NUL byte.
168    NulInPathArgument,
169    /// A caller-supplied path argument exceeds the length limit.
170    PathTooLong {
171        /// Length of the path in bytes.
172        len: usize,
173        /// The limit in bytes.
174        max: usize,
175    },
176    /// A path component is on the banned list.
177    BannedComponent {
178        /// The component.
179        component: Box<str>,
180    },
181    /// A path component holds a character no supported platform accepts.
182    UnsafeComponent {
183        /// What makes the component hazardous.
184        hazard: PortableHazard,
185        /// The rule set that found it.
186        model: PathModel,
187        /// The component, escaped.
188        component: Box<str>,
189    },
190    /// A path component is a Windows reserved device name.
191    ReservedDeviceName {
192        /// The component, escaped.
193        component: Box<str>,
194    },
195    /// A path component ends with a dot or a space.
196    TrailingDotOrSpace {
197        /// The component, escaped.
198        component: Box<str>,
199    },
200    /// A path component contains `:`.
201    StreamSeparator {
202        /// The component, escaped.
203        component: Box<str>,
204    },
205    /// An entry path is deeper than the limit.
206    PathDepth {
207        /// Depth of the path.
208        depth: usize,
209        /// The limit.
210        max: usize,
211    },
212    /// A symlink target is deeper than the limit.
213    SymlinkTargetDepth {
214        /// Depth of the target.
215        depth: usize,
216        /// The limit.
217        max: usize,
218    },
219    /// A link target is empty.
220    LinkTargetEmpty(LinkKind),
221    /// A link target contains a NUL byte.
222    LinkTargetNul(LinkKind),
223    /// A symlink target contains a banned path component.
224    LinkTargetBannedComponent {
225        /// The component.
226        component: Box<str>,
227    },
228    /// A symlink target stored as entry data is above the host limit.
229    LinkTargetTooLarge {
230        /// Size of the stored target in bytes.
231        size: u64,
232        /// The limit in bytes.
233        max: u64,
234    },
235    /// A link entry has no target.
236    LinkTargetMissing(LinkKind),
237    /// A link target was not read, so it cannot be validated.
238    LinkTargetUnread(LinkKind),
239    /// A link target could not be read, so it cannot be validated.
240    LinkTargetUnreadable(LinkKind),
241    /// A Windows reparse point, whose target cannot be read.
242    ReparsePointTarget {
243        /// The entry name.
244        name: Box<str>,
245    },
246    /// The kind of link is disabled by the configuration.
247    LinksNotAllowed(LinkKind),
248    /// A path component below the destination is a symlink the policy refuses.
249    SymlinkComponent {
250        /// The walked path up to and including the symlink.
251        walked: Box<str>,
252    },
253    /// A parent of the entry is a symlink that does not resolve to a
254    /// directory.
255    SymlinkParent {
256        /// The entry that would be created.
257        entry: Box<str>,
258        /// The blocking parent.
259        parent: Box<str>,
260    },
261    /// The entry would replace an existing symlink.
262    ReplacesSymlink {
263        /// The entry path.
264        rel: Box<str>,
265    },
266    /// A device node, FIFO or socket.
267    SpecialEntry {
268        /// Which special file.
269        kind: SpecialFile,
270        /// The entry name, when the format reports it.
271        name: Option<Box<str>>,
272    },
273    /// A TAR typeflag that is not a file, directory or link.
274    UnsupportedTarType {
275        /// The typeflag, rendered.
276        kind: Box<str>,
277    },
278    /// A 7z Unix mode whose type bits name no defined file type.
279    UndefinedUnixType {
280        /// The type bits, shifted down.
281        bits: u8,
282        /// The entry name.
283        name: Box<str>,
284    },
285    /// A 7z entry whose recorded kind contradicts its native kind.
286    KindContradiction {
287        /// What the 7z header says.
288        native: NativeKind,
289        /// Where the contradicting claim was recorded.
290        claimed_by: KindSource,
291        /// The entry name.
292        name: Box<str>,
293    },
294    /// A root entry that is not a directory.
295    RootEntryNotDirectory,
296    /// A ZIP root entry that is neither a directory nor an empty file.
297    RootEntryNotDirectoryOrEmptyFile,
298    /// The whole archive is password-protected.
299    EncryptedArchive,
300    /// One ZIP entry is encrypted.
301    EncryptedEntry {
302        /// The entry name.
303        name: Box<str>,
304    },
305    /// A ZIP compression method exarch does not read.
306    UnsupportedCompressionMethod {
307        /// The method, rendered.
308        method: Box<str>,
309    },
310    /// A solid 7z archive while solid archives are disabled.
311    SolidArchive,
312    /// A stream decompressed past its declared size.
313    DeclaredSizeExceeded {
314        /// The declared uncompressed size in bytes.
315        declared: u64,
316    },
317    /// A stream ended before its declared size.
318    DeclaredSizeMismatch {
319        /// The declared uncompressed size in bytes.
320        declared: u64,
321        /// The bytes actually produced.
322        actual: u64,
323    },
324    /// A hardlink target changed while it was being copied.
325    HardlinkTargetChanged,
326    /// A TAR read passed the metadata budget.
327    TarMetadataBudget {
328        /// The budget in bytes.
329        limit: u64,
330    },
331    /// A TAR archive drained more synthesized bytes than the cross-entry cap.
332    TarSyntheticBudget {
333        /// The cap in bytes.
334        limit: u64,
335    },
336    /// The host cannot create symlinks.
337    SymlinksUnsupported,
338    /// Extraction can fail at an entry unless duplicates are skipped.
339    ConflictUnlessSkipped {
340        /// The entry path.
341        rel: Box<str>,
342        /// The filesystem error, rendered.
343        cause: Box<str>,
344    },
345    /// Extraction fails at an entry.
346    ConflictFails {
347        /// The entry path.
348        rel: Box<str>,
349        /// The filesystem error, rendered.
350        cause: Box<str>,
351    },
352    /// A source path to archive lies outside the archive root.
353    SourceOutsideRoot {
354        /// The source path.
355        path: Box<str>,
356        /// The root directory.
357        root: Box<str>,
358    },
359}
360
361impl Violation {
362    /// The `SecurityConfig` setting whose current value refused the entry, or
363    /// `None` when no setting relaxes this refusal.
364    #[must_use]
365    pub const fn relaxable_by(&self) -> Option<PolicySetting> {
366        match self {
367            Self::BannedComponent { .. } | Self::LinkTargetBannedComponent { .. } => {
368                Some(PolicySetting::BannedComponents)
369            }
370            Self::ReservedDeviceName { .. } => Some(PolicySetting::WindowsReservedNames),
371            Self::PathDepth { .. } | Self::SymlinkTargetDepth { .. } => {
372                Some(PolicySetting::MaxPathDepth)
373            }
374            Self::LinksNotAllowed(LinkKind::Symlink) | Self::SymlinkComponent { .. } => {
375                Some(PolicySetting::Symlinks)
376            }
377            Self::LinksNotAllowed(LinkKind::Hardlink) => Some(PolicySetting::Hardlinks),
378            Self::SolidArchive => Some(PolicySetting::SolidArchives),
379            Self::TarMetadataBudget { .. } => Some(PolicySetting::MaxTarMetadataBytes),
380            Self::EmptyPath
381            | Self::NulInPath { .. }
382            | Self::NulInPathArgument
383            | Self::PathTooLong { .. }
384            | Self::UnsafeComponent { .. }
385            | Self::TrailingDotOrSpace { .. }
386            | Self::StreamSeparator { .. }
387            | Self::LinkTargetEmpty(_)
388            | Self::LinkTargetNul(_)
389            | Self::LinkTargetTooLarge { .. }
390            | Self::LinkTargetMissing(_)
391            | Self::LinkTargetUnread(_)
392            | Self::LinkTargetUnreadable(_)
393            | Self::ReparsePointTarget { .. }
394            | Self::SymlinkParent { .. }
395            | Self::ReplacesSymlink { .. }
396            | Self::SpecialEntry { .. }
397            | Self::UnsupportedTarType { .. }
398            | Self::UndefinedUnixType { .. }
399            | Self::KindContradiction { .. }
400            | Self::RootEntryNotDirectory
401            | Self::RootEntryNotDirectoryOrEmptyFile
402            | Self::EncryptedArchive
403            | Self::EncryptedEntry { .. }
404            | Self::UnsupportedCompressionMethod { .. }
405            | Self::DeclaredSizeExceeded { .. }
406            | Self::DeclaredSizeMismatch { .. }
407            | Self::HardlinkTargetChanged
408            | Self::TarSyntheticBudget { .. }
409            | Self::SymlinksUnsupported
410            | Self::ConflictUnlessSkipped { .. }
411            | Self::ConflictFails { .. }
412            | Self::SourceOutsideRoot { .. } => None,
413        }
414    }
415
416    /// The family this kind belongs to.
417    #[must_use]
418    pub const fn sub_code(&self) -> SecurityViolationSubCode {
419        use SecurityViolationSubCode as C;
420        match self {
421            Self::EmptyPath
422            | Self::NulInPath { .. }
423            | Self::NulInPathArgument
424            | Self::PathTooLong { .. }
425            | Self::BannedComponent { .. }
426            | Self::UnsafeComponent { .. }
427            | Self::ReservedDeviceName { .. }
428            | Self::TrailingDotOrSpace { .. }
429            | Self::StreamSeparator { .. } => C::PathName,
430            Self::PathDepth { .. } | Self::SymlinkTargetDepth { .. } => C::PathDepth,
431            Self::LinkTargetEmpty(_)
432            | Self::LinkTargetNul(_)
433            | Self::LinkTargetBannedComponent { .. }
434            | Self::LinkTargetTooLarge { .. }
435            | Self::LinkTargetMissing(_)
436            | Self::LinkTargetUnread(_)
437            | Self::LinkTargetUnreadable(_)
438            | Self::ReparsePointTarget { .. } => C::LinkTarget,
439            Self::LinksNotAllowed(_) => C::LinkPolicy,
440            Self::SymlinkComponent { .. }
441            | Self::SymlinkParent { .. }
442            | Self::ReplacesSymlink { .. } => C::ExistingSymlink,
443            Self::SpecialEntry { .. }
444            | Self::UnsupportedTarType { .. }
445            | Self::UndefinedUnixType { .. }
446            | Self::KindContradiction { .. } => C::EntryType,
447            Self::RootEntryNotDirectory | Self::RootEntryNotDirectoryOrEmptyFile => C::RootEntry,
448            Self::EncryptedArchive | Self::EncryptedEntry { .. } => C::Encrypted,
449            Self::UnsupportedCompressionMethod { .. } => C::CompressionMethod,
450            Self::SolidArchive => C::SolidArchive,
451            Self::DeclaredSizeExceeded { .. } | Self::DeclaredSizeMismatch { .. } => {
452                C::DeclaredSize
453            }
454            Self::HardlinkTargetChanged => C::ConcurrentChange,
455            Self::TarMetadataBudget { .. } | Self::TarSyntheticBudget { .. } => C::TarMetadata,
456            Self::SymlinksUnsupported => C::Platform,
457            Self::ConflictUnlessSkipped { .. } | Self::ConflictFails { .. } => C::OutputConflict,
458            Self::SourceOutsideRoot { .. } => C::SourcePath,
459        }
460    }
461}
462
463pub(crate) fn fmt_tar_read_budget(f: &mut fmt::Formatter<'_>, limit: u64) -> fmt::Result {
464    write!(
465        f,
466        "TAR metadata read budget exceeded: more than {limit} bytes read while searching for \
467         the next archive entry (long-name/long-link/PAX headers, or a run of GNU sparse \
468         extension blocks)"
469    )
470}
471
472pub(crate) fn fmt_tar_synthetic_budget(f: &mut fmt::Formatter<'_>, limit: u64) -> fmt::Result {
473    write!(
474        f,
475        "TAR cumulative synthetic-byte drain budget exceeded: more than {limit} bytes of \
476         synthesized (unbacked) padding drained from unread entries across this archive"
477    )
478}
479
480impl fmt::Display for Violation {
481    #[expect(
482        clippy::too_many_lines,
483        reason = "one flat match over every kind keeps each message next to its kind"
484    )]
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        match self {
487            Self::EmptyPath => f.write_str(crate::types::safe_path::EMPTY_PATH_REASON),
488            Self::NulInPath { path } => write!(f, "path contains null bytes: {path}"),
489            Self::NulInPathArgument => {
490                f.write_str("path contains null bytes - potential security issue")
491            }
492            Self::PathTooLong { len, max } => write!(
493                f,
494                "path exceeds maximum length of {max} bytes (got {len} bytes)"
495            ),
496            Self::BannedComponent { component } => {
497                write!(f, "banned path component: {component}")
498            }
499            Self::UnsafeComponent {
500                hazard,
501                model: PathModel::Portable,
502                component,
503            } => write!(f, "path component is not portable ({hazard}): {component}"),
504            Self::UnsafeComponent {
505                hazard, component, ..
506            } => write!(f, "path component {hazard}: {component}"),
507            Self::KindContradiction {
508                native,
509                claimed_by,
510                name,
511            } => write!(
512                f,
513                "7z entry is a {} but its {} says {}: {name}",
514                native.noun(),
515                claimed_by.noun(),
516                native.opposite()
517            ),
518            Self::ReservedDeviceName { component } => {
519                write!(f, "Windows reserved device name: {component}")
520            }
521            Self::TrailingDotOrSpace { component } => {
522                write!(f, "path component ends with '.' or ' ': {component}")
523            }
524            Self::StreamSeparator { component } => {
525                write!(f, "path component contains ':': {component}")
526            }
527            Self::PathDepth { depth, max } => {
528                write!(f, "path depth {depth} exceeds maximum {max}")
529            }
530            Self::SymlinkTargetDepth { depth, max } => {
531                write!(f, "symlink target depth {depth} exceeds maximum {max}")
532            }
533            Self::LinkTargetEmpty(kind) => write!(f, "{kind} target is empty"),
534            Self::LinkTargetNul(kind) => write!(f, "{kind} target contains null bytes"),
535            Self::LinkTargetBannedComponent { component } => {
536                write!(f, "symlink target contains banned component: {component}")
537            }
538            Self::LinkTargetTooLarge { size, max } => {
539                write!(f, "symlink target too large: {size} bytes (max {max})")
540            }
541            Self::LinkTargetMissing(kind) => write!(f, "{kind} target is missing"),
542            Self::LinkTargetUnread(kind) => {
543                write!(f, "{kind} target was not read, so it cannot be validated")
544            }
545            Self::LinkTargetUnreadable(kind) => write!(
546                f,
547                "{kind} target could not be read, so it cannot be validated"
548            ),
549            Self::ReparsePointTarget { name } => write!(
550                f,
551                "symlink detected in 7z archive: {name} (Windows reparse point attribute set). \
552                 Its target cannot be read due to sevenz-rust2 API limitations."
553            ),
554            Self::LinksNotAllowed(kind) => write!(f, "{kind}s not allowed"),
555            Self::SymlinkComponent { walked } => {
556                write!(f, "path component is a symlink: {walked}")
557            }
558            Self::SymlinkParent { entry, parent } => write!(
559                f,
560                "refusing to create {entry} under the existing symlink at {parent}"
561            ),
562            Self::ReplacesSymlink { rel } => {
563                write!(f, "refusing to replace the existing symlink at {rel}")
564            }
565            Self::SpecialEntry { kind, name: None } => {
566                write!(f, "{} entries not supported", kind.noun())
567            }
568            Self::SpecialEntry {
569                kind,
570                name: Some(name),
571            } => write!(f, "{} entries not supported: {name}", kind.noun()),
572            Self::UnsupportedTarType { kind } => write!(f, "unsupported entry type: {kind}"),
573            Self::UndefinedUnixType { bits, name } => write!(
574                f,
575                "7z entry has an undefined Unix file type ({bits:#x}): {name}"
576            ),
577            Self::RootEntryNotDirectory => {
578                f.write_str("archive root entry '.' must be a directory")
579            }
580            Self::RootEntryNotDirectoryOrEmptyFile => {
581                f.write_str("archive root entry '.' must be a directory or an empty regular file")
582            }
583            Self::EncryptedArchive => f.write_str(
584                "archive is encrypted (password-protected). Encrypted archives are not \
585                 supported; decrypt the archive externally and try again.",
586            ),
587            Self::EncryptedEntry { name } => write!(f, "encrypted entry detected: {name}"),
588            Self::UnsupportedCompressionMethod { method } => {
589                write!(f, "unsupported compression method: {method}")
590            }
591            Self::SolidArchive => {
592                f.write_str("solid 7z archives are not allowed (enable allow_solid_archives)")
593            }
594            Self::DeclaredSizeExceeded { declared } => write!(
595                f,
596                "decompressed size exceeded the declared uncompressed size of {declared} bytes"
597            ),
598            Self::DeclaredSizeMismatch { declared, actual } => write!(
599                f,
600                "decompressed size ({actual} bytes) does not match the declared uncompressed \
601                 size ({declared} bytes)"
602            ),
603            Self::HardlinkTargetChanged => {
604                f.write_str("hardlink target changed while it was being copied")
605            }
606            Self::TarMetadataBudget { limit } => fmt_tar_read_budget(f, *limit),
607            Self::TarSyntheticBudget { limit } => fmt_tar_synthetic_budget(f, *limit),
608            Self::SymlinksUnsupported => f.write_str("symlinks are not supported on this platform"),
609            Self::ConflictUnlessSkipped { rel, cause } => write!(
610                f,
611                "extraction can fail at {rel} unless duplicates are skipped: {cause}"
612            ),
613            Self::ConflictFails { rel, cause } => {
614                write!(f, "extraction fails at {rel}: {cause}")
615            }
616            Self::SourceOutsideRoot { path, root } => {
617                write!(f, "path {path} is not under root directory: {root}")
618            }
619        }
620    }
621}
622
623#[cfg(test)]
624mod tests {
625    use super::*;
626
627    fn text(s: &str) -> Box<str> {
628        s.into()
629    }
630
631    #[expect(
632        clippy::too_many_lines,
633        reason = "a table with one row per Violation kind"
634    )]
635    fn one_of_each() -> Vec<(Violation, SecurityViolationSubCode, Option<PolicySetting>)> {
636        use SecurityViolationSubCode as C;
637        let link = LinkKind::Symlink;
638        vec![
639            (Violation::EmptyPath, C::PathName, None),
640            (Violation::NulInPath { path: text("p") }, C::PathName, None),
641            (Violation::NulInPathArgument, C::PathName, None),
642            (Violation::PathTooLong { len: 2, max: 1 }, C::PathName, None),
643            (
644                Violation::BannedComponent {
645                    component: text("c"),
646                },
647                C::PathName,
648                Some(PolicySetting::BannedComponents),
649            ),
650            (
651                Violation::UnsafeComponent {
652                    hazard: PortableHazard::Backslash,
653                    model: PathModel::Portable,
654                    component: text("c"),
655                },
656                C::PathName,
657                None,
658            ),
659            (
660                Violation::ReservedDeviceName {
661                    component: text("c"),
662                },
663                C::PathName,
664                Some(PolicySetting::WindowsReservedNames),
665            ),
666            (
667                Violation::TrailingDotOrSpace {
668                    component: text("c"),
669                },
670                C::PathName,
671                None,
672            ),
673            (
674                Violation::StreamSeparator {
675                    component: text("c"),
676                },
677                C::PathName,
678                None,
679            ),
680            (
681                Violation::PathDepth { depth: 2, max: 1 },
682                C::PathDepth,
683                Some(PolicySetting::MaxPathDepth),
684            ),
685            (
686                Violation::SymlinkTargetDepth { depth: 2, max: 1 },
687                C::PathDepth,
688                Some(PolicySetting::MaxPathDepth),
689            ),
690            (Violation::LinkTargetEmpty(link), C::LinkTarget, None),
691            (Violation::LinkTargetNul(link), C::LinkTarget, None),
692            (
693                Violation::LinkTargetBannedComponent {
694                    component: text("c"),
695                },
696                C::LinkTarget,
697                Some(PolicySetting::BannedComponents),
698            ),
699            (
700                Violation::LinkTargetTooLarge { size: 2, max: 1 },
701                C::LinkTarget,
702                None,
703            ),
704            (Violation::LinkTargetMissing(link), C::LinkTarget, None),
705            (Violation::LinkTargetUnread(link), C::LinkTarget, None),
706            (Violation::LinkTargetUnreadable(link), C::LinkTarget, None),
707            (
708                Violation::ReparsePointTarget { name: text("n") },
709                C::LinkTarget,
710                None,
711            ),
712            (
713                Violation::LinksNotAllowed(LinkKind::Symlink),
714                C::LinkPolicy,
715                Some(PolicySetting::Symlinks),
716            ),
717            (
718                Violation::LinksNotAllowed(LinkKind::Hardlink),
719                C::LinkPolicy,
720                Some(PolicySetting::Hardlinks),
721            ),
722            (
723                Violation::SymlinkComponent { walked: text("w") },
724                C::ExistingSymlink,
725                Some(PolicySetting::Symlinks),
726            ),
727            (
728                Violation::SymlinkParent {
729                    entry: text("e"),
730                    parent: text("p"),
731                },
732                C::ExistingSymlink,
733                None,
734            ),
735            (
736                Violation::ReplacesSymlink { rel: text("r") },
737                C::ExistingSymlink,
738                None,
739            ),
740            (
741                Violation::SpecialEntry {
742                    kind: SpecialFile::Fifo,
743                    name: None,
744                },
745                C::EntryType,
746                None,
747            ),
748            (
749                Violation::UnsupportedTarType { kind: text("k") },
750                C::EntryType,
751                None,
752            ),
753            (
754                Violation::UndefinedUnixType {
755                    bits: 1,
756                    name: text("n"),
757                },
758                C::EntryType,
759                None,
760            ),
761            (
762                Violation::KindContradiction {
763                    native: NativeKind::File,
764                    claimed_by: KindSource::UnixMode,
765                    name: text("n"),
766                },
767                C::EntryType,
768                None,
769            ),
770            (Violation::RootEntryNotDirectory, C::RootEntry, None),
771            (
772                Violation::RootEntryNotDirectoryOrEmptyFile,
773                C::RootEntry,
774                None,
775            ),
776            (Violation::EncryptedArchive, C::Encrypted, None),
777            (
778                Violation::EncryptedEntry { name: text("n") },
779                C::Encrypted,
780                None,
781            ),
782            (
783                Violation::UnsupportedCompressionMethod { method: text("m") },
784                C::CompressionMethod,
785                None,
786            ),
787            (
788                Violation::SolidArchive,
789                C::SolidArchive,
790                Some(PolicySetting::SolidArchives),
791            ),
792            (
793                Violation::DeclaredSizeExceeded { declared: 1 },
794                C::DeclaredSize,
795                None,
796            ),
797            (
798                Violation::DeclaredSizeMismatch {
799                    declared: 1,
800                    actual: 2,
801                },
802                C::DeclaredSize,
803                None,
804            ),
805            (Violation::HardlinkTargetChanged, C::ConcurrentChange, None),
806            (
807                Violation::TarMetadataBudget { limit: 1 },
808                C::TarMetadata,
809                Some(PolicySetting::MaxTarMetadataBytes),
810            ),
811            (
812                Violation::TarSyntheticBudget { limit: 1 },
813                C::TarMetadata,
814                None,
815            ),
816            (Violation::SymlinksUnsupported, C::Platform, None),
817            (
818                Violation::ConflictUnlessSkipped {
819                    rel: text("r"),
820                    cause: text("c"),
821                },
822                C::OutputConflict,
823                None,
824            ),
825            (
826                Violation::ConflictFails {
827                    rel: text("r"),
828                    cause: text("c"),
829                },
830                C::OutputConflict,
831                None,
832            ),
833            (
834                Violation::SourceOutsideRoot {
835                    path: text("p"),
836                    root: text("r"),
837                },
838                C::SourcePath,
839                None,
840            ),
841        ]
842    }
843
844    #[test]
845    fn test_every_kind_has_family_setting_and_text() {
846        for (kind, code, setting) in one_of_each() {
847            assert_eq!(kind.sub_code(), code, "{kind:?}");
848            assert_eq!(kind.relaxable_by(), setting, "{kind:?}");
849            assert!(!kind.to_string().is_empty(), "{kind:?}");
850        }
851    }
852
853    /// The text of each `one_of_each` row, in order; byte-identical to the
854    /// pre-typing messages (verified by the security audit), and callers match
855    /// on them, so a wording change must be a deliberate edit here.
856    const EXPECTED_TEXT: [&str; 43] = [
857        "empty path not allowed",
858        "path contains null bytes: p",
859        "path contains null bytes - potential security issue",
860        "path exceeds maximum length of 1 bytes (got 2 bytes)",
861        "banned path component: c",
862        "path component is not portable (contains a backslash): c",
863        "Windows reserved device name: c",
864        "path component ends with '.' or ' ': c",
865        "path component contains ':': c",
866        "path depth 2 exceeds maximum 1",
867        "symlink target depth 2 exceeds maximum 1",
868        "symlink target is empty",
869        "symlink target contains null bytes",
870        "symlink target contains banned component: c",
871        "symlink target too large: 2 bytes (max 1)",
872        "symlink target is missing",
873        "symlink target was not read, so it cannot be validated",
874        "symlink target could not be read, so it cannot be validated",
875        "symlink detected in 7z archive: n (Windows reparse point attribute set). Its target cannot be read due to sevenz-rust2 API limitations.",
876        "symlinks not allowed",
877        "hardlinks not allowed",
878        "path component is a symlink: w",
879        "refusing to create e under the existing symlink at p",
880        "refusing to replace the existing symlink at r",
881        "FIFO entries not supported",
882        "unsupported entry type: k",
883        "7z entry has an undefined Unix file type (0x1): n",
884        "7z entry is a file but its Unix mode says directory: n",
885        "archive root entry '.' must be a directory",
886        "archive root entry '.' must be a directory or an empty regular file",
887        "archive is encrypted (password-protected). Encrypted archives are not supported; decrypt the archive externally and try again.",
888        "encrypted entry detected: n",
889        "unsupported compression method: m",
890        "solid 7z archives are not allowed (enable allow_solid_archives)",
891        "decompressed size exceeded the declared uncompressed size of 1 bytes",
892        "decompressed size (2 bytes) does not match the declared uncompressed size (1 bytes)",
893        "hardlink target changed while it was being copied",
894        "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)",
895        "TAR cumulative synthetic-byte drain budget exceeded: more than 1 bytes of synthesized (unbacked) padding drained from unread entries across this archive",
896        "symlinks are not supported on this platform",
897        "extraction can fail at r unless duplicates are skipped: c",
898        "extraction fails at r: c",
899        "path p is not under root directory: r",
900    ];
901
902    #[test]
903    fn test_every_kind_renders_its_pinned_text() {
904        let kinds = one_of_each();
905        assert_eq!(kinds.len(), EXPECTED_TEXT.len());
906        for ((kind, ..), expected) in kinds.iter().zip(EXPECTED_TEXT) {
907            assert_eq!(kind.to_string(), expected, "{kind:?}");
908        }
909    }
910
911    #[test]
912    fn test_every_family_has_a_kind() {
913        let seen: Vec<_> = one_of_each().iter().map(|(k, ..)| k.sub_code()).collect();
914        for code in SecurityViolationSubCode::ALL {
915            assert!(
916                *code == SecurityViolationSubCode::TarTrailer || seen.contains(code),
917                "{code} has no Violation kind"
918            );
919        }
920    }
921
922    #[test]
923    fn test_link_policy_text_names_the_link_kind() {
924        assert_eq!(
925            Violation::LinksNotAllowed(LinkKind::Symlink).to_string(),
926            "symlinks not allowed"
927        );
928        assert_eq!(
929            Violation::LinksNotAllowed(LinkKind::Hardlink).to_string(),
930            "hardlinks not allowed"
931        );
932    }
933}