diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 54876d19..67665c4e 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -38,7 +38,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX)) + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) } /// Add an image within a decoded texel budget, inside the caller's edit diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 85590d9d..bcff2435 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -1,6 +1,6 @@ //! Decoding imported image resources (fills, alphas, stencils). -use crate::{FormatError, MAX_IMAGE_SIZE, Result}; +use crate::{FormatError, MAX_IMAGE_SIZE, MAX_RESOURCE_TEXELS, Result}; /// A decoded image: RGBA as 0..1 floats in the file's own encoding (8/16-bit files stay /// sRGB-encoded; `srgb` says so), row-major, top row first. @@ -15,7 +15,7 @@ pub struct DecodedImage { /// Decode PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR bytes. pub fn decode_image(bytes: &[u8]) -> Result { - decode_image_within(bytes, u64::MAX) + decode_image_within(bytes, MAX_RESOURCE_TEXELS) } /// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the @@ -100,4 +100,15 @@ mod tests { assert!(matches!(decode_image_within(&png, 63), Err(FormatError::TooLarge(_)))); assert!(decode_image(&png).is_ok()); } + + #[test] + fn the_default_decoder_refuses_more_than_the_resource_texel_budget_from_the_header() { + // An 18-byte TGA header: 16384² is inside the edge limit but far over 64 M texels. + let mut header = [0u8; 18]; + header[2] = 2; + header[12..14].copy_from_slice(&16_384u16.to_le_bytes()); + header[14..16].copy_from_slice(&16_384u16.to_le_bytes()); + header[16] = 24; + assert!(matches!(decode_image(&header), Err(FormatError::TooLarge(_)))); + } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 6e57432e..d8550531 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -95,6 +95,10 @@ pub(crate) fn guard(kind: &'static str, f: impl FnOnce() -> Result) -> Res /// Largest image edge accepted or produced anywhere in this crate. pub const MAX_IMAGE_SIZE: u32 = 16_384; +/// Most texels an imported image resource may decode to by default (8192 × 8192). +/// Larger images are refused from their header before any pixels are decoded. +pub const MAX_RESOURCE_TEXELS: u64 = 1 << 26; + /// Read a whole file, refusing files over `cap` bytes. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> {