Skip to main content

thunderstore_engine/
extract.rs

1//! Generic, CRC-verified zip extraction primitives.
2//!
3//! These are the reusable archive operations shared by every Thunderstore mod
4//! manager: extracting a package zip with per-entry CRC32 verification and
5//! path-traversal protection, deciding whether a downloaded version differs
6//! from what is already on disk, and parsing the `Owner-Name-Version.zip`
7//! filename convention. Where the extracted files ultimately land is install
8//! policy and lives in the caller (see [`crate::install`]).
9
10#![deny(missing_docs)]
11
12#[cfg(feature = "io")]
13use crate::error::{Error, Result};
14#[cfg(feature = "io")]
15use crate::manifest::Manifest;
16#[cfg(feature = "io")]
17use std::fs;
18#[cfg(feature = "io")]
19use std::io::{Read, Write};
20#[cfg(feature = "io")]
21use std::path::{Component, Path, PathBuf};
22#[cfg(feature = "io")]
23use std::sync::atomic::{AtomicU64, Ordering};
24#[cfg(feature = "io")]
25use tracing::{debug, error, warn};
26
27/// Size of the reusable read buffer used to stream each archive entry to disk.
28/// This bounds extraction memory to a constant regardless of entry size; it is an
29/// IO buffer, not a cap on legitimate file size.
30#[cfg(feature = "io")]
31const EXTRACT_CHUNK_SIZE: usize = 64 * 1024;
32
33/// Resource limits enforced while extracting an archive, to defend against
34/// decompression bombs (an archive that is small on disk but expands to an
35/// enormous number of entries or bytes).
36///
37/// These bound *disk* usage and entry count; extraction memory is already a
38/// fixed `EXTRACT_CHUNK_SIZE` buffer regardless of these values. The defaults
39/// are generous enough for real mod and texture packs while still rejecting
40/// pathological archives; tune them with [`extract_zip_with_limits`] when a
41/// caller needs different bounds.
42#[derive(Debug, Clone, Copy)]
43pub struct ExtractLimits {
44  /// Maximum number of entries (files + directories) an archive may contain.
45  pub max_entries: u64,
46  /// Maximum uncompressed size of any single entry, in bytes.
47  pub max_file_bytes: u64,
48  /// Maximum total uncompressed size across all entries, in bytes.
49  pub max_total_bytes: u64,
50}
51
52impl Default for ExtractLimits {
53  fn default() -> Self {
54    Self {
55      max_entries: 100_000,
56      max_file_bytes: 1 << 30,  // 1 GiB
57      max_total_bytes: 4 << 30, // 4 GiB
58    }
59  }
60}
61
62/// Computes a unique sibling temp path next to `path` so a partially-extracted
63/// entry can be written, CRC-verified, then atomically renamed into place — an
64/// interrupted or corrupt entry never leaves a usable file behind.
65#[cfg(feature = "io")]
66fn temp_sibling_path(path: &Path) -> PathBuf {
67  static COUNTER: AtomicU64 = AtomicU64::new(0);
68
69  let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
70  let pid = std::process::id();
71  let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("entry");
72  let tmp_name = format!(".{name}.{pid}.{seq}.partial");
73
74  match path.parent() {
75    Some(parent) => parent.join(tmp_name),
76    None => PathBuf::from(tmp_name),
77  }
78}
79
80/// Streams a single archive entry to `tmp_path`, holding only a fixed-size buffer
81/// in memory, and verifies its CRC32 against `expected_crc32`.
82///
83/// Enforces the byte limits in `limits` against the *actual* number of bytes
84/// streamed (not the archive's declared sizes, which an attacker controls):
85/// `max_file_bytes` for this entry and `max_total_bytes` for the cumulative
86/// `total_written` across the whole archive. Exceeding either returns
87/// [`Error::ExtractLimitExceeded`].
88///
89/// Returns [`Error::ChecksumMismatch`] when the computed CRC differs from the one
90/// recorded in the archive. The caller is responsible for renaming `tmp_path` into
91/// place on success and removing it on any error.
92#[cfg(feature = "io")]
93fn write_entry<R: Read>(
94  entry: &mut R,
95  buffer: &mut [u8],
96  tmp_path: &Path,
97  expected_crc32: u32,
98  dest: &Path,
99  limits: &ExtractLimits,
100  total_written: &mut u64,
101) -> Result<()> {
102  let mut outfile = fs::File::create(tmp_path)?;
103  let mut hasher = crc32fast::Hasher::new();
104  let mut file_written: u64 = 0;
105
106  loop {
107    let read = entry.read(&mut buffer[..])?;
108
109    if read == 0 {
110      break;
111    }
112
113    file_written += read as u64;
114    *total_written += read as u64;
115
116    check_extract_size(dest, file_written, *total_written, limits)?;
117
118    hasher.update(&buffer[..read]);
119    outfile.write_all(&buffer[..read])?;
120  }
121
122  let actual_crc32 = hasher.finalize();
123
124  if actual_crc32 != expected_crc32 {
125    error!(
126      "CRC32 verification failed for {}: expected {:08x}, got {:08x}",
127      dest.display(),
128      expected_crc32,
129      actual_crc32
130    );
131
132    return Err(Error::ChecksumMismatch {
133      path: dest.display().to_string(),
134      expected: expected_crc32,
135      actual: actual_crc32,
136    });
137  }
138
139  outfile.flush()?;
140
141  Ok(())
142}
143
144/// Enforces the streamed-byte limits for one entry: the per-entry
145/// `max_file_bytes` and the cumulative `max_total_bytes` across the archive.
146///
147/// Checked against the *actual* bytes streamed (which an attacker cannot forge,
148/// unlike an archive's declared sizes). Pure — no I/O — so the decompression-bomb
149/// guard is unit-testable. Returns [`Error::ExtractLimitExceeded`] on breach; this
150/// stays distinct from the network `SizeCap`/[`Error::SizeLimitExceeded`] path
151/// because archive limits also bound a non-byte quantity (entry count).
152#[cfg(feature = "io")]
153fn check_extract_size(
154  dest: &Path,
155  file_written: u64,
156  total_written: u64,
157  limits: &ExtractLimits,
158) -> Result<()> {
159  if file_written > limits.max_file_bytes {
160    return Err(Error::ExtractLimitExceeded(format!(
161      "entry {} exceeds max file size of {} bytes",
162      dest.display(),
163      limits.max_file_bytes
164    )));
165  }
166
167  if total_written > limits.max_total_bytes {
168    return Err(Error::ExtractLimitExceeded(format!(
169      "archive exceeds max total uncompressed size of {} bytes",
170      limits.max_total_bytes
171    )));
172  }
173
174  Ok(())
175}
176
177/// Joins a validated archive entry path onto `dest_dir`, or returns `None` if the
178/// entry would escape the destination.
179///
180/// `entry` is the result of [`zip::read::ZipFile::enclosed_name`] (already `None`
181/// for a rejected path). As defense in depth on top of that, this rejects any
182/// absolute, root, drive-prefix, or `..` component itself, so the traversal guard
183/// is a single pure function testable against crafted paths without a real
184/// archive.
185#[cfg(feature = "io")]
186fn safe_join(dest_dir: &Path, entry: Option<&Path>) -> Option<PathBuf> {
187  let entry = entry?;
188
189  for component in entry.components() {
190    match component {
191      Component::Normal(_) | Component::CurDir => {}
192      Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
193    }
194  }
195
196  Some(dest_dir.join(entry))
197}
198
199/// The permissions to force on an extracted entry, or `None` to keep whatever
200/// [`fs::File::create`] and the process umask already produced.
201///
202/// Only the archive's *execute* bits are consulted, and only to widen the file to
203/// `0o755`. A loader package ships `run_bepinex.sh` / `start_game_bepinex.sh`
204/// marked executable and the generated Steam wrapper `exec`s whichever one it
205/// finds, so an entry that loses that bit turns a modded launch into a bare
206/// `Permission denied`, which under Steam surfaces only as the game silently
207/// never starting.
208///
209/// The recorded mode is deliberately **not** reproduced wholesale. A downloaded
210/// package is untrusted input: applying it verbatim would honour `setuid`,
211/// `setgid`, and sticky bits, and would let an entry declare itself
212/// world-writable. Widening to a fixed `0o755` can do neither. An entry with no
213/// recorded mode at all, which is every archive built on Windows, is left alone
214/// rather than guessed at.
215#[cfg(all(unix, feature = "io"))]
216fn entry_permissions(unix_mode: Option<u32>) -> Option<fs::Permissions> {
217  use std::os::unix::fs::PermissionsExt;
218
219  let mode = unix_mode?;
220
221  if mode & 0o111 == 0 {
222    return None;
223  }
224
225  Some(fs::Permissions::from_mode(0o755))
226}
227
228/// Applies an archive entry's recorded execute bit to the file just extracted to
229/// `path`. See [`entry_permissions`] for why only that bit is honoured.
230///
231/// A no-op off Unix, where a zip entry's Unix mode has nothing to map onto.
232#[cfg(feature = "io")]
233fn apply_entry_mode(path: &Path, unix_mode: Option<u32>) -> Result<()> {
234  #[cfg(unix)]
235  if let Some(permissions) = entry_permissions(unix_mode) {
236    fs::set_permissions(path, permissions)?;
237  }
238
239  #[cfg(not(unix))]
240  let _ = (path, unix_mode);
241
242  Ok(())
243}
244
245/// Extracts a zip archive to `dest_dir` with per-entry CRC32 verification and
246/// the default [`ExtractLimits`].
247///
248/// Entry paths are validated with [`zip::read::ZipFile::enclosed_name`] so that
249/// archive entries containing `..` or absolute paths cannot escape `dest_dir`.
250///
251/// # Errors
252///
253/// Returns an error if the file is not a valid zip archive, if IO fails, if
254/// CRC32 verification fails for any extracted entry ([`Error::ChecksumMismatch`]),
255/// or if the archive exceeds a default extraction limit
256/// ([`Error::ExtractLimitExceeded`]).
257#[cfg(feature = "io")]
258pub fn extract_zip(zip_path: &Path, dest_dir: &Path) -> Result<()> {
259  extract_zip_with_limits(zip_path, dest_dir, &ExtractLimits::default())
260}
261
262/// Extracts a zip archive to `dest_dir` with per-entry CRC32 verification,
263/// enforcing the supplied [`ExtractLimits`] to defend against decompression
264/// bombs.
265///
266/// Entry paths are validated with [`zip::read::ZipFile::enclosed_name`] so that
267/// archive entries containing `..` or absolute paths cannot escape `dest_dir`.
268/// The entry count and the actual streamed byte totals are checked against
269/// `limits`; CRC32 is an integrity check only and does not authenticate content.
270///
271/// # Errors
272///
273/// Returns an error if the file is not a valid zip archive, if IO fails, if
274/// CRC32 verification fails for any extracted entry ([`Error::ChecksumMismatch`]),
275/// or if the archive exceeds a limit in `limits`
276/// ([`Error::ExtractLimitExceeded`]).
277#[cfg(feature = "io")]
278pub fn extract_zip_with_limits(
279  zip_path: &Path,
280  dest_dir: &Path,
281  limits: &ExtractLimits,
282) -> Result<()> {
283  extract_zip_reporting(zip_path, dest_dir, limits, &mut |_, _| {})
284}
285
286/// [`extract_zip_with_limits`], calling `on_progress(done, total)` in archive
287/// entries before each entry and once more after the last.
288#[cfg(feature = "io")]
289pub(crate) fn extract_zip_reporting(
290  zip_path: &Path,
291  dest_dir: &Path,
292  limits: &ExtractLimits,
293  on_progress: &mut dyn FnMut(u64, u64),
294) -> Result<()> {
295  let file = fs::File::open(zip_path)?;
296  let mut archive = zip::ZipArchive::new(file)?;
297
298  if archive.len() as u64 > limits.max_entries {
299    return Err(Error::ExtractLimitExceeded(format!(
300      "archive has {} entries, exceeding the limit of {}",
301      archive.len(),
302      limits.max_entries
303    )));
304  }
305
306  fs::create_dir_all(dest_dir)?;
307
308  let mut total_written: u64 = 0;
309  let mut buffer = vec![0u8; EXTRACT_CHUNK_SIZE];
310  let entries = archive.len() as u64;
311
312  for i in 0..archive.len() {
313    on_progress(i as u64, entries);
314
315    let mut file_in_archive = archive.by_index(i)?;
316    let enclosed = file_in_archive.enclosed_name();
317    let outpath = match safe_join(dest_dir, enclosed.as_deref()) {
318      Some(path) => path,
319      None => {
320        warn!("Invalid file path in zip: {:?}", file_in_archive.name());
321        continue;
322      }
323    };
324
325    let comment = file_in_archive.comment();
326
327    if !comment.is_empty() {
328      debug!("File {} comment: {:?}", i, comment);
329    }
330
331    if file_in_archive.name().ends_with('/') {
332      debug!("Creating directory {}", outpath.display());
333      fs::create_dir_all(&outpath)?;
334    } else {
335      debug!("Extracting file {} to {}", i, outpath.display());
336
337      if let Some(parent) = outpath.parent()
338        && !parent.exists()
339      {
340        fs::create_dir_all(parent)?;
341      }
342
343      let expected_crc32 = file_in_archive.crc32();
344      // Read before streaming: `write_entry` borrows the entry mutably, and the
345      // mode is needed after the file is renamed into place.
346      let unix_mode = file_in_archive.unix_mode();
347      let tmp_path = temp_sibling_path(&outpath);
348
349      // Stream the entry to a temp file, verifying the CRC as we go. Any failure
350      // (IO, a short/corrupt entry the `zip` reader rejects, or a CRC mismatch)
351      // must remove the temp file so a corrupt entry never lands at `outpath`.
352      match write_entry(
353        &mut file_in_archive,
354        &mut buffer,
355        &tmp_path,
356        expected_crc32,
357        &outpath,
358        limits,
359        &mut total_written,
360      ) {
361        Ok(()) => {
362          // Applied to the temp file rather than to `outpath`, so the entry
363          // becomes visible at its final path already carrying its final mode
364          // instead of appearing briefly as non-executable. Any failure here is
365          // treated exactly like a failed rename: remove the temp file so a
366          // half-finished entry never lands.
367          if let Err(err) = apply_entry_mode(&tmp_path, unix_mode) {
368            let _ = fs::remove_file(&tmp_path);
369
370            return Err(err);
371          }
372
373          // A failed rename must also remove the temp file, so a CRC-verified
374          // entry that cannot be moved into place leaves no orphan behind.
375          if let Err(err) = fs::rename(&tmp_path, &outpath) {
376            let _ = fs::remove_file(&tmp_path);
377
378            return Err(err.into());
379          }
380
381          debug!("CRC32 verification successful for {}", outpath.display());
382        }
383        Err(err) => {
384          let _ = fs::remove_file(&tmp_path);
385
386          return Err(err);
387        }
388      }
389    }
390  }
391
392  on_progress(entries, entries);
393
394  Ok(())
395}
396
397/// Calculates the CRC32 checksum for a byte buffer.
398#[cfg(all(test, feature = "io"))]
399fn calculate_crc32(data: &[u8]) -> u32 {
400  let mut hasher = crc32fast::Hasher::new();
401  hasher.update(data);
402
403  hasher.finalize()
404}
405
406/// Determines whether a mod should be (re)extracted based on version comparison.
407///
408/// Returns `Ok(true)` if `mod_dir` has no `manifest.json`, if its manifest has a
409/// different `version_number` than `version`, or if its manifest cannot be
410/// parsed. Returns `Ok(false)` only when an existing manifest already records
411/// the same version.
412#[cfg(feature = "io")]
413pub fn should_extract(mod_dir: &Path, version: &str) -> Result<bool> {
414  let manifest_path = mod_dir.join("manifest.json");
415
416  let existing_version = if manifest_path.exists() {
417    match Manifest::from_file(&manifest_path) {
418      Ok(manifest) => Some(manifest.version_number),
419      Err(err) => {
420        warn!(
421          "Failed to parse manifest in {}: {}; re-extracting",
422          mod_dir.display(),
423          err
424        );
425
426        None
427      }
428    }
429  } else {
430    debug!(
431      "No manifest in {}, extracting version {}",
432      mod_dir.display(),
433      version
434    );
435
436    None
437  };
438
439  let reextract = should_reextract(existing_version.as_deref(), version);
440
441  if let Some(existing) = &existing_version {
442    if reextract {
443      debug!(
444        "{} version changed from {} to {}, extracting",
445        mod_dir.display(),
446        existing,
447        version
448      );
449    } else {
450      debug!(
451        "{} already has version {}, skipping",
452        mod_dir.display(),
453        version
454      );
455    }
456  }
457
458  Ok(reextract)
459}
460
461/// The pure re-extract decision, given the version an existing on-disk manifest
462/// records (`None` when there is no manifest, or it could not be parsed) and the
463/// `requested` version.
464///
465/// Re-extract unless an existing manifest already records exactly the requested
466/// version. Extracted from [`should_extract`] so the decision is testable without
467/// writing manifest files to disk.
468#[cfg(feature = "io")]
469fn should_reextract(existing_version: Option<&str>, requested: &str) -> bool {
470  match existing_version {
471    Some(existing) => existing != requested,
472    None => true,
473  }
474}
475
476/// Parses a Thunderstore package zip filename of the form
477/// `Owner-Name-Version.zip`.
478///
479/// Returns the package full name (`Owner-Name`) and the version string, or
480/// `None` if the filename does not contain at least three `-`-separated parts.
481///
482/// Only the first two `-` delimiters are significant: the owner and name never
483/// contain `-`, but everything after the second delimiter is taken verbatim as
484/// the version, so a version that itself contains `-` (e.g. a `1.0.0-beta`
485/// prerelease) is preserved rather than truncated.
486pub fn parse_package_filename(file_name: &str) -> Option<(String, String)> {
487  let stem = file_name.strip_suffix(".zip").unwrap_or(file_name);
488  let parts: Vec<&str> = stem.splitn(3, '-').collect();
489
490  if parts.len() < 3 {
491    return None;
492  }
493
494  let full_name = format!("{}-{}", parts[0], parts[1]);
495  let version = parts[2].to_string();
496
497  Some((full_name, version))
498}
499
500#[cfg(all(test, feature = "io"))]
501mod tests {
502  use super::*;
503  use std::fs::File;
504  use std::io::Write;
505  use tempfile::tempdir;
506  use zip::write::{FileOptions, ZipWriter};
507
508  #[test]
509  fn test_calculate_crc32() {
510    let data = b"test data for crc32 calculation";
511    let crc = calculate_crc32(data);
512
513    let expected_crc: u32 = 1707861357;
514
515    assert_eq!(crc, expected_crc);
516  }
517
518  #[test]
519  fn safe_join_rejects_traversal_and_absolute() {
520    let base = Path::new("/dest");
521
522    assert_eq!(safe_join(base, None), None);
523    assert_eq!(safe_join(base, Some(Path::new("../escape"))), None);
524    assert_eq!(safe_join(base, Some(Path::new("a/../../b"))), None);
525    assert_eq!(safe_join(base, Some(Path::new("/etc/passwd"))), None);
526
527    assert_eq!(
528      safe_join(base, Some(Path::new("plugins/mod.dll"))),
529      Some(PathBuf::from("/dest/plugins/mod.dll"))
530    );
531    assert!(safe_join(base, Some(Path::new("./ok.txt"))).is_some());
532  }
533
534  /// A drive or UNC prefix only parses as one on Windows, so that is the only
535  /// host where the guard can be seen to catch it.
536  #[test]
537  #[cfg(windows)]
538  fn safe_join_rejects_drive_and_unc_prefixes() {
539    let base = Path::new(r"C:\dest");
540
541    assert_eq!(
542      safe_join(base, Some(Path::new(r"C:\Windows\evil.dll"))),
543      None
544    );
545    assert_eq!(safe_join(base, Some(Path::new("C:evil.dll"))), None);
546    assert_eq!(
547      safe_join(base, Some(Path::new(r"\\server\share\evil.dll"))),
548      None
549    );
550  }
551
552  #[test]
553  fn should_reextract_truth_table() {
554    // No existing manifest (or an unparseable one) => re-extract.
555    assert!(should_reextract(None, "1.0.0"));
556    // Same version already present => skip.
557    assert!(!should_reextract(Some("1.0.0"), "1.0.0"));
558    // Different version present => re-extract.
559    assert!(should_reextract(Some("1.0.0"), "1.0.1"));
560  }
561
562  #[test]
563  fn check_extract_size_enforces_both_caps() {
564    let limits = ExtractLimits {
565      max_entries: 1,
566      max_file_bytes: 10,
567      max_total_bytes: 20,
568    };
569
570    // At the caps is allowed.
571    assert!(check_extract_size(Path::new("f"), 10, 20, &limits).is_ok());
572
573    // Over the per-file cap.
574    assert!(matches!(
575      check_extract_size(Path::new("f"), 11, 11, &limits).unwrap_err(),
576      Error::ExtractLimitExceeded(_)
577    ));
578
579    // Over the whole-archive cap.
580    assert!(matches!(
581      check_extract_size(Path::new("f"), 5, 21, &limits).unwrap_err(),
582      Error::ExtractLimitExceeded(_)
583    ));
584  }
585
586  #[test]
587  fn temp_sibling_path_is_unique_and_sibling() {
588    let base = Path::new("/tmp/x/file.dll");
589
590    let a = temp_sibling_path(base);
591    let b = temp_sibling_path(base);
592
593    assert_ne!(a, b);
594    assert_eq!(a.parent(), Some(Path::new("/tmp/x")));
595  }
596
597  #[test]
598  fn write_entry_streams_verifies_crc_and_enforces_cap() {
599    let dir = tempdir().unwrap();
600    let data = b"hello world, this is a streamed entry";
601    let crc = calculate_crc32(data);
602    let limits = ExtractLimits::default();
603
604    // Success: a small buffer forces multiple read iterations; the file lands and
605    // the running total reflects every byte.
606    let tmp = dir.path().join("ok.partial");
607    let mut reader = std::io::Cursor::new(data.to_vec());
608    let mut buffer = vec![0u8; 4];
609    let mut total = 0u64;
610
611    write_entry(
612      &mut reader,
613      &mut buffer,
614      &tmp,
615      crc,
616      Path::new("ok"),
617      &limits,
618      &mut total,
619    )
620    .unwrap();
621
622    assert_eq!(std::fs::read(&tmp).unwrap(), data);
623    assert_eq!(total, data.len() as u64);
624
625    // CRC mismatch is reported.
626    let tmp2 = dir.path().join("bad.partial");
627    let mut reader = std::io::Cursor::new(data.to_vec());
628    let mut buffer = vec![0u8; 64];
629    let mut total = 0u64;
630
631    let err = write_entry(
632      &mut reader,
633      &mut buffer,
634      &tmp2,
635      0xDEAD_BEEF,
636      Path::new("bad"),
637      &limits,
638      &mut total,
639    )
640    .unwrap_err();
641
642    assert!(matches!(err, Error::ChecksumMismatch { .. }));
643
644    // The per-file byte cap is enforced against the actual streamed bytes.
645    let tmp3 = dir.path().join("big.partial");
646    let tight = ExtractLimits {
647      max_file_bytes: 4,
648      ..ExtractLimits::default()
649    };
650    let mut reader = std::io::Cursor::new(vec![0u8; 10]);
651    let mut buffer = vec![0u8; 64];
652    let mut total = 0u64;
653
654    let err = write_entry(
655      &mut reader,
656      &mut buffer,
657      &tmp3,
658      0,
659      Path::new("big"),
660      &tight,
661      &mut total,
662    )
663    .unwrap_err();
664
665    assert!(matches!(err, Error::ExtractLimitExceeded(_)));
666  }
667
668  #[test]
669  fn test_parse_package_filename() {
670    assert_eq!(
671      parse_package_filename("Owner-ModName-1.0.0.zip"),
672      Some(("Owner-ModName".to_string(), "1.0.0".to_string()))
673    );
674
675    assert_eq!(parse_package_filename("InvalidFile.zip"), None);
676  }
677
678  #[test]
679  fn test_parse_package_filename_preserves_hyphenated_version() {
680    assert_eq!(
681      parse_package_filename("Owner-ModName-1.0.0-beta.1.zip"),
682      Some(("Owner-ModName".to_string(), "1.0.0-beta.1".to_string()))
683    );
684  }
685
686  #[test]
687  fn test_extract_zip_with_valid_paths() {
688    let temp_dir = tempdir().unwrap();
689    let output_dir = temp_dir.path().join("output");
690    fs::create_dir_all(&output_dir).unwrap();
691
692    let zip_path = temp_dir.path().join("test_invalid_paths.zip");
693    let file = File::create(&zip_path).unwrap();
694    let mut zip = ZipWriter::new(file);
695
696    let options: FileOptions<'_, ()> =
697      FileOptions::default().compression_method(zip::CompressionMethod::Stored);
698
699    zip.start_file("valid_file.txt", options).unwrap();
700    zip.write_all(b"Valid file content").unwrap();
701
702    zip.finish().unwrap();
703
704    let result = extract_zip(&zip_path, &output_dir);
705
706    assert!(result.is_ok());
707
708    let valid_file = output_dir.join("valid_file.txt");
709    assert!(valid_file.exists());
710  }
711
712  /// A loader package ships `start_game_bepinex.sh` / `run_bepinex.sh` marked
713  /// executable in the archive, and the generated Steam wrapper `exec`s whichever
714  /// one it finds. Dropping the archive's execute bit makes that `exec` fail with
715  /// `Permission denied`, which under Steam surfaces only as the game silently
716  /// never starting, so the bit has to survive extraction.
717  #[test]
718  #[cfg(unix)]
719  fn test_extract_zip_preserves_the_executable_bit() {
720    use std::os::unix::fs::PermissionsExt;
721
722    let temp_dir = tempdir().unwrap();
723    let output_dir = temp_dir.path().join("output");
724
725    let zip_path = temp_dir.path().join("test_modes.zip");
726    let file = File::create(&zip_path).unwrap();
727    let mut zip = ZipWriter::new(file);
728
729    let executable: FileOptions<'_, ()> = FileOptions::default()
730      .compression_method(zip::CompressionMethod::Stored)
731      .unix_permissions(0o755);
732    let plain: FileOptions<'_, ()> = FileOptions::default()
733      .compression_method(zip::CompressionMethod::Stored)
734      .unix_permissions(0o644);
735
736    zip.start_file("start_game_bepinex.sh", executable).unwrap();
737    zip.write_all(b"#!/bin/sh\n").unwrap();
738
739    zip.start_file("mods.yml", plain).unwrap();
740    zip.write_all(b"[]").unwrap();
741
742    zip.finish().unwrap();
743
744    extract_zip(&zip_path, &output_dir).unwrap();
745
746    let script_mode = fs::metadata(output_dir.join("start_game_bepinex.sh"))
747      .unwrap()
748      .permissions()
749      .mode();
750
751    assert!(
752      script_mode & 0o111 != 0,
753      "executable entry extracted without an execute bit: {script_mode:o}"
754    );
755
756    // A non-executable entry must not be widened just because a sibling was
757    // executable: only the archive's own execute bits are honoured.
758    let plain_mode = fs::metadata(output_dir.join("mods.yml"))
759      .unwrap()
760      .permissions()
761      .mode();
762
763    assert!(
764      plain_mode & 0o111 == 0,
765      "plain entry gained an execute bit: {plain_mode:o}"
766    );
767  }
768
769  /// An archive built on Windows records no Unix mode at all. Those entries must
770  /// still extract, keeping the default permissions rather than erroring or being
771  /// made executable.
772  #[test]
773  #[cfg(unix)]
774  fn test_extract_zip_handles_entries_with_no_unix_mode() {
775    use std::os::unix::fs::PermissionsExt;
776
777    let temp_dir = tempdir().unwrap();
778    let output_dir = temp_dir.path().join("output");
779
780    let zip_path = temp_dir.path().join("test_no_mode.zip");
781    let file = File::create(&zip_path).unwrap();
782    let mut zip = ZipWriter::new(file);
783
784    let options: FileOptions<'_, ()> =
785      FileOptions::default().compression_method(zip::CompressionMethod::Stored);
786
787    zip.start_file("plugin.dll", options).unwrap();
788    zip.write_all(b"bytes").unwrap();
789
790    zip.finish().unwrap();
791
792    extract_zip(&zip_path, &output_dir).unwrap();
793
794    let mode = fs::metadata(output_dir.join("plugin.dll"))
795      .unwrap()
796      .permissions()
797      .mode();
798
799    assert!(
800      mode & 0o111 == 0,
801      "entry with no mode made executable: {mode:o}"
802    );
803  }
804
805  /// `setuid`/`setgid`/sticky bits in an archive are never reproduced on disk: a
806  /// downloaded package must not be able to plant a setuid file.
807  #[test]
808  #[cfg(unix)]
809  fn test_extract_zip_drops_setuid_bits() {
810    use std::os::unix::fs::PermissionsExt;
811
812    let temp_dir = tempdir().unwrap();
813    let output_dir = temp_dir.path().join("output");
814
815    let zip_path = temp_dir.path().join("test_setuid.zip");
816    let file = File::create(&zip_path).unwrap();
817    let mut zip = ZipWriter::new(file);
818
819    let options: FileOptions<'_, ()> = FileOptions::default()
820      .compression_method(zip::CompressionMethod::Stored)
821      .unix_permissions(0o4755);
822
823    zip.start_file("evil.sh", options).unwrap();
824    zip.write_all(b"#!/bin/sh\n").unwrap();
825
826    zip.finish().unwrap();
827
828    extract_zip(&zip_path, &output_dir).unwrap();
829
830    let mode = fs::metadata(output_dir.join("evil.sh"))
831      .unwrap()
832      .permissions()
833      .mode();
834
835    assert!(
836      mode & 0o7000 == 0,
837      "setuid/setgid/sticky survived: {mode:o}"
838    );
839    assert!(mode & 0o111 != 0, "execute bit lost: {mode:o}");
840  }
841
842  #[test]
843  fn test_extract_zip_with_directory() {
844    let temp_dir = tempdir().unwrap();
845    let output_dir = temp_dir.path().join("output");
846    fs::create_dir_all(&output_dir).unwrap();
847
848    let zip_path = temp_dir.path().join("test_with_dir.zip");
849    let file = File::create(&zip_path).unwrap();
850    let mut zip = ZipWriter::new(file);
851
852    let options: FileOptions<'_, ()> =
853      FileOptions::default().compression_method(zip::CompressionMethod::Stored);
854
855    zip.add_directory("test_dir/", options).unwrap();
856
857    zip.start_file("test_dir/file_in_dir.txt", options).unwrap();
858    zip.write_all(b"File in directory").unwrap();
859
860    zip.finish().unwrap();
861
862    let result = extract_zip(&zip_path, &output_dir);
863
864    assert!(result.is_ok());
865
866    let dir_path = output_dir.join("test_dir");
867    assert!(dir_path.exists());
868    assert!(dir_path.is_dir());
869
870    let file_in_dir = dir_path.join("file_in_dir.txt");
871    assert!(file_in_dir.exists());
872
873    let content = fs::read_to_string(&file_in_dir).unwrap();
874    assert_eq!(content, "File in directory");
875  }
876
877  #[test]
878  fn test_extract_zip_with_nested_directories() {
879    let temp_dir = tempdir().unwrap();
880    let output_dir = temp_dir.path().join("output");
881
882    let zip_path = temp_dir.path().join("test_nested.zip");
883    let file = File::create(&zip_path).unwrap();
884    let mut zip = ZipWriter::new(file);
885
886    let options: FileOptions<'_, ()> =
887      FileOptions::default().compression_method(zip::CompressionMethod::Stored);
888
889    zip
890      .start_file("deep/nested/path/file.txt", options)
891      .unwrap();
892    zip.write_all(b"Deep nested file").unwrap();
893
894    zip.finish().unwrap();
895
896    let result = extract_zip(&zip_path, &output_dir);
897
898    assert!(result.is_ok());
899
900    let nested_file = output_dir.join("deep/nested/path/file.txt");
901    assert!(nested_file.exists());
902
903    let content = fs::read_to_string(&nested_file).unwrap();
904    assert_eq!(content, "Deep nested file");
905  }
906
907  #[test]
908  fn test_extract_zip_streams_large_file() {
909    let temp_dir = tempdir().unwrap();
910    let output_dir = temp_dir.path().join("output");
911
912    let zip_path = temp_dir.path().join("test_large.zip");
913    let file = File::create(&zip_path).unwrap();
914    let mut zip = ZipWriter::new(file);
915
916    let options: FileOptions<'_, ()> =
917      FileOptions::default().compression_method(zip::CompressionMethod::Stored);
918
919    // Larger than EXTRACT_CHUNK_SIZE so the streaming loop runs many iterations.
920    let payload: Vec<u8> = (0..(64 * 1024 * 3 + 17)).map(|i| (i % 251) as u8).collect();
921
922    zip.start_file("big.bin", options).unwrap();
923    zip.write_all(&payload).unwrap();
924
925    zip.finish().unwrap();
926
927    let result = extract_zip(&zip_path, &output_dir);
928
929    assert!(result.is_ok());
930
931    let extracted = output_dir.join("big.bin");
932    let content = fs::read(&extracted).unwrap();
933
934    assert_eq!(content, payload);
935
936    // No leftover temp/partial files from the atomic write.
937    let leftover = fs::read_dir(&output_dir)
938      .unwrap()
939      .filter_map(|e| e.ok())
940      .any(|e| e.file_name().to_string_lossy().contains(".partial"));
941
942    assert!(!leftover, "no .partial temp files should remain");
943  }
944
945  #[test]
946  fn test_extract_zip_reuses_buffer_across_entries() {
947    let temp_dir = tempdir().unwrap();
948    let output_dir = temp_dir.path().join("output");
949
950    // A large entry followed by a smaller one: the read buffer is reused across
951    // entries, so the smaller entry must not inherit stale bytes from the larger.
952    let big: Vec<u8> = (0..(64 * 1024 * 2 + 5)).map(|i| (i % 251) as u8).collect();
953    let small = b"tiny".to_vec();
954    let zip_path = temp_dir.path().join("multi.zip");
955    write_stored_zip(&zip_path, &[("big.bin", &big), ("small.txt", &small)]);
956
957    let result = extract_zip(&zip_path, &output_dir);
958
959    assert!(result.is_ok());
960
961    let big_out = fs::read(output_dir.join("big.bin")).unwrap();
962    let small_out = fs::read(output_dir.join("small.txt")).unwrap();
963
964    assert_eq!(big_out, big);
965    assert_eq!(small_out, small);
966    assert!(no_partial_files(&output_dir));
967  }
968
969  #[test]
970  fn test_extract_zip_leaves_no_file_on_crc_mismatch() {
971    let temp_dir = tempdir().unwrap();
972    let output_dir = temp_dir.path().join("output");
973
974    let zip_path = temp_dir.path().join("test_corrupt.zip");
975    let file = File::create(&zip_path).unwrap();
976    let mut zip = ZipWriter::new(file);
977
978    let options: FileOptions<'_, ()> =
979      FileOptions::default().compression_method(zip::CompressionMethod::Stored);
980
981    // Stored compression keeps the payload as raw bytes in the local entry, so
982    // flipping one payload byte makes the actual CRC diverge from the stored one.
983    let marker = b"UNIQUEMARKERPAYLOAD";
984    let mut payload = marker.to_vec();
985    payload.extend_from_slice(&[7u8; 64]);
986
987    zip.start_file("data.bin", options).unwrap();
988    zip.write_all(&payload).unwrap();
989
990    zip.finish().unwrap();
991
992    let mut bytes = fs::read(&zip_path).unwrap();
993    let pos = bytes
994      .windows(marker.len())
995      .position(|w| w == marker)
996      .expect("payload marker present in archive");
997
998    // Corrupt a byte inside the payload (after the marker).
999    bytes[pos + marker.len()] ^= 0xFF;
1000    fs::write(&zip_path, &bytes).unwrap();
1001
1002    let result = extract_zip(&zip_path, &output_dir);
1003
1004    // A corrupted entry must fail extraction. Depending on compression, the
1005    // mismatch is caught either by our CRC check (`ChecksumMismatch`) or by the
1006    // `zip` reader's own validation (surfaced as an IO/ZIP error) — either way
1007    // extraction errors and nothing is left behind.
1008    assert!(result.is_err());
1009
1010    // The corrupt entry must not leave a usable file (nor a .partial temp).
1011    assert!(!output_dir.join("data.bin").exists());
1012
1013    let leftover = fs::read_dir(&output_dir)
1014      .unwrap()
1015      .filter_map(|e| e.ok())
1016      .any(|e| e.file_name().to_string_lossy().contains(".partial"));
1017
1018    assert!(!leftover, "no .partial temp files should remain");
1019  }
1020
1021  fn write_stored_zip(zip_path: &Path, entries: &[(&str, &[u8])]) {
1022    let file = File::create(zip_path).unwrap();
1023    let mut zip = ZipWriter::new(file);
1024
1025    let options: FileOptions<'_, ()> =
1026      FileOptions::default().compression_method(zip::CompressionMethod::Stored);
1027
1028    for (name, contents) in entries {
1029      zip.start_file(*name, options).unwrap();
1030      zip.write_all(contents).unwrap();
1031    }
1032
1033    zip.finish().unwrap();
1034  }
1035
1036  fn no_partial_files(dir: &Path) -> bool {
1037    !fs::read_dir(dir)
1038      .unwrap()
1039      .filter_map(|e| e.ok())
1040      .any(|e| e.file_name().to_string_lossy().contains(".partial"))
1041  }
1042
1043  #[test]
1044  fn test_extract_zip_rejects_too_many_entries() {
1045    let temp_dir = tempdir().unwrap();
1046    let output_dir = temp_dir.path().join("output");
1047
1048    let zip_path = temp_dir.path().join("many_entries.zip");
1049    write_stored_zip(
1050      &zip_path,
1051      &[("a.txt", b"a"), ("b.txt", b"b"), ("c.txt", b"c")],
1052    );
1053
1054    let limits = ExtractLimits {
1055      max_entries: 2,
1056      ..Default::default()
1057    };
1058
1059    let result = extract_zip_with_limits(&zip_path, &output_dir, &limits);
1060
1061    assert!(matches!(result, Err(Error::ExtractLimitExceeded(_))));
1062  }
1063
1064  #[test]
1065  fn test_extract_zip_rejects_oversized_entry() {
1066    let temp_dir = tempdir().unwrap();
1067    let output_dir = temp_dir.path().join("output");
1068
1069    let zip_path = temp_dir.path().join("big_entry.zip");
1070    let payload = vec![0u8; 100];
1071    write_stored_zip(&zip_path, &[("big.bin", &payload)]);
1072
1073    let limits = ExtractLimits {
1074      max_file_bytes: 8,
1075      ..Default::default()
1076    };
1077
1078    let result = extract_zip_with_limits(&zip_path, &output_dir, &limits);
1079
1080    assert!(matches!(result, Err(Error::ExtractLimitExceeded(_))));
1081    assert!(!output_dir.join("big.bin").exists());
1082    assert!(no_partial_files(&output_dir));
1083  }
1084
1085  #[test]
1086  fn test_extract_zip_rejects_exceeding_total() {
1087    let temp_dir = tempdir().unwrap();
1088    let output_dir = temp_dir.path().join("output");
1089
1090    let zip_path = temp_dir.path().join("total.zip");
1091    let chunk = vec![7u8; 80];
1092    write_stored_zip(&zip_path, &[("one.bin", &chunk), ("two.bin", &chunk)]);
1093
1094    // Each entry fits under max_file_bytes, but together they exceed the total.
1095    let limits = ExtractLimits {
1096      max_file_bytes: 1_000,
1097      max_total_bytes: 100,
1098      ..Default::default()
1099    };
1100
1101    let result = extract_zip_with_limits(&zip_path, &output_dir, &limits);
1102
1103    assert!(matches!(result, Err(Error::ExtractLimitExceeded(_))));
1104    assert!(no_partial_files(&output_dir));
1105  }
1106
1107  #[test]
1108  fn test_extract_zip_within_default_limits_succeeds() {
1109    let temp_dir = tempdir().unwrap();
1110    let output_dir = temp_dir.path().join("output");
1111
1112    let zip_path = temp_dir.path().join("normal.zip");
1113    write_stored_zip(&zip_path, &[("plugin.dll", b"content")]);
1114
1115    let result = extract_zip_with_limits(&zip_path, &output_dir, &ExtractLimits::default());
1116
1117    assert!(result.is_ok());
1118    assert!(output_dir.join("plugin.dll").exists());
1119  }
1120
1121  #[test]
1122  fn test_extract_zip_rejects_path_traversal() {
1123    let temp_dir = tempdir().unwrap();
1124    let output_dir = temp_dir.path().join("output");
1125    fs::create_dir_all(&output_dir).unwrap();
1126
1127    // A crafted archive whose entry tries to climb out of the extraction root,
1128    // alongside a benign entry.
1129    let zip_path = temp_dir.path().join("traversal.zip");
1130    write_stored_zip(
1131      &zip_path,
1132      &[("../escaped.txt", b"malicious"), ("safe.txt", b"benign")],
1133    );
1134
1135    let result = extract_zip(&zip_path, &output_dir);
1136
1137    // Extraction succeeds by skipping the unsafe entry, the benign file lands
1138    // inside the root, and nothing is written to the parent (outside the root).
1139    assert!(result.is_ok());
1140    assert!(output_dir.join("safe.txt").exists());
1141    assert!(!temp_dir.path().join("escaped.txt").exists());
1142    assert!(no_partial_files(&output_dir));
1143  }
1144
1145  #[test]
1146  fn test_should_extract() {
1147    let temp_dir = tempdir().unwrap();
1148    let mod_dir = temp_dir.path().join("Owner-ModName");
1149    fs::create_dir_all(&mod_dir).unwrap();
1150
1151    let result = should_extract(&mod_dir, "1.0.0");
1152    assert!(result.unwrap());
1153
1154    let manifest_content = r#"{
1155      "version_number": "1.0.0",
1156      "name": "TestMod",
1157      "description": "Test mod description"
1158    }"#;
1159
1160    let manifest_path = mod_dir.join("manifest.json");
1161    let mut file = File::create(&manifest_path).unwrap();
1162    file.write_all(manifest_content.as_bytes()).unwrap();
1163
1164    let result = should_extract(&mod_dir, "1.0.0");
1165    assert!(!result.unwrap());
1166
1167    let result = should_extract(&mod_dir, "2.0.0");
1168    assert!(result.unwrap());
1169
1170    let mut file = File::create(&manifest_path).unwrap();
1171    file.write_all(b"invalid json content").unwrap();
1172
1173    let result = should_extract(&mod_dir, "1.0.0");
1174    assert!(result.unwrap());
1175  }
1176}