1use super::config_error::ConfigSetting;
9use super::redaction::sanitize_io_error_for_error;
10use super::types::ArchiveError;
11use super::types::PartialWrites;
12use super::types::PolicySetting;
13use super::types::QuotaKind;
14use super::types::ReaderFormatError;
15use super::types::ZipBombScope;
16use crate::ExtractionReport;
17use crate::closed_enum::closed_enum;
18
19closed_enum! {
20 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34 #[non_exhaustive]
35 pub enum ErrorCode {
36 PathTraversal => "PATH_TRAVERSAL",
38 SymlinkEscape => "SYMLINK_ESCAPE",
40 HardlinkEscape => "HARDLINK_ESCAPE",
42 ZipBomb => "ZIP_BOMB",
44 ZipInconsistency => "ZIP_INCONSISTENCY",
46 QuotaExceeded => "QUOTA_EXCEEDED",
48 SecurityViolation => "SECURITY_VIOLATION",
50 InvalidArchive => "INVALID_ARCHIVE",
52 IoError => "IO_ERROR",
54 InvalidPermissions => "INVALID_PERMISSIONS",
56 SourceNotFound => "SOURCE_NOT_FOUND",
58 SourceNotAccessible => "SOURCE_NOT_ACCESSIBLE",
60 OutputExists => "OUTPUT_EXISTS",
62 InvalidCompressionLevel => "INVALID_COMPRESSION_LEVEL",
64 UnknownFormat => "UNKNOWN_FORMAT",
66 InvalidConfiguration => "INVALID_CONFIGURATION",
68 }
69}
70
71closed_enum! {
72 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85 #[non_exhaustive]
86 pub enum InvalidArchiveSubCode {
87 TarAmbiguity => "TAR_AMBIGUITY",
89 TarTrailer => "TAR_TRAILER",
91 LinkTarget => "LINK_TARGET",
93 DuplicateEntry => "DUPLICATE_ENTRY",
95 EntryName => "ENTRY_NAME",
97 DeclaredSize => "DECLARED_SIZE",
99 Integrity => "INTEGRITY",
101 ZipReader => "ZIP_READER",
113 TarReader => "TAR_READER",
117 SevenZReader => "SEVENZ_READER",
121 }
122}
123
124closed_enum! {
125 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136 #[non_exhaustive]
137 pub enum SecurityViolationSubCode {
138 PathName => "PATH_NAME",
140 PathDepth => "PATH_DEPTH",
142 LinkTarget => "LINK_TARGET",
144 LinkPolicy => "LINK_POLICY",
146 ExistingSymlink => "EXISTING_SYMLINK",
148 EntryType => "ENTRY_TYPE",
150 RootEntry => "ROOT_ENTRY",
152 Encrypted => "ENCRYPTED",
154 CompressionMethod => "COMPRESSION_METHOD",
156 SolidArchive => "SOLID_ARCHIVE",
158 DeclaredSize => "DECLARED_SIZE",
160 ConcurrentChange => "CONCURRENT_CHANGE",
162 TarMetadata => "TAR_METADATA",
164 TarTrailer => "TAR_TRAILER",
166 Platform => "PLATFORM",
168 OutputConflict => "OUTPUT_CONFLICT",
170 SourcePath => "SOURCE_PATH",
172 }
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
190#[non_exhaustive]
191pub enum SubCode {
192 InvalidArchive(InvalidArchiveSubCode),
194 SecurityViolation(SecurityViolationSubCode),
196 Quota(QuotaKind),
198 ZipBomb(ZipBombScope),
200}
201
202impl SubCode {
203 pub const QUOTA_ALL: &'static [Self] = &[
205 Self::Quota(QuotaKind::FileCount),
206 Self::Quota(QuotaKind::TotalSize),
207 Self::Quota(QuotaKind::FileSize),
208 Self::Quota(QuotaKind::IntegerOverflow),
209 Self::Quota(QuotaKind::DecoderMemory),
210 Self::Quota(QuotaKind::CompressedMembers),
211 Self::Quota(QuotaKind::TreeNodes),
212 Self::Quota(QuotaKind::SinkCapacity),
213 Self::Quota(QuotaKind::SolidBlockMemory),
214 ];
215 pub const ZIP_BOMB_ALL: &'static [Self] = &[
217 Self::ZipBomb(ZipBombScope::Entry),
218 Self::ZipBomb(ZipBombScope::SolidBlock),
219 Self::ZipBomb(ZipBombScope::SkippedEntries),
220 ];
221
222 #[must_use]
224 pub const fn as_str(self) -> &'static str {
225 match self {
226 Self::InvalidArchive(code) => code.as_str(),
227 Self::SecurityViolation(code) => code.as_str(),
228 Self::Quota(kind) => quota_sub_code(kind),
229 Self::ZipBomb(scope) => zip_bomb_sub_code(scope),
230 }
231 }
232}
233
234const fn quota_sub_code(kind: QuotaKind) -> &'static str {
237 match kind {
238 QuotaKind::FileCount => "FILE_COUNT",
239 QuotaKind::TotalSize => "TOTAL_SIZE",
240 QuotaKind::FileSize => "FILE_SIZE",
241 QuotaKind::IntegerOverflow => "INTEGER_OVERFLOW",
242 QuotaKind::DecoderMemory => "DECODER_MEMORY",
243 QuotaKind::CompressedMembers => "COMPRESSED_MEMBERS",
244 QuotaKind::TreeNodes => "TREE_NODES",
245 QuotaKind::SinkCapacity => "SINK_CAPACITY",
246 QuotaKind::SolidBlockMemory => "SOLID_BLOCK_MEMORY",
247 }
248}
249
250const fn zip_bomb_sub_code(scope: ZipBombScope) -> &'static str {
253 match scope {
254 ZipBombScope::Entry => "ENTRY",
255 ZipBombScope::SolidBlock => "SOLID_BLOCK",
256 ZipBombScope::SkippedEntries => "SKIPPED_ENTRIES",
257 }
258}
259
260impl std::fmt::Display for SubCode {
261 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
262 f.write_str(self.as_str())
263 }
264}
265
266#[derive(Debug, Clone, PartialEq, Eq)]
295#[non_exhaustive]
296pub enum FfiKind {
297 PathTraversal,
299 SymlinkEscape,
301 HardlinkEscape,
303 #[non_exhaustive]
305 ZipBomb {
306 scope: ZipBombScope,
308 },
309 ZipInconsistency,
311 #[non_exhaustive]
313 QuotaExceeded {
314 kind: QuotaKind,
316 },
317 #[non_exhaustive]
319 SecurityViolation {
320 relaxable_by: Option<PolicySetting>,
323 sub_code: SecurityViolationSubCode,
325 },
326 #[non_exhaustive]
328 InvalidArchive {
329 sub_code: Option<InvalidArchiveSubCode>,
331 },
332 Io(std::io::ErrorKind),
334 InvalidPermissions,
336 SourceNotFound,
338 SourceNotAccessible,
340 OutputExists,
342 InvalidCompressionLevel,
344 UnknownFormat,
346 #[non_exhaustive]
348 InvalidConfiguration {
349 setting: Option<ConfigSetting>,
352 },
353}
354
355impl FfiKind {
356 #[must_use]
359 pub const fn relaxable_by(&self) -> Option<PolicySetting> {
360 match self {
361 Self::SecurityViolation { relaxable_by, .. } => *relaxable_by,
362 Self::PathTraversal
363 | Self::SymlinkEscape
364 | Self::HardlinkEscape
365 | Self::ZipBomb { .. }
366 | Self::ZipInconsistency
367 | Self::QuotaExceeded { .. }
368 | Self::InvalidArchive { .. }
369 | Self::Io(_)
370 | Self::InvalidPermissions
371 | Self::SourceNotFound
372 | Self::SourceNotAccessible
373 | Self::OutputExists
374 | Self::InvalidCompressionLevel
375 | Self::UnknownFormat
376 | Self::InvalidConfiguration { .. } => None,
377 }
378 }
379
380 #[must_use]
383 pub const fn setting(&self) -> Option<ConfigSetting> {
384 match self {
385 Self::InvalidConfiguration { setting } => *setting,
386 _ => None,
387 }
388 }
389
390 #[must_use]
392 pub const fn sub_code(&self) -> Option<SubCode> {
393 match self {
394 Self::SecurityViolation { sub_code, .. } => Some(SubCode::SecurityViolation(*sub_code)),
395 Self::InvalidArchive {
396 sub_code: Some(code),
397 } => Some(SubCode::InvalidArchive(*code)),
398 Self::ZipBomb { scope } => Some(SubCode::ZipBomb(*scope)),
399 Self::QuotaExceeded { kind } => Some(SubCode::Quota(*kind)),
400 Self::InvalidArchive { sub_code: None }
401 | Self::PathTraversal
402 | Self::SymlinkEscape
403 | Self::HardlinkEscape
404 | Self::ZipInconsistency
405 | Self::Io(_)
406 | Self::InvalidPermissions
407 | Self::SourceNotFound
408 | Self::SourceNotAccessible
409 | Self::OutputExists
410 | Self::InvalidCompressionLevel
411 | Self::UnknownFormat
412 | Self::InvalidConfiguration { .. } => None,
413 }
414 }
415
416 #[must_use]
418 pub const fn code(&self) -> ErrorCode {
419 match self {
420 Self::PathTraversal => ErrorCode::PathTraversal,
421 Self::SymlinkEscape => ErrorCode::SymlinkEscape,
422 Self::HardlinkEscape => ErrorCode::HardlinkEscape,
423 Self::ZipBomb { .. } => ErrorCode::ZipBomb,
424 Self::ZipInconsistency => ErrorCode::ZipInconsistency,
425 Self::QuotaExceeded { .. } => ErrorCode::QuotaExceeded,
426 Self::SecurityViolation { .. } => ErrorCode::SecurityViolation,
427 Self::InvalidArchive { .. } => ErrorCode::InvalidArchive,
428 Self::Io(_) => ErrorCode::IoError,
429 Self::InvalidPermissions => ErrorCode::InvalidPermissions,
430 Self::SourceNotFound => ErrorCode::SourceNotFound,
431 Self::SourceNotAccessible => ErrorCode::SourceNotAccessible,
432 Self::OutputExists => ErrorCode::OutputExists,
433 Self::InvalidCompressionLevel => ErrorCode::InvalidCompressionLevel,
434 Self::UnknownFormat => ErrorCode::UnknownFormat,
435 Self::InvalidConfiguration { .. } => ErrorCode::InvalidConfiguration,
436 }
437 }
438}
439
440#[derive(Debug, Clone)]
454#[non_exhaustive]
455pub enum PartialOutcome {
456 Kept(ExtractionReport),
458 RolledBack,
461 Discarded,
464}
465
466impl PartialOutcome {
467 #[must_use]
469 pub const fn writes(&self) -> PartialWrites {
470 match self {
471 Self::Kept(_) => PartialWrites::Kept,
472 Self::RolledBack => PartialWrites::RolledBack,
473 Self::Discarded => PartialWrites::Discarded,
474 }
475 }
476}
477
478#[derive(Debug, Clone)]
483#[non_exhaustive]
484pub struct FfiErrorMessage {
485 pub kind: FfiKind,
487
488 pub description: String,
490
491 pub partial: Option<PartialOutcome>,
493
494 pub source_fault: Option<FfiSourceFault>,
497}
498
499#[derive(Debug, Clone)]
516#[non_exhaustive]
517pub struct FfiSourceFault {
518 pub raw_os_error: Option<i32>,
520
521 pub text: String,
524
525 pub name: String,
528}
529
530impl FfiErrorMessage {
531 const fn new(kind: FfiKind, description: String) -> Self {
532 Self {
533 kind,
534 description,
535 partial: None,
536 source_fault: None,
537 }
538 }
539}
540
541impl ArchiveError {
542 #[must_use]
566 pub fn into_ffi_message(self) -> FfiErrorMessage {
567 if let Self::PartialExtraction(partial) = self {
568 let (source, report, writes) = partial.into_parts();
569 let mut msg = source.into_ffi_message();
570 msg.partial = Some(match writes {
571 PartialWrites::Kept => PartialOutcome::Kept(report),
572 PartialWrites::RolledBack => PartialOutcome::RolledBack,
573 PartialWrites::Discarded => PartialOutcome::Discarded,
574 });
575 return msg;
576 }
577 let mut msg = FfiErrorMessage::new(self.ffi_kind(), self.ffi_description());
578 if let Self::SourceNotAccessible { error, .. } = &self {
579 msg.source_fault = Some(FfiSourceFault {
580 raw_os_error: error.raw_os_error(),
581 text: sanitize_io_error_for_error(error),
582 name: self.redacted_path().unwrap_or_default(),
583 });
584 }
585 msg
586 }
587
588 #[must_use]
605 pub fn ffi_kind(&self) -> FfiKind {
606 match self {
607 Self::PathTraversal { .. } => FfiKind::PathTraversal,
608 Self::SymlinkEscape { .. } => FfiKind::SymlinkEscape,
609 Self::HardlinkEscape { .. } => FfiKind::HardlinkEscape,
610 Self::ZipBomb(details) => FfiKind::ZipBomb {
611 scope: details.scope(),
612 },
613 Self::ZipInconsistency(_) => FfiKind::ZipInconsistency,
614 Self::QuotaExceeded { resource } => FfiKind::QuotaExceeded {
615 kind: resource.kind(),
616 },
617 Self::SecurityViolation { kind } => FfiKind::SecurityViolation {
618 relaxable_by: kind.relaxable_by(),
619 sub_code: kind.sub_code(),
620 },
621 Self::InvalidArchive(m) => FfiKind::InvalidArchive {
622 sub_code: m.sub_code(),
623 },
624 Self::TarAmbiguity(_) => FfiKind::InvalidArchive {
625 sub_code: Some(InvalidArchiveSubCode::TarAmbiguity),
626 },
627 Self::TarTrailer(refusal) => {
628 if refusal.is_policy_refusal() {
629 FfiKind::SecurityViolation {
630 relaxable_by: refusal.relaxable_by(),
631 sub_code: SecurityViolationSubCode::TarTrailer,
632 }
633 } else {
634 FfiKind::InvalidArchive {
635 sub_code: Some(InvalidArchiveSubCode::TarTrailer),
636 }
637 }
638 }
639 Self::Io(io_err) => FfiKind::Io(io_err.kind()),
640 Self::InvalidPermissions { .. } => FfiKind::InvalidPermissions,
641 Self::SourceNotFound { .. } => FfiKind::SourceNotFound,
642 Self::SourceNotAccessible { .. } => FfiKind::SourceNotAccessible,
643 Self::OutputExists { .. } => FfiKind::OutputExists,
644 Self::InvalidCompressionLevel { .. } => FfiKind::InvalidCompressionLevel,
645 Self::UnknownFormat { .. } | Self::ReaderFormat(ReaderFormatError::Unrecognized) => {
646 FfiKind::UnknownFormat
647 }
648 Self::InvalidConfiguration { setting, .. } => FfiKind::InvalidConfiguration {
649 setting: Some(*setting),
650 },
651 Self::ReaderFormat(_) => FfiKind::InvalidConfiguration { setting: None },
652 Self::PartialExtraction(partial) => partial.cause().ffi_kind(),
653 }
654 }
655
656 fn ffi_description(&self) -> String {
658 let path = self
659 .redacted_path()
660 .unwrap_or_else(|| "<unknown>".to_string());
661 match self {
662 Self::PathTraversal { .. } => format!("path traversal detected: {path}"),
663 Self::SymlinkEscape { .. } => {
664 format!("symlink target outside extraction directory: {path}")
665 }
666 Self::HardlinkEscape { .. } => {
667 format!("hardlink target outside extraction directory: {path}")
668 }
669 Self::ZipBomb(_)
670 | Self::ZipInconsistency(_)
671 | Self::TarAmbiguity(_)
672 | Self::TarTrailer(_)
673 | Self::SecurityViolation { .. } => self.to_string(),
674 Self::QuotaExceeded { resource } => resource.to_string(),
675 Self::InvalidArchive(reason) => format!("invalid archive: {reason}"),
676 Self::Io(io_err) => sanitize_io_error_for_error(io_err),
677 Self::InvalidPermissions { mode, .. } => {
678 format!("invalid permissions for {path}: {:#o}", mode.get())
679 }
680 Self::SourceNotFound { .. } => format!("source path not found: {path}"),
681 Self::SourceNotAccessible { error, .. } => {
682 format!(
683 "source path is not accessible: {path}: {}",
684 sanitize_io_error_for_error(error)
685 )
686 }
687 Self::OutputExists { .. } => format!("output file already exists: {path}"),
688 Self::InvalidCompressionLevel { level } => {
689 format!("invalid compression level {level}, must be 1-9")
690 }
691 Self::UnknownFormat { .. } => {
692 format!("cannot determine archive format from: {path}")
693 }
694 Self::InvalidConfiguration { setting, problem } => format!(
695 "invalid configuration: {}",
696 super::config_error::message(*setting, problem)
697 ),
698 Self::ReaderFormat(reason) => reason.to_string(),
699 Self::PartialExtraction(partial) => partial.cause().ffi_description(),
700 }
701 }
702
703 #[must_use]
719 pub fn error_code(&self) -> ErrorCode {
720 self.ffi_kind().code()
721 }
722}
723
724#[cfg(test)]
725mod tests {
726 use super::super::config_error::ConfigProblem;
727 use super::super::types::QuotaResource;
728 use super::super::types::ZipBombDetails;
729 use super::super::types::ZipBombScope;
730 use super::super::violation::Violation;
731 use super::*;
732 use std::collections::HashSet;
733
734 use crate::security::Compressed;
735 use crate::security::Uncompressed;
736 use std::assert_matches;
737 use std::path::PathBuf;
738
739 #[test]
740 fn test_ffi_kind_accessors_expose_payload() {
741 let kind = FfiKind::SecurityViolation {
742 relaxable_by: Some(PolicySetting::Symlinks),
743 sub_code: SecurityViolationSubCode::TarTrailer,
744 };
745 assert_eq!(kind.relaxable_by(), Some(PolicySetting::Symlinks));
746 assert_eq!(
747 kind.sub_code(),
748 Some(SubCode::SecurityViolation(
749 SecurityViolationSubCode::TarTrailer
750 ))
751 );
752 let kind = FfiKind::InvalidArchive {
753 sub_code: Some(InvalidArchiveSubCode::TarAmbiguity),
754 };
755 assert_eq!(kind.relaxable_by(), None);
756 assert_eq!(kind.sub_code().map(SubCode::as_str), Some("TAR_AMBIGUITY"));
757 assert_eq!(
758 FfiKind::ZipBomb {
759 scope: ZipBombScope::Entry
760 }
761 .sub_code()
762 .map(SubCode::as_str),
763 Some("ENTRY")
764 );
765 }
766
767 #[test]
771 fn test_attacker_path_never_redacted() {
772 let error = ArchiveError::PathTraversal {
773 path: PathBuf::from("../../etc/passwd"),
774 };
775 let msg = error.into_ffi_message();
776 assert!(msg.description.contains("../../etc/passwd"));
777 }
778
779 #[test]
784 #[cfg(not(debug_assertions))]
785 fn test_host_path_redacted_in_release() {
786 let error = ArchiveError::SourceNotFound {
787 path: PathBuf::from("/srv/secret/app/x.txt"),
788 };
789 let msg = error.into_ffi_message();
790 assert!(msg.description.contains("x.txt"));
791 assert!(!msg.description.contains("/srv/secret"));
792 }
793
794 #[test]
797 #[cfg(not(debug_assertions))]
798 fn test_io_error_redacted_in_release() {
799 let error = ArchiveError::Io(std::io::Error::new(
800 std::io::ErrorKind::PermissionDenied,
801 "directory is not writable: /srv/secret/app/private-output",
802 ));
803 let msg = error.into_ffi_message();
804 assert!(!msg.description.contains("/srv/secret"));
805 }
806
807 #[test]
808 fn test_error_codes_match() {
809 let test_cases = vec![
810 (
811 ArchiveError::PathTraversal {
812 path: PathBuf::from("test"),
813 },
814 ErrorCode::PathTraversal,
815 ),
816 (
817 ArchiveError::SymlinkEscape {
818 path: PathBuf::from("test"),
819 },
820 ErrorCode::SymlinkEscape,
821 ),
822 (
823 ArchiveError::ZipBomb(ZipBombDetails::new(
824 ZipBombScope::Entry,
825 Compressed(100),
826 Uncompressed(10000),
827 )),
828 ErrorCode::ZipBomb,
829 ),
830 ];
831
832 for (error, expected_code) in test_cases {
833 assert_eq!(error.error_code(), expected_code);
834 assert_eq!(error.into_ffi_message().kind.code(), expected_code);
835 }
836 }
837
838 fn one_error_per_variant() -> Vec<ArchiveError> {
839 vec![
840 ArchiveError::PathTraversal {
841 path: PathBuf::from("test"),
842 },
843 ArchiveError::SymlinkEscape {
844 path: PathBuf::from("test"),
845 },
846 ArchiveError::HardlinkEscape {
847 path: PathBuf::from("test"),
848 },
849 ArchiveError::ZipBomb(ZipBombDetails::new(
850 ZipBombScope::Entry,
851 Compressed(100),
852 Uncompressed(10000),
853 )),
854 ArchiveError::ZipInconsistency(
855 super::super::zip_inconsistency::ZipInconsistency::OverlappingEntries,
856 ),
857 ArchiveError::QuotaExceeded {
858 resource: QuotaResource::IntegerOverflow,
859 },
860 ArchiveError::from(Violation::EncryptedArchive),
861 ArchiveError::unclassified("test"),
862 ArchiveError::Io(std::io::Error::other("test")),
863 ArchiveError::InvalidPermissions {
864 path: PathBuf::from("test"),
865 mode: crate::RawMode::new(0o777),
866 },
867 ArchiveError::SourceNotFound {
868 path: PathBuf::from("test"),
869 },
870 ArchiveError::SourceNotAccessible {
871 path: PathBuf::from("test"),
872 error: std::io::Error::other("test"),
873 },
874 ArchiveError::OutputExists {
875 path: PathBuf::from("test"),
876 },
877 ArchiveError::InvalidCompressionLevel { level: 10 },
878 ArchiveError::UnknownFormat {
879 path: PathBuf::from("test"),
880 },
881 ArchiveError::InvalidConfiguration {
882 setting: ConfigSetting::OutputPath,
883 problem: ConfigProblem::NotSet,
884 },
885 ]
886 }
887
888 #[test]
889 fn test_all_error_variants_have_codes() {
890 for error in one_error_per_variant() {
891 let code = error.error_code();
892 let msg = error.into_ffi_message();
893 assert_eq!(msg.kind.code(), code);
894 assert!(!msg.description.is_empty());
895 assert!(msg.partial.is_none());
896 }
897 }
898
899 #[test]
900 fn test_kind_code_covers_error_code_all_exactly_once() {
901 let mut seen: Vec<ErrorCode> = one_error_per_variant()
902 .into_iter()
903 .map(|e| e.into_ffi_message().kind.code())
904 .collect();
905 seen.sort_by_key(|c| c.as_str());
906 let mut expected = ErrorCode::ALL.to_vec();
907 expected.sort_by_key(|c| c.as_str());
908 assert_eq!(seen, expected);
909 }
910
911 fn every_tar_ambiguity() -> Vec<super::super::tar_ambiguity::TarAmbiguity> {
912 use super::super::tar_ambiguity::TarAmbiguity as A;
913 use super::super::tar_ambiguity::TarExtensionKind as Ext;
914 use super::super::tar_ambiguity::TarHeaderField as Field;
915 use super::super::tar_ambiguity::TarNonRegularKind as NonRegular;
916 use super::super::tar_ambiguity::TarPathKey as Key;
917 let key = || "k".to_string();
918 vec![
919 A::MalformedRecord,
920 A::EmptyKey,
921 A::OversizedRecord { key: key() },
922 A::DuplicateRecord { key: key() },
923 A::UnsupportedRecord { key: key() },
924 A::InvalidSize,
925 A::GlobalOverride { key: key() },
926 A::GlobalTooLarge { size: 2, limit: 1 },
927 A::LocalBeforeGlobal,
928 A::LongRecordBeforeGlobal,
929 A::StackedLongRecord { key: Key::Path },
930 A::StackedSizeRecord,
931 A::UnrecognizedHeader { kind: Ext::Pax },
932 A::SparseEntry,
933 A::NonCanonicalNumber { field: Field::Size },
934 A::PrefixWithoutUstar,
935 A::ChecksumMismatch,
936 A::DuplicateExtensionHeader { kind: Ext::Pax },
937 A::WindowMismatch,
938 A::NonZeroPadding,
939 A::MalformedLongRecord {
940 kind: Ext::LongName,
941 },
942 A::NonRegularPayload {
943 kind: NonRegular::Directory,
944 size: 1,
945 path: "d".into(),
946 },
947 A::DirectoryNamedPayload {
948 size: 1,
949 path: "d/".into(),
950 },
951 ]
952 }
953
954 #[test]
955 fn test_ffi_kind_sub_code_table() {
956 use super::super::tar_trailer::TarTrailerRefusal as R;
957 use super::super::tar_trailer::TrailerCorruption;
958
959 let ambiguity = Some(InvalidArchiveSubCode::TarAmbiguity);
960 let trailer = Some(InvalidArchiveSubCode::TarTrailer);
961 let invalid = |sub_code| FfiKind::InvalidArchive { sub_code };
962
963 for variant in every_tar_ambiguity() {
964 let error = ArchiveError::TarAmbiguity(variant);
965 assert_eq!(error.ffi_kind(), invalid(ambiguity), "{error:?}");
966 }
967
968 for refusal in [
969 R::Truncated,
970 R::Corrupt {
971 cause: TrailerCorruption::Decoder,
972 detail: "d".into(),
973 },
974 R::Corrupt {
975 cause: TrailerCorruption::TrailingData,
976 detail: "d".into(),
977 },
978 ] {
979 let error = ArchiveError::TarTrailer(refusal);
980 assert_eq!(error.ffi_kind(), invalid(trailer), "{error:?}");
981 }
982 assert_eq!(
983 ArchiveError::TarTrailer(R::OverCap { cap: 1 }).ffi_kind(),
984 FfiKind::SecurityViolation {
985 relaxable_by: Some(PolicySetting::MaxTarMetadataBytes),
986 sub_code: SecurityViolationSubCode::TarTrailer,
987 }
988 );
989
990 assert_eq!(ArchiveError::unclassified("x").ffi_kind(), invalid(None));
991 assert_eq!(
992 ArchiveError::from(Violation::EncryptedArchive).ffi_kind(),
993 FfiKind::SecurityViolation {
994 relaxable_by: None,
995 sub_code: SecurityViolationSubCode::Encrypted,
996 }
997 );
998 let wrapped = ArchiveError::PartialExtraction(crate::Partial::new(
999 ArchiveError::TarAmbiguity(super::super::tar_ambiguity::TarAmbiguity::SparseEntry),
1000 ExtractionReport::default(),
1001 PartialWrites::Kept,
1002 ));
1003 assert_eq!(wrapped.ffi_kind(), invalid(ambiguity));
1004 }
1005
1006 #[test]
1007 fn test_partial_extraction_sets_partial() {
1008 let wrap = |writes| {
1009 ArchiveError::PartialExtraction(crate::Partial::new(
1010 ArchiveError::from(Violation::EncryptedArchive),
1011 ExtractionReport::default(),
1012 writes,
1013 ))
1014 };
1015 let kept = wrap(PartialWrites::Kept).into_ffi_message();
1016 assert_matches!(kept.partial, Some(PartialOutcome::Kept(_)));
1017 assert_eq!(kept.kind.code(), ErrorCode::SecurityViolation);
1018 let rolled = wrap(PartialWrites::RolledBack).into_ffi_message();
1019 assert_matches!(rolled.partial, Some(PartialOutcome::RolledBack));
1020 let discarded = wrap(PartialWrites::Discarded).into_ffi_message();
1021 assert_matches!(discarded.partial, Some(PartialOutcome::Discarded));
1022 assert_eq!(PartialOutcome::Discarded.writes(), PartialWrites::Discarded);
1023 }
1024
1025 #[test]
1026 fn quota_and_zip_bomb_sub_codes_are_screaming_and_unique() {
1027 let quotas: Vec<_> = QuotaKind::ALL
1028 .iter()
1029 .map(|&kind| SubCode::Quota(kind).as_str())
1030 .collect();
1031 let scopes: Vec<_> = ZipBombScope::ALL
1032 .iter()
1033 .map(|&scope| SubCode::ZipBomb(scope).as_str())
1034 .collect();
1035 for set in ["as, &scopes] {
1036 let unique: HashSet<_> = set.iter().collect();
1037 assert_eq!(unique.len(), set.len(), "{set:?}");
1038 for code in set {
1039 assert!(
1040 code.chars().all(|c| c.is_ascii_uppercase() || c == '_'),
1041 "{code}"
1042 );
1043 }
1044 }
1045 }
1046
1047 #[test]
1048 fn quota_and_zip_bomb_kinds_carry_their_sub_code() {
1049 let quota = ArchiveError::QuotaExceeded {
1050 resource: QuotaResource::SolidBlockMemory {
1051 scope: crate::SolidMemoryScope::Block,
1052 current: 2,
1053 max: 1,
1054 },
1055 };
1056 assert_eq!(
1057 quota.ffi_kind().sub_code(),
1058 Some(SubCode::Quota(QuotaKind::SolidBlockMemory))
1059 );
1060 assert_eq!(
1061 quota.ffi_kind().sub_code().map(SubCode::as_str),
1062 Some("SOLID_BLOCK_MEMORY")
1063 );
1064 }
1065
1066 #[test]
1067 fn the_sub_code_constants_cover_every_kind_and_scope() {
1068 let quotas: Vec<_> = QuotaKind::ALL.iter().map(|&k| SubCode::Quota(k)).collect();
1069 assert_eq!(SubCode::QUOTA_ALL, quotas.as_slice());
1070 let scopes: Vec<_> = ZipBombScope::ALL
1071 .iter()
1072 .map(|&s| SubCode::ZipBomb(s))
1073 .collect();
1074 assert_eq!(SubCode::ZIP_BOMB_ALL, scopes.as_slice());
1075 }
1076}