Skip to main content

shaul_core/
archive.rs

1use std::fs::{File, OpenOptions};
2use std::io::{Read, Write};
3use std::path::{Component, Path, PathBuf};
4use std::sync::Arc;
5
6use uuid::Uuid;
7
8use crate::error::{Error, Result};
9use crate::path::archive_stem;
10
11const MAX_ARCHIVE_ENTRIES: u64 = 100_000;
12const MAX_EXTRACTED_BYTES: u64 = 100 * 1024 * 1024 * 1024;
13
14/// Archive formats recognized by [`detect_archive`] and handled by
15/// [`extract_archive`].
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum ArchiveKind {
19    /// ZIP archive.
20    Zip,
21    /// Uncompressed tar archive.
22    Tar,
23    /// Gzip-compressed tar archive.
24    TarGz,
25    /// Zstandard-compressed tar archive.
26    TarZst,
27    /// Single gzip-compressed file.
28    Gzip,
29    /// Single zstd-compressed file.
30    Zstd,
31}
32
33impl ArchiveKind {
34    /// Returns `true` for formats that wrap one file rather than a directory
35    /// tree.
36    pub fn is_single_file(self) -> bool {
37        matches!(self, Self::Gzip | Self::Zstd)
38    }
39}
40
41/// Summary of an extraction.
42#[derive(Clone, Debug)]
43pub struct ExtractReport {
44    /// Path the archive contents were written to. Custom extractors must return
45    /// a path under [`ExtractorRequest::extract_root`].
46    pub target: PathBuf,
47    /// Number of file entries extracted.
48    pub files_extracted: u64,
49    /// Non-fatal issues, such as skipped symlinks.
50    pub warnings: Vec<String>,
51}
52
53/// Read-only inputs supplied to an [`ArchiveExtractor`].
54#[non_exhaustive]
55pub struct ExtractorRequest<'a> {
56    /// Archive file to read.
57    pub path: &'a Path,
58    /// Directory the extractor may write into. Writes outside this directory
59    /// are rejected by the registry after extraction, and are a contract
60    /// violation for the implementation.
61    pub extract_root: &'a Path,
62    /// Whether an existing extraction target may be replaced.
63    pub overwrite: bool,
64}
65
66impl<'a> ExtractorRequest<'a> {
67    /// Creates a request for `path` rooted at `extract_root`.
68    pub fn new(path: &'a Path, extract_root: &'a Path, overwrite: bool) -> Self {
69        Self {
70            path,
71            extract_root,
72            overwrite,
73        }
74    }
75}
76
77/// One archive format implementation used by [`ExtractorRegistry`].
78///
79/// Extractors run on a blocking worker. Implementations must keep every write
80/// under [`ExtractorRequest::extract_root`], reject unsafe entry paths, and
81/// should extract into a temporary directory before renaming the final target
82/// into place.
83pub trait ArchiveExtractor: Send + Sync {
84    /// Stable name used in diagnostics.
85    fn name(&self) -> &'static str;
86
87    /// Returns `true` when this extractor handles `path`.
88    ///
89    /// The registry calls this in order and the first match owns the file.
90    /// Implementations should be cheap and free of side effects; return
91    /// `Ok(false)` for unsupported files and reserve `Err` for real I/O or
92    /// detection failures.
93    fn supports(&self, path: &Path) -> Result<bool>;
94
95    /// Extracts the archive described by `request`.
96    fn extract(&self, request: &ExtractorRequest<'_>) -> Result<ExtractReport>;
97}
98
99/// Extractor for the archive formats built into shaul: zip, tar, tar.gz,
100/// tar.zst, gzip and zstd.
101pub struct BuiltinExtractor;
102
103impl ArchiveExtractor for BuiltinExtractor {
104    fn name(&self) -> &'static str {
105        "builtin"
106    }
107
108    fn supports(&self, path: &Path) -> Result<bool> {
109        Ok(detect_archive(path)?.is_some())
110    }
111
112    fn extract(&self, request: &ExtractorRequest<'_>) -> Result<ExtractReport> {
113        let kind = detect_archive(request.path)?.ok_or_else(|| {
114            Error::Extraction(format!("unsupported archive: {}", request.path.display()))
115        })?;
116        extract_archive(request.path, kind, request.extract_root, request.overwrite)
117    }
118}
119
120/// Ordered list of archive extractors.
121///
122/// [`ExtractorRegistry::default`] contains [`BuiltinExtractor`]. Use
123/// [`ExtractorRegistry::with`] to try a custom extractor before the built-ins,
124/// or [`ExtractorRegistry::new`] for an explicit list.
125#[derive(Clone)]
126pub struct ExtractorRegistry {
127    extractors: Vec<Arc<dyn ArchiveExtractor>>,
128}
129
130impl Default for ExtractorRegistry {
131    fn default() -> Self {
132        Self {
133            extractors: vec![Arc::new(BuiltinExtractor)],
134        }
135    }
136}
137
138impl ExtractorRegistry {
139    /// Creates a registry containing exactly `extractors`, in order.
140    pub fn new(extractors: Vec<Arc<dyn ArchiveExtractor>>) -> Self {
141        Self { extractors }
142    }
143
144    /// Prepends `extractor` so it is tried before the existing entries.
145    pub fn with(mut self, extractor: Arc<dyn ArchiveExtractor>) -> Self {
146        self.extractors.insert(0, extractor);
147        self
148    }
149
150    /// Returns `true` when an extractor claims `path`.
151    pub fn supports(&self, path: &Path) -> Result<bool> {
152        for extractor in &self.extractors {
153            if extractor.supports(path)? {
154                return Ok(true);
155            }
156        }
157        Ok(false)
158    }
159
160    /// Extracts `path` with the first matching extractor.
161    ///
162    /// Returns `Ok(None)` when no extractor supports the file. The final target
163    /// reported by the extractor is checked to be inside `extract_root`.
164    pub fn extract(
165        &self,
166        path: &Path,
167        extract_root: &Path,
168        overwrite: bool,
169    ) -> Result<Option<ExtractReport>> {
170        for extractor in &self.extractors {
171            if extractor.supports(path)? {
172                std::fs::create_dir_all(extract_root)?;
173                let request = ExtractorRequest::new(path, extract_root, overwrite);
174                let report = extractor.extract(&request)?;
175                validate_extract_target(extract_root, &report.target)?;
176                return Ok(Some(report));
177            }
178        }
179        Ok(None)
180    }
181}
182
183fn validate_extract_target(extract_root: &Path, target: &Path) -> Result<()> {
184    let root = extract_root.canonicalize()?;
185    let target = target.canonicalize()?;
186    if !target.starts_with(&root) {
187        return Err(Error::Extraction(format!(
188            "extractor wrote outside the extraction root: {}",
189            target.display()
190        )));
191    }
192    Ok(())
193}
194
195/// Detect by magic bytes, using the extension only for legacy tarballs that
196/// lack the `ustar` marker.
197pub fn detect_archive(path: &Path) -> Result<Option<ArchiveKind>> {
198    let mut file = File::open(path)?;
199    let mut prefix = [0u8; 512];
200    let read = file.read(&mut prefix)?;
201    let prefix = &prefix[..read];
202
203    if prefix.starts_with(b"PK\x03\x04")
204        || prefix.starts_with(b"PK\x05\x06")
205        || prefix.starts_with(b"PK\x07\x08")
206    {
207        return Ok(Some(ArchiveKind::Zip));
208    }
209
210    if prefix.starts_with(&[0x1f, 0x8b]) {
211        return Ok(Some(if decompressed_is_tar_gzip(prefix) {
212            ArchiveKind::TarGz
213        } else {
214            ArchiveKind::Gzip
215        }));
216    }
217
218    if prefix.starts_with(&[0x28, 0xb5, 0x2f, 0xfd]) {
219        return Ok(Some(if decompressed_is_tar_zstd(prefix) {
220            ArchiveKind::TarZst
221        } else {
222            ArchiveKind::Zstd
223        }));
224    }
225
226    if is_tar(prefix) {
227        return Ok(Some(ArchiveKind::Tar));
228    }
229
230    let extension = path
231        .extension()
232        .and_then(|value| value.to_str())
233        .unwrap_or_default()
234        .to_ascii_lowercase();
235    if extension == "tar" {
236        return Ok(Some(ArchiveKind::Tar));
237    }
238
239    Ok(None)
240}
241
242fn is_tar(bytes: &[u8]) -> bool {
243    bytes.len() >= 262 && &bytes[257..262] == b"ustar"
244}
245
246fn decompressed_is_tar_gzip(prefix: &[u8]) -> bool {
247    let mut decoder = flate2::read::GzDecoder::new(prefix);
248    let mut decoded = [0u8; 512];
249    let read = decoder.read(&mut decoded).unwrap_or(0);
250    is_tar(&decoded[..read])
251}
252
253fn decompressed_is_tar_zstd(prefix: &[u8]) -> bool {
254    let Ok(mut decoder) = ruzstd::decoding::StreamingDecoder::new(prefix) else {
255        return false;
256    };
257    let mut decoded = [0u8; 512];
258    let read = decoder.read(&mut decoded).unwrap_or(0);
259    is_tar(&decoded[..read])
260}
261
262/// Extract into `extract_root`. Multi-entry archives land under a directory
263/// named after the archive stem; single-file `.gz`/`.zst` archives land at
264/// `<stem>`. Extraction is performed in a temporary directory and renamed
265/// into place only after it succeeds.
266pub fn extract_archive(
267    path: &Path,
268    kind: ArchiveKind,
269    extract_root: &Path,
270    overwrite: bool,
271) -> Result<ExtractReport> {
272    std::fs::create_dir_all(extract_root)?;
273    let stem = archive_stem(path);
274    if kind.is_single_file() {
275        extract_single_file(path, kind, extract_root, &stem, overwrite)
276    } else {
277        extract_directory(path, kind, extract_root, &stem, overwrite)
278    }
279}
280
281fn extract_single_file(
282    path: &Path,
283    kind: ArchiveKind,
284    extract_root: &Path,
285    stem: &str,
286    overwrite: bool,
287) -> Result<ExtractReport> {
288    let target = extract_root.join(stem);
289    prepare_target(&target, overwrite)?;
290
291    let temp_dir = extract_root.join(format!(".shaul-extract-{}", Uuid::new_v4()));
292    std::fs::create_dir_all(&temp_dir)?;
293    let temp_file = temp_dir.join(stem);
294
295    let result = (|| -> Result<()> {
296        let input = File::open(path)?;
297        let mut output = OpenOptions::new()
298            .create(true)
299            .write(true)
300            .truncate(true)
301            .open(&temp_file)?;
302        match kind {
303            ArchiveKind::Gzip => {
304                let decoder = flate2::read::GzDecoder::new(input);
305                let mut limited = decoder.take(MAX_EXTRACTED_BYTES + 1);
306                let copied = std::io::copy(&mut limited, &mut output)?;
307                ensure_extracted_bytes(copied)?;
308            }
309            ArchiveKind::Zstd => {
310                let decoder = ruzstd::decoding::StreamingDecoder::new(input)
311                    .map_err(|error| Error::Extraction(format!("zstd: {error}")))?;
312                let mut limited = decoder.take(MAX_EXTRACTED_BYTES + 1);
313                let copied = std::io::copy(&mut limited, &mut output)?;
314                ensure_extracted_bytes(copied)?;
315            }
316            other => {
317                return Err(Error::Extraction(format!(
318                    "unsupported single-file archive: {other:?}"
319                )));
320            }
321        }
322        output.flush()?;
323        output.sync_all()?;
324        Ok(())
325    })();
326
327    if let Err(error) = result {
328        let _ = std::fs::remove_dir_all(&temp_dir);
329        return Err(error);
330    }
331
332    if target.exists() {
333        remove_existing(&target)?;
334    }
335    std::fs::rename(&temp_file, &target)?;
336    let _ = std::fs::remove_dir_all(&temp_dir);
337    Ok(ExtractReport {
338        target,
339        files_extracted: 1,
340        warnings: Vec::new(),
341    })
342}
343
344fn extract_directory(
345    path: &Path,
346    kind: ArchiveKind,
347    extract_root: &Path,
348    stem: &str,
349    overwrite: bool,
350) -> Result<ExtractReport> {
351    let target = extract_root.join(stem);
352    prepare_target(&target, overwrite)?;
353
354    let temp_dir = extract_root.join(format!(".shaul-extract-{}", Uuid::new_v4()));
355    std::fs::create_dir_all(&temp_dir)?;
356
357    let mut warnings = Vec::new();
358    let result = match kind {
359        ArchiveKind::Zip => extract_zip(path, &temp_dir, &mut warnings),
360        ArchiveKind::Tar | ArchiveKind::TarGz | ArchiveKind::TarZst => {
361            extract_tar(path, kind, &temp_dir, &mut warnings)
362        }
363        other => Err(Error::Extraction(format!(
364            "unsupported archive kind: {other:?}"
365        ))),
366    };
367
368    let files_extracted = match result {
369        Ok(count) => count,
370        Err(error) => {
371            let _ = std::fs::remove_dir_all(&temp_dir);
372            return Err(error);
373        }
374    };
375
376    if target.exists() {
377        remove_existing(&target)?;
378    }
379    std::fs::rename(&temp_dir, &target)?;
380    Ok(ExtractReport {
381        target,
382        files_extracted,
383        warnings,
384    })
385}
386
387fn prepare_target(target: &Path, overwrite: bool) -> Result<()> {
388    if target.exists() && !overwrite {
389        return Err(Error::Extraction(format!(
390            "extraction target already exists: {} (use --force to overwrite)",
391            target.display()
392        )));
393    }
394    Ok(())
395}
396
397fn remove_existing(path: &Path) -> Result<()> {
398    let metadata = std::fs::symlink_metadata(path)?;
399    if metadata.is_dir() {
400        std::fs::remove_dir_all(path)?;
401    } else {
402        std::fs::remove_file(path)?;
403    }
404    Ok(())
405}
406
407fn extract_zip(path: &Path, target: &Path, warnings: &mut Vec<String>) -> Result<u64> {
408    let file = File::open(path)?;
409    let mut archive =
410        zip::ZipArchive::new(file).map_err(|error| Error::Extraction(format!("zip: {error}")))?;
411    ensure_archive_entries(archive.len() as u64)?;
412    let mut files = 0u64;
413    let mut extracted_bytes = 0u64;
414    for index in 0..archive.len() {
415        let mut entry = archive
416            .by_index(index)
417            .map_err(|error| Error::Extraction(format!("zip entry {index}: {error}")))?;
418        let Some(name) = entry.enclosed_name() else {
419            let display = entry
420                .name()
421                .map(|name| name.to_string())
422                .unwrap_or_else(|_| "<invalid>".to_string());
423            return Err(Error::Extraction(format!(
424                "unsafe zip entry path: {display}"
425            )));
426        };
427        if name.as_os_str().is_empty() {
428            continue;
429        }
430        if entry.is_symlink() {
431            warnings.push(format!("skipped symlink entry: {}", name.display()));
432            continue;
433        }
434        let output = target.join(&name);
435        if entry.is_dir() {
436            std::fs::create_dir_all(&output)?;
437            continue;
438        }
439        if !path_is_safe(&name) {
440            return Err(Error::Extraction(format!(
441                "unsafe zip entry path: {}",
442                name.display()
443            )));
444        }
445        if let Some(parent) = output.parent() {
446            std::fs::create_dir_all(parent)?;
447        }
448        let remaining = MAX_EXTRACTED_BYTES.saturating_sub(extracted_bytes);
449        let mut writer = File::create(&output)?;
450        let copied = std::io::copy(&mut (&mut entry).take(remaining + 1), &mut writer)?;
451        ensure_extracted_bytes(extracted_bytes.saturating_add(copied))?;
452        extracted_bytes += copied;
453        files += 1;
454    }
455    Ok(files)
456}
457
458fn extract_tar(
459    path: &Path,
460    kind: ArchiveKind,
461    target: &Path,
462    warnings: &mut Vec<String>,
463) -> Result<u64> {
464    let file = File::open(path)?;
465    let reader: Box<dyn Read> = match kind {
466        ArchiveKind::Tar => Box::new(file),
467        ArchiveKind::TarGz => Box::new(flate2::read::GzDecoder::new(file)),
468        ArchiveKind::TarZst => Box::new(
469            ruzstd::decoding::StreamingDecoder::new(file)
470                .map_err(|error| Error::Extraction(format!("zstd: {error}")))?,
471        ),
472        other => {
473            return Err(Error::Extraction(format!(
474                "unsupported tar kind: {other:?}"
475            )));
476        }
477    };
478    let mut archive = tar::Archive::new(reader);
479    let mut files = 0u64;
480    let mut entries_seen = 0u64;
481    let mut extracted_bytes = 0u64;
482    for entry in archive
483        .entries()
484        .map_err(|error| Error::Extraction(format!("tar: {error}")))?
485    {
486        entries_seen += 1;
487        ensure_archive_entries(entries_seen)?;
488        let mut entry = entry.map_err(|error| Error::Extraction(format!("tar entry: {error}")))?;
489        let entry_type = entry.header().entry_type();
490        if entry_type.is_symlink()
491            || entry_type.is_hard_link()
492            || entry_type.is_block_special()
493            || entry_type.is_character_special()
494            || entry_type.is_fifo()
495        {
496            let path = entry
497                .path()
498                .map(|path| path.display().to_string())
499                .unwrap_or_else(|_| "<invalid>".to_string());
500            warnings.push(format!("skipped special tar entry: {path}"));
501            continue;
502        }
503        let path = entry
504            .path()
505            .map_err(|error| Error::Extraction(format!("tar path: {error}")))?
506            .into_owned();
507        if !path_is_safe(&path) {
508            return Err(Error::Extraction(format!(
509                "unsafe tar entry path: {}",
510                path.display()
511            )));
512        }
513        let output = target.join(&path);
514        if entry_type.is_dir() {
515            std::fs::create_dir_all(&output)?;
516            continue;
517        }
518        if let Some(parent) = output.parent() {
519            std::fs::create_dir_all(parent)?;
520        }
521        let size = entry.header().size().unwrap_or(0);
522        extracted_bytes = extracted_bytes.saturating_add(size);
523        ensure_extracted_bytes(extracted_bytes)?;
524        entry
525            .unpack(&output)
526            .map_err(|error| Error::Extraction(format!("tar unpack: {error}")))?;
527        files += 1;
528    }
529    Ok(files)
530}
531
532fn ensure_archive_entries(entries: u64) -> Result<()> {
533    if entries > MAX_ARCHIVE_ENTRIES {
534        return Err(Error::Extraction(format!(
535            "archive has more than {MAX_ARCHIVE_ENTRIES} entries"
536        )));
537    }
538    Ok(())
539}
540
541fn ensure_extracted_bytes(bytes: u64) -> Result<()> {
542    if bytes > MAX_EXTRACTED_BYTES {
543        return Err(Error::Extraction(format!(
544            "archive expands beyond {MAX_EXTRACTED_BYTES} bytes"
545        )));
546    }
547    Ok(())
548}
549
550fn path_is_safe(path: &Path) -> bool {
551    path.components()
552        .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
553}
554
555#[allow(dead_code)]
556fn _unused_read_write(_: &mut dyn Read, _: &mut dyn Write) {}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use flate2::Compression;
562    use flate2::write::GzEncoder;
563
564    #[test]
565    fn rejects_archives_over_extraction_limits() {
566        assert!(ensure_archive_entries(MAX_ARCHIVE_ENTRIES).is_ok());
567        assert!(ensure_archive_entries(MAX_ARCHIVE_ENTRIES + 1).is_err());
568        assert!(ensure_extracted_bytes(MAX_EXTRACTED_BYTES).is_ok());
569        assert!(ensure_extracted_bytes(MAX_EXTRACTED_BYTES + 1).is_err());
570    }
571
572    #[test]
573    fn extracts_tar_gz() {
574        let dir = tempfile::tempdir().unwrap();
575        let archive_path = dir.path().join("data.tar.gz");
576        let file = File::create(&archive_path).unwrap();
577        let encoder = GzEncoder::new(file, Compression::default());
578        let mut builder = tar::Builder::new(encoder);
579        let mut header = tar::Header::new_gnu();
580        header.set_size(5);
581        header.set_mode(0o644);
582        header.set_cksum();
583        builder
584            .append_data(&mut header, "hello.txt", &b"hello"[..])
585            .unwrap();
586        let encoder = builder.into_inner().unwrap();
587        encoder.finish().unwrap();
588
589        assert_eq!(
590            detect_archive(&archive_path).unwrap(),
591            Some(ArchiveKind::TarGz)
592        );
593        let report = extract_archive(&archive_path, ArchiveKind::TarGz, dir.path(), false).unwrap();
594        assert!(report.target.join("hello.txt").exists());
595        assert_eq!(
596            std::fs::read_to_string(report.target.join("hello.txt")).unwrap(),
597            "hello"
598        );
599    }
600
601    #[test]
602    fn extracts_single_gzip() {
603        let dir = tempfile::tempdir().unwrap();
604        let archive_path = dir.path().join("hello.txt.gz");
605        let mut encoder =
606            GzEncoder::new(File::create(&archive_path).unwrap(), Compression::default());
607        encoder.write_all(b"hello").unwrap();
608        encoder.finish().unwrap();
609
610        assert_eq!(
611            detect_archive(&archive_path).unwrap(),
612            Some(ArchiveKind::Gzip)
613        );
614        let report = extract_archive(&archive_path, ArchiveKind::Gzip, dir.path(), false).unwrap();
615        assert_eq!(std::fs::read_to_string(report.target).unwrap(), "hello");
616    }
617
618    #[test]
619    fn does_not_overwrite_without_permission() {
620        let dir = tempfile::tempdir().unwrap();
621        let archive_path = dir.path().join("data.tar.gz");
622        let file = File::create(&archive_path).unwrap();
623        let encoder = GzEncoder::new(file, Compression::default());
624        let mut builder = tar::Builder::new(encoder);
625        let mut header = tar::Header::new_gnu();
626        header.set_size(1);
627        header.set_mode(0o644);
628        header.set_cksum();
629        builder.append_data(&mut header, "file", &b"x"[..]).unwrap();
630        let encoder = builder.into_inner().unwrap();
631        encoder.finish().unwrap();
632        extract_archive(&archive_path, ArchiveKind::TarGz, dir.path(), false).unwrap();
633        assert!(extract_archive(&archive_path, ArchiveKind::TarGz, dir.path(), false).is_err());
634    }
635
636    #[test]
637    fn extracts_zip() {
638        let dir = tempfile::tempdir().unwrap();
639        let path = dir.path().join("data.zip");
640        {
641            let file = File::create(&path).unwrap();
642            let mut archive = zip::ZipWriter::new(file);
643            let options = zip::write::SimpleFileOptions::default();
644            archive.start_file("hello.txt", options).unwrap();
645            archive.write_all(b"hello").unwrap();
646            archive.finish().unwrap();
647        }
648        assert_eq!(detect_archive(&path).unwrap(), Some(ArchiveKind::Zip));
649        let report = extract_archive(&path, ArchiveKind::Zip, dir.path(), false).unwrap();
650        assert_eq!(
651            std::fs::read_to_string(report.target.join("hello.txt")).unwrap(),
652            "hello"
653        );
654    }
655
656    #[test]
657    fn detects_nothing_for_plain_file() {
658        let dir = tempfile::tempdir().unwrap();
659        let path = dir.path().join("plain.bin");
660        std::fs::write(&path, [0u8; 512]).unwrap();
661        assert_eq!(detect_archive(&path).unwrap(), None);
662    }
663
664    struct DemoExtractor;
665
666    impl ArchiveExtractor for DemoExtractor {
667        fn name(&self) -> &'static str {
668            "demo"
669        }
670
671        fn supports(&self, path: &Path) -> Result<bool> {
672            Ok(path.extension().and_then(|extension| extension.to_str()) == Some("demo"))
673        }
674
675        fn extract(&self, request: &ExtractorRequest<'_>) -> Result<ExtractReport> {
676            let target = request.extract_root.join("demo-out");
677            std::fs::create_dir_all(&target)?;
678            std::fs::write(target.join("hello.txt"), b"demo")?;
679            Ok(ExtractReport {
680                target,
681                files_extracted: 1,
682                warnings: Vec::new(),
683            })
684        }
685    }
686
687    struct OverrideBuiltin;
688
689    impl ArchiveExtractor for OverrideBuiltin {
690        fn name(&self) -> &'static str {
691            "override"
692        }
693
694        fn supports(&self, path: &Path) -> Result<bool> {
695            Ok(path.to_string_lossy().ends_with(".tar.gz"))
696        }
697
698        fn extract(&self, request: &ExtractorRequest<'_>) -> Result<ExtractReport> {
699            let target = request.extract_root.join("override-out");
700            std::fs::create_dir_all(&target)?;
701            std::fs::write(target.join("override.txt"), b"override")?;
702            Ok(ExtractReport {
703                target,
704                files_extracted: 1,
705                warnings: Vec::new(),
706            })
707        }
708    }
709
710    #[test]
711    fn custom_extractor_is_selected_and_runs() {
712        let dir = tempfile::tempdir().unwrap();
713        let path = dir.path().join("sample.demo");
714        std::fs::write(&path, b"demo").unwrap();
715        let registry = ExtractorRegistry::default().with(Arc::new(DemoExtractor));
716
717        assert!(registry.supports(&path).unwrap());
718        let report = registry.extract(&path, dir.path(), false).unwrap().unwrap();
719        assert_eq!(report.files_extracted, 1);
720        assert_eq!(
721            std::fs::read_to_string(report.target.join("hello.txt")).unwrap(),
722            "demo"
723        );
724    }
725
726    #[test]
727    fn custom_extractor_precedes_builtins() {
728        let dir = tempfile::tempdir().unwrap();
729        let path = dir.path().join("sample.tar.gz");
730        std::fs::write(&path, b"not really a tarball").unwrap();
731        let registry = ExtractorRegistry::default().with(Arc::new(OverrideBuiltin));
732
733        let report = registry.extract(&path, dir.path(), false).unwrap().unwrap();
734        assert_eq!(
735            std::fs::read_to_string(report.target.join("override.txt")).unwrap(),
736            "override"
737        );
738    }
739
740    #[test]
741    fn registry_returns_none_when_no_extractor_matches() {
742        let dir = tempfile::tempdir().unwrap();
743        let path = dir.path().join("plain.bin");
744        std::fs::write(&path, b"plain").unwrap();
745        let registry = ExtractorRegistry::new(Vec::new());
746
747        assert!(!registry.supports(&path).unwrap());
748        assert!(
749            registry
750                .extract(&path, dir.path(), false)
751                .unwrap()
752                .is_none()
753        );
754    }
755
756    struct EscapingExtractor;
757
758    impl ArchiveExtractor for EscapingExtractor {
759        fn name(&self) -> &'static str {
760            "escaping"
761        }
762
763        fn supports(&self, _path: &Path) -> Result<bool> {
764            Ok(true)
765        }
766
767        fn extract(&self, request: &ExtractorRequest<'_>) -> Result<ExtractReport> {
768            let target = request.extract_root.parent().unwrap().join("escaped");
769            std::fs::create_dir_all(&target)?;
770            std::fs::write(target.join("outside.txt"), b"outside")?;
771            Ok(ExtractReport {
772                target,
773                files_extracted: 1,
774                warnings: Vec::new(),
775            })
776        }
777    }
778
779    #[test]
780    fn extractor_target_must_stay_under_root() {
781        let dir = tempfile::tempdir().unwrap();
782        let root = dir.path().join("root");
783        std::fs::create_dir_all(&root).unwrap();
784        let path = root.join("input.bin");
785        std::fs::write(&path, b"input").unwrap();
786        let registry = ExtractorRegistry::new(vec![Arc::new(EscapingExtractor)]);
787
788        let error = registry.extract(&path, &root, false).unwrap_err();
789        assert!(matches!(error, Error::Extraction(_)));
790    }
791
792    struct FailingExtractor;
793
794    impl ArchiveExtractor for FailingExtractor {
795        fn name(&self) -> &'static str {
796            "failing"
797        }
798
799        fn supports(&self, _path: &Path) -> Result<bool> {
800            Ok(true)
801        }
802
803        fn extract(&self, _request: &ExtractorRequest<'_>) -> Result<ExtractReport> {
804            Err(Error::Extraction("boom".to_string()))
805        }
806    }
807
808    #[test]
809    fn a_claiming_extractor_failure_does_not_fall_through() {
810        let dir = tempfile::tempdir().unwrap();
811        let path = dir.path().join("sample.tar.gz");
812        std::fs::write(&path, b"not really a tarball").unwrap();
813        let registry = ExtractorRegistry::default().with(Arc::new(FailingExtractor));
814
815        let error = registry.extract(&path, dir.path(), false).unwrap_err();
816        assert!(matches!(error, Error::Extraction(message) if message == "boom"));
817    }
818}