archmeld 1.3.0

Secure, memory-safe, type-safe CLI for multi-format archive extraction, inspection and decompression
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
//! Archive extraction for archmeld-native formats.
//!
//! Provides an [`Extractor`] for formats not handled by
//! `exarch-core`: TAR.LZ4, standalone compression (gz,
//! bz2, xz, lz4, zstd, lzma), and LHA/LZH.
//!
//! ZIP, TAR (gz/bz2/xz/zst), and 7-Zip are delegated to
//! `exarch-core` in the CLI layer (`cli.rs`).
//!
// Archive extraction: indexing, arithmetic, and numeric casts are
// fundamental to archive handling. Safety is ensured by bounds checks.
#![allow(clippy::indexing_slicing)]
#![allow(clippy::arithmetic_side_effects)]
#![allow(clippy::as_conversions)]
#![allow(clippy::cast_possible_truncation)]

use std::io::{self, Cursor, Read};
use std::path::{Component, Path, PathBuf};

use crate::error::{Error, Result};
use crate::format::ArchiveFormat;

/// A single file extracted from an archive.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ExtractedFile {
    /// Relative path within the archive.
    pub path: String,
    /// File contents.
    #[serde(skip)]
    pub data: Vec<u8>,
    /// Size in bytes.
    pub size: u64,
    /// Whether this entry represents a directory.
    pub is_directory: bool,
}

/// Configurable archive extractor with safety limits.
///
/// Used for archmeld-native extraction (formats not
/// handled by exarch-core).
#[derive(Debug, Clone)]
#[allow(clippy::struct_field_names)]
pub struct Extractor {
    max_file_size: u64,
    max_total_size: u64,
    max_files: usize,
    max_compression_ratio: u64,
}

impl Default for Extractor {
    fn default() -> Self {
        Self::new()
    }
}

