safe_unzip 0.1.5

Secure zip extraction. Prevents Zip Slip and Zip Bombs.
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
//! Async extraction API (requires the `async` feature).
//!
//! This module provides async versions of the extraction functions. Since the underlying
//! `zip` crate (and optionally `tar` crate with the `tar` feature) are synchronous,
//! extraction runs in a blocking thread pool via [`tokio::task::spawn_blocking`].
//!
//! # Example
//!
//! ```no_run
//! use safe_unzip::r#async::{extract_file, AsyncExtractor};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), safe_unzip::Error> {
//!     // Simple extraction
//!     let report = extract_file("/var/uploads", "archive.zip").await?;
//!     
//!     // With options
//!     let report = AsyncExtractor::new("/var/uploads")?
//!         .max_total_bytes(500 * 1024 * 1024)
//!         .max_file_count(1000)
//!         .extract_file("archive.zip")
//!         .await?;
//!     
//!     println!("Extracted {} files", report.files_extracted);
//!     Ok(())
//! }
//! ```
//!
//! # When to Use Async
//!
//! Use async extraction when:
//! - You're in an async runtime (tokio, async-std)
//! - You want to extract multiple archives concurrently
//! - You need to interleave extraction with other async I/O
//!
//! For simple scripts or sync contexts, use the regular [`crate::extract`] functions.

#[cfg(feature = "tar")]
use crate::{Driver, ExtractionReport, OverwriteMode, SymlinkBehavior, TarAdapter, ValidationMode};
use crate::{Error, ExtractionMode, Extractor, Limits, OverwritePolicy, Report, SymlinkPolicy};
use std::path::{Path, PathBuf};
use tokio::task::spawn_blocking;

/// Async extractor with the same security guarantees as [`Extractor`].
///
/// This wraps the synchronous extractor and runs extraction in a blocking thread pool.
/// All configuration options from [`Extractor`] are available.
#[derive(Clone)]
pub struct AsyncExtractor {
    destination: PathBuf,
    limits: Limits,
    overwrite: OverwritePolicy,
    symlinks: SymlinkPolicy,
    mode: ExtractionMode,
    create_destination: bool,
}

impl AsyncExtractor {
    /// Create an async extractor for the given destination directory.
    ///
    /// Returns [`Error::DestinationNotFound`] if the directory doesn't exist.
    /// Use [`Self::new_or_create`] to auto-create the destination.
    pub fn new<P: AsRef<Path>>(destination: P) -> Result<Self, Error> {
        let dest = destination.as_ref();
        if !dest.exists() {
            return Err(Error::DestinationNotFound {
                path: dest.display().to_string(),
            });
        }
        Ok(Self {
            destination: dest.to_path_buf(),
            limits: Limits::default(),
            overwrite: OverwritePolicy::default(),
            symlinks: SymlinkPolicy::default(),
            mode: ExtractionMode::default(),
            create_destination: false,
        })
    }

    /// Create an async extractor, creating the destination directory if needed.
    pub fn new_or_create<P: AsRef<Path>>(destination: P) -> Result<Self, Error> {
        let dest = destination.as_ref();
        if !dest.exists() {
            std::fs::create_dir_all(dest)?;
        }
        Ok(Self {
            destination: dest.to_path_buf(),
            limits: Limits::default(),
            overwrite: OverwritePolicy::default(),
            symlinks: SymlinkPolicy::default(),
            mode: ExtractionMode::default(),
            create_destination: true,
        })
    }

    /// Set resource limits.
    pub fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Set maximum total bytes to extract.
    pub fn max_total_bytes(mut self, bytes: u64) -> Self {
        self.limits.max_total_bytes = bytes;
        self
    }

    /// Set maximum number of files to extract.
    pub fn max_file_count(mut self, count: usize) -> Self {
        self.limits.max_file_count = count;
        self
    }

    /// Set maximum size for a single file.
    pub fn max_single_file(mut self, bytes: u64) -> Self {
        self.limits.max_single_file = bytes;
        self
    }

    /// Set maximum directory depth.
    pub fn max_path_depth(mut self, depth: usize) -> Self {
        self.limits.max_path_depth = depth;
        self
    }

    /// Set overwrite policy.
    pub fn overwrite(mut self, policy: OverwritePolicy) -> Self {
        self.overwrite = policy;
        self
    }

    /// Set symlink policy.
    pub fn symlinks(mut self, policy: SymlinkPolicy) -> Self {
        self.symlinks = policy;
        self
    }

    /// Set extraction mode.
    pub fn mode(mut self, mode: ExtractionMode) -> Self {
        self.mode = mode;
        self
    }

