Skip to main content

vtcode_commons/
http_body.rs

1//! Size-bounded reads of HTTP response bodies.
2//!
3//! `reqwest::Response::text()`, `::bytes()` and `::json()` buffer the entire
4//! body, so a misbehaving or hostile endpoint (or a proxy error page) can
5//! exhaust memory before any caller-side check runs. Every response read goes
6//! through these helpers instead, which reject up front when `Content-Length`
7//! already exceeds the cap and otherwise stop pulling `chunk()`s the moment
8//! the cap is crossed, so peak memory is bounded even when the server lies
9//! about or omits `Content-Length`.
10//!
11//! Bodies are decoded as UTF-8 (lossily). The JSON and text APIs these callers
12//! talk to are UTF-8, and `reqwest`'s charset sniffing is not worth giving up a
13//! hard memory bound for.
14
15use reqwest::Response;
16
17/// Cap for error-path bodies read only to build a diagnostic message.
18pub const ERROR_BODY_LIMIT_BYTES: usize = 64 * 1024;
19/// Cap for small control-plane responses (OAuth token exchanges, registries).
20pub const CONTROL_BODY_LIMIT_BYTES: usize = 2 * 1024 * 1024;
21/// Cap for ordinary API payloads (agent protocol, non-streaming completions).
22pub const API_BODY_LIMIT_BYTES: usize = 32 * 1024 * 1024;
23
24/// Why a bounded body read did not produce a complete body.
25#[derive(Debug, thiserror::Error)]
26pub enum BodyReadError {
27    /// The body is larger than the allowed limit.
28    #[error("response body exceeds the {limit} byte limit")]
29    TooLarge {
30        /// The limit that was exceeded, in bytes.
31        limit: usize,
32    },
33    /// The transport failed while reading the body.
34    #[error("failed to read response body: {0}")]
35    Transport(#[from] reqwest::Error),
36    /// The body was read in full but is not valid JSON for the requested type.
37    #[error("invalid JSON in response body: {0}")]
38    Json(#[from] serde_json::Error),
39}
40
41/// Maximum bytes retained for one incomplete SSE event.
42///
43/// Draining keeps a wire buffer at the unprocessed tail, but the tail itself is
44/// unbounded when a peer never emits an event boundary. SSE payloads are
45/// per-event JSON deltas (typically well under 64 KiB), but gateways that batch
46/// a whole completion into one event can legitimately exceed 1 MiB, so the cap
47/// only fails closed far past any real event (16 MiB is a multi-million-token
48/// event) while still stopping a boundary-less peer after bounded memory
49/// instead of growing for the stream lifetime.
50pub const MAX_SSE_TAIL_BYTES: usize = 16_777_216;
51
52/// The unprocessed SSE tail grew past [`MAX_SSE_TAIL_BYTES`] without
53/// completing an event.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct SseTailOverflow {
56    /// Retained tail bytes when the bound tripped.
57    pub retained_bytes: usize,
58}
59
60impl std::fmt::Display for SseTailOverflow {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        write!(
63            f,
64            "stream event exceeded {MAX_SSE_TAIL_BYTES} bytes without an event boundary (retained {} bytes)",
65            self.retained_bytes
66        )
67    }
68}
69
70impl std::error::Error for SseTailOverflow {}
71
72/// Fail-closed bound for the unprocessed SSE tail.
73///
74/// Call once per chunk, after draining the consumed prefix, so the measured
75/// length is what the loop actually retains. Takes a length rather than the
76/// buffer so byte and string wire buffers share it.
77///
78/// # Errors
79///
80/// Returns [`SseTailOverflow`] when `retained_bytes` tops
81/// [`MAX_SSE_TAIL_BYTES`]; the caller must abort the stream.
82pub const fn check_sse_tail_bound(retained_bytes: usize) -> Result<(), SseTailOverflow> {
83    if retained_bytes > MAX_SSE_TAIL_BYTES {
84        return Err(SseTailOverflow { retained_bytes });
85    }
86    Ok(())
87}
88
89/// Read the whole body, failing with [`BodyReadError::TooLarge`] when it is
90/// larger than `limit` bytes.
91///
92/// # Errors
93///
94/// Returns [`BodyReadError::TooLarge`] when the body exceeds `limit`, and
95/// [`BodyReadError::Transport`] when reading a chunk fails.
96pub async fn read_body_limited(mut response: Response, limit: usize) -> Result<Vec<u8>, BodyReadError> {
97    if response
98        .content_length()
99        .is_some_and(|declared| declared > u64::try_from(limit).unwrap_or(u64::MAX))
100    {
101        return Err(BodyReadError::TooLarge { limit });
102    }
103    let mut body = Vec::with_capacity(limit.min(64 * 1024));
104    while let Some(chunk) = response.chunk().await? {
105        if chunk.len() > limit.saturating_sub(body.len()) {
106            return Err(BodyReadError::TooLarge { limit });
107        }
108        body.extend_from_slice(&chunk);
109    }
110    Ok(body)
111}
112
113/// Read the whole body as text, failing when it is larger than `limit` bytes.
114///
115/// # Errors
116///
117/// Same as [`read_body_limited`].
118pub async fn read_text_limited(response: Response, limit: usize) -> Result<String, BodyReadError> {
119    let body = read_body_limited(response, limit).await?;
120    Ok(String::from_utf8_lossy(&body).into_owned())
121}
122
123/// Read a control-plane response (OAuth, registry) as text under
124/// [`CONTROL_BODY_LIMIT_BYTES`].
125///
126/// # Errors
127///
128/// Same as [`read_body_limited`].
129pub async fn read_control_text(response: Response) -> Result<String, BodyReadError> {
130    read_text_limited(response, CONTROL_BODY_LIMIT_BYTES).await
131}
132
133/// Read the whole body and parse it as JSON, failing when it is larger than
134/// `limit` bytes.
135///
136/// # Errors
137///
138/// Same as [`read_body_limited`], plus [`BodyReadError::Json`] when the body
139/// does not parse as `T`.
140pub async fn read_json_limited<T: serde::de::DeserializeOwned>(
141    response: Response,
142    limit: usize,
143) -> Result<T, BodyReadError> {
144    let body = read_body_limited(response, limit).await?;
145    Ok(serde_json::from_slice(&body)?)
146}
147
148/// Read at most `limit` bytes of the body as text for a diagnostic message.
149///
150/// Never fails: an oversized body is cut at `limit` and a transport error ends
151/// the read early, because the caller is already reporting a failure and only
152/// wants a bounded excerpt.
153pub async fn read_text_excerpt(mut response: Response, limit: usize) -> String {
154    let mut body = Vec::with_capacity(limit.min(8 * 1024));
155    while body.len() < limit {
156        let Ok(Some(chunk)) = response.chunk().await else {
157            break;
158        };
159        let take = chunk.len().min(limit - body.len());
160        body.extend(chunk.iter().copied().take(take));
161    }
162    String::from_utf8_lossy(&body).into_owned()
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use std::io::{Read, Write};
169    use std::net::TcpListener;
170
171    /// Serve one response whose head and body are written verbatim, then close.
172    /// Returns `None` when the sandbox forbids binding sockets (callers skip).
173    fn serve_once(head: &'static str, body: Vec<u8>) -> Option<String> {
174        let listener = match TcpListener::bind("127.0.0.1:0") {
175            Ok(listener) => listener,
176            Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return None,
177            Err(err) => panic!("bind fixture listener: {err}"),
178        };
179        let addr = listener.local_addr().expect("listener address");
180        drop(std::thread::spawn(move || {
181            let Ok((mut stream, _)) = listener.accept() else { return };
182            let mut request = [0u8; 4096];
183            if stream.read(&mut request).is_err() {
184                return;
185            }
186            // The client may hang up early once it has seen enough: ignore write errors.
187            if stream.write_all(head.as_bytes()).is_err() {
188                return;
189            }
190            // A client that hung up early has seen enough; nothing to report.
191            drop(stream.write_all(&body));
192        }));
193        Some(format!("http://{addr}/"))
194    }
195
196    async fn fetch(url: &str) -> Response {
197        crate::http::create_default_client()
198            .get(url)
199            .send()
200            .await
201            .expect("fixture responds")
202    }
203
204    #[test]
205    fn sse_tail_bound_is_inclusive_at_the_cap_and_fails_one_byte_over() {
206        assert_eq!(check_sse_tail_bound(0), Ok(()));
207        assert_eq!(check_sse_tail_bound(MAX_SSE_TAIL_BYTES), Ok(()));
208        let overflow = check_sse_tail_bound(MAX_SSE_TAIL_BYTES + 1).expect_err("one byte over the cap");
209        assert_eq!(overflow, SseTailOverflow { retained_bytes: MAX_SSE_TAIL_BYTES + 1 });
210        assert!(overflow.to_string().contains("without an event boundary"));
211    }
212
213    #[tokio::test]
214    async fn a_body_within_the_limit_is_returned_whole() {
215        let body = vec![b'a'; 1000];
216        let Some(url) =
217            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n", body.clone())
218        else {
219            return;
220        };
221
222        let read = read_body_limited(fetch(&url).await, 1000)
223            .await
224            .expect("exactly at the limit is allowed");
225
226        assert_eq!(read, body);
227    }
228
229    #[tokio::test]
230    async fn a_declared_length_over_the_limit_is_rejected_before_reading() {
231        // Declares 1 MiB but sends nothing: only the up-front check can reject it
232        // without waiting on a body that never arrives.
233        let Some(url) =
234            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 1048576\r\nConnection: close\r\n\r\n", Vec::new())
235        else {
236            return;
237        };
238
239        let err = read_body_limited(fetch(&url).await, 1024)
240            .await
241            .expect_err("declared size is over the cap");
242
243        assert!(matches!(err, BodyReadError::TooLarge { limit: 1024 }), "{err}");
244    }
245
246    #[tokio::test]
247    async fn an_undeclared_body_over_the_limit_is_rejected_while_streaming() {
248        // No Content-Length: the server streams until close, so only the running
249        // total can bound the read.
250        let Some(url) = serve_once("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b'x'; 200_000]) else {
251            return;
252        };
253
254        let err = read_body_limited(fetch(&url).await, 1024)
255            .await
256            .expect_err("streamed size is over the cap");
257
258        assert!(matches!(err, BodyReadError::TooLarge { limit: 1024 }), "{err}");
259    }
260
261    #[tokio::test]
262    async fn one_byte_over_the_limit_is_rejected() {
263        let Some(url) = serve_once("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b'y'; 1025]) else {
264            return;
265        };
266
267        assert!(read_body_limited(fetch(&url).await, 1024).await.is_err());
268    }
269
270    #[tokio::test]
271    async fn text_decoding_replaces_invalid_utf8_instead_of_failing() {
272        let Some(url) =
273            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\n", vec![b'o', 0xFF, b'k'])
274        else {
275            return;
276        };
277
278        let text = read_text_limited(fetch(&url).await, 64).await.expect("lossy decode");
279
280        assert_eq!(text, "o\u{FFFD}k");
281    }
282
283    #[tokio::test]
284    async fn json_is_parsed_within_the_limit_and_rejected_over_it() {
285        let Some(url) = serve_once(
286            "HTTP/1.1 200 OK\r\nContent-Length: 13\r\nConnection: close\r\n\r\n",
287            br#"{"key":"abc"}"#.to_vec(),
288        ) else {
289            return;
290        };
291        let parsed: serde_json::Value = read_json_limited(fetch(&url).await, 64).await.expect("valid json");
292        assert_eq!(parsed["key"], "abc");
293
294        let Some(url) = serve_once("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b' '; 4096]) else {
295            return;
296        };
297        let err = read_json_limited::<serde_json::Value>(fetch(&url).await, 64)
298            .await
299            .expect_err("over the cap");
300        assert!(matches!(err, BodyReadError::TooLarge { limit: 64 }), "{err}");
301
302        let Some(url) =
303            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n", b"nope".to_vec())
304        else {
305            return;
306        };
307        let err = read_json_limited::<serde_json::Value>(fetch(&url).await, 64)
308            .await
309            .expect_err("not json");
310        assert!(matches!(err, BodyReadError::Json(_)), "{err}");
311    }
312
313    #[tokio::test]
314    async fn an_excerpt_is_cut_at_the_limit_and_never_fails() {
315        let Some(url) = serve_once("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b'z'; 200_000]) else {
316            return;
317        };
318
319        let excerpt = read_text_excerpt(fetch(&url).await, 100).await;
320
321        assert_eq!(excerpt.len(), 100);
322        assert!(excerpt.bytes().all(|byte| byte == b'z'));
323    }
324
325    #[tokio::test]
326    async fn an_excerpt_of_a_short_body_is_the_whole_body() {
327        let Some(url) =
328            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\n", b"short".to_vec())
329        else {
330            return;
331        };
332
333        assert_eq!(read_text_excerpt(fetch(&url).await, 100).await, "short");
334    }
335}