forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

thumbs.rs130 lines, 5.1 KiBHistoryRawDownload
1//! Thumbnails of pictures: decode a PNG, JPEG, WebP or GIF and write a small lossless WebP no wider or taller
2//! than [`THUMB_EDGE`]. It is pure: bytes in, bytes out, no file access and no external program.
3//!
4//! The decoder runs under hard limits. A picture that claims more than [`MAX_DIMENSION`] pixels on a side, or
5//! would need more than [`MAX_ALLOC_BYTES`] to decode, is refused from its header, before any large buffer is
6//! allocated. A refused picture is `Invalid("bad_image")`; the thumbnail worker marks such a file `failed`.
7
8use std::io::Cursor;
9
10use image::{ImageFormat, ImageReader, Limits};
11
12use crate::error::{Error, Result};
13
14/// Longest edge of a thumbnail, in pixels. The aspect ratio is kept.
15pub const THUMB_EDGE: u32 = 320;
16
17/// Largest source picture the worker reads, in bytes. Larger files get no thumbnail.
18pub const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024;
19
20/// Largest width or height the decoder accepts, in pixels: 10000 by 10000 is 100 megapixels.
21pub const MAX_DIMENSION: u32 = 10_000;
22
23/// Most memory the decoder may allocate for one picture: 256 MiB. The thumbnail worker decodes one picture at a
24/// time, so this and [`MAX_SOURCE_BYTES`] bound its peak.
25pub const MAX_ALLOC_BYTES: u64 = 256 * 1024 * 1024;
26
27/// The formats that get thumbnails. Anything else is not decoded.
28const FORMATS: [ImageFormat; 4] = [
29 ImageFormat::Png,
30 ImageFormat::Jpeg,
31 ImageFormat::WebP,
32 ImageFormat::Gif,
33];
34
35/// Decodes `source` under the limits and returns a WebP thumbnail of it.
36///
37/// The format is found from the leading bytes, never from a file name, and must be one of [`FORMATS`]. Any
38/// decoder error, including a limit, is `Invalid("bad_image")`. Nothing here panics on hostile input.
39pub fn make_thumbnail(source: &[u8]) -> Result<Vec<u8>> {
40 let bad = || Error::Invalid("bad_image".into());
41 let mut reader = ImageReader::new(Cursor::new(source))
42 .with_guessed_format()
43 .map_err(|_| bad())?;
44 if !reader.format().is_some_and(|f| FORMATS.contains(&f)) {
45 return Err(bad());
46 }
47 // The header alone gives the size of the decoded picture. A picture that would need more than the
48 // allocation limit is refused here, before the decoder sizes any buffer, whatever its format.
49 let (width, height) = ImageReader::new(Cursor::new(source))
50 .with_guessed_format()
51 .map_err(|_| bad())?
52 .into_dimensions()
53 .map_err(|_| bad())?;
54 if u64::from(width) * u64::from(height) * 4 > MAX_ALLOC_BYTES {
55 return Err(bad());
56 }
57 let mut limits = Limits::default();
58 limits.max_image_width = Some(MAX_DIMENSION);
59 limits.max_image_height = Some(MAX_DIMENSION);
60 limits.max_alloc = Some(MAX_ALLOC_BYTES);
61 reader.limits(limits);
62 let picture = reader.decode().map_err(|_| bad())?;
63 let thumb = picture.thumbnail(THUMB_EDGE, THUMB_EDGE);
64 let mut out = Cursor::new(Vec::new());
65 thumb
66 .write_to(&mut out, ImageFormat::WebP)
67 .map_err(|_| bad())?;
68 Ok(out.into_inner())
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 /// A 4x2 PNG made by the encoder, the source of the tests below.
76 fn small_png() -> Vec<u8> {
77 let img = image::RgbaImage::from_pixel(4, 2, image::Rgba([200, 30, 30, 255]));
78 let mut out = Cursor::new(Vec::new());
79 img.write_to(&mut out, ImageFormat::Png).unwrap();
80 out.into_inner()
81 }
82
83 /// CRC-32 (the PNG chunk checksum), bit by bit. Only the tests use it.
84 fn crc32(bytes: &[u8]) -> u32 {
85 let mut crc = !0u32;
86 for &byte in bytes {
87 crc ^= u32::from(byte);
88 for _ in 0..8 {
89 crc = if crc & 1 == 1 {
90 (crc >> 1) ^ 0xEDB8_8320
91 } else {
92 crc >> 1
93 };
94 }
95 }
96 !crc
97 }
98
99 #[test]
100 fn a_small_png_becomes_a_webp_thumbnail() {
101 let thumb = make_thumbnail(&small_png()).unwrap();
102 assert_eq!(&thumb[..4], b"RIFF");
103 assert_eq!(&thumb[8..12], b"WEBP");
104 assert!(image::load_from_memory(&thumb).is_ok());
105 }
106
107 /// A PNG whose header claims 100000 by 100000 pixels. Its IHDR checksum is fixed up so that only the
108 /// dimension limit can refuse it. It must fail cleanly, without a panic or a huge allocation.
109 #[test]
110 fn a_decompression_bomb_png_is_refused_without_a_panic() {
111 let mut png = small_png();
112 // The IHDR chunk starts at byte 8: length (4), type (4), then width and height (4 each).
113 assert_eq!(&png[12..16], b"IHDR");
114 png[16..20].copy_from_slice(&100_000u32.to_be_bytes());
115 png[20..24].copy_from_slice(&100_000u32.to_be_bytes());
116 let crc = crc32(&png[12..29]);
117 png[29..33].copy_from_slice(&crc.to_be_bytes());
118 let result = make_thumbnail(&png);
119 assert!(
120 matches!(result, Err(Error::Invalid(ref m)) if m == "bad_image"),
121 "a bomb must be refused: {result:?}"
122 );
123 }
124
125 #[test]
126 fn non_pictures_are_refused() {
127 assert!(make_thumbnail(b"plain text, not a picture").is_err());
128 assert!(make_thumbnail(b"").is_err());
129 }
130}