Files
faunosteo/crates/worker/src/webp_check.rs
T

292 lines
9.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Parent-side check of the child's output (review Part IV.1): the keyed parent never
//! decodes pixels. It parses the RIFF container, allowlists the chunk types, reads the
//! canvas size from the bitstream headers and refuses any metadata chunk.
use std::fmt;
/// Why the parent refused the child's output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebpIssue {
TooShort,
NotRiff,
RiffSizeMismatch,
NotWebp,
ChunkOverrun,
ForbiddenChunk([u8; 4]),
MissingBitstream,
BadBitstream,
Dimensions { width: u32, height: u32 },
}
impl fmt::Display for WebpIssue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ForbiddenChunk(fourcc) => {
write!(f, "forbidden chunk {}", String::from_utf8_lossy(fourcc))
}
Self::Dimensions { width, height } => write!(f, "unexpected size {width}x{height}"),
other => write!(f, "{other:?}"),
}
}
}
/// What the parent learnt from the container without decoding a pixel.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebpSummary {
pub width: u32,
pub height: u32,
pub chunks: Vec<[u8; 4]>,
}
const ALLOWED_CHUNKS: [&[u8; 4]; 4] = [b"VP8X", b"VP8 ", b"VP8L", b"ALPH"];
/// Parses the container of a WebP file produced by the child.
pub fn inspect(bytes: &[u8]) -> Result<WebpSummary, WebpIssue> {
let header = bytes.get(0..12).ok_or(WebpIssue::TooShort)?;
if &header[0..4] != b"RIFF" {
return Err(WebpIssue::NotRiff);
}
let riff_size = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as usize;
if riff_size.checked_add(8) != Some(bytes.len()) {
return Err(WebpIssue::RiffSizeMismatch);
}
if &header[8..12] != b"WEBP" {
return Err(WebpIssue::NotWebp);
}
let mut offset = 12;
let mut chunks: Vec<[u8; 4]> = Vec::new();
let mut canvas: Option<(u32, u32)> = None;
let mut frame: Option<(u32, u32)> = None;
while offset < bytes.len() {
let chunk_header = bytes
.get(offset..offset + 8)
.ok_or(WebpIssue::ChunkOverrun)?;
let fourcc = [
chunk_header[0],
chunk_header[1],
chunk_header[2],
chunk_header[3],
];
let size = u32::from_le_bytes([
chunk_header[4],
chunk_header[5],
chunk_header[6],
chunk_header[7],
]) as usize;
let start = offset + 8;
let end = start.checked_add(size).ok_or(WebpIssue::ChunkOverrun)?;
let payload = bytes.get(start..end).ok_or(WebpIssue::ChunkOverrun)?;
if !ALLOWED_CHUNKS.contains(&&fourcc) {
return Err(WebpIssue::ForbiddenChunk(fourcc));
}
// Structure the encoder produces, and nothing else: an optional VP8X first, then an
// optional ALPH (extended files only), then exactly one VP8 or VP8L frame.
match &fourcc {
b"VP8X" => {
if !chunks.is_empty() {
return Err(WebpIssue::BadBitstream);
}
canvas = Some(parse_vp8x(payload)?);
}
b"ALPH" => {
if canvas.is_none() || frame.is_some() {
return Err(WebpIssue::BadBitstream);
}
}
b"VP8 " | b"VP8L" => {
if frame.is_some() {
return Err(WebpIssue::BadBitstream);
}
frame = Some(if &fourcc == b"VP8 " {
parse_vp8(payload)?
} else {
parse_vp8l(payload)?
});
}
_ => return Err(WebpIssue::ForbiddenChunk(fourcc)),
}
chunks.push(fourcc);
offset = end + (size & 1);
}
let frame = frame.ok_or(WebpIssue::MissingBitstream)?;
// The canvas (VP8X) and the frame must agree: the encoder never writes otherwise.
if let Some(canvas) = canvas
&& canvas != frame
{
return Err(WebpIssue::BadBitstream);
}
let (width, height) = canvas.unwrap_or(frame);
Ok(WebpSummary {
width,
height,
chunks,
})
}
/// `inspect`, then the canvas must be exactly `side` × `side`.
pub fn expect_square(bytes: &[u8], side: u32) -> Result<WebpSummary, WebpIssue> {
let summary = inspect(bytes)?;
if summary.width != side || summary.height != side {
return Err(WebpIssue::Dimensions {
width: summary.width,
height: summary.height,
});
}
Ok(summary)
}
fn parse_vp8x(payload: &[u8]) -> Result<(u32, u32), WebpIssue> {
let p = payload.get(0..10).ok_or(WebpIssue::BadBitstream)?;
let width = 1 + u32::from_le_bytes([p[4], p[5], p[6], 0]);
let height = 1 + u32::from_le_bytes([p[7], p[8], p[9], 0]);
Ok((width, height))
}
fn parse_vp8(payload: &[u8]) -> Result<(u32, u32), WebpIssue> {
let p = payload.get(0..10).ok_or(WebpIssue::BadBitstream)?;
if p[3..6] != [0x9d, 0x01, 0x2a] {
return Err(WebpIssue::BadBitstream);
}
let width = u32::from(u16::from_le_bytes([p[6], p[7]]) & 0x3fff);
let height = u32::from(u16::from_le_bytes([p[8], p[9]]) & 0x3fff);
Ok((width, height))
}
fn parse_vp8l(payload: &[u8]) -> Result<(u32, u32), WebpIssue> {
let p = payload.get(0..5).ok_or(WebpIssue::BadBitstream)?;
if p[0] != 0x2f {
return Err(WebpIssue::BadBitstream);
}
let bits = u32::from_le_bytes([p[1], p[2], p[3], p[4]]);
Ok(((bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1))
}
#[cfg(test)]
mod tests {
use super::*;
fn riff(chunks: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
let mut body = b"WEBP".to_vec();
for (fourcc, payload) in chunks {
body.extend_from_slice(*fourcc);
body.extend_from_slice(&(payload.len() as u32).to_le_bytes());
body.extend_from_slice(payload);
if payload.len() % 2 == 1 {
body.push(0);
}
}
let mut out = b"RIFF".to_vec();
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend_from_slice(&body);
out
}
fn vp8x(width: u32, height: u32) -> Vec<u8> {
let w = (width - 1).to_le_bytes();
let h = (height - 1).to_le_bytes();
vec![0x10, 0, 0, 0, w[0], w[1], w[2], h[0], h[1], h[2]]
}
#[test]
fn a_square_vp8x_file_passes() {
let mut vp8 = vec![0u8; 20];
vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]);
vp8[6..8].copy_from_slice(&512u16.to_le_bytes());
vp8[8..10].copy_from_slice(&512u16.to_le_bytes());
let bytes = riff(&[(b"VP8X", &vp8x(512, 512)), (b"VP8 ", &vp8)]);
let summary = expect_square(&bytes, 512);
assert_eq!(summary.map(|s| (s.width, s.height)), Ok((512, 512)));
}
#[test]
fn a_frame_disagreeing_with_its_canvas_is_refused() {
let mut vp8 = vec![0u8; 10];
vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]);
vp8[6..8].copy_from_slice(&256u16.to_le_bytes());
vp8[8..10].copy_from_slice(&512u16.to_le_bytes());
let bytes = riff(&[(b"VP8X", &vp8x(512, 512)), (b"VP8 ", &vp8)]);
assert_eq!(inspect(&bytes), Err(WebpIssue::BadBitstream));
}
#[test]
fn chunk_structure_is_strict() {
let mut vp8 = vec![0u8; 20];
vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]);
vp8[6..8].copy_from_slice(&512u16.to_le_bytes());
vp8[8..10].copy_from_slice(&512u16.to_le_bytes());
// two frames
assert_eq!(
inspect(&riff(&[(b"VP8 ", &vp8), (b"VP8 ", &vp8)])),
Err(WebpIssue::BadBitstream)
);
// ALPH without VP8X
assert_eq!(
inspect(&riff(&[(b"ALPH", &[0; 4]), (b"VP8 ", &vp8)])),
Err(WebpIssue::BadBitstream)
);
// VP8X not first
assert_eq!(
inspect(&riff(&[(b"VP8 ", &vp8), (b"VP8X", &vp8x(512, 512))])),
Err(WebpIssue::BadBitstream)
);
// the encoder's extended layout
assert!(
expect_square(
&riff(&[
(b"VP8X", &vp8x(512, 512)),
(b"ALPH", &[0; 4]),
(b"VP8 ", &vp8)
]),
512
)
.is_ok()
);
}
#[test]
fn metadata_chunks_are_refused() {
let bytes = riff(&[(b"VP8X", &vp8x(512, 512)), (b"EXIF", b"x")]);
// refused on the chunk type before any structural rule
assert_eq!(inspect(&bytes), Err(WebpIssue::ForbiddenChunk(*b"EXIF")));
}
#[test]
fn wrong_sizes_are_refused() {
let mut vp8 = vec![0u8; 20];
vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]);
vp8[6..8].copy_from_slice(&511u16.to_le_bytes());
vp8[8..10].copy_from_slice(&512u16.to_le_bytes());
let bytes = riff(&[(b"VP8X", &vp8x(511, 512)), (b"VP8 ", &vp8)]);
assert_eq!(
expect_square(&bytes, 512),
Err(WebpIssue::Dimensions {
width: 511,
height: 512
})
);
let mut truncated = riff(&[(b"VP8X", &vp8x(512, 512))]);
truncated.pop();
assert_eq!(inspect(&truncated), Err(WebpIssue::RiffSizeMismatch));
assert_eq!(
inspect(&riff(&[(b"VP8X", &vp8x(512, 512))])),
Err(WebpIssue::MissingBitstream)
);
assert_eq!(inspect(b"not a webp"), Err(WebpIssue::TooShort));
}
#[test]
fn simple_lossy_and_lossless_headers_give_the_size() {
let mut vp8 = vec![0u8; 10];
vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]);
vp8[6..8].copy_from_slice(&512u16.to_le_bytes());
vp8[8..10].copy_from_slice(&512u16.to_le_bytes());
assert!(expect_square(&riff(&[(b"VP8 ", &vp8)]), 512).is_ok());
let bits: u32 = (512 - 1) | ((512 - 1) << 14);
let mut vp8l = vec![0x2f];
vp8l.extend_from_slice(&bits.to_le_bytes());
assert!(expect_square(&riff(&[(b"VP8L", &vp8l)]), 512).is_ok());
}
}