Skip to main content

exarch_core/error/
messages.rs

1//! FFI error message formatting.
2//!
3//! The single source of binding-facing error data: a stable [`ErrorCode`], a
4//! typed [`FfiKind`] with the payload each code carries, a redacted
5//! description and the fate of partial output. Python, Node.js and the CLI
6//! consume [`FfiErrorMessage`] instead of re-matching [`ArchiveError`].
7
8use 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    /// Stable machine-readable identifier of an [`ArchiveError`] variant.
21    ///
22    /// The spellings are part of every binding's observable contract; the
23    /// bindings take them from [`ErrorCode::as_str`].
24    ///
25    /// # Examples
26    ///
27    /// ```
28    /// use exarch_core::ErrorCode;
29    ///
30    /// assert_eq!(ErrorCode::ZipBomb.as_str(), "ZIP_BOMB");
31    /// assert!(ErrorCode::ALL.contains(&ErrorCode::PathTraversal));
32    /// ```
33    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34    #[non_exhaustive]
35    pub enum ErrorCode {
36        /// [`ArchiveError::PathTraversal`].
37        PathTraversal => "PATH_TRAVERSAL",
38        /// [`ArchiveError::SymlinkEscape`].
39        SymlinkEscape => "SYMLINK_ESCAPE",
40        /// [`ArchiveError::HardlinkEscape`].
41        HardlinkEscape => "HARDLINK_ESCAPE",
42        /// [`ArchiveError::ZipBomb`].
43        ZipBomb => "ZIP_BOMB",
44        /// [`ArchiveError::ZipInconsistency`].
45        ZipInconsistency => "ZIP_INCONSISTENCY",
46        /// [`ArchiveError::QuotaExceeded`].
47        QuotaExceeded => "QUOTA_EXCEEDED",
48        /// [`ArchiveError::SecurityViolation`].
49        SecurityViolation => "SECURITY_VIOLATION",
50        /// [`ArchiveError::InvalidArchive`].
51        InvalidArchive => "INVALID_ARCHIVE",
52        /// [`ArchiveError::Io`].
53        IoError => "IO_ERROR",
54        /// [`ArchiveError::InvalidPermissions`].
55        InvalidPermissions => "INVALID_PERMISSIONS",
56        /// [`ArchiveError::SourceNotFound`].
57        SourceNotFound => "SOURCE_NOT_FOUND",
58        /// [`ArchiveError::SourceNotAccessible`].
59        SourceNotAccessible => "SOURCE_NOT_ACCESSIBLE",
60        /// [`ArchiveError::OutputExists`].
61        OutputExists => "OUTPUT_EXISTS",
62        /// [`ArchiveError::InvalidCompressionLevel`].
63        InvalidCompressionLevel => "INVALID_COMPRESSION_LEVEL",
64        /// [`ArchiveError::UnknownFormat`].
65        UnknownFormat => "UNKNOWN_FORMAT",
66        /// [`ArchiveError::InvalidConfiguration`].
67        InvalidConfiguration => "INVALID_CONFIGURATION",
68    }
69}
70
71closed_enum! {
72    /// Finer classification of an [`ErrorCode::InvalidArchive`] error.
73    ///
74    /// Bindings expose it so callers can tell a TAR refusal from any other
75    /// malformed archive without parsing the message.
76    ///
77    /// # Examples
78    ///
79    /// ```
80    /// use exarch_core::InvalidArchiveSubCode;
81    ///
82    /// assert_eq!(InvalidArchiveSubCode::TarTrailer.as_str(), "TAR_TRAILER");
83    /// ```
84    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85    #[non_exhaustive]
86    pub enum InvalidArchiveSubCode {
87        /// [`ArchiveError::TarAmbiguity`].
88        TarAmbiguity => "TAR_AMBIGUITY",
89        /// A corrupt or truncated stream after the TAR end-of-archive marker.
90        TarTrailer => "TAR_TRAILER",
91        /// A link entry whose target is missing, unreadable or unusable.
92        LinkTarget => "LINK_TARGET",
93        /// An entry path that is already taken.
94        DuplicateEntry => "DUPLICATE_ENTRY",
95        /// An entry path or name that cannot be read.
96        EntryName => "ENTRY_NAME",
97        /// A declared size that contradicts the archive.
98        DeclaredSize => "DECLARED_SIZE",
99        /// An entry whose integrity decode failed.
100        Integrity => "INTEGRITY",
101        /// A failure of the ZIP reader or of the structural check built on it:
102        /// the archive or an entry cannot be opened or read, the census and
103        /// the reader disagree about the central directory, an entry's data
104        /// range is not representable, or the zstd entries cannot be walked
105        /// within the archive extent.
106        ///
107        /// It also covers I/O failures the `zip` crate wraps into its own
108        /// errors. A wrapped I/O error surfaces as [`ErrorCode::IoError`] during
109        /// the structure scan at open, where the reader's own fault is
110        /// preferred, but as this code when extraction, listing or the
111        /// descriptor-tail re-read hit it.
112        ZipReader => "ZIP_READER",
113        /// A failure of the TAR reader: an entry, its PAX header or the entry
114        /// stream cannot be read, or the reader was used after an entry was
115        /// abandoned.
116        TarReader => "TAR_READER",
117        /// A failure of the 7z reader: the header cannot be parsed or is
118        /// inconsistent, a block uses an unsupported coder, or `sevenz-rust2`
119        /// reports an error with no kind of its own.
120        SevenZReader => "SEVENZ_READER",
121    }
122}
123
124closed_enum! {
125    /// Finer classification of an [`ErrorCode::SecurityViolation`] error.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// use exarch_core::SecurityViolationSubCode;
131    ///
132    /// assert_eq!(SecurityViolationSubCode::TarTrailer.as_str(), "TAR_TRAILER");
133    /// assert_eq!(SecurityViolationSubCode::PathName.as_str(), "PATH_NAME");
134    /// ```
135    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136    #[non_exhaustive]
137    pub enum SecurityViolationSubCode {
138        /// An entry or argument path is refused by name rules.
139        PathName => "PATH_NAME",
140        /// A path or symlink target is deeper than the limit.
141        PathDepth => "PATH_DEPTH",
142        /// The target of a symlink or hardlink cannot be accepted.
143        LinkTarget => "LINK_TARGET",
144        /// The kind of link is disabled by the configuration.
145        LinkPolicy => "LINK_POLICY",
146        /// A symlink already at or above the entry's location blocks it.
147        ExistingSymlink => "EXISTING_SYMLINK",
148        /// An entry type exarch does not extract.
149        EntryType => "ENTRY_TYPE",
150        /// A root entry that is not a directory.
151        RootEntry => "ROOT_ENTRY",
152        /// An encrypted archive or entry.
153        Encrypted => "ENCRYPTED",
154        /// A compression method exarch does not read.
155        CompressionMethod => "COMPRESSION_METHOD",
156        /// A solid archive while solid archives are disabled.
157        SolidArchive => "SOLID_ARCHIVE",
158        /// A stream disagrees with the size its archive declared.
159        DeclaredSize => "DECLARED_SIZE",
160        /// A file changed while it was being copied.
161        ConcurrentChange => "CONCURRENT_CHANGE",
162        /// A TAR metadata or synthetic-byte budget was exceeded.
163        TarMetadata => "TAR_METADATA",
164        /// An over-cap tail after the TAR end-of-archive marker.
165        TarTrailer => "TAR_TRAILER",
166        /// The host platform cannot do what the entry asks.
167        Platform => "PLATFORM",
168        /// An existing output conflicts with an entry.
169        OutputConflict => "OUTPUT_CONFLICT",
170        /// A source path to archive lies outside the archive root.
171        SourcePath => "SOURCE_PATH",
172    }
173}
174
175/// The finer classification of an error, tagged with the class it refines.
176///
177/// The variant is the error class, so a pair of class and sub-code that core
178/// never produces cannot be built.
179///
180/// # Examples
181///
182/// ```
183/// use exarch_core::InvalidArchiveSubCode;
184/// use exarch_core::SubCode;
185///
186/// let code = SubCode::InvalidArchive(InvalidArchiveSubCode::TarTrailer);
187/// assert_eq!(code.as_str(), "TAR_TRAILER");
188/// ```
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
190#[non_exhaustive]
191pub enum SubCode {
192    /// Refines [`ErrorCode::InvalidArchive`].
193    InvalidArchive(InvalidArchiveSubCode),
194    /// Refines [`ErrorCode::SecurityViolation`].
195    SecurityViolation(SecurityViolationSubCode),
196    /// Refines [`ErrorCode::QuotaExceeded`] with the quota that was exceeded.
197    Quota(QuotaKind),
198    /// Refines [`ErrorCode::ZipBomb`] with what the ratio was measured over.
199    ZipBomb(ZipBombScope),
200}
201
202impl SubCode {
203    /// Every sub-code of a quota error, in [`QuotaKind::ALL`] order.
204    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    /// Every sub-code of a zip-bomb error, in [`ZipBombScope::ALL`] order.
216    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    /// The stable string form of the wrapped sub-code.
223    #[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
234/// The `SCREAMING_SNAKE` sub-code of a quota, distinct from the `snake_case`
235/// [`QuotaKind::as_str`] that the CLI and Python/Node `kind` fields use.
236const 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
250/// The `SCREAMING_SNAKE` sub-code of a zip-bomb scope, distinct from the
251/// human-readable [`ZipBombScope::as_str`] used in messages.
252const 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/// The error class of an [`FfiErrorMessage`], with the payload that class
267/// carries.
268///
269/// One variant per [`ErrorCode`]; [`FfiKind::code`] is the bijection.
270/// Payload lives inside the variant so a binding cannot read a field that
271/// does not exist for the class.
272///
273/// # Examples
274///
275/// ```
276/// use exarch_core::ArchiveError;
277/// use exarch_core::ErrorCode;
278/// use exarch_core::FfiKind;
279/// use exarch_core::SecurityViolationSubCode;
280/// use exarch_core::Violation;
281/// use std::assert_matches;
282///
283/// let msg = ArchiveError::from(Violation::EncryptedArchive).into_ffi_message();
284/// assert_matches!(
285///     msg.kind,
286///     FfiKind::SecurityViolation {
287///         relaxable_by: None,
288///         sub_code: SecurityViolationSubCode::Encrypted,
289///         ..
290///     }
291/// );
292/// assert_eq!(msg.kind.code(), ErrorCode::SecurityViolation);
293/// ```
294#[derive(Debug, Clone, PartialEq, Eq)]
295#[non_exhaustive]
296pub enum FfiKind {
297    /// Entry path escapes the destination.
298    PathTraversal,
299    /// Symlink target escapes the destination.
300    SymlinkEscape,
301    /// Hardlink target escapes the destination.
302    HardlinkEscape,
303    /// Compression ratio limit exceeded.
304    #[non_exhaustive]
305    ZipBomb {
306        /// What the refused ratio was measured over.
307        scope: ZipBombScope,
308    },
309    /// ZIP structure is ambiguous or self-contradictory.
310    ZipInconsistency,
311    /// A quota was exceeded.
312    #[non_exhaustive]
313    QuotaExceeded {
314        /// The quota dimension that was exceeded.
315        kind: QuotaKind,
316    },
317    /// Denied by security policy.
318    #[non_exhaustive]
319    SecurityViolation {
320        /// The `SecurityConfig` setting whose current value refused the
321        /// entry; see [`ArchiveError::relaxable_by`].
322        relaxable_by: Option<PolicySetting>,
323        /// The family of the refusal.
324        sub_code: SecurityViolationSubCode,
325    },
326    /// Archive is corrupted or malformed.
327    #[non_exhaustive]
328    InvalidArchive {
329        /// Finer classification, when the failure has one.
330        sub_code: Option<InvalidArchiveSubCode>,
331    },
332    /// I/O failure of the given kind.
333    Io(std::io::ErrorKind),
334    /// Invalid permission bits.
335    InvalidPermissions,
336    /// Creation source does not exist.
337    SourceNotFound,
338    /// Creation source cannot be read.
339    SourceNotAccessible,
340    /// Output file already exists.
341    OutputExists,
342    /// Compression level out of range.
343    InvalidCompressionLevel,
344    /// Archive format could not be determined.
345    UnknownFormat,
346    /// Configuration is invalid.
347    #[non_exhaustive]
348    InvalidConfiguration {
349        /// The setting or input that was refused; `None` for a reader format
350        /// that cannot be used.
351        setting: Option<ConfigSetting>,
352    },
353}
354
355impl FfiKind {
356    /// The `SecurityConfig` setting whose current value refused the entry, if
357    /// this is a [`FfiKind::SecurityViolation`] that a setting can relax.
358    #[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    /// The configuration setting or input that was refused, if this is a
381    /// [`FfiKind::InvalidConfiguration`] that names one.
382    #[must_use]
383    pub const fn setting(&self) -> Option<ConfigSetting> {
384        match self {
385            Self::InvalidConfiguration { setting } => *setting,
386            _ => None,
387        }
388    }
389
390    /// The finer classification of this error, when it has one.
391    #[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    /// The stable [`ErrorCode`] of this class.
417    #[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/// What happened to the output of an extraction that stopped part-way.
441///
442/// # Examples
443///
444/// ```
445/// use exarch_core::PartialOutcome;
446/// use exarch_core::PartialWrites;
447///
448/// assert_eq!(
449///     PartialOutcome::RolledBack.writes(),
450///     PartialWrites::RolledBack
451/// );
452/// ```
453#[derive(Debug, Clone)]
454#[non_exhaustive]
455pub enum PartialOutcome {
456    /// The written files remain in the destination; the report counts them.
457    Kept(ExtractionReport),
458    /// Atomic extraction discarded the written files; no counters are
459    /// meaningful.
460    RolledBack,
461    /// An in-memory extraction dropped what it collected; no counters are
462    /// meaningful.
463    Discarded,
464}
465
466impl PartialOutcome {
467    /// The [`PartialWrites`] state matching this outcome.
468    #[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/// Error data for FFI consumption.
479///
480/// `#[non_exhaustive]` and output-only: bindings read it, only
481/// [`ArchiveError::into_ffi_message`] builds it.
482#[derive(Debug, Clone)]
483#[non_exhaustive]
484pub struct FfiErrorMessage {
485    /// Error class and its class-specific payload.
486    pub kind: FfiKind,
487
488    /// Human-readable, redacted description.
489    pub description: String,
490
491    /// Set when the error came from a partially completed extraction.
492    pub partial: Option<PartialOutcome>,
493
494    /// The failure behind an unreadable creation source, so a binding can
495    /// expose `errno`, `strerror` and `filename`.
496    pub source_fault: Option<FfiSourceFault>,
497}
498
499/// What a binding needs of an unreadable creation source, redacted like the
500/// rest of the message.
501///
502/// # Examples
503///
504/// ```
505/// use exarch_core::ArchiveError;
506///
507/// let error = ArchiveError::SourceNotAccessible {
508///     path: "src/a.txt".into(),
509///     error: std::io::Error::from_raw_os_error(13),
510/// };
511/// let fault = error.into_ffi_message().source_fault.unwrap();
512/// assert_eq!(fault.raw_os_error, Some(13));
513/// assert!(fault.name.ends_with("a.txt"));
514/// ```
515#[derive(Debug, Clone)]
516#[non_exhaustive]
517pub struct FfiSourceFault {
518    /// The OS error number, when the failure has one.
519    pub raw_os_error: Option<i32>,
520
521    /// The error text: the full `Display` in debug builds, the `ErrorKind`
522    /// description in release builds.
523    pub text: String,
524
525    /// The source path as the shared policy redacts it: the file name only in
526    /// release builds.
527    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    /// Converts the error into the data every binding consumes.
543    ///
544    /// Path and I/O-error text is redacted per the shared policy in
545    /// [`super::redaction`] — see [`Self::redacted_path`] and
546    /// [`sanitize_io_error_for_error`]. A [`Self::PartialExtraction`] yields
547    /// its source's message with [`FfiErrorMessage::partial`] set.
548    ///
549    /// # Examples
550    ///
551    /// ```
552    /// use exarch_core::ArchiveError;
553    /// use exarch_core::ErrorCode;
554    /// use std::path::PathBuf;
555    ///
556    /// let error = ArchiveError::PathTraversal {
557    ///     path: PathBuf::from("../../etc/passwd"),
558    /// };
559    ///
560    /// let msg = error.into_ffi_message();
561    /// assert_eq!(msg.kind.code(), ErrorCode::PathTraversal);
562    /// // Archive-relative, attacker-authored path: never redacted (#462).
563    /// assert!(msg.description.contains("../../etc/passwd"));
564    /// ```
565    #[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    /// The binding-facing class of this error, without consuming it.
589    ///
590    /// The only variant-to-[`FfiKind`] table: [`Self::error_code`] and
591    /// [`Self::into_ffi_message`] derive from it. A
592    /// [`Self::PartialExtraction`] reports its source's kind.
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// use exarch_core::ArchiveError;
598    /// use exarch_core::ErrorCode;
599    /// use exarch_core::Malformation;
600    ///
601    /// let err = ArchiveError::from(Malformation::PackSizesOverflow);
602    /// assert_eq!(err.ffi_kind().code(), ErrorCode::InvalidArchive);
603    /// ```
604    #[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    /// The redacted, binding-facing description.
657    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    /// Returns the stable [`ErrorCode`] of this error.
704    ///
705    /// Useful for matching on error types without full message formatting.
706    ///
707    /// # Examples
708    ///
709    /// ```
710    /// use exarch_core::ArchiveError;
711    /// use exarch_core::ErrorCode;
712    /// use exarch_core::Violation;
713    ///
714    /// let err = ArchiveError::from(Violation::EncryptedArchive);
715    /// assert_eq!(err.error_code(), ErrorCode::SecurityViolation);
716    /// assert_eq!(err.error_code().as_str(), "SECURITY_VIOLATION");
717    /// ```
718    #[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    /// Regression test for #462: `PathTraversal` carries an
768    /// archive-relative, attacker-authored path and must never be redacted,
769    /// unlike a genuinely host-derived path variant (see the test below).
770    #[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    /// Regression test for #453: `SourceNotFound` carries a host filesystem
780    /// path; in release builds it must be redacted to filename-only. This
781    /// only exercises the release-build branch — the debug-build behavior
782    /// is covered directly in `super::redaction`.
783    #[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    /// Regression test for #453: `Io` messages must not leak a host path
795    /// embedded in the free-form message text in release builds.
796    #[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 [&quotas, &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}