fix: verify downloads and bound imported metadata

This commit is contained in:
objz committed 2026-10-01 17:44:06 +02:00
1 parent 2b6750a971
commit 3149b96971
25 files changed
+678 -215

No files matched your search

+12 -4
View File
@@ -29,6 +29,17 @@ pub use worlds::{scan_one_world, scan_worlds};
use std::io::Read;
const MAX_LOCAL_METADATA_BYTES: u64 = 8 * 1024 * 1024;
fn read_local_metadata(reader: impl Read) -> Option<Vec<u8>> {
let mut bytes = Vec::new();
reader
.take(MAX_LOCAL_METADATA_BYTES + 1)
.read_to_end(&mut bytes)
.ok()?;
(bytes.len() as u64 <= MAX_LOCAL_METADATA_BYTES).then_some(bytes)
}
pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> {
let disabled_ext = format!("{ext}.disabled");
if let Some(stem) = file_name.strip_suffix(&disabled_ext) {
@@ -49,10 +60,7 @@ pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
}
pub(crate) fn read_icon_from_zip(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
let mut entry = archive.by_name("pack.png").ok()?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf).ok()?;
Some(buf)
read_local_metadata(archive.by_name("pack.png").ok()?)
}
pub(crate) fn open_zip(path: &std::path::Path) -> Option<zip::ZipArchive<std::fs::File>> {
+14 -18
View File
@@ -1,7 +1,6 @@
// SPDX-FileCopyrightText: 2026 Constantin Bauer
// SPDX-License-Identifier: GPL-3.0-only
use std::io::Read;
use std::path::Path;
use serde::Deserialize;
@@ -212,9 +211,10 @@ fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Ve
fn read_fabric_meta(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String, String)> {
let mut entry = archive.by_name("fabric.mod.json").ok()?;
let mut raw = String::new();
entry.read_to_string(&mut raw).ok()?;
let raw = String::from_utf8(super::read_local_metadata(
archive.by_name("fabric.mod.json").ok()?,
)?)
.ok()?;
let sanitized = sanitize_json_strings(&raw);
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
let icon = data.icon_path();
@@ -224,9 +224,10 @@ fn read_fabric_meta(
fn read_quilt_meta(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String, String)> {
let mut entry = archive.by_name("quilt.mod.json").ok()?;
let mut raw = String::new();
entry.read_to_string(&mut raw).ok()?;
let raw = String::from_utf8(super::read_local_metadata(
archive.by_name("quilt.mod.json").ok()?,
)?)
.ok()?;
let sanitized = sanitize_json_strings(&raw);
let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?;
let version = data.quilt_loader.version;
@@ -282,9 +283,10 @@ fn read_forge_toml_meta(
fn read_mcmod_info(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String, String)> {
let mut entry = archive.by_name("mcmod.info").ok()?;
let mut raw = String::new();
entry.read_to_string(&mut raw).ok()?;
let raw = String::from_utf8(super::read_local_metadata(
archive.by_name("mcmod.info").ok()?,
)?)
.ok()?;
let sanitized = sanitize_json_strings(&raw);
let parsed: serde_json::Value = serde_json::from_str(&sanitized).ok()?;
let first = match &parsed {
@@ -316,10 +318,7 @@ fn read_mcmod_info(
}
fn read_zip_string(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<String> {
let mut entry = archive.by_name(path).ok()?;
let mut s = String::new();
entry.read_to_string(&mut s).ok()?;
Some(s)
String::from_utf8(super::read_local_metadata(archive.by_name(path).ok()?)?).ok()
}
// some mod authors put raw newlines/tabs inside json string values which is
@@ -360,10 +359,7 @@ fn sanitize_json_strings(input: &str) -> String {
}
fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<Vec<u8>> {
let mut entry = archive.by_name(path).ok()?;
let mut bytes = Vec::new();
entry.read_to_end(&mut bytes).ok()?;
Some(bytes)
super::read_local_metadata(archive.by_name(path).ok()?)
}
#[cfg(test)]
+11 -4
View File
@@ -110,7 +110,8 @@ fn read_metadata_from_zip(path: &Path) -> (String, Option<Vec<u8>>) {
let description = archive
.by_name("pack.mcmeta")
.ok()
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
.and_then(super::read_local_metadata)
.and_then(|bytes| serde_json::from_slice::<PackMcMeta>(&bytes).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
let icon_bytes = super::read_icon_from_zip(&mut archive);
@@ -118,10 +119,16 @@ fn read_metadata_from_zip(path: &Path) -> (String, Option<Vec<u8>>) {
}
fn read_metadata_from_dir(path: &Path) -> (String, Option<Vec<u8>>) {
let description = std::fs::read_to_string(path.join("pack.mcmeta"))
let description = std::fs::File::open(path.join("pack.mcmeta"))
.ok()
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
.and_then(super::read_local_metadata)
.and_then(|bytes| serde_json::from_slice::<PackMcMeta>(&bytes).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
(description, std::fs::read(path.join("pack.png")).ok())
(
description,
std::fs::File::open(path.join("pack.png"))
.ok()
.and_then(super::read_local_metadata),
)
}
+3 -1
View File
@@ -10,7 +10,9 @@ use super::entry::{ContentEntry, WorldDetails, WorldGameMode};
use super::{fallback_icon_large, make_icon_pixels};
pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
let icon_bytes = File::open(path.join("icon.png"))
.ok()
.and_then(super::read_local_metadata);
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
+12 -5
View File
@@ -65,7 +65,8 @@ fn parse(path: &Path) -> Result<Manifest, String> {
let entry = archive
.by_name("manifest.json")
.map_err(|_| "Missing manifest.json in CurseForge pack".to_owned())?;
serde_json::from_reader(entry).map_err(|error| format!("Invalid CurseForge manifest: {error}"))
let raw = super::read_pack_manifest(entry)?;
serde_json::from_slice(&raw).map_err(|error| format!("Invalid CurseForge manifest: {error}"))
}
fn loader(manifest: &Manifest) -> (ModLoader, Option<String>) {
@@ -178,14 +179,18 @@ async fn download_files(
pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>, String> {
let manifest = parse(path)?;
let api_key = crate::net::curseforge::api_key()
.ok_or_else(|| "CurseForge API key is not configured".to_owned())?;
let overrides = super::override_files(path, &[manifest.overrides.trim_matches('/')])?;
let ids = manifest
.files
.iter()
.filter(|file| file.required)
.map(|file| file.file_id)
.collect::<Vec<_>>();
if ids.is_empty() {
return Ok(overrides);
}
let api_key = crate::net::curseforge::api_key()
.ok_or_else(|| "CurseForge API key is not configured".to_owned())?;
let versions =
crate::net::curseforge::fetch_file_versions(&crate::net::HttpClient::new(), api_key, &ids)
.await
@@ -197,7 +202,7 @@ pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>,
ids.len()
));
}
versions
let mut files: Vec<_> = versions
.into_iter()
.map(|version| {
version
@@ -208,7 +213,9 @@ pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>,
.map(|file| std::path::PathBuf::from("mods").join(&file.filename))
.ok_or_else(|| format!("CurseForge file '{}' has no artifact", version.id))
})
.collect()
.collect::<Result<_, _>>()?;
files.extend(overrides);
Ok(files)
}
fn count_overrides(path: &Path, root: &str) -> Result<usize, String> {
+7 -9
View File
@@ -119,8 +119,6 @@ fn extract_mmc_archive(
archive_path: &Path,
minecraft_dir: &Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use std::io::Read;
progress::set_action("Extracting pack contents...".to_string());
progress::set_sub_action(String::new());
@@ -178,15 +176,14 @@ fn extract_mmc_archive(
.unwrap_or_default();
progress::set_sub_action(filename.to_string());
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
let mut destination = std::fs::File::create(&dest)?;
let size = std::io::copy(&mut entry, &mut destination)?;
tracing::trace!(
"Extracting MultiMC entry {} to {} ({} bytes)",
entry_name,
dest.display(),
buf.len()
size
);
std::fs::write(&dest, &buf)?;
extracted += 1;
}
@@ -210,7 +207,8 @@ fn parse_mmc_pack(path: &Path) -> Result<MmcPack, String> {
.by_name(&entry_name)
.map_err(|e| format!("Failed to read mmc-pack.json: {e}"))?;
serde_json::from_reader(entry).map_err(|e| format!("Invalid mmc-pack.json: {e}"))
let raw = super::read_pack_manifest(entry)?;
serde_json::from_slice(&raw).map_err(|e| format!("Invalid mmc-pack.json: {e}"))
}
fn instance_name_from_cfg(path: &Path) -> Option<String> {
@@ -220,8 +218,8 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
let entry_name = find_entry(&archive, "instance.cfg")?;
tracing::trace!("Reading instance name from {}", entry_name);
let entry = archive.by_name(&entry_name).ok()?;
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
let raw = super::read_pack_manifest(entry).ok()?;
let reader = std::io::BufRead::lines(std::io::BufReader::new(raw.as_slice()));
for line in reader.map_while(Result::ok) {
if let Some(value) = line.strip_prefix("name=") {
let name = value.trim().to_string();
+44
View File
@@ -8,6 +8,22 @@ pub mod refresh;
use std::path::{Path, PathBuf};
const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024;
fn read_pack_manifest(reader: impl std::io::Read) -> Result<Vec<u8>, String> {
use std::io::Read;
let mut bytes = Vec::new();
reader
.take(MAX_PACK_MANIFEST_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|error| error.to_string())?;
if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES {
return Err("Pack manifest exceeds 8 MiB".to_owned());
}
Ok(bytes)
}
use crate::instance::manager::InstanceManager;
use crate::instance::models::ModLoader;
@@ -270,6 +286,34 @@ async fn owned_files(summary: &ImportSummary) -> Result<Vec<PathBuf>, String> {
}
}
fn override_files(path: &Path, roots: &[&str]) -> Result<Vec<PathBuf>, String> {
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
let mut files = Vec::new();
for index in 0..archive.len() {
let entry = archive.by_index(index).map_err(|error| error.to_string())?;
if entry.is_dir() {
continue;
}
let Some(root) = roots
.iter()
.find(|root| entry.name().starts_with(&format!("{root}/")))
else {
continue;
};
let relative = entry
.enclosed_name()
.ok_or_else(|| format!("Unsafe override path: {}", entry.name()))?
.strip_prefix(root)
.map_err(|error| error.to_string())?
.to_owned();
if !relative.as_os_str().is_empty() {
files.push(relative);
}
}
Ok(files)
}
fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
let instance_dir = manager.instances_dir.join(name);
if let Err(error) = std::fs::remove_dir_all(&instance_dir)
+12 -9
View File
@@ -47,8 +47,9 @@ pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
let entry = archive
.by_name("modrinth.index.json")
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
let raw = super::read_pack_manifest(entry)?;
let index: MrpackIndex =
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
serde_json::from_slice(&raw).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
@@ -310,11 +311,16 @@ fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
}
pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> {
parse_mrpack(path)?
let mut files: Vec<_> = parse_mrpack(path)?
.files
.into_iter()
.map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string()))
.collect()
.collect::<Result<_, _>>()?;
files.extend(super::override_files(
path,
&["overrides", "client-overrides"],
)?);
Ok(files)
}
fn verify_mrpack_file(
@@ -420,8 +426,6 @@ fn extract_overrides(
mrpack_path: &Path,
minecraft_dir: &Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use std::io::Read;
progress::set_action("Extracting overrides...".to_string());
progress::set_sub_action(String::new());
@@ -466,15 +470,14 @@ fn extract_overrides(
std::fs::create_dir_all(parent)?;
}
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
let mut destination = std::fs::File::create(&dest)?;
let size = std::io::copy(&mut entry, &mut destination)?;
tracing::trace!(
"Extracting .mrpack override {} to {} ({} bytes)",
entry_name,
dest.display(),
buf.len()
size
);
std::fs::write(&dest, &buf)?;
extracted += 1;
}
+8 -7
View File
@@ -4,23 +4,24 @@
#[must_use]
pub fn maven_coord_to_path(coord: &str) -> Option<String> {
let parts: Vec<&str> = coord.split(':').collect();
match parts.as_slice() {
let path = match parts.as_slice() {
[group, artifact, version] => {
let group_path = group.replace('.', "/");
Some(format!(
format!(
"{}/{}/{}/{}-{}.jar",
group_path, artifact, version, artifact, version
))
)
}
[group, artifact, version, classifier] => {
let group_path = group.replace('.', "/");
Some(format!(
format!(
"{}/{}/{}/{}-{}-{}.jar",
group_path, artifact, version, artifact, version, classifier
))
)
}
_ => None,
}
_ => return None,
};
crate::storage::safe_relative_path(std::path::Path::new(&path)).then_some(path)
}
#[cfg(test)]
+9
View File
@@ -2,6 +2,15 @@
// SPDX-License-Identifier: GPL-3.0-only
use super::*;
#[test]
fn local_metadata_reads_have_a_size_limit() {
assert_eq!(
super::super::read_local_metadata(&b"icon"[..]),
Some(b"icon".to_vec())
);
assert!(super::super::read_local_metadata(std::io::repeat(0)).is_none());
}
use crate::instance::content::entry::{ContentEntry, toggle_entry};
use std::path::PathBuf;
+22
View File
@@ -66,3 +66,25 @@ fn empty_overrides_root_does_not_count_the_manifest() {
assert_eq!(build_summary(&path).unwrap().override_count, 0);
}
#[tokio::test]
async fn override_only_pack_tracks_files_under_its_configured_root() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("pack.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
let options = zip::write::SimpleFileOptions::default();
use std::io::Write;
zip.start_file("manifest.json", options).unwrap();
zip.write_all(
br#"{"name":"Pack","version":"1","minecraft":{"version":"1.20.1"},"overrides":"client"}"#,
)
.unwrap();
zip.start_file("client/config/pack.toml", options).unwrap();
zip.write_all(b"pack").unwrap();
zip.finish().unwrap();
assert_eq!(
owned_files(&path).await.unwrap(),
vec![std::path::PathBuf::from("config/pack.toml")]
);
}
@@ -4,6 +4,16 @@
use super::*;
use std::io::Write;
#[test]
fn oversized_pack_manifest_is_rejected() {
assert_eq!(read_pack_manifest(&b"{}"[..]).unwrap(), b"{}");
assert!(
read_pack_manifest(std::io::repeat(0))
.unwrap_err()
.contains("8 MiB")
);
}
fn make_pack_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> std::path::PathBuf {
let path = tmp.join(name);
let file = std::fs::File::create(&path).unwrap();
+7
View File
@@ -54,6 +54,13 @@ fn summary_counts_both_override_roots() {
assert_eq!(summary.loader, ModLoader::Fabric);
assert_eq!(summary.loader_version.as_deref(), Some("0.16.14"));
assert_eq!(summary.override_count, 2);
assert_eq!(
owned_files(&path).unwrap(),
vec![
PathBuf::from("config/test.toml"),
PathBuf::from("options.txt")
]
);
}
#[test]
+10 -1
View File
@@ -29,7 +29,16 @@ fn maven_nested_group() {
#[test]
fn maven_invalid_coordinates() {
for coordinate in ["org.example:artifact", "a:b:c:d:e", "just-a-string", ""] {
for coordinate in [
"org.example:artifact",
"a:b:c:d:e",
"just-a-string",
"",
".example:artifact:1",
"org.example:../escape:1",
"org.example:artifact:../1",
"org.example:artifact:1:../../escape",
] {
assert_eq!(maven_coord_to_path(coordinate), None);
}
}