vtcode-commons 0.186.0

Shared traits for paths, telemetry, and error reporting reused across VT Code component extractions
Documentation
//! Size-bounded reads of HTTP response bodies.
//!
//! `reqwest::Response::text()`, `::bytes()` and `::json()` buffer the entire
//! body, so a misbehaving or hostile endpoint (or a proxy error page) can
//! exhaust memory before any caller-side check runs. Every response read goes
//! through these helpers instead, which reject up front when `Content-Length`
//! already exceeds the cap and otherwise stop pulling `chunk()`s the moment
//! the cap is crossed, so peak memory is bounded even when the server lies
//! about or omits `Content-Length`.
//!
//! Bodies are decoded as UTF-8 (lossily). The JSON and text APIs these callers
//! talk to are UTF-8, and `reqwest`'s charset sniffing is not worth giving up a
//! hard memory bound for.

use reqwest::Response;

/// Cap for error-path bodies read only to build a diagnostic message.
pub const ERROR_BODY_LIMIT_BYTES: usize = 64 * 1024;
/// Cap for small control-plane responses (OAuth token exchanges, registries).
pub const CONTROL_BODY_LIMIT_BYTES: usize = 2 * 1024 * 1024;
/// Cap for ordinary API payloads (agent protocol, non-streaming completions).
pub const API_BODY_LIMIT_BYTES: usize = 32 * 1024 * 1024;

/// Why a bounded body read did not produce a complete body.
#[derive(Debug, thiserror::Error)]
pub enum BodyReadError {
    /// The body is larger than the allowed limit.
    #[error("response body exceeds the {limit} byte limit")]
    TooLarge {
        /// The limit that was exceeded, in bytes.
        limit: usize,
    },
    /// The transport failed while reading the body.
    #[error("failed to read response body: {0}")]
    Transport(#[from] reqwest::Error),
    /// The body was read in full but is not valid JSON for the requested type.
    #[error("invalid JSON in response body: {0}")]
    Json(#[from] serde_json::Error),
}

/// Maximum bytes retained for one incomplete SSE event.
///
/// Draining keeps a wire buffer at the unprocessed tail, but the tail itself is
/// unbounded when a peer never emits an event boundary. SSE payloads are
/// per-event JSON deltas (typically well under 64 KiB), but gateways that batch
/// a whole completion into one event can legitimately exceed 1 MiB, so the cap
/// only fails closed far past any real event (16 MiB is a multi-million-token
/// event) while still stopping a boundary-less peer after bounded memory
/// instead of growing for the stream lifetime.
pub const MAX_SSE_TAIL_BYTES: usize = 16_777_216;

/// The unprocessed SSE tail grew past [`MAX_SSE_TAIL_BYTES`] without
/// completing an event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SseTailOverflow {
    /// Retained tail bytes when the bound tripped.
    pub retained_bytes: usize,
}

impl std::fmt::Display for SseTailOverflow {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "stream event exceeded {MAX_SSE_TAIL_BYTES} bytes without an event boundary (retained {} bytes)",
            self.retained_bytes
        )
    }
}

impl std::error::Error for SseTailOverflow {}

/// Fail-closed bound for the unprocessed SSE tail.
///
/// Call once per chunk, after draining the consumed prefix, so the measured
/// length is what the loop actually retains. Takes a length rather than the
/// buffer so byte and string wire buffers share it.
///
/// # Errors
///
/// Returns [`SseTailOverflow`] when `retained_bytes` tops
/// [`MAX_SSE_TAIL_BYTES`]; the caller must abort the stream.
pub const fn check_sse_tail_bound(retained_bytes: usize) -> Result<(), SseTailOverflow> {
    if retained_bytes > MAX_SSE_TAIL_BYTES {
        return Err(SseTailOverflow { retained_bytes });
    }
    Ok(())
}

