exarch-core 0.12.0

Memory-safe archive extraction library with security validation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Configuration for archive creation operations.

use crate::ArchiveError;
use crate::Limit;
use crate::PermissionPolicy;
use crate::Result;
use crate::error::RequestedLevel;
use crate::pattern::EntryPattern;
use std::num::NonZeroU64;
use std::num::NonZeroUsize;
use std::path::PathBuf;

/// A compression level on exarch's 1-9 scale; the default is 6.
///
/// Built only through [`TryFrom<u8>`] / [`TryFrom<u32>`], so the range is
/// checked once at the boundary and every codec mapping can rely on it.
///
/// # Examples
///
/// ```
/// use exarch_core::CompressionLevel;
///
/// let level = CompressionLevel::try_from(9u8)?;
/// assert_eq!(level.get(), 9);
/// assert_eq!(CompressionLevel::default(), CompressionLevel::DEFAULT);
/// assert_eq!(
///     (CompressionLevel::MIN.get(), CompressionLevel::MAX.get()),
///     (1, 9)
/// );
/// assert!(CompressionLevel::try_from(0u8).is_err());
/// assert!(CompressionLevel::try_from(10u32).is_err());
/// # Ok::<(), exarch_core::ArchiveError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CompressionLevel(u8);

impl CompressionLevel {
    /// The default level, 6.
    pub const DEFAULT: Self = Self(6);
    /// The highest level, 9: slowest, smallest output.
    pub const MAX: Self = Self(9);
    /// The lowest level, 1: fastest, largest output.
    pub const MIN: Self = Self(1);

    /// The level on the 1-9 scale.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

impl Default for CompressionLevel {
    fn default() -> Self {
        Self::DEFAULT
    }
}

impl TryFrom<u8> for CompressionLevel {
    type Error = ArchiveError;

    /// # Errors
    ///
    /// Returns [`ArchiveError::InvalidCompressionLevel`] if `level` is not in
    /// 1-9.
    fn try_from(level: u8) -> Result<Self> {
        if (Self::MIN.0..=Self::MAX.0).contains(&level) {
            Ok(Self(level))
        } else {
            Err(ArchiveError::InvalidCompressionLevel {
                level: RequestedLevel::Integer(i64::from(level)),
            })
        }
    }
}

impl TryFrom<u32> for CompressionLevel {
    type Error = ArchiveError;

    /// # Errors
    ///
    /// Returns [`ArchiveError::InvalidCompressionLevel`] if `level` is not in
    /// 1-9.
    fn try_from(level: u32) -> Result<Self> {
        Self::from_i128(i128::from(level))
    }
}

impl TryFrom<RequestedLevel> for CompressionLevel {
    type Error = ArchiveError;

    /// Accepts what a caller asked for, as a binding or the CLI reports it.
    ///
    /// # Errors
    ///
    /// Returns [`ArchiveError::InvalidCompressionLevel`] carrying `requested`
    /// unless it is an integer in 1-9.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CompressionLevel;
    /// use exarch_core::RequestedLevel;
    ///
    /// assert_eq!(
    ///     CompressionLevel::try_from(RequestedLevel::Integer(9))?.get(),
    ///     9
    /// );
    /// assert!(CompressionLevel::try_from(RequestedLevel::OutOfRange).is_err());
    /// assert!(CompressionLevel::try_from(RequestedLevel::Fractional(1.5)).is_err());
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    fn try_from(requested: RequestedLevel) -> Result<Self> {
        match requested {
            RequestedLevel::Integer(level) => Self::from_i128(i128::from(level)),
            other => Err(ArchiveError::InvalidCompressionLevel { level: other }),
        }
    }
}

impl CompressionLevel {
    /// Parses an integer of any width, as a binding receives it.
    ///
    /// # Errors
    ///
    /// Returns [`ArchiveError::InvalidCompressionLevel`] carrying the
    /// requested value if it is not in 1-9.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CompressionLevel;
    ///
    /// assert_eq!(CompressionLevel::from_i128(9)?.get(), 9);
    /// assert!(CompressionLevel::from_i128(-3).is_err());
    /// assert!(CompressionLevel::from_i128(1 << 40).is_err());
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    pub fn from_i128(level: i128) -> Result<Self> {
        u8::try_from(level)
            .ok()
            .filter(|level| (Self::MIN.0..=Self::MAX.0).contains(level))
            .map(Self)
            .ok_or_else(|| ArchiveError::InvalidCompressionLevel {
                level: i64::try_from(level)
                    .map_or(RequestedLevel::OutOfRange, RequestedLevel::Integer),
            })
    }

