1use super::redaction::sanitize_io_error_for_error;
9use super::types::ArchiveError;
10use super::types::PartialWrites;
11use super::types::PolicySetting;
12use super::types::ReaderFormatError;
13use crate::ExtractionReport;
14use crate::closed_enum::closed_enum;
15
16closed_enum! {
17 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31 #[non_exhaustive]
32 pub enum ErrorCode {
33 PathTraversal => "PATH_TRAVERSAL",
35 SymlinkEscape => "SYMLINK_ESCAPE",
37 HardlinkEscape => "HARDLINK_ESCAPE",
39 ZipBomb => "ZIP_BOMB",
41 ZipInconsistency => "ZIP_INCONSISTENCY",
43 QuotaExceeded => "QUOTA_EXCEEDED",
45 SecurityViolation => "SECURITY_VIOLATION",
47 InvalidArchive => "INVALID_ARCHIVE",
49 IoError => "IO_ERROR",
51 InvalidPermissions => "INVALID_PERMISSIONS",
53 SourceNotFound => "SOURCE_NOT_FOUND",
55 SourceNotAccessible => "SOURCE_NOT_ACCESSIBLE",
57 OutputExists => "OUTPUT_EXISTS",
59 InvalidCompressionLevel => "INVALID_COMPRESSION_LEVEL",
61 UnknownFormat => "UNKNOWN_FORMAT",
63 InvalidConfiguration => "INVALID_CONFIGURATION",
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
88#[non_exhaustive]
89pub enum FfiKind {
90 PathTraversal,
92 SymlinkEscape,
94 HardlinkEscape,
96 ZipBomb,
98 ZipInconsistency,
100 QuotaExceeded,
102 SecurityViolation {
104 relaxable_by: Option<PolicySetting>,
107 },
108 InvalidArchive,
110 Io(std::io::ErrorKind),
112 InvalidPermissions,
114 SourceNotFound,
116 SourceNotAccessible,
118 OutputExists,
120 InvalidCompressionLevel,
122 UnknownFormat,
124 InvalidConfiguration,
126}
127
128impl FfiKind {
129 #[must_use]
131 pub const fn code(&self) -> ErrorCode {
132 match self {
133 Self::PathTraversal => ErrorCode::PathTraversal,
134 Self::SymlinkEscape => ErrorCode::SymlinkEscape,
135 Self::HardlinkEscape => ErrorCode::HardlinkEscape,
136 Self::ZipBomb => ErrorCode::ZipBomb,
137 Self::ZipInconsistency => ErrorCode::ZipInconsistency,
138 Self::QuotaExceeded => ErrorCode::QuotaExceeded,
139 Self::SecurityViolation { .. } => ErrorCode::SecurityViolation,
140 Self::InvalidArchive => ErrorCode::InvalidArchive,
141 Self::Io(_) => ErrorCode::IoError,
142 Self::InvalidPermissions => ErrorCode::InvalidPermissions,
143 Self::SourceNotFound => ErrorCode::SourceNotFound,
144 Self::SourceNotAccessible => ErrorCode::SourceNotAccessible,
145 Self::OutputExists => ErrorCode::OutputExists,
146 Self::InvalidCompressionLevel => ErrorCode::InvalidCompressionLevel,
147 Self::UnknownFormat => ErrorCode::UnknownFormat,
148 Self::InvalidConfiguration => ErrorCode::InvalidConfiguration,
149 }
150 }
151}
152
153#[derive(Debug, Clone)]
167#[non_exhaustive]
168pub enum PartialOutcome {
169 Kept(ExtractionReport),
171 RolledBack,
174 Discarded,
177}
178
179impl PartialOutcome {
180 #[must_use]
182 pub const fn writes(&self) -> PartialWrites {
183 match self {
184 Self::Kept(_) => PartialWrites::Kept,
185 Self::RolledBack => PartialWrites::RolledBack,
186 Self::Discarded => PartialWrites::Discarded,
187 }
188 }
189}
190
191#[derive(Debug, Clone)]
196#[non_exhaustive]
197pub struct FfiErrorMessage {
198 pub kind: FfiKind,
200
201 pub description: String,
203
204 pub partial: Option<PartialOutcome>,
206}
207
208impl FfiErrorMessage {
209 const fn new(kind: FfiKind, description: String) -> Self {
210 Self {
211 kind,
212 description,
213 partial: None,
214 }
215 }
216}
217
218impl ArchiveError {
219 #[must_use]
243 pub fn into_ffi_message(self) -> FfiErrorMessage {
244 if let Self::PartialExtraction {
245 source,
246 report,
247 writes,
248 } = self
249 {
250 let mut msg = source.into_ffi_message();
251 msg.partial = Some(match writes {
252 PartialWrites::Kept => PartialOutcome::Kept(report),
253 PartialWrites::RolledBack => PartialOutcome::RolledBack,
254 PartialWrites::Discarded => PartialOutcome::Discarded,
255 });
256 return msg;
257 }
258 FfiErrorMessage::new(self.ffi_kind(), self.ffi_description())
259 }
260
261 fn ffi_kind(&self) -> FfiKind {
264 match self {
265 Self::PathTraversal { .. } => FfiKind::PathTraversal,
266 Self::SymlinkEscape { .. } => FfiKind::SymlinkEscape,
267 Self::HardlinkEscape { .. } => FfiKind::HardlinkEscape,
268 Self::ZipBomb(_) => FfiKind::ZipBomb,
269 Self::ZipInconsistency(_) => FfiKind::ZipInconsistency,
270 Self::QuotaExceeded { .. } => FfiKind::QuotaExceeded,
271 Self::SecurityViolation { relaxable_by, .. } => FfiKind::SecurityViolation {
272 relaxable_by: *relaxable_by,
273 },
274 Self::InvalidArchive(_) => FfiKind::InvalidArchive,
275 Self::Io(io_err) => FfiKind::Io(io_err.kind()),
276 Self::InvalidPermissions { .. } => FfiKind::InvalidPermissions,
277 Self::SourceNotFound { .. } => FfiKind::SourceNotFound,
278 Self::SourceNotAccessible { .. } => FfiKind::SourceNotAccessible,
279 Self::OutputExists { .. } => FfiKind::OutputExists,
280 Self::InvalidCompressionLevel { .. } => FfiKind::InvalidCompressionLevel,
281 Self::UnknownFormat { .. } | Self::ReaderFormat(ReaderFormatError::Unrecognized) => {
282 FfiKind::UnknownFormat
283 }
284 Self::InvalidConfiguration { .. } | Self::ReaderFormat(_) => {
285 FfiKind::InvalidConfiguration
286 }
287 Self::PartialExtraction { source, .. } => source.ffi_kind(),
288 }
289 }
290
291 fn ffi_description(&self) -> String {
293 let path = self
294 .redacted_path()
295 .unwrap_or_else(|| "<unknown>".to_string());
296 match self {
297 Self::PathTraversal { .. } => format!("path traversal detected: {path}"),
298 Self::SymlinkEscape { .. } => {
299 format!("symlink target outside extraction directory: {path}")
300 }
301 Self::HardlinkEscape { .. } => {
302 format!("hardlink target outside extraction directory: {path}")
303 }
304 Self::ZipBomb(_) | Self::ZipInconsistency(_) => self.to_string(),
305 Self::QuotaExceeded { resource } => resource.to_string(),
306 Self::SecurityViolation { reason, .. } => {
307 format!("operation denied by security policy: {reason}")
308 }
309 Self::InvalidArchive(reason) => format!("invalid archive: {reason}"),
310 Self::Io(io_err) => sanitize_io_error_for_error(io_err),
311 Self::InvalidPermissions { mode, .. } => {
312 format!("invalid permissions for {path}: {mode:#o}")
313 }
314 Self::SourceNotFound { .. } => format!("source path not found: {path}"),
315 Self::SourceNotAccessible { .. } => {
316 format!("source path is not accessible: {path}")
317 }
318 Self::OutputExists { .. } => format!("output file already exists: {path}"),
319 Self::InvalidCompressionLevel { level } => {
320 format!("invalid compression level {level}, must be 1-9")
321 }
322 Self::UnknownFormat { .. } => {
323 format!("cannot determine archive format from: {path}")
324 }
325 Self::InvalidConfiguration { reason } => format!("invalid configuration: {reason}"),
326 Self::ReaderFormat(reason) => reason.to_string(),
327 Self::PartialExtraction { source, .. } => source.ffi_description(),
328 }
329 }
330
331 #[must_use]
346 pub fn error_code(&self) -> ErrorCode {
347 self.ffi_kind().code()
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::super::types::QuotaResource;
354 use super::super::types::ZipBombDetails;
355 use super::super::types::ZipBombScope;
356 use super::*;
357 use std::assert_matches;
358 use std::path::PathBuf;
359
360 #[test]
364 fn test_attacker_path_never_redacted() {
365 let error = ArchiveError::PathTraversal {
366 path: PathBuf::from("../../etc/passwd"),
367 };
368 let msg = error.into_ffi_message();
369 assert!(msg.description.contains("../../etc/passwd"));
370 }
371
372 #[test]
377 #[cfg(not(debug_assertions))]
378 fn test_host_path_redacted_in_release() {
379 let error = ArchiveError::SourceNotFound {
380 path: PathBuf::from("/srv/secret/app/x.txt"),
381 };
382 let msg = error.into_ffi_message();
383 assert!(msg.description.contains("x.txt"));
384 assert!(!msg.description.contains("/srv/secret"));
385 }
386
387 #[test]
390 #[cfg(not(debug_assertions))]
391 fn test_io_error_redacted_in_release() {
392 let error = ArchiveError::Io(std::io::Error::new(
393 std::io::ErrorKind::PermissionDenied,
394 "directory is not writable: /srv/secret/app/private-output",
395 ));
396 let msg = error.into_ffi_message();
397 assert!(!msg.description.contains("/srv/secret"));
398 }
399
400 #[test]
401 fn test_error_codes_match() {
402 let test_cases = vec![
403 (
404 ArchiveError::PathTraversal {
405 path: PathBuf::from("test"),
406 },
407 ErrorCode::PathTraversal,
408 ),
409 (
410 ArchiveError::SymlinkEscape {
411 path: PathBuf::from("test"),
412 },
413 ErrorCode::SymlinkEscape,
414 ),
415 (
416 ArchiveError::ZipBomb(ZipBombDetails::new(ZipBombScope::Entry, 100, 10000)),
417 ErrorCode::ZipBomb,
418 ),
419 ];
420
421 for (error, expected_code) in test_cases {
422 assert_eq!(error.error_code(), expected_code);
423 assert_eq!(error.into_ffi_message().kind.code(), expected_code);
424 }
425 }
426
427 fn one_error_per_variant() -> Vec<ArchiveError> {
428 vec![
429 ArchiveError::PathTraversal {
430 path: PathBuf::from("test"),
431 },
432 ArchiveError::SymlinkEscape {
433 path: PathBuf::from("test"),
434 },
435 ArchiveError::HardlinkEscape {
436 path: PathBuf::from("test"),
437 },
438 ArchiveError::ZipBomb(ZipBombDetails::new(ZipBombScope::Entry, 100, 10000)),
439 ArchiveError::ZipInconsistency(
440 super::super::zip_inconsistency::ZipInconsistency::OverlappingEntries,
441 ),
442 ArchiveError::QuotaExceeded {
443 resource: QuotaResource::IntegerOverflow,
444 },
445 ArchiveError::violation("test".into()),
446 ArchiveError::InvalidArchive("test".into()),
447 ArchiveError::Io(std::io::Error::other("test")),
448 ArchiveError::InvalidPermissions {
449 path: PathBuf::from("test"),
450 mode: 0o777,
451 },
452 ArchiveError::SourceNotFound {
453 path: PathBuf::from("test"),
454 },
455 ArchiveError::SourceNotAccessible {
456 path: PathBuf::from("test"),
457 },
458 ArchiveError::OutputExists {
459 path: PathBuf::from("test"),
460 },
461 ArchiveError::InvalidCompressionLevel { level: 10 },
462 ArchiveError::UnknownFormat {
463 path: PathBuf::from("test"),
464 },
465 ArchiveError::InvalidConfiguration {
466 reason: "test".into(),
467 },
468 ]
469 }
470
471 #[test]
472 fn test_all_error_variants_have_codes() {
473 for error in one_error_per_variant() {
474 let code = error.error_code();
475 let msg = error.into_ffi_message();
476 assert_eq!(msg.kind.code(), code);
477 assert!(!msg.description.is_empty());
478 assert!(msg.partial.is_none());
479 }
480 }
481
482 #[test]
483 fn test_kind_code_covers_error_code_all_exactly_once() {
484 let mut seen: Vec<ErrorCode> = one_error_per_variant()
485 .into_iter()
486 .map(|e| e.into_ffi_message().kind.code())
487 .collect();
488 seen.sort_by_key(|c| c.as_str());
489 let mut expected = ErrorCode::ALL.to_vec();
490 expected.sort_by_key(|c| c.as_str());
491 assert_eq!(seen, expected);
492 }
493
494 #[test]
495 fn test_partial_extraction_sets_partial() {
496 let wrap = |writes| ArchiveError::PartialExtraction {
497 source: Box::new(ArchiveError::violation("x".into())),
498 report: ExtractionReport::default(),
499 writes,
500 };
501 let kept = wrap(PartialWrites::Kept).into_ffi_message();
502 assert_matches!(kept.partial, Some(PartialOutcome::Kept(_)));
503 assert_eq!(kept.kind.code(), ErrorCode::SecurityViolation);
504 let rolled = wrap(PartialWrites::RolledBack).into_ffi_message();
505 assert_matches!(rolled.partial, Some(PartialOutcome::RolledBack));
506 let discarded = wrap(PartialWrites::Discarded).into_ffi_message();
507 assert_matches!(discarded.partial, Some(PartialOutcome::Discarded));
508 assert_eq!(PartialOutcome::Discarded.writes(), PartialWrites::Discarded);
509 }
510}