vtcode-llm 0.186.0

LLM provider abstraction, client implementations, and streaming for VT Code
Documentation
//! Centralized HTTP client factory for LLM providers.
//!
//! Provides consistent timeout configuration and client creation
//! across all providers based on the application's TimeoutsConfig.

use reqwest::Client;
use std::time::Duration;

use vtcode_config::TimeoutsConfig;

/// Factory for creating pre-configured HTTP clients.
pub struct HttpClientFactory;

impl HttpClientFactory {
    /// Create an HTTP client for standard LLM API requests.
    ///
    /// The request budget comes from `default_ceiling_seconds`; the connect phase
    /// comes from `http_connect_seconds`, so a slow or high-latency link can be
    /// tuned independently of how long a completion may run.
    pub fn for_llm(config: &TimeoutsConfig) -> Client {
        vtcode_commons::http::create_origin_bound_client_with_timeouts(
            Self::connect_timeout(config),
            Self::llm_timeout(config),
        )
    }

    pub(crate) fn for_llm_without_redirects(config: &TimeoutsConfig) -> Result<Client, reqwest::Error> {
        vtcode_commons::http::create_client_without_redirects(Self::connect_timeout(config), Self::llm_timeout(config))
    }

    fn llm_timeout(config: &TimeoutsConfig) -> Duration {
        let timeout_secs = if config.default_ceiling_seconds > 0 {
            config.default_ceiling_seconds
        } else {
            180 // Fallback if disabled
        };

        Duration::from_secs(timeout_secs)
    }

    /// Connect budget from `[timeouts] http_connect_seconds`, falling back to the
    /// historical 30s when the key is set to `0` (disabled), because reqwest needs
    /// a concrete duration at this call site.
    fn connect_timeout(config: &TimeoutsConfig) -> Duration {
        match config.ceiling_duration(config.http_connect_seconds) {
            Some(connect) => connect,
            None => Duration::from_secs(30),
        }
    }

    /// Create an HTTP client optimized for streaming requests.
    ///
    /// Uses the `streaming_ceiling_seconds` from TimeoutsConfig.
    /// Streaming requests typically take longer as they wait for incremental output.
    pub fn for_streaming(config: &TimeoutsConfig) -> Client {
        let timeout_secs = if config.streaming_ceiling_seconds > 0 {
            config.streaming_ceiling_seconds
        } else {
            600 // 10 minutes fallback for streaming
        };

        Client::builder()
            .timeout(Duration::from_secs(timeout_secs))
            .connect_timeout(Self::connect_timeout(config))
            .pool_idle_timeout(Some(Duration::from_secs(90)))
            .pool_max_idle_per_host(1)
            .redirect(vtcode_commons::http::same_origin_redirect_policy())
            .build()
            .unwrap_or_else(|_| vtcode_commons::http::create_origin_bound_streaming_client())
    }

    /// Create an HTTP client with explicit timeout values.
    ///
    /// Use this when providers need custom timeout handling.
    pub(crate) fn with_timeouts(request_timeout: Duration, connect_timeout: Duration) -> Client {
        vtcode_commons::http::create_origin_bound_client_with_timeouts(connect_timeout, request_timeout)
    }

