Skip to main content

artifactize_tools/
image.rs

1//! Pure image normalization and MIME detection.
2
3mod file;
4pub(crate) use file::{read, read_output};
5
6use base64::{
7    Engine, alphabet,
8    engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig, general_purpose::STANDARD},
9};
10
11use std::path::Path;
12
13use super::Content;
14
15/// The only image formats accepted by tool results and provider turns.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
17pub enum Mime {
18    #[serde(rename = "image/png")]
19    Png,
20    #[serde(rename = "image/jpeg")]
21    Jpeg,
22    #[serde(rename = "image/webp")]
23    Webp,
24}
25
26impl Mime {
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::Png => "image/png",
30            Self::Jpeg => "image/jpeg",
31            Self::Webp => "image/webp",
32        }
33    }
34}
35
36impl std::str::FromStr for Mime {
37    type Err = &'static str;
38    fn from_str(text: &str) -> Result<Self, Self::Err> {
39        match text {
40            "image/png" => Ok(Self::Png),
41            "image/jpeg" => Ok(Self::Jpeg),
42            "image/webp" => Ok(Self::Webp),
43            _ => Err("Image MIME type must be image/png, image/jpeg or image/webp."),
44        }
45    }
46}
47
48/// Bound decoded image memory and base64 provider payloads while allowing review screenshots.
49pub const IMAGE_LIMIT: usize = 4 * 1024 * 1024;
50/// The eight bytes every PNG file starts with.
51const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
52/// The first chunk header of a PNG: IHDR with its fixed 13-byte length.
53const PNG_IHDR_HEADER: &[u8] = b"\0\0\0\rIHDR";
54/// A PNG chunk header: a 4-byte big-endian data length and a 4-byte chunk type.
55const PNG_CHUNK_HEADER_BYTES: usize = 8;
56/// PNG chunk data lengths are encoded as one big-endian u32.
57const PNG_LENGTH_BYTES: usize = std::mem::size_of::<u32>();
58/// Base64 encodes each group of three bytes as four ASCII characters.
59const BASE64_INPUT_BYTES: usize = 3;
60const BASE64_OUTPUT_BYTES: usize = 4;
61/// A PNG chunk's bytes besides its data: the header and a 4-byte CRC.
62const PNG_CHUNK_OVERHEAD_BYTES: usize = 12;
63/// The chunk type that marks an animated PNG, which reviews do not accept.
64const PNG_ANIMATION_CONTROL: &[u8] = b"acTL";
65/// The chunk type that ends a PNG.
66const PNG_END: &[u8] = b"IEND";
67/// A JPEG start-of-image marker followed by the first byte of the next marker.
68const JPEG_START: &[u8] = b"\xff\xd8\xff";
69/// The marker code after `JPEG_START` that means JPEG-LS, which is not a baseline JPEG.
70const JPEG_LS_MARKER: u8 = 0xf7;
71/// A WebP file is a RIFF container whose form type, at bytes 8 to 12, is `WEBP`.
72const RIFF_SIGNATURE: &[u8] = b"RIFF";
73const WEBP_FORM: &[u8] = b"WEBP";
74const RIFF_FORM_TYPE: std::ops::Range<usize> = 8..12;
75
76/// Accept MIME text from callers at their wire boundary.
77pub fn from_base64(data: &str, mime_type: &str) -> Result<Content, String> {
78    normalize_base64(data, mime_type.parse()?)
79}
80
81/// Read a file-backed image whose MIME type has not already been parsed by the caller.
82pub fn from_output(
83    root: &Path,
84    path: impl AsRef<Path>,
85    mime_type: &str,
86) -> Result<Content, String> {
87    let mime_type = mime_type.parse()?;
88    normalize(&read_output(root, path.as_ref())?, Some(mime_type))
89}
90
91pub(crate) fn normalize_base64(data: &str, mime_type: Mime) -> Result<Content, String> {
92    if data.len() > IMAGE_LIMIT.div_ceil(BASE64_INPUT_BYTES) * BASE64_OUTPUT_BYTES {
93        return Err("Image exceeds the 4 MiB limit.".into());
94    }
95    let decoder = GeneralPurpose::new(
96        &alphabet::STANDARD,
97        GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
98    );
99    let bytes = decoder
100        .decode(data)
101        .map_err(|_| "Image requires valid base64 data.")?;
102    normalize(&bytes, Some(mime_type))
103}
104
105pub fn normalize(bytes: &[u8], declared: Option<Mime>) -> Result<Content, String> {
106    if bytes.is_empty() || bytes.len() > IMAGE_LIMIT {
107        return Err("Image exceeds the 4 MiB limit or contains no data.".into());
108    }
109    let mime_type = mime_type(bytes)
110        .ok_or("Image must be PNG, JPEG or WebP; GIF, BMP and animated PNG are not supported.")?;
111    if declared.is_some_and(|declared| declared != mime_type) {
112        return Err("Image bytes do not match declared MIME type.".into());
113    }
114    Ok(Content::Image {
115        data: STANDARD.encode(bytes),
116        mime_type,
117    })
118}
119
120fn mime_type(bytes: &[u8]) -> Option<Mime> {
121    if bytes.starts_with(JPEG_START) && bytes.get(JPEG_START.len()) != Some(&JPEG_LS_MARKER) {
122        Some(Mime::Jpeg)
123    } else if bytes.starts_with(PNG_SIGNATURE) {
124        let ihdr = PNG_SIGNATURE.len()..PNG_SIGNATURE.len() + PNG_IHDR_HEADER.len();
125        if bytes.get(ihdr) != Some(PNG_IHDR_HEADER) {
126            return None;
127        }
128        // Scan chunk boundaries, not image payloads, for animation control.
129        let mut offset = PNG_SIGNATURE.len();
130        while offset < bytes.len() {
131            let header = bytes.get(offset..offset + PNG_CHUNK_HEADER_BYTES)?;
132            let (length, kind) = header.split_at(PNG_LENGTH_BYTES);
133            let length = u32::from_be_bytes(length.try_into().ok()?) as usize;
134            let end = offset
135                .checked_add(PNG_CHUNK_OVERHEAD_BYTES)?
136                .checked_add(length)?;
137            if end > bytes.len() || kind == PNG_ANIMATION_CONTROL {
138                return None;
139            }
140            if kind == PNG_END {
141                return Some(Mime::Png);
142            }
143            offset = end;
144        }
145        None
146    } else if bytes.starts_with(RIFF_SIGNATURE) && bytes.get(RIFF_FORM_TYPE) == Some(WEBP_FORM) {
147        Some(Mime::Webp)
148    } else {
149        None
150    }
151}