Skip to main content

vtcode_core/utils/
image_processing.rs

1//! Image processing utilities
2//!
3//! Re-exports from `vtcode-commons::image` plus URL-based image fetching.
4
5use anyhow::{Context, Result};
6use url::Url;
7pub use vtcode_commons::image::*;
8
9use crate::tools::web_fetch::{is_blocked_special_use_tld, is_private_host};
10
11/// Maximum redirects followed for a remote image. Each hop is re-validated
12/// against the SSRF guards: a public URL that redirects to a private host
13/// must stop rather than leak internal bytes into the model context.
14const MAX_IMAGE_REDIRECT_HOPS: usize = 5;
15
16/// Validate a remote image URL before any network happens: HTTP(S) scheme, a
17/// real host, and no private/special-use destination. Mirrors the `web_fetch`
18/// destination guards so `@<url>` image fetches cannot reach hosts that page
19/// fetches cannot.
20fn validate_image_url(url: &str) -> Result<Url> {
21    let parsed = Url::parse(url).with_context(|| format!("Invalid URL: {url}"))?;
22    if !matches!(parsed.scheme(), "http" | "https") {
23        anyhow::bail!("Invalid URL: {url}");
24    }
25    let host = parsed
26        .host_str()
27        .filter(|host| !host.is_empty())
28        .with_context(|| format!("Invalid URL (no host): {url}"))?;
29    if is_private_host(host) || is_blocked_special_use_tld(host) {
30        anyhow::bail!("Refusing to fetch image from private/local host '{host}'");
31    }
32    Ok(parsed)
33}
34
35/// Pure redirect-hop check behind the reqwest policy below, factored out so the
36/// hop cap and per-hop SSRF re-validation are unit-testable without a server.
37fn image_redirect_hop_allowed(next: &Url, previous_hops: usize) -> bool {
38    if previous_hops >= MAX_IMAGE_REDIRECT_HOPS {
39        return false;
40    }
41    if !matches!(next.scheme(), "http" | "https") {
42        return false;
43    }
44    next.host_str()
45        .is_some_and(|host| !is_private_host(host) && !is_blocked_special_use_tld(host))
46}
47
48/// Reads an image from a URL and converts it to base64 format
49pub async fn read_image_from_url(url: &str) -> Result<ImageData> {
50    let parsed = validate_image_url(url)?;
51
52    let client = vtcode_commons::http::apply_connect_timeout(
53        reqwest::Client::builder().timeout(std::time::Duration::from_secs(30)).redirect(
54            reqwest::redirect::Policy::custom(|attempt| {
55                if image_redirect_hop_allowed(attempt.url(), attempt.previous().len()) {
56                    attempt.follow()
57                } else {
58                    attempt.stop()
59                }
60            }),
61        ),
62    )
63    .build()
64    .context("Failed to create HTTP client")?;
65
66    let response = client
67        .get(parsed)
68        .send()
69        .await
70        .with_context(|| format!("Failed to fetch image from URL: {url}"))?;
71
72    if !response.status().is_success() {
73        return Err(anyhow::anyhow!("HTTP error when fetching image: {} (status: {})", url, response.status()));
74    }
75
76    let content_length = response.content_length().unwrap_or(0);
77    if content_length > 20 * 1024 * 1024 {
78        return Err(anyhow::anyhow!("Image from URL too large: {content_length} bytes (max 20MB)"));
79    }
80
81    let declared_mime_type = response
82        .headers()
83        .get(reqwest::header::CONTENT_TYPE)
84        .and_then(|v| v.to_str().ok())
85        .and_then(detect_mime_type_from_content_type);
86
87    // A declared but unsupported image type (SVG/BMP/TIFF) must fail here
88    // instead of falling through to magic-byte sniffing, which would
89    // mislabel SVG markup as PNG and produce a provider 400 downstream.
90    if let Some(content_type) = response
91        .headers()
92        .get(reqwest::header::CONTENT_TYPE)
93        .and_then(|v| v.to_str().ok())
94        && content_type.to_lowercase().starts_with("image/")
95        && declared_mime_type
96            .as_deref()
97            .is_none_or(|mime| !is_supported_image_mime_type(mime))
98    {
99        return Err(anyhow::anyhow!("Unsupported image content type for LLM vision: {content_type}"));
100    }
101
102    let mime_type = declared_mime_type;
103
104    let file_contents = response
105        .bytes()
106        .await
107        .with_context(|| format!("Failed to read response body from: {url}"))?
108        .to_vec();
109
110    // Reject markup/error pages that slipped past the header check: SVG and
111    // HTML payloads are text, not raster images, and providers refuse them.
112    let leading = file_contents.iter().take_while(|byte| byte.is_ascii_whitespace()).count();
113    if file_contents.len() > leading && file_contents[leading] == b'<' {
114        return Err(anyhow::anyhow!("URL did not return raster image data: {url}"));
115    }
116
117    let mime_type = mime_type.unwrap_or_else(|| detect_mime_type_from_data(&file_contents));
118    if !is_supported_image_mime_type(&mime_type) {
119        return Err(anyhow::anyhow!("Unsupported image content type for LLM vision: {mime_type}"));
120    }
121    let base64_data = encode_to_base64(&file_contents);
122
123    Ok(ImageData {
124        base64_data,
125        mime_type,
126        file_path: url.to_string(),
127        size: file_contents.len() as u64,
128    })
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn private_hosts_are_rejected() {
137        for url in [
138            "http://127.0.0.1/x.png",
139            "http://127.0.0.2:8080/x.png",
140            "https://10.1.2.3/x.png",
141            "http://192.168.0.1/x.png",
142            "http://172.16.5.4/x.png",
143            "http://169.254.169.254/latest/meta-data/",
144            "http://localhost/x.png",
145            "http://localhost.localdomain/x.png",
146            "http://[::1]/x.png",
147            "http://[::ffff:127.0.0.1]/x.png",
148            "http://user:pass@127.0.0.1/x.png",
149        ] {
150            assert!(validate_image_url(url).is_err(), "{url} must be rejected");
151        }
152    }
153
154    #[test]
155    fn special_use_tlds_are_rejected() {
156        for url in [
157            "http://printer.local/x.png",
158            "http://printer.local./x.png",
159            "http://wiki.internal/x.png",
160            "http://app.localhost/x.png",
161            "http://example.test/x.png",
162            "http://example.invalid/x.png",
163            "http://nas.home.arpa/x.png",
164        ] {
165            assert!(validate_image_url(url).is_err(), "{url} must be rejected");
166        }
167    }
168
169    #[test]
170    fn public_urls_are_accepted() {
171        // Asymmetric partners to the rejection lists: public IPs, public DNS,
172        // ports, and userinfo on a public host all validate.
173        for url in [
174            "https://example.com/x.png",
175            "http://93.184.216.34/x.png",
176            "https://example.com:8443/a/b.png?size=large#frag",
177            "http://[2606:4700:4700::1111]/x.png",
178            "https://user@example.com/x.png",
179        ] {
180            assert!(validate_image_url(url).is_ok(), "{url} must validate");
181        }
182    }
183
184    #[test]
185    fn non_http_schemes_and_malformed_urls_are_rejected() {
186        for url in ["ftp://example.com/x.png", "file:///etc/passwd", "not a url", "http://"] {
187            assert!(validate_image_url(url).is_err(), "{url} must be rejected");
188        }
189    }
190
191    #[test]
192    fn redirect_hops_recheck_the_destination_and_cap() {
193        let public = Url::parse("https://cdn.example.com/x.png").unwrap();
194        let private = Url::parse("http://169.254.169.254/x.png").unwrap();
195        let downgrade = Url::parse("ftp://example.com/x.png").unwrap();
196        assert!(image_redirect_hop_allowed(&public, 0));
197        assert!(image_redirect_hop_allowed(&public, MAX_IMAGE_REDIRECT_HOPS - 1));
198        assert!(!image_redirect_hop_allowed(&public, MAX_IMAGE_REDIRECT_HOPS));
199        assert!(!image_redirect_hop_allowed(&private, 0));
200        assert!(!image_redirect_hop_allowed(&downgrade, 0));
201    }
202}