    /// Extract a ZIP file asynchronously.
    ///
    /// The actual extraction runs in a blocking thread pool.
    pub async fn extract_file<P: AsRef<Path>>(&self, path: P) -> Result<Report, Error> {
        let extractor = self.build_sync_extractor()?;
        let path = path.as_ref().to_path_buf();

        spawn_blocking(move || extractor.extract_file(path))
            .await
            .map_err(|e| Error::Io(std::io::Error::other(e)))?
    }

    /// Extract a ZIP from bytes asynchronously.
    pub async fn extract_bytes(&self, data: Vec<u8>) -> Result<Report, Error> {
        let extractor = self.build_sync_extractor()?;

        spawn_blocking(move || {
            let cursor = std::io::Cursor::new(data);
            extractor.extract(cursor)
        })
        .await
        .map_err(|e| Error::Io(std::io::Error::other(e)))?
    }

    /// Extract a TAR file asynchronously.
    #[cfg(feature = "tar")]
    pub async fn extract_tar_file<P: AsRef<Path>>(&self, path: P) -> Result<Report, Error> {
        let driver = self.build_driver()?;
        let path = path.as_ref().to_path_buf();

        let report = spawn_blocking(move || driver.extract_tar_file(path))
            .await
            .map_err(|e| Error::Io(std::io::Error::other(e)))??;
        Ok(extraction_report_to_report(report))
    }

    /// Extract a gzip-compressed TAR file asynchronously.
    #[cfg(feature = "tar")]
    pub async fn extract_tar_gz_file<P: AsRef<Path>>(&self, path: P) -> Result<Report, Error> {
        let driver = self.build_driver()?;
        let path = path.as_ref().to_path_buf();

        let report = spawn_blocking(move || driver.extract_tar_gz_file(path))
            .await
            .map_err(|e| Error::Io(std::io::Error::other(e)))??;
        Ok(extraction_report_to_report(report))
    }

    /// Extract a TAR from bytes asynchronously.
    #[cfg(feature = "tar")]
    pub async fn extract_tar_bytes(&self, data: Vec<u8>) -> Result<Report, Error> {
        let driver = self.build_driver()?;

        let report = spawn_blocking(move || {
            let cursor = std::io::Cursor::new(data);
            let adapter = TarAdapter::new(cursor);
            driver.extract_tar(adapter)
        })
        .await
        .map_err(|e| Error::Io(std::io::Error::other(e)))??;
        Ok(extraction_report_to_report(report))
    }

    /// Extract a gzip-compressed TAR from bytes asynchronously.
    #[cfg(feature = "tar")]
    pub async fn extract_tar_gz_bytes(&self, data: Vec<u8>) -> Result<Report, Error> {
        let driver = self.build_driver()?;

        let report = spawn_blocking(move || {
            let cursor = std::io::Cursor::new(data);
            let decoder = flate2::read::GzDecoder::new(cursor);
            let adapter = TarAdapter::new(decoder);
            driver.extract_tar(adapter)
        })
        .await
        .map_err(|e| Error::Io(std::io::Error::other(e)))??;
        Ok(extraction_report_to_report(report))
    }

    fn build_sync_extractor(&self) -> Result<Extractor, Error> {
        let extractor = if self.create_destination {
            Extractor::new_or_create(&self.destination)?
        } else {
            Extractor::new(&self.destination)?
        };

        Ok(extractor
            .limits(self.limits)
            .overwrite(self.overwrite)
            .symlinks(self.symlinks)
            .mode(self.mode))
    }

    #[cfg(feature = "tar")]
    fn build_driver(&self) -> Result<Driver, Error> {
        let driver = if self.create_destination {
            Driver::new_or_create(&self.destination)?
        } else {
            Driver::new(&self.destination)?
        };

        Ok(driver
            .limits(self.limits)
            .overwrite(convert_overwrite_policy(self.overwrite))
            .symlinks(convert_symlink_policy(self.symlinks))
            .validation(convert_extraction_mode(self.mode)))
    }
}

// Helper to convert between report types
#[cfg(feature = "tar")]
fn extraction_report_to_report(report: ExtractionReport) -> Report {
    Report {
        files_extracted: report.files_extracted,
        dirs_created: report.dirs_created,
        bytes_written: report.bytes_written,
        entries_skipped: report.entries_skipped,
    }
}

