use reqwest::Client;
use std::time::Duration;
use vtcode_config::TimeoutsConfig;
pub struct HttpClientFactory;
impl HttpClientFactory {
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 };
Duration::from_secs(timeout_secs)
}
fn connect_timeout(config: &TimeoutsConfig) -> Duration {
match config.ceiling_duration(config.http_connect_seconds) {
Some(connect) => connect,
None => Duration::from_secs(30),
}
}
pub fn for_streaming(config: &TimeoutsConfig) -> Client {
let timeout_secs = if config.streaming_ceiling_seconds > 0 {
config.streaming_ceiling_seconds
} else {
600 };
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())
}
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)
}
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();
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() {
let config = TimeoutsConfig { http_connect_seconds: 0, ..Default::default() };
assert_eq!(HttpClientFactory::connect_timeout(&config), Duration::from_secs(30));
}
#[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;
}
#[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");
}
}