exarch-core 0.9.0

Memory-safe archive extraction library with security validation
Documentation
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
//! Configuration for archive creation operations.

use crate::ArchiveError;
use crate::Limit;
use crate::Result;
use crate::creation::filters::ExcludePattern;
use std::num::NonZeroU64;
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::creation::CompressionLevel;
///
/// let level = CompressionLevel::try_from(9u8)?;
/// assert_eq!(level.get(), 9);
/// assert_eq!(CompressionLevel::default().get(), 6);
/// 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 level on the 1-9 scale.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

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

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 (1..=9).contains(&level) {
            Ok(Self(level))
        } else {
            Err(ArchiveError::InvalidCompressionLevel {
                level: u32::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> {
        u8::try_from(level)
            .ok()
            .and_then(|level| Self::try_from(level).ok())
            .ok_or(ArchiveError::InvalidCompressionLevel { level })
    }
}

/// 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::creation::CompressionLevel;
/// use exarch_core::creation::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<ExcludePattern>,

    /// 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,

    /// Preserve file permissions in the archive.
    ///
    /// Default: `true`.
    pub preserve_permissions: bool,
}

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
    /// - `preserve_permissions`: `true`
    fn default() -> Self {
        Self {
            follow_symlinks: false,
            include_hidden: false,
            max_file_size: Limit::Unbounded,
            exclude_patterns: vec![
                ExcludePattern::exact(".git"),
                ExcludePattern::exact(".DS_Store"),
                ExcludePattern::suffix(".tmp"),
            ],
            strip_prefix: None,
            compression_level: CompressionLevel::default(),
            preserve_permissions: true,
        }
    }
}

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::creation::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 whether to include hidden files.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::creation::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::Limit;
    /// use exarch_core::creation::CreationConfig;
    ///
    /// 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::creation::CreationConfig;
    /// use exarch_core::creation::ExcludePattern;
    ///
    /// let log = ExcludePattern::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<ExcludePattern>) -> Self {
        self.exclude_patterns = patterns;
        self
    }

    /// Sets the strip prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::creation::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::creation::CompressionLevel;
    /// use exarch_core::creation::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::creation::CreationConfig;
    ///
    /// let config = CreationConfig::default().with_preserve_permissions(false);
    /// assert!(!config.preserve_permissions);
    /// ```
    #[must_use]
    pub fn with_preserve_permissions(mut self, preserve: bool) -> Self {
        self.preserve_permissions = preserve;
        self
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
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.preserve_permissions);
    }

    #[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![ExcludePattern::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![ExcludePattern::try_from("*.log").unwrap()]
        );
        assert_eq!(config.strip_prefix, Some(PathBuf::from("/base")));
        assert_eq!(config.compression_level, level);
        assert!(!config.preserve_permissions);
    }

    #[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: l }) if l == u32::from(level)
            );
        }
        for level in [0u32, 10, 256, 4_294_967_295] {
            assert_matches!(
                CompressionLevel::try_from(level),
                Err(ArchiveError::InvalidCompressionLevel { level: l }) if l == 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.preserve_permissions);
    }

    #[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(&ExcludePattern::exact(".git")),
            "should exclude .git by default"
        );
    }
}