From d4889545487688610f3efd2d823b7c60cf5e36fe Mon Sep 17 00:00:00 2001 From: objz Date: Tue, 4 Aug 2026 21:02:35 +0200 Subject: [PATCH] fix(content): bound remote resource usage --- src/instance/import/curseforge.rs | 6 ++--- src/net/mod.rs | 24 +++++++++++++++++++ src/tui/input.rs | 5 +++- src/tui/tests/widgets/markdown.rs | 8 +++++++ src/tui/widgets/markdown.rs | 23 +++++++++++++++++- .../widgets/popups/import_modpack/state.rs | 5 +++- tests/net_retry.rs | 18 ++++++++++++++ 7 files changed, 82 insertions(+), 7 deletions(-) diff --git a/src/instance/import/curseforge.rs b/src/instance/import/curseforge.rs index 8590c72..5e9f180 100644 --- a/src/instance/import/curseforge.rs +++ b/src/instance/import/curseforge.rs @@ -1,7 +1,6 @@ // curseforge modpack archives: manifest.json references provider file ids, // while the overrides directory contains configs and other bundled files. -use std::io::Read; use std::path::Path; use serde::Deserialize; @@ -236,9 +235,8 @@ fn extract_overrides( if let Some(parent) = destination.parent() { std::fs::create_dir_all(parent)?; } - let mut bytes = Vec::new(); - entry.read_to_end(&mut bytes)?; - std::fs::write(destination, bytes)?; + let mut destination = std::fs::File::create(destination)?; + std::io::copy(&mut entry, &mut destination)?; } Ok(()) } diff --git a/src/net/mod.rs b/src/net/mod.rs index 644faaa..777b9dc 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -105,6 +105,30 @@ impl HttpClient { .await } + pub async fn get_bytes_limited(&self, url: &str, limit: usize) -> Result, NetError> { + get_with_retry(self, url, move |mut response| async move { + if response + .content_length() + .is_some_and(|length| length > limit as u64) + { + return Err(NetError::Parse(format!( + "Response exceeds the {limit}-byte limit" + ))); + } + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await? { + if bytes.len().saturating_add(chunk.len()) > limit { + return Err(NetError::Parse(format!( + "Response exceeds the {limit}-byte limit" + ))); + } + bytes.extend_from_slice(&chunk); + } + Ok(bytes) + }) + .await + } + pub async fn post_json(&self, url: &str, body: &B) -> Result where B: Serialize + ?Sized, diff --git a/src/tui/input.rs b/src/tui/input.rs index fed55e6..460f1c2 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -1006,7 +1006,10 @@ impl App { .await .map_err(|error| error.to_string())?; let bytes = client - .get_bytes(&url) + .get_bytes_limited( + &url, + crate::tui::widgets::markdown::MAX_PROJECT_IMAGE_BYTES, + ) .await .map_err(|error| error.to_string())?; tokio::task::spawn_blocking(move || { diff --git a/src/tui/tests/widgets/markdown.rs b/src/tui/tests/widgets/markdown.rs index 53d0077..b7d40ff 100644 --- a/src/tui/tests/widgets/markdown.rs +++ b/src/tui/tests/widgets/markdown.rs @@ -555,6 +555,14 @@ fn gif_images_decode_their_first_frame() { assert_eq!(image.height(), 1); } +#[test] +fn oversized_images_are_rejected_before_decoding() { + let image = image::DynamicImage::new_rgba8(super::MAX_PROJECT_IMAGE_DIMENSION + 1, 1); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); + assert!(super::decode_image(bytes.get_ref()).is_err()); +} + #[test] fn image_rows_align_fitted_images_to_the_bottom() { let picker = ratatui_image::picker::Picker::halfblocks(); diff --git a/src/tui/widgets/markdown.rs b/src/tui/widgets/markdown.rs index d635943..ab82033 100644 --- a/src/tui/widgets/markdown.rs +++ b/src/tui/widgets/markdown.rs @@ -30,6 +30,9 @@ use crate::instance::content::{ }; const MAX_DOCUMENT_WIDTH: u16 = 110; +pub(crate) const MAX_PROJECT_IMAGE_BYTES: usize = 16 * 1024 * 1024; +const MAX_PROJECT_IMAGE_DIMENSION: u32 = 8192; +const MAX_PROJECT_IMAGE_ALLOCATION: u64 = 64 * 1024 * 1024; struct TextBlock { source: String, @@ -225,13 +228,31 @@ pub fn image_urls(title: &str, body: &str) -> Vec { } pub fn decode_image(bytes: &[u8]) -> Result { - if let Ok(image) = image::load_from_memory(bytes) { + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .map_err(|error| error.to_string())?; + let mut limits = image::Limits::default(); + limits.max_image_width = Some(MAX_PROJECT_IMAGE_DIMENSION); + limits.max_image_height = Some(MAX_PROJECT_IMAGE_DIMENSION); + limits.max_alloc = Some(MAX_PROJECT_IMAGE_ALLOCATION); + reader.limits(limits); + if let Ok(image) = reader.decode() { return Ok(image); } let mut options = resvg::usvg::Options::default(); options.fontdb_mut().load_system_fonts(); let tree = resvg::usvg::Tree::from_data(bytes, &options).map_err(|error| error.to_string())?; let size = tree.size().to_int_size(); + let allocation = u64::from(size.width()) + .checked_mul(u64::from(size.height())) + .and_then(|pixels| pixels.checked_mul(4)) + .ok_or_else(|| "SVG image dimensions are too large".to_owned())?; + if size.width() > MAX_PROJECT_IMAGE_DIMENSION + || size.height() > MAX_PROJECT_IMAGE_DIMENSION + || allocation > MAX_PROJECT_IMAGE_ALLOCATION + { + return Err("SVG image dimensions are too large".to_owned()); + } let mut pixmap = resvg::tiny_skia::Pixmap::new(size.width(), size.height()) .ok_or_else(|| "SVG image dimensions are too large".to_owned())?; resvg::render( diff --git a/src/tui/widgets/popups/import_modpack/state.rs b/src/tui/widgets/popups/import_modpack/state.rs index fc96558..a5d80a0 100644 --- a/src/tui/widgets/popups/import_modpack/state.rs +++ b/src/tui/widgets/popups/import_modpack/state.rs @@ -842,7 +842,10 @@ fn spawn_project_page(request: crate::tui::widgets::content::discovery::ProjectP .await .map_err(|error| error.to_string())?; let bytes = client - .get_bytes(&url) + .get_bytes_limited( + &url, + crate::tui::widgets::markdown::MAX_PROJECT_IMAGE_BYTES, + ) .await .map_err(|error| error.to_string())?; tokio::task::spawn_blocking(move || { diff --git a/tests/net_retry.rs b/tests/net_retry.rs index 3e266f2..0d70804 100644 --- a/tests/net_retry.rs +++ b/tests/net_retry.rs @@ -103,6 +103,24 @@ async fn get_json_gives_up_after_max_retries() { ); } +#[tokio::test] +async fn get_bytes_limited_rejects_oversized_responses() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/large.bin")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![0; 9])) + .expect(1) + .mount(&server) + .await; + + let url = format!("{}/large.bin", server.uri()); + let error = client_without_timeout() + .get_bytes_limited(&url, 8) + .await + .unwrap_err(); + assert!(error.to_string().contains("8-byte limit")); +} + // ---------- download_file ---------- #[tokio::test(start_paused = true)]