fix: verify downloads and bound imported metadata
This commit is contained in:
1 parent
2b6750a971
commit
3149b96971
25 files changed
+678
-215
No files matched your search
@@ -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>> {
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -88,22 +88,18 @@ fn rule_matches(rule: &Rule, ctx: &RuleContext) -> bool {
|
||||
}
|
||||
|
||||
// mojang's os.version constraints are typically anchored regex patterns
|
||||
// (e.g. `^10\\.`). we do a substring containment check as a defensive
|
||||
// approximation that doesn't pull in the `regex` crate. when the host
|
||||
// os_version is empty (Windows fallback path returns ""), version-gated
|
||||
// rules don't match - which is the conservative default.
|
||||
// version-gated rules do not match an unknown host version.
|
||||
fn os_version_matches(pattern: &str, host_version: &str) -> bool {
|
||||
if host_version.is_empty() {
|
||||
return false;
|
||||
}
|
||||
// strip common regex anchors and metacharacters for substring lookup.
|
||||
// good enough for the rare profile that uses os.version.
|
||||
let needle = pattern
|
||||
.trim_start_matches('^')
|
||||
.trim_end_matches('$')
|
||||
.trim_end_matches('.')
|
||||
.trim_end_matches('\\');
|
||||
host_version.contains(needle)
|
||||
match regex::Regex::new(pattern) {
|
||||
Ok(regex) => regex.is_match(host_version),
|
||||
Err(error) => {
|
||||
tracing::warn!("Invalid OS version pattern '{pattern}': {error}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool {
|
||||
|
||||
@@ -235,6 +235,14 @@ fn os_version_pattern_does_not_match_when_host_unknown() {
|
||||
assert!(!evaluate(&rules, &ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_version_regex_respects_anchors_and_escapes() {
|
||||
assert!(os_version_matches(r"^10\.", "10.15.7"));
|
||||
assert!(!os_version_matches(r"^10\.", "110.15.7"));
|
||||
assert!(!os_version_matches(r"^10\.", "10x15"));
|
||||
assert!(!os_version_matches("[", "10.15.7"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_deserializes_from_mojang_json() {
|
||||
// shape lifted from real mojang library rules.
|
||||
|
||||
+35
-26
@@ -232,19 +232,7 @@ async fn get<T: serde::de::DeserializeOwned>(
|
||||
api_key: &str,
|
||||
url: &str,
|
||||
) -> Result<T, NetError> {
|
||||
let response = client
|
||||
.inner()
|
||||
.get(url)
|
||||
.header("x-api-key", api_key)
|
||||
.send()
|
||||
.await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(NetError::StatusError {
|
||||
status: response.status().as_u16(),
|
||||
url: url.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(response.json().await?)
|
||||
authenticated_request(url, || client.inner().get(url).header("x-api-key", api_key)).await
|
||||
}
|
||||
|
||||
async fn post<B: serde::Serialize + ?Sized, T: serde::de::DeserializeOwned>(
|
||||
@@ -253,20 +241,41 @@ async fn post<B: serde::Serialize + ?Sized, T: serde::de::DeserializeOwned>(
|
||||
url: &str,
|
||||
body: &B,
|
||||
) -> Result<T, NetError> {
|
||||
let response = client
|
||||
.inner()
|
||||
.post(url)
|
||||
.header("x-api-key", api_key)
|
||||
.json(body)
|
||||
.send()
|
||||
.await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(NetError::StatusError {
|
||||
status: response.status().as_u16(),
|
||||
url: url.to_owned(),
|
||||
});
|
||||
authenticated_request(url, || {
|
||||
client
|
||||
.inner()
|
||||
.post(url)
|
||||
.header("x-api-key", api_key)
|
||||
.json(body)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn authenticated_request<T: serde::de::DeserializeOwned>(
|
||||
url: &str,
|
||||
build: impl Fn() -> reqwest::RequestBuilder,
|
||||
) -> Result<T, NetError> {
|
||||
for attempt in 0..=super::MAX_RETRIES {
|
||||
let result = async {
|
||||
let response = build().send().await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(NetError::StatusError {
|
||||
status: response.status().as_u16(),
|
||||
url: url.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(response.json().await?)
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) if error.is_retryable() && attempt < super::MAX_RETRIES => {
|
||||
super::sleep_before_retry("request", url, attempt, &error).await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(response.json().await?)
|
||||
unreachable!("retry loop returns on success or final error")
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
|
||||
+49
-18
@@ -13,9 +13,11 @@ use reqwest::Client;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const MAX_PROVIDER_ASSET_BYTES: usize = 16 * 1024 * 1024;
|
||||
static NEXT_DOWNLOAD_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum NetError {
|
||||
@@ -151,7 +153,7 @@ impl HttpClient {
|
||||
.await;
|
||||
match result {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) if is_retryable(&error) && attempt < MAX_RETRIES => {
|
||||
Err(error) if error.is_retryable() && attempt < MAX_RETRIES => {
|
||||
sleep_before_retry("request", url, attempt, &error).await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
@@ -187,7 +189,7 @@ where
|
||||
match client.get(url).await {
|
||||
Ok(resp) => match decode(resp).await {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(e) if is_retryable(&e) => {
|
||||
Err(e) if e.is_retryable() => {
|
||||
if attempt == MAX_RETRIES {
|
||||
return Err(e);
|
||||
}
|
||||
@@ -195,7 +197,7 @@ where
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
Err(e) if is_retryable(&e) => {
|
||||
Err(e) if e.is_retryable() => {
|
||||
if attempt == MAX_RETRIES {
|
||||
return Err(e);
|
||||
}
|
||||
@@ -233,14 +235,14 @@ pub async fn download_file(
|
||||
) -> Result<(), NetError> {
|
||||
tracing::debug!("Downloading {} to {}", url, dest.display());
|
||||
|
||||
let result = 'download: {
|
||||
'download: {
|
||||
for attempt in 0..=MAX_RETRIES {
|
||||
match download_file_once(client, url, dest, &progress_cb).await {
|
||||
Ok(()) => {
|
||||
tracing::debug!("Downloaded {} to {}", url, dest.display());
|
||||
break 'download Ok(());
|
||||
}
|
||||
Err(e) if is_retryable(&e) => {
|
||||
Err(e) if e.is_retryable() => {
|
||||
if attempt == MAX_RETRIES {
|
||||
break 'download Err(e);
|
||||
}
|
||||
@@ -250,11 +252,7 @@ pub async fn download_file(
|
||||
}
|
||||
}
|
||||
unreachable!("retry loop returns on success or final error")
|
||||
};
|
||||
if result.is_err() {
|
||||
let _ = tokio::fs::remove_file(dest).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) async fn download_loader_libraries<'a>(
|
||||
@@ -268,7 +266,7 @@ pub(crate) async fn download_loader_libraries<'a>(
|
||||
let maven_path = crate::instance::loader::maven::maven_coord_to_path(name)
|
||||
.ok_or_else(|| NetError::Parse(format!("Invalid Maven coordinate: {name}")))?;
|
||||
let dest = libraries_dir.join(&maven_path);
|
||||
if dest.exists() {
|
||||
if valid_jar(&dest) {
|
||||
tracing::debug!("{loader} library already exists: {name}");
|
||||
continue;
|
||||
}
|
||||
@@ -278,10 +276,23 @@ pub(crate) async fn download_loader_libraries<'a>(
|
||||
tracing::info!("Downloading {loader} library: {name}");
|
||||
tracing::trace!("{loader} library destination: {}", dest.display());
|
||||
download_file(client, &download_url, &dest, |_, _| {}).await?;
|
||||
if !valid_jar(&dest) {
|
||||
let _ = tokio::fs::remove_file(&dest).await;
|
||||
return Err(NetError::Parse(format!(
|
||||
"Downloaded {loader} library '{name}' is not a valid JAR"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn valid_jar(path: &Path) -> bool {
|
||||
std::fs::File::open(path)
|
||||
.ok()
|
||||
.and_then(|file| zip::ZipArchive::new(file).ok())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
async fn download_file_once(
|
||||
client: &HttpClient,
|
||||
url: &str,
|
||||
@@ -298,18 +309,38 @@ async fn download_file_once(
|
||||
tokio::fs::create_dir_all(parent).await?;
|
||||
}
|
||||
|
||||
let mut file = tokio::fs::File::create(dest).await?;
|
||||
let temporary = dest.with_file_name(format!(
|
||||
".{}.{}.{}.download",
|
||||
dest.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("file"),
|
||||
std::process::id(),
|
||||
NEXT_DOWNLOAD_ID.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let mut file = tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
.await?;
|
||||
let mut downloaded: u64 = 0;
|
||||
let mut stream = response;
|
||||
|
||||
while let Some(chunk) = stream.chunk().await? {
|
||||
file.write_all(&chunk).await?;
|
||||
downloaded += chunk.len() as u64;
|
||||
progress_cb(downloaded, total);
|
||||
let result = async {
|
||||
while let Some(chunk) = stream.chunk().await? {
|
||||
file.write_all(&chunk).await?;
|
||||
downloaded += chunk.len() as u64;
|
||||
progress_cb(downloaded, total);
|
||||
}
|
||||
file.flush().await?;
|
||||
drop(file);
|
||||
crate::storage::replace_file(&temporary, dest)?;
|
||||
Ok(())
|
||||
}
|
||||
file.flush().await?;
|
||||
|
||||
Ok(())
|
||||
.await;
|
||||
if result.is_err() {
|
||||
let _ = tokio::fs::remove_file(&temporary).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
// body decode errors and timeouts are worth retrying, but a 404 or disk
|
||||
|
||||
+5
-1
@@ -525,7 +525,11 @@ pub async fn download_version_file(
|
||||
validate_path_component(&version.id, "provider version id")?;
|
||||
let path = destination.join(&file.filename);
|
||||
if path.exists() {
|
||||
if verify_version_file(&path, file)? {
|
||||
if ["sha512", "sha1"]
|
||||
.iter()
|
||||
.any(|algorithm| file.hashes.contains_key(*algorithm))
|
||||
&& verify_version_file(&path, file)?
|
||||
{
|
||||
return Ok(DownloadOutcome::SkippedExisting(path));
|
||||
}
|
||||
return Err(crate::net::NetError::Parse(format!(
|
||||
|
||||
+102
-65
@@ -160,7 +160,20 @@ pub async fn fetch_version_meta_with_raw(
|
||||
entry.id,
|
||||
entry.url
|
||||
);
|
||||
client.get_json_with_raw(&entry.url, "version meta").await
|
||||
let (meta, raw): (VersionMeta, Vec<u8>) =
|
||||
client.get_json_with_raw(&entry.url, "version meta").await?;
|
||||
if !sha1_matches(&raw, &entry.sha1) || meta.id != entry.id {
|
||||
return Err(NetError::Parse(format!(
|
||||
"Version metadata for '{}' does not match its manifest",
|
||||
entry.id
|
||||
)));
|
||||
}
|
||||
Ok((meta, raw))
|
||||
}
|
||||
|
||||
fn sha1_matches(bytes: &[u8], expected: &str) -> bool {
|
||||
use sha1::Digest;
|
||||
format!("{:x}", sha1::Sha1::digest(bytes)).eq_ignore_ascii_case(expected)
|
||||
}
|
||||
|
||||
fn sha1_hex(path: &Path) -> Option<String> {
|
||||
@@ -192,7 +205,7 @@ fn verify_cached(path: &Path, expected_sha1: &str, expected_size: u64) -> bool {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
sha1_hex(path).is_some_and(|hash| hash == expected_sha1)
|
||||
sha1_hex(path).is_some_and(|hash| hash.eq_ignore_ascii_case(expected_sha1))
|
||||
}
|
||||
|
||||
pub async fn download_client_jar(
|
||||
@@ -278,7 +291,7 @@ pub async fn download_libraries(
|
||||
.join(&meta.id)
|
||||
.join("natives");
|
||||
|
||||
let mut downloads: Vec<(String, PathBuf, String)> = Vec::new();
|
||||
let mut downloads: Vec<(String, PathBuf, String, String, u64)> = Vec::new();
|
||||
// natives jars to unpack once every download has landed:
|
||||
// (jar path inside the library cache, extract.exclude prefixes)
|
||||
let mut natives_jars: Vec<(PathBuf, Vec<String>)> = Vec::new();
|
||||
@@ -291,20 +304,22 @@ pub async fn download_libraries(
|
||||
}
|
||||
|
||||
if let Some(artifact) = &library.downloads.artifact {
|
||||
let rel = match library_relative_path(library, artifact.path.as_str()) {
|
||||
Some(rel) => rel,
|
||||
None => {
|
||||
tracing::warn!("Skipping unresolvable library {}", library.name);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let rel = library_relative_path(library, artifact.path.as_str()).ok_or_else(|| {
|
||||
NetError::Parse(format!("Invalid library path for {}", library.name))
|
||||
})?;
|
||||
let destination = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.libraries()
|
||||
.join(&rel);
|
||||
if verify_cached(&destination, &artifact.sha1, artifact.size) {
|
||||
tracing::trace!("Library already cached: {}", rel);
|
||||
} else {
|
||||
downloads.push((artifact.url.clone(), destination, rel));
|
||||
downloads.push((
|
||||
artifact.url.clone(),
|
||||
destination,
|
||||
rel,
|
||||
artifact.sha1.clone(),
|
||||
artifact.size,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,25 +341,31 @@ pub async fn download_libraries(
|
||||
let rel = if !info.path.is_empty() {
|
||||
info.path.clone()
|
||||
} else {
|
||||
match crate::instance::loader::maven::maven_coord_to_path(&format!(
|
||||
crate::instance::loader::maven::maven_coord_to_path(&format!(
|
||||
"{}:{}",
|
||||
library.name, classifier
|
||||
)) {
|
||||
Some(rel) => rel,
|
||||
None => {
|
||||
tracing::warn!(
|
||||
"Skipping natives of library {}: no usable path",
|
||||
library.name
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
))
|
||||
.ok_or_else(|| {
|
||||
NetError::Parse(format!("Invalid native library path for {}", library.name))
|
||||
})?
|
||||
};
|
||||
if !crate::storage::safe_relative_path(Path::new(&rel)) {
|
||||
return Err(NetError::Parse(format!(
|
||||
"Invalid native library path for {}",
|
||||
library.name
|
||||
)));
|
||||
}
|
||||
let destination = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.libraries()
|
||||
.join(&rel);
|
||||
if !verify_cached(&destination, &info.sha1, info.size) {
|
||||
downloads.push((info.url.clone(), destination.clone(), rel));
|
||||
downloads.push((
|
||||
info.url.clone(),
|
||||
destination.clone(),
|
||||
rel,
|
||||
info.sha1.clone(),
|
||||
info.size,
|
||||
));
|
||||
}
|
||||
let exclude = library
|
||||
.extract
|
||||
@@ -373,10 +394,12 @@ pub async fn download_libraries(
|
||||
}
|
||||
|
||||
fn library_relative_path(library: &Library, recorded_path: &str) -> Option<String> {
|
||||
if !recorded_path.is_empty() {
|
||||
return Some(recorded_path.to_owned());
|
||||
}
|
||||
crate::instance::loader::maven::maven_coord_to_path(&library.name)
|
||||
let path = if recorded_path.is_empty() {
|
||||
crate::instance::loader::maven::maven_coord_to_path(&library.name)?
|
||||
} else {
|
||||
recorded_path.to_owned()
|
||||
};
|
||||
crate::storage::safe_relative_path(Path::new(&path)).then_some(path)
|
||||
}
|
||||
|
||||
fn extract_natives(jar: &Path, dest: &Path, exclude: &[String]) -> Result<(), NetError> {
|
||||
@@ -433,60 +456,61 @@ pub async fn download_assets_from(
|
||||
assets_base: &str,
|
||||
) -> Result<(), NetError> {
|
||||
set_action("Downloading assets...");
|
||||
if !crate::storage::safe_relative_path(Path::new(&meta.asset_index.id))
|
||||
|| Path::new(&meta.asset_index.id).components().count() != 1
|
||||
{
|
||||
clear();
|
||||
return Err(NetError::Parse("Invalid asset index ID".to_owned()));
|
||||
}
|
||||
let index_path = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.assets()
|
||||
.join("indexes")
|
||||
.join(format!("{}.json", meta.asset_index.id));
|
||||
let asset_index: AssetIndexContent = if index_path.exists() {
|
||||
let bytes = tokio::fs::read(&index_path).await?;
|
||||
serde_json::from_slice(&bytes)
|
||||
.map_err(|error| NetError::Parse(format!("Invalid cached asset index: {error}")))?
|
||||
let cached = match tokio::fs::read(&index_path).await {
|
||||
Ok(bytes) if sha1_matches(&bytes, &meta.asset_index.sha1) => {
|
||||
serde_json::from_slice(&bytes).ok()
|
||||
}
|
||||
Ok(_) => {
|
||||
tracing::warn!(
|
||||
"Invalid cached asset index at {}; fetching again",
|
||||
index_path.display()
|
||||
);
|
||||
None
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let asset_index: AssetIndexContent = if let Some(index) = cached {
|
||||
index
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"Fetching asset index {} from {}",
|
||||
meta.asset_index.id,
|
||||
meta.asset_index.url
|
||||
);
|
||||
let index = match client.get_json(&meta.asset_index.url).await {
|
||||
Ok(index) => index,
|
||||
let bytes = match client.get_bytes(&meta.asset_index.url).await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
clear();
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
match serde_json::to_string(&index) {
|
||||
Ok(json) => {
|
||||
if let Some(parent) = index_path.parent() {
|
||||
match tokio::fs::create_dir_all(parent).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::debug!("Failed to create asset index dir: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
match tokio::fs::write(&index_path, json).await {
|
||||
Ok(_) => {
|
||||
tracing::debug!("Saved asset index to {}", index_path.display());
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!(
|
||||
"Failed to write asset index {}: {}",
|
||||
index_path.display(),
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!("Failed to serialize asset index: {}", e);
|
||||
}
|
||||
if !sha1_matches(&bytes, &meta.asset_index.sha1) {
|
||||
clear();
|
||||
return Err(NetError::Parse(format!(
|
||||
"Asset index '{}' failed its SHA-1 verification",
|
||||
meta.asset_index.id
|
||||
)));
|
||||
}
|
||||
let index = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| NetError::Parse(format!("Invalid asset index: {error}")))?;
|
||||
crate::storage::write_atomic(&index_path, &bytes)?;
|
||||
index
|
||||
};
|
||||
|
||||
let mut downloads = Vec::new();
|
||||
for object in asset_index.objects.values() {
|
||||
if object.hash.len() < 2 {
|
||||
if object.hash.len() != 40 || !object.hash.bytes().all(|byte| byte.is_ascii_hexdigit()) {
|
||||
clear();
|
||||
return Err(NetError::Parse(format!(
|
||||
"Invalid asset hash: {}",
|
||||
@@ -506,7 +530,13 @@ pub async fn download_assets_from(
|
||||
continue;
|
||||
}
|
||||
|
||||
downloads.push((url, destination, object.hash.clone()));
|
||||
downloads.push((
|
||||
url,
|
||||
destination,
|
||||
object.hash.clone(),
|
||||
object.hash.clone(),
|
||||
object.size,
|
||||
));
|
||||
}
|
||||
|
||||
if downloads.is_empty() {
|
||||
@@ -528,7 +558,7 @@ pub async fn download_assets_from(
|
||||
// Continue other downloads after one fails; report the first error afterward.
|
||||
async fn run_parallel_downloads(
|
||||
client: &HttpClient,
|
||||
downloads: Vec<(String, PathBuf, String)>,
|
||||
downloads: Vec<(String, PathBuf, String, String, u64)>,
|
||||
report_count_progress: bool,
|
||||
) -> Result<(), NetError> {
|
||||
let total_downloads = downloads.len() as u64;
|
||||
@@ -592,9 +622,9 @@ async fn run_parallel_downloads(
|
||||
fn spawn_download_task(
|
||||
set: &mut JoinSet<Result<String, NetError>>,
|
||||
client: &HttpClient,
|
||||
job: (String, PathBuf, String),
|
||||
job: (String, PathBuf, String, String, u64),
|
||||
) {
|
||||
let (url, destination, label) = job;
|
||||
let (url, destination, label, sha1, size) = job;
|
||||
let task_client = client.clone();
|
||||
|
||||
set.spawn(async move {
|
||||
@@ -604,7 +634,14 @@ fn spawn_download_task(
|
||||
destination.display()
|
||||
);
|
||||
let result = download_file(&task_client, &url, &destination, |_current, _total| {}).await;
|
||||
result.map(|()| {
|
||||
result?;
|
||||
if !verify_cached(&destination, &sha1, size) {
|
||||
tokio::fs::remove_file(&destination).await?;
|
||||
return Err(NetError::Parse(format!(
|
||||
"Downloaded '{label}' failed its SHA-1 or size verification"
|
||||
)));
|
||||
}
|
||||
Ok({
|
||||
tracing::trace!("Finished parallel download '{}'", label);
|
||||
label
|
||||
})
|
||||
|
||||
@@ -3,6 +3,46 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn authenticated_requests_retry_transient_failures_with_the_api_key() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use wiremock::matchers::{header, method, path};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
let server = MockServer::start().await;
|
||||
for verb in ["GET", "POST"] {
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
Mock::given(method(verb))
|
||||
.and(path(format!("/{verb}")))
|
||||
.and(header("x-api-key", "test-key"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
if attempts.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
ResponseTemplate::new(503)
|
||||
} else {
|
||||
ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok": true}))
|
||||
}
|
||||
})
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let client: HttpClient = reqwest::Client::builder().build().unwrap().into();
|
||||
let fetched: serde_json::Value = get(&client, "test-key", &format!("{}/GET", server.uri()))
|
||||
.await
|
||||
.unwrap();
|
||||
let posted: serde_json::Value = post(
|
||||
&client,
|
||||
"test-key",
|
||||
&format!("{}/POST", server.uri()),
|
||||
&serde_json::json!({}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(fetched["ok"].as_bool().unwrap());
|
||||
assert!(posted["ok"].as_bool().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_category_ids_match_the_selected_class() {
|
||||
let response: ApiResponse<Vec<SearchCategory>> = serde_json::from_str(r#"{"data":[{"id":6,"slug":"mc-mods","name":"Mods","classId":null},{"id":11,"slug":"magic","name":"Magic","classId":6},{"id":22,"slug":"magic","name":"Magic","classId":4471}]}"#).unwrap();
|
||||
|
||||
@@ -292,7 +292,7 @@ fn modpack_versions_are_not_limited_to_hardcoded_loaders() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn content_download_skips_an_existing_filename() {
|
||||
async fn content_download_rejects_an_unverifiable_existing_filename() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("example.jar");
|
||||
std::fs::write(&path, b"existing").unwrap();
|
||||
@@ -304,11 +304,11 @@ async fn content_download_skips_an_existing_filename() {
|
||||
hashes: HashMap::new(),
|
||||
}]);
|
||||
|
||||
let outcome = download_version_file(&crate::net::HttpClient::new(), &version, directory.path())
|
||||
let error = download_version_file(&crate::net::HttpClient::new(), &version, directory.path())
|
||||
.await
|
||||
.unwrap();
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(outcome, DownloadOutcome::SkippedExisting(path));
|
||||
assert!(error.to_string().contains("does not match"));
|
||||
assert_eq!(
|
||||
std::fs::read(directory.path().join("example.jar")).unwrap(),
|
||||
b"existing"
|
||||
|
||||
+49
-4
@@ -202,10 +202,19 @@ async fn quilt_fetch_profile_parses_libraries() {
|
||||
async fn fabric_and_quilt_download_libraries_into_the_shared_cache() {
|
||||
let server = MockServer::start().await;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
for (name, content) in [("fabric", "fabric jar"), ("quilt", "quilt jar")] {
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
use std::io::Write;
|
||||
zip.start_file(
|
||||
"META-INF/MANIFEST.MF",
|
||||
zip::write::SimpleFileOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
zip.write_all(b"Manifest-Version: 1.0\n").unwrap();
|
||||
let jar = zip.finish().unwrap().into_inner();
|
||||
for name in ["fabric", "quilt"] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/example/{name}/1.0/{name}-1.0.jar")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_string(content))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(jar.clone()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
@@ -238,7 +247,7 @@ async fn fabric_and_quilt_download_libraries_into_the_shared_cache() {
|
||||
download_fabric_libraries(&client, &fabric, temp.path())
|
||||
.await
|
||||
.unwrap();
|
||||
for (name, content) in [("fabric", "fabric jar"), ("quilt", "quilt jar")] {
|
||||
for name in ["fabric", "quilt"] {
|
||||
assert_eq!(
|
||||
std::fs::read(
|
||||
rmcl::storage::MetadataPaths::new(temp.path())
|
||||
@@ -246,11 +255,47 @@ async fn fabric_and_quilt_download_libraries_into_the_shared_cache() {
|
||||
.join(format!("example/{name}/1.0/{name}-1.0.jar"))
|
||||
)
|
||||
.unwrap(),
|
||||
content.as_bytes()
|
||||
jar
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fabric_replaces_a_truncated_cached_library() {
|
||||
let server = MockServer::start().await;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
use std::io::Write;
|
||||
zip.start_file("valid.txt", zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(b"ok").unwrap();
|
||||
let jar = zip.finish().unwrap().into_inner();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/example/fabric/1.0/fabric-1.0.jar"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(jar.clone()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let profile = FabricProfile {
|
||||
id: "fabric".into(),
|
||||
main_class: String::new(),
|
||||
libraries: vec![FabricLibrary {
|
||||
name: "example:fabric:1.0".into(),
|
||||
url: server.uri(),
|
||||
}],
|
||||
};
|
||||
let destination = rmcl::storage::MetadataPaths::new(temp.path())
|
||||
.libraries()
|
||||
.join("example/fabric/1.0/fabric-1.0.jar");
|
||||
std::fs::create_dir_all(destination.parent().unwrap()).unwrap();
|
||||
std::fs::write(&destination, b"truncated").unwrap();
|
||||
|
||||
download_fabric_libraries(&HttpClient::new(), &profile, temp.path())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(destination).unwrap(), jar);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn neoforge_fetch_versions_filters_by_prefix() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
+173
-27
@@ -12,6 +12,11 @@ use rmcl::net::mojang::{
|
||||
fetch_version_manifest_from, fetch_version_meta_with_raw,
|
||||
};
|
||||
|
||||
fn sha1(bytes: &[u8]) -> String {
|
||||
use sha1::Digest;
|
||||
format!("{:x}", sha1::Sha1::digest(bytes))
|
||||
}
|
||||
|
||||
fn synthetic_manifest() -> serde_json::Value {
|
||||
json!({
|
||||
"latest": { "release": "1.20.1", "snapshot": "24w01a" },
|
||||
@@ -79,12 +84,10 @@ async fn fetch_version_manifest_parses_synthetic_response() {
|
||||
async fn fetch_version_meta_returns_struct_and_raw_bytes() {
|
||||
let server = MockServer::start().await;
|
||||
let body_json = synthetic_version_meta();
|
||||
// serialise once so we can assert the raw bytes equal what the mock
|
||||
// actually sent (wiremock re-serialises the json, so we have to match
|
||||
// its output format)
|
||||
let body = serde_json::to_vec(&body_json).unwrap();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/1.20.1.json"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(body_json.clone()))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(body.clone()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
@@ -93,7 +96,7 @@ async fn fetch_version_meta_returns_struct_and_raw_bytes() {
|
||||
id: "1.20.1".to_string(),
|
||||
version_type: "release".to_string(),
|
||||
url: format!("{}/1.20.1.json", server.uri()),
|
||||
sha1: "0".repeat(40),
|
||||
sha1: sha1(&body),
|
||||
};
|
||||
|
||||
let (meta, raw) = fetch_version_meta_with_raw(&HttpClient::new(), &entry)
|
||||
@@ -111,6 +114,27 @@ async fn fetch_version_meta_returns_struct_and_raw_bytes() {
|
||||
assert_eq!(reparsed["mainClass"], "net.minecraft.client.main.Main");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_metadata_rejects_a_wrong_manifest_hash() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/version.json"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(synthetic_version_meta()))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let entry = VersionEntry {
|
||||
id: "1.20.1".to_owned(),
|
||||
version_type: "release".to_owned(),
|
||||
url: format!("{}/version.json", server.uri()),
|
||||
sha1: "0".repeat(40),
|
||||
};
|
||||
assert!(
|
||||
fetch_version_meta_with_raw(&HttpClient::new(), &entry)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
// constructs a minimal VersionMeta with a single library pointing at the
|
||||
// wiremock server. lets download_libraries hit synthetic URLs without any
|
||||
// production-side URL override.
|
||||
@@ -136,8 +160,8 @@ fn meta_with_one_library(server_uri: &str) -> VersionMeta {
|
||||
artifact: Some(Artifact {
|
||||
url: format!("{server_uri}/slf4j.jar"),
|
||||
path: "org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar".to_string(),
|
||||
sha1: "0".repeat(40),
|
||||
size: 11,
|
||||
sha1: sha1(b"jar-bytes"),
|
||||
size: b"jar-bytes".len() as u64,
|
||||
}),
|
||||
classifiers: None,
|
||||
},
|
||||
@@ -221,7 +245,10 @@ async fn download_libraries_redownloads_corrupted_cache() {
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let meta = meta_with_one_library(&server.uri());
|
||||
let mut meta = meta_with_one_library(&server.uri());
|
||||
let artifact = meta.libraries[0].downloads.artifact.as_mut().unwrap();
|
||||
artifact.sha1 = sha1(b"fresh-bytes");
|
||||
artifact.size = b"fresh-bytes".len() as u64;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let existing = tmp
|
||||
.path()
|
||||
@@ -237,33 +264,61 @@ async fn download_libraries_redownloads_corrupted_cache() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_assets_from_writes_index_and_assets() {
|
||||
// exercises the full path: index fetch + write, then per-asset download
|
||||
// from the configurable assets base. uses download_assets_from so the
|
||||
// hardcoded ASSETS_BASE_URL stays out of the way.
|
||||
async fn library_rejects_wrong_download_bytes_and_unsafe_paths() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/assets/index.json"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"objects": {
|
||||
"minecraft/lang/en_us.json": {
|
||||
"hash": "ab1234567890abcdef1234567890abcdef123456",
|
||||
"size": 11
|
||||
}
|
||||
}
|
||||
})))
|
||||
.and(path("/slf4j.jar"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"wrong".to_vec()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
// asset hash starts with "ab" so the per-asset URL is /<base>/ab/<hash>.
|
||||
let mut meta = meta_with_one_library(&server.uri());
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let library = temp
|
||||
.path()
|
||||
.join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar");
|
||||
assert!(
|
||||
download_libraries(&HttpClient::new(), &meta, temp.path())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(!library.exists());
|
||||
|
||||
meta.libraries[0].downloads.artifact.as_mut().unwrap().path =
|
||||
"../../../../escape.jar".to_owned();
|
||||
assert!(
|
||||
download_libraries(&HttpClient::new(), &meta, temp.path())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(!temp.path().join("escape.jar").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_assets_from_writes_index_and_assets() {
|
||||
let server = MockServer::start().await;
|
||||
let hash = sha1(b"asset-bytes");
|
||||
let index = serde_json::to_vec(&json!({
|
||||
"objects": {
|
||||
"minecraft/lang/en_us.json": {"hash": hash, "size": b"asset-bytes".len()}
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/cdn/ab/ab1234567890abcdef1234567890abcdef123456"))
|
||||
.and(path("/assets/index.json"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(index.clone()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/cdn/{}/{}", &hash[..2], hash)))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"asset-bytes".to_vec()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let meta = meta_with_one_library(&server.uri());
|
||||
let mut meta = meta_with_one_library(&server.uri());
|
||||
meta.asset_index.sha1 = sha1(&index);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cdn_base = format!("{}/cdn", server.uri());
|
||||
|
||||
@@ -275,7 +330,9 @@ async fn download_assets_from_writes_index_and_assets() {
|
||||
assert!(index_path.exists(), "index file missing");
|
||||
let asset_path = tmp
|
||||
.path()
|
||||
.join("cache/minecraft/assets/objects/ab/ab1234567890abcdef1234567890abcdef123456");
|
||||
.join("cache/minecraft/assets/objects")
|
||||
.join(&hash[..2])
|
||||
.join(&hash);
|
||||
assert!(asset_path.exists(), "asset file missing");
|
||||
assert_eq!(std::fs::read(&asset_path).unwrap(), b"asset-bytes");
|
||||
}
|
||||
@@ -286,14 +343,16 @@ async fn download_assets_writes_index_when_objects_is_empty() {
|
||||
// path without triggering individual asset downloads (which go to the
|
||||
// hardcoded ASSETS_BASE_URL and can't be wiremocked here).
|
||||
let server = MockServer::start().await;
|
||||
let index = serde_json::to_vec(&json!({"objects": {}})).unwrap();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/assets/index.json"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"objects": {}})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(index.clone()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let meta = meta_with_one_library(&server.uri());
|
||||
let mut meta = meta_with_one_library(&server.uri());
|
||||
meta.asset_index.sha1 = sha1(&index);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
download_assets(&HttpClient::new(), &meta, tmp.path())
|
||||
@@ -310,6 +369,93 @@ async fn download_assets_writes_index_when_objects_is_empty() {
|
||||
assert!(body.get("objects").is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_cached_index_is_refetched() {
|
||||
let server = MockServer::start().await;
|
||||
let body = serde_json::to_vec(&json!({"objects": {}})).unwrap();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/assets/index.json"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(body.clone()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut meta = meta_with_one_library(&server.uri());
|
||||
meta.asset_index.sha1 = sha1(&body);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let index_path = tmp.path().join("cache/minecraft/assets/indexes/5.json");
|
||||
std::fs::create_dir_all(index_path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&index_path, b"{\"objects\":{\"fake\":{}}}").unwrap();
|
||||
|
||||
download_assets(&HttpClient::new(), &meta, tmp.path())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(index_path).unwrap(), body);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_asset_hash_returns_an_error_without_escaping_or_panicking() {
|
||||
let server = MockServer::start().await;
|
||||
let body =
|
||||
serde_json::to_vec(&json!({"objects": {"bad": {"hash": "aé/../escape", "size": 1}}}))
|
||||
.unwrap();
|
||||
let mut meta = meta_with_one_library(&server.uri());
|
||||
meta.asset_index.sha1 = sha1(&body);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let index_path = tmp.path().join("cache/minecraft/assets/indexes/5.json");
|
||||
std::fs::create_dir_all(index_path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&index_path, body).unwrap();
|
||||
|
||||
assert!(
|
||||
download_assets(&HttpClient::new(), &meta, tmp.path())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(!tmp.path().join("escape").exists());
|
||||
meta.asset_index.id = "../outside".to_owned();
|
||||
assert!(
|
||||
download_assets(&HttpClient::new(), &meta, tmp.path())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn downloaded_asset_must_match_index_hash_and_size() {
|
||||
let server = MockServer::start().await;
|
||||
let hash = sha1(b"expected");
|
||||
let body = serde_json::to_vec(&json!({"objects": {"one": {"hash": hash, "size": 8}}})).unwrap();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/assets/index.json"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(body.clone()))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/cdn/{}/{}", &hash[..2], hash)))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"bad bytes".to_vec()))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut meta = meta_with_one_library(&server.uri());
|
||||
meta.asset_index.sha1 = sha1(&body);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let asset = tmp
|
||||
.path()
|
||||
.join("cache/minecraft/assets/objects")
|
||||
.join(&hash[..2])
|
||||
.join(&hash);
|
||||
|
||||
assert!(
|
||||
download_assets_from(
|
||||
&HttpClient::new(),
|
||||
&meta,
|
||||
tmp.path(),
|
||||
&format!("{}/cdn", server.uri())
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(!asset.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_libraries_downloads_and_extracts_natives() {
|
||||
// pre-1.13-era library: no artifact, only a natives classifier for the
|
||||
|
||||
@@ -49,6 +49,30 @@ async fn get_json_retries_5xx_then_succeeds() {
|
||||
assert!(result.ok);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn get_json_retries_rate_limit() {
|
||||
let server = MockServer::start().await;
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/limited"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
if attempts.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
ResponseTemplate::new(429)
|
||||
} else {
|
||||
ResponseTemplate::new(200).set_body_json(json!({"ok": true}))
|
||||
}
|
||||
})
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let result: ApiResponse = client_without_timeout()
|
||||
.get_json(&format!("{}/limited", server.uri()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.ok);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_json_fails_fast_on_4xx() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
Reference in new issue
Block a user