fix(content): validate provider download paths

This commit is contained in:
objz committed 2026-08-04 20:46:21 +02:00
1 parent fb976f1cb9
commit 95a25836a0
4 files changed
+177 -23

No files matched your search

+69 -23
View File
@@ -2,7 +2,7 @@
// and extract config/resource overrides from the zip
use std::collections::HashMap;
use std::path::Path;
use std::path::{Path, PathBuf};
use serde::Deserialize;
@@ -223,31 +223,39 @@ async fn download_mod_files(
for _ in 0..max_concurrent {
if let Some(file) = file_iter.next() {
let client = client.clone();
let dest = minecraft_dir.join(&file.path);
let url = file.downloads.first().cloned().unwrap_or_default();
if url.is_empty() {
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
}
let relative = safe_mrpack_path(&file.path)?;
let dest = minecraft_dir.join(relative);
let url = file.downloads.first().cloned().ok_or_else(|| {
crate::net::NetError::Parse(format!(
".mrpack file '{}' has no download URL",
file.path
))
})?;
let filename = file
.path
.rsplit('/')
.next()
.unwrap_or(&file.path)
.to_string();
let hashes = file.hashes.clone();
let file_size = file.file_size;
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
&& let Err(error) = tokio::fs::create_dir_all(parent).await
{
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
return Err(crate::net::NetError::from(error));
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
if !verify_mrpack_file(&dest, file_size, &hashes)? {
let _ = tokio::fs::remove_file(&dest).await;
return Err(crate::net::NetError::Parse(format!(
"Downloaded .mrpack file '{}' failed its size or hash verification",
dest.display()
)));
}
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
Ok::<(), crate::net::NetError>(())
@@ -262,31 +270,36 @@ async fn download_mod_files(
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
}
let client = client.clone();
let dest = minecraft_dir.join(&file.path);
let url = file.downloads.first().cloned().unwrap_or_default();
if url.is_empty() {
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
}
let relative = safe_mrpack_path(&file.path)?;
let dest = minecraft_dir.join(relative);
let url = file.downloads.first().cloned().ok_or_else(|| {
crate::net::NetError::Parse(format!(".mrpack file '{}' has no download URL", file.path))
})?;
let filename = file
.path
.rsplit('/')
.next()
.unwrap_or(&file.path)
.to_string();
let hashes = file.hashes.clone();
let file_size = file.file_size;
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
&& let Err(error) = tokio::fs::create_dir_all(parent).await
{
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
return Err(crate::net::NetError::from(error));
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
if !verify_mrpack_file(&dest, file_size, &hashes)? {
let _ = tokio::fs::remove_file(&dest).await;
return Err(crate::net::NetError::Parse(format!(
"Downloaded .mrpack file '{}' failed its size or hash verification",
dest.display()
)));
}
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
Ok::<(), crate::net::NetError>(())
@@ -302,6 +315,39 @@ async fn download_mod_files(
Ok(())
}
fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
let path = Path::new(path);
if path.as_os_str().is_empty()
|| path
.components()
.any(|component| !matches!(component, std::path::Component::Normal(_)))
{
return Err(crate::net::NetError::Parse(format!(
"Unsafe .mrpack file path '{}'",
path.display()
)));
}
Ok(path.to_owned())
}
fn verify_mrpack_file(
path: &Path,
expected_size: u64,
expected_hashes: &HashMap<String, String>,
) -> Result<bool, crate::net::NetError> {
let fingerprint = fingerprint(path)?;
if fingerprint.size != expected_size {
return Ok(false);
}
Ok(["sha512", "sha1"].into_iter().all(|algorithm| {
expected_hashes.get(algorithm).is_none_or(|expected| {
fingerprint
.hash(algorithm)
.is_some_and(|actual| actual.eq_ignore_ascii_case(expected))
})
}))
}
fn seed_content_manifest(
index: &MrpackIndex,
paths: &InstancePaths,
+66
View File
@@ -217,6 +217,72 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() {
});
}
#[test]
fn mod_file_rejects_paths_outside_the_instance() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
let index = MrpackIndex {
format_version: 1,
game: "minecraft".to_owned(),
version_id: "1".to_owned(),
name: "Unsafe path".to_owned(),
dependencies: Default::default(),
files: vec![MrpackFile {
path: "../escape.jar".to_owned(),
hashes: Default::default(),
downloads: vec!["https://example.invalid/escape.jar".to_owned()],
file_size: 1,
}],
};
let tmp = tempfile::tempdir().unwrap();
let error = download_mod_files(&index, tmp.path()).await.unwrap_err();
assert!(error.to_string().contains("Unsafe .mrpack file path"));
assert!(!tmp.path().parent().unwrap().join("escape.jar").exists());
});
}
#[test]
fn mod_file_removes_downloads_with_invalid_metadata() {
let _guard = crate::tests::TEST_LOCK
.lock()
.unwrap_or_else(|error| error.into_inner());
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/corrupt.jar"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"corrupt".to_vec()))
.mount(&server)
.await;
let index = MrpackIndex {
format_version: 1,
game: "minecraft".to_owned(),
version_id: "1".to_owned(),
name: "Corrupt download".to_owned(),
dependencies: Default::default(),
files: vec![MrpackFile {
path: "mods/corrupt.jar".to_owned(),
hashes: Default::default(),
downloads: vec![format!("{}/corrupt.jar", server.uri())],
file_size: 1,
}],
};
let tmp = tempfile::tempdir().unwrap();
assert!(download_mod_files(&index, tmp.path()).await.is_err());
assert!(!tmp.path().join("mods/corrupt.jar").exists());
crate::feedback::progress::clear();
});
}
#[test]
fn import_seeds_exact_modrinth_content_identity() {
let tmp = tempfile::tempdir().unwrap();