    /// Parses a floating-point number, as a JavaScript caller passes it.
    ///
    /// # Errors
    ///
    /// Returns [`ArchiveError::InvalidCompressionLevel`] carrying the
    /// requested value for a non-finite number, a fractional number or a whole
    /// number outside 1-9.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CompressionLevel;
    ///
    /// assert_eq!(CompressionLevel::from_f64(6.0)?.get(), 6);
    /// assert!(CompressionLevel::from_f64(1.5).is_err());
    /// assert!(CompressionLevel::from_f64(f64::NAN).is_err());
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    #[expect(
        clippy::cast_possible_truncation,
        reason = "a whole number saturated by `as`; any value outside 1-9 is refused by from_i128"
    )]
    pub fn from_f64(level: f64) -> Result<Self> {
        if !level.is_finite() {
            return Err(ArchiveError::InvalidCompressionLevel {
                level: RequestedLevel::NonFinite,
            });
        }
        if level.fract() != 0.0 {
            return Err(ArchiveError::InvalidCompressionLevel {
                level: RequestedLevel::Fractional(level),
            });
        }
        Self::from_i128(level as i128)
    }
}

/// How many threads compress ZIP entries while an archive is created.
///
/// The bytes of the archive do not depend on this value: a ZIP is the same for
/// [`Sequential`](Self::Sequential) and every thread count. Formats other than
/// ZIP, and targets without threads, ignore it. A count above the threads the
/// host offers is clamped to them.
///
/// # Examples
///
/// ```
/// use std::num::NonZeroUsize;
///
/// use exarch_core::CreationConfig;
/// use exarch_core::Parallelism;
///
/// assert_eq!(
///     CreationConfig::default().parallelism,
///     Parallelism::Sequential
/// );
/// let four = Parallelism::Threads(NonZeroUsize::new(4).unwrap());
/// let config = CreationConfig::default().with_parallelism(four);
/// assert_eq!(config.parallelism, four);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Parallelism {
    /// Compress every entry on the calling thread.
    #[default]
    Sequential,
    /// Compress ZIP entries on up to this many worker threads.
    Threads(NonZeroUsize),
}

/// Configuration for archive creation operations.
///
/// Controls how archives are created from filesystem sources, including
/// security options, compression settings, and file filtering.
///
/// # Examples
///
/// ```
/// use exarch_core::CompressionLevel;
/// use exarch_core::CreationConfig;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Use secure defaults
/// let config = CreationConfig::default();
///
/// // Customize for specific needs
/// let custom = CreationConfig::default()
///     .with_follow_symlinks(true)
///     .with_compression_level(CompressionLevel::try_from(9u8)?);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CreationConfig {
    /// Follow symlinks when adding files to archive.
    ///
    /// Default: `false` (store symlinks as symlinks).
    ///
    /// Security note: Following symlinks may include unintended files
    /// from outside the source directory.
    pub follow_symlinks: bool,

    /// Include hidden entries (names starting with '.').
    ///
    /// When `false`, a hidden file is skipped and a hidden directory below a
    /// source directory is skipped whole: it is never entered, so nothing
    /// inside it (`.ssh/id_rsa`, `.aws/credentials`) is archived, even under a
    /// visible name. The skipped directory is counted once as a hidden skip.
    /// A hidden source directory named by the caller, and a source file named
    /// directly, are archived regardless.
    ///
    /// The name on disk decides, before `strip_prefix` applies. With
    /// [`follow_symlinks`](Self::follow_symlinks) a link is judged by its own
    /// visible name, not its target's: a link `keys -> .ssh` is archived (its
    /// contents under `keys/`), while a hidden-named link to a directory is
    /// skipped.
    ///
    /// Default: `false` (skip hidden entries).
    pub include_hidden: bool,

    /// Maximum size for a single file in bytes.
    ///
    /// Files larger than this limit will be skipped.
    /// [`Limit::Unbounded`] means no limit; a zero limit is unrepresentable.
    ///
    /// Default: [`Limit::Unbounded`].
    pub max_file_size: Limit<NonZeroU64>,

    /// Patterns to exclude from the archive.
    ///
    /// Files matching these patterns will be skipped.
    ///
    /// Default: `[".git", ".DS_Store", "*.tmp"]`.
    pub exclude_patterns: Vec<EntryPattern>,

    /// Prefix to strip from entry paths in the archive.
    ///
    /// If set, this prefix will be removed from all entry paths.
    /// Useful for creating archives without deep directory nesting.
    ///
    /// Default: `None`.
    pub strip_prefix: Option<PathBuf>,

    /// Compression level (1-9).
    ///
    /// Higher values provide better compression but slower speed.
    ///
    /// Default: 6 (balanced).
    pub compression_level: CompressionLevel,

    /// Whether file permissions are stored in the archive.
    ///
    /// Default: [`PermissionPolicy::Preserve`].
    pub permissions: PermissionPolicy,

    /// Threads that compress ZIP entries.
    ///
    /// Default: [`Parallelism::Sequential`].
    pub parallelism: Parallelism,
}

