Skip to main content

exarch_core/error/
config_error.rs

1//! Typed configuration refusals.
2//!
3//! [`ArchiveError::InvalidConfiguration`] names the setting that was refused
4//! ([`ConfigSetting`]) and why ([`ConfigProblem`]), so a front end can point at
5//! the offending flag or property without parsing a message.
6//!
7//! [`ArchiveError::InvalidConfiguration`]: super::ArchiveError::InvalidConfiguration
8
9use std::fmt;
10use std::path::PathBuf;
11
12use crate::closed_enum::closed_enum;
13use crate::formats::detect::ExtractOnlyFormat;
14
15closed_enum! {
16    /// A configuration value or required input that was refused.
17    ///
18    /// `as_str` is the stable `snake_case` identifier shared by the Python, Node
19    /// and CLI front ends; [`label`](Self::label) is the noun used in messages.
20    ///
21    /// # Examples
22    ///
23    /// ```
24    /// use exarch_core::ConfigSetting;
25    ///
26    /// assert_eq!(ConfigSetting::MaxFileSize.as_str(), "max_file_size");
27    /// assert_eq!(ConfigSetting::AllowedExtension.label(), "allowed extension");
28    /// ```
29    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30    #[non_exhaustive]
31    pub enum ConfigSetting {
32        /// `SecurityConfig::max_file_size`.
33        MaxFileSize => "max_file_size",
34        /// `SecurityConfig::max_total_size`.
35        MaxTotalSize => "max_total_size",
36        /// `SecurityConfig::max_file_count`.
37        MaxFileCount => "max_file_count",
38        /// `SecurityConfig::max_path_depth`.
39        MaxPathDepth => "max_path_depth",
40        /// `SecurityConfig::max_compression_ratio`.
41        MaxCompressionRatio => "max_compression_ratio",
42        /// `SecurityConfig::max_solid_compression_ratio`.
43        MaxSolidCompressionRatio => "max_solid_compression_ratio",
44        /// `SecurityConfig::max_solid_block_memory`.
45        MaxSolidBlockMemory => "max_solid_block_memory",
46        /// `SecurityConfig::max_tar_metadata_bytes`.
47        MaxTarMetadataBytes => "max_tar_metadata_bytes",
48        /// `SecurityConfig::max_decoder_memory`.
49        MaxDecoderMemory => "max_decoder_memory",
50        /// The decompression budget of an integrity check.
51        DecompressionBudget => "decompression_budget",
52        /// An entry of the extension allowlist.
53        AllowedExtension => "allowed_extension",
54        /// An entry of the banned path component list.
55        BannedPathComponent => "banned_path_component",
56        /// The path of the archive to create.
57        OutputPath => "output_path",
58        /// The paths to add to an archive.
59        SourcePaths => "source_paths",
60        /// The prefix stripped from entry names.
61        StripPrefix => "strip_prefix",
62        /// The archive format to create.
63        CreationFormat => "creation_format",
64        /// Atomic extraction.
65        AtomicExtraction => "atomic_extraction",
66        /// The writer a ZIP archive is created into.
67        ZipOutputWriter => "zip_output_writer",
68        /// The byte cap of an in-memory extraction.
69        MaxBytes => "max_bytes",
70        /// `SecurityConfig::parallel_decode`, the lookahead memory of parallel
71        /// 7z decoding.
72        ParallelDecodeMemory => "parallel_decode_memory",
73        /// An entry of the creation exclude patterns.
74        ExcludePattern => "exclude_pattern",
75        /// The ZIP structure policy.
76        ZipConsistency => "zip_consistency",
77        /// The path model of a sink extraction.
78        PathModel => "path_model",
79        /// The archive format of an extraction or listing.
80        ArchiveFormat => "archive_format",
81        /// The decode reuse mode of an extraction.
82        DecodeReuse => "decode_reuse",
83        /// The byte limit of a decode reuse mode.
84        DecodeReuseLimit => "decode_reuse_limit",
85        /// The kind of an entry skip.
86        SkipKind => "skip_kind",
87        /// The durability of a created archive file.
88        Durability => "durability",
89    }
90}
91
92impl ConfigSetting {
93    /// The message of a refused configuration: `"{label} {problem}"`, or
94    /// `"no {label} provided"` for a list that came up empty.
95    ///
96    /// # Examples
97    ///
98    /// ```
99    /// use exarch_core::ConfigProblem;
100    /// use exarch_core::ConfigSetting;
101    ///
102    /// let text = ConfigSetting::MaxFileSize.describe(&ConfigProblem::Zero);
103    /// assert_eq!(text, "max_file_size must not be zero");
104    /// ```
105    #[must_use]
106    pub fn describe(self, problem: &ConfigProblem) -> String {
107        match problem {
108            ConfigProblem::NoneProvided => format!("no {} provided", self.label()),
109            ConfigProblem::NotCreatable { .. } => problem.to_string(),
110            other => format!("{} {other}", self.label()),
111        }
112    }
113
114    /// The noun used for this setting in messages.
115    #[must_use]
116    pub const fn label(self) -> &'static str {
117        match self {
118            Self::DecompressionBudget => "decompression budget",
119            Self::AllowedExtension => "allowed extension",
120            Self::BannedPathComponent => "banned path component",
121            Self::OutputPath => "output path",
122            Self::SourcePaths => "source paths",
123            Self::CreationFormat => "creation format",
124            Self::AtomicExtraction => "atomic extraction",
125            Self::ZipOutputWriter => "ZIP output writer",
126            Self::ParallelDecodeMemory => "parallel decode memory",
127            Self::ExcludePattern => "exclude pattern",
128            Self::ZipConsistency => "zip consistency",
129            Self::PathModel => "path model",
130            Self::ArchiveFormat => "archive format",
131            Self::DecodeReuse => "decode reuse",
132            Self::DecodeReuseLimit => "decode reuse limit",
133            Self::SkipKind => "skip kind",
134            Self::MaxFileSize
135            | Self::MaxTotalSize
136            | Self::MaxFileCount
137            | Self::MaxPathDepth
138            | Self::MaxCompressionRatio
139            | Self::MaxSolidCompressionRatio
140            | Self::MaxSolidBlockMemory
141            | Self::MaxTarMetadataBytes
142            | Self::MaxDecoderMemory
143            | Self::StripPrefix
144            | Self::Durability
145            | Self::MaxBytes => self.as_str(),
146        }
147    }
148}
149
150/// Why a configuration value or input was refused.
151///
152/// # Examples
153///
154/// ```
155/// use exarch_core::ConfigProblem;
156///
157/// assert_eq!(ConfigProblem::Zero.to_string(), "must not be zero");
158/// ```
159#[derive(Debug, Clone, PartialEq, Eq)]
160#[non_exhaustive]
161pub enum ConfigProblem {
162    /// A limit is zero.
163    Zero,
164    /// A byte count is negative.
165    Negative,
166    /// A number is NaN or infinite.
167    NotFinite,
168    /// A number has a fractional part.
169    NotWholeNumber,
170    /// A number is above the largest accepted value.
171    TooLarge {
172        /// The largest accepted value.
173        max: u64,
174    },
175    /// A required input is missing.
176    NotSet,
177    /// No input of this kind was given.
178    NoneProvided,
179    /// The path has no parent directory.
180    NoParent,
181    /// The operation is not supported for this input.
182    NotSupported,
183    /// Atomic extraction cannot target a sink.
184    CannotTargetSink,
185    /// The prefix would remove the whole name of this path.
186    RemovesWholeName {
187        /// The path that would be left without a name.
188        path: PathBuf,
189    },
190    /// The writer is not at offset zero.
191    NotAtStart,
192    /// The entry is empty.
193    Empty,
194    /// The entry has whitespace or control characters.
195    BlankOrControl,
196    /// The entry starts or ends with whitespace or control characters.
197    PaddedWithBlank,
198    /// The entry contains a path separator.
199    ContainsSeparator,
200    /// The extension has an inner dot.
201    InnerDot,
202    /// The entry is `.` or `..`.
203    DotEntry,
204    /// The value is not one of the allowed values.
205    NotOneOf {
206        /// The accepted string forms.
207        allowed: &'static [&'static str],
208    },
209    /// The format can be read but not created.
210    NotCreatable {
211        /// The extract-only format that was asked for.
212        format: ExtractOnlyFormat,
213    },
214    /// The entry is longer than the maximum.
215    TooLong {
216        /// The longest accepted length in bytes.
217        max: usize,
218        /// The length of the entry in bytes.
219        got: usize,
220    },
221    /// The entry contains a NUL byte.
222    ContainsNul,
223    /// A creation exclude pattern the matcher does not support.
224    ExcludePatternRefused {
225        /// The refused pattern text, cut to the maximum entry length.
226        pattern: String,
227        /// Why the pattern is refused.
228        reason: ExcludeRefusal,
229    },
230}
231
232closed_enum! {
233    /// Why a creation exclude pattern is refused.
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// use exarch_core::ExcludeRefusal;
239    ///
240    /// assert_eq!(ExcludeRefusal::GlobMetacharacter.as_str(), "glob_metacharacter");
241    /// ```
242    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
243    #[non_exhaustive]
244    pub enum ExcludeRefusal {
245        /// The pattern is empty
246        Empty => "empty",
247        /// The pattern is longer than the maximum entry length
248        TooLong => "too_long",
249        /// The pattern contains a NUL byte
250        ContainsNul => "contains_nul",
251        /// A path component is `.` or `..`
252        DotEntry => "dot_entry",
253        /// The pattern is an absolute path
254        Absolute => "absolute",
255        /// The wildcard shape is not one of `name`, `name*` and `*name`
256        UnsupportedWildcard => "unsupported_wildcard",
257        /// A `*` is combined with a path separator
258        WildcardWithSeparator => "wildcard_with_separator",
259        /// The pattern holds `?`, `[`, `]`, `{`, `}` or `!`, which would be
260        /// matched literally
261        GlobMetacharacter => "glob_metacharacter",
262        /// The pattern starts or ends with whitespace or a control character
263        PaddedWithBlank => "padded_with_blank",
264        /// The pattern holds a comma, which reads as a list separator
265        ContainsComma => "contains_comma",
266    }
267}
268
269impl ExcludeRefusal {
270    /// A short explanation for a message.
271    #[must_use]
272    pub const fn explanation(self) -> &'static str {
273        match self {
274            Self::Empty => "is empty",
275            Self::TooLong => "is longer than the maximum entry length",
276            Self::ContainsNul => "contains a null byte",
277            Self::DotEntry => "has a `.` or `..` component",
278            Self::Absolute => {
279                "is an absolute path; patterns match archive paths, which are relative"
280            }
281            Self::UnsupportedWildcard => {
282                "uses an unsupported `*` shape; only `name`, `name*` and `*name` are supported"
283            }
284            Self::WildcardWithSeparator => {
285                "combines `*` with a path separator (for `build/*` write `build`)"
286            }
287            Self::GlobMetacharacter => {
288                "contains `?`, `[`, `]`, `{`, `}` or `!`, which are not glob syntax here and would match literally"
289            }
290            Self::PaddedWithBlank => "starts or ends with whitespace",
291            Self::ContainsComma => "contains a comma; give one pattern per option",
292        }
293    }
294}
295
296impl fmt::Display for ConfigProblem {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        match self {
299            Self::Zero => f.write_str("must not be zero"),
300            Self::Negative => f.write_str("must not be negative"),
301            Self::NotOneOf { allowed } => {
302                write!(
303                    f,
304                    "is not one of the allowed values: {}",
305                    allowed.join(", ")
306                )
307            }
308            Self::NotCreatable { format } => {
309                write!(
310                    f,
311                    "{} archive creation is not supported",
312                    format.extension()
313                )
314            }
315            Self::NotFinite => f.write_str("must be a finite number"),
316            Self::NotWholeNumber => f.write_str("must be a whole number"),
317            Self::TooLarge { max } => write!(f, "must not exceed {max}"),
318            Self::NotSet => f.write_str("not set"),
319            Self::NoneProvided => f.write_str("none provided"),
320            Self::NoParent => f.write_str("has no parent"),
321            Self::NotSupported => f.write_str("is not supported"),
322            Self::CannotTargetSink => f.write_str("renames a directory and cannot target a sink"),
323            Self::RemovesWholeName { path } => {
324                write!(f, "removes the whole name of {}", path.display())
325            }
326            Self::NotAtStart => f.write_str("must be positioned at offset 0"),
327            Self::Empty => f.write_str("must not be empty"),
328            Self::BlankOrControl => {
329                f.write_str("must not contain whitespace or control characters")
330            }
331            Self::PaddedWithBlank => {
332                f.write_str("must not start or end with whitespace or control characters")
333            }
334            Self::ContainsSeparator => f.write_str("must not contain a path separator"),
335            Self::InnerDot => f.write_str(
336                "must be a single extension without an inner dot (use `gz`, not `tar.gz`)",
337            ),
338            Self::DotEntry => f.write_str("must not be `.` or `..`"),
339            Self::TooLong { max, got } => {
340                write!(f, "exceeds maximum length of {max} bytes (got {got} bytes)")
341            }
342            Self::ContainsNul => f.write_str("contains null bytes - potential security issue"),
343            Self::ExcludePatternRefused { pattern, reason } => {
344                write!(f, "{pattern:?} {}", reason.explanation())
345            }
346        }
347    }
348}
349
350pub(crate) fn message(setting: ConfigSetting, problem: &ConfigProblem) -> String {
351    setting.describe(problem)
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn the_ffi_kind_names_the_setting() {
360        let err = crate::ArchiveError::InvalidConfiguration {
361            setting: ConfigSetting::MaxFileCount,
362            problem: ConfigProblem::Zero,
363        };
364        assert_eq!(err.ffi_kind().setting(), Some(ConfigSetting::MaxFileCount));
365        assert_eq!(
366            crate::ArchiveError::from(crate::Malformation::PackSizesOverflow)
367                .ffi_kind()
368                .setting(),
369            None
370        );
371    }
372
373    #[test]
374    fn a_host_path_keeps_its_native_spelling() {
375        let problem = ConfigProblem::RemovesWholeName {
376            path: PathBuf::from("C:\\src\\a"),
377        };
378        let text = problem.to_string();
379        assert!(text.ends_with("C:\\src\\a"), "{text}");
380    }
381
382    #[test]
383    fn messages_keep_their_established_text() {
384        let cases = [
385            (
386                ConfigSetting::MaxFileSize,
387                ConfigProblem::Zero,
388                "max_file_size must not be zero",
389            ),
390            (
391                ConfigSetting::MaxCompressionRatio,
392                ConfigProblem::NotFinite,
393                "max_compression_ratio must be a finite number",
394            ),
395            (
396                ConfigSetting::DecompressionBudget,
397                ConfigProblem::Zero,
398                "decompression budget must not be zero",
399            ),
400            (
401                ConfigSetting::SourcePaths,
402                ConfigProblem::NoneProvided,
403                "no source paths provided",
404            ),
405            (
406                ConfigSetting::OutputPath,
407                ConfigProblem::NoParent,
408                "output path has no parent",
409            ),
410            (
411                ConfigSetting::CreationFormat,
412                ConfigProblem::NotCreatable {
413                    format: ExtractOnlyFormat::SevenZ,
414                },
415                "7z archive creation is not supported",
416            ),
417            (
418                ConfigSetting::AtomicExtraction,
419                ConfigProblem::CannotTargetSink,
420                "atomic extraction renames a directory and cannot target a sink",
421            ),
422            (
423                ConfigSetting::DecodeReuse,
424                ConfigProblem::NotOneOf {
425                    allowed: crate::DecodeReuseKind::NAMES,
426                },
427                "decode reuse is not one of the allowed values: off, memory, temp_file",
428            ),
429            (
430                ConfigSetting::StripPrefix,
431                ConfigProblem::RemovesWholeName { path: "a".into() },
432                "strip_prefix removes the whole name of a",
433            ),
434            (
435                ConfigSetting::ZipOutputWriter,
436                ConfigProblem::NotAtStart,
437                "ZIP output writer must be positioned at offset 0",
438            ),
439            (
440                ConfigSetting::AllowedExtension,
441                ConfigProblem::TooLong { max: 4, got: 5 },
442                "allowed extension exceeds maximum length of 4 bytes (got 5 bytes)",
443            ),
444        ];
445        for (setting, problem, text) in cases {
446            assert_eq!(message(setting, &problem), text);
447        }
448    }
449}