impl Extractor {
    /// Create a new extractor with default safety limits.
    ///
    /// Defaults: 100 MiB per file, 1 GiB total,
    /// 10 000 files, 100:1 compression ratio.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            max_file_size: 100 * 1024 * 1024,
            max_total_size: 1024 * 1024 * 1024,
            max_files: 10_000,
            max_compression_ratio: 100,
        }
    }

    /// Set maximum allowed size for a single extracted
    /// file.
    #[must_use]
    pub const fn with_max_file_size(mut self, limit: u64) -> Self {
        self.max_file_size = limit;
        self
    }

    /// Set maximum total extraction size.
    #[must_use]
    pub const fn with_max_total_size(mut self, limit: u64) -> Self {
        self.max_total_size = limit;
        self
    }

    /// Set maximum number of files to extract.
    #[must_use]
    pub const fn with_max_files(mut self, limit: usize) -> Self {
        self.max_files = limit;
        self
    }

    /// Set maximum allowed compression ratio.
    #[must_use]
    pub const fn with_max_compression_ratio(mut self, limit: u64) -> Self {
        self.max_compression_ratio = limit;
        self
    }

    /// Extract files from archive data (native formats
    /// only).
    ///
    /// ZIP, TAR (gz/bz2/xz/zst), and 7-Zip should use
    /// `exarch-core` via the CLI layer instead.
    ///
    /// # Errors
    ///
    /// Returns error on I/O failure, size/count limit
    /// violation, path traversal, or unsupported format.
    pub fn extract(&self, data: &[u8], format: ArchiveFormat) -> Result<Vec<ExtractedFile>> {
        match format {
            ArchiveFormat::TarLz4 => {
                let decompressed = decompress_lz4(data)?;
                self.extract_tar(&decompressed)
            },
            ArchiveFormat::Gz => self.extract_single(decompress_gz(data)?),
            ArchiveFormat::Bz2 => self.extract_single(decompress_bz2(data)?),
            ArchiveFormat::Xz => self.extract_single(decompress_xz(data)?),
            ArchiveFormat::Lz4 => self.extract_single(decompress_lz4(data)?),
            ArchiveFormat::Zstd => self.extract_single(decompress_zstd(data)?),
            ArchiveFormat::Lzma => self.extract_single(decompress_lzma(data)?),
            ArchiveFormat::Lha => self.extract_lha(data),
            ArchiveFormat::Rar => Err(Error::UnsupportedFormat(
                "RAR extraction not available \
                     (no pure-Rust library compatible \
                     with forbid(unsafe_code))"
                    .into(),
            )),
            ArchiveFormat::Arc => Err(Error::UnsupportedFormat(
                "ARC extraction not available \
                     (no pure-Rust library available)"
                    .into(),
            )),
            ArchiveFormat::Zoo => Err(Error::UnsupportedFormat(
                "ZOO extraction not available \
                     (no pure-Rust library available)"
                    .into(),
            )),
            other @ (ArchiveFormat::Zip
            | ArchiveFormat::Tar
            | ArchiveFormat::TarGz
            | ArchiveFormat::TarBz2
            | ArchiveFormat::TarXz
            | ArchiveFormat::TarZst
            | ArchiveFormat::SevenZip
            | ArchiveFormat::Xar
            | ArchiveFormat::Dds
            | ArchiveFormat::StuffIt
            | ArchiveFormat::CompactPro
            | ArchiveFormat::Unknown) => Err(Error::UnsupportedFormat(format!(
                "{other}: use exarch-core path \
                     for this format"
            ))),
        }
    }

    /// List archive contents without extracting data.
    ///
    /// # Errors
    ///
    /// Returns error on I/O failure or unsupported format.
    pub fn list(&self, data: &[u8], format: ArchiveFormat) -> Result<Vec<ArchiveEntry>> {
        match format {
            ArchiveFormat::TarLz4 => {
                let decompressed = decompress_lz4(data)?;
                self.list_tar(&decompressed)
            },
            ArchiveFormat::Lha => self.list_lha(data),
            other @ (ArchiveFormat::Zip
            | ArchiveFormat::Tar
            | ArchiveFormat::TarGz
            | ArchiveFormat::TarBz2
            | ArchiveFormat::TarXz
            | ArchiveFormat::TarZst
            | ArchiveFormat::SevenZip
            | ArchiveFormat::Gz
            | ArchiveFormat::Bz2
            | ArchiveFormat::Xz
            | ArchiveFormat::Lz4
            | ArchiveFormat::Zstd
            | ArchiveFormat::Lzma
            | ArchiveFormat::Rar
            | ArchiveFormat::Arc
            | ArchiveFormat::Zoo
            | ArchiveFormat::Xar
            | ArchiveFormat::Dds
            | ArchiveFormat::StuffIt
            | ArchiveFormat::CompactPro
            | ArchiveFormat::Unknown) => Err(Error::UnsupportedFormat(format!(
                "{other}: use exarch-core path \
                     for listing"
            ))),
        }
    }

    fn extract_tar(&self, data: &[u8]) -> Result<Vec<ExtractedFile>> {
        let cursor = Cursor::new(data);
        let mut archive = tar::Archive::new(cursor);
        let mut files = Vec::new();
        let mut total_size: u64 = 0;

        for entry in archive.entries()? {
            if files.len() >= self.max_files {
                return Err(Error::MaxFilesExceeded {
                    count: files.len(),
                    limit: self.max_files,
                });
            }

            let mut entry = entry?;
            let path = entry.path()?.to_str().map(String::from).unwrap_or_default();
            let safe_path = sanitize_path(&path)?;
            let is_directory = entry.header().entry_type().is_dir();
            let size = entry.header().size()?;

            if is_directory {
                files.push(ExtractedFile {
                    path: safe_path,
                    data: Vec::new(),
                    size: 0,
                    is_directory: true,
                });
                continue;
            }

            if size > self.max_file_size {
                return Err(Error::FileTooLarge {
                    size,
                    limit: self.max_file_size,
                });
            }

            total_size = total_size.saturating_add(size);
            if total_size > self.max_total_size {
                return Err(Error::TotalSizeLimitExceeded {
                    limit: self.max_total_size,
                });
            }

            let mut buf = Vec::with_capacity(size.try_into().unwrap_or(0));
            entry.read_to_end(&mut buf)?;

            files.push(ExtractedFile {
                path: safe_path,
                data: buf,
                size,
                is_directory: false,
            });
        }

        Ok(files)
    }

    fn extract_single(&self, decompressed: Vec<u8>) -> Result<Vec<ExtractedFile>> {
        let size = decompressed.len() as u64;
        if size > self.max_file_size {
            return Err(Error::FileTooLarge {
                size,
                limit: self.max_file_size,
            });
        }

        Ok(vec![ExtractedFile {
            path: "decompressed".into(),
            data: decompressed,
            size,
            is_directory: false,
        }])
    }

    fn list_tar(&self, data: &[u8]) -> Result<Vec<ArchiveEntry>> {
        let cursor = Cursor::new(data);
        let mut archive = tar::Archive::new(cursor);
        let mut entries = Vec::new();

        for entry in archive.entries()? {
            let entry = entry?;
            let path = entry.path()?.to_str().map(String::from).unwrap_or_default();
            let size = entry.header().size()?;

            entries.push(ArchiveEntry {
                path,
                compressed_size: size,
                uncompressed_size: size,
                is_directory: entry.header().entry_type().is_dir(),
                compression_method: "stored".into(),
            });
        }

        Ok(entries)
    }
}