/// Read the whole body, failing with [`BodyReadError::TooLarge`] when it is
/// larger than `limit` bytes.
///
/// # Errors
///
/// Returns [`BodyReadError::TooLarge`] when the body exceeds `limit`, and
/// [`BodyReadError::Transport`] when reading a chunk fails.
pub async fn read_body_limited(mut response: Response, limit: usize) -> Result<Vec<u8>, BodyReadError> {
    if response
        .content_length()
        .is_some_and(|declared| declared > u64::try_from(limit).unwrap_or(u64::MAX))
    {
        return Err(BodyReadError::TooLarge { limit });
    }
    let mut body = Vec::with_capacity(limit.min(64 * 1024));
    while let Some(chunk) = response.chunk().await? {
        if chunk.len() > limit.saturating_sub(body.len()) {
            return Err(BodyReadError::TooLarge { limit });
        }
        body.extend_from_slice(&chunk);
    }
    Ok(body)
}

/// Read the whole body as text, failing when it is larger than `limit` bytes.
///
/// # Errors
///
/// Same as [`read_body_limited`].
pub async fn read_text_limited(response: Response, limit: usize) -> Result<String, BodyReadError> {
    let body = read_body_limited(response, limit).await?;
    Ok(String::from_utf8_lossy(&body).into_owned())
}

/// Read a control-plane response (OAuth, registry) as text under
/// [`CONTROL_BODY_LIMIT_BYTES`].
///
/// # Errors
///
/// Same as [`read_body_limited`].
pub async fn read_control_text(response: Response) -> Result<String, BodyReadError> {
    read_text_limited(response, CONTROL_BODY_LIMIT_BYTES).await
}

/// Read the whole body and parse it as JSON, failing when it is larger than
/// `limit` bytes.
///
/// # Errors
///
/// Same as [`read_body_limited`], plus [`BodyReadError::Json`] when the body
/// does not parse as `T`.
pub async fn read_json_limited<T: serde::de::DeserializeOwned>(
    response: Response,
    limit: usize,
) -> Result<T, BodyReadError> {
    let body = read_body_limited(response, limit).await?;
    Ok(serde_json::from_slice(&body)?)
}

