Skip to main content

adk_surface/
images.rs

1//! Images a person sends with a message (spec 3.3 §5.1): a screenshot of a failing build, a
2//! photo of a receipt. They reach the agent as the message's own parts, so a model that sees
3//! images reads them with the text.
4//!
5//! The engine trusts nothing about an image but its bytes: the type a surface declares must
6//! match the file's own signature, and only raster formats a browser shows without running
7//! anything are taken — PNG, JPEG, WebP and GIF; never SVG.
8
9use base64::Engine as _;
10
11use crate::error::{Result, SurfaceError};
12use crate::model::ImageData;
13
14/// The most images one message carries.
15pub const MAX_IMAGES: usize = 4;
16
17/// The most bytes one image has, decoded. The web home shrinks larger pictures before it
18/// sends them.
19pub const MAX_IMAGE_BYTES: usize = 3 * 1024 * 1024;
20
21/// The types the engine takes.
22pub const IMAGE_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"];
23
24/// An image of a message, decoded and checked: what a [`Source`](crate::Source) sends to the
25/// agent.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct MessageImage {
28    /// One of [`IMAGE_TYPES`].
29    pub mime_type: String,
30    /// The image's bytes.
31    pub data: Vec<u8>,
32}
33
34/// The type `bytes` begin like, among [`IMAGE_TYPES`].
35fn sniff(bytes: &[u8]) -> Option<&'static str> {
36    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
37        Some("image/png")
38    } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
39        Some("image/jpeg")
40    } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
41        Some("image/webp")
42    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
43        Some("image/gif")
44    } else {
45        None
46    }
47}
48
49/// Decodes and checks a message's images: at most [`MAX_IMAGES`], each base64 of at most
50/// [`MAX_IMAGE_BYTES`] whose bytes are the type it declares.
51///
52/// # Errors
53///
54/// `surface.invalid` naming the first image that fails, and why.
55///
56/// # Example
57///
58/// ```rust
59/// use adk_surface::images::decode;
60/// use adk_surface::model::ImageData;
61///
62/// let png = ImageData { mime_type: "image/png".into(), data: "iVBORw0KGgoAAAANSUhEUg==".into() };
63/// assert_eq!(decode(&[png]).unwrap()[0].mime_type, "image/png");
64///
65/// let svg = ImageData { mime_type: "image/svg+xml".into(), data: "PHN2Zz4=".into() };
66/// assert!(decode(&[svg]).is_err());
67/// ```
68pub fn decode(images: &[ImageData]) -> Result<Vec<MessageImage>> {
69    if images.len() > MAX_IMAGES {
70        return Err(SurfaceError::Invalid(format!(
71            "a message carries at most {MAX_IMAGES} images; this one has {}",
72            images.len()
73        )));
74    }
75    images
76        .iter()
77        .enumerate()
78        .map(|(index, image)| {
79            let n = index + 1;
80            if !IMAGE_TYPES.contains(&image.mime_type.as_str()) {
81                return Err(SurfaceError::Invalid(format!(
82                    "image {n} is {}: send PNG, JPEG, WebP or GIF",
83                    image.mime_type
84                )));
85            }
86            // Four base64 characters make three bytes: refuse an oversized one before decoding.
87            if image.data.len() > MAX_IMAGE_BYTES / 3 * 4 + 4 {
88                return Err(too_large(n));
89            }
90            let data = base64::engine::general_purpose::STANDARD
91                .decode(image.data.as_bytes())
92                .map_err(|_| SurfaceError::Invalid(format!("image {n} is not base64")))?;
93            if data.len() > MAX_IMAGE_BYTES {
94                return Err(too_large(n));
95            }
96            match sniff(&data) {
97                Some(found) if found == image.mime_type => {
98                    Ok(MessageImage { mime_type: image.mime_type.clone(), data })
99                }
100                Some(found) => Err(SurfaceError::Invalid(format!(
101                    "image {n} says {} but is {found}",
102                    image.mime_type
103                ))),
104                None => Err(SurfaceError::Invalid(format!(
105                    "image {n} is not a PNG, JPEG, WebP or GIF file"
106                ))),
107            }
108        })
109        .collect()
110}
111
112fn too_large(n: usize) -> SurfaceError {
113    SurfaceError::Invalid(format!(
114        "image {n} is larger than {} MB; send a smaller one",
115        MAX_IMAGE_BYTES / (1024 * 1024)
116    ))
117}
118
119/// The images of a message as the thread shows them: base64 again, for the page.
120pub(crate) fn shown(mime_type: &str, data: &[u8]) -> Option<ImageData> {
121    (IMAGE_TYPES.contains(&mime_type)
122        && data.len() <= MAX_IMAGE_BYTES
123        && sniff(data) == Some(mime_type))
124    .then(|| ImageData {
125        mime_type: mime_type.to_string(),
126        data: base64::engine::general_purpose::STANDARD.encode(data),
127    })
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    fn image(mime_type: &str, bytes: &[u8]) -> ImageData {
135        ImageData {
136            mime_type: mime_type.into(),
137            data: base64::engine::general_purpose::STANDARD.encode(bytes),
138        }
139    }
140
141    #[test]
142    fn takes_each_raster_type_by_its_signature() {
143        let webp = [b"RIFF".as_slice(), &[0, 0, 0, 0], b"WEBPVP8 "].concat();
144        for (mime, bytes) in [
145            ("image/png", b"\x89PNG\r\n\x1a\nrest".to_vec()),
146            ("image/jpeg", vec![0xFF, 0xD8, 0xFF, 0xE0]),
147            ("image/webp", webp),
148            ("image/gif", b"GIF89a....".to_vec()),
149        ] {
150            let decoded = decode(&[image(mime, &bytes)]).unwrap();
151            assert_eq!(decoded, vec![MessageImage { mime_type: mime.into(), data: bytes }]);
152        }
153    }
154
155    #[test]
156    fn refuses_what_is_not_what_it_says() {
157        let png = b"\x89PNG\r\n\x1a\n";
158        let refused = |images: &[ImageData]| decode(images).unwrap_err().to_string();
159        assert!(refused(&[image("image/jpeg", png)]).contains("says image/jpeg but is image/png"));
160        assert!(refused(&[image("image/svg+xml", b"<svg onload=alert(1)>")]).contains("PNG, JPEG"));
161        assert!(refused(&[image("image/png", b"<html>")]).contains("not a PNG"));
162        let bad = ImageData { mime_type: "image/png".into(), data: "%%%".into() };
163        assert!(refused(&[bad]).contains("not base64"));
164        assert!(refused(&vec![image("image/png", png); MAX_IMAGES + 1]).contains("at most 4"));
165        let big = [png.as_slice(), &vec![0; MAX_IMAGE_BYTES]].concat();
166        assert!(refused(&[image("image/png", &big)]).contains("larger than 3 MB"));
167    }
168
169    #[test]
170    fn shows_only_what_it_would_take() {
171        assert!(shown("image/png", b"\x89PNG\r\n\x1a\n").is_some());
172        assert!(shown("image/svg+xml", b"<svg/>").is_none());
173        assert!(shown("image/png", b"GIF89a").is_none());
174    }
175}