use super::config_error::ConfigSetting;
use super::redaction::sanitize_io_error_for_error;
use super::types::ArchiveError;
use super::types::PartialWrites;
use super::types::PolicySetting;
use super::types::QuotaKind;
use super::types::ReaderFormatError;
use super::types::ZipBombScope;
use crate::ExtractionReport;
use crate::closed_enum::closed_enum;
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
PathTraversal => "PATH_TRAVERSAL",
SymlinkEscape => "SYMLINK_ESCAPE",
HardlinkEscape => "HARDLINK_ESCAPE",
ZipBomb => "ZIP_BOMB",
ZipInconsistency => "ZIP_INCONSISTENCY",
QuotaExceeded => "QUOTA_EXCEEDED",
SecurityViolation => "SECURITY_VIOLATION",
InvalidArchive => "INVALID_ARCHIVE",
IoError => "IO_ERROR",
InvalidPermissions => "INVALID_PERMISSIONS",
SourceNotFound => "SOURCE_NOT_FOUND",
SourceNotAccessible => "SOURCE_NOT_ACCESSIBLE",
OutputExists => "OUTPUT_EXISTS",
InvalidCompressionLevel => "INVALID_COMPRESSION_LEVEL",
UnknownFormat => "UNKNOWN_FORMAT",
InvalidConfiguration => "INVALID_CONFIGURATION",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum InvalidArchiveSubCode {
TarAmbiguity => "TAR_AMBIGUITY",
TarTrailer => "TAR_TRAILER",
LinkTarget => "LINK_TARGET",
DuplicateEntry => "DUPLICATE_ENTRY",
EntryName => "ENTRY_NAME",
DeclaredSize => "DECLARED_SIZE",
Integrity => "INTEGRITY",
ZipReader => "ZIP_READER",
TarReader => "TAR_READER",
SevenZReader => "SEVENZ_READER",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SecurityViolationSubCode {
PathName => "PATH_NAME",
PathDepth => "PATH_DEPTH",
LinkTarget => "LINK_TARGET",
LinkPolicy => "LINK_POLICY",
ExistingSymlink => "EXISTING_SYMLINK",
EntryType => "ENTRY_TYPE",
RootEntry => "ROOT_ENTRY",
Encrypted => "ENCRYPTED",
CompressionMethod => "COMPRESSION_METHOD",
SolidArchive => "SOLID_ARCHIVE",
DeclaredSize => "DECLARED_SIZE",
ConcurrentChange => "CONCURRENT_CHANGE",
TarMetadata => "TAR_METADATA",
TarTrailer => "TAR_TRAILER",
Platform => "PLATFORM",
OutputConflict => "OUTPUT_CONFLICT",
SourcePath => "SOURCE_PATH",
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SubCode {
InvalidArchive(InvalidArchiveSubCode),
SecurityViolation(SecurityViolationSubCode),
Quota(QuotaKind),
ZipBomb(ZipBombScope),
}
impl SubCode {
pub const QUOTA_ALL: &'static [Self] = &[
Self::Quota(QuotaKind::FileCount),
Self::Quota(QuotaKind::TotalSize),
Self::Quota(QuotaKind::FileSize),
Self::Quota(QuotaKind::IntegerOverflow),
Self::Quota(QuotaKind::DecoderMemory),
Self::Quota(QuotaKind::CompressedMembers),
Self::Quota(QuotaKind::TreeNodes),
Self::Quota(QuotaKind::SinkCapacity),
Self::Quota(QuotaKind::SolidBlockMemory),
];
pub const ZIP_BOMB_ALL: &'static [Self] = &[
Self::ZipBomb(ZipBombScope::Entry),
Self::ZipBomb(ZipBombScope::SolidBlock),
Self::ZipBomb(ZipBombScope::SkippedEntries),
];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::InvalidArchive(code) => code.as_str(),
Self::SecurityViolation(code) => code.as_str(),
Self::Quota(kind) => quota_sub_code(kind),
Self::ZipBomb(scope) => zip_bomb_sub_code(scope),
}
}
}
const fn quota_sub_code(kind: QuotaKind) -> &'static str {
match kind {
QuotaKind::FileCount => "FILE_COUNT",
QuotaKind::TotalSize => "TOTAL_SIZE",
QuotaKind::FileSize => "FILE_SIZE",
QuotaKind::IntegerOverflow => "INTEGER_OVERFLOW",
QuotaKind::DecoderMemory => "DECODER_MEMORY",
QuotaKind::CompressedMembers => "COMPRESSED_MEMBERS",
QuotaKind::TreeNodes => "TREE_NODES",
QuotaKind::SinkCapacity => "SINK_CAPACITY",
QuotaKind::SolidBlockMemory => "SOLID_BLOCK_MEMORY",
}
}
const fn zip_bomb_sub_code(scope: ZipBombScope) -> &'static str {
match scope {
ZipBombScope::Entry => "ENTRY",
ZipBombScope::SolidBlock => "SOLID_BLOCK",
ZipBombScope::SkippedEntries => "SKIPPED_ENTRIES",
}
}
impl std::fmt::Display for SubCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FfiKind {
PathTraversal,
SymlinkEscape,
HardlinkEscape,
#[non_exhaustive]
ZipBomb {
scope: ZipBombScope,
},
ZipInconsistency,
#[non_exhaustive]
QuotaExceeded {
kind: QuotaKind,
},
#[non_exhaustive]
SecurityViolation {
relaxable_by: Option<PolicySetting>,
sub_code: SecurityViolationSubCode,
},
#[non_exhaustive]
InvalidArchive {
sub_code: Option<InvalidArchiveSubCode>,
},
Io(std::io::ErrorKind),
InvalidPermissions,
SourceNotFound,
SourceNotAccessible,
OutputExists,
InvalidCompressionLevel,
UnknownFormat,
#[non_exhaustive]
InvalidConfiguration {
setting: Option<ConfigSetting>,
},
}
impl FfiKind {
#[must_use]
pub const fn relaxable_by(&self) -> Option<PolicySetting> {
match self {
Self::SecurityViolation { relaxable_by, .. } => *relaxable_by,
Self::PathTraversal
| Self::SymlinkEscape
| Self::HardlinkEscape
| Self::ZipBomb { .. }
| Self::ZipInconsistency
| Self::QuotaExceeded { .. }
| Self::InvalidArchive { .. }
| Self::Io(_)
| Self::InvalidPermissions
| Self::SourceNotFound
| Self::SourceNotAccessible
| Self::OutputExists
| Self::InvalidCompressionLevel
| Self::UnknownFormat
| Self::InvalidConfiguration { .. } => None,
}
}
#[must_use]
pub const fn setting(&self) -> Option<ConfigSetting> {
match self {
Self::InvalidConfiguration { setting } => *setting,
_ => None,
}
}
#[must_use]
pub const fn sub_code(&self) -> Option<SubCode> {
match self {
Self::SecurityViolation { sub_code, .. } => Some(SubCode::SecurityViolation(*sub_code)),
Self::InvalidArchive {
sub_code: Some(code),
} => Some(SubCode::InvalidArchive(*code)),
Self::ZipBomb { scope } => Some(SubCode::ZipBomb(*scope)),
Self::QuotaExceeded { kind } => Some(SubCode::Quota(*kind)),
Self::InvalidArchive { sub_code: None }
| Self::PathTraversal
| Self::SymlinkEscape
| Self::HardlinkEscape
| Self::ZipInconsistency
| Self::Io(_)
| Self::InvalidPermissions
| Self::SourceNotFound
| Self::SourceNotAccessible
| Self::OutputExists
| Self::InvalidCompressionLevel
| Self::UnknownFormat
| Self::InvalidConfiguration { .. } => None,
}
}
#[must_use]
pub const fn code(&self) -> ErrorCode {
match self {
Self::PathTraversal => ErrorCode::PathTraversal,
Self::SymlinkEscape => ErrorCode::SymlinkEscape,
Self::HardlinkEscape => ErrorCode::HardlinkEscape,
Self::ZipBomb { .. } => ErrorCode::ZipBomb,
Self::ZipInconsistency => ErrorCode::ZipInconsistency,
Self::QuotaExceeded { .. } => ErrorCode::QuotaExceeded,
Self::SecurityViolation { .. } => ErrorCode::SecurityViolation,
Self::InvalidArchive { .. } => ErrorCode::InvalidArchive,
Self::Io(_) => ErrorCode::IoError,
Self::InvalidPermissions => ErrorCode::InvalidPermissions,
Self::SourceNotFound => ErrorCode::SourceNotFound,
Self::SourceNotAccessible => ErrorCode::SourceNotAccessible,
Self::OutputExists => ErrorCode::OutputExists,
Self::InvalidCompressionLevel => ErrorCode::InvalidCompressionLevel,
Self::UnknownFormat => ErrorCode::UnknownFormat,
Self::InvalidConfiguration { .. } => ErrorCode::InvalidConfiguration,
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PartialOutcome {
Kept(ExtractionReport),
RolledBack,
Discarded,
}
impl PartialOutcome {
#[must_use]
pub const fn writes(&self) -> PartialWrites {
match self {
Self::Kept(_) => PartialWrites::Kept,
Self::RolledBack => PartialWrites::RolledBack,
Self::Discarded => PartialWrites::Discarded,
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct FfiErrorMessage {
pub kind: FfiKind,
pub description: String,
pub partial: Option<PartialOutcome>,
pub source_fault: Option<FfiSourceFault>,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct FfiSourceFault {
pub raw_os_error: Option<i32>,
pub text: String,
pub name: String,
}
impl FfiErrorMessage {
const fn new(kind: FfiKind, description: String) -> Self {
Self {
kind,
description,
partial: None,
source_fault: None,
}
}
}
impl ArchiveError {
#[must_use]
pub fn into_ffi_message(self) -> FfiErrorMessage {
if let Self::PartialExtraction(partial) = self {
let (source, report, writes) = partial.into_parts();
let mut msg = source.into_ffi_message();
msg.partial = Some(match writes {
PartialWrites::Kept => PartialOutcome::Kept(report),
PartialWrites::RolledBack => PartialOutcome::RolledBack,
PartialWrites::Discarded => PartialOutcome::Discarded,
});
return msg;
}
let mut msg = FfiErrorMessage::new(self.ffi_kind(), self.ffi_description());
if let Self::SourceNotAccessible { error, .. } = &self {
msg.source_fault = Some(FfiSourceFault {
raw_os_error: error.raw_os_error(),
text: sanitize_io_error_for_error(error),
name: self.redacted_path().unwrap_or_default(),
});
}
msg
}
#[must_use]
pub fn ffi_kind(&self) -> FfiKind {
match self {
Self::PathTraversal { .. } => FfiKind::PathTraversal,
Self::SymlinkEscape { .. } => FfiKind::SymlinkEscape,
Self::HardlinkEscape { .. } => FfiKind::HardlinkEscape,
Self::ZipBomb(details) => FfiKind::ZipBomb {
scope: details.scope(),
},
Self::ZipInconsistency(_) => FfiKind::ZipInconsistency,
Self::QuotaExceeded { resource } => FfiKind::QuotaExceeded {
kind: resource.kind(),
},
Self::SecurityViolation { kind } => FfiKind::SecurityViolation {
relaxable_by: kind.relaxable_by(),
sub_code: kind.sub_code(),
},
Self::InvalidArchive(m) => FfiKind::InvalidArchive {
sub_code: m.sub_code(),
},
Self::TarAmbiguity(_) => FfiKind::InvalidArchive {
sub_code: Some(InvalidArchiveSubCode::TarAmbiguity),
},
Self::TarTrailer(refusal) => {
if refusal.is_policy_refusal() {
FfiKind::SecurityViolation {
relaxable_by: refusal.relaxable_by(),
sub_code: SecurityViolationSubCode::TarTrailer,
}
} else {
FfiKind::InvalidArchive {
sub_code: Some(InvalidArchiveSubCode::TarTrailer),
}
}
}
Self::Io(io_err) => FfiKind::Io(io_err.kind()),
Self::InvalidPermissions { .. } => FfiKind::InvalidPermissions,
Self::SourceNotFound { .. } => FfiKind::SourceNotFound,
Self::SourceNotAccessible { .. } => FfiKind::SourceNotAccessible,
Self::OutputExists { .. } => FfiKind::OutputExists,
Self::InvalidCompressionLevel { .. } => FfiKind::InvalidCompressionLevel,
Self::UnknownFormat { .. } | Self::ReaderFormat(ReaderFormatError::Unrecognized) => {
FfiKind::UnknownFormat
}
Self::InvalidConfiguration { setting, .. } => FfiKind::InvalidConfiguration {
setting: Some(*setting),
},
Self::ReaderFormat(_) => FfiKind::InvalidConfiguration { setting: None },
Self::PartialExtraction(partial) => partial.cause().ffi_kind(),
}
}
fn ffi_description(&self) -> String {
let path = self
.redacted_path()
.unwrap_or_else(|| "<unknown>".to_string());
match self {
Self::PathTraversal { .. } => format!("path traversal detected: {path}"),
Self::SymlinkEscape { .. } => {
format!("symlink target outside extraction directory: {path}")
}
Self::HardlinkEscape { .. } => {
format!("hardlink target outside extraction directory: {path}")
}
Self::ZipBomb(_)
| Self::ZipInconsistency(_)
| Self::TarAmbiguity(_)
| Self::TarTrailer(_)
| Self::SecurityViolation { .. } => self.to_string(),
Self::QuotaExceeded { resource } => resource.to_string(),
Self::InvalidArchive(reason) => format!("invalid archive: {reason}"),
Self::Io(io_err) => sanitize_io_error_for_error(io_err),
Self::InvalidPermissions { mode, .. } => {
format!("invalid permissions for {path}: {:#o}", mode.get())
}
Self::SourceNotFound { .. } => format!("source path not found: {path}"),
Self::SourceNotAccessible { error, .. } => {
format!(
"source path is not accessible: {path}: {}",
sanitize_io_error_for_error(error)
)
}
Self::OutputExists { .. } => format!("output file already exists: {path}"),
Self::InvalidCompressionLevel { level } => {
format!("invalid compression level {level}, must be 1-9")
}
Self::UnknownFormat { .. } => {
format!("cannot determine archive format from: {path}")
}
Self::InvalidConfiguration { setting, problem } => format!(
"invalid configuration: {}",
super::config_error::message(*setting, problem)
),
Self::ReaderFormat(reason) => reason.to_string(),
Self::PartialExtraction(partial) => partial.cause().ffi_description(),
}
}
#[must_use]
pub fn error_code(&self) -> ErrorCode {
self.ffi_kind().code()
}
}
#[cfg(test)]
mod tests {
use super::super::config_error::ConfigProblem;
use super::super::types::QuotaResource;
use super::super::types::ZipBombDetails;
use super::super::types::ZipBombScope;
use super::super::violation::Violation;
use super::*;
use std::collections::HashSet;
use crate::security::Compressed;
use crate::security::Uncompressed;
use std::assert_matches;
use std::path::PathBuf;
#[test]
fn test_ffi_kind_accessors_expose_payload() {
let kind = FfiKind::SecurityViolation {
relaxable_by: Some(PolicySetting::Symlinks),
sub_code: SecurityViolationSubCode::TarTrailer,
};
assert_eq!(kind.relaxable_by(), Some(PolicySetting::Symlinks));
assert_eq!(
kind.sub_code(),
Some(SubCode::SecurityViolation(
SecurityViolationSubCode::TarTrailer
))
);
let kind = FfiKind::InvalidArchive {
sub_code: Some(InvalidArchiveSubCode::TarAmbiguity),
};
assert_eq!(kind.relaxable_by(), None);
assert_eq!(kind.sub_code().map(SubCode::as_str), Some("TAR_AMBIGUITY"));
assert_eq!(
FfiKind::ZipBomb {
scope: ZipBombScope::Entry
}
.sub_code()
.map(SubCode::as_str),
Some("ENTRY")
);
}
#[test]
fn test_attacker_path_never_redacted() {
let error = ArchiveError::PathTraversal {
path: PathBuf::from("../../etc/passwd"),
};
let msg = error.into_ffi_message();
assert!(msg.description.contains("../../etc/passwd"));
}
#[test]
#[cfg(not(debug_assertions))]
fn test_host_path_redacted_in_release() {
let error = ArchiveError::SourceNotFound {
path: PathBuf::from("/srv/secret/app/x.txt"),
};
let msg = error.into_ffi_message();
assert!(msg.description.contains("x.txt"));
assert!(!msg.description.contains("/srv/secret"));
}
#[test]
#[cfg(not(debug_assertions))]
fn test_io_error_redacted_in_release() {
let error = ArchiveError::Io(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"directory is not writable: /srv/secret/app/private-output",
));
let msg = error.into_ffi_message();
assert!(!msg.description.contains("/srv/secret"));
}
#[test]
fn test_error_codes_match() {
let test_cases = vec![
(
ArchiveError::PathTraversal {
path: PathBuf::from("test"),
},
ErrorCode::PathTraversal,
),
(
ArchiveError::SymlinkEscape {
path: PathBuf::from("test"),
},
ErrorCode::SymlinkEscape,
),
(
ArchiveError::ZipBomb(ZipBombDetails::new(
ZipBombScope::Entry,
Compressed(100),
Uncompressed(10000),
)),
ErrorCode::ZipBomb,
),
];
for (error, expected_code) in test_cases {
assert_eq!(error.error_code(), expected_code);
assert_eq!(error.into_ffi_message().kind.code(), expected_code);
}
}
fn one_error_per_variant() -> Vec<ArchiveError> {
vec![
ArchiveError::PathTraversal {
path: PathBuf::from("test"),
},
ArchiveError::SymlinkEscape {
path: PathBuf::from("test"),
},
ArchiveError::HardlinkEscape {
path: PathBuf::from("test"),
},
ArchiveError::ZipBomb(ZipBombDetails::new(
ZipBombScope::Entry,
Compressed(100),
Uncompressed(10000),
)),
ArchiveError::ZipInconsistency(
super::super::zip_inconsistency::ZipInconsistency::OverlappingEntries,
),
ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow,
},
ArchiveError::from(Violation::EncryptedArchive),
ArchiveError::unclassified("test"),
ArchiveError::Io(std::io::Error::other("test")),
ArchiveError::InvalidPermissions {
path: PathBuf::from("test"),
mode: crate::RawMode::new(0o777),
},
ArchiveError::SourceNotFound {
path: PathBuf::from("test"),
},
ArchiveError::SourceNotAccessible {
path: PathBuf::from("test"),
error: std::io::Error::other("test"),
},
ArchiveError::OutputExists {
path: PathBuf::from("test"),
},
ArchiveError::InvalidCompressionLevel { level: 10 },
ArchiveError::UnknownFormat {
path: PathBuf::from("test"),
},
ArchiveError::InvalidConfiguration {
setting: ConfigSetting::OutputPath,
problem: ConfigProblem::NotSet,
},
]
}
#[test]
fn test_all_error_variants_have_codes() {
for error in one_error_per_variant() {
let code = error.error_code();
let msg = error.into_ffi_message();
assert_eq!(msg.kind.code(), code);
assert!(!msg.description.is_empty());
assert!(msg.partial.is_none());
}
}
#[test]
fn test_kind_code_covers_error_code_all_exactly_once() {
let mut seen: Vec<ErrorCode> = one_error_per_variant()
.into_iter()
.map(|e| e.into_ffi_message().kind.code())
.collect();
seen.sort_by_key(|c| c.as_str());
let mut expected = ErrorCode::ALL.to_vec();
expected.sort_by_key(|c| c.as_str());
assert_eq!(seen, expected);
}
fn every_tar_ambiguity() -> Vec<super::super::tar_ambiguity::TarAmbiguity> {
use super::super::tar_ambiguity::TarAmbiguity as A;
use super::super::tar_ambiguity::TarExtensionKind as Ext;
use super::super::tar_ambiguity::TarHeaderField as Field;
use super::super::tar_ambiguity::TarNonRegularKind as NonRegular;
use super::super::tar_ambiguity::TarPathKey as Key;
let key = || "k".to_string();
vec![
A::MalformedRecord,
A::EmptyKey,
A::OversizedRecord { key: key() },
A::DuplicateRecord { key: key() },
A::UnsupportedRecord { key: key() },
A::InvalidSize,
A::GlobalOverride { key: key() },
A::GlobalTooLarge { size: 2, limit: 1 },
A::LocalBeforeGlobal,
A::LongRecordBeforeGlobal,
A::StackedLongRecord { key: Key::Path },
A::StackedSizeRecord,
A::UnrecognizedHeader { kind: Ext::Pax },
A::SparseEntry,
A::NonCanonicalNumber { field: Field::Size },
A::PrefixWithoutUstar,
A::ChecksumMismatch,
A::DuplicateExtensionHeader { kind: Ext::Pax },
A::WindowMismatch,
A::NonZeroPadding,
A::MalformedLongRecord {
kind: Ext::LongName,
},
A::NonRegularPayload {
kind: NonRegular::Directory,
size: 1,
path: "d".into(),
},
A::DirectoryNamedPayload {
size: 1,
path: "d/".into(),
},
]
}
#[test]
fn test_ffi_kind_sub_code_table() {
use super::super::tar_trailer::TarTrailerRefusal as R;
use super::super::tar_trailer::TrailerCorruption;
let ambiguity = Some(InvalidArchiveSubCode::TarAmbiguity);
let trailer = Some(InvalidArchiveSubCode::TarTrailer);
let invalid = |sub_code| FfiKind::InvalidArchive { sub_code };
for variant in every_tar_ambiguity() {
let error = ArchiveError::TarAmbiguity(variant);
assert_eq!(error.ffi_kind(), invalid(ambiguity), "{error:?}");
}
for refusal in [
R::Truncated,
R::Corrupt {
cause: TrailerCorruption::Decoder,
detail: "d".into(),
},
R::Corrupt {
cause: TrailerCorruption::TrailingData,
detail: "d".into(),
},
] {
let error = ArchiveError::TarTrailer(refusal);
assert_eq!(error.ffi_kind(), invalid(trailer), "{error:?}");
}
assert_eq!(
ArchiveError::TarTrailer(R::OverCap { cap: 1 }).ffi_kind(),
FfiKind::SecurityViolation {
relaxable_by: Some(PolicySetting::MaxTarMetadataBytes),
sub_code: SecurityViolationSubCode::TarTrailer,
}
);
assert_eq!(ArchiveError::unclassified("x").ffi_kind(), invalid(None));
assert_eq!(
ArchiveError::from(Violation::EncryptedArchive).ffi_kind(),
FfiKind::SecurityViolation {
relaxable_by: None,
sub_code: SecurityViolationSubCode::Encrypted,
}
);
let wrapped = ArchiveError::PartialExtraction(crate::Partial::new(
ArchiveError::TarAmbiguity(super::super::tar_ambiguity::TarAmbiguity::SparseEntry),
ExtractionReport::default(),
PartialWrites::Kept,
));
assert_eq!(wrapped.ffi_kind(), invalid(ambiguity));
}
#[test]
fn test_partial_extraction_sets_partial() {
let wrap = |writes| {
ArchiveError::PartialExtraction(crate::Partial::new(
ArchiveError::from(Violation::EncryptedArchive),
ExtractionReport::default(),
writes,
))
};
let kept = wrap(PartialWrites::Kept).into_ffi_message();
assert_matches!(kept.partial, Some(PartialOutcome::Kept(_)));
assert_eq!(kept.kind.code(), ErrorCode::SecurityViolation);
let rolled = wrap(PartialWrites::RolledBack).into_ffi_message();
assert_matches!(rolled.partial, Some(PartialOutcome::RolledBack));
let discarded = wrap(PartialWrites::Discarded).into_ffi_message();
assert_matches!(discarded.partial, Some(PartialOutcome::Discarded));
assert_eq!(PartialOutcome::Discarded.writes(), PartialWrites::Discarded);
}
#[test]
fn quota_and_zip_bomb_sub_codes_are_screaming_and_unique() {
let quotas: Vec<_> = QuotaKind::ALL
.iter()
.map(|&kind| SubCode::Quota(kind).as_str())
.collect();
let scopes: Vec<_> = ZipBombScope::ALL
.iter()
.map(|&scope| SubCode::ZipBomb(scope).as_str())
.collect();
for set in ["as, &scopes] {
let unique: HashSet<_> = set.iter().collect();
assert_eq!(unique.len(), set.len(), "{set:?}");
for code in set {
assert!(
code.chars().all(|c| c.is_ascii_uppercase() || c == '_'),
"{code}"
);
}
}
}
#[test]
fn quota_and_zip_bomb_kinds_carry_their_sub_code() {
let quota = ArchiveError::QuotaExceeded {
resource: QuotaResource::SolidBlockMemory {
scope: crate::SolidMemoryScope::Block,
current: 2,
max: 1,
},
};
assert_eq!(
quota.ffi_kind().sub_code(),
Some(SubCode::Quota(QuotaKind::SolidBlockMemory))
);
assert_eq!(
quota.ffi_kind().sub_code().map(SubCode::as_str),
Some("SOLID_BLOCK_MEMORY")
);
}
#[test]
fn the_sub_code_constants_cover_every_kind_and_scope() {
let quotas: Vec<_> = QuotaKind::ALL.iter().map(|&k| SubCode::Quota(k)).collect();
assert_eq!(SubCode::QUOTA_ALL, quotas.as_slice());
let scopes: Vec<_> = ZipBombScope::ALL
.iter()
.map(|&s| SubCode::ZipBomb(s))
.collect();
assert_eq!(SubCode::ZIP_BOMB_ALL, scopes.as_slice());
}
}