    /// Create a default HTTP client with reasonable defaults.
    ///
    /// Uses 180s request timeout and 30s connect timeout.
    pub fn default_client() -> Client {
        vtcode_commons::http::create_origin_bound_client_with_timeouts(
            Duration::from_secs(30),
            Duration::from_secs(180),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_client_is_created() {
        let client = HttpClientFactory::default_client();
        // Just verify it doesn't panic
        drop(client);
    }

    #[test]
    fn for_llm_uses_config_timeout() {
        let config = TimeoutsConfig::default();
        let client = HttpClientFactory::for_llm(&config);
        drop(client);
    }

    #[test]
    fn for_streaming_uses_longer_timeout() {
        let config = TimeoutsConfig::default();
        let client = HttpClientFactory::for_streaming(&config);
        drop(client);
    }

    #[test]
    fn connect_timeout_follows_the_configured_http_key() {
        let config = TimeoutsConfig { http_connect_seconds: 45, ..Default::default() };
        assert_eq!(HttpClientFactory::connect_timeout(&config), Duration::from_secs(45));
    }

    #[test]
    fn connect_timeout_falls_back_when_disabled() {
        // `0` means "no limit" in `[timeouts]`, but reqwest still needs a
        // concrete connect duration here, so the historical 30s applies.
        let config = TimeoutsConfig { http_connect_seconds: 0, ..Default::default() };
        assert_eq!(HttpClientFactory::connect_timeout(&config), Duration::from_secs(30));
    }

    /// Regression (mirrors the MCP CVE-2026-64684 test): LLM clients must not
    /// follow cross-origin redirects, otherwise custom key headers (`x-api-key`,
    /// `x-goog-api-key`) replay to the redirect target — reqwest strips only
    /// `Authorization`/`Cookie`-family headers there. Same-origin redirects
    /// stay within the trusted origin and are followed (see below).
    #[tokio::test]
    async fn llm_clients_do_not_follow_cross_origin_redirects() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        async fn read_http_request(stream: &mut tokio::net::TcpStream) -> Vec<u8> {
            let mut buf = Vec::new();
            let mut chunk = [0_u8; 1024];
            while let Ok(n) = stream.read(&mut chunk).await {
                if n == 0 {
                    break;
                }
                buf.extend_from_slice(&chunk[..n]);
                if buf.len() > 65536 || String::from_utf8_lossy(&buf).contains("\r\n\r\n") {
                    break;
                }
            }
            buf
        }

        async fn assert_no_follow(client: Client) {
            let hits = Arc::new(AtomicUsize::new(0));
            let leaked = Arc::new(AtomicUsize::new(0));
            let capture_listener = TcpListener::bind("127.0.0.1:0").await.expect("bind capture listener");
            let capture_addr = capture_listener.local_addr().expect("capture addr");
            let capture_task = tokio::spawn({
                let hits = Arc::clone(&hits);
                let leaked = Arc::clone(&leaked);
                async move {
                    if let Ok((mut stream, _)) = capture_listener.accept().await {
                        let raw = read_http_request(&mut stream).await;
                        let _ = hits.fetch_add(1, Ordering::SeqCst);
                        if String::from_utf8_lossy(&raw).contains("x-api-key:") {
                            let _ = leaked.fetch_add(1, Ordering::SeqCst);
                        }
                    }
                }
            });

            let redirect_listener = TcpListener::bind("127.0.0.1:0").await.expect("bind redirect listener");
            let redirect_addr = redirect_listener.local_addr().expect("redirect addr");
            let redirect_task = tokio::spawn(async move {
                if let Ok((mut stream, _)) = redirect_listener.accept().await {
                    let _ = read_http_request(&mut stream).await;
                    let response = format!(
                        "HTTP/1.1 307 Temporary Redirect\r\nlocation: http://{capture_addr}/v1\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
                    );
                    drop(stream.write_all(response.as_bytes()).await);
                }
            });

            let response = client
                .get(format!("http://{redirect_addr}/v1"))
                .header("x-api-key", "super-secret")
                .send()
                .await
                .expect("request completes");
            assert_eq!(response.status(), reqwest::StatusCode::TEMPORARY_REDIRECT);

            redirect_task.await.expect("redirect server completes");
            capture_task.abort();

            assert_eq!(hits.load(Ordering::SeqCst), 0, "redirect target must never be contacted");
            assert_eq!(leaked.load(Ordering::SeqCst), 0, "custom auth header must never reach redirect target");
        }

        let config = TimeoutsConfig::default();
        assert_no_follow(HttpClientFactory::for_llm(&config)).await;
        assert_no_follow(HttpClientFactory::for_streaming(&config)).await;
        assert_no_follow(HttpClientFactory::default_client()).await;
    }

    /// Same-origin redirects (trailing-slash normalization, gateway rewrites)
    /// stay within the origin the caller trusts with the key, so they must be
    /// followed transparently with credentials intact.
    #[tokio::test]
    async fn llm_clients_follow_same_origin_redirects() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let hits = Arc::new(AtomicUsize::new(0));
        let authed = Arc::new(AtomicUsize::new(0));
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind listener");
        let addr = listener.local_addr().expect("listener addr");
        let server_task = tokio::spawn({
            let hits = Arc::clone(&hits);
            let authed = Arc::clone(&authed);
            async move {
                for _ in 0..2 {
                    let Ok((mut stream, _)) = listener.accept().await else {
                        break;
                    };
                    let mut buf = Vec::new();
                    let mut chunk = [0_u8; 1024];
                    while let Ok(n) = stream.read(&mut chunk).await {
                        if n == 0 {
                            break;
                        }
                        buf.extend_from_slice(&chunk[..n]);
                        if buf.len() > 65536 || String::from_utf8_lossy(&buf).contains("\r\n\r\n") {
                            break;
                        }
                    }
                    let request = String::from_utf8_lossy(&buf).into_owned();
                    let _ = hits.fetch_add(1, Ordering::SeqCst);
                    if request.contains("x-api-key: super-secret") {
                        let _ = authed.fetch_add(1, Ordering::SeqCst);
                    }
                    let response = if request.starts_with("GET /start ") {
                        "HTTP/1.1 307 Temporary Redirect\r\nlocation: /final\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
                    } else {
                        "HTTP/1.1 200 OK\r\ncontent-length: 8\r\nconnection: close\r\n\r\nfollowed"
                    };
                    drop(stream.write_all(response.as_bytes()).await);
                    drop(stream.shutdown().await);
                }
            }
        });

        let config = TimeoutsConfig::default();
        let client = HttpClientFactory::for_llm(&config);
        let response = client
            .get(format!("http://{addr}/start"))
            .header("x-api-key", "super-secret")
            .send()
            .await
            .expect("request completes");
        assert_eq!(response.status(), reqwest::StatusCode::OK);
        let body =
            vtcode_commons::http_body::read_text_limited(response, vtcode_commons::http_body::API_BODY_LIMIT_BYTES)
                .await
                .expect("body");
        assert_eq!(body, "followed");

        server_task.await.expect("server completes");
        assert_eq!(hits.load(Ordering::SeqCst), 2, "both hops must reach the same origin");
        assert_eq!(authed.load(Ordering::SeqCst), 2, "credentials stay attached within the origin");
    }
}