/// Read at most `limit` bytes of the body as text for a diagnostic message.
///
/// Never fails: an oversized body is cut at `limit` and a transport error ends
/// the read early, because the caller is already reporting a failure and only
/// wants a bounded excerpt.
pub async fn read_text_excerpt(mut response: Response, limit: usize) -> String {
    let mut body = Vec::with_capacity(limit.min(8 * 1024));
    while body.len() < limit {
        let Ok(Some(chunk)) = response.chunk().await else {
            break;
        };
        let take = chunk.len().min(limit - body.len());
        body.extend(chunk.iter().copied().take(take));
    }
    String::from_utf8_lossy(&body).into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};
    use std::net::TcpListener;

    /// Serve one response whose head and body are written verbatim, then close.
    /// Returns `None` when the sandbox forbids binding sockets (callers skip).
    fn serve_once(head: &'static str, body: Vec<u8>) -> Option<String> {
        let listener = match TcpListener::bind("127.0.0.1:0") {
            Ok(listener) => listener,
            Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => return None,
            Err(err) => panic!("bind fixture listener: {err}"),
        };
        let addr = listener.local_addr().expect("listener address");
        drop(std::thread::spawn(move || {
            let Ok((mut stream, _)) = listener.accept() else { return };
            let mut request = [0u8; 4096];
            if stream.read(&mut request).is_err() {
                return;
            }
            // The client may hang up early once it has seen enough: ignore write errors.
            if stream.write_all(head.as_bytes()).is_err() {
                return;
            }
            // A client that hung up early has seen enough; nothing to report.
            drop(stream.write_all(&body));
        }));
        Some(format!("http://{addr}/"))
    }

    async fn fetch(url: &str) -> Response {
        crate::http::create_default_client()
            .get(url)
            .send()
            .await
            .expect("fixture responds")
    }

    #[test]
    fn sse_tail_bound_is_inclusive_at_the_cap_and_fails_one_byte_over() {
        assert_eq!(check_sse_tail_bound(0), Ok(()));
        assert_eq!(check_sse_tail_bound(MAX_SSE_TAIL_BYTES), Ok(()));
        let overflow = check_sse_tail_bound(MAX_SSE_TAIL_BYTES + 1).expect_err("one byte over the cap");
        assert_eq!(overflow, SseTailOverflow { retained_bytes: MAX_SSE_TAIL_BYTES + 1 });
        assert!(overflow.to_string().contains("without an event boundary"));
    }

    #[tokio::test]
    async fn a_body_within_the_limit_is_returned_whole() {
        let body = vec![b'a'; 1000];
        let Some(url) =
            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n", body.clone())
        else {
            return;
        };

        let read = read_body_limited(fetch(&url).await, 1000)
            .await
            .expect("exactly at the limit is allowed");

        assert_eq!(read, body);
    }

    #[tokio::test]
    async fn a_declared_length_over_the_limit_is_rejected_before_reading() {
        // Declares 1 MiB but sends nothing: only the up-front check can reject it
        // without waiting on a body that never arrives.
        let Some(url) =
            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 1048576\r\nConnection: close\r\n\r\n", Vec::new())
        else {
            return;
        };

        let err = read_body_limited(fetch(&url).await, 1024)
            .await
            .expect_err("declared size is over the cap");

        assert!(matches!(err, BodyReadError::TooLarge { limit: 1024 }), "{err}");
    }

    #[tokio::test]
    async fn an_undeclared_body_over_the_limit_is_rejected_while_streaming() {
        // No Content-Length: the server streams until close, so only the running
        // total can bound the read.
        let Some(url) = serve_once("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b'x'; 200_000]) else {
            return;
        };

        let err = read_body_limited(fetch(&url).await, 1024)
            .await
            .expect_err("streamed size is over the cap");

        assert!(matches!(err, BodyReadError::TooLarge { limit: 1024 }), "{err}");
    }

    #[tokio::test]
    async fn one_byte_over_the_limit_is_rejected() {
        let Some(url) = serve_once("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b'y'; 1025]) else {
            return;
        };

        assert!(read_body_limited(fetch(&url).await, 1024).await.is_err());
    }

    #[tokio::test]
    async fn text_decoding_replaces_invalid_utf8_instead_of_failing() {
        let Some(url) =
            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\n", vec![b'o', 0xFF, b'k'])
        else {
            return;
        };

        let text = read_text_limited(fetch(&url).await, 64).await.expect("lossy decode");

        assert_eq!(text, "o\u{FFFD}k");
    }

    #[tokio::test]
    async fn json_is_parsed_within_the_limit_and_rejected_over_it() {
        let Some(url) = serve_once(
            "HTTP/1.1 200 OK\r\nContent-Length: 13\r\nConnection: close\r\n\r\n",
            br#"{"key":"abc"}"#.to_vec(),
        ) else {
            return;
        };
        let parsed: serde_json::Value = read_json_limited(fetch(&url).await, 64).await.expect("valid json");
        assert_eq!(parsed["key"], "abc");

        let Some(url) = serve_once("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b' '; 4096]) else {
            return;
        };
        let err = read_json_limited::<serde_json::Value>(fetch(&url).await, 64)
            .await
            .expect_err("over the cap");
        assert!(matches!(err, BodyReadError::TooLarge { limit: 64 }), "{err}");

        let Some(url) =
            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n", b"nope".to_vec())
        else {
            return;
        };
        let err = read_json_limited::<serde_json::Value>(fetch(&url).await, 64)
            .await
            .expect_err("not json");
        assert!(matches!(err, BodyReadError::Json(_)), "{err}");
    }

    #[tokio::test]
    async fn an_excerpt_is_cut_at_the_limit_and_never_fails() {
        let Some(url) = serve_once("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", vec![b'z'; 200_000]) else {
            return;
        };

        let excerpt = read_text_excerpt(fetch(&url).await, 100).await;

        assert_eq!(excerpt.len(), 100);
        assert!(excerpt.bytes().all(|byte| byte == b'z'));
    }

    #[tokio::test]
    async fn an_excerpt_of_a_short_body_is_the_whole_body() {
        let Some(url) =
            serve_once("HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\n", b"short".to_vec())
        else {
            return;
        };

        assert_eq!(read_text_excerpt(fetch(&url).await, 100).await, "short");
    }
}