Skip to main content

exarch_core/
config.rs

1//! Security configuration for archive extraction.
2
3use std::num::NonZeroU64;
4use std::num::NonZeroUsize;
5
6use crate::ConfigProblem;
7use crate::ConfigSetting;
8use crate::Limit;
9use crate::RatioLimit;
10use crate::closed_enum::closed_enum;
11use crate::non_zero;
12use crate::non_zero_u64;
13use crate::types::Extension;
14use crate::types::PathComponentName;
15
16closed_enum! {
17    /// Whether an archive feature is admitted.
18    ///
19    /// Names the stored state of each [`AllowedFeatures`] field instead of an
20    /// unlabeled `bool`. The default is [`Refuse`](Admit::Refuse), the
21    /// deny-by-default policy.
22    ///
23    /// # Examples
24    ///
25    /// ```
26    /// use exarch_core::Admit;
27    /// use exarch_core::SecurityConfig;
28    ///
29    /// assert_eq!(SecurityConfig::default().allowed.symlinks, Admit::Refuse);
30    /// let config = SecurityConfig::default().with_allow_symlinks(true);
31    /// assert!(config.allowed.symlinks.is_allowed());
32    /// assert_eq!(Admit::from_allowed(false), Admit::Refuse);
33    /// ```
34    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
35    pub enum Admit {
36        /// The feature is refused
37        #[default]
38        Refuse => "refuse",
39
40        /// The feature is admitted
41        Allow => "allow",
42    }
43}
44
45impl Admit {
46    /// Returns `true` for [`Allow`](Admit::Allow).
47    #[must_use]
48    pub const fn is_allowed(self) -> bool {
49        matches!(self, Self::Allow)
50    }
51
52    /// [`Allow`](Admit::Allow) when `allowed` is `true`, otherwise
53    /// [`Refuse`](Admit::Refuse).
54    #[must_use]
55    pub const fn from_allowed(allowed: bool) -> Self {
56        if allowed { Self::Allow } else { Self::Refuse }
57    }
58}
59
60/// Feature flags controlling what archive features are allowed during
61/// extraction.
62///
63/// All features default to [`Admit::Refuse`] (deny-by-default security policy).
64#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct AllowedFeatures {
67    /// Allow symlinks in extracted archives.
68    pub symlinks: Admit,
69
70    /// Allow hardlinks in extracted archives.
71    pub hardlinks: Admit,
72
73    /// Allow absolute paths in archive entries.
74    pub absolute_paths: Admit,
75
76    /// Allow world-writable files (mode 0o002).
77    ///
78    /// World-writable files pose security risks in multi-user environments.
79    pub world_writable: Admit,
80
81    /// Allow Windows reserved device names (`CON`, `NUL`, `COM1`, ...) as path
82    /// components.
83    ///
84    /// Only consulted when extracting on Windows; has no effect elsewhere.
85    /// There is no CLI or binding opt-out, and the permissive preset does not
86    /// enable it.
87    pub windows_reserved_names: Admit,
88}
89
90const DEFAULT_BANNED_PATH_COMPONENTS: [&str; 7] =
91    [".git", ".ssh", ".gnupg", ".aws", ".kube", ".docker", ".env"];
92
93fn default_banned_path_components() -> Vec<PathComponentName> {
94    // The constants are valid by construction;
95    // `default_banned_components_are_all_usable` pins it.
96    DEFAULT_BANNED_PATH_COMPONENTS
97        .iter()
98        .filter_map(|name| PathComponentName::try_from(*name).ok())
99        .collect()
100}
101
102closed_enum! {
103    /// How ZIP structure that different readers interpret differently is
104    /// handled.
105    ///
106    /// A ZIP archive stores each entry's metadata twice, in a local header and
107    /// in the central directory. Random-access readers follow the central
108    /// directory and streaming readers follow the local headers, so an
109    /// archive whose copies disagree, that hides records, repeats a name or
110    /// overlaps entries is a parser differential ("Zip Cloaking").
111    ///
112    /// `Enforce` (the default, also for [`SecurityConfig::permissive`])
113    /// rejects such archives in `extract` and `list` and reports them in
114    /// `verify`. `Ignore` keeps the central-directory interpretation and
115    /// raises no structural finding; resource limits still apply.
116    ///
117    /// # Examples
118    ///
119    /// ```
120    /// use exarch_core::SecurityConfig;
121    /// use exarch_core::ZipConsistencyPolicy;
122    ///
123    /// assert_eq!(
124    ///     SecurityConfig::default().zip_consistency,
125    ///     ZipConsistencyPolicy::Enforce
126    /// );
127    /// let relaxed = SecurityConfig::default().with_zip_consistency(ZipConsistencyPolicy::Ignore);
128    /// assert_eq!(relaxed.zip_consistency.as_str(), "ignore");
129    /// ```
130    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
131    #[non_exhaustive]
132    pub enum ZipConsistencyPolicy {
133        /// Reject or report structurally ambiguous ZIP archives
134        #[default]
135        Enforce => "enforce",
136
137        /// Use the central directory interpretation without structural findings
138        Ignore => "ignore",
139    }
140}
141
142/// Limits applied to a solid 7z archive that is admitted.
143///
144/// A solid block compresses several files into one stream, so no per-file
145/// ratio exists: `max_ratio` replaces
146/// [`max_compression_ratio`](SecurityConfig::max_compression_ratio) for its
147/// members. The limits exist only inside [`SolidArchives::Allow`], so they
148/// cannot be set while solid archives are refused.
149///
150/// # Examples
151///
152/// ```
153/// use exarch_core::SolidLimits;
154///
155/// let limits = SolidLimits::DEFAULT.with_max_block_memory(exarch_core::non_zero!(1 << 20));
156/// assert_eq!(limits.max_block_memory.get(), 1 << 20);
157/// assert_eq!(limits.max_ratio, SolidLimits::DEFAULT.max_ratio);
158/// ```
159#[derive(Debug, Clone, Copy, PartialEq)]
160#[non_exhaustive]
161pub struct SolidLimits {
162    /// Maximum decoded size of a solid archive, in bytes.
163    ///
164    /// Solid members share one compressed stream, so a crafted block can
165    /// declare a far larger decoded size than its compressed size suggests.
166    /// The check compares the declared uncompressed sizes of the archive's
167    /// files with this value before any data is decoded.
168    pub max_block_memory: NonZeroU64,
169
170    /// Maximum compression ratio of a whole solid block (summed uncompressed
171    /// size of its files / compressed size of its pack streams).
172    pub max_ratio: RatioLimit,
173}
174
175impl SolidLimits {
176    /// 512 MiB of block memory and a ratio of 1000: the limits of
177    /// [`SecurityConfig::default`] once solid archives are allowed.
178    pub const DEFAULT: Self = Self {
179        max_block_memory: non_zero!(512 * 1024 * 1024),
180        max_ratio: crate::ratio_limit!(1000.0),
181    };
182    /// 1 GiB of block memory and a ratio of 10,000, as in
183    /// [`SecurityConfig::permissive`].
184    pub const PERMISSIVE: Self = Self {
185        max_block_memory: non_zero!(1024 * 1024 * 1024),
186        max_ratio: crate::ratio_limit!(10_000.0),
187    };
188
189    /// Limits from explicit values.
190    #[must_use]
191    pub const fn new(max_block_memory: NonZeroU64, max_ratio: RatioLimit) -> Self {
192        Self {
193            max_block_memory,
194            max_ratio,
195        }
196    }
197
198    /// Replaces [`max_block_memory`](Self::max_block_memory).
199    #[must_use]
200    pub const fn with_max_block_memory(mut self, max_block_memory: NonZeroU64) -> Self {
201        self.max_block_memory = max_block_memory;
202        self
203    }
204
205    /// Replaces [`max_ratio`](Self::max_ratio).
206    #[must_use]
207    pub const fn with_max_ratio(mut self, max_ratio: RatioLimit) -> Self {
208        self.max_ratio = max_ratio;
209        self
210    }
211}
212
213impl Default for SolidLimits {
214    fn default() -> Self {
215        Self::DEFAULT
216    }
217}
218
219/// Whether solid 7z archives are extracted, and under which limits.
220///
221/// Solid archives compress several files into one block, so extracting any
222/// file requires decoding the block. A crafted archive can declare a huge
223/// block, which makes admitting solid archives a memory and CPU risk: enable
224/// them only for trusted input. The limits live in [`Allow`](Self::Allow), so
225/// they cannot be set and then ignored while the policy is
226/// [`Refuse`](Self::Refuse).
227///
228/// # Examples
229///
230/// ```
231/// use exarch_core::SecurityConfig;
232/// use exarch_core::SolidArchives;
233/// use exarch_core::SolidLimits;
234///
235/// assert_eq!(
236///     SecurityConfig::default().solid_archives,
237///     SolidArchives::Refuse
238/// );
239/// let config = SecurityConfig::default().with_allow_solid_archives(true);
240/// assert_eq!(config.solid_archives.limits(), Some(SolidLimits::DEFAULT));
241/// ```
242#[derive(Debug, Clone, Copy, Default, PartialEq)]
243#[non_exhaustive]
244pub enum SolidArchives {
245    /// Solid archives are rejected
246    #[default]
247    Refuse,
248
249    /// Solid archives are extracted within these limits
250    Allow(SolidLimits),
251}
252
253impl SolidArchives {
254    /// The limits of an admitted policy, or `None` under
255    /// [`Refuse`](Self::Refuse).
256    #[must_use]
257    pub const fn limits(self) -> Option<SolidLimits> {
258        match self {
259            Self::Refuse => None,
260            Self::Allow(limits) => Some(limits),
261        }
262    }
263
264    /// Returns `true` for [`Allow`](Self::Allow).
265    #[must_use]
266    pub const fn is_allowed(self) -> bool {
267        matches!(self, Self::Allow(_))
268    }
269
270    /// Admits or refuses solid archives.
271    ///
272    /// `true` keeps the limits of an already admitted policy and otherwise
273    /// admits under [`SolidLimits::DEFAULT`]; `false` refuses and drops any
274    /// limits.
275    #[must_use]
276    pub const fn with_allowed(self, allow: bool) -> Self {
277        match (allow, self) {
278            (true, admitted @ Self::Allow(_)) => admitted,
279            (true, Self::Refuse) => Self::Allow(SolidLimits::DEFAULT),
280            (false, _) => Self::Refuse,
281        }
282    }
283
284    /// Replaces the limits of an admitted policy.
285    ///
286    /// # Errors
287    ///
288    /// Returns [`crate::ArchiveError::InvalidConfiguration`] naming
289    /// [`ConfigSetting::MaxSolidBlockMemory`] under [`Refuse`](Self::Refuse),
290    /// because the limits would be silently ignored.
291    pub fn with_limits(self, limits: SolidLimits) -> crate::Result<Self> {
292        match self {
293            Self::Allow(_) => Ok(Self::Allow(limits)),
294            Self::Refuse => Err(crate::ArchiveError::InvalidConfiguration {
295                setting: ConfigSetting::MaxSolidBlockMemory,
296                problem: ConfigProblem::NotSupported,
297            }),
298        }
299    }
300
301    /// Replaces only the block memory limit of an admitted policy, keeping its
302    /// ratio.
303    ///
304    /// # Errors
305    ///
306    /// Fails as [`with_limits`](Self::with_limits) does.
307    ///
308    /// # Examples
309    ///
310    /// ```
311    /// use exarch_core::SolidArchives;
312    /// use exarch_core::SolidLimits;
313    ///
314    /// let memory = exarch_core::non_zero!(1 << 20);
315    /// assert!(SolidArchives::Refuse.with_max_block_memory(memory).is_err());
316    ///
317    /// let allowed = SolidArchives::Allow(SolidLimits::PERMISSIVE).with_max_block_memory(memory)?;
318    /// let limits = allowed.limits().expect("an admitted policy has limits");
319    /// assert_eq!(limits.max_block_memory, memory);
320    /// assert_eq!(limits.max_ratio, SolidLimits::PERMISSIVE.max_ratio);
321    /// # Ok::<(), exarch_core::ArchiveError>(())
322    /// ```
323    pub fn with_max_block_memory(self, max_block_memory: NonZeroU64) -> crate::Result<Self> {
324        match self {
325            Self::Allow(limits) => Ok(Self::Allow(limits.with_max_block_memory(max_block_memory))),
326            Self::Refuse => self.with_limits(SolidLimits::DEFAULT),
327        }
328    }
329}
330
331/// How much extra memory a 7z block may use to decode LZMA2 runs ahead on
332/// worker threads.
333///
334/// An LZMA2 stream written with multiple threads (7-Zip's default for large
335/// inputs) consists of independent runs, so several can be decoded at once.
336/// Decoded runs wait in memory until the consumer reaches them, so the
337/// lookahead is bounded: `Bounded(n)` lets in-flight runs hold at most `n`
338/// bytes on top of the decoder window that
339/// [`max_decoder_memory`](SecurityConfig::max_decoder_memory) already
340/// admits. `Sequential` decodes on the calling thread only.
341///
342/// Archives written with runs of a few MiB decode within about 10% of an
343/// unbounded multi-threaded reader at the default; a stock 7-Zip archive has
344/// 64 MiB runs and needs about 100 MiB of lookahead
345/// per extra concurrent run.
346///
347/// A valid archive decodes to the same bytes in either mode, and a corrupt one
348/// fails the same file with the same error kind; only how many leading bytes
349/// that file received can differ.
350///
351/// # Concurrency
352///
353/// The limit applies to one extraction or verification. Each call may start
354/// up to 16 worker threads and hold its own lookahead, so concurrent calls
355/// (for example from several Python threads or Node promises) multiply both
356/// the threads and the memory. Size the setting for the number of calls that
357/// can run at once, or use `Sequential`.
358///
359/// # Examples
360///
361/// ```
362/// use std::num::NonZeroU64;
363///
364/// use exarch_core::ParallelDecode;
365/// use exarch_core::SecurityConfig;
366///
367/// assert_eq!(
368///     SecurityConfig::default().parallel_decode,
369///     ParallelDecode::Bounded(NonZeroU64::new(128 * 1024 * 1024).unwrap())
370/// );
371/// let config = SecurityConfig::default().with_parallel_decode(ParallelDecode::Sequential);
372/// assert_eq!(config.parallel_decode, ParallelDecode::Sequential);
373/// ```
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375#[non_exhaustive]
376pub enum ParallelDecode {
377    /// Decode on the calling thread only
378    Sequential,
379
380    /// Decode runs ahead on worker threads, holding at most this many bytes
381    Bounded(NonZeroU64),
382}
383
384/// Default base of the compressed member allowance.
385pub(crate) const DEFAULT_MEMBER_ALLOWANCE: NonZeroU64 = non_zero!(10_000);
386
387impl ParallelDecode {
388    /// Default lookahead: 128 MiB.
389    pub const DEFAULT_BYTES: NonZeroU64 = non_zero!(128 * 1024 * 1024);
390
391    /// The lookahead memory in bytes, or `None` for [`Sequential`].
392    ///
393    /// [`Sequential`]: ParallelDecode::Sequential
394    ///
395    /// # Examples
396    ///
397    /// ```
398    /// use std::num::NonZeroU64;
399    ///
400    /// use exarch_core::ParallelDecode;
401    ///
402    /// assert_eq!(ParallelDecode::Sequential.lookahead(), None);
403    /// let bytes = NonZeroU64::new(1 << 20).unwrap();
404    /// assert_eq!(ParallelDecode::Bounded(bytes).lookahead(), Some(bytes));
405    /// ```
406    #[must_use]
407    pub const fn lookahead(self) -> Option<NonZeroU64> {
408        match self {
409            Self::Sequential => None,
410            Self::Bounded(bytes) => Some(bytes),
411        }
412    }
413}
414
415impl ParallelDecode {
416    /// The mode for an optional lookahead: `None` is
417    /// [`Sequential`](Self::Sequential).
418    ///
419    /// # Examples
420    ///
421    /// ```
422    /// use std::num::NonZeroU64;
423    ///
424    /// use exarch_core::ParallelDecode;
425    ///
426    /// assert_eq!(ParallelDecode::from_bytes(None), ParallelDecode::Sequential);
427    /// let bytes = NonZeroU64::MIN;
428    /// assert_eq!(
429    ///     ParallelDecode::from_bytes(Some(bytes)),
430    ///     ParallelDecode::Bounded(bytes)
431    /// );
432    /// ```
433    #[must_use]
434    pub const fn from_bytes(lookahead: Option<NonZeroU64>) -> Self {
435        match lookahead {
436            Some(bytes) => Self::Bounded(bytes),
437            None => Self::Sequential,
438        }
439    }
440}
441
442impl From<Option<NonZeroU64>> for ParallelDecode {
443    fn from(lookahead: Option<NonZeroU64>) -> Self {
444        Self::from_bytes(lookahead)
445    }
446}
447
448impl Default for ParallelDecode {
449    fn default() -> Self {
450        Self::Bounded(Self::DEFAULT_BYTES)
451    }
452}
453
454/// Security configuration with default-deny settings.
455///
456/// This configuration controls various security checks performed during
457/// archive extraction to prevent common vulnerabilities.
458///
459/// # Performance Note
460///
461/// This struct contains heap-allocated collections
462/// (`Vec<Extension>`/`Vec<PathComponentName>`). For performance, pass by
463/// reference (`&SecurityConfig`) rather than cloning. If shared ownership is
464/// needed across threads, consider wrapping in `Arc<SecurityConfig>`.
465///
466/// # Examples
467///
468/// ```
469/// use exarch_core::SecurityConfig;
470///
471/// // Use secure defaults
472/// let config = SecurityConfig::default();
473///
474/// // Customize via fluent builder
475/// let custom = SecurityConfig::default()
476///     .with_max_file_size(exarch_core::non_zero!(100 * 1024 * 1024))
477///     .with_max_total_size(exarch_core::non_zero!(1024 * 1024 * 1024))
478///     .with_allow_symlinks(true);
479/// ```
480#[derive(Debug, Clone)]
481#[non_exhaustive]
482pub struct SecurityConfig {
483    /// Maximum size for a single file in bytes.
484    pub max_file_size: Limit<NonZeroU64>,
485
486    /// Maximum total size for all extracted files in bytes.
487    pub max_total_size: Limit<NonZeroU64>,
488
489    /// Maximum compression ratio allowed (uncompressed / compressed).
490    pub max_compression_ratio: RatioLimit,
491
492    /// Maximum number of entries that can be extracted.
493    ///
494    /// The extraction API counts files, symlinks and hardlinks, not
495    /// directories. `list` and `verify`, and the CLI's `extract` (which lists
496    /// the archive first), count every entry.
497    pub max_file_count: Limit<NonZeroUsize>,
498
499    /// Maximum path depth allowed.
500    pub max_path_depth: NonZeroUsize,
501
502    /// Feature flags controlling what archive features are allowed.
503    ///
504    /// Use this to enable symlinks, hardlinks, absolute paths, etc.
505    pub allowed: AllowedFeatures,
506
507    /// Preserve file permissions from archive.
508    pub preserve_permissions: bool,
509
510    /// List of allowed file extensions (empty = allow all).
511    ///
512    /// Extensions are matched case-insensitively (e.g., `txt` matches both
513    /// `file.txt` and `file.TXT`); [`Extension`] normalizes a leading dot away.
514    ///
515    /// When this list is non-empty, files without a file extension are treated
516    /// as not allowed and will be skipped during extraction.
517    pub allowed_extensions: Vec<Extension>,
518
519    /// List of banned path components (e.g., ".git", ".ssh").
520    pub banned_path_components: Vec<PathComponentName>,
521
522    /// Whether solid 7z archives are extracted, and under which limits.
523    ///
524    /// Solid archives compress multiple files together as a single block.
525    /// While this provides better compression ratios, it has security
526    /// implications:
527    ///
528    /// - **Denial of service**: a malicious archive can declare very large
529    ///   solid blocks that exhaust CPU time and disk space
530    /// - **Decoded volume**: the block limit bounds the decoded size of the
531    ///   archive's files, not resident memory; decoding streams, and the memory
532    ///   of parallel decoding is bounded by
533    ///   [`parallel_decode`](Self::parallel_decode)
534    ///
535    /// **Security Recommendation**: Only enable for trusted archives.
536    ///
537    /// Default: [`SolidArchives::Refuse`] (solid archives rejected). The limits
538    /// of an admitted policy default to [`SolidLimits::DEFAULT`] (512 MiB,
539    /// ratio 1000).
540    pub solid_archives: SolidArchives,
541
542    /// Maximum bytes the TAR reader may consume for headers and metadata
543    /// records in the gap between two consecutive entries.
544    ///
545    /// **TAR Metadata Buffering Model:**
546    ///
547    /// GNU long-name (`L`), GNU long-link (`K`), and PAX extended header
548    /// (`x`/`g`) records are buffered fully into memory by the underlying
549    /// `tar` crate *before* any entry reaches the entry validator or quota
550    /// tracker — a crafted record can declare a multi-gigabyte length backed
551    /// by a tiny compressed stream, exhausting memory with no quota
552    /// enforcement (metadata-entry decompression bomb).
553    ///
554    /// **Enforcement Strategy:**
555    /// - A read-budget wrapper meters bytes the `tar` crate reads while
556    ///   searching for the next entry (headers, long-name/long-link/PAX
557    ///   records, GNU sparse extension blocks) and returns an error once
558    ///   `max_tar_metadata_bytes` is exceeded, before any oversized allocation
559    ///   completes
560    /// - Applies uniformly to `extract`, `list`, and `verify`
561    /// - The window this bounds contains no entry *data* — only metadata — so
562    ///   it does not interact with `max_file_size`/`max_total_size`. Draining
563    ///   an unread entry before the next header search is a separate concern
564    ///   (see `formats::tar_metadata_limit`'s module docs) bounded by
565    ///   synthesized-byte accounting, not by this or any other quota value
566    /// - Legitimate long-path/xattr metadata records are at most a few
567    ///   kilobytes each, and a GNU tar sparse file with heavy fragmentation can
568    ///   use up to a few thousand 512-byte extension blocks; either or both
569    ///   share this single budget (not "plus" each other), so the default
570    ///   leaves headroom for either shape, not necessarily both at their
571    ///   extremes simultaneously
572    /// - The real peak memory this bounds is roughly 5x the configured value
573    ///   (GNU sparse extension blocks expand into multiple `EntryIo` records
574    ///   per block before the growth is charged against this budget), not an
575    ///   exact multiple — treat it as an order-of-magnitude ceiling, not a
576    ///   tight bound
577    /// - Also caps the decoded bytes that follow the end-of-archive marker of a
578    ///   compressed TAR, which extraction, listing and `verify` with integrity
579    ///   read to the end of the stream so the codec's trailer (a gzip CRC) is
580    ///   checked. That cap never falls below 1 MiB (it covers `tar -b 2048`
581    ///   record padding), so lowering this value under 1 MiB does not tighten
582    ///   it; a longer tail is refused naming the effective cap
583    ///
584    /// Default: 4 MiB (4,194,304 bytes)
585    pub max_tar_metadata_bytes: NonZeroU64,
586
587    /// Maximum memory in bytes a decoder may use for its dictionary or window.
588    ///
589    /// The xz block header declares the LZMA2 dictionary size (up to 4 GiB)
590    /// and a zstd frame header declares its window (up to 2^41 bytes), so
591    /// without a limit a tiny archive can drive resident memory far beyond
592    /// what the output quotas allow. Archives that need more fail with
593    /// `QuotaExceeded { DecoderMemory }`.
594    ///
595    /// - xz: bounds the decoder's dictionary and state; applies to `extract`,
596    ///   `list` and `verify` of `.tar.xz`.
597    /// - zstd: bounds the window to the largest power of two at or below this
598    ///   value, at most 128 MiB (libzstd's own ceiling), so a limit of 3 MiB
599    ///   admits windows up to 2 MiB. It applies to `.tar.zst` and to ZIP
600    ///   entries, which are checked from their frame headers: a ZIP archive
601    ///   with a larger window is refused by `extract`, `list` and `verify`
602    ///   before any entry is listed or extracted. Windows of 1 KiB or less are
603    ///   always admitted, and the decoder's fixed state is not counted.
604    /// - 7z: also admits the 7z decoder window; the lookahead of parallel 7z
605    ///   decoding is budgeted separately by
606    ///   [`parallel_decode`](Self::parallel_decode).
607    ///
608    /// Other codecs are bounded by their format (bzip2 blocks of at most
609    /// 900 KB). Not exposed through the CLI or language bindings.
610    ///
611    /// Default: 256 MiB (268,435,456 bytes)
612    pub max_decoder_memory: NonZeroU64,
613
614    /// Base number of gzip members or bzip2 streams a compressed TAR may hold.
615    ///
616    /// `gzip -dc` and `bzip2 -dc` decode every member, and each costs a decoder
617    /// setup, so a stream of empty members would burn time without producing
618    /// output the size quotas could count. Member `n` may start only while
619    /// `n <= allowance`, where `allowance = compressed_member_allowance +
620    /// decoded_bytes / 16 KiB`; a stream that starts a member beyond that
621    /// fails with `QuotaExceeded { CompressedMembers }`. The output term lets
622    /// writers that flush a member per record (bgzf blocks are at most 64 KiB)
623    /// pass at any output size, provided they average 16 KiB or more per
624    /// member. A gzip or bzip2 stream averaging less than that over large
625    /// outputs must raise this value. Applies to `extract`, `list` and
626    /// `verify` of `.tar.gz` and `.tar.bz2`; xz and zstd are not governed by
627    /// it. Not exposed through the CLI or language bindings.
628    ///
629    /// Default: 10,000 (100,000 for [`SecurityConfig::permissive`])
630    pub compressed_member_allowance: NonZeroU64,
631
632    /// Lookahead memory for decoding independent LZMA2 runs of a 7z block on
633    /// worker threads.
634    ///
635    /// Applies to `extract` and `verify` with integrity checking of 7z
636    /// archives. It is separate from `max_decoder_memory`, which keeps
637    /// bounding the decoder window. See [`ParallelDecode`].
638    ///
639    /// Default: `Bounded` at 128 MiB (1 GiB for [`SecurityConfig::permissive`])
640    pub parallel_decode: ParallelDecode,
641
642    /// How ZIP archives with ambiguous structure are handled.
643    ///
644    /// Default: [`ZipConsistencyPolicy::Enforce`], including for
645    /// [`SecurityConfig::permissive`]. Pre-ZIP64 archives with more than
646    /// 65535 entries (wrapped end-record count) and archives with orphaned
647    /// local headers, or with a central directory signature in a gap before an
648    /// entry (left by in-place updaters), are rejected under `Enforce`.
649    pub zip_consistency: ZipConsistencyPolicy,
650}
651
652impl Default for SecurityConfig {
653    /// Creates a `SecurityConfig` with secure default settings.
654    ///
655    /// Default values:
656    /// - `max_file_size`: 50 MB
657    /// - `max_total_size`: 500 MB
658    /// - `max_compression_ratio`: 100.0
659    /// - `max_file_count`: 10,000
660    /// - `max_path_depth`: 32
661    /// - `allowed`: All features refused (deny-by-default)
662    /// - `preserve_permissions`: false
663    /// - `allowed_extensions`: empty (allow all)
664    /// - `banned_path_components`: `[".git", ".ssh", ".gnupg", ".aws", ".kube",
665    ///   ".docker", ".env"]`
666    /// - `solid_archives`: [`SolidArchives::Refuse`] (solid archives rejected)
667    /// - `max_tar_metadata_bytes`: 4 MiB
668    /// - `max_decoder_memory`: 256 MiB
669    /// - `compressed_member_allowance`: 10,000
670    /// - `parallel_decode`: `Bounded` at 128 MiB
671    /// - `zip_consistency`: `Enforce`
672    fn default() -> Self {
673        Self {
674            max_file_size: Limit::Bounded(non_zero!(50 * 1024 * 1024)), // 50 MB
675            max_total_size: Limit::Bounded(non_zero!(500 * 1024 * 1024)), // 500 MB
676            max_compression_ratio: crate::ratio_limit!(100.0),
677            max_file_count: Limit::Bounded(non_zero!(10_000)),
678            max_path_depth: non_zero!(32),
679            allowed: AllowedFeatures::default(), // All false
680            preserve_permissions: false,
681            allowed_extensions: Vec::new(),
682            banned_path_components: default_banned_path_components(),
683            solid_archives: SolidArchives::Refuse,
684            max_tar_metadata_bytes: non_zero!(4 * 1024 * 1024), // 4 MiB
685            max_decoder_memory: non_zero!(256 * 1024 * 1024),   // 256 MiB
686            compressed_member_allowance: DEFAULT_MEMBER_ALLOWANCE,
687            parallel_decode: ParallelDecode::Bounded(ParallelDecode::DEFAULT_BYTES),
688            zip_consistency: ZipConsistencyPolicy::Enforce,
689        }
690    }
691}
692
693/// Lookahead memory of [`SecurityConfig::permissive`]: 1 GiB.
694const PERMISSIVE_PARALLEL_DECODE: NonZeroU64 = non_zero!(1024 * 1024 * 1024);
695
696impl SecurityConfig {
697    /// Creates a permissive configuration for trusted archives.
698    ///
699    /// This configuration allows symlinks, hardlinks, absolute paths, and
700    /// solid archives. Use only when extracting archives from trusted sources.
701    #[must_use]
702    pub fn permissive() -> Self {
703        Self {
704            allowed: AllowedFeatures {
705                symlinks: Admit::Allow,
706                hardlinks: Admit::Allow,
707                absolute_paths: Admit::Allow,
708                world_writable: Admit::Allow,
709                windows_reserved_names: Admit::Refuse,
710            },
711            preserve_permissions: true,
712            max_compression_ratio: crate::ratio_limit!(1000.0),
713            banned_path_components: Vec::new(),
714            solid_archives: SolidArchives::Allow(SolidLimits::PERMISSIVE),
715            max_tar_metadata_bytes: non_zero!(16 * 1024 * 1024), // 16 MiB for permissive
716            max_decoder_memory: non_zero!(1024 * 1024 * 1024),   // 1 GiB for permissive
717            compressed_member_allowance: non_zero!(100_000),
718            parallel_decode: ParallelDecode::Bounded(PERMISSIVE_PARALLEL_DECODE),
719            ..Self::default()
720        }
721    }
722
723    /// Sets the maximum size for a single extracted file in bytes.
724    ///
725    /// # Examples
726    ///
727    /// ```
728    /// use exarch_core::SecurityConfig;
729    ///
730    /// let config =
731    ///     SecurityConfig::default().with_max_file_size(exarch_core::non_zero!(100 * 1024 * 1024));
732    /// assert!(config.max_file_size.admits(100 * 1024 * 1024));
733    /// ```
734    #[must_use]
735    #[inline]
736    pub fn with_max_file_size(mut self, size: impl Into<Limit<NonZeroU64>>) -> Self {
737        self.max_file_size = size.into();
738        self
739    }
740
741    /// Sets the maximum total size for all extracted files in bytes.
742    ///
743    /// # Examples
744    ///
745    /// ```
746    /// use exarch_core::SecurityConfig;
747    ///
748    /// let config =
749    ///     SecurityConfig::default().with_max_total_size(exarch_core::non_zero!(1024 * 1024 * 1024));
750    /// assert_eq!(config.max_total_size.ceiling(), 1024 * 1024 * 1024);
751    /// ```
752    #[must_use]
753    #[inline]
754    pub fn with_max_total_size(mut self, size: impl Into<Limit<NonZeroU64>>) -> Self {
755        self.max_total_size = size.into();
756        self
757    }
758
759    /// Sets the maximum allowed compression ratio (uncompressed / compressed).
760    ///
761    /// # Examples
762    ///
763    /// ```
764    /// use exarch_core::SecurityConfig;
765    ///
766    /// let config =
767    ///     SecurityConfig::default().with_max_compression_ratio(exarch_core::ratio_limit!(50.0));
768    /// assert_eq!(config.max_compression_ratio.get(), 50.0);
769    /// ```
770    #[must_use]
771    #[inline]
772    pub fn with_max_compression_ratio(mut self, ratio: RatioLimit) -> Self {
773        self.max_compression_ratio = ratio;
774        self
775    }
776
777    /// Sets the maximum number of files that can be extracted.
778    ///
779    /// # Examples
780    ///
781    /// ```
782    /// use exarch_core::SecurityConfig;
783    ///
784    /// let config = SecurityConfig::default().with_max_file_count(exarch_core::non_zero!(500));
785    /// assert_eq!(config.max_file_count.ceiling(), 500);
786    /// ```
787    #[must_use]
788    #[inline]
789    pub fn with_max_file_count(mut self, count: impl Into<Limit<NonZeroUsize>>) -> Self {
790        self.max_file_count = count.into();
791        self
792    }
793
794    /// Sets the maximum path depth allowed.
795    ///
796    /// # Examples
797    ///
798    /// ```
799    /// use exarch_core::SecurityConfig;
800    ///
801    /// let config = SecurityConfig::default().with_max_path_depth(exarch_core::non_zero!(16));
802    /// assert_eq!(config.max_path_depth.get(), 16);
803    /// ```
804    #[must_use]
805    #[inline]
806    pub fn with_max_path_depth(mut self, depth: NonZeroUsize) -> Self {
807        self.max_path_depth = depth;
808        self
809    }
810
811    /// Sets the feature flags controlling allowed archive features.
812    ///
813    /// # Examples
814    ///
815    /// ```
816    /// use exarch_core::SecurityConfig;
817    /// use exarch_core::config::AllowedFeatures;
818    ///
819    /// let features = AllowedFeatures::default();
820    /// let config = SecurityConfig::default().with_allowed(features);
821    /// assert!(!config.allowed.symlinks.is_allowed());
822    /// ```
823    #[must_use]
824    #[inline]
825    pub fn with_allowed(mut self, allowed: AllowedFeatures) -> Self {
826        self.allowed = allowed;
827        self
828    }
829
830    /// Enables or disables symlinks in extracted archives.
831    ///
832    /// # Examples
833    ///
834    /// ```
835    /// use exarch_core::SecurityConfig;
836    ///
837    /// let config = SecurityConfig::default().with_allow_symlinks(true);
838    /// assert!(config.allowed.symlinks.is_allowed());
839    /// ```
840    #[must_use]
841    #[inline]
842    pub fn with_allow_symlinks(mut self, allow: bool) -> Self {
843        self.allowed.symlinks = Admit::from_allowed(allow);
844        self
845    }
846
847    /// Enables or disables hardlinks in extracted archives.
848    ///
849    /// # Examples
850    ///
851    /// ```
852    /// use exarch_core::SecurityConfig;
853    ///
854    /// let config = SecurityConfig::default().with_allow_hardlinks(true);
855    /// assert!(config.allowed.hardlinks.is_allowed());
856    /// ```
857    #[must_use]
858    #[inline]
859    pub fn with_allow_hardlinks(mut self, allow: bool) -> Self {
860        self.allowed.hardlinks = Admit::from_allowed(allow);
861        self
862    }
863
864    /// Enables or disables absolute paths in archive entries.
865    ///
866    /// # Examples
867    ///
868    /// ```
869    /// use exarch_core::SecurityConfig;
870    ///
871    /// let config = SecurityConfig::default().with_allow_absolute_paths(true);
872    /// assert!(config.allowed.absolute_paths.is_allowed());
873    /// ```
874    #[must_use]
875    #[inline]
876    pub fn with_allow_absolute_paths(mut self, allow: bool) -> Self {
877        self.allowed.absolute_paths = Admit::from_allowed(allow);
878        self
879    }
880
881    /// Enables or disables world-writable files.
882    ///
883    /// # Examples
884    ///
885    /// ```
886    /// use exarch_core::SecurityConfig;
887    ///
888    /// let config = SecurityConfig::default().with_allow_world_writable(true);
889    /// assert!(config.allowed.world_writable.is_allowed());
890    /// ```
891    #[must_use]
892    #[inline]
893    pub fn with_allow_world_writable(mut self, allow: bool) -> Self {
894        self.allowed.world_writable = Admit::from_allowed(allow);
895        self
896    }
897
898    /// Enables or disables Windows reserved device names (`CON`, `NUL`,
899    /// `COM1`, ...) as path components. Only consulted on Windows.
900    ///
901    /// # Examples
902    ///
903    /// ```
904    /// use exarch_core::SecurityConfig;
905    ///
906    /// let config = SecurityConfig::default().with_allow_windows_reserved_names(true);
907    /// assert!(config.allowed.windows_reserved_names.is_allowed());
908    /// ```
909    #[must_use]
910    #[inline]
911    pub fn with_allow_windows_reserved_names(mut self, allow: bool) -> Self {
912        self.allowed.windows_reserved_names = Admit::from_allowed(allow);
913        self
914    }
915
916    /// Enables or disables preserving file permissions from the archive.
917    ///
918    /// # Examples
919    ///
920    /// ```
921    /// use exarch_core::SecurityConfig;
922    ///
923    /// let config = SecurityConfig::default().with_preserve_permissions(true);
924    /// assert!(config.preserve_permissions);
925    /// ```
926    #[must_use]
927    #[inline]
928    pub fn with_preserve_permissions(mut self, preserve: bool) -> Self {
929        self.preserve_permissions = preserve;
930        self
931    }
932
933    /// Sets the list of allowed file extensions.
934    ///
935    /// An empty list allows all extensions.
936    ///
937    /// # Examples
938    ///
939    /// ```
940    /// use exarch_core::SecurityConfig;
941    ///
942    /// let config = SecurityConfig::default()
943    ///     .try_add_allowed_extension(".txt")?
944    ///     .try_add_allowed_extension("pdf")?;
945    /// assert!(config.is_extension_allowed(Some("txt")));
946    /// assert!(!config.is_extension_allowed(Some("exe")));
947    /// # Ok::<(), exarch_core::ArchiveError>(())
948    /// ```
949    #[must_use]
950    #[inline]
951    pub fn with_allowed_extensions(mut self, extensions: Vec<Extension>) -> Self {
952        self.allowed_extensions = extensions;
953        self
954    }
955
956    /// Appends one allowed extension, parsed by [`Extension`].
957    ///
958    /// # Errors
959    ///
960    /// Returns [`crate::ArchiveError::InvalidConfiguration`] when `extension`
961    /// is not a usable extension.
962    pub fn try_add_allowed_extension(mut self, extension: &str) -> crate::Result<Self> {
963        self.allowed_extensions
964            .push(Extension::try_from(extension)?);
965        Ok(self)
966    }
967
968    /// Appends one banned path component, parsed by [`PathComponentName`].
969    ///
970    /// # Errors
971    ///
972    /// Returns [`crate::ArchiveError::InvalidConfiguration`] when `component`
973    /// is not a usable path component name.
974    pub fn try_add_banned_path_component(mut self, component: &str) -> crate::Result<Self> {
975        self.banned_path_components
976            .push(PathComponentName::try_from(component)?);
977        Ok(self)
978    }
979
980    /// Sets the list of banned path components.
981    ///
982    /// # Examples
983    ///
984    /// ```
985    /// use exarch_core::SecurityConfig;
986    ///
987    /// let config = SecurityConfig::default()
988    ///     .with_banned_path_components(Vec::new())
989    ///     .try_add_banned_path_component(".git")?;
990    /// assert!(!config.is_path_component_allowed(".git"));
991    /// assert!(config.is_path_component_allowed(".ssh"));
992    /// # Ok::<(), exarch_core::ArchiveError>(())
993    /// ```
994    #[must_use]
995    #[inline]
996    pub fn with_banned_path_components(mut self, components: Vec<PathComponentName>) -> Self {
997        self.banned_path_components = components;
998        self
999    }
1000
1001    /// Sets the solid 7z archive policy together with its limits.
1002    ///
1003    /// # Examples
1004    ///
1005    /// ```
1006    /// use exarch_core::SecurityConfig;
1007    /// use exarch_core::SolidArchives;
1008    /// use exarch_core::SolidLimits;
1009    ///
1010    /// let limits = SolidLimits::DEFAULT.with_max_block_memory(exarch_core::non_zero!(1 << 30));
1011    /// let config = SecurityConfig::default().with_solid_archives(SolidArchives::Allow(limits));
1012    /// assert_eq!(config.solid_archives.limits(), Some(limits));
1013    /// ```
1014    #[must_use]
1015    #[inline]
1016    pub fn with_solid_archives(mut self, solid: SolidArchives) -> Self {
1017        self.solid_archives = solid;
1018        self
1019    }
1020
1021    /// Enables or disables extraction from solid 7z archives.
1022    ///
1023    /// `true` keeps the limits of an already admitted policy and otherwise
1024    /// admits solid archives under [`SolidLimits::DEFAULT`]; a previous
1025    /// [`Refuse`](SolidArchives::Refuse) therefore never carries limits over.
1026    /// `false` refuses solid archives and drops any limits.
1027    ///
1028    /// # Examples
1029    ///
1030    /// ```
1031    /// use exarch_core::SecurityConfig;
1032    ///
1033    /// let config = SecurityConfig::default().with_allow_solid_archives(true);
1034    /// assert!(config.solid_archives.is_allowed());
1035    /// ```
1036    #[must_use]
1037    #[inline]
1038    pub fn with_allow_solid_archives(mut self, allow: bool) -> Self {
1039        self.solid_archives = self.solid_archives.with_allowed(allow);
1040        self
1041    }
1042
1043    /// Sets the limits of an already admitted solid archive policy.
1044    ///
1045    /// # Errors
1046    ///
1047    /// Returns [`crate::ArchiveError::InvalidConfiguration`] naming
1048    /// [`ConfigSetting::MaxSolidBlockMemory`] when solid archives are refused,
1049    /// because the limits would be silently ignored.
1050    ///
1051    /// # Examples
1052    ///
1053    /// ```
1054    /// use exarch_core::SecurityConfig;
1055    /// use exarch_core::SolidLimits;
1056    ///
1057    /// let limits = SolidLimits::DEFAULT.with_max_block_memory(exarch_core::non_zero!(1 << 30));
1058    /// assert!(SecurityConfig::default().with_solid_limits(limits).is_err());
1059    ///
1060    /// let config = SecurityConfig::default()
1061    ///     .with_allow_solid_archives(true)
1062    ///     .with_solid_limits(limits)?;
1063    /// assert_eq!(config.solid_archives.limits(), Some(limits));
1064    /// # Ok::<(), exarch_core::ArchiveError>(())
1065    /// ```
1066    pub fn with_solid_limits(mut self, limits: SolidLimits) -> crate::Result<Self> {
1067        self.solid_archives = self.solid_archives.with_limits(limits)?;
1068        Ok(self)
1069    }
1070
1071    /// Sets the maximum bytes the TAR reader may consume for headers and
1072    /// metadata records (GNU long-name/long-link, PAX extended headers, GNU
1073    /// sparse extension blocks) in the gap between two consecutive entries.
1074    ///
1075    /// # Examples
1076    ///
1077    /// ```
1078    /// use exarch_core::SecurityConfig;
1079    ///
1080    /// let config =
1081    ///     SecurityConfig::default().with_max_tar_metadata_bytes(exarch_core::non_zero!(64 * 1024));
1082    /// assert_eq!(config.max_tar_metadata_bytes.get(), 64 * 1024);
1083    /// ```
1084    #[must_use]
1085    #[inline]
1086    pub fn with_max_tar_metadata_bytes(mut self, size: NonZeroU64) -> Self {
1087        self.max_tar_metadata_bytes = size;
1088        self
1089    }
1090
1091    /// Sets the maximum memory a decoder may use, in bytes: the xz
1092    /// dictionary, and the zstd window as the largest power of two within it.
1093    ///
1094    /// # Examples
1095    ///
1096    /// ```
1097    /// use exarch_core::SecurityConfig;
1098    ///
1099    /// let config =
1100    ///     SecurityConfig::default().with_max_decoder_memory(exarch_core::non_zero!(64 * 1024 * 1024));
1101    /// assert_eq!(config.max_decoder_memory.get(), 64 * 1024 * 1024);
1102    /// ```
1103    #[must_use]
1104    #[inline]
1105    pub fn with_max_decoder_memory(mut self, size: NonZeroU64) -> Self {
1106        self.max_decoder_memory = size;
1107        self
1108    }
1109
1110    /// Sets the base number of gzip members or bzip2 streams a compressed TAR
1111    /// may hold, before the allowance of one more per 16 KiB of output.
1112    ///
1113    /// See [`compressed_member_allowance`](SecurityConfig::compressed_member_allowance).
1114    ///
1115    /// # Examples
1116    ///
1117    /// ```
1118    /// use exarch_core::SecurityConfig;
1119    ///
1120    /// use std::num::NonZeroU64;
1121    ///
1122    /// let base = NonZeroU64::new(50_000).unwrap();
1123    /// let config = SecurityConfig::default().with_compressed_member_allowance(base);
1124    /// assert_eq!(config.compressed_member_allowance, base);
1125    /// ```
1126    #[must_use]
1127    #[inline]
1128    pub fn with_compressed_member_allowance(mut self, base: NonZeroU64) -> Self {
1129        self.compressed_member_allowance = base;
1130        self
1131    }
1132
1133    /// Sets the lookahead memory for parallel 7z LZMA2 decoding.
1134    ///
1135    /// # Examples
1136    ///
1137    /// ```
1138    /// use exarch_core::ParallelDecode;
1139    /// use exarch_core::SecurityConfig;
1140    ///
1141    /// let config = SecurityConfig::default().with_parallel_decode(ParallelDecode::Sequential);
1142    /// assert_eq!(config.parallel_decode, ParallelDecode::Sequential);
1143    /// ```
1144    #[must_use]
1145    #[inline]
1146    pub fn with_parallel_decode(mut self, mode: ParallelDecode) -> Self {
1147        self.parallel_decode = mode;
1148        self
1149    }
1150
1151    /// Sets how ZIP archives with ambiguous structure are handled.
1152    ///
1153    /// # Examples
1154    ///
1155    /// ```
1156    /// use exarch_core::SecurityConfig;
1157    /// use exarch_core::ZipConsistencyPolicy;
1158    ///
1159    /// let config = SecurityConfig::default().with_zip_consistency(ZipConsistencyPolicy::Ignore);
1160    /// assert_eq!(config.zip_consistency, ZipConsistencyPolicy::Ignore);
1161    /// ```
1162    #[must_use]
1163    #[inline]
1164    pub fn with_zip_consistency(mut self, policy: ZipConsistencyPolicy) -> Self {
1165        self.zip_consistency = policy;
1166        self
1167    }
1168}
1169
1170/// Read-only queries.
1171impl SecurityConfig {
1172    /// Validates whether a path component is allowed.
1173    ///
1174    /// Comparison is case-insensitive to prevent bypass on case-insensitive
1175    /// filesystems (Windows, macOS default).
1176    #[must_use]
1177    pub fn is_path_component_allowed(&self, component: &str) -> bool {
1178        !self
1179            .banned_path_components
1180            .iter()
1181            .any(|banned| banned.matches(component))
1182    }
1183
1184    /// Returns `true` if a file with the given optional extension may be
1185    /// extracted.
1186    ///
1187    /// When `allowed_extensions` is empty, all files are permitted. When it is
1188    /// non-empty, only listed extensions are permitted (ignoring ASCII case),
1189    /// and `extension` being `None` (the file has no extension) is not
1190    /// allowed.
1191    ///
1192    /// # Examples
1193    ///
1194    /// ```
1195    /// use exarch_core::SecurityConfig;
1196    ///
1197    /// let config = SecurityConfig::default().try_add_allowed_extension("txt")?;
1198    ///
1199    /// assert!(config.is_extension_allowed(Some("txt")));
1200    /// assert!(!config.is_extension_allowed(Some("exe")));
1201    /// // Files without an extension are blocked when the allowlist is non-empty.
1202    /// assert!(!config.is_extension_allowed(None));
1203    ///
1204    /// // Empty allowlist permits everything, including extension-less files.
1205    /// let permissive = SecurityConfig::default();
1206    /// assert!(permissive.is_extension_allowed(None));
1207    /// # Ok::<(), exarch_core::ArchiveError>(())
1208    /// ```
1209    #[must_use]
1210    pub fn is_extension_allowed(&self, extension: Option<&str>) -> bool {
1211        self.allowed_extensions.is_empty()
1212            || extension.is_some_and(|ext| self.allowed_extensions.iter().any(|a| a.matches(ext)))
1213    }
1214
1215    /// The config of a list pass that precedes extraction: the same quota,
1216    /// path, allowlist and decoder limits, with the flags that only matter once
1217    /// bytes are written reset to their deny-by-default values.
1218    pub(crate) fn for_listing(&self) -> Self {
1219        let mut listing = self.clone();
1220        listing.allowed.symlinks = Admit::Refuse;
1221        listing.allowed.hardlinks = Admit::Refuse;
1222        listing.allowed.world_writable = Admit::Refuse;
1223        listing.preserve_permissions = false;
1224        listing
1225    }
1226}
1227
1228/// Options controlling extraction behavior (non-security).
1229///
1230/// Separate from `SecurityConfig` to keep security settings focused.
1231/// These options control operational behavior like atomicity.
1232#[derive(Debug, Clone)]
1233#[non_exhaustive]
1234pub struct ExtractionOptions {
1235    /// Extract atomically: use a temp dir in the same parent as the output
1236    /// directory, rename on success, and delete on failure.
1237    ///
1238    /// When enabled, extraction is all-or-nothing: if extraction fails,
1239    /// the output directory will not be created. This prevents partial
1240    /// extraction artifacts from remaining on disk.
1241    ///
1242    /// Note: cleanup is best-effort if the process is terminated via SIGKILL.
1243    pub atomic: bool,
1244
1245    /// Skip duplicate entries silently instead of aborting.
1246    ///
1247    /// When `true` (default), if an archive contains two entries with the same
1248    /// destination path, the second entry is skipped and a warning is recorded
1249    /// in `ExtractionReport`. When `false`, duplicate entries cause an error.
1250    pub skip_duplicates: bool,
1251
1252    /// Where a ZIP extraction keeps the output its structural check already
1253    /// decoded, so deflate entries are decoded once instead of twice.
1254    ///
1255    /// Defaults to [`DecodeReuse::Memory`] with [`ReuseLimit::DEFAULT`]. Only
1256    /// extractions that write into a directory use it; see [`DecodeReuse`].
1257    pub decode_reuse: DecodeReuse,
1258}
1259
1260impl Default for ExtractionOptions {
1261    fn default() -> Self {
1262        Self {
1263            atomic: false,
1264            skip_duplicates: true,
1265            decode_reuse: DecodeReuse::default(),
1266        }
1267    }
1268}
1269
1270impl ExtractionOptions {
1271    /// Enables or disables atomic extraction.
1272    ///
1273    /// When enabled, extraction is all-or-nothing: the output directory is not
1274    /// created if extraction fails.
1275    ///
1276    /// # Examples
1277    ///
1278    /// ```
1279    /// use exarch_core::ExtractionOptions;
1280    ///
1281    /// let opts = ExtractionOptions::default().with_atomic(true);
1282    /// assert!(opts.atomic);
1283    /// ```
1284    #[must_use]
1285    #[inline]
1286    pub fn with_atomic(mut self, atomic: bool) -> Self {
1287        self.atomic = atomic;
1288        self
1289    }
1290
1291    /// Enables or disables skipping duplicate entries silently.
1292    ///
1293    /// # Examples
1294    ///
1295    /// ```
1296    /// use exarch_core::ExtractionOptions;
1297    ///
1298    /// let opts = ExtractionOptions::default().with_skip_duplicates(false);
1299    /// assert!(!opts.skip_duplicates);
1300    /// ```
1301    #[must_use]
1302    #[inline]
1303    pub fn with_skip_duplicates(mut self, skip: bool) -> Self {
1304        self.skip_duplicates = skip;
1305        self
1306    }
1307
1308    /// Chooses where ZIP extraction keeps the census output for reuse.
1309    ///
1310    /// # Examples
1311    ///
1312    /// ```
1313    /// use exarch_core::DecodeReuse;
1314    /// use exarch_core::ExtractionOptions;
1315    ///
1316    /// let opts = ExtractionOptions::default().with_decode_reuse(DecodeReuse::Off);
1317    /// assert_eq!(opts.decode_reuse, DecodeReuse::Off);
1318    /// ```
1319    #[must_use]
1320    #[inline]
1321    pub const fn with_decode_reuse(mut self, reuse: DecodeReuse) -> Self {
1322        self.decode_reuse = reuse;
1323        self
1324    }
1325}
1326
1327/// The most decoded bytes a ZIP extraction keeps for reuse.
1328///
1329/// The structural check of a ZIP archive decodes deflate entries to find where
1330/// their streams end, and extraction would decode them again. With a
1331/// [`DecodeReuse`] mode other than `Off`, the check keeps what it decoded, up
1332/// to this limit, and extraction writes the kept bytes instead.
1333///
1334/// # Examples
1335///
1336/// ```
1337/// use std::num::NonZeroU64;
1338///
1339/// use exarch_core::ReuseLimit;
1340///
1341/// let limit = ReuseLimit::new(NonZeroU64::MIN);
1342/// assert_eq!(limit.get(), 1);
1343/// assert_eq!(
1344///     ReuseLimit::new(NonZeroU64::MAX).get(),
1345///     ReuseLimit::MAX.get()
1346/// );
1347/// ```
1348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1349pub struct ReuseLimit(NonZeroU64);
1350
1351impl ReuseLimit {
1352    /// 32 MiB: covers a typical source archive and stays below the
1353    /// per-extraction decoder ceilings.
1354    pub const DEFAULT: Self = Self(non_zero!(32 * 1024 * 1024));
1355    /// 256 MiB, the most the structural check decodes in its first pass.
1356    pub const MAX: Self = Self(non_zero!(256 * 1024 * 1024));
1357    pub(crate) const MAX_BYTES: u64 = Self::MAX.0.get();
1358
1359    /// A limit of `bytes`, clamped to [`ReuseLimit::MAX`].
1360    #[must_use]
1361    pub const fn new(bytes: NonZeroU64) -> Self {
1362        if bytes.get() > Self::MAX_BYTES {
1363            Self::MAX
1364        } else {
1365            Self(bytes)
1366        }
1367    }
1368
1369    /// The limit in bytes.
1370    #[must_use]
1371    pub const fn get(self) -> u64 {
1372        self.0.get()
1373    }
1374}
1375
1376/// Where a ZIP extraction keeps decoded output between the structural check and
1377/// the write, so a deflate entry is decoded once.
1378///
1379/// The check that refuses entry data past a stream end decodes each deflate
1380/// entry, and extraction decodes it again. A kept entry is checked against its
1381/// CRC-32 again when it is read back, so a damaged store is refused like a
1382/// damaged archive, and an entry that was not kept is decoded from the archive
1383/// as before.
1384///
1385/// The bytes kept never exceed the smallest of the mode's [`ReuseLimit`], the
1386/// config's `max_decoder_memory` and its `max_total_size`, and an entry that
1387/// `max_file_size` or `max_compression_ratio` would refuse is not kept, so a
1388/// memory-capped container can lower `max_decoder_memory` to bound the cost.
1389///
1390/// Reuse applies to extractions that write into a directory
1391/// ([`extract_archive`](crate::extract_archive) and
1392/// [`ListedArchive::extract`](crate::ListedArchive::extract)). Sink and
1393/// callback extraction keeps output only when
1394/// [`SinkOptions::decode_reuse`](crate::SinkOptions::decode_reuse) opts in, and
1395/// defaults to `Off`; listing and verification never keep output. Bzip2 and
1396/// zstd entries are always decoded twice.
1397///
1398/// An entry above the mode's [`ReuseLimit`] is decoded twice whatever the mode
1399/// is: the default [`ReuseLimit::DEFAULT`] of 32 MiB leaves a larger member
1400/// decoded twice under [`extract_archive`](crate::extract_archive). With
1401/// `TempFile` the plaintext of the kept entries sits in the temporary
1402/// directory until the extraction ends, and the limit bounds only the store,
1403/// not the memory the entry being written uses on top of it.
1404///
1405/// # Examples
1406///
1407/// ```
1408/// use exarch_core::DecodeReuse;
1409/// use exarch_core::ReuseLimit;
1410///
1411/// assert_eq!(
1412///     DecodeReuse::default(),
1413///     DecodeReuse::Memory(ReuseLimit::DEFAULT)
1414/// );
1415/// ```
1416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1417#[non_exhaustive]
1418pub enum DecodeReuse {
1419    /// Keep nothing; every entry is decoded twice.
1420    Off,
1421    /// Keep decoded entries in memory, up to the limit.
1422    ///
1423    /// Works on every target and writes nothing outside the destination.
1424    Memory(ReuseLimit),
1425    /// Keep decoded entries in an unnamed temporary file, up to the limit.
1426    ///
1427    /// The file lives in the platform's temporary directory and holds the
1428    /// plaintext of the archive until the extraction ends. When no temporary
1429    /// file can be created, or on WASI, nothing is kept.
1430    ///
1431    /// On Linux and Android a file that lands on a tmpfs or ramfs is detected
1432    /// and charged like [`Memory`](Self::Memory): its length counts against
1433    /// the shared decoder-memory budget, and when an extraction into a sink
1434    /// needs room the latest kept entries are cut off the end of the file and
1435    /// decoded again. The bytes of entries already extracted are not released
1436    /// until the extraction ends, so a RAM-backed spool is charged
1437    /// conservatively: evicting an entry below the one currently being read
1438    /// frees nothing, because the file is never cut lower than that entry's
1439    /// end. The Linux detection is compiled and exercised only by CI; it has
1440    /// not been run on a Linux host. On every other target the file is assumed
1441    /// to be on disk, so a temporary directory that is a RAM disk (FreeBSD
1442    /// tmpfs, a macOS RAM disk) holds the spool in memory outside the budget.
1443    ///
1444    /// Writing the spool and reading it back is paid in kernel time on every
1445    /// byte kept. Measured (2026-11, macOS, release CLI, a shared host at a
1446    /// load average of 5 to 12, deflate ZIPs of 10 MiB members at a
1447    /// compression ratio of about 2.2): 1.15x the wall time of the build
1448    /// before decode reuse for an archive of 100 MiB decoded (a 47 MB ZIP)
1449    /// and 1.18x for 300 MiB decoded (a 140 MB ZIP). Most of the excess is
1450    /// system time; user time rose by about 0.05 s of the 0.13 s excess on the
1451    /// larger archive. [`Memory`](Self::Memory) measures 1.07x on the 100 MiB
1452    /// one. Writing the decoder's 256 KiB chunks to the file without the
1453    /// 64 KiB buffer measured no faster, and a memory-mapped spool is ruled
1454    /// out by the crate's `unsafe` ban, so this is the floor of the design.
1455    /// Linux (ext4, tmpfs) is not measured.
1456    ///
1457    /// The archive's own listing pass for TAR, which also spools to a
1458    /// temporary file, is not charged to this budget.
1459    TempFile(ReuseLimit),
1460}
1461
1462closed_enum! {
1463    /// The mode of a [`DecodeReuse`] without its limit, as the front ends spell
1464    /// it.
1465    ///
1466    /// # Examples
1467    ///
1468    /// ```
1469    /// use exarch_core::DecodeReuse;
1470    /// use exarch_core::DecodeReuseKind;
1471    ///
1472    /// assert_eq!(DecodeReuse::Off.kind(), DecodeReuseKind::Off);
1473    /// assert_eq!(DecodeReuseKind::TempFile.as_str(), "temp_file");
1474    /// ```
1475    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1476    pub enum DecodeReuseKind {
1477        /// [`DecodeReuse::Off`].
1478        Off => "off",
1479        /// [`DecodeReuse::Memory`].
1480        Memory => "memory",
1481        /// [`DecodeReuse::TempFile`].
1482        TempFile => "temp_file",
1483    }
1484}
1485
1486impl DecodeReuse {
1487    /// The mode without its limit.
1488    #[must_use]
1489    pub const fn kind(self) -> DecodeReuseKind {
1490        match self {
1491            Self::Off => DecodeReuseKind::Off,
1492            Self::Memory(_) => DecodeReuseKind::Memory,
1493            Self::TempFile(_) => DecodeReuseKind::TempFile,
1494        }
1495    }
1496}
1497
1498impl Default for DecodeReuse {
1499    fn default() -> Self {
1500        Self::Memory(ReuseLimit::DEFAULT)
1501    }
1502}
1503
1504/// Upper bound on the bytes `verify` decodes to check payload integrity.
1505///
1506/// The budget bounds the work done **beyond what listing already does**: ZIP
1507/// entries and 7z blocks are charged their declared uncompressed size before
1508/// they are decoded. TAR entry content is never charged because listing
1509/// decodes it anyway, and neither is the compressed TAR tail after the end
1510/// marker: that read is bounded by `max_tar_metadata_bytes` (at least 1 MiB)
1511/// instead. The default is a fixed 500 MiB, equal to the default
1512/// `max_total_size`; it does not follow a raised `max_total_size`.
1513///
1514/// # Examples
1515///
1516/// ```
1517/// use exarch_core::DecompressionBudget;
1518///
1519/// assert!(DecompressionBudget::try_from_bytes(0).is_err());
1520/// let budget = DecompressionBudget::try_from_bytes(1024)?;
1521/// assert_eq!(budget.get(), 1024);
1522/// assert_eq!(DecompressionBudget::default(), DecompressionBudget::DEFAULT);
1523/// # Ok::<(), exarch_core::ArchiveError>(())
1524/// ```
1525#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1526pub struct DecompressionBudget(std::num::NonZeroU64);
1527
1528impl DecompressionBudget {
1529    /// The default budget: 500 MiB.
1530    pub const DEFAULT: Self = Self(non_zero!(500 * 1024 * 1024));
1531
1532    /// Creates a budget from a non-zero byte count.
1533    #[must_use]
1534    pub const fn new(bytes: std::num::NonZeroU64) -> Self {
1535        Self(bytes)
1536    }
1537
1538    /// Creates a budget from a byte count.
1539    ///
1540    /// # Errors
1541    ///
1542    /// Returns [`ArchiveError::InvalidConfiguration`](crate::ArchiveError) when
1543    /// `bytes` is zero.
1544    pub fn try_from_bytes(bytes: u64) -> crate::Result<Self> {
1545        non_zero_u64(ConfigSetting::DecompressionBudget, bytes).map(Self)
1546    }
1547
1548    /// Returns the budget in bytes.
1549    #[must_use]
1550    pub const fn get(self) -> u64 {
1551        self.0.get()
1552    }
1553}
1554
1555impl Default for DecompressionBudget {
1556    fn default() -> Self {
1557        Self::DEFAULT
1558    }
1559}
1560
1561/// Whether `verify` checks payload integrity.
1562///
1563/// A budget without the check is unrepresentable: the budget lives inside the
1564/// [`DecodeToEof`](Self::DecodeToEof) variant.
1565#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1566#[non_exhaustive]
1567pub enum IntegrityCheck {
1568    /// Metadata-only verification (the default).
1569    #[default]
1570    Skip,
1571
1572    /// Decode payload to the decoder's EOF so checksums and codec framing are
1573    /// verified, spending at most the given budget on extra decoding.
1574    DecodeToEof(DecompressionBudget),
1575}
1576
1577impl IntegrityCheck {
1578    /// The decompression budget of the check, or `None` for
1579    /// [`Skip`](Self::Skip).
1580    ///
1581    /// The one exhaustive match over the variants, so a new check mode fails to
1582    /// compile here instead of reading as "enabled, no budget" in a front end.
1583    ///
1584    /// # Examples
1585    ///
1586    /// ```
1587    /// use exarch_core::DecompressionBudget;
1588    /// use exarch_core::IntegrityCheck;
1589    ///
1590    /// assert_eq!(IntegrityCheck::Skip.budget(), None);
1591    /// let check = IntegrityCheck::DecodeToEof(DecompressionBudget::DEFAULT);
1592    /// assert_eq!(check.budget(), Some(DecompressionBudget::DEFAULT));
1593    /// ```
1594    #[must_use]
1595    pub const fn budget(self) -> Option<DecompressionBudget> {
1596        match self {
1597            Self::Skip => None,
1598            Self::DecodeToEof(budget) => Some(budget),
1599        }
1600    }
1601}
1602
1603/// Options controlling `verify` behavior.
1604///
1605/// # Examples
1606///
1607/// ```
1608/// use exarch_core::DecompressionBudget;
1609/// use exarch_core::IntegrityCheck;
1610/// use exarch_core::VerificationOptions;
1611///
1612/// let options = VerificationOptions::default();
1613/// assert_eq!(options.integrity, IntegrityCheck::Skip);
1614///
1615/// let options = options.with_integrity(IntegrityCheck::DecodeToEof(DecompressionBudget::DEFAULT));
1616/// assert_ne!(options.integrity, IntegrityCheck::Skip);
1617/// ```
1618#[derive(Debug, Clone, Copy, Default)]
1619#[non_exhaustive]
1620pub struct VerificationOptions {
1621    /// Payload integrity check mode.
1622    pub integrity: IntegrityCheck,
1623}
1624
1625impl VerificationOptions {
1626    /// Sets the payload integrity check mode.
1627    #[must_use]
1628    pub fn with_integrity(mut self, integrity: IntegrityCheck) -> Self {
1629        self.integrity = integrity;
1630        self
1631    }
1632}
1633
1634/// Whether listing reads the symlink targets a format keeps in compressed
1635/// entry data.
1636///
1637/// 7z keeps link targets in compressed entry data, so reading them decodes
1638/// part of the archive, which in a solid block can be most of it. Listing
1639/// therefore skips them by default. Other formats always report their targets:
1640/// TAR keeps them in headers, and ZIP reads them from a small local entry. This
1641/// is a Rust API option only; the Python and Node `list_archive` skip 7z
1642/// targets.
1643///
1644/// # Examples
1645///
1646/// ```
1647/// use exarch_core::StoredTargets;
1648///
1649/// assert_eq!(StoredTargets::default(), StoredTargets::Skip);
1650/// ```
1651#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1652#[non_exhaustive]
1653pub enum StoredTargets {
1654    /// Leave 7z link targets unread, so listing decodes no entry data (the
1655    /// default).
1656    #[default]
1657    Skip,
1658
1659    /// Read the targets, decoding the blocks that hold them.
1660    Read,
1661}
1662
1663/// Options controlling `list` behavior.
1664///
1665/// # Examples
1666///
1667/// ```
1668/// use exarch_core::ListOptions;
1669/// use exarch_core::StoredTargets;
1670///
1671/// let options = ListOptions::default();
1672/// assert_eq!(options.stored_targets, StoredTargets::Skip);
1673///
1674/// let options = options.with_stored_targets(StoredTargets::Read);
1675/// assert_eq!(options.stored_targets, StoredTargets::Read);
1676/// ```
1677#[derive(Debug, Clone, Copy, Default)]
1678#[non_exhaustive]
1679pub struct ListOptions {
1680    /// Whether to read the link targets a format keeps in entry data.
1681    pub stored_targets: StoredTargets,
1682}
1683
1684impl ListOptions {
1685    /// Sets whether link targets kept in entry data are read.
1686    #[must_use]
1687    pub fn with_stored_targets(mut self, stored_targets: StoredTargets) -> Self {
1688        self.stored_targets = stored_targets;
1689        self
1690    }
1691}
1692
1693#[cfg(test)]
1694#[allow(
1695    clippy::unwrap_used,
1696    clippy::expect_used,
1697    clippy::field_reassign_with_default
1698)]
1699mod tests {
1700    use std::assert_matches;
1701
1702    use super::*;
1703
1704    #[test]
1705    fn test_default_config() {
1706        let config = SecurityConfig::default();
1707        assert!(!config.allowed.symlinks.is_allowed());
1708        assert!(!config.allowed.hardlinks.is_allowed());
1709        assert!(!config.allowed.absolute_paths.is_allowed());
1710        assert_eq!(config.max_file_size.ceiling(), 50 * 1024 * 1024);
1711    }
1712
1713    #[test]
1714    fn test_permissive_config() {
1715        let config = SecurityConfig::permissive();
1716        assert!(config.allowed.symlinks.is_allowed());
1717        assert!(config.allowed.hardlinks.is_allowed());
1718        assert!(config.allowed.absolute_paths.is_allowed());
1719    }
1720
1721    #[test]
1722    fn test_extension_allowed_empty_list() {
1723        let config = SecurityConfig::default();
1724        assert!(config.is_extension_allowed(Some("txt")));
1725        assert!(config.is_extension_allowed(Some("pdf")));
1726    }
1727
1728    #[test]
1729    fn test_extension_allowed_with_list() {
1730        let mut config = SecurityConfig::default();
1731        config.allowed_extensions = vec![
1732            Extension::try_from("txt").unwrap(),
1733            Extension::try_from("pdf").unwrap(),
1734        ];
1735        assert!(config.is_extension_allowed(Some("txt")));
1736        assert!(config.is_extension_allowed(Some("TXT")));
1737        assert!(!config.is_extension_allowed(Some("exe")));
1738    }
1739
1740    #[test]
1741    fn test_path_component_allowed() {
1742        let config = SecurityConfig::default();
1743        assert!(config.is_path_component_allowed("src"));
1744        assert!(!config.is_path_component_allowed(".git"));
1745        assert!(!config.is_path_component_allowed(".ssh"));
1746
1747        // Case-insensitive matching prevents bypass
1748        assert!(!config.is_path_component_allowed(".Git"));
1749        assert!(!config.is_path_component_allowed(".GIT"));
1750        assert!(!config.is_path_component_allowed(".SSH"));
1751        assert!(!config.is_path_component_allowed(".Gnupg"));
1752    }
1753
1754    // M-TEST-3: Config field validation
1755    #[test]
1756    fn test_config_default_security_flags() {
1757        let config = SecurityConfig::default();
1758
1759        // All security-sensitive flags should be false by default
1760        // (deny-by-default)
1761        assert!(
1762            !config.allowed.symlinks.is_allowed(),
1763            "symlinks should be denied by default"
1764        );
1765        assert!(
1766            !config.allowed.hardlinks.is_allowed(),
1767            "hardlinks should be denied by default"
1768        );
1769        assert!(
1770            !config.allowed.absolute_paths.is_allowed(),
1771            "absolute paths should be denied by default"
1772        );
1773        assert!(
1774            !config.preserve_permissions,
1775            "permissions should not be preserved by default"
1776        );
1777        assert!(
1778            !config.allowed.world_writable.is_allowed(),
1779            "world-writable should be denied by default"
1780        );
1781    }
1782
1783    #[test]
1784    fn test_config_permissive_security_flags() {
1785        let config = SecurityConfig::permissive();
1786
1787        // Permissive config should allow all features
1788        assert!(
1789            config.allowed.symlinks.is_allowed(),
1790            "permissive allows symlinks"
1791        );
1792        assert!(
1793            config.allowed.hardlinks.is_allowed(),
1794            "permissive allows hardlinks"
1795        );
1796        assert!(
1797            config.allowed.absolute_paths.is_allowed(),
1798            "permissive allows absolute paths"
1799        );
1800        assert!(
1801            config.preserve_permissions,
1802            "permissive preserves permissions"
1803        );
1804        assert!(
1805            config.allowed.world_writable.is_allowed(),
1806            "permissive allows world-writable"
1807        );
1808    }
1809
1810    #[test]
1811    fn test_config_quota_limits() {
1812        let config = SecurityConfig::default();
1813
1814        // Verify default quota values are sensible
1815        assert_eq!(
1816            config.max_file_size.ceiling(),
1817            50 * 1024 * 1024,
1818            "50 MB file limit"
1819        );
1820        assert_eq!(
1821            config.max_total_size.ceiling(),
1822            500 * 1024 * 1024,
1823            "500 MB total limit"
1824        );
1825        assert_eq!(
1826            config.max_file_count.ceiling(),
1827            10_000,
1828            "10k file count limit"
1829        );
1830        assert_eq!(config.max_path_depth.get(), 32, "32 level depth limit");
1831        #[allow(clippy::float_cmp)]
1832        {
1833            assert_eq!(
1834                config.max_compression_ratio.get(),
1835                100.0,
1836                "100x compression ratio limit"
1837            );
1838        }
1839    }
1840
1841    #[test]
1842    fn test_config_banned_components_not_empty() {
1843        let config = SecurityConfig::default();
1844
1845        // Default should ban common sensitive directories
1846        assert!(
1847            !config.banned_path_components.is_empty(),
1848            "should have banned components by default"
1849        );
1850        assert!(
1851            config
1852                .banned_path_components
1853                .contains(&PathComponentName::try_from(".git").unwrap()),
1854            "should ban .git"
1855        );
1856        assert!(
1857            config
1858                .banned_path_components
1859                .contains(&PathComponentName::try_from(".ssh").unwrap()),
1860            "should ban .ssh"
1861        );
1862    }
1863
1864    #[test]
1865    fn test_config_solid_archives_default() {
1866        let config = SecurityConfig::default();
1867
1868        // Solid archives should be denied by default (security)
1869        assert_eq!(
1870            config.solid_archives,
1871            SolidArchives::Refuse,
1872            "solid archives should be denied by default"
1873        );
1874        assert_eq!(
1875            SolidLimits::DEFAULT.max_block_memory.get(),
1876            512 * 1024 * 1024,
1877            "max solid block memory should be 512 MB"
1878        );
1879    }
1880
1881    #[test]
1882    fn test_config_permissive_solid_archives() {
1883        let config = SecurityConfig::permissive();
1884
1885        // Permissive config should allow solid archives
1886        assert_eq!(
1887            config.solid_archives,
1888            SolidArchives::Allow(SolidLimits::PERMISSIVE),
1889            "permissive config should allow solid archives"
1890        );
1891        assert_eq!(
1892            SolidLimits::PERMISSIVE.max_block_memory.get(),
1893            1024 * 1024 * 1024,
1894            "permissive should have 1 GB solid block limit"
1895        );
1896    }
1897
1898    #[test]
1899    fn test_config_tar_metadata_bytes_default() {
1900        let config = SecurityConfig::default();
1901        assert_eq!(
1902            config.max_tar_metadata_bytes.get(),
1903            4 * 1024 * 1024,
1904            "max TAR metadata bytes should be 4 MiB by default"
1905        );
1906    }
1907
1908    #[test]
1909    fn test_config_permissive_tar_metadata_bytes() {
1910        let config = SecurityConfig::permissive();
1911        assert_eq!(
1912            config.max_tar_metadata_bytes.get(),
1913            16 * 1024 * 1024,
1914            "permissive should have 16 MiB TAR metadata budget"
1915        );
1916    }
1917
1918    #[test]
1919    fn test_with_max_tar_metadata_bytes_builder() {
1920        let config = SecurityConfig::default().with_max_tar_metadata_bytes(crate::non_zero!(2048));
1921        assert_eq!(config.max_tar_metadata_bytes.get(), 2048);
1922    }
1923
1924    #[test]
1925    fn test_solid_compression_ratio_defaults() {
1926        assert_eq!(SolidLimits::DEFAULT.max_ratio.get(), 1000.0);
1927        assert_eq!(SolidLimits::PERMISSIVE.max_ratio.get(), 10_000.0);
1928    }
1929
1930    #[test]
1931    fn allowing_solid_archives_keeps_admitted_limits_and_resets_a_refusal() {
1932        let custom = SolidLimits::DEFAULT.with_max_block_memory(crate::non_zero!(4096));
1933        let kept = SecurityConfig::default()
1934            .with_solid_archives(SolidArchives::Allow(custom))
1935            .with_allow_solid_archives(true);
1936        assert_eq!(kept.solid_archives, SolidArchives::Allow(custom));
1937
1938        let reset = SecurityConfig::default().with_allow_solid_archives(true);
1939        assert_eq!(
1940            reset.solid_archives,
1941            SolidArchives::Allow(SolidLimits::DEFAULT)
1942        );
1943
1944        let refused = SecurityConfig::default()
1945            .with_solid_archives(SolidArchives::Allow(custom))
1946            .with_allow_solid_archives(false);
1947        assert_eq!(refused.solid_archives, SolidArchives::Refuse);
1948    }
1949
1950    #[test]
1951    fn solid_limits_cannot_be_set_while_solid_archives_are_refused() {
1952        let err = SecurityConfig::default()
1953            .with_solid_limits(SolidLimits::DEFAULT)
1954            .unwrap_err();
1955        assert_matches!(
1956            err,
1957            crate::ArchiveError::InvalidConfiguration {
1958                setting: ConfigSetting::MaxSolidBlockMemory,
1959                problem: ConfigProblem::NotSupported,
1960            }
1961        );
1962        let custom = SolidLimits::DEFAULT.with_max_block_memory(crate::non_zero!(4096));
1963        let config = SecurityConfig::default()
1964            .with_allow_solid_archives(true)
1965            .with_solid_limits(custom)
1966            .unwrap();
1967        assert_eq!(config.solid_archives.limits(), Some(custom));
1968    }
1969
1970    #[test]
1971    fn every_integrity_check_has_a_budget_rule() {
1972        for check in [
1973            IntegrityCheck::Skip,
1974            IntegrityCheck::DecodeToEof(DecompressionBudget::DEFAULT),
1975        ] {
1976            let expected = match check {
1977                IntegrityCheck::Skip => None,
1978                IntegrityCheck::DecodeToEof(budget) => Some(budget),
1979            };
1980            assert_eq!(check.budget(), expected);
1981        }
1982    }
1983
1984    #[test]
1985    fn admit_converts_to_and_from_a_bool() {
1986        assert_eq!(Admit::from_allowed(true), Admit::Allow);
1987        assert_eq!(Admit::from_allowed(false), Admit::Refuse);
1988        assert!(Admit::Allow.is_allowed());
1989        assert!(!Admit::Refuse.is_allowed());
1990        assert_eq!(Admit::default(), Admit::Refuse);
1991    }
1992
1993    #[test]
1994    fn for_listing_resets_write_time_flags_only() {
1995        let listing = SecurityConfig::permissive().for_listing();
1996        assert_eq!(listing.allowed.symlinks, Admit::Refuse);
1997        assert_eq!(listing.allowed.hardlinks, Admit::Refuse);
1998        assert_eq!(listing.allowed.world_writable, Admit::Refuse);
1999        assert!(!listing.preserve_permissions);
2000        assert_eq!(listing.allowed.absolute_paths, Admit::Allow);
2001        assert_eq!(
2002            listing.solid_archives,
2003            SecurityConfig::permissive().solid_archives
2004        );
2005        assert_eq!(
2006            listing.max_decoder_memory,
2007            SecurityConfig::permissive().max_decoder_memory
2008        );
2009    }
2010
2011    #[test]
2012    fn test_compressed_member_allowance_defaults() {
2013        assert_eq!(
2014            SecurityConfig::default().compressed_member_allowance.get(),
2015            10_000
2016        );
2017        assert_eq!(
2018            SecurityConfig::permissive()
2019                .compressed_member_allowance
2020                .get(),
2021            100_000
2022        );
2023    }
2024
2025    #[test]
2026    fn test_parallel_decode_defaults() {
2027        let bytes = |config: SecurityConfig| match config.parallel_decode {
2028            ParallelDecode::Bounded(n) => n.get(),
2029            ParallelDecode::Sequential => 0,
2030        };
2031        assert_eq!(bytes(SecurityConfig::default()), 128 * 1024 * 1024);
2032        assert_eq!(bytes(SecurityConfig::permissive()), 1024 * 1024 * 1024);
2033    }
2034
2035    #[test]
2036    fn test_max_decoder_memory_defaults() {
2037        assert_eq!(
2038            SecurityConfig::default().max_decoder_memory.get(),
2039            256 * 1024 * 1024
2040        );
2041        assert_eq!(
2042            SecurityConfig::permissive().max_decoder_memory.get(),
2043            1024 * 1024 * 1024
2044        );
2045    }
2046
2047    // Regression tests for #449 and #871: malformed `allowed_extensions` /
2048    // `banned_path_components` entries are refused at construction, so a
2049    // config can never hold one.
2050
2051    #[test]
2052    fn test_try_add_refuses_unusable_entries() {
2053        let long = "x".repeat(256);
2054        for raw in ["", "bad\0ext", " gz", "tar.gz", "a/b", long.as_str()] {
2055            assert!(
2056                SecurityConfig::default()
2057                    .try_add_allowed_extension(raw)
2058                    .is_err(),
2059                "{raw:?}"
2060            );
2061        }
2062        for raw in ["", "bad\0", "a/b", "..", long.as_str()] {
2063            assert!(
2064                SecurityConfig::default()
2065                    .try_add_banned_path_component(raw)
2066                    .is_err(),
2067                "{raw:?}"
2068            );
2069        }
2070    }
2071
2072    #[test]
2073    fn test_dotted_extension_is_normalized_and_matches_any_case() {
2074        let cfg = SecurityConfig::default()
2075            .try_add_allowed_extension(".txt")
2076            .unwrap();
2077        assert!(cfg.is_extension_allowed(Some("txt")));
2078        assert!(crate::formats::common::is_extension_allowed(
2079            std::path::Path::new("A.TXT"),
2080            &cfg
2081        ));
2082        assert!(cfg.is_extension_allowed(Some("TXT")));
2083        assert!(!cfg.is_extension_allowed(Some("md")));
2084    }
2085
2086    #[test]
2087    fn default_banned_components_are_all_usable() {
2088        assert_eq!(
2089            default_banned_path_components().len(),
2090            DEFAULT_BANNED_PATH_COMPONENTS.len()
2091        );
2092    }
2093}