diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 7d588336f1..381d6f5226 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -4,7 +4,8 @@ Codecs for flat raster image formats, written in pure Rust. This crate defines i type and shares its baseline and extended JPEG decoders through `craft-jpeg`, its optional HEIF decoder through `craft-heif`, and its optional AVIF decoder through `craft-video`'s AV1 decoder. It builds for `wasm32-unknown-unknown` and does no filesystem I/O: decoders take `&[u8]` and -encoders return `Vec`. +encoders return `Vec`. `read_bounded(reader, max_bytes)` reads a caller's file or stream into +bytes for them and fails with `ErrorKind::FileTooLarge` when the input is longer than `max_bytes`. It follows the "Avoiding GIMP's hole" rules in `docs/architecture.md` ยง1.1: diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index a5e572f36d..ee2537625e 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -95,6 +95,22 @@ pub fn decode_with(bytes: &[u8], opts: &DecodeOptions) -> Result std::io::Result> { + use std::io::Read as _; + let mut bytes = Vec::new(); + reader.take(max_bytes.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > max_bytes { + return Err(std::io::Error::new(std::io::ErrorKind::FileTooLarge, format!("the image input is longer than {max_bytes} bytes"))); + } + Ok(bytes) +} + /// Decode as a specific format with default [`Limits`]. pub fn decode_as(format: Format, bytes: &[u8]) -> Result { decode_as_with(format, bytes, &DecodeOptions::default()) diff --git a/crates/image-codecs/tests/it/limits.rs b/crates/image-codecs/tests/it/limits.rs index b9b047c615..ec86753ebe 100644 --- a/crates/image-codecs/tests/it/limits.rs +++ b/crates/image-codecs/tests/it/limits.rs @@ -17,6 +17,27 @@ fn encoded(f: Format) -> Vec { encode(&img, f, &EncodeOptions::default()).unwrap() } +#[test] +fn read_bounded_takes_input_up_to_its_cap() { + let png = encoded(Format::Png); + let len = png.len() as u64; + let bytes = read_bounded(png.as_slice(), len).unwrap(); + assert!(decode_with(&bytes, &DecodeOptions::default()).is_ok()); + assert_eq!(read_bounded(png.as_slice(), len - 1).err().map(|e| e.kind()), Some(std::io::ErrorKind::FileTooLarge)); +} + +#[test] +fn read_bounded_stops_a_stream_with_no_end() { + assert_eq!(read_bounded(std::io::repeat(0), 1 << 16).err().map(|e| e.kind()), Some(std::io::ErrorKind::FileTooLarge)); +} + +#[test] +fn read_bounded_reads_one_byte_past_its_cap() { + let mut input = std::io::Cursor::new(vec![0u8; 1 << 16]); + assert_eq!(read_bounded(&mut input, 100).err().map(|e| e.kind()), Some(std::io::ErrorKind::FileTooLarge)); + assert_eq!(input.position(), 101); +} + #[test] fn max_pixels_enforced_for_every_format() { for f in rw_formats() {