/// Metadata about a single archive entry (for listing).
#[derive(Debug, Clone, serde::Serialize)]
pub struct ArchiveEntry {
    /// Entry path **exactly as the archive declares it** — not sanitised.
    ///
    /// Listing must report what is really in the file, including a hostile
    /// `../../etc/passwd`, or the listing cannot be used to inspect a suspect
    /// archive. Run [`sanitize_path`] before this value ever reaches a
    /// filesystem call.
    pub path: String,
    /// Stored size in bytes, as recorded in the archive.
    pub compressed_size: u64,
    /// Size after decompression in bytes, as *claimed* by the archive header.
    ///
    /// Attacker-controlled: a bomb understates it. It feeds the ratio and
    /// size limits, and is never trusted as an allocation size.
    pub uncompressed_size: u64,
    /// Whether the entry is a directory rather than a file.
    pub is_directory: bool,
    /// Compression method name for display (`"deflate"`, `"store"`, …).
    pub compression_method: String,
}

/// Sanitize archive paths to prevent path traversal.
pub fn sanitize_path(raw: &str) -> Result<String> {
    let path = Path::new(raw);
    let mut safe = PathBuf::new();

    for component in path.components() {
        match component {
            Component::Normal(c) => safe.push(c),
            Component::RootDir | Component::CurDir => {},
            Component::ParentDir => {
                return Err(Error::PathTraversal(raw.to_owned()));
            },
            Component::Prefix(_) => {
                return Err(Error::PathTraversal(raw.to_owned()));
            },
        }
    }

    Ok(safe.to_string_lossy().into_owned())
}

// --- Decompression helpers ---

fn decompress_gz(data: &[u8]) -> Result<Vec<u8>> {
    let mut decoder = flate2::read::GzDecoder::new(data);
    let mut out = Vec::new();
    decoder.read_to_end(&mut out)?;
    Ok(out)
}

fn decompress_bz2(data: &[u8]) -> Result<Vec<u8>> {
    let mut decoder = bzip2::read::BzDecoder::new(data);
    let mut out = Vec::new();
    decoder.read_to_end(&mut out)?;
    Ok(out)
}

