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::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    /// Stable machine-readable identifier of an [`ArchiveError`] variant.
18    ///
19    /// The spellings are part of every binding's observable contract; the
20    /// bindings take them from [`ErrorCode::as_str`].
21    ///
22    /// # Examples
23    ///
24    /// ```
25    /// use exarch_core::ErrorCode;
26    ///
27    /// assert_eq!(ErrorCode::ZipBomb.as_str(), "ZIP_BOMB");
28    /// assert!(ErrorCode::ALL.contains(&ErrorCode::PathTraversal));
29    /// ```
30    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31    #[non_exhaustive]
32    pub enum ErrorCode {
33        /// [`ArchiveError::PathTraversal`].
34        PathTraversal => "PATH_TRAVERSAL",
35        /// [`ArchiveError::SymlinkEscape`].
36        SymlinkEscape => "SYMLINK_ESCAPE",
37        /// [`ArchiveError::HardlinkEscape`].
38        HardlinkEscape => "HARDLINK_ESCAPE",
39        /// [`ArchiveError::ZipBomb`].
40        ZipBomb => "ZIP_BOMB",
41        /// [`ArchiveError::ZipInconsistency`].
42        ZipInconsistency => "ZIP_INCONSISTENCY",
43        /// [`ArchiveError::QuotaExceeded`].
44        QuotaExceeded => "QUOTA_EXCEEDED",
45        /// [`ArchiveError::SecurityViolation`].
46        SecurityViolation => "SECURITY_VIOLATION",
47        /// [`ArchiveError::InvalidArchive`].
48        InvalidArchive => "INVALID_ARCHIVE",
49        /// [`ArchiveError::Io`].
50        IoError => "IO_ERROR",
51        /// [`ArchiveError::InvalidPermissions`].
52        InvalidPermissions => "INVALID_PERMISSIONS",
53        /// [`ArchiveError::SourceNotFound`].
54        SourceNotFound => "SOURCE_NOT_FOUND",
55        /// [`ArchiveError::SourceNotAccessible`].
56        SourceNotAccessible => "SOURCE_NOT_ACCESSIBLE",
57        /// [`ArchiveError::OutputExists`].
58        OutputExists => "OUTPUT_EXISTS",
59        /// [`ArchiveError::InvalidCompressionLevel`].
60        InvalidCompressionLevel => "INVALID_COMPRESSION_LEVEL",
61        /// [`ArchiveError::UnknownFormat`].
62        UnknownFormat => "UNKNOWN_FORMAT",
63        /// [`ArchiveError::InvalidConfiguration`].
64        InvalidConfiguration => "INVALID_CONFIGURATION",
65    }
66}
67
68/// The error class of an [`FfiErrorMessage`], with the payload that class
69/// carries.
70///
71/// One variant per [`ErrorCode`]; [`FfiKind::code`] is the bijection.
72/// Payload lives inside the variant so a binding cannot read a field that
73/// does not exist for the class.
74///
75/// # Examples
76///
77/// ```
78/// use exarch_core::ArchiveError;
79/// use exarch_core::ErrorCode;
80/// use exarch_core::FfiKind;
81/// use std::assert_matches;
82///
83/// let msg = ArchiveError::violation("nope".into()).into_ffi_message();
84/// assert_matches!(msg.kind, FfiKind::SecurityViolation { relaxable_by: None });
85/// assert_eq!(msg.kind.code(), ErrorCode::SecurityViolation);
86/// ```
87#[derive(Debug, Clone, PartialEq, Eq)]
88#[non_exhaustive]
89pub enum FfiKind {
90    /// Entry path escapes the destination.
91    PathTraversal,
92    /// Symlink target escapes the destination.
93    SymlinkEscape,
94    /// Hardlink target escapes the destination.
95    HardlinkEscape,
96    /// Compression ratio limit exceeded.
97    ZipBomb,
98    /// ZIP structure is ambiguous or self-contradictory.
99    ZipInconsistency,
100    /// A quota was exceeded.
101    QuotaExceeded,
102    /// Denied by security policy.
103    SecurityViolation {
104        /// The `SecurityConfig` setting whose current value refused the
105        /// entry; see [`ArchiveError::relaxable_by`].
106        relaxable_by: Option<PolicySetting>,
107    },
108    /// Archive is corrupted or malformed.
109    InvalidArchive,
110    /// I/O failure of the given kind.
111    Io(std::io::ErrorKind),
112    /// Invalid permission bits.
113    InvalidPermissions,
114    /// Creation source does not exist.
115    SourceNotFound,
116    /// Creation source cannot be read.
117    SourceNotAccessible,
118    /// Output file already exists.
119    OutputExists,
120    /// Compression level out of range.
121    InvalidCompressionLevel,
122    /// Archive format could not be determined.
123    UnknownFormat,
124    /// Configuration is invalid.
125    InvalidConfiguration,
126}
127
128impl FfiKind {
129    /// The stable [`ErrorCode`] of this class.
130    #[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/// What happened to the output of an extraction that stopped part-way.
154///
155/// # Examples
156///
157/// ```
158/// use exarch_core::PartialOutcome;
159/// use exarch_core::PartialWrites;
160///
161/// assert_eq!(
162///     PartialOutcome::RolledBack.writes(),
163///     PartialWrites::RolledBack
164/// );
165/// ```
166#[derive(Debug, Clone)]
167#[non_exhaustive]
168pub enum PartialOutcome {
169    /// The written files remain in the destination; the report counts them.
170    Kept(ExtractionReport),
171    /// Atomic extraction discarded the written files; no counters are
172    /// meaningful.
173    RolledBack,
174    /// An in-memory extraction dropped what it collected; no counters are
175    /// meaningful.
176    Discarded,
177}
178
179impl PartialOutcome {
180    /// The [`PartialWrites`] state matching this outcome.
181    #[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/// Error data for FFI consumption.
192///
193/// `#[non_exhaustive]` and output-only: bindings read it, only
194/// [`ArchiveError::into_ffi_message`] builds it.
195#[derive(Debug, Clone)]
196#[non_exhaustive]
197pub struct FfiErrorMessage {
198    /// Error class and its class-specific payload.
199    pub kind: FfiKind,
200
201    /// Human-readable, redacted description.
202    pub description: String,
203
204    /// Set when the error came from a partially completed extraction.
205    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    /// Converts the error into the data every binding consumes.
220    ///
221    /// Path and I/O-error text is redacted per the shared policy in
222    /// [`super::redaction`] — see [`Self::redacted_path`] and
223    /// [`sanitize_io_error_for_error`]. A [`Self::PartialExtraction`] yields
224    /// its source's message with [`FfiErrorMessage::partial`] set.
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// use exarch_core::ArchiveError;
230    /// use exarch_core::ErrorCode;
231    /// use std::path::PathBuf;
232    ///
233    /// let error = ArchiveError::PathTraversal {
234    ///     path: PathBuf::from("../../etc/passwd"),
235    /// };
236    ///
237    /// let msg = error.into_ffi_message();
238    /// assert_eq!(msg.kind.code(), ErrorCode::PathTraversal);
239    /// // Archive-relative, attacker-authored path: never redacted (#462).
240    /// assert!(msg.description.contains("../../etc/passwd"));
241    /// ```
242    #[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    /// The only variant-to-[`FfiKind`] table; [`Self::error_code`] derives
262    /// from it.
263    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    /// The redacted, binding-facing description.
292    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    /// Returns the stable [`ErrorCode`] of this error.
332    ///
333    /// Useful for matching on error types without full message formatting.
334    ///
335    /// # Examples
336    ///
337    /// ```
338    /// use exarch_core::ArchiveError;
339    /// use exarch_core::ErrorCode;
340    ///
341    /// let err = ArchiveError::violation("nope".into());
342    /// assert_eq!(err.error_code(), ErrorCode::SecurityViolation);
343    /// assert_eq!(err.error_code().as_str(), "SECURITY_VIOLATION");
344    /// ```
345    #[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    /// Regression test for #462: `PathTraversal` carries an
361    /// archive-relative, attacker-authored path and must never be redacted,
362    /// unlike a genuinely host-derived path variant (see the test below).
363    #[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    /// Regression test for #453: `SourceNotFound` carries a host filesystem
373    /// path; in release builds it must be redacted to filename-only. This
374    /// only exercises the release-build branch — the debug-build behavior
375    /// is covered directly in `super::redaction`.
376    #[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    /// Regression test for #453: `Io` messages must not leak a host path
388    /// embedded in the free-form message text in release builds.
389    #[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}