From be88cf921f21438234416bc53ec812b31edc1eeb Mon Sep 17 00:00:00 2001 From: "Calum H. (IMB11)" Date: Wed, 11 Nov 2026 15:10:39 +0000 Subject: [PATCH 1/2] fix: downsize icons above max res --- apps/app/src/api/thumbnails.rs | 11 +- packages/app-lib/src/api/instance/icon.rs | 100 ++++++++++++++---- .../instances/commands/create_instance.rs | 46 ++++---- 3 files changed, 108 insertions(+), 49 deletions(-) diff --git a/apps/app/src/api/thumbnails.rs b/apps/app/src/api/thumbnails.rs index ebbe197df8a..1e909fca6e6 100644 --- a/apps/app/src/api/thumbnails.rs +++ b/apps/app/src/api/thumbnails.rs @@ -72,13 +72,10 @@ fn create_thumbnail( return Ok(target); } std::fs::create_dir_all(cache)?; - let mut reader = image::ImageReader::open(path)?.with_guessed_format()?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(256 * 1024 * 1024); - limits.max_image_width = Some(16384); - limits.max_image_height = Some(16384); - reader.limits(limits); - let image = reader.decode().map_err(std::io::Error::other)?; + let image = image::ImageReader::open(path)? + .with_guessed_format()? + .decode() + .map_err(std::io::Error::other)?; let thumbnail = image.thumbnail(size, size); drop(image); let temporary = target.with_extension("tmp"); diff --git a/packages/app-lib/src/api/instance/icon.rs b/packages/app-lib/src/api/instance/icon.rs index 43676e6c44e..ea7c652f834 100644 --- a/packages/app-lib/src/api/instance/icon.rs +++ b/packages/app-lib/src/api/instance/icon.rs @@ -16,8 +16,6 @@ use std::path::{Path, PathBuf}; const INSTANCE_ICON_MAX_BYTES: usize = 4 * 1024 * 1024; const INSTANCE_ICON_MAX_DIMENSION: u32 = 512; -const INSTANCE_ICON_MAX_SOURCE_DIMENSION: u32 = 8_192; -const INSTANCE_ICON_MAX_DECODE_BYTES: u64 = 64 * 1024 * 1024; const GENERATED_ICON_SIZE: u32 = 256; const MAX_SYMBOL_BYTES: usize = 4 * 1024 * 1024; const MAX_SYMBOL_DIMENSION: u32 = 4096; @@ -426,28 +424,20 @@ fn normalize_raster(reader: R) -> crate::Result where R: BufRead + Seek, { - let mut reader = image::ImageReader::new(reader) + let image = image::ImageReader::new(reader) .with_guessed_format() .context(ErrorKind::InputError( "could not identify instance icon format".to_string(), + ))? + .decode() + .context(ErrorKind::InputError( + "could not decode instance icon".to_string(), ))?; - let mut limits = image::Limits::default(); - limits.max_image_width = Some(INSTANCE_ICON_MAX_SOURCE_DIMENSION); - limits.max_image_height = Some(INSTANCE_ICON_MAX_SOURCE_DIMENSION); - limits.max_alloc = Some(INSTANCE_ICON_MAX_DECODE_BYTES); - reader.limits(limits); - - let image = reader.decode().context(ErrorKind::InputError( - "could not decode instance icon".to_string(), - ))?; let image = if image.width() > INSTANCE_ICON_MAX_DIMENSION || image.height() > INSTANCE_ICON_MAX_DIMENSION { - image.resize( - INSTANCE_ICON_MAX_DIMENSION, - INSTANCE_ICON_MAX_DIMENSION, - image::imageops::FilterType::Lanczos3, - ) + image + .thumbnail(INSTANCE_ICON_MAX_DIMENSION, INSTANCE_ICON_MAX_DIMENSION) } else { image }; @@ -479,8 +469,16 @@ fn inspect_legacy_icon(icon_path: &Path) -> crate::Result { return Ok(LegacyIconAction::Remove); } - if metadata.len() < INSTANCE_ICON_MAX_BYTES as u64 - && image::guess_format(bytes).ok() == Some(image::ImageFormat::Png) + let is_png = + image::guess_format(bytes).ok() == Some(image::ImageFormat::Png); + if is_png + && metadata.len() < INSTANCE_ICON_MAX_BYTES as u64 + && ImageReader::with_format(reader, ImageFormat::Png) + .into_dimensions() + .is_ok_and(|(width, height)| { + width <= INSTANCE_ICON_MAX_DIMENSION + && height <= INSTANCE_ICON_MAX_DIMENSION + }) { return Ok(LegacyIconAction::Keep); } @@ -620,11 +618,29 @@ fn svg_not_supported_error() -> crate::Error { #[cfg(test)] mod tests { use super::{ - GENERATED_ICON_SIZE, ValidatedIconBackground, render_generated_icon, + GENERATED_ICON_SIZE, INSTANCE_ICON_MAX_DIMENSION, LegacyIconAction, + ValidatedIconBackground, inspect_legacy_icon, normalize_raster, + render_generated_icon, }; use image::{DynamicImage, ImageFormat, Rgba, RgbaImage}; use std::io::Cursor; + fn blank_png(width: u32, height: u32) -> Vec { + let mut bytes = Cursor::new(Vec::new()); + DynamicImage::ImageRgba8(RgbaImage::new(width, height)) + .write_to(&mut bytes, ImageFormat::Png) + .unwrap(); + bytes.into_inner() + } + + fn normalized_dimensions(source: Vec) -> (u32, u32) { + let bytes = normalize_raster(Cursor::new(source)).unwrap(); + let icon = + image::load_from_memory_with_format(&bytes, ImageFormat::Png) + .unwrap(); + (icon.width(), icon.height()) + } + fn png(pixel: Rgba) -> Vec { let mut bytes = Cursor::new(Vec::new()); DynamicImage::ImageRgba8(RgbaImage::from_pixel(1, 1, pixel)) @@ -652,6 +668,50 @@ mod tests { assert_eq!(icon.get_pixel(0, 0), &Rgba([105, 60, 40, 255])); } + #[test] + fn normalize_raster_downscales_large_rgba_icon() { + assert_eq!( + normalized_dimensions(blank_png(4500, 4500)), + (INSTANCE_ICON_MAX_DIMENSION, INSTANCE_ICON_MAX_DIMENSION) + ); + } + + #[test] + fn normalize_raster_downscales_wide_icon_preserving_aspect() { + assert_eq!( + normalized_dimensions(blank_png(10_240, 1_024)), + ( + INSTANCE_ICON_MAX_DIMENSION, + INSTANCE_ICON_MAX_DIMENSION / 10 + ) + ); + } + + #[test] + fn normalize_raster_keeps_small_icon_size() { + assert_eq!(normalized_dimensions(blank_png(64, 32)), (64, 32)); + } + + #[test] + fn legacy_icon_normalizes_oversized_png() { + let directory = tempfile::tempdir().unwrap(); + let small = directory.path().join("small.png"); + let large = directory.path().join("large.png"); + std::fs::write(&small, blank_png(INSTANCE_ICON_MAX_DIMENSION, 64)) + .unwrap(); + std::fs::write(&large, blank_png(INSTANCE_ICON_MAX_DIMENSION + 1, 64)) + .unwrap(); + + assert!(matches!( + inspect_legacy_icon(&small).unwrap(), + LegacyIconAction::Keep + )); + assert!(matches!( + inspect_legacy_icon(&large).unwrap(), + LegacyIconAction::Normalize + )); + } + #[test] fn generated_icon_rejects_invalid_symbol_data() { assert!( diff --git a/packages/app-lib/src/state/instances/commands/create_instance.rs b/packages/app-lib/src/state/instances/commands/create_instance.rs index 6eb548a256d..2530a296809 100644 --- a/packages/app-lib/src/state/instances/commands/create_instance.rs +++ b/packages/app-lib/src/state/instances/commands/create_instance.rs @@ -58,12 +58,8 @@ pub(crate) async fn create_instance( None }; - let icon_path = resolve_icon_path( - input.icon_path.as_deref(), - matches!(&input.link, InstanceLink::SharedInstance { .. }), - state, - ) - .await?; + let icon_path = + resolve_icon_path(input.icon_path.as_deref(), true, state).await?; let now = Utc::now(); let instance_id = format!("local:{}", Uuid::new_v4()); let content_set_id = format!("content-set:{}", Uuid::new_v4()); @@ -200,7 +196,7 @@ async fn path_available( pub(crate) async fn resolve_icon_path( icon_path: Option<&str>, - ignore_missing_remote_icon: bool, + ignore_remote_icon_errors: bool, state: &State, ) -> crate::Result> { let Some(icon) = icon_path else { @@ -208,24 +204,30 @@ pub(crate) async fn resolve_icon_path( }; let file = if icon.starts_with("https://") || icon.starts_with("http://") { - let bytes = match fetch::fetch( - icon, - None, - None, - None, - &state.fetch_semaphore, - &state.pool, - ) - .await - { - Ok(bytes) => bytes, - Err(error) if ignore_missing_remote_icon => { - tracing::warn!("Error while getting instance icon: {error}"); + let cached = async { + let bytes = fetch::fetch( + icon, + None, + None, + None, + &state.fetch_semaphore, + &state.pool, + ) + .await?; + crate::api::instance::cache_icon(bytes, state).await + } + .await; + match cached { + Ok(file) => file, + Err(error) if ignore_remote_icon_errors => { + tracing::warn!( + icon, + "Error while getting instance icon: {error}" + ); return Ok(None); } Err(error) => return Err(error), - }; - crate::api::instance::cache_icon(bytes, state).await? + } } else { crate::api::instance::cache_icon_from_path( &state.directories.caches_dir().join(icon), From b64e12af223d6273dc6b2df3c57ab49eb9e3fc73 Mon Sep 17 00:00:00 2001 From: "Calum H. (IMB11)" Date: Wed, 11 Nov 2026 15:18:59 +0000 Subject: [PATCH 2/2] fix: rev --- packages/app-lib/src/api/instance/icon.rs | 91 ++++++----------------- 1 file changed, 21 insertions(+), 70 deletions(-) diff --git a/packages/app-lib/src/api/instance/icon.rs b/packages/app-lib/src/api/instance/icon.rs index ea7c652f834..39102c67a43 100644 --- a/packages/app-lib/src/api/instance/icon.rs +++ b/packages/app-lib/src/api/instance/icon.rs @@ -16,6 +16,9 @@ use std::path::{Path, PathBuf}; const INSTANCE_ICON_MAX_BYTES: usize = 4 * 1024 * 1024; const INSTANCE_ICON_MAX_DIMENSION: u32 = 512; +const INSTANCE_ICON_MAX_DECODE_BYTES: u64 = 256 * 1024 * 1024; +static INSTANCE_ICON_DECODES: tokio::sync::Semaphore = + tokio::sync::Semaphore::const_new(2); const GENERATED_ICON_SIZE: u32 = 256; const MAX_SYMBOL_BYTES: usize = 4 * 1024 * 1024; const MAX_SYMBOL_DIMENSION: u32 = 4096; @@ -261,7 +264,9 @@ pub(crate) async fn cache_icon( bytes: Bytes, state: &State, ) -> crate::Result { + let permit = INSTANCE_ICON_DECODES.acquire().await?; let bytes = tokio::task::spawn_blocking(move || { + let _permit = permit; if looks_like_svg(&bytes) { return Err(svg_not_supported_error()); } @@ -278,7 +283,9 @@ pub(crate) async fn cache_icon_from_path( state: &State, ) -> crate::Result { let icon_path = icon_path.to_path_buf(); + let permit = INSTANCE_ICON_DECODES.acquire().await?; let bytes = tokio::task::spawn_blocking(move || { + let _permit = permit; let file = StdFile::open(&icon_path).context(ErrorKind::InputError( format!("could not open instance icon {}", icon_path.display()), ))?; @@ -424,20 +431,26 @@ fn normalize_raster(reader: R) -> crate::Result where R: BufRead + Seek, { - let image = image::ImageReader::new(reader) + let mut reader = image::ImageReader::new(reader) .with_guessed_format() .context(ErrorKind::InputError( "could not identify instance icon format".to_string(), - ))? - .decode() - .context(ErrorKind::InputError( - "could not decode instance icon".to_string(), ))?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some(INSTANCE_ICON_MAX_DECODE_BYTES); + reader.limits(limits); + + let image = reader.decode().context(ErrorKind::InputError( + "could not decode instance icon".to_string(), + ))?; let image = if image.width() > INSTANCE_ICON_MAX_DIMENSION || image.height() > INSTANCE_ICON_MAX_DIMENSION { - image - .thumbnail(INSTANCE_ICON_MAX_DIMENSION, INSTANCE_ICON_MAX_DIMENSION) + image.resize( + INSTANCE_ICON_MAX_DIMENSION, + INSTANCE_ICON_MAX_DIMENSION, + FilterType::Lanczos3, + ) } else { image }; @@ -618,29 +631,11 @@ fn svg_not_supported_error() -> crate::Error { #[cfg(test)] mod tests { use super::{ - GENERATED_ICON_SIZE, INSTANCE_ICON_MAX_DIMENSION, LegacyIconAction, - ValidatedIconBackground, inspect_legacy_icon, normalize_raster, - render_generated_icon, + GENERATED_ICON_SIZE, ValidatedIconBackground, render_generated_icon, }; use image::{DynamicImage, ImageFormat, Rgba, RgbaImage}; use std::io::Cursor; - fn blank_png(width: u32, height: u32) -> Vec { - let mut bytes = Cursor::new(Vec::new()); - DynamicImage::ImageRgba8(RgbaImage::new(width, height)) - .write_to(&mut bytes, ImageFormat::Png) - .unwrap(); - bytes.into_inner() - } - - fn normalized_dimensions(source: Vec) -> (u32, u32) { - let bytes = normalize_raster(Cursor::new(source)).unwrap(); - let icon = - image::load_from_memory_with_format(&bytes, ImageFormat::Png) - .unwrap(); - (icon.width(), icon.height()) - } - fn png(pixel: Rgba) -> Vec { let mut bytes = Cursor::new(Vec::new()); DynamicImage::ImageRgba8(RgbaImage::from_pixel(1, 1, pixel)) @@ -668,50 +663,6 @@ mod tests { assert_eq!(icon.get_pixel(0, 0), &Rgba([105, 60, 40, 255])); } - #[test] - fn normalize_raster_downscales_large_rgba_icon() { - assert_eq!( - normalized_dimensions(blank_png(4500, 4500)), - (INSTANCE_ICON_MAX_DIMENSION, INSTANCE_ICON_MAX_DIMENSION) - ); - } - - #[test] - fn normalize_raster_downscales_wide_icon_preserving_aspect() { - assert_eq!( - normalized_dimensions(blank_png(10_240, 1_024)), - ( - INSTANCE_ICON_MAX_DIMENSION, - INSTANCE_ICON_MAX_DIMENSION / 10 - ) - ); - } - - #[test] - fn normalize_raster_keeps_small_icon_size() { - assert_eq!(normalized_dimensions(blank_png(64, 32)), (64, 32)); - } - - #[test] - fn legacy_icon_normalizes_oversized_png() { - let directory = tempfile::tempdir().unwrap(); - let small = directory.path().join("small.png"); - let large = directory.path().join("large.png"); - std::fs::write(&small, blank_png(INSTANCE_ICON_MAX_DIMENSION, 64)) - .unwrap(); - std::fs::write(&large, blank_png(INSTANCE_ICON_MAX_DIMENSION + 1, 64)) - .unwrap(); - - assert!(matches!( - inspect_legacy_icon(&small).unwrap(), - LegacyIconAction::Keep - )); - assert!(matches!( - inspect_legacy_icon(&large).unwrap(), - LegacyIconAction::Normalize - )); - } - #[test] fn generated_icon_rejects_invalid_symbol_data() { assert!(