fn decompress_xz(data: &[u8]) -> Result<Vec<u8>> {
    // XZ stream header: 6 magic + 2 flags + 4 CRC32
    // = 12 bytes minimum.
    if data.len() < 12 {
        return Err(Error::Xz("XZ stream too short".into()));
    }

    // Validate stream flags (bytes 6-7).
    // Byte 6: must be 0x00 (reserved).
    // Byte 7 bits 0-3: check type (0=None,
    //   1=CRC32, 4=CRC64, 10=SHA-256).
    // Byte 7 bits 4-7: reserved (must be 0).
    if data[6] != 0x00 {
        return Err(Error::Xz(
            "invalid XZ stream flags (byte 6 \
             must be 0x00)"
                .into(),
        ));
    }
    let check_type = data[7] & 0x0F;
    let reserved_hi = data[7] & 0xF0;
    if reserved_hi != 0 {
        return Err(Error::Xz(
            "invalid XZ stream flags (reserved \
             bits set in byte 7)"
                .into(),
        ));
    }
    if !matches!(check_type, 0 | 1 | 4 | 10) {
        return Err(Error::Xz(format!(
            "unsupported XZ check type: {check_type}"
        )));
    }

    // Verify header CRC32 (over the 2 flag bytes).
    let stored_crc = u32::from_le_bytes([data[8], data[9], data[10], data[11]]);
    let computed_crc = crc32fast::hash(&data[6..8]);
    if stored_crc != computed_crc {
        return Err(Error::Xz("XZ header CRC32 mismatch".into()));
    }

    // lzma-rs can panic on malformed XZ block/index
    // headers (e.g. integer overflow at xz.rs:52).
    // Use catch_unwind to convert panics into errors.
    let data_vec = data.to_vec();
    std::panic::catch_unwind(|| {
        let mut out = Vec::new();
        lzma_rs::xz_decompress(&mut io::Cursor::new(&data_vec), &mut out).map(|()| out)
    })
    .map_err(|_| Error::Xz("XZ decoder panicked on malformed input".into()))?
    .map_err(|e| Error::Xz(e.to_string()))
}

fn decompress_zstd(data: &[u8]) -> Result<Vec<u8>> {
    let decoder = zstd::Decoder::new(data)?;
    let mut out = Vec::new();
    io::BufReader::new(decoder).read_to_end(&mut out)?;
    Ok(out)
}

fn decompress_lz4(data: &[u8]) -> Result<Vec<u8>> {
    let mut decoder = lz4_flex::frame::FrameDecoder::new(data);
    let mut out = Vec::new();
    decoder
        .read_to_end(&mut out)
        .map_err(|e| Error::Lz4(e.to_string()))?;
    Ok(out)
}

fn decompress_lzma(data: &[u8]) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    lzma_rs::lzma_decompress(&mut io::Cursor::new(data), &mut out)?;
    Ok(out)
}

/// Upper bound on the buffer archmeld pre-allocates for one LHA entry.
///
/// This is an OOM guard against a lying header, **not** a correctness bound:
/// it only sizes the initial `Vec::with_capacity`, and `read_to_end` grows the
/// buffer as needed, so the extracted bytes are identical whatever this value
/// is. Changing it alters allocation strategy only.
///
/// Mutating the expression changes only allocation strategy, so no *extraction*
/// test can tell the difference. It is still worth pinning: the value is a
/// documented OOM bound, and `lha_prealloc_cap_is_16_mib` asserts it against a
/// literal so a careless edit (or a mutant) is caught.
const LHA_PREALLOC_CAP: usize = 16 * 1024 * 1024;

