1#![allow(
17 clippy::disallowed_methods,
18 reason = "This module implements the shared timeout policy; bare builders are the policy's own building blocks."
19)]
20
21use anyhow::anyhow;
22use reqwest::{Client, ClientBuilder};
23use std::future::Future;
24use std::sync::LazyLock;
25use std::time::Duration;
26
27use crate::retry::RetryPolicy;
28
29const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
31const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
33const DEFAULT_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct HttpTimeouts {
44 pub connect: Option<Duration>,
46 pub request: Option<Duration>,
48 pub download: Option<Duration>,
50}
51
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[serde(rename_all = "snake_case")]
60pub enum PostQuantumTlsPolicy {
61 #[default]
63 Prefer,
64 Require,
66}
67
68impl Default for HttpTimeouts {
69 fn default() -> Self {
70 Self {
71 connect: Some(DEFAULT_CONNECT_TIMEOUT),
72 request: Some(DEFAULT_REQUEST_TIMEOUT),
73 download: Some(DEFAULT_DOWNLOAD_TIMEOUT),
74 }
75 }
76}
77
78impl HttpTimeouts {
79 #[must_use]
82 pub const fn from_seconds(connect: u64, request: u64, download: u64) -> Self {
83 Self {
84 connect: duration_or_disabled(connect),
85 request: duration_or_disabled(request),
86 download: duration_or_disabled(download),
87 }
88 }
89
90 fn apply_to(self, mut builder: ClientBuilder) -> ClientBuilder {
93 if let Some(request) = self.request {
94 builder = builder.timeout(request);
95 }
96 if let Some(connect) = self.connect {
97 builder = builder.connect_timeout(connect);
98 }
99 builder
100 }
101}
102
103const fn duration_or_disabled(seconds: u64) -> Option<Duration> {
106 if seconds == 0 {
107 None
108 } else {
109 Some(Duration::from_secs(seconds))
110 }
111}
112
113static HTTP_TIMEOUTS: LazyLock<arc_swap::ArcSwap<HttpTimeouts>> =
114 LazyLock::new(|| arc_swap::ArcSwap::from_pointee(HttpTimeouts::default()));
115
116static HTTP_TLS_POLICY: LazyLock<std::sync::Mutex<Option<PostQuantumTlsPolicy>>> =
117 LazyLock::new(|| std::sync::Mutex::new(None));
118
119pub fn install_http_tls_policy(policy: PostQuantumTlsPolicy) -> anyhow::Result<()> {
130 let mut installed_policy = HTTP_TLS_POLICY
131 .lock()
132 .map_err(|error| anyhow!("HTTP TLS policy state is poisoned: {error}"))?;
133
134 validate_policy_change(*installed_policy, policy)?;
135 if installed_policy.is_some() {
136 return Ok(());
137 }
138
139 install_crypto_provider(policy)?;
140 *installed_policy = Some(policy);
141 Ok(())
142}
143
144fn validate_policy_change(
145 installed: Option<PostQuantumTlsPolicy>,
146 requested: PostQuantumTlsPolicy,
147) -> anyhow::Result<()> {
148 if installed.is_some_and(|installed| installed != requested) {
149 return Err(anyhow!(
150 "HTTP TLS policy cannot change from {:?} to {requested:?} after startup; restart VT Code",
151 installed
152 ));
153 }
154 Ok(())
155}
156
157pub fn post_quantum_tls_policy() -> anyhow::Result<PostQuantumTlsPolicy> {
159 let installed_policy = HTTP_TLS_POLICY
160 .lock()
161 .map_err(|error| anyhow!("HTTP TLS policy state is poisoned: {error}"))?;
162 Ok((*installed_policy).unwrap_or_default())
163}
164
165pub fn rustls_crypto_provider() -> anyhow::Result<rustls::crypto::CryptoProvider> {
170 crypto_provider(post_quantum_tls_policy()?)
171}
172
173fn crypto_provider(policy: PostQuantumTlsPolicy) -> anyhow::Result<rustls::crypto::CryptoProvider> {
174 let mut provider = rustls::crypto::aws_lc_rs::default_provider();
175 if policy == PostQuantumTlsPolicy::Require {
176 provider
177 .kx_groups
178 .retain(|group| group.name() == rustls::NamedGroup::X25519MLKEM768);
179 provider
180 .cipher_suites
181 .retain(|suite| suite.suite() == rustls::CipherSuite::TLS13_AES_256_GCM_SHA384);
182 validate_strict_provider(&provider)?;
183 }
184 Ok(provider)
185}
186
187fn validate_strict_provider(provider: &rustls::crypto::CryptoProvider) -> anyhow::Result<()> {
188 if provider.kx_groups.len() != 1
189 || provider
190 .kx_groups
191 .first()
192 .is_none_or(|group| group.name() != rustls::NamedGroup::X25519MLKEM768)
193 || provider.cipher_suites.len() != 1
194 || provider
195 .cipher_suites
196 .first()
197 .is_none_or(|suite| suite.suite() != rustls::CipherSuite::TLS13_AES_256_GCM_SHA384)
198 {
199 return Err(anyhow!("strict post-quantum TLS requires only X25519MLKEM768 and TLS13_AES_256_GCM_SHA384"));
200 }
201 Ok(())
202}
203
204fn install_crypto_provider(policy: PostQuantumTlsPolicy) -> anyhow::Result<()> {
205 if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
206 return if policy == PostQuantumTlsPolicy::Require {
207 validate_strict_provider(provider)
208 } else {
209 Ok(())
210 };
211 }
212
213 let provider = crypto_provider(policy)?;
214 if provider.clone().install_default().is_ok() {
215 return Ok(());
216 }
217
218 let installed = rustls::crypto::CryptoProvider::get_default()
219 .ok_or_else(|| anyhow!("Rustls default provider installation failed"))?;
220 if policy == PostQuantumTlsPolicy::Require {
221 validate_strict_provider(installed)?;
222 }
223 Ok(())
224}
225
226fn initialize_default_tls_policy() -> anyhow::Result<()> {
227 let mut installed_policy = HTTP_TLS_POLICY
228 .lock()
229 .map_err(|error| anyhow!("HTTP TLS policy state is poisoned: {error}"))?;
230 if installed_policy.is_none() {
231 install_crypto_provider(PostQuantumTlsPolicy::Prefer)?;
232 *installed_policy = Some(PostQuantumTlsPolicy::Prefer);
233 }
234 Ok(())
235}
236
237pub fn install_http_timeouts(timeouts: HttpTimeouts) {
245 if let Err(error) = initialize_default_tls_policy() {
246 tracing::error!(%error, "failed to initialize the default HTTP TLS policy");
247 }
248 HTTP_TIMEOUTS.store(std::sync::Arc::new(timeouts));
249}
250
251#[must_use]
253pub fn http_timeouts() -> HttpTimeouts {
254 **HTTP_TIMEOUTS.load()
255}
256
257fn apply_platform_proxy_policy(builder: ClientBuilder) -> ClientBuilder {
258 #[cfg(target_os = "macos")]
259 {
260 builder.no_proxy()
262 }
263 #[cfg(not(target_os = "macos"))]
264 {
265 builder
266 }
267}
268
269fn try_build_client<F>(configure: F) -> Result<Client, reqwest::Error>
274where
275 F: Fn(ClientBuilder) -> ClientBuilder,
276{
277 let primary_builder = configure(apply_platform_proxy_policy(ClientBuilder::new()));
278 match primary_builder.build() {
279 Ok(client) => Ok(client),
280 Err(primary_err) => {
281 let fallback_builder = HttpTimeouts::default().apply_to(apply_platform_proxy_policy(ClientBuilder::new()));
282 match fallback_builder.build() {
283 Ok(client) => Ok(client),
284 Err(fallback_err) => {
285 tracing::error!(
286 primary_error = %primary_err,
287 fallback_error = %fallback_err,
288 "HTTP client creation failed with both primary and fallback configurations"
289 );
290 Err(fallback_err)
291 }
292 }
293 }
294 }
295}
296
297fn build_client<F>(configure: F) -> Client
305where
306 F: Fn(ClientBuilder) -> ClientBuilder,
307{
308 try_build_client(configure).unwrap_or_else(|e| {
309 tracing::error!(
310 error = %e,
311 "HTTP client build failed (primary + fallback); falling back to bare default client. \
312 This usually indicates a TLS configuration issue or system resource exhaustion."
313 );
314 Client::new()
315 })
316}
317
318pub fn create_default_client() -> Client {
320 build_client(|builder| http_timeouts().apply_to(builder))
321}
322
323pub fn create_client_with_timeout(timeout: Duration) -> Client {
328 let connect = http_timeouts().connect;
329 build_client(move |builder| {
330 let builder = builder.timeout(timeout);
331 match connect {
332 Some(connect) => builder.connect_timeout(connect),
333 None => builder,
334 }
335 })
336}
337
338pub fn create_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
340 build_client(|builder| builder.timeout(request_timeout).connect_timeout(connect_timeout))
341}
342
343const SAME_ORIGIN_REDIRECT_LIMIT: usize = 10;
345
346pub fn same_origin_redirect_policy() -> reqwest::redirect::Policy {
357 reqwest::redirect::Policy::custom(|attempt| {
358 if attempt.previous().len() > SAME_ORIGIN_REDIRECT_LIMIT {
359 return attempt.stop();
360 }
361 let next = attempt.url();
362 let allowed = attempt
363 .previous()
364 .last()
365 .is_some_and(|previous| redirect_target_allowed(next, previous));
366 if allowed { attempt.follow() } else { attempt.stop() }
367 })
368}
369
370fn redirect_target_allowed(next: &reqwest::Url, previous: &reqwest::Url) -> bool {
376 if next.host_str().is_none() || next.host_str() != previous.host_str() {
377 return false;
378 }
379 if previous.scheme() == "https" && next.scheme() == "http" {
380 return false;
381 }
382 next.port_or_known_default() == previous.port_or_known_default()
383 || (previous.scheme() == "http" && next.scheme() == "https")
384}
385
386pub fn create_origin_bound_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
392 let build = |connect: Duration, request: Duration| {
393 apply_platform_proxy_policy(ClientBuilder::new())
394 .timeout(request)
395 .connect_timeout(connect)
396 .redirect(same_origin_redirect_policy())
397 .build()
398 };
399 match build(connect_timeout, request_timeout) {
400 Ok(client) => client,
401 Err(primary_err) => {
402 let fallback = HttpTimeouts::default()
403 .apply_to(apply_platform_proxy_policy(ClientBuilder::new()))
404 .redirect(same_origin_redirect_policy())
405 .build();
406 match fallback {
407 Ok(client) => client,
408 Err(fallback_err) => {
409 tracing::error!(
410 primary_error = %primary_err,
411 fallback_error = %fallback_err,
412 "Origin-bound HTTP client creation failed; falling back to a bare origin-bound client"
413 );
414 ClientBuilder::new()
415 .redirect(same_origin_redirect_policy())
416 .build()
417 .unwrap_or_else(|_| Client::new())
418 }
419 }
420 }
421 }
422}
423
424pub fn create_client_without_redirects(
426 connect_timeout: Duration,
427 request_timeout: Duration,
428) -> Result<Client, reqwest::Error> {
429 apply_platform_proxy_policy(ClientBuilder::new())
430 .timeout(request_timeout)
431 .connect_timeout(connect_timeout)
432 .redirect(reqwest::redirect::Policy::none())
433 .build()
434}
435
436pub fn create_default_client_without_redirects() -> Result<Client, reqwest::Error> {
441 let timeouts = http_timeouts();
442 let mut builder = apply_platform_proxy_policy(ClientBuilder::new()).redirect(reqwest::redirect::Policy::none());
443 if let Some(request) = timeouts.request {
444 builder = builder.timeout(request);
445 }
446 if let Some(connect) = timeouts.connect {
447 builder = builder.connect_timeout(connect);
448 }
449 builder.build()
450}
451
452pub fn create_client_with_user_agent(user_agent: &str) -> Client {
454 let timeouts = http_timeouts();
455 build_client(move |mut builder| {
456 builder = builder.user_agent(user_agent);
457 timeouts.apply_to(builder)
458 })
459}
460
461pub fn create_origin_bound_streaming_client() -> Client {
468 let connect = http_timeouts().connect;
469 let build = |builder: ClientBuilder| {
470 let builder = builder
471 .tcp_keepalive(Some(Duration::from_secs(60)))
472 .redirect(same_origin_redirect_policy());
473 match connect {
474 Some(connect) => builder.connect_timeout(connect),
475 None => builder,
476 }
477 };
478 match build(apply_platform_proxy_policy(ClientBuilder::new())).build() {
479 Ok(client) => client,
480 Err(primary_err) => {
481 tracing::error!(
482 primary_error = %primary_err,
483 "Origin-bound streaming HTTP client creation failed; using bare origin-bound client"
484 );
485 ClientBuilder::new()
486 .redirect(same_origin_redirect_policy())
487 .build()
488 .unwrap_or_else(|_| Client::new())
489 }
490 }
491}
492
493pub fn create_streaming_client() -> Client {
503 let connect = http_timeouts().connect;
504 build_client(move |builder| {
505 let builder = builder.tcp_keepalive(Some(Duration::from_secs(60)));
506 match connect {
507 Some(connect) => builder.connect_timeout(connect),
508 None => builder,
509 }
510 })
511}
512
513pub fn create_download_client(user_agent: &str) -> Client {
520 let timeouts = http_timeouts();
521 build_client(move |mut builder| {
522 builder = builder.user_agent(user_agent).tcp_keepalive(Some(Duration::from_secs(60)));
523 if let Some(download) = timeouts.download {
524 builder = builder.timeout(download);
525 }
526 if let Some(connect) = timeouts.connect {
527 builder = builder.connect_timeout(connect);
528 }
529 builder
530 })
531}
532
533pub fn get_or_create_default_client(existing: Option<Client>) -> Client {
535 existing.unwrap_or_else(create_default_client)
536}
537
538pub fn apply_connect_timeout(builder: ClientBuilder) -> ClientBuilder {
544 match http_timeouts().connect {
545 Some(connect) => builder.connect_timeout(connect),
546 None => builder,
547 }
548}
549
550pub async fn send_with_retry<F, Fut>(policy: &RetryPolicy, make_request: F) -> Result<reqwest::Response, reqwest::Error>
571where
572 F: Fn() -> Fut,
573 Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
574{
575 send_with_retry_inner(policy, true, make_request).await
576}
577
578pub async fn send_with_retry_transport_only<F, Fut>(
584 policy: &RetryPolicy,
585 make_request: F,
586) -> Result<reqwest::Response, reqwest::Error>
587where
588 F: Fn() -> Fut,
589 Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
590{
591 send_with_retry_inner(policy, false, make_request).await
592}
593
594async fn send_with_retry_inner<F, Fut>(
595 policy: &RetryPolicy,
596 retry_status: bool,
597 make_request: F,
598) -> Result<reqwest::Response, reqwest::Error>
599where
600 F: Fn() -> Fut,
601 Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
602{
603 let attempts = policy.max_attempts.max(1);
606 let mut attempt: u32 = 0;
607 loop {
608 if attempt > 0 {
609 tokio::time::sleep(policy.delay_for_attempt(attempt - 1)).await;
610 }
611 let last = attempt + 1 >= attempts;
612 match make_request().await {
613 Ok(response) if !retry_status || last || !policy.classify_status(response.status().as_u16()).retryable => {
614 return Ok(response);
615 }
616 Ok(_) => {}
617 Err(error) if error.is_builder() || last => return Err(error),
618 Err(_) => {}
619 }
620 attempt += 1;
621 }
622}
623
624#[cfg(test)]
625mod tests;