// Helper to convert policy types (only needed for TAR via Driver)
#[cfg(feature = "tar")]
fn convert_overwrite_policy(policy: OverwritePolicy) -> OverwriteMode {
    match policy {
        OverwritePolicy::Error => OverwriteMode::Error,
        OverwritePolicy::Skip => OverwriteMode::Skip,
        OverwritePolicy::Overwrite => OverwriteMode::Overwrite,
    }
}

#[cfg(feature = "tar")]
fn convert_symlink_policy(policy: SymlinkPolicy) -> SymlinkBehavior {
    match policy {
        SymlinkPolicy::Skip => SymlinkBehavior::Skip,
        SymlinkPolicy::Error => SymlinkBehavior::Error,
    }
}

#[cfg(feature = "tar")]
fn convert_extraction_mode(mode: ExtractionMode) -> ValidationMode {
    match mode {
        ExtractionMode::Streaming => ValidationMode::Streaming,
        ExtractionMode::ValidateFirst => ValidationMode::ValidateFirst,
    }
}

// ============================================================================
// Convenience functions
// ============================================================================

/// Extract a ZIP file asynchronously with default settings.
///
/// Creates the destination directory if it doesn't exist.
///
/// # Example
///
/// ```no_run
/// use safe_unzip::r#async::extract_file;
///
/// #[tokio::main]
/// async fn main() -> Result<(), safe_unzip::Error> {
///     let report = extract_file("/var/uploads", "archive.zip").await?;
///     println!("Extracted {} files", report.files_extracted);
///     Ok(())
/// }
/// ```
pub async fn extract_file<D, F>(destination: D, file_path: F) -> Result<Report, Error>
where
    D: AsRef<Path>,
    F: AsRef<Path>,
{
    AsyncExtractor::new_or_create(destination)?
        .extract_file(file_path)
        .await
}

/// Extract a ZIP from bytes asynchronously with default settings.
///
/// Creates the destination directory if it doesn't exist.
pub async fn extract_bytes<D>(destination: D, data: Vec<u8>) -> Result<Report, Error>
where
    D: AsRef<Path>,
{
    AsyncExtractor::new_or_create(destination)?
        .extract_bytes(data)
        .await
}

/// Extract a TAR file asynchronously with default settings.
///
/// Creates the destination directory if it doesn't exist.
///
/// # Example
///
/// ```no_run
/// use safe_unzip::r#async::extract_tar_file;
///
/// #[tokio::main]
/// async fn main() -> Result<(), safe_unzip::Error> {
///     let report = extract_tar_file("/var/uploads", "archive.tar").await?;
///     println!("Extracted {} files", report.files_extracted);
///     Ok(())
/// }
/// ```
#[cfg(feature = "tar")]
pub async fn extract_tar_file<D, F>(destination: D, file_path: F) -> Result<Report, Error>
where
    D: AsRef<Path>,
    F: AsRef<Path>,
{
    AsyncExtractor::new_or_create(destination)?
        .extract_tar_file(file_path)
        .await
}

/// Extract a gzip-compressed TAR file asynchronously with default settings.
///
/// Creates the destination directory if it doesn't exist.
///
/// # Example
///
/// ```no_run
/// use safe_unzip::r#async::extract_tar_gz_file;
///
/// #[tokio::main]
/// async fn main() -> Result<(), safe_unzip::Error> {
///     let report = extract_tar_gz_file("/var/uploads", "archive.tar.gz").await?;
///     println!("Extracted {} files", report.files_extracted);
///     Ok(())
/// }
/// ```
#[cfg(feature = "tar")]
pub async fn extract_tar_gz_file<D, F>(destination: D, file_path: F) -> Result<Report, Error>
where
    D: AsRef<Path>,
    F: AsRef<Path>,
{
    AsyncExtractor::new_or_create(destination)?
        .extract_tar_gz_file(file_path)
        .await
}

/// Extract a TAR from bytes asynchronously with default settings.
///
/// Creates the destination directory if it doesn't exist.
#[cfg(feature = "tar")]
pub async fn extract_tar_bytes<D>(destination: D, data: Vec<u8>) -> Result<Report, Error>
where
    D: AsRef<Path>,
{
    AsyncExtractor::new_or_create(destination)?
        .extract_tar_bytes(data)
        .await
}

/// Extract a gzip-compressed TAR from bytes asynchronously with default settings.
///
/// Creates the destination directory if it doesn't exist.
#[cfg(feature = "tar")]
pub async fn extract_tar_gz_bytes<D>(destination: D, data: Vec<u8>) -> Result<Report, Error>
where
    D: AsRef<Path>,
{
    AsyncExtractor::new_or_create(destination)?
        .extract_tar_gz_bytes(data)
        .await
}