impl Extractor {
    fn extract_lha(&self, data: &[u8]) -> Result<Vec<ExtractedFile>> {
        let cursor = Cursor::new(data);
        let mut lha_reader =
            delharc::LhaDecodeReader::new(cursor).map_err(|e| Error::Lha(e.to_string()))?;

        let mut files = Vec::new();
        let mut total_size: u64 = 0;

        loop {
            if files.len() >= self.max_files {
                return Err(Error::MaxFilesExceeded {
                    count: files.len(),
                    limit: self.max_files,
                });
            }

            let header = lha_reader.header();
            let path = header.parse_pathname();
            let safe_path = sanitize_path(&path.to_string_lossy())?;
            let is_directory = header.is_directory();
            let original_size = header.original_size;

            if is_directory {
                files.push(ExtractedFile {
                    path: safe_path,
                    data: Vec::new(),
                    size: 0,
                    is_directory: true,
                });
            } else if lha_reader.is_decoder_supported() {
                if original_size > self.max_file_size {
                    return Err(Error::FileTooLarge {
                        size: original_size,
                        limit: self.max_file_size,
                    });
                }

                total_size = total_size.saturating_add(original_size);
                if total_size > self.max_total_size {
                    return Err(Error::TotalSizeLimitExceeded {
                        limit: self.max_total_size,
                    });
                }

                // Cap pre-allocation to prevent OOM
                // from untrusted header sizes.
                let cap = usize::try_from(original_size)
                    .unwrap_or(0)
                    .min(LHA_PREALLOC_CAP);
                let mut buf = Vec::with_capacity(cap);
                lha_reader
                    .read_to_end(&mut buf)
                    .map_err(|e| Error::Lha(e.to_string()))?;

                files.push(ExtractedFile {
                    path: safe_path,
                    data: buf,
                    size: original_size,
                    is_directory: false,
                });
            } else {
                // Unsupported compression — skip with
                // warning (do not write 0-byte file)
                eprintln!(
                    "Warning: skipping '{}' \
                     (unsupported LHA compression)",
                    safe_path
                );
            }

            match lha_reader.next_file() {
                Ok(true) => {},
                Ok(false) => break,
                Err(e) => {
                    return Err(Error::Lha(e.to_string()));
                },
            }
        }

        Ok(files)
    }

    fn list_lha(&self, data: &[u8]) -> Result<Vec<ArchiveEntry>> {
        let cursor = Cursor::new(data);
        let mut lha_reader =
            delharc::LhaDecodeReader::new(cursor).map_err(|e| Error::Lha(e.to_string()))?;

        let mut entries = Vec::new();

        loop {
            let header = lha_reader.header();
            let path = header.parse_pathname();
            let method = header
                .compression_method()
                .map_or_else(|_| "unknown".into(), |m| m.to_string());

            entries.push(ArchiveEntry {
                path: path.to_string_lossy().into_owned(),
                compressed_size: header.compressed_size,
                uncompressed_size: header.original_size,
                is_directory: header.is_directory(),
                compression_method: method,
            });

            match lha_reader.next_file() {
                Ok(true) => {},
                Ok(false) => break,
                Err(e) => {
                    return Err(Error::Lha(e.to_string()));
                },
            }
        }

        Ok(entries)
    }
}

