vtcode_llm/
http_client.rs1use reqwest::Client;
7use std::time::Duration;
8
9use vtcode_config::TimeoutsConfig;
10
11pub struct HttpClientFactory;
13
14impl HttpClientFactory {
15 pub fn for_llm(config: &TimeoutsConfig) -> Client {
21 vtcode_commons::http::create_origin_bound_client_with_timeouts(
22 Self::connect_timeout(config),
23 Self::llm_timeout(config),
24 )
25 }
26
27 pub(crate) fn for_llm_without_redirects(config: &TimeoutsConfig) -> Result<Client, reqwest::Error> {
28 vtcode_commons::http::create_client_without_redirects(Self::connect_timeout(config), Self::llm_timeout(config))
29 }
30
31 fn llm_timeout(config: &TimeoutsConfig) -> Duration {
32 let timeout_secs = if config.default_ceiling_seconds > 0 {
33 config.default_ceiling_seconds
34 } else {
35 180 };
37
38 Duration::from_secs(timeout_secs)
39 }
40
41 fn connect_timeout(config: &TimeoutsConfig) -> Duration {
45 match config.ceiling_duration(config.http_connect_seconds) {
46 Some(connect) => connect,
47 None => Duration::from_secs(30),
48 }
49 }
50
51 pub fn for_streaming(config: &TimeoutsConfig) -> Client {
56 let timeout_secs = if config.streaming_ceiling_seconds > 0 {
57 config.streaming_ceiling_seconds
58 } else {
59 600 };
61
62 Client::builder()
63 .timeout(Duration::from_secs(timeout_secs))
64 .connect_timeout(Self::connect_timeout(config))
65 .pool_idle_timeout(Some(Duration::from_secs(90)))
66 .pool_max_idle_per_host(1)
67 .redirect(vtcode_commons::http::same_origin_redirect_policy())
68 .build()
69 .unwrap_or_else(|_| vtcode_commons::http::create_origin_bound_streaming_client())
70 }
71
72 pub(crate) fn with_timeouts(request_timeout: Duration, connect_timeout: Duration) -> Client {
76 vtcode_commons::http::create_origin_bound_client_with_timeouts(connect_timeout, request_timeout)
77 }
78
79 pub fn default_client() -> Client {
83 vtcode_commons::http::create_origin_bound_client_with_timeouts(
84 Duration::from_secs(30),
85 Duration::from_secs(180),
86 )
87 }
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 #[test]
95 fn default_client_is_created() {
96 let client = HttpClientFactory::default_client();
97 drop(client);
99 }
100
101 #[test]
102 fn for_llm_uses_config_timeout() {
103 let config = TimeoutsConfig::default();
104 let client = HttpClientFactory::for_llm(&config);
105 drop(client);
106 }
107
108 #[test]
109 fn for_streaming_uses_longer_timeout() {
110 let config = TimeoutsConfig::default();
111 let client = HttpClientFactory::for_streaming(&config);
112 drop(client);
113 }
114
115 #[test]
116 fn connect_timeout_follows_the_configured_http_key() {
117 let config = TimeoutsConfig { http_connect_seconds: 45, ..Default::default() };
118 assert_eq!(HttpClientFactory::connect_timeout(&config), Duration::from_secs(45));
119 }
120
121 #[test]
122 fn connect_timeout_falls_back_when_disabled() {
123 let config = TimeoutsConfig { http_connect_seconds: 0, ..Default::default() };
126 assert_eq!(HttpClientFactory::connect_timeout(&config), Duration::from_secs(30));
127 }
128
129 #[tokio::test]
135 async fn llm_clients_do_not_follow_cross_origin_redirects() {
136 use std::sync::Arc;
137 use std::sync::atomic::{AtomicUsize, Ordering};
138
139 use tokio::io::{AsyncReadExt, AsyncWriteExt};
140 use tokio::net::TcpListener;
141
142 async fn read_http_request(stream: &mut tokio::net::TcpStream) -> Vec<u8> {
143 let mut buf = Vec::new();
144 let mut chunk = [0_u8; 1024];
145 while let Ok(n) = stream.read(&mut chunk).await {
146 if n == 0 {
147 break;
148 }
149 buf.extend_from_slice(&chunk[..n]);
150 if buf.len() > 65536 || String::from_utf8_lossy(&buf).contains("\r\n\r\n") {
151 break;
152 }
153 }
154 buf
155 }
156
157 async fn assert_no_follow(client: Client) {
158 let hits = Arc::new(AtomicUsize::new(0));
159 let leaked = Arc::new(AtomicUsize::new(0));
160 let capture_listener = TcpListener::bind("127.0.0.1:0").await.expect("bind capture listener");
161 let capture_addr = capture_listener.local_addr().expect("capture addr");
162 let capture_task = tokio::spawn({
163 let hits = Arc::clone(&hits);
164 let leaked = Arc::clone(&leaked);
165 async move {
166 if let Ok((mut stream, _)) = capture_listener.accept().await {
167 let raw = read_http_request(&mut stream).await;
168 let _ = hits.fetch_add(1, Ordering::SeqCst);
169 if String::from_utf8_lossy(&raw).contains("x-api-key:") {
170 let _ = leaked.fetch_add(1, Ordering::SeqCst);
171 }
172 }
173 }
174 });
175
176 let redirect_listener = TcpListener::bind("127.0.0.1:0").await.expect("bind redirect listener");
177 let redirect_addr = redirect_listener.local_addr().expect("redirect addr");
178 let redirect_task = tokio::spawn(async move {
179 if let Ok((mut stream, _)) = redirect_listener.accept().await {
180 let _ = read_http_request(&mut stream).await;
181 let response = format!(
182 "HTTP/1.1 307 Temporary Redirect\r\nlocation: http://{capture_addr}/v1\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
183 );
184 drop(stream.write_all(response.as_bytes()).await);
185 }
186 });
187
188 let response = client
189 .get(format!("http://{redirect_addr}/v1"))
190 .header("x-api-key", "super-secret")
191 .send()
192 .await
193 .expect("request completes");
194 assert_eq!(response.status(), reqwest::StatusCode::TEMPORARY_REDIRECT);
195
196 redirect_task.await.expect("redirect server completes");
197 capture_task.abort();
198
199 assert_eq!(hits.load(Ordering::SeqCst), 0, "redirect target must never be contacted");
200 assert_eq!(leaked.load(Ordering::SeqCst), 0, "custom auth header must never reach redirect target");
201 }
202
203 let config = TimeoutsConfig::default();
204 assert_no_follow(HttpClientFactory::for_llm(&config)).await;
205 assert_no_follow(HttpClientFactory::for_streaming(&config)).await;
206 assert_no_follow(HttpClientFactory::default_client()).await;
207 }
208
209 #[tokio::test]
213 async fn llm_clients_follow_same_origin_redirects() {
214 use std::sync::Arc;
215 use std::sync::atomic::{AtomicUsize, Ordering};
216
217 use tokio::io::{AsyncReadExt, AsyncWriteExt};
218 use tokio::net::TcpListener;
219
220 let hits = Arc::new(AtomicUsize::new(0));
221 let authed = Arc::new(AtomicUsize::new(0));
222 let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind listener");
223 let addr = listener.local_addr().expect("listener addr");
224 let server_task = tokio::spawn({
225 let hits = Arc::clone(&hits);
226 let authed = Arc::clone(&authed);
227 async move {
228 for _ in 0..2 {
229 let Ok((mut stream, _)) = listener.accept().await else {
230 break;
231 };
232 let mut buf = Vec::new();
233 let mut chunk = [0_u8; 1024];
234 while let Ok(n) = stream.read(&mut chunk).await {
235 if n == 0 {
236 break;
237 }
238 buf.extend_from_slice(&chunk[..n]);
239 if buf.len() > 65536 || String::from_utf8_lossy(&buf).contains("\r\n\r\n") {
240 break;
241 }
242 }
243 let request = String::from_utf8_lossy(&buf).into_owned();
244 let _ = hits.fetch_add(1, Ordering::SeqCst);
245 if request.contains("x-api-key: super-secret") {
246 let _ = authed.fetch_add(1, Ordering::SeqCst);
247 }
248 let response = if request.starts_with("GET /start ") {
249 "HTTP/1.1 307 Temporary Redirect\r\nlocation: /final\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
250 } else {
251 "HTTP/1.1 200 OK\r\ncontent-length: 8\r\nconnection: close\r\n\r\nfollowed"
252 };
253 drop(stream.write_all(response.as_bytes()).await);
254 drop(stream.shutdown().await);
255 }
256 }
257 });
258
259 let config = TimeoutsConfig::default();
260 let client = HttpClientFactory::for_llm(&config);
261 let response = client
262 .get(format!("http://{addr}/start"))
263 .header("x-api-key", "super-secret")
264 .send()
265 .await
266 .expect("request completes");
267 assert_eq!(response.status(), reqwest::StatusCode::OK);
268 let body =
269 vtcode_commons::http_body::read_text_limited(response, vtcode_commons::http_body::API_BODY_LIMIT_BYTES)
270 .await
271 .expect("body");
272 assert_eq!(body, "followed");
273
274 server_task.await.expect("server completes");
275 assert_eq!(hits.load(Ordering::SeqCst), 2, "both hops must reach the same origin");
276 assert_eq!(authed.load(Ordering::SeqCst), 2, "credentials stay attached within the origin");
277 }
278}