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;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SpecialFile {
Fifo,
CharDevice,
BlockDevice,
Socket,
}
impl SpecialFile {
#[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",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PortableHazard {
NotUtf8,
Backslash,
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",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TarTypeflag(u8);
impl TarTypeflag {
#[must_use]
pub const fn new(byte: u8) -> Self {
Self(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)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NativeKind {
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",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum KindSource {
UnixMode,
WindowsAttribute,
}
impl KindSource {
const fn noun(self) -> &'static str {
match self {
Self::UnixMode => "Unix mode",
Self::WindowsAttribute => "Windows attributes",
}
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EncryptionRefusal {
PasswordRequired => "password_required",
WrongPassword => "wrong_password",
AuthenticationFailed => "authentication_failed",
WrongPasswordOrCorrupt => "wrong_password_or_corrupt",
WeakEncryptionRefused => "weak_encryption_refused",
KdfCostExceeded => "kdf_cost_exceeded",
UnusablePassword => "unusable_password",
}
}
impl EncryptionRefusal {
#[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",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Violation {
EmptyPath,
NulInPath {
path: Box<str>,
},
NulInPathArgument,
PathTooLong {
len: usize,
max: usize,
},
BannedComponent {
component: Box<str>,
},
UnsafeComponent {
hazard: PortableHazard,
model: PathModel,
component: Box<str>,
},
ReservedDeviceName {
component: Box<str>,
},
TrailingDotOrSpace {
component: Box<str>,
},
ShortNameAlias {
component: Box<str>,
},
StreamSeparator {
component: Box<str>,
},
PathDepth {
depth: usize,
max: usize,
},
SymlinkTargetDepth {
depth: usize,
max: usize,
},
LinkTargetEmpty(LinkKind),
LinkTargetNul(LinkKind),
LinkTargetBannedComponent {
kind: LinkKind,
component: Box<str>,
},
LinkTargetTooLarge {
size: u64,
max: u64,
},
LinkTargetMissing(LinkKind),
LinkTargetUnread(LinkKind),
LinkTargetUnreadable(LinkKind),
ReparsePointTarget {
name: Box<str>,
},
LinksNotAllowed(LinkKind),
SymlinkComponent {
walked: Box<str>,
by: super::types::OccupiedBy,
},
SymlinkParent {
entry: Box<str>,
parent: Box<str>,
by: super::types::OccupiedBy,
},
DestinationChanged,
ReplacesSymlink {
rel: Box<str>,
by: super::types::OccupiedBy,
},
SpecialEntry {
kind: SpecialFile,
name: Option<Box<str>>,
},
UnsupportedTarType {
typeflag: TarTypeflag,
},
UndefinedUnixType {
bits: u8,
name: Box<str>,
},
KindContradiction {
native: NativeKind,
claimed_by: KindSource,
name: Box<str>,
},
RootEntryNotDirectory,
RootEntryNotDirectoryOrEmptyFile,
Encrypted {
reason: EncryptionRefusal,
name: Option<Box<str>>,
},
UnsupportedCompressionMethod {
method: Box<str>,
},
SolidArchive,
DeclaredSizeExceeded {
declared: u64,
},
DeclaredSizeMismatch {
declared: u64,
actual: u64,
},
HardlinkTargetChanged,
TarMetadataBudget {
limit: u64,
},
TarSyntheticBudget {
limit: u64,
},
SymlinksUnsupported,
ConflictUnlessSkipped {
rel: Box<str>,
cause: Box<str>,
},
ConflictFails {
rel: Box<str>,
cause: Box<str>,
},
HardlinkTargetNotExtracted {
link: Box<str>,
target: Box<str>,
},
HardlinkTargetAmbiguous {
link: Box<str>,
target: Box<str>,
},
LinkUnderFlatten {
kind: LinkKind,
name: Box<str>,
},
SourceOutsideRoot {
path: Box<str>,
root: Box<str>,
},
RepeatedPath {
path: Box<str>,
earlier: ManifestEntryType,
later: ManifestEntryType,
},
}
impl Violation {
#[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,
}
}
#[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:?}");
}
}
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"
);
}
}