/// Returns true if this format should be handled by
/// exarch-core (in the CLI layer) rather than the
/// native `Extractor`.
#[must_use]
pub const fn is_exarch_format(fmt: ArchiveFormat) -> bool {
    matches!(
        fmt,
        ArchiveFormat::Zip
            | ArchiveFormat::Tar
            | ArchiveFormat::TarGz
            | ArchiveFormat::TarBz2
            | ArchiveFormat::TarXz
            | ArchiveFormat::TarZst
            | ArchiveFormat::SevenZip
    )
}

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

    #[test]
    fn test_sanitize_path_normal() {
        assert_eq!(
            sanitize_path("foo/bar.txt").ok(),
            Some("foo/bar.txt".into())
        );
    }

    #[test]
    fn test_sanitize_path_traversal() {
        assert!(sanitize_path("../../../etc/passwd").is_err());
    }

    #[test]
    fn test_sanitize_path_absolute() {
        let result = sanitize_path("/etc/passwd");
        assert!(result.is_ok());
        assert_eq!(result.ok(), Some("etc/passwd".into()));
    }

    #[test]
    fn test_extractor_defaults() {
        let ext = Extractor::new();
        assert_eq!(ext.max_file_size, 100 * 1024 * 1024);
        assert_eq!(ext.max_total_size, 1024 * 1024 * 1024);
        assert_eq!(ext.max_files, 10_000);
        assert_eq!(ext.max_compression_ratio, 100);
    }

    #[test]
    fn test_extractor_custom_limits() {
        let ext = Extractor::new()
            .with_max_file_size(1024)
            .with_max_total_size(4096)
            .with_max_files(500)
            .with_max_compression_ratio(50);
        assert_eq!(ext.max_file_size, 1024);
        assert_eq!(ext.max_total_size, 4096);
        assert_eq!(ext.max_files, 500);
        assert_eq!(ext.max_compression_ratio, 50);
    }

    #[test]
    fn test_is_exarch_format() {
        assert!(is_exarch_format(ArchiveFormat::Zip));
        assert!(is_exarch_format(ArchiveFormat::Tar));
        assert!(is_exarch_format(ArchiveFormat::TarGz));
        assert!(is_exarch_format(ArchiveFormat::SevenZip));
        assert!(!is_exarch_format(ArchiveFormat::TarLz4));
        assert!(!is_exarch_format(ArchiveFormat::Lha));
        assert!(!is_exarch_format(ArchiveFormat::Lzma));
        assert!(!is_exarch_format(ArchiveFormat::Gz));
    }

    // -----------------------------------------------------------------
    // Size-limit boundary tests
    //
    // These exist because `cargo mutants` proved the previous suite did
    // not verify the limits at all: flipping `>` to `>=`, `==` or `<` in
    // the checks below left every test green. The suite executed the
    // limits without ever asserting they REJECT anything, so the
    // zip-bomb defence was implemented but not demonstrated.
    //
    // Each limit therefore gets a PAIR: exactly-at-the-limit must be
    // accepted, and one byte over must fail with the specific error.
    // The pair is what kills the mutants -- an "over the limit fails"
    // test alone still lets `>` -> `>=` survive, because that mutant
    // only misbehaves exactly ON the boundary.
    // -----------------------------------------------------------------

    /// Build an uncompressed TAR containing `count` entries of
    /// `size` bytes each. Entry names are unique so nothing is skipped.
    fn tar_with_entries(count: usize, size: usize) -> Vec<u8> {
        let mut builder = tar::Builder::new(Vec::new());
        for i in 0..count {
            let data = vec![b'a'; size];
            let mut header = tar::Header::new_gnu();
            header.set_size(size as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder
                .append_data(&mut header, format!("f{i}.bin"), &data[..])
                .expect("append entry to in-memory tar");
        }
        builder.into_inner().expect("finish in-memory tar")
    }

    /// LZ4-frame the tar so `extract` dispatches to `Extractor::extract_tar`.
    ///
    /// Plain `ArchiveFormat::Tar` is routed to the exarch-core backend, so
    /// `TarLz4` is the only format that reaches the limit checks under test.
    fn tar_lz4(count: usize, size: usize) -> Vec<u8> {
        let raw = tar_with_entries(count, size);
        let mut enc = lz4_flex::frame::FrameEncoder::new(Vec::new());
        std::io::Write::write_all(&mut enc, &raw).expect("lz4 write");
        enc.finish().expect("lz4 finish")
    }

    #[test]
    fn tar_entry_exactly_at_max_file_size_is_accepted() {
        let data = tar_lz4(1, 1024);
        let out = Extractor::new()
            .with_max_file_size(1024)
            .with_max_total_size(1024 * 1024)
            .extract(&data, ArchiveFormat::TarLz4);
        assert!(
            out.is_ok(),
            "an entry of exactly max_file_size must extract, got {out:?}"
        );
    }

    #[test]
    fn tar_entry_one_byte_over_max_file_size_is_refused() {
        let data = tar_lz4(1, 1025);
        let err = Extractor::new()
            .with_max_file_size(1024)
            .with_max_total_size(1024 * 1024)
            .extract(&data, ArchiveFormat::TarLz4)
            .expect_err("an entry over max_file_size must be refused");
        assert!(
            matches!(
                err,
                Error::FileTooLarge {
                    size: 1025,
                    limit: 1024
                }
            ),
            "expected FileTooLarge{{size:1025,limit:1024}}, got {err:?}"
        );
    }

    #[test]
    fn tar_total_exactly_at_max_total_size_is_accepted() {
        // Two entries of 512 bytes: the running total lands exactly on
        // the ceiling on the second entry.
        let data = tar_lz4(2, 512);
        let out = Extractor::new()
            .with_max_file_size(1024)
            .with_max_total_size(1024)
            .extract(&data, ArchiveFormat::TarLz4);
        assert!(
            out.is_ok(),
            "a running total of exactly max_total_size must extract, got {out:?}"
        );
    }

    #[test]
    fn tar_total_one_byte_over_max_total_size_is_refused() {
        let data = tar_lz4(2, 512);
        let err = Extractor::new()
            .with_max_file_size(1024)
            .with_max_total_size(1023)
            .extract(&data, ArchiveFormat::TarLz4)
            .expect_err("a running total over max_total_size must be refused");
        assert!(
            matches!(err, Error::TotalSizeLimitExceeded { limit: 1023 }),
            "expected TotalSizeLimitExceeded{{limit:1023}}, got {err:?}"
        );
    }

    #[test]
    fn tar_exactly_max_files_entries_are_accepted() {
        let data = tar_lz4(3, 16);
        let out = Extractor::new()
            .with_max_files(3)
            .with_max_file_size(1024)
            .with_max_total_size(1024)
            .extract(&data, ArchiveFormat::TarLz4);
        assert!(
            out.is_ok(),
            "exactly max_files entries must extract, got {out:?}"
        );
    }

    #[test]
    fn tar_one_entry_over_max_files_is_refused() {
        let data = tar_lz4(4, 16);
        let err = Extractor::new()
            .with_max_files(3)
            .with_max_file_size(1024)
            .with_max_total_size(1024)
            .extract(&data, ArchiveFormat::TarLz4)
            .expect_err("more than max_files entries must be refused");
        assert!(
            matches!(err, Error::MaxFilesExceeded { count: 3, limit: 3 }),
            "expected MaxFilesExceeded{{count:3,limit:3}}, got {err:?}"
        );
    }

    #[test]
    fn single_file_exactly_at_max_file_size_is_accepted() {
        // extract_single carries its own `size > max_file_size` check,
        // so it needs the same boundary pair as the tar path.
        let payload = vec![b'z'; 256];
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        std::io::Write::write_all(&mut gz, &payload).expect("gzip write");
        let data = gz.finish().expect("gzip finish");

        let out = Extractor::new()
            .with_max_file_size(256)
            .with_max_total_size(1024)
            .extract(&data, ArchiveFormat::Gz);
        assert!(
            out.is_ok(),
            "a single file of exactly max_file_size must extract, got {out:?}"
        );
    }

    /// Pin the OOM guard against a literal.
    ///
    /// The expanded number is written out on purpose: repeating
    /// `16 * 1024 * 1024` here would mutate in lockstep with the constant and
    /// assert nothing.
    #[test]
    fn lha_prealloc_cap_is_16_mib() {
        assert_eq!(
            LHA_PREALLOC_CAP, 16_777_216,
            "the LHA pre-allocation cap is a documented OOM bound; \
             changing it is a deliberate decision, not a refactor"
        );
    }

    // -- decompress_xz short-stream guard --------------------------------
    //
    // `data.len() < 12` had two surviving mutants (`==` and `<=`). Killing
    // both needs the pair: 11 bytes must be refused AS TOO SHORT (a bare
    // is_err() assertion lets `==` survive, because a short slice then
    // fails later for a different reason), and 12 bytes must get past the
    // guard.

    #[test]
    fn xz_stream_below_minimum_length_is_refused_as_too_short() {
        let err = Extractor::new()
            .extract(&[0u8; 11], ArchiveFormat::Xz)
            .expect_err("an 11-byte xz stream must be refused");
        // `if let` rather than a match with a wildcard arm: the crate denies
        // clippy::wildcard_enum_match_arm so a new Error variant cannot be
        // silently swallowed here.
        let Error::Xz(ref msg) = err else {
            panic!("expected Error::Xz(too short), got {err:?}")
        };
        assert!(
            msg.contains("too short"),
            "expected the short-stream guard, got Xz({msg:?})"
        );
    }

    #[test]
    fn xz_stream_at_minimum_length_passes_the_short_guard() {
        // 12 zero bytes are not a valid xz stream, so this still errors --
        // but it must get PAST the length guard and fail on the header
        // instead. That distinction is what kills the `<=` mutant.
        let err = Extractor::new()
            .extract(&[0u8; 12], ArchiveFormat::Xz)
            .expect_err("12 zero bytes are still not a valid xz stream");
        if let Error::Xz(ref msg) = err {
            assert!(
                !msg.contains("too short"),
                "12 bytes must clear the length guard, got Xz({msg:?})"
            );
        }
    }

    // -- LHA size limits -------------------------------------------------
    //
    // extract_lha carries its own copies of the max_file_size and
    // max_total_size checks, and they had the same unasserted-comparison
    // problem as the tar path. The fixture's real entry size is discovered
    // first, so the boundary is exact without hard-coding a magic number.

    fn lha_fixture() -> Vec<u8> {
        std::fs::read("test-fixtures/sample.lzh").expect("read sample.lzh fixture")
    }

    fn lha_largest_entry_size() -> u64 {
        Extractor::new()
            .extract(&lha_fixture(), ArchiveFormat::Lha)
            .expect("fixture extracts with default limits")
            .iter()
            .map(|f| f.size)
            .max()
            .expect("fixture has at least one entry")
    }

    #[test]
    fn lha_entry_exactly_at_max_file_size_is_accepted() {
        let n = lha_largest_entry_size();
        let out = Extractor::new()
            .with_max_file_size(n)
            .with_max_total_size(u64::MAX)
            .extract(&lha_fixture(), ArchiveFormat::Lha);
        assert!(
            out.is_ok(),
            "an entry of exactly max_file_size must extract, got {out:?}"
        );
    }

    #[test]
    fn lha_entry_one_byte_over_max_file_size_is_refused() {
        let n = lha_largest_entry_size();
        let err = Extractor::new()
            .with_max_file_size(n - 1)
            .with_max_total_size(u64::MAX)
            .extract(&lha_fixture(), ArchiveFormat::Lha)
            .expect_err("an entry over max_file_size must be refused");
        assert!(
            matches!(err, Error::FileTooLarge { limit, .. } if limit == n - 1),
            "expected FileTooLarge with limit {}, got {err:?}",
            n - 1
        );
    }

    #[test]
    fn lha_total_exactly_at_max_total_size_is_accepted() {
        let total: u64 = Extractor::new()
            .extract(&lha_fixture(), ArchiveFormat::Lha)
            .expect("fixture extracts")
            .iter()
            .map(|f| f.size)
            .sum();
        let out = Extractor::new()
            .with_max_file_size(u64::MAX)
            .with_max_total_size(total)
            .extract(&lha_fixture(), ArchiveFormat::Lha);
        assert!(
            out.is_ok(),
            "a total of exactly max_total_size must extract, got {out:?}"
        );
    }

    #[test]
    fn lha_total_one_byte_over_max_total_size_is_refused() {
        let total: u64 = Extractor::new()
            .extract(&lha_fixture(), ArchiveFormat::Lha)
            .expect("fixture extracts")
            .iter()
            .map(|f| f.size)
            .sum();
        let err = Extractor::new()
            .with_max_file_size(u64::MAX)
            .with_max_total_size(total - 1)
            .extract(&lha_fixture(), ArchiveFormat::Lha)
            .expect_err("a total over max_total_size must be refused");
        assert!(
            matches!(err, Error::TotalSizeLimitExceeded { limit } if limit == total - 1),
            "expected TotalSizeLimitExceeded with limit {}, got {err:?}",
            total - 1
        );
    }

    #[test]
    fn single_file_one_byte_over_max_file_size_is_refused() {
        let payload = vec![b'z'; 257];
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        std::io::Write::write_all(&mut gz, &payload).expect("gzip write");
        let data = gz.finish().expect("gzip finish");

        let err = Extractor::new()
            .with_max_file_size(256)
            .with_max_total_size(1024)
            .extract(&data, ArchiveFormat::Gz)
            .expect_err("a single file over max_file_size must be refused");
        assert!(
            matches!(
                err,
                Error::FileTooLarge {
                    size: 257,
                    limit: 256
                }
            ),
            "expected FileTooLarge{{size:257,limit:256}}, got {err:?}"
        );
    }
}