use super::redaction::sanitize_io_error_for_error;
use super::types::ArchiveError;
use super::types::PartialWrites;
use super::types::PolicySetting;
use super::types::ReaderFormatError;
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",
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FfiKind {
PathTraversal,
SymlinkEscape,
HardlinkEscape,
ZipBomb,
ZipInconsistency,
QuotaExceeded,
SecurityViolation {
relaxable_by: Option<PolicySetting>,
},
InvalidArchive,
Io(std::io::ErrorKind),
InvalidPermissions,
SourceNotFound,
SourceNotAccessible,
OutputExists,
InvalidCompressionLevel,
UnknownFormat,
InvalidConfiguration,
}
impl FfiKind {
#[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>,
}
impl FfiErrorMessage {
const fn new(kind: FfiKind, description: String) -> Self {
Self {
kind,
description,
partial: None,
}
}
}
impl ArchiveError {
#[must_use]
pub fn into_ffi_message(self) -> FfiErrorMessage {
if let Self::PartialExtraction {
source,
report,
writes,
} = self
{
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;
}
FfiErrorMessage::new(self.ffi_kind(), self.ffi_description())
}
fn ffi_kind(&self) -> FfiKind {
match self {
Self::PathTraversal { .. } => FfiKind::PathTraversal,
Self::SymlinkEscape { .. } => FfiKind::SymlinkEscape,
Self::HardlinkEscape { .. } => FfiKind::HardlinkEscape,
Self::ZipBomb(_) => FfiKind::ZipBomb,
Self::ZipInconsistency(_) => FfiKind::ZipInconsistency,
Self::QuotaExceeded { .. } => FfiKind::QuotaExceeded,
Self::SecurityViolation { relaxable_by, .. } => FfiKind::SecurityViolation {
relaxable_by: *relaxable_by,
},
Self::InvalidArchive(_) => FfiKind::InvalidArchive,
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 { .. } | Self::ReaderFormat(_) => {
FfiKind::InvalidConfiguration
}
Self::PartialExtraction { source, .. } => source.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.to_string(),
Self::QuotaExceeded { resource } => resource.to_string(),
Self::SecurityViolation { reason, .. } => {
format!("operation denied by security policy: {reason}")
}
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}: {mode:#o}")
}
Self::SourceNotFound { .. } => format!("source path not found: {path}"),
Self::SourceNotAccessible { .. } => {
format!("source path is not accessible: {path}")
}
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 { reason } => format!("invalid configuration: {reason}"),
Self::ReaderFormat(reason) => reason.to_string(),
Self::PartialExtraction { source, .. } => source.ffi_description(),
}
}
#[must_use]
pub fn error_code(&self) -> ErrorCode {
self.ffi_kind().code()
}
}
#[cfg(test)]
mod tests {
use super::super::types::QuotaResource;
use super::super::types::ZipBombDetails;
use super::super::types::ZipBombScope;
use super::*;
use std::assert_matches;
use std::path::PathBuf;
#[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, 100, 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, 100, 10000)),
ArchiveError::ZipInconsistency(
super::super::zip_inconsistency::ZipInconsistency::OverlappingEntries,
),
ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow,
},
ArchiveError::violation("test".into()),
ArchiveError::InvalidArchive("test".into()),
ArchiveError::Io(std::io::Error::other("test")),
ArchiveError::InvalidPermissions {
path: PathBuf::from("test"),
mode: 0o777,
},
ArchiveError::SourceNotFound {
path: PathBuf::from("test"),
},
ArchiveError::SourceNotAccessible {
path: PathBuf::from("test"),
},
ArchiveError::OutputExists {
path: PathBuf::from("test"),
},
ArchiveError::InvalidCompressionLevel { level: 10 },
ArchiveError::UnknownFormat {
path: PathBuf::from("test"),
},
ArchiveError::InvalidConfiguration {
reason: "test".into(),
},
]
}
#[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);
}
#[test]
fn test_partial_extraction_sets_partial() {
let wrap = |writes| ArchiveError::PartialExtraction {
source: Box::new(ArchiveError::violation("x".into())),
report: 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);
}
}