Skip to main content

exarch_core/
api.rs

1//! High-level public API for archive extraction, creation, and inspection.
2
3use std::path::Path;
4
5use crate::ArchiveError;
6use crate::ArchiveReader;
7use crate::CreateRequest;
8use crate::EntrySink;
9use crate::ExtractRequest;
10use crate::ExtractionReport;
11use crate::OutputFile;
12use crate::OutputFormat;
13use crate::ProgressCallback;
14use crate::Result;
15use crate::SecurityConfig;
16use crate::config::ExtractionOptions;
17use crate::creation::CreationConfig;
18use crate::creation::CreationReport;
19use crate::formats::SevenZArchive;
20use crate::formats::ZipArchive;
21use crate::formats::compression::CompressionCodec;
22use crate::formats::compression::DecoderLimits;
23use crate::formats::detect::CreatableFormat;
24use crate::formats::detect::FormatFamily;
25use crate::formats::detect::detect_format;
26use crate::formats::detect::detect_format_from_extension;
27use crate::formats::detect::is_zip_family_alias;
28use crate::formats::source_fault::TapSource;
29use crate::inspection::ArchiveManifest;
30use crate::inspection::VerificationReport;
31use crate::inspection::integrity::TarTrailer;
32use crate::reader::SeekableFormat;
33use crate::reader::Source;
34use crate::reader::tar_archive;
35use crate::sink::SinkOptions;
36use crate::sink::SinkReuse;
37use crate::sink::SinkTarget;
38
39/// Extracts an archive to the specified output directory.
40///
41/// This is the main high-level API for extracting archives with security
42/// validation. The archive format is automatically detected.
43///
44/// # Arguments
45///
46/// * `archive_path` - Path to the archive file
47/// * `output_dir` - Directory where files will be extracted
48/// * `config` - Security configuration for the extraction
49///
50/// # Errors
51///
52/// Returns an error if:
53/// - Archive file cannot be opened
54/// - Archive format is unsupported
55/// - Security validation fails
56/// - I/O operations fail
57///
58/// # Examples
59///
60/// ```no_run
61/// use exarch_core::SecurityConfig;
62/// use exarch_core::extract_archive;
63///
64/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
65/// let config = SecurityConfig::default();
66/// let report = extract_archive("archive.tar.gz", "/tmp/output", &config)?;
67/// println!("Extracted {} files", report.files_extracted);
68/// # Ok(())
69/// # }
70/// ```
71pub fn extract_archive<P: AsRef<Path>, Q: AsRef<Path>>(
72    archive_path: P,
73    output_dir: Q,
74    config: &SecurityConfig,
75) -> Result<ExtractionReport> {
76    ExtractRequest::new(config).extract(archive_path, output_dir)
77}
78
79/// Extracts `archive_path` under a config that is already validated.
80pub(crate) fn extract_validated<P: AsRef<Path>, Q: AsRef<Path>>(
81    archive_path: P,
82    output_dir: Q,
83    config: &SecurityConfig,
84    options: &ExtractionOptions,
85    progress: &mut dyn ProgressCallback,
86) -> Result<ExtractionReport> {
87    let archive_path = archive_path.as_ref();
88    let output_dir = output_dir.as_ref();
89
90    // Detect archive format from file extension
91    let format = detect_format(archive_path)?;
92
93    // Dispatch to format-specific extraction
94    match format.family() {
95        FormatFamily::Tar(codec) => {
96            extract_tar(archive_path, output_dir, config, options, progress, codec)
97        }
98        FormatFamily::Seekable(SeekableFormat::Zip) => {
99            extract_zip(archive_path, output_dir, config, options, progress)
100        }
101        FormatFamily::Seekable(SeekableFormat::SevenZ) => {
102            extract_7z(archive_path, output_dir, config, options, progress)
103        }
104    }
105}
106
107/// Runs `extract` into `output_dir`, or into a staging directory that is
108/// renamed over `output_dir` on success when `options` ask for atomic
109/// extraction.
110pub(crate) fn extract_staged(
111    output_dir: &Path,
112    options: &ExtractionOptions,
113    extract: impl FnOnce(&Path) -> Result<ExtractionReport>,
114) -> Result<ExtractionReport> {
115    if options.atomic {
116        extract_atomic(output_dir, extract)
117    } else {
118        extract(output_dir)
119    }
120}
121
122#[expect(
123    clippy::disallowed_methods,
124    reason = "stages the whole extraction in a private sibling directory, then renames it into place"
125)]
126fn extract_atomic(
127    output_dir: &Path,
128    extract: impl FnOnce(&Path) -> Result<ExtractionReport>,
129) -> Result<ExtractionReport> {
130    // Canonicalize output_dir to resolve any symlinks in the path before
131    // computing the parent, so temp dir lands on the same filesystem.
132    // If output_dir doesn't exist yet, use its lexical parent.
133    let canonical_output = if output_dir.exists() {
134        output_dir.canonicalize().map_err(ArchiveError::Io)?
135    } else {
136        output_dir.to_path_buf()
137    };
138
139    let parent = canonical_output
140        .parent()
141        .ok_or(ArchiveError::InvalidConfiguration {
142            setting: crate::ConfigSetting::OutputPath,
143            problem: crate::ConfigProblem::NoParent,
144        })?;
145
146    std::fs::create_dir_all(parent).map_err(ArchiveError::Io)?;
147
148    let temp_dir = tempfile::Builder::new()
149        .prefix(".exarch-")
150        .tempdir_in(parent)
151        .map_err(|e| {
152            ArchiveError::Io(std::io::Error::new(
153                e.kind(),
154                format!(
155                    "failed to create temp directory in {}: {e}",
156                    parent.display()
157                ),
158            ))
159        })?;
160
161    let result = extract(temp_dir.path());
162
163    match result {
164        Ok(report) => {
165            // Consume TempDir to prevent Drop cleanup, then rename.
166            let temp_path = temp_dir.keep();
167            std::fs::rename(&temp_path, output_dir).map_err(|e| {
168                // Rename failed: clean up temp dir
169                let _ = std::fs::remove_dir_all(&temp_path);
170                // Map AlreadyExists to OutputExists for caller clarity
171                if e.kind() == std::io::ErrorKind::AlreadyExists {
172                    ArchiveError::OutputExists {
173                        path: output_dir.to_path_buf(),
174                    }
175                } else {
176                    ArchiveError::Io(std::io::Error::new(
177                        e.kind(),
178                        format!("failed to rename temp dir to {}: {e}", output_dir.display()),
179                    ))
180                }
181            })?;
182
183            Ok(report)
184        }
185        Err(e) => {
186            // TempDir Drop runs here: cleans up temp dir automatically.
187            Err(e.rolled_back())
188        }
189    }
190}
191
192/// Opens `archive_path` as a TAR stream (decoded with `codec` when present)
193/// and extracts it.
194fn extract_tar(
195    archive_path: &Path,
196    output_dir: &Path,
197    config: &SecurityConfig,
198    options: &ExtractionOptions,
199    progress: &mut dyn ProgressCallback,
200    codec: Option<CompressionCodec>,
201) -> Result<ExtractionReport> {
202    use crate::formats::tar::open_tar_stream;
203
204    let decoded = open_tar_stream(archive_path, codec, DecoderLimits::of(config))?;
205    let trailer = TarTrailer::for_codec(codec);
206    let source = decoded.source();
207    extract_tar_stream(
208        decoded.stream,
209        source,
210        trailer,
211        output_dir,
212        config,
213        options,
214        progress,
215    )
216}
217
218/// Extracts a TAR stream that is already decoded; `source` meters its raw
219/// input and `trailer` says how the bytes after the end-of-archive marker are
220/// checked.
221pub(crate) fn extract_tar_stream<R: std::io::Read>(
222    stream: R,
223    source: TapSource,
224    trailer: TarTrailer,
225    output_dir: &Path,
226    config: &SecurityConfig,
227    options: &ExtractionOptions,
228    progress: &mut dyn ProgressCallback,
229) -> Result<ExtractionReport> {
230    use crate::formats::TarArchive;
231    use crate::formats::traits::ArchiveFormat;
232
233    TarArchive::with_source(stream, source, trailer, config).extract(output_dir, options, progress)
234}
235
236fn extract_zip(
237    archive_path: &Path,
238    output_dir: &Path,
239    config: &SecurityConfig,
240    options: &ExtractionOptions,
241    progress: &mut dyn ProgressCallback,
242) -> Result<ExtractionReport> {
243    use crate::formats::ZipArchive;
244    use crate::formats::traits::ArchiveFormat;
245    use std::fs::File;
246
247    let file = File::open(archive_path)?;
248    let archive = ZipArchive::for_extraction(file, config, options.decode_reuse)?;
249    archive.extract(output_dir, options, progress)
250}
251
252fn extract_7z(
253    archive_path: &Path,
254    output_dir: &Path,
255    config: &SecurityConfig,
256    options: &ExtractionOptions,
257    progress: &mut dyn ProgressCallback,
258) -> Result<ExtractionReport> {
259    use crate::formats::SevenZArchive;
260    use crate::formats::traits::ArchiveFormat;
261    use std::fs::File;
262
263    let file = File::open(archive_path)?;
264    let archive = SevenZArchive::new(file, config)?;
265    archive.extract(output_dir, options, progress)
266}
267
268/// Creates an archive from source files and directories.
269///
270/// The format is detected from the output file extension; use
271/// [`CreateRequest`] with an [`OutputFile`] to state it. An existing output
272/// is replaced atomically once the archive is complete, and a failed creation
273/// leaves the output as it was.
274///
275/// # Arguments
276///
277/// * `output_path` - Path to the output archive file
278/// * `sources` - Source files and directories to include
279/// * `config` - Creation configuration
280///
281/// # Errors
282///
283/// Returns an error if:
284/// - Cannot determine archive format
285/// - Source files don't exist
286/// - I/O operations fail
287/// - Configuration is invalid
288///
289/// # Examples
290///
291/// ```no_run
292/// use exarch_core::create_archive;
293/// use exarch_core::creation::CreationConfig;
294///
295/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
296/// let config = CreationConfig::default();
297/// let report = create_archive("output.tar.gz", &["src/", "Cargo.toml"], &config)?;
298/// println!("Created archive with {} files", report.files_added);
299/// # Ok(())
300/// # }
301/// ```
302pub fn create_archive<P: AsRef<Path>, Q: AsRef<Path>>(
303    output_path: P,
304    sources: &[Q],
305    config: &CreationConfig,
306) -> Result<CreationReport> {
307    CreateRequest::new(config).create(&OutputFile::replace(output_path.as_ref()), sources)
308}
309
310/// Lists archive contents without extracting.
311///
312/// Returns a manifest containing metadata for all entries in the archive.
313/// No files are written to disk during this operation.
314///
315/// # Arguments
316///
317/// * `archive_path` - Path to archive file
318/// * `config` - Security configuration (quota limits apply)
319///
320/// # Errors
321///
322/// Returns error if:
323/// - Archive file cannot be opened
324/// - Archive format is unsupported or corrupted
325/// - Quota limits exceeded (file count, total size, single file size)
326/// - Declared compressed sizes exceed the archive length
327///
328/// # Examples
329///
330/// ```no_run
331/// use exarch_core::SecurityConfig;
332/// use exarch_core::list_archive;
333///
334/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
335/// let config = SecurityConfig::default();
336/// let manifest = list_archive("archive.tar.gz", &config)?;
337///
338/// println!("Archive contains {} files", manifest.total_entries());
339/// for entry in manifest.entries() {
340///     println!("{}: {} bytes", entry.path.display(), entry.size());
341/// }
342/// # Ok(())
343/// # }
344/// ```
345pub fn list_archive<P: AsRef<Path>>(
346    archive_path: P,
347    config: &SecurityConfig,
348) -> Result<ArchiveManifest> {
349    crate::inspection::list_archive(archive_path, config)
350}
351
352/// Verifies archive security without extracting.
353///
354/// Performs metadata-only validation:
355/// - Security checks (path traversal, zip bombs, CVEs)
356/// - Policy checks (file types, permissions)
357///
358/// Payload integrity (checksums, decode-to-end) is not verified: the report's
359/// `integrity_status` is
360/// [`IntegrityStatus::Skipped`](crate::IntegrityStatus::Skipped);
361/// use [`VerifyRequest`](crate::VerifyRequest) with `VerificationOptions` to
362/// request it.
363///
364/// # Arguments
365///
366/// * `archive_path` - Path to archive file
367/// * `config` - Security configuration for validation
368///
369/// # Errors
370///
371/// Returns error if:
372/// - Archive file cannot be opened
373/// - Archive is severely corrupted (cannot read structure)
374/// - Declared compressed sizes exceed the archive length
375/// - An entry name is a path traversal (`..` component, or an absolute path
376///   unless `allowed.absolute_paths` is set): the listing step rejects it with
377///   [`ArchiveError::PathTraversal`] before a report exists
378///
379/// Other security violations are reported in `VerificationReport::issues`
380/// instead: disallowed links, link targets that escape the destination,
381/// quota and compression-ratio violations, NUL bytes, banned components and
382/// unsafe permissions.
383///
384/// # Examples
385///
386/// ```no_run
387/// use exarch_core::SecurityConfig;
388/// use exarch_core::VerificationStatus;
389/// use exarch_core::verify_archive;
390///
391/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
392/// let config = SecurityConfig::default();
393/// let report = verify_archive("archive.tar.gz", &config)?;
394///
395/// if report.status() == VerificationStatus::Pass {
396///     println!("Archive is safe to extract");
397/// } else {
398///     eprintln!("Security issues found:");
399///     for issue in report.issues() {
400///         eprintln!("  [{}] {}", issue.severity(), issue.message());
401///     }
402/// }
403/// # Ok(())
404/// # }
405/// ```
406pub fn verify_archive<P: AsRef<Path>>(
407    archive_path: P,
408    config: &SecurityConfig,
409) -> Result<VerificationReport> {
410    crate::inspection::verify_archive(archive_path, config)
411}
412
413/// [`extract_to_sink_with_progress`], with a ZIP archive's census output kept
414/// within `reuse` when the sink is one that shares its memory limit.
415pub(crate) fn extract_to_sink_reusing<S: EntrySink>(
416    reader: ArchiveReader<'_>,
417    sink: &mut S,
418    config: &SecurityConfig,
419    options: SinkOptions,
420    progress: &mut dyn ProgressCallback,
421    reuse: Option<SinkReuse>,
422) -> Result<ExtractionReport> {
423    match reader.into_source() {
424        Source::Tar { stream, codec } => {
425            let archive = tar_archive(stream, codec, config)?;
426            let mut target = SinkTarget::new(sink, config);
427            archive.extract_into(&mut target, config, options, progress)
428        }
429        Source::Seekable {
430            reader,
431            format: SeekableFormat::Zip,
432        } => {
433            let mut archive = match reuse {
434                Some(reuse) => ZipArchive::for_sink(reader, config, &reuse)?,
435                None => ZipArchive::for_extraction(reader, config, options.decode_reuse)?,
436            };
437            archive.check_structure(config)?.extract_with(
438                |config| Ok(SinkTarget::new(sink, config)),
439                options,
440                progress,
441            )
442        }
443        Source::Seekable {
444            reader,
445            format: SeekableFormat::SevenZ,
446        } => {
447            let mut archive = SevenZArchive::new(reader, config)?;
448            archive.admit(config)?.extract_with(
449                |config| Ok(SinkTarget::new(sink, config)),
450                options,
451                progress,
452            )
453        }
454    }
455}
456
457/// Rejects creation for ZIP-family extensions that aren't plain `.zip`.
458///
459/// They're all ZIP underneath but add extra requirements - signing
460/// (apk/aab/ipa/appx/msix), checksum manifests (whl), ordering and
461/// stored-compression rules (epub), descriptor files (war/ear/vsix/nbm) - which
462/// exarch doesn't produce. Silently emitting a bare ZIP with one of these
463/// extensions would be misleading, so creation errors instead; a caller who
464/// needs it states [`CreatableFormat::Zip`] on the [`OutputFile`].
465///
466/// Returns `Ok(())` for anything else - `.zip`, tar variants, unknown
467/// extensions (those get caught later by `detect_format`).
468fn reject_zip_family_creation(output: &Path) -> Result<()> {
469    let Some(ext) = output.extension().and_then(|e| e.to_str()) else {
470        return Ok(());
471    };
472    if is_zip_family_alias(ext) {
473        let ext_lower = ext.to_ascii_lowercase();
474        return Err(ArchiveError::unclassified(format!(
475            "creation for .{ext_lower} isn't supported: the format is ZIP-based but \
476             requires extra structure (signing, manifests, ordering) that exarch \
477             doesn't produce. Use .zip, or state the format with \
478             OutputFile::with_format(exarch_core::formats::detect::CreatableFormat::Zip) \
479             to override."
480        )));
481    }
482    Ok(())
483}
484
485/// Determines the archive format of `output`.
486///
487/// Extension-only detection; magic-byte detection is intentionally excluded so
488/// that a pre-existing output file with stale bytes cannot override the
489/// caller's intended format.
490pub(crate) fn resolve_output_format(output: &OutputFile) -> Result<CreatableFormat> {
491    match output.format() {
492        OutputFormat::Explicit(format) => Ok(format),
493        OutputFormat::FromExtension => {
494            reject_zip_family_creation(output.path())?;
495            CreatableFormat::try_from(detect_format_from_extension(output.path())?)
496        }
497    }
498}
499
500#[cfg(test)]
501#[allow(clippy::unwrap_used)]
502mod tests {
503    use super::*;
504    use crate::NoopProgress;
505    use crate::raw_zip::RawEntry;
506    use crate::raw_zip::RawZip;
507    use std::assert_matches;
508    use std::path::PathBuf;
509
510    #[test]
511    fn test_extract_archive_nonexistent_file() {
512        let config = SecurityConfig::default();
513        let result = extract_archive(
514            PathBuf::from("nonexistent_test.tar"),
515            PathBuf::from("/tmp/test"),
516            &config,
517        );
518        // Should fail because file doesn't exist
519        assert!(result.is_err());
520    }
521
522    #[test]
523    fn test_determine_creation_format_tar() {
524        let path = PathBuf::from("archive.tar");
525        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
526        assert_eq!(format, CreatableFormat::Tar);
527    }
528
529    #[test]
530    fn test_determine_creation_format_tar_gz() {
531        let path = PathBuf::from("archive.tar.gz");
532        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
533        assert_eq!(format, CreatableFormat::TarGz);
534
535        let path2 = PathBuf::from("archive.tgz");
536        let format2 = resolve_output_format(&OutputFile::replace(&path2)).unwrap();
537        assert_eq!(format2, CreatableFormat::TarGz);
538    }
539
540    #[test]
541    fn test_determine_creation_format_tar_bz2() {
542        let path = PathBuf::from("archive.tar.bz2");
543        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
544        assert_eq!(format, CreatableFormat::TarBz2);
545    }
546
547    #[test]
548    fn test_determine_creation_format_tar_xz() {
549        let path = PathBuf::from("archive.tar.xz");
550        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
551        assert_eq!(format, CreatableFormat::TarXz);
552    }
553
554    #[test]
555    fn test_determine_creation_format_tar_zst() {
556        let path = PathBuf::from("archive.tar.zst");
557        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
558        assert_eq!(format, CreatableFormat::TarZst);
559    }
560
561    #[test]
562    fn test_determine_creation_format_zip() {
563        let path = PathBuf::from("archive.zip");
564        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
565        assert_eq!(format, CreatableFormat::Zip);
566    }
567
568    #[test]
569    fn test_determine_creation_format_explicit() {
570        let path = PathBuf::from("archive.xyz");
571        let output = OutputFile::replace(&path).with_format(CreatableFormat::TarGz);
572        let format = resolve_output_format(&output).unwrap();
573        assert_eq!(format, CreatableFormat::TarGz);
574    }
575
576    #[test]
577    fn test_determine_creation_format_unknown() {
578        let path = PathBuf::from("archive.rar");
579        let result = resolve_output_format(&OutputFile::replace(&path));
580        assert!(result.is_err());
581    }
582
583    #[test]
584    fn test_determine_creation_format_ignores_stale_magic_bytes() {
585        // Regression for C1: a pre-existing output file whose bytes match a
586        // different format must not override the extension-derived format.
587        let dir = tempfile::tempdir().unwrap();
588        let path = dir.path().join("backup.zip");
589        // Write gzip magic bytes into a file named .zip
590        std::fs::write(&path, b"\x1f\x8b\x08\x00\x00\x00\x00\x00").unwrap();
591
592        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
593        assert_eq!(
594            format,
595            CreatableFormat::Zip,
596            "creation format must follow extension, not stale on-disk magic bytes"
597        );
598    }
599
600    #[test]
601    fn test_extract_archive_7z_not_implemented() {
602        let dest = tempfile::TempDir::new().unwrap();
603        let path = PathBuf::from("test.7z");
604
605        let result = extract_archive(&path, dest.path(), &SecurityConfig::default());
606
607        assert!(result.is_err());
608    }
609
610    #[test]
611    fn test_create_archive_zip_family_not_supported() {
612        // Mirrors test_create_archive_7z_not_supported. Spot-checks a couple
613        // of extensions rather than every one - the integration test
614        // covers the full list.
615        let dest = tempfile::TempDir::new().unwrap();
616        for ext in ["apk", "whl", "EPUB"] {
617            let archive_path = dest.path().join(format!("output.{ext}"));
618            let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
619            assert_matches!(
620                result,
621                Err(ArchiveError::InvalidArchive(_)),
622                ".{ext} should be rejected, got {result:?}",
623            );
624        }
625    }
626
627    #[test]
628    fn test_create_archive_zip_family_override_bypasses_guard() {
629        // An explicit OutputFile format is the escape hatch -
630        // skips the ZIP-family guard. Caller takes responsibility for the
631        // resulting file not being spec-valid.
632        let dest = tempfile::TempDir::new().unwrap();
633        let src = dest.path().join("source.txt");
634        std::fs::write(&src, b"hello").unwrap();
635        let archive_path = dest.path().join("output.apk");
636        let result = CreateRequest::new(&CreationConfig::default()).create(
637            &OutputFile::replace(&archive_path).with_format(CreatableFormat::Zip),
638            &[&src],
639        );
640        assert!(
641            result.is_ok(),
642            "explicit format override should bypass the guard, got {result:?}",
643        );
644    }
645
646    #[test]
647    fn test_create_archive_7z_not_supported() {
648        let dest = tempfile::TempDir::new().unwrap();
649        let archive_path = dest.path().join("output.7z");
650
651        let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
652
653        assert!(result.is_err());
654        assert_matches!(
655            result.unwrap_err(),
656            ArchiveError::InvalidConfiguration { .. }
657        );
658    }
659
660    #[test]
661    fn test_extract_archive_with_options_and_progress_non_atomic_delegates_to_normal() {
662        let dest = tempfile::TempDir::new().unwrap();
663        let options = ExtractionOptions {
664            atomic: false,
665            skip_duplicates: true,
666            ..ExtractionOptions::default()
667        };
668        let result = ExtractRequest::new(&SecurityConfig::default())
669            .with_options(options)
670            .with_progress(&mut NoopProgress)
671            .extract(PathBuf::from("nonexistent.tar.gz"), dest.path());
672        assert!(result.is_err());
673    }
674
675    #[test]
676    fn test_extract_archive_with_options_delegates() {
677        let dest = tempfile::TempDir::new().unwrap();
678        let options = ExtractionOptions {
679            atomic: false,
680            skip_duplicates: true,
681            ..ExtractionOptions::default()
682        };
683        let result = ExtractRequest::new(&SecurityConfig::default())
684            .with_options(options)
685            .extract(PathBuf::from("nonexistent.tar.gz"), dest.path());
686        assert!(result.is_err());
687    }
688
689    #[test]
690    fn test_extract_atomic_success() {
691        use crate::create_archive;
692        use crate::creation::CreationConfig;
693
694        // Create a valid tar.gz to extract
695        let archive_dir = tempfile::TempDir::new().unwrap();
696        let archive_path = archive_dir.path().join("test.tar.gz");
697
698        // Create a simple archive with one file
699        let src_dir = tempfile::TempDir::new().unwrap();
700        std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
701        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
702
703        let parent = tempfile::TempDir::new().unwrap();
704        let output_dir = parent.path().join("extracted");
705
706        let options = ExtractionOptions {
707            atomic: true,
708            skip_duplicates: true,
709            ..ExtractionOptions::default()
710        };
711        let result = ExtractRequest::new(&SecurityConfig::default())
712            .with_options(options)
713            .extract(&archive_path, &output_dir);
714
715        assert!(result.is_ok());
716        assert!(output_dir.exists());
717        // No temp dir remnants
718        let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
719        assert_eq!(
720            temp_entries.len(),
721            1,
722            "Expected only the output dir, found temp remnants"
723        );
724    }
725
726    #[test]
727    fn test_extract_atomic_failure_cleans_up() {
728        let parent = tempfile::TempDir::new().unwrap();
729        let output_dir = parent.path().join("extracted");
730
731        let options = ExtractionOptions {
732            atomic: true,
733            skip_duplicates: true,
734            ..ExtractionOptions::default()
735        };
736        let result = ExtractRequest::new(&SecurityConfig::default())
737            .with_options(options)
738            .extract(PathBuf::from("nonexistent_archive.tar.gz"), &output_dir);
739
740        assert!(result.is_err());
741        // Output dir must not exist
742        assert!(!output_dir.exists());
743        // No temp dir remnants in parent
744        let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
745        assert!(
746            temp_entries.is_empty(),
747            "Temp dir not cleaned up after failure"
748        );
749    }
750
751    #[test]
752    fn test_extract_atomic_output_already_exists_fails() {
753        use crate::create_archive;
754        use crate::creation::CreationConfig;
755
756        let parent = tempfile::TempDir::new().unwrap();
757        let output_dir = parent.path().join("extracted");
758        std::fs::create_dir_all(&output_dir).unwrap();
759        // Create a file in output_dir so it's non-empty (rename over non-empty
760        // dir fails on most OSes)
761        std::fs::write(output_dir.join("existing.txt"), b"old content").unwrap();
762
763        let archive_dir = tempfile::TempDir::new().unwrap();
764        let archive_path = archive_dir.path().join("test.tar.gz");
765        let src_dir = tempfile::TempDir::new().unwrap();
766        std::fs::write(src_dir.path().join("new.txt"), b"new content").unwrap();
767        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
768
769        let options = ExtractionOptions {
770            atomic: true,
771            skip_duplicates: true,
772            ..ExtractionOptions::default()
773        };
774        let result = ExtractRequest::new(&SecurityConfig::default())
775            .with_options(options)
776            .extract(&archive_path, &output_dir);
777
778        // Should fail with OutputExists or Io (platform dependent rename
779        // semantics)
780        assert!(result.is_err());
781        // Output dir must still have old content (not corrupted)
782        assert!(output_dir.join("existing.txt").exists());
783    }
784
785    // Regression test for issue #170: progress callback silently dropped
786    #[test]
787    fn test_progress_callback_invoked_during_extraction() {
788        use crate::ProgressCallback;
789        use std::path::Path;
790
791        struct TrackingProgress {
792            started: usize,
793            completed: usize,
794            finished: bool,
795        }
796
797        impl ProgressCallback for TrackingProgress {
798            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
799                self.started += 1;
800            }
801
802            fn on_bytes_written(&mut self, _bytes: u64) {}
803
804            fn on_entry_complete(&mut self, _path: &Path) {
805                self.completed += 1;
806            }
807
808            fn on_complete(&mut self) {
809                self.finished = true;
810            }
811        }
812
813        let archive_dir = tempfile::TempDir::new().unwrap();
814        let archive_path = archive_dir.path().join("test.tar.gz");
815        let src_dir = tempfile::TempDir::new().unwrap();
816        std::fs::write(src_dir.path().join("a.txt"), b"hello").unwrap();
817        std::fs::write(src_dir.path().join("b.txt"), b"world").unwrap();
818        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
819
820        let dest = tempfile::TempDir::new().unwrap();
821        let mut progress = TrackingProgress {
822            started: 0,
823            completed: 0,
824            finished: false,
825        };
826
827        let report = ExtractRequest::new(&SecurityConfig::default())
828            .with_progress(&mut progress)
829            .extract(&archive_path, dest.path())
830            .unwrap();
831
832        assert!(report.files_extracted >= 2, "expected at least 2 files");
833        assert!(progress.started >= 2, "on_entry_start not called");
834        assert!(progress.completed >= 2, "on_entry_complete not called");
835        assert!(progress.finished, "on_complete not called");
836    }
837
838    // Regression test for issue #170: ZIP format
839    #[test]
840    fn test_progress_callback_invoked_during_zip_extraction() {
841        use crate::ProgressCallback;
842        use std::path::Path;
843
844        struct TrackingProgress {
845            started: usize,
846            completed: usize,
847            finished: bool,
848        }
849
850        impl ProgressCallback for TrackingProgress {
851            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
852                self.started += 1;
853            }
854
855            fn on_bytes_written(&mut self, _bytes: u64) {}
856
857            fn on_entry_complete(&mut self, _path: &Path) {
858                self.completed += 1;
859            }
860
861            fn on_complete(&mut self) {
862                self.finished = true;
863            }
864        }
865
866        let tmp = tempfile::TempDir::new().unwrap();
867        let archive_path = tmp.path().join("test.zip");
868        let src_dir = tempfile::TempDir::new().unwrap();
869        std::fs::write(src_dir.path().join("x.txt"), b"foo").unwrap();
870        std::fs::write(src_dir.path().join("y.txt"), b"bar").unwrap();
871        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
872
873        let dest = tempfile::TempDir::new().unwrap();
874        let mut progress = TrackingProgress {
875            started: 0,
876            completed: 0,
877            finished: false,
878        };
879        let report = ExtractRequest::new(&SecurityConfig::default())
880            .with_progress(&mut progress)
881            .extract(&archive_path, dest.path())
882            .unwrap();
883
884        assert!(report.files_extracted >= 2, "expected at least 2 files");
885        assert!(progress.started >= 2, "on_entry_start not called for ZIP");
886        assert!(
887            progress.completed >= 2,
888            "on_entry_complete not called for ZIP"
889        );
890        assert!(progress.finished, "on_complete not called for ZIP");
891    }
892
893    // Regression test for issue #170: 7z format
894    #[test]
895    fn test_progress_callback_invoked_during_sevenz_extraction() {
896        use crate::ProgressCallback;
897        use std::path::Path;
898
899        struct TrackingProgress {
900            started: usize,
901            completed: usize,
902            finished: bool,
903        }
904
905        impl ProgressCallback for TrackingProgress {
906            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
907                self.started += 1;
908            }
909
910            fn on_bytes_written(&mut self, _bytes: u64) {}
911
912            fn on_entry_complete(&mut self, _path: &Path) {
913                self.completed += 1;
914            }
915
916            fn on_complete(&mut self) {
917                self.finished = true;
918            }
919        }
920
921        let fixture =
922            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/simple.7z");
923
924        let dest = tempfile::TempDir::new().unwrap();
925        let mut progress = TrackingProgress {
926            started: 0,
927            completed: 0,
928            finished: false,
929        };
930        let report = ExtractRequest::new(&SecurityConfig::default())
931            .with_progress(&mut progress)
932            .extract(&fixture, dest.path())
933            .unwrap();
934
935        assert!(
936            report.files_extracted >= 1,
937            "expected at least 1 file from simple.7z"
938        );
939        assert!(progress.started >= 1, "on_entry_start not called for 7z");
940        assert!(
941            progress.completed >= 1,
942            "on_entry_complete not called for 7z"
943        );
944        assert!(progress.finished, "on_complete not called for 7z");
945    }
946
947    // Regression test for issue #304: on_bytes_written must be called with > 0
948    // bytes when extracting non-empty files from TAR archives.
949    #[test]
950    fn test_on_bytes_written_called_for_tar() {
951        use crate::ProgressCallback;
952        use std::path::Path;
953
954        struct ByteTracker {
955            total: u64,
956        }
957
958        impl ProgressCallback for ByteTracker {
959            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}
960
961            fn on_bytes_written(&mut self, bytes: u64) {
962                self.total += bytes;
963            }
964
965            fn on_entry_complete(&mut self, _path: &Path) {}
966
967            fn on_complete(&mut self) {}
968        }
969
970        let archive_dir = tempfile::TempDir::new().unwrap();
971        let archive_path = archive_dir.path().join("test.tar.gz");
972        let src_dir = tempfile::TempDir::new().unwrap();
973        std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
974        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
975
976        let dest = tempfile::TempDir::new().unwrap();
977        let mut progress = ByteTracker { total: 0 };
978        let report = ExtractRequest::new(&SecurityConfig::default())
979            .with_progress(&mut progress)
980            .extract(&archive_path, dest.path())
981            .unwrap();
982
983        assert!(
984            report.bytes_written > 0,
985            "report.bytes_written must be > 0, got {}",
986            report.bytes_written
987        );
988        assert!(
989            progress.total > 0,
990            "on_bytes_written must be called with > 0 bytes for TAR, got {}",
991            progress.total
992        );
993    }
994
995    // Regression test for issue #304: on_bytes_written must be called with > 0
996    // bytes when extracting non-empty files from ZIP archives.
997    #[test]
998    fn test_on_bytes_written_called_for_zip() {
999        use crate::ProgressCallback;
1000        use std::path::Path;
1001
1002        struct ByteTracker {
1003            total: u64,
1004        }
1005
1006        impl ProgressCallback for ByteTracker {
1007            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}
1008
1009            fn on_bytes_written(&mut self, bytes: u64) {
1010                self.total += bytes;
1011            }
1012
1013            fn on_entry_complete(&mut self, _path: &Path) {}
1014
1015            fn on_complete(&mut self) {}
1016        }
1017
1018        let tmp = tempfile::TempDir::new().unwrap();
1019        let archive_path = tmp.path().join("test.zip");
1020        let src_dir = tempfile::TempDir::new().unwrap();
1021        std::fs::write(src_dir.path().join("data.txt"), b"hello world").unwrap();
1022        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1023
1024        let dest = tempfile::TempDir::new().unwrap();
1025        let mut progress = ByteTracker { total: 0 };
1026        let report = ExtractRequest::new(&SecurityConfig::default())
1027            .with_progress(&mut progress)
1028            .extract(&archive_path, dest.path())
1029            .unwrap();
1030
1031        assert!(
1032            report.bytes_written > 0,
1033            "report.bytes_written must be > 0, got {}",
1034            report.bytes_written
1035        );
1036        assert!(
1037            progress.total > 0,
1038            "on_bytes_written must be called with > 0 bytes for ZIP, got {}",
1039            progress.total
1040        );
1041    }
1042
1043    // Regression test for issue #304: on_bytes_written must be called with > 0
1044    // bytes when extracting non-empty files from 7z archives.
1045    #[test]
1046    fn test_on_bytes_written_called_for_sevenz() {
1047        use crate::ProgressCallback;
1048        use std::path::Path;
1049
1050        struct ByteTracker {
1051            total: u64,
1052        }
1053
1054        impl ProgressCallback for ByteTracker {
1055            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}
1056
1057            fn on_bytes_written(&mut self, bytes: u64) {
1058                self.total += bytes;
1059            }
1060
1061            fn on_entry_complete(&mut self, _path: &Path) {}
1062
1063            fn on_complete(&mut self) {}
1064        }
1065
1066        let fixture =
1067            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/simple.7z");
1068
1069        let dest = tempfile::TempDir::new().unwrap();
1070        let mut progress = ByteTracker { total: 0 };
1071        let report = ExtractRequest::new(&SecurityConfig::default())
1072            .with_progress(&mut progress)
1073            .extract(&fixture, dest.path())
1074            .unwrap();
1075
1076        assert!(
1077            report.bytes_written > 0,
1078            "report.bytes_written must be > 0, got {}",
1079            report.bytes_written
1080        );
1081        assert!(
1082            progress.total > 0,
1083            "on_bytes_written must be called with > 0 bytes for 7z, got {}",
1084            progress.total
1085        );
1086    }
1087
1088    // Regression test for BYTES-1: on_bytes_written must be called when TAR
1089    // hardlinks are extracted (copy path in create_hardlink).
1090    #[test]
1091    fn test_tar_hardlink_calls_on_bytes_written() {
1092        use crate::ProgressCallback;
1093        use crate::formats::TarArchive;
1094        use crate::formats::traits::ArchiveFormat;
1095        use std::io::Cursor;
1096        use std::path::Path;
1097
1098        struct ByteTracker {
1099            total: u64,
1100        }
1101
1102        impl ProgressCallback for ByteTracker {
1103            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}
1104
1105            fn on_bytes_written(&mut self, bytes: u64) {
1106                self.total += bytes;
1107            }
1108
1109            fn on_entry_complete(&mut self, _path: &Path) {}
1110
1111            fn on_complete(&mut self) {}
1112        }
1113
1114        // Build a TAR with one regular file and one hardlink pointing to it.
1115        let content = b"hello hardlink";
1116        let tar_data = {
1117            let mut builder = tar::Builder::new(Vec::new());
1118
1119            let mut header = tar::Header::new_gnu();
1120            header.set_size(content.len() as u64);
1121            header.set_mode(0o644);
1122            header.set_entry_type(tar::EntryType::Regular);
1123            header.set_cksum();
1124            builder
1125                .append_data(&mut header, "original.txt", content.as_ref())
1126                .unwrap();
1127
1128            let mut hdr = tar::Header::new_gnu();
1129            hdr.set_size(0);
1130            hdr.set_mode(0o644);
1131            hdr.set_entry_type(tar::EntryType::Link);
1132            hdr.set_link_name("original.txt").unwrap();
1133            hdr.set_cksum();
1134            builder
1135                .append_data(&mut hdr, "link.txt", std::io::empty())
1136                .unwrap();
1137
1138            builder.into_inner().unwrap()
1139        };
1140
1141        let temp = tempfile::TempDir::new().unwrap();
1142        let mut config = SecurityConfig::default();
1143        config.allowed.hardlinks = crate::Admit::Allow;
1144
1145        let archive = TarArchive::new(Cursor::new(tar_data), &config);
1146        let mut progress = ByteTracker { total: 0 };
1147        let report = archive
1148            .extract(temp.path(), &ExtractionOptions::default(), &mut progress)
1149            .unwrap();
1150
1151        // The hardlink copies the file content — bytes should be reported
1152        // twice.
1153        let expected = (content.len() as u64) * 2;
1154        assert_eq!(
1155            progress.total, expected,
1156            "on_bytes_written must report bytes for both original and hardlink copy, \
1157             got {} (report.bytes_written={})",
1158            progress.total, report.bytes_written
1159        );
1160    }
1161
1162    // Regression test for issue #305: on_entry_complete must be called even
1163    // when TAR extraction fails mid-entry due to a path traversal violation.
1164    #[test]
1165    fn test_tar_on_entry_complete_called_on_path_traversal_error() {
1166        use crate::ProgressCallback;
1167        use crate::formats::TarArchive;
1168        use crate::formats::traits::ArchiveFormat;
1169        use std::io::Cursor;
1170        use std::path::Path;
1171
1172        struct SymmetryTracker {
1173            started: usize,
1174            completed: usize,
1175        }
1176
1177        impl ProgressCallback for SymmetryTracker {
1178            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
1179                self.started += 1;
1180            }
1181
1182            fn on_bytes_written(&mut self, _bytes: u64) {}
1183
1184            fn on_entry_complete(&mut self, _path: &Path) {
1185                self.completed += 1;
1186            }
1187
1188            fn on_complete(&mut self) {}
1189        }
1190
1191        // Build a minimal TAR with a path-traversal entry at raw bytes level
1192        // (bypassing the `tar` crate's sanitization).
1193        let tar_data = make_raw_tar_single(b"../../etc/passwd", b"evil");
1194
1195        let temp = tempfile::TempDir::new().unwrap();
1196        let archive = TarArchive::new(Cursor::new(tar_data), &SecurityConfig::default());
1197        let mut progress = SymmetryTracker {
1198            started: 0,
1199            completed: 0,
1200        };
1201        let result = archive.extract(temp.path(), &ExtractionOptions::default(), &mut progress);
1202
1203        assert!(result.is_err(), "traversal entry must be rejected");
1204        assert_eq!(
1205            progress.started, progress.completed,
1206            "on_entry_complete must be called for every on_entry_start, \
1207             even when extraction fails: started={}, completed={}",
1208            progress.started, progress.completed
1209        );
1210    }
1211
1212    // Regression test for issue #305: on_entry_complete must be called even
1213    // when ZIP extraction fails mid-entry due to a path traversal violation.
1214    #[test]
1215    fn test_zip_on_entry_complete_called_on_path_traversal_error() {
1216        use crate::ProgressCallback;
1217        use crate::formats::ZipArchive;
1218        use crate::formats::traits::ArchiveFormat;
1219        use std::io::Cursor;
1220        use std::path::Path;
1221
1222        struct SymmetryTracker {
1223            started: usize,
1224            completed: usize,
1225        }
1226
1227        impl ProgressCallback for SymmetryTracker {
1228            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
1229                self.started += 1;
1230            }
1231
1232            fn on_bytes_written(&mut self, _bytes: u64) {}
1233
1234            fn on_entry_complete(&mut self, _path: &Path) {
1235                self.completed += 1;
1236            }
1237
1238            fn on_complete(&mut self) {}
1239        }
1240
1241        // Build a ZIP with a traversal path using zip::ZipWriter.
1242        let zip_data = make_zip_with_traversal(b"../../etc/passwd", b"evil");
1243
1244        let temp = tempfile::TempDir::new().unwrap();
1245        let archive = ZipArchive::new(Cursor::new(zip_data), &SecurityConfig::default()).unwrap();
1246        let mut progress = SymmetryTracker {
1247            started: 0,
1248            completed: 0,
1249        };
1250        let result = archive.extract(temp.path(), &ExtractionOptions::default(), &mut progress);
1251
1252        assert!(result.is_err(), "traversal entry must be rejected");
1253        assert_eq!(
1254            progress.started, progress.completed,
1255            "on_entry_complete must be called for every on_entry_start in ZIP, \
1256             even when extraction fails: started={}, completed={}",
1257            progress.started, progress.completed
1258        );
1259    }
1260
1261    // Builds a single-entry POSIX ustar TAR with an arbitrary raw path,
1262    // bypassing the `tar` crate's path sanitization.
1263    fn make_raw_tar_single(path: &[u8], data: &[u8]) -> Vec<u8> {
1264        let mut out = Vec::new();
1265        let mut header = [0u8; 512];
1266
1267        let path_len = path.len().min(100);
1268        header[..path_len].copy_from_slice(&path[..path_len]);
1269        header[100..108].copy_from_slice(b"0000644\0");
1270        header[108..116].copy_from_slice(b"0000000\0");
1271        header[116..124].copy_from_slice(b"0000000\0");
1272        let size_str = format!("{:011o}\0", data.len());
1273        header[124..136].copy_from_slice(size_str.as_bytes());
1274        header[136..148].copy_from_slice(b"00000000000\0");
1275        header[156] = b'0';
1276        header[257..263].copy_from_slice(b"ustar ");
1277        header[263..265].copy_from_slice(b" \0");
1278        header[148..156].copy_from_slice(b"        ");
1279        let checksum: u32 = header.iter().map(|&b| u32::from(b)).sum();
1280        let ck_str = format!("{checksum:06o}\0 ");
1281        header[148..156].copy_from_slice(ck_str.as_bytes());
1282
1283        out.extend_from_slice(&header);
1284        out.extend_from_slice(data);
1285        let rem = data.len() % 512;
1286        if rem != 0 {
1287            out.extend(std::iter::repeat_n(0u8, 512 - rem));
1288        }
1289        out.extend(std::iter::repeat_n(0u8, 1024));
1290        out
1291    }
1292
1293    // Builds a single-entry ZIP whose name is written verbatim, so a traversal
1294    // path survives into the headers.
1295    fn make_zip_with_traversal(path: &[u8], data: &[u8]) -> Vec<u8> {
1296        let entry = RawEntry {
1297            name: path.to_vec(),
1298            date: 0,
1299            ..RawEntry::stored("", data)
1300        };
1301        RawZip::new(vec![entry]).build().bytes
1302    }
1303}