//! Thumbnails of pictures: decode a PNG, JPEG, WebP or GIF and write a small lossless WebP no wider or taller //! than [`THUMB_EDGE`]. It is pure: bytes in, bytes out, no file access and no external program. //! //! The decoder runs under hard limits. A picture that claims more than [`MAX_DIMENSION`] pixels on a side, or //! would need more than [`MAX_ALLOC_BYTES`] to decode, is refused from its header, before any large buffer is //! allocated. A refused picture is `Invalid("bad_image")`; the thumbnail worker marks such a file `failed`. use std::io::Cursor; use image::{ImageFormat, ImageReader, Limits}; use crate::error::{Error, Result}; /// Longest edge of a thumbnail, in pixels. The aspect ratio is kept. pub const THUMB_EDGE: u32 = 320; /// Largest source picture the worker reads, in bytes. Larger files get no thumbnail. pub const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; /// Largest width or height the decoder accepts, in pixels: 10000 by 10000 is 100 megapixels. pub const MAX_DIMENSION: u32 = 10_000; /// Most memory the decoder may allocate for one picture: 256 MiB. The thumbnail worker decodes one picture at a /// time, so this and [`MAX_SOURCE_BYTES`] bound its peak. pub const MAX_ALLOC_BYTES: u64 = 256 * 1024 * 1024; /// The formats that get thumbnails. Anything else is not decoded. const FORMATS: [ImageFormat; 4] = [ ImageFormat::Png, ImageFormat::Jpeg, ImageFormat::WebP, ImageFormat::Gif, ]; /// Decodes `source` under the limits and returns a WebP thumbnail of it. /// /// The format is found from the leading bytes, never from a file name, and must be one of [`FORMATS`]. Any /// decoder error, including a limit, is `Invalid("bad_image")`. Nothing here panics on hostile input. pub fn make_thumbnail(source: &[u8]) -> Result> { let bad = || Error::Invalid("bad_image".into()); let mut reader = ImageReader::new(Cursor::new(source)) .with_guessed_format() .map_err(|_| bad())?; if !reader.format().is_some_and(|f| FORMATS.contains(&f)) { return Err(bad()); } // The header alone gives the size of the decoded picture. A picture that would need more than the // allocation limit is refused here, before the decoder sizes any buffer, whatever its format. let (width, height) = ImageReader::new(Cursor::new(source)) .with_guessed_format() .map_err(|_| bad())? .into_dimensions() .map_err(|_| bad())?; if u64::from(width) * u64::from(height) * 4 > MAX_ALLOC_BYTES { return Err(bad()); } let mut limits = Limits::default(); limits.max_image_width = Some(MAX_DIMENSION); limits.max_image_height = Some(MAX_DIMENSION); limits.max_alloc = Some(MAX_ALLOC_BYTES); reader.limits(limits); let picture = reader.decode().map_err(|_| bad())?; let thumb = picture.thumbnail(THUMB_EDGE, THUMB_EDGE); let mut out = Cursor::new(Vec::new()); thumb .write_to(&mut out, ImageFormat::WebP) .map_err(|_| bad())?; Ok(out.into_inner()) } #[cfg(test)] mod tests { use super::*; /// A 4x2 PNG made by the encoder, the source of the tests below. fn small_png() -> Vec { let img = image::RgbaImage::from_pixel(4, 2, image::Rgba([200, 30, 30, 255])); let mut out = Cursor::new(Vec::new()); img.write_to(&mut out, ImageFormat::Png).unwrap(); out.into_inner() } /// CRC-32 (the PNG chunk checksum), bit by bit. Only the tests use it. fn crc32(bytes: &[u8]) -> u32 { let mut crc = !0u32; for &byte in bytes { crc ^= u32::from(byte); for _ in 0..8 { crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; } } !crc } #[test] fn a_small_png_becomes_a_webp_thumbnail() { let thumb = make_thumbnail(&small_png()).unwrap(); assert_eq!(&thumb[..4], b"RIFF"); assert_eq!(&thumb[8..12], b"WEBP"); assert!(image::load_from_memory(&thumb).is_ok()); } /// A PNG whose header claims 100000 by 100000 pixels. Its IHDR checksum is fixed up so that only the /// dimension limit can refuse it. It must fail cleanly, without a panic or a huge allocation. #[test] fn a_decompression_bomb_png_is_refused_without_a_panic() { let mut png = small_png(); // The IHDR chunk starts at byte 8: length (4), type (4), then width and height (4 each). assert_eq!(&png[12..16], b"IHDR"); png[16..20].copy_from_slice(&100_000u32.to_be_bytes()); png[20..24].copy_from_slice(&100_000u32.to_be_bytes()); let crc = crc32(&png[12..29]); png[29..33].copy_from_slice(&crc.to_be_bytes()); let result = make_thumbnail(&png); assert!( matches!(result, Err(Error::Invalid(ref m)) if m == "bad_image"), "a bomb must be refused: {result:?}" ); } #[test] fn non_pictures_are_refused() { assert!(make_thumbnail(b"plain text, not a picture").is_err()); assert!(make_thumbnail(b"").is_err()); } }