impl Default for CreationConfig {
    /// Creates a `CreationConfig` with secure default settings.
    ///
    /// Default values:
    /// - `follow_symlinks`: `false`
    /// - `include_hidden`: `false`
    /// - `max_file_size`: [`Limit::Unbounded`]
    /// - `exclude_patterns`: `[".git", ".DS_Store", "*.tmp"]`
    /// - `strip_prefix`: `None`
    /// - `compression_level`: 6
    /// - `permissions`: [`PermissionPolicy::Preserve`]
    /// - `parallelism`: [`Parallelism::Sequential`]
    fn default() -> Self {
        Self {
            follow_symlinks: false,
            include_hidden: false,
            max_file_size: Limit::Unbounded,
            exclude_patterns: vec![
                EntryPattern::literal_name(".git"),
                EntryPattern::literal_name(".DS_Store"),
                EntryPattern::suffix_name(".tmp"),
            ],
            strip_prefix: None,
            compression_level: CompressionLevel::default(),
            permissions: PermissionPolicy::Preserve,
            parallelism: Parallelism::Sequential,
        }
    }
}

impl CreationConfig {
    /// Creates a new `CreationConfig` with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets whether to follow symlinks.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CreationConfig;
    ///
    /// let config = CreationConfig::default().with_follow_symlinks(true);
    /// assert!(config.follow_symlinks);
    /// ```
    #[must_use]
    pub fn with_follow_symlinks(mut self, follow: bool) -> Self {
        self.follow_symlinks = follow;
        self
    }

    /// Sets the threads that compress ZIP entries.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CreationConfig;
    /// use exarch_core::Parallelism;
    ///
    /// let config = CreationConfig::default().with_parallelism(Parallelism::Sequential);
    /// assert_eq!(config.parallelism, Parallelism::Sequential);
    /// ```
    #[must_use]
    pub fn with_parallelism(mut self, parallelism: Parallelism) -> Self {
        self.parallelism = parallelism;
        self
    }

    /// Sets whether to include hidden files.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CreationConfig;
    ///
    /// let config = CreationConfig::default().with_include_hidden(true);
    /// assert!(config.include_hidden);
    /// ```
    #[must_use]
    pub fn with_include_hidden(mut self, include: bool) -> Self {
        self.include_hidden = include;
        self
    }

    /// Sets the maximum file size; larger files are skipped.
    ///
    /// Pass a [`NonZeroU64`] for a bound or [`Limit::Unbounded`] for none.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CreationConfig;
    /// use exarch_core::Limit;
    ///
    /// let config = CreationConfig::default().with_max_file_size(exarch_core::non_zero!(1024 * 1024));
    /// assert!(config.max_file_size.admits(1024 * 1024));
    /// assert!(!config.max_file_size.admits(1024 * 1024 + 1));
    ///
    /// let config = config.with_max_file_size(Limit::Unbounded);
    /// assert_eq!(config.max_file_size, Limit::Unbounded);
    /// ```
    #[must_use]
    pub fn with_max_file_size(mut self, max_size: impl Into<Limit<NonZeroU64>>) -> Self {
        self.max_file_size = max_size.into();
        self
    }

    /// Sets the exclude patterns.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CreationConfig;
    /// use exarch_core::EntryPattern;
    ///
    /// let log = EntryPattern::try_from("*.log")?;
    /// let config = CreationConfig::default().with_exclude_patterns(vec![log.clone()]);
    /// assert_eq!(config.exclude_patterns, vec![log]);
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    #[must_use]
    pub fn with_exclude_patterns(mut self, patterns: Vec<EntryPattern>) -> Self {
        self.exclude_patterns = patterns;
        self
    }

    /// Sets the strip prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CreationConfig;
    /// use std::path::PathBuf;
    ///
    /// let config = CreationConfig::default().with_strip_prefix(Some(PathBuf::from("/base")));
    /// assert_eq!(config.strip_prefix, Some(PathBuf::from("/base")));
    /// ```
    #[must_use]
    pub fn with_strip_prefix(mut self, prefix: Option<PathBuf>) -> Self {
        self.strip_prefix = prefix;
        self
    }

    /// Sets the compression level.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CompressionLevel;
    /// use exarch_core::CreationConfig;
    ///
    /// let level = CompressionLevel::try_from(9u8)?;
    /// let config = CreationConfig::default().with_compression_level(level);
    /// assert_eq!(config.compression_level, level);
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    #[must_use]
    pub fn with_compression_level(mut self, level: CompressionLevel) -> Self {
        self.compression_level = level;
        self
    }

    /// Sets whether to preserve permissions.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::CreationConfig;
    ///
    /// let config = CreationConfig::default().with_preserve_permissions(false);
    /// assert!(!config.permissions.preserves());
    /// ```
    #[must_use]
    pub fn with_preserve_permissions(mut self, preserve: bool) -> Self {
        self.permissions = PermissionPolicy::from_preserve(preserve);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::assert_matches;

    #[test]
    fn test_creation_config_default() {
        let config = CreationConfig::default();
        assert!(!config.follow_symlinks);
        assert!(!config.include_hidden);
        assert_eq!(config.max_file_size, Limit::Unbounded);
        assert_eq!(config.exclude_patterns.len(), 3);
        let shown: Vec<String> = config
            .exclude_patterns
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(shown, [".git", ".DS_Store", "*.tmp"]);
        assert_eq!(config.strip_prefix, None);
        assert_eq!(config.compression_level, CompressionLevel::default());
        assert!(config.permissions.preserves());
    }

    #[test]
    fn test_creation_config_builder() {
        let level = CompressionLevel::try_from(9u8).unwrap();
        let config = CreationConfig::default()
            .with_follow_symlinks(true)
            .with_include_hidden(true)
            .with_max_file_size(crate::non_zero!(1024 * 1024))
            .with_exclude_patterns(vec![EntryPattern::try_from("*.log").unwrap()])
            .with_strip_prefix(Some(PathBuf::from("/base")))
            .with_compression_level(level)
            .with_preserve_permissions(false);

        assert!(config.follow_symlinks);
        assert!(config.include_hidden);
        assert_eq!(
            config.max_file_size,
            Limit::Bounded(crate::non_zero!(1024 * 1024))
        );
        assert_eq!(
            config.exclude_patterns,
            vec![EntryPattern::try_from("*.log").unwrap()]
        );
        assert_eq!(config.strip_prefix, Some(PathBuf::from("/base")));
        assert_eq!(config.compression_level, level);
        assert!(!config.permissions.preserves());
    }

    #[test]
    fn test_compression_level_refuses_out_of_range() {
        for level in [0u8, 10, 200] {
            assert_matches!(
                CompressionLevel::try_from(level),
                Err(ArchiveError::InvalidCompressionLevel { level: RequestedLevel::Integer(l) }) if l == i64::from(level)
            );
        }
        for level in [0u32, 10, 256, 4_294_967_295] {
            assert_matches!(
                CompressionLevel::try_from(level),
                Err(ArchiveError::InvalidCompressionLevel { level: RequestedLevel::Integer(l) }) if l == i64::from(level)
            );
        }
    }

    #[test]
    fn test_compression_level_accepts_the_whole_scale() {
        for level in 1u8..=9 {
            assert_eq!(CompressionLevel::try_from(level).unwrap().get(), level);
            assert_eq!(
                CompressionLevel::try_from(u32::from(level)).unwrap().get(),
                level
            );
        }
        assert_eq!(CompressionLevel::default().get(), 6);
    }

    #[test]
    fn test_creation_config_new() {
        let config = CreationConfig::new();
        assert_eq!(config.compression_level, CompressionLevel::default());
        assert!(config.permissions.preserves());
    }

    #[test]
    fn test_creation_config_secure_defaults() {
        let config = CreationConfig::default();

        // Security: Don't follow symlinks by default
        assert!(
            !config.follow_symlinks,
            "should not follow symlinks by default (security)"
        );

        // Security: Don't include hidden files by default
        assert!(
            !config.include_hidden,
            "should not include hidden files by default"
        );

        // Security: Exclude sensitive patterns
        assert!(
            config
                .exclude_patterns
                .contains(&EntryPattern::literal_name(".git")),
            "should exclude .git by default"
        );
    }
}