toolkit_http/config.rs
1use std::collections::HashSet;
2use std::path::PathBuf;
3use std::sync::Arc;
4use std::time::Duration;
5
6use rustls_pki_types::CertificateDer;
7
8/// Default User-Agent string for HTTP requests
9pub const DEFAULT_USER_AGENT: &str = concat!("toolkit-http/", env!("CARGO_PKG_VERSION"));
10
11/// Standard idempotency key header name (display form)
12pub const IDEMPOTENCY_KEY_HEADER: &str = "Idempotency-Key";
13
14/// Lowercase idempotency key header for `HeaderName` construction
15const IDEMPOTENCY_KEY_HEADER_LOWER: &str = "idempotency-key";
16
17/// Conditions that trigger a retry
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19#[non_exhaustive]
20pub enum RetryTrigger {
21 /// Transport-level errors (connection refused, DNS failure, reset, etc.)
22 TransportError,
23 /// Request timeout
24 Timeout,
25 /// Specific HTTP status code
26 Status(u16),
27 /// Error that is never retryable (e.g., `DeadlineExceeded`, `ServiceClosed`)
28 NonRetryable,
29}
30
31impl RetryTrigger {
32 /// Create a trigger for HTTP 429 Too Many Requests
33 pub const TOO_MANY_REQUESTS: Self = Self::Status(429);
34 /// Create a trigger for HTTP 408 Request Timeout
35 pub const REQUEST_TIMEOUT: Self = Self::Status(408);
36 /// Create a trigger for HTTP 500 Internal Server Error
37 pub const INTERNAL_SERVER_ERROR: Self = Self::Status(500);
38 /// Create a trigger for HTTP 502 Bad Gateway
39 pub const BAD_GATEWAY: Self = Self::Status(502);
40 /// Create a trigger for HTTP 503 Service Unavailable
41 pub const SERVICE_UNAVAILABLE: Self = Self::Status(503);
42 /// Create a trigger for HTTP 504 Gateway Timeout
43 pub const GATEWAY_TIMEOUT: Self = Self::Status(504);
44}
45
46/// Check if HTTP method is idempotent (safe to retry) per RFC 9110.
47///
48/// Idempotent methods: GET, HEAD, PUT, DELETE, OPTIONS, TRACE.
49/// Non-idempotent methods: POST, PATCH.
50#[must_use]
51pub fn is_idempotent_method(method: &http::Method) -> bool {
52 matches!(
53 *method,
54 http::Method::GET
55 | http::Method::HEAD
56 | http::Method::PUT
57 | http::Method::DELETE
58 | http::Method::OPTIONS
59 | http::Method::TRACE
60 )
61}
62
63/// Exponential backoff configuration for retries
64///
65/// Computes delay as: `min(initial * multiplier^attempt, max)` with optional jitter.
66#[derive(Debug, Clone)]
67pub struct ExponentialBackoff {
68 /// Initial backoff duration (default: 100ms)
69 pub initial: Duration,
70
71 /// Maximum backoff duration (default: 10s)
72 pub max: Duration,
73
74 /// Backoff multiplier for exponential growth (default: 2.0)
75 pub multiplier: f64,
76
77 /// Enable jitter to prevent thundering herd (default: true)
78 ///
79 /// When enabled, adds random delay of 0-25% to each backoff.
80 pub jitter: bool,
81}
82
83impl Default for ExponentialBackoff {
84 fn default() -> Self {
85 Self {
86 initial: Duration::from_millis(100),
87 max: Duration::from_secs(10),
88 multiplier: 2.0,
89 jitter: true,
90 }
91 }
92}
93
94impl ExponentialBackoff {
95 /// Create backoff with custom initial and max durations
96 #[must_use]
97 pub fn new(initial: Duration, max: Duration) -> Self {
98 Self {
99 initial,
100 max,
101 ..Default::default()
102 }
103 }
104
105 /// Create fast backoff for testing (1ms initial, 100ms max, no jitter)
106 #[must_use]
107 pub fn fast() -> Self {
108 Self {
109 initial: Duration::from_millis(1),
110 max: Duration::from_millis(100),
111 multiplier: 2.0,
112 jitter: false,
113 }
114 }
115
116 /// Create aggressive backoff (50ms initial, 30s max)
117 #[must_use]
118 pub fn aggressive() -> Self {
119 Self {
120 initial: Duration::from_millis(50),
121 max: Duration::from_secs(30),
122 multiplier: 2.0,
123 jitter: true,
124 }
125 }
126}
127
128/// Retry policy configuration with exponential backoff
129///
130/// Retry decisions are based on two sets of triggers:
131/// - `always_retry`: Conditions that always trigger retry (regardless of HTTP method)
132/// - `idempotent_retry`: Conditions that trigger retry only for idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS, TRACE)
133/// OR when the request has an idempotency key header
134///
135/// **Safety by default**: Non-idempotent methods (POST, PATCH) are only retried on
136/// triggers in `always_retry` unless the request contains an idempotency key header.
137#[derive(Debug, Clone)]
138pub struct RetryConfig {
139 /// Maximum number of retries after the initial attempt (0 = no retries, default: 3)
140 /// Total attempts = 1 (initial) + `max_retries`
141 pub max_retries: usize,
142
143 /// Backoff strategy configuration
144 pub backoff: ExponentialBackoff,
145
146 /// Triggers that always retry regardless of HTTP method
147 /// Default: [Status(429)]
148 ///
149 /// **Note**: `TransportError` and `Timeout` are NOT in `always_retry` by default to avoid
150 /// duplicating non-idempotent requests. They are in `idempotent_retry` instead.
151 pub always_retry: HashSet<RetryTrigger>,
152
153 /// Triggers that only retry for idempotent methods (GET, HEAD, OPTIONS, TRACE)
154 /// OR when the request has an idempotency key header.
155 /// Default: `[TransportError, Timeout, Status(408), Status(500), Status(502), Status(503), Status(504)]`
156 pub idempotent_retry: HashSet<RetryTrigger>,
157
158 /// If true, ignore the `Retry-After` HTTP header and always use backoff policy.
159 /// If false (default), use `Retry-After` value when present for computing retry delay.
160 pub ignore_retry_after: bool,
161
162 /// Maximum bytes to drain from response body before retrying on HTTP status.
163 /// Draining the body allows connection reuse. Default: 64 KiB.
164 /// If the body exceeds this limit, draining stops and the connection may not be reused.
165 ///
166 /// **Note**: This limit applies to **decompressed** bytes. For compressed responses,
167 /// the actual network traffic may be smaller than the configured limit.
168 pub retry_response_drain_limit: usize,
169
170 /// Whether to skip draining response body on retry.
171 ///
172 /// When `true`, the response body is not drained before retrying, meaning
173 /// connections may not be reused after retryable errors. This saves CPU/memory
174 /// by not decompressing error response bodies.
175 ///
176 /// # Performance Tradeoff
177 ///
178 /// Body draining operates on **decompressed** bytes (after `DecompressionLayer`).
179 /// When servers return compressed error responses (e.g., gzip-compressed 503 HTML),
180 /// draining requires CPU to decompress the body even though we discard the content.
181 ///
182 /// **Recommendation:**
183 /// - Set to `true` for high-throughput services where connection reuse is less
184 /// important than CPU efficiency, or when error responses are typically compressed
185 /// - Keep `false` (default) for low-to-medium throughput services where connection
186 /// reuse reduces latency and TCP connection overhead
187 ///
188 /// The `Content-Length` header is checked before draining; bodies larger than
189 /// `retry_response_drain_limit` are skipped automatically regardless of this setting.
190 ///
191 /// Default: `false` (drain enabled for connection reuse)
192 pub skip_drain_on_retry: bool,
193
194 /// Header name that, when present on a request, enables retry for non-idempotent methods.
195 /// Default: "Idempotency-Key"
196 ///
197 /// Set to `None` to disable idempotency-key based retry (only `always_retry` triggers
198 /// will apply to non-idempotent methods).
199 ///
200 /// When a request includes this header, triggers in `idempotent_retry` will apply
201 /// regardless of the HTTP method.
202 ///
203 /// Pre-parsed at config construction to avoid runtime parsing overhead.
204 pub idempotency_key_header: Option<http::header::HeaderName>,
205}
206
207/// Default drain limit for response bodies before retry (64 KiB)
208pub const DEFAULT_RETRY_RESPONSE_DRAIN_LIMIT: usize = 64 * 1024;
209
210impl Default for RetryConfig {
211 fn default() -> Self {
212 Self {
213 max_retries: 3,
214 backoff: ExponentialBackoff::default(),
215 // Only 429 always retries - server explicitly requests retry
216 always_retry: HashSet::from([RetryTrigger::TOO_MANY_REQUESTS]),
217 // TransportError and Timeout moved here for safety - only retry idempotent methods
218 // or when idempotency key header is present
219 idempotent_retry: HashSet::from([
220 RetryTrigger::TransportError,
221 RetryTrigger::Timeout,
222 RetryTrigger::REQUEST_TIMEOUT,
223 RetryTrigger::INTERNAL_SERVER_ERROR,
224 RetryTrigger::BAD_GATEWAY,
225 RetryTrigger::SERVICE_UNAVAILABLE,
226 RetryTrigger::GATEWAY_TIMEOUT,
227 ]),
228 ignore_retry_after: false,
229 retry_response_drain_limit: DEFAULT_RETRY_RESPONSE_DRAIN_LIMIT,
230 skip_drain_on_retry: false,
231 idempotency_key_header: Some(http::header::HeaderName::from_static(
232 IDEMPOTENCY_KEY_HEADER_LOWER,
233 )),
234 }
235 }
236}
237
238impl RetryConfig {
239 /// Create config with no retries
240 #[must_use]
241 pub fn disabled() -> Self {
242 Self {
243 max_retries: 0,
244 ..Default::default()
245 }
246 }
247
248 /// Create config with aggressive retry policy (retries all 5xx for any method)
249 ///
250 /// **WARNING**: This policy retries non-idempotent methods on transport errors
251 /// and timeouts, which may cause duplicate side effects. Use with caution.
252 #[must_use]
253 pub fn aggressive() -> Self {
254 Self {
255 max_retries: 5,
256 backoff: ExponentialBackoff::aggressive(),
257 always_retry: HashSet::from([
258 RetryTrigger::TransportError,
259 RetryTrigger::Timeout,
260 RetryTrigger::TOO_MANY_REQUESTS,
261 RetryTrigger::REQUEST_TIMEOUT,
262 RetryTrigger::INTERNAL_SERVER_ERROR,
263 RetryTrigger::BAD_GATEWAY,
264 RetryTrigger::SERVICE_UNAVAILABLE,
265 RetryTrigger::GATEWAY_TIMEOUT,
266 ]),
267 idempotent_retry: HashSet::new(),
268 ignore_retry_after: false,
269 retry_response_drain_limit: DEFAULT_RETRY_RESPONSE_DRAIN_LIMIT,
270 skip_drain_on_retry: false,
271 idempotency_key_header: Some(http::header::HeaderName::from_static(
272 IDEMPOTENCY_KEY_HEADER_LOWER,
273 )),
274 }
275 }
276
277 /// Check if the given trigger should cause a retry for the given HTTP method
278 ///
279 /// # Arguments
280 /// * `trigger` - The condition that triggered the retry consideration
281 /// * `method` - The HTTP method of the request
282 /// * `has_idempotency_key` - Whether the request has an idempotency key header
283 ///
284 /// # Retry Logic
285 /// - Triggers in `always_retry` are always retried regardless of method
286 /// - Triggers in `idempotent_retry` are retried if:
287 /// - The method is idempotent (GET, HEAD, PUT, DELETE, OPTIONS, TRACE), OR
288 /// - The request has an idempotency key header
289 #[must_use]
290 pub fn should_retry(
291 &self,
292 trigger: RetryTrigger,
293 method: &http::Method,
294 has_idempotency_key: bool,
295 ) -> bool {
296 if self.always_retry.contains(&trigger) {
297 return true;
298 }
299 if self.idempotent_retry.contains(&trigger)
300 && (is_idempotent_method(method) || has_idempotency_key)
301 {
302 return true;
303 }
304 false
305 }
306}
307
308/// Concurrency-limit configuration.
309///
310/// Despite the name, this is a *concurrency* cap (max in-flight requests), not a
311/// requests-per-second rate limit. Installed by
312/// [`HttpClientBuilder::concurrency_limit`](crate::builder::HttpClientBuilder::concurrency_limit);
313/// see there for the load-shedding behaviour.
314#[derive(Debug, Clone)]
315pub struct RateLimitConfig {
316 /// Maximum in-flight requests at once. Defaults to 100
317 /// ([`RateLimitConfig::default`]). `usize::MAX` disables the limiter
318 /// entirely (the layer is skipped in `build`); `0` is clamped to `1` at
319 /// `build` time so the client can never wedge shedding every request.
320 pub max_concurrent_requests: usize,
321}
322
323impl Default for RateLimitConfig {
324 fn default() -> Self {
325 Self {
326 max_concurrent_requests: 100,
327 }
328 }
329}
330
331impl RateLimitConfig {
332 /// Create config with unlimited concurrency
333 #[must_use]
334 pub fn unlimited() -> Self {
335 Self {
336 max_concurrent_requests: usize::MAX,
337 }
338 }
339
340 /// Create config with very conservative limit
341 #[must_use]
342 pub fn conservative() -> Self {
343 Self {
344 max_concurrent_requests: 10,
345 }
346 }
347}
348
349/// Configuration for redirect behavior
350///
351/// Controls how the HTTP client handles 3xx redirect responses with security protections.
352///
353/// ## Security Features
354///
355/// - **Same-origin enforcement**: By default, only follows redirects to the same host
356/// - **Header stripping**: Removes `Authorization`, `Cookie` on cross-origin redirects
357/// - **Downgrade protection**: Blocks HTTPS → HTTP redirects
358/// - **Host allow-list**: Configurable list of trusted redirect targets
359///
360/// ## Example
361///
362/// ```rust,ignore
363/// use toolkit_http::RedirectConfig;
364/// use std::collections::HashSet;
365///
366/// // Permissive mode for general-purpose clients
367/// let config = RedirectConfig::permissive();
368///
369/// // Custom allow-list for trusted hosts
370/// let config = RedirectConfig {
371/// same_origin_only: true,
372/// allowed_redirect_hosts: HashSet::from(["cdn.example.com".to_string()]),
373/// ..Default::default()
374/// };
375/// ```
376#[derive(Debug, Clone)]
377pub struct RedirectConfig {
378 /// Maximum number of redirects to follow (default: 10)
379 ///
380 /// Set to `0` to disable redirect following entirely.
381 pub max_redirects: usize,
382
383 /// Only allow same-origin redirects (default: true)
384 ///
385 /// When `true`, redirects to different hosts are blocked unless the target
386 /// host is in `allowed_redirect_hosts`.
387 ///
388 /// **Security**: This is the safest default, preventing SSRF attacks where
389 /// a malicious server redirects requests to internal services.
390 pub same_origin_only: bool,
391
392 /// Hosts that are allowed as redirect targets even when `same_origin_only` is true
393 ///
394 /// Use this to allow redirects to known, trusted hosts (e.g., CDN domains,
395 /// authentication servers).
396 ///
397 /// **Note**: Entries should be hostnames only, without scheme or port.
398 /// Example: `"cdn.example.com"`, not `"https://cdn.example.com"`.
399 pub allowed_redirect_hosts: HashSet<String>,
400
401 /// Strip sensitive headers on cross-origin redirects (default: true)
402 ///
403 /// When a redirect goes to a different origin (even if allowed), this removes:
404 /// - `Authorization` header (prevents credential leakage)
405 /// - `Cookie` header (prevents session hijacking)
406 /// - `Proxy-Authorization` header
407 ///
408 /// **Security**: Always keep this enabled unless you have specific requirements.
409 pub strip_sensitive_headers: bool,
410
411 /// Allow HTTPS → HTTP downgrades (default: false)
412 ///
413 /// When `false`, redirects from HTTPS to HTTP are blocked.
414 ///
415 /// **Security**: Downgrades expose traffic to interception. Only enable
416 /// for testing with local mock servers.
417 pub allow_https_downgrade: bool,
418}
419
420impl Default for RedirectConfig {
421 fn default() -> Self {
422 Self {
423 max_redirects: 10,
424 same_origin_only: true,
425 allowed_redirect_hosts: HashSet::new(),
426 strip_sensitive_headers: true,
427 allow_https_downgrade: false,
428 }
429 }
430}
431
432impl RedirectConfig {
433 /// Create a permissive configuration that allows all redirects with header stripping
434 ///
435 /// This is suitable for general-purpose HTTP clients that need to follow
436 /// redirects to any host, but still want protection against credential leakage.
437 ///
438 /// **Note**: This configuration still blocks HTTPS → HTTP downgrades.
439 #[must_use]
440 pub fn permissive() -> Self {
441 Self {
442 max_redirects: 10,
443 same_origin_only: false,
444 allowed_redirect_hosts: HashSet::new(),
445 strip_sensitive_headers: true,
446 allow_https_downgrade: false,
447 }
448 }
449
450 /// Create a configuration that disables redirect following
451 #[must_use]
452 pub fn disabled() -> Self {
453 Self {
454 max_redirects: 0,
455 ..Default::default()
456 }
457 }
458
459 /// Create a configuration for testing (allows HTTP, permissive)
460 ///
461 /// **WARNING**: Only use for local testing with mock servers.
462 #[must_use]
463 pub fn for_testing() -> Self {
464 Self {
465 max_redirects: 10,
466 same_origin_only: false,
467 allowed_redirect_hosts: HashSet::new(),
468 strip_sensitive_headers: true, // Still strip headers even in tests
469 allow_https_downgrade: true, // Allow for HTTP mock servers
470 }
471 }
472}
473
474/// TLS root certificate configuration
475#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
476#[non_exhaustive]
477pub enum TlsRootConfig {
478 /// Use Mozilla's root certificates (webpki-roots, no OS dependency)
479 #[default]
480 WebPki,
481 /// Use OS native root certificate store
482 Native,
483}
484
485/// Transport security configuration
486///
487/// Controls whether the client enforces TLS or allows insecure HTTP.
488///
489/// [`TransportSecurity::default`] is `TlsOnly` under `--features fips` and
490/// `AllowInsecureHttp` otherwise, the same as every non-testing preset.
491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
492#[non_exhaustive]
493pub enum TransportSecurity {
494 /// Require TLS for all connections (HTTPS only)
495 TlsOnly,
496 /// Allow insecure HTTP connections
497 ///
498 /// Use [`HttpClientBuilder::deny_insecure_http`] to switch to `TlsOnly`
499 /// when TLS enforcement is required.
500 ///
501 /// **FIPS**: under `--features fips` this is never the default; it has to
502 /// be selected explicitly, and [`HttpClientBuilder::build`] logs a warning
503 /// when it is. FIPS 140-3 covers the crypto modules, not whether a given
504 /// connection is encrypted, so whether plaintext is acceptable (e.g. to a
505 /// loopback mTLS sidecar) is a deployment decision.
506 ///
507 /// [`HttpClientBuilder::deny_insecure_http`]: crate::builder::HttpClientBuilder::deny_insecure_http
508 /// [`HttpClientBuilder::build`]: crate::builder::HttpClientBuilder::build
509 AllowInsecureHttp,
510}
511
512impl Default for TransportSecurity {
513 fn default() -> Self {
514 DEFAULT_TRANSPORT
515 }
516}
517
518/// Default transport security for built-in presets.
519///
520/// Under `--features fips` every non-testing preset defaults to
521/// [`TransportSecurity::TlsOnly`] so cleartext HTTP cannot be selected by
522/// accident; otherwise the historical [`TransportSecurity::AllowInsecureHttp`]
523/// default is retained for local development convenience.
524#[cfg(feature = "fips")]
525const DEFAULT_TRANSPORT: TransportSecurity = TransportSecurity::TlsOnly;
526#[cfg(not(feature = "fips"))]
527const DEFAULT_TRANSPORT: TransportSecurity = TransportSecurity::AllowInsecureHttp;
528
529/// Minimum TLS protocol version the client will negotiate.
530///
531/// Maps onto the rustls protocol-version slice passed to
532/// `ClientConfig::builder_with_provider(..).with_protocol_versions(..)`:
533/// - [`TlsVersion::Tls12`] advertises both TLS 1.2 and TLS 1.3 (the historical
534/// `with_safe_default_protocol_versions()` behaviour).
535/// - [`TlsVersion::Tls13`] advertises TLS 1.3 only.
536///
537/// This is a *user* knob; it does not relax FIPS hardening. Under
538/// `--features fips`, `tls::apply_fips_hardening` still asserts
539/// `ClientConfig::fips()`, so a version selection incompatible with the active
540/// FIPS provider surfaces as a [`crate::error::HttpError::Tls`] at build time.
541#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
542#[non_exhaustive]
543pub enum TlsVersion {
544 /// Allow TLS 1.2 and TLS 1.3 (default — matches rustls safe defaults).
545 #[default]
546 Tls12,
547 /// Require TLS 1.3; reject TLS 1.2 handshakes.
548 Tls13,
549}
550
551/// Client-certificate (mutual TLS) identity.
552///
553/// Holds filesystem paths to PEM-encoded material rather than parsed key bytes
554/// so that [`HttpClientConfig`] stays cheaply `Clone`/`Debug` and no private-key
555/// bytes are held in the config. The files are read and parsed lazily in
556/// [`HttpClientBuilder::build`]; IO or parse failures are reported as
557/// [`crate::error::HttpError::Tls`].
558///
559/// [`HttpClientBuilder::build`]: crate::builder::HttpClientBuilder::build
560#[derive(Debug, Clone, PartialEq, Eq)]
561#[non_exhaustive]
562pub struct ClientAuthConfig {
563 /// Path to a PEM file containing the client certificate chain
564 /// (leaf first, then intermediates).
565 pub cert_chain: PathBuf,
566 /// Path to a PEM file containing the client private key
567 /// (PKCS#8, PKCS#1/RSA, or SEC1/EC).
568 pub key: PathBuf,
569}
570
571impl ClientAuthConfig {
572 /// Construct a mutual-TLS identity from PEM cert-chain and key file paths.
573 #[must_use]
574 pub fn new(cert_chain: impl Into<PathBuf>, key: impl Into<PathBuf>) -> Self {
575 Self {
576 cert_chain: cert_chain.into(),
577 key: key.into(),
578 }
579 }
580}
581
582/// TLS handshake configuration for the HTTP client.
583///
584/// Carries knobs that shape the rustls `ClientConfig` beyond the root-trust
585/// strategy (which lives in [`TlsRootConfig`]):
586/// - [`TlsConfig::min_version`] — minimum negotiated protocol version.
587/// - [`TlsConfig::client_auth`] — optional mutual-TLS client identity.
588#[derive(Debug, Clone, Default, PartialEq, Eq)]
589#[non_exhaustive]
590pub struct TlsConfig {
591 /// Minimum TLS protocol version (default: [`TlsVersion::Tls12`]).
592 pub min_version: TlsVersion,
593 /// Optional client-certificate identity for mutual TLS (default: `None`).
594 pub client_auth: Option<ClientAuthConfig>,
595}
596
597/// Overall HTTP client configuration
598#[derive(Clone)]
599#[non_exhaustive]
600pub struct HttpClientConfig {
601 /// Per-request timeout (default: 30 seconds)
602 ///
603 /// This timeout applies to each individual HTTP request/attempt.
604 /// If retries are enabled, each retry attempt gets its own timeout.
605 pub request_timeout: Duration,
606
607 /// Total timeout spanning all retry attempts (default: None)
608 ///
609 /// When set, the entire operation (including all retries and backoff delays)
610 /// must complete within this duration. If the deadline is exceeded,
611 /// the request fails with `HttpError::DeadlineExceeded(total_timeout)`.
612 ///
613 /// When `None`, there is no total deadline - each attempt can take up to
614 /// `request_timeout`, and retries can continue indefinitely within their limits.
615 pub total_timeout: Option<Duration>,
616
617 /// Maximum response body size in bytes (default: 10 MB)
618 pub max_body_size: usize,
619
620 /// User-Agent header value (default: "toolkit-http/1.0")
621 pub user_agent: String,
622
623 /// Retry policy configuration
624 pub retry: Option<RetryConfig>,
625
626 /// Rate limiting / concurrency configuration
627 pub rate_limit: Option<RateLimitConfig>,
628
629 /// Transport security mode.
630 ///
631 /// Default: `TlsOnly` under `--features fips`, `AllowInsecureHttp` otherwise.
632 /// Only [`HttpClientConfig::for_testing`] keeps `AllowInsecureHttp` regardless
633 /// of features. Under `--features fips`, setting `AllowInsecureHttp` is an
634 /// explicit opt-in: [`HttpClientBuilder::build`] accepts it and logs a warning.
635 ///
636 /// Use [`HttpClientBuilder::deny_insecure_http`] to enforce TLS for all connections.
637 ///
638 /// [`HttpClientBuilder::build`]: crate::builder::HttpClientBuilder::build
639 pub transport: TransportSecurity,
640
641 /// TLS root certificate strategy (default: `WebPki`). See also
642 /// [`extra_root_certs`](Self::extra_root_certs).
643 pub tls_roots: TlsRootConfig,
644
645 /// TLS handshake configuration: minimum protocol version and optional
646 /// mutual-TLS client identity (default: [`TlsConfig::default`] — TLS 1.2
647 /// floor, no client auth).
648 pub tls: TlsConfig,
649
650 /// Enable OpenTelemetry tracing layer (default: false)
651 /// Creates spans for outbound requests and injects trace context headers.
652 pub otel: bool,
653
654 /// Buffer capacity for concurrent request handling (default: 1024)
655 ///
656 /// The HTTP client uses an internal buffer to allow multiple concurrent
657 /// requests without external locking. This sets the maximum number of
658 /// requests that can be queued waiting for processing.
659 pub buffer_capacity: usize,
660
661 /// Redirect policy configuration (default: same-origin only with header stripping)
662 ///
663 /// Controls how 3xx redirect responses are handled with security protections:
664 /// - Same-origin enforcement (SSRF protection)
665 /// - Sensitive header stripping on cross-origin redirects
666 /// - HTTPS downgrade protection
667 ///
668 /// Use `RedirectConfig::permissive()` for general-purpose HTTP client behavior
669 /// that allows cross-origin redirects with header stripping.
670 ///
671 /// Use `RedirectConfig::disabled()` to turn off redirect following entirely.
672 pub redirect: RedirectConfig,
673
674 /// Timeout for idle connections in the pool (default: 90 seconds)
675 ///
676 /// Connections that remain idle (unused) for longer than this duration
677 /// will be closed and removed from the pool. This prevents resource leaks
678 /// and ensures connections don't become stale.
679 ///
680 /// Set to `None` to use hyper-util's default idle timeout.
681 pub pool_idle_timeout: Option<Duration>,
682
683 /// Maximum number of idle connections per host (default: 32)
684 ///
685 /// Limits how many idle connections are kept in the pool for each host.
686 /// Setting this to `0` disables connection reuse entirely.
687 /// Setting this too high may waste resources on rarely-used connections.
688 ///
689 /// **Note**: This only limits *idle* connections. Active connections are
690 /// not limited by this setting.
691 pub pool_max_idle_per_host: usize,
692
693 /// Bound on establishing a connection: DNS, TCP connect (to the destination
694 /// or the proxy), proxy `CONNECT` and TLS handshake together (default:
695 /// `None`, bounded only by `request_timeout`). A connect timeout surfaces
696 /// as [`HttpError::Transport`](crate::HttpError::Transport).
697 pub connect_timeout: Option<Duration>,
698
699 /// Extra trust anchors added to the store selected by `tls_roots`
700 /// (default: none). Use for a private CA without touching the OS store.
701 /// With [`TlsRootConfig::Native`], they also stand in for an OS store
702 /// that has no usable certificate.
703 pub extra_root_certs: Arc<[CertificateDer<'static>]>,
704
705 /// Outbound (forward) proxy (default: [`OutboundProxy::None`]).
706 pub outbound_proxy: OutboundProxy,
707}
708
709/// Outbound (forward) proxy for client connections.
710///
711/// HTTPS destinations go through an HTTP `CONNECT` tunnel; TLS still runs end
712/// to end with the destination, so `tls_roots`, `extra_root_certs` and FIPS
713/// hardening apply unchanged. Plain-HTTP destinations (only reachable with
714/// [`TransportSecurity::AllowInsecureHttp`]) are forwarded in absolute form.
715///
716/// Proxy URLs use `http` (a missing scheme means `http`) or `https`; anything
717/// else fails [`HttpClientBuilder::build`]. An `https://` proxy is verified
718/// with the same roots as destinations but is never sent the client
719/// certificate. SOCKS and OS proxy settings are not supported. Credentials in
720/// the URL (`http://user:pass@host:port`, percent-encoded, `@` included) are sent to the
721/// proxy as `Basic` `Proxy-Authorization`; with an `http://` proxy that hop,
722/// and the credentials, are cleartext.
723///
724/// [`HttpClientBuilder::build`]: crate::builder::HttpClientBuilder::build
725#[derive(Clone, Debug, Default, PartialEq, Eq)]
726#[non_exhaustive]
727pub enum OutboundProxy {
728 /// Connect directly (default).
729 #[default]
730 None,
731 /// Read `HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY` and `NO_PROXY` once, when
732 /// the client is built.
733 ///
734 /// `HTTPS_PROXY` is used for HTTPS destinations and `HTTP_PROXY` for plain
735 /// HTTP; `ALL_PROXY` fills in when that variable is unset or empty. Of
736 /// each upper/lower case pair the upper case one wins when it is set, even
737 /// to an empty value (curl prefers lower case). Only the URLs that will be
738 /// used are validated: `HTTP_PROXY` is ignored unless plain HTTP is
739 /// allowed.
740 ///
741 /// When `REQUEST_METHOD` is set (a CGI process), the environment proxy is
742 /// ignored: `HTTP_PROXY` there can come from a request header (httpoxy).
743 FromEnv,
744 /// Use the given proxies.
745 Explicit(ExplicitProxy),
746}
747
748impl From<ExplicitProxy> for OutboundProxy {
749 fn from(proxy: ExplicitProxy) -> Self {
750 Self::Explicit(proxy)
751 }
752}
753
754/// Proxies for [`OutboundProxy::Explicit`].
755#[derive(Clone, Default, PartialEq, Eq)]
756#[non_exhaustive]
757pub struct ExplicitProxy {
758 /// Proxy for `http://` destinations.
759 pub http: Option<String>,
760 /// Proxy for `https://` destinations.
761 pub https: Option<String>,
762 /// Comma-separated bypass list in `NO_PROXY` syntax: host names
763 /// (matching subdomains too), IPs, CIDRs, or `*`.
764 pub no_proxy: Option<String>,
765}
766
767impl ExplicitProxy {
768 /// Use `proxy_url` for both `http://` and `https://` destinations.
769 #[must_use]
770 pub fn all(proxy_url: impl Into<String>) -> Self {
771 let url = proxy_url.into();
772 Self {
773 http: Some(url.clone()),
774 https: Some(url),
775 no_proxy: None,
776 }
777 }
778
779 /// Set the proxy for `http://` destinations.
780 #[must_use]
781 pub fn with_http(mut self, proxy_url: impl Into<String>) -> Self {
782 self.http = Some(proxy_url.into());
783 self
784 }
785
786 /// Set the proxy for `https://` destinations.
787 #[must_use]
788 pub fn with_https(mut self, proxy_url: impl Into<String>) -> Self {
789 self.https = Some(proxy_url.into());
790 self
791 }
792
793 /// Set the bypass list.
794 #[must_use]
795 pub fn with_no_proxy(mut self, list: impl Into<String>) -> Self {
796 self.no_proxy = Some(list.into());
797 self
798 }
799}
800
801impl std::fmt::Debug for ExplicitProxy {
802 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
803 f.debug_struct("ExplicitProxy")
804 .field("http", &self.http.as_deref().map(redact_userinfo))
805 .field("https", &self.https.as_deref().map(redact_userinfo))
806 .field("no_proxy", &self.no_proxy)
807 .finish()
808 }
809}
810
811/// Replace everything between the scheme and the last `@` with `***`.
812///
813/// Uses the last `@` of the whole string, not of the authority: unencoded
814/// `/`, `?` or `#` in a password would otherwise end the authority early.
815/// Proxy URLs have no meaningful path, so over-redacting one is harmless.
816pub fn redact_userinfo(url: &str) -> String {
817 // Only a real scheme counts: a `://` inside a scheme-less password must
818 // not shield the credentials before it.
819 let after_scheme = url
820 .find("://")
821 .filter(|&i| {
822 let scheme = &url[..i];
823 scheme.starts_with(|c: char| c.is_ascii_alphabetic())
824 && scheme
825 .chars()
826 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
827 })
828 .map_or(0, |i| i + 3);
829 match url[after_scheme..].rfind('@') {
830 Some(at) => format!(
831 "{}***@{}",
832 &url[..after_scheme],
833 &url[after_scheme + at + 1..]
834 ),
835 None => url.to_owned(),
836 }
837}
838
839// Manual so `extra_root_certs` prints as a count, not as kilobytes of DER.
840impl std::fmt::Debug for HttpClientConfig {
841 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
842 f.debug_struct("HttpClientConfig")
843 .field("request_timeout", &self.request_timeout)
844 .field("total_timeout", &self.total_timeout)
845 .field("max_body_size", &self.max_body_size)
846 .field("user_agent", &self.user_agent)
847 .field("retry", &self.retry)
848 .field("rate_limit", &self.rate_limit)
849 .field("transport", &self.transport)
850 .field("tls_roots", &self.tls_roots)
851 .field("tls", &self.tls)
852 .field("otel", &self.otel)
853 .field("buffer_capacity", &self.buffer_capacity)
854 .field("redirect", &self.redirect)
855 .field("pool_idle_timeout", &self.pool_idle_timeout)
856 .field("pool_max_idle_per_host", &self.pool_max_idle_per_host)
857 .field("connect_timeout", &self.connect_timeout)
858 .field("extra_root_certs", &self.extra_root_certs.len())
859 .field("outbound_proxy", &self.outbound_proxy)
860 .finish()
861 }
862}
863
864impl Default for HttpClientConfig {
865 fn default() -> Self {
866 Self {
867 request_timeout: Duration::from_secs(30),
868 total_timeout: None,
869 max_body_size: 10 * 1024 * 1024, // 10 MB
870 user_agent: DEFAULT_USER_AGENT.to_owned(),
871 retry: Some(RetryConfig::default()),
872 rate_limit: Some(RateLimitConfig::default()),
873 transport: DEFAULT_TRANSPORT,
874 tls_roots: TlsRootConfig::default(),
875 tls: TlsConfig::default(),
876 otel: false,
877 buffer_capacity: 1024,
878 redirect: RedirectConfig::default(),
879 pool_idle_timeout: Some(Duration::from_secs(90)),
880 pool_max_idle_per_host: 32,
881 connect_timeout: None,
882 extra_root_certs: Arc::default(),
883 outbound_proxy: OutboundProxy::None,
884 }
885 }
886}
887
888impl HttpClientConfig {
889 /// Create minimal configuration (no retry, no rate limit, small timeout)
890 #[must_use]
891 pub fn minimal() -> Self {
892 Self {
893 request_timeout: Duration::from_secs(10),
894 total_timeout: None,
895 max_body_size: 1024 * 1024, // 1 MB
896 user_agent: DEFAULT_USER_AGENT.to_owned(),
897 retry: None,
898 rate_limit: None,
899 transport: DEFAULT_TRANSPORT,
900 tls_roots: TlsRootConfig::default(),
901 tls: TlsConfig::default(),
902 otel: false,
903 buffer_capacity: 256,
904 redirect: RedirectConfig::default(),
905 pool_idle_timeout: Some(Duration::from_secs(30)),
906 pool_max_idle_per_host: 8,
907 connect_timeout: None,
908 extra_root_certs: Arc::default(),
909 outbound_proxy: OutboundProxy::None,
910 }
911 }
912
913 /// Create configuration for infrastructure services (aggressive retry, large timeout)
914 #[must_use]
915 pub fn infra_default() -> Self {
916 Self {
917 request_timeout: Duration::from_mins(1),
918 total_timeout: None,
919 max_body_size: 50 * 1024 * 1024, // 50 MB
920 user_agent: DEFAULT_USER_AGENT.to_owned(),
921 retry: Some(RetryConfig::aggressive()),
922 rate_limit: Some(RateLimitConfig::default()),
923 transport: DEFAULT_TRANSPORT,
924 tls_roots: TlsRootConfig::default(),
925 tls: TlsConfig::default(),
926 otel: false,
927 buffer_capacity: 1024,
928 redirect: RedirectConfig::default(),
929 pool_idle_timeout: Some(Duration::from_mins(2)),
930 pool_max_idle_per_host: 64,
931 connect_timeout: None,
932 extra_root_certs: Arc::default(),
933 outbound_proxy: OutboundProxy::None,
934 }
935 }
936
937 /// Create configuration for `OAuth2` token endpoints (conservative retry)
938 ///
939 /// Token endpoints use POST but are effectively idempotent for retry purposes:
940 /// - Getting a token twice is safe (you'd just use the second one)
941 /// - Transport errors before response mean no token was issued
942 ///
943 /// This config retries on transport errors, timeout, and 429 for all methods.
944 #[must_use]
945 pub fn token_endpoint() -> Self {
946 Self {
947 request_timeout: Duration::from_secs(30),
948 total_timeout: None,
949 max_body_size: 1024 * 1024, // 1 MB
950 user_agent: DEFAULT_USER_AGENT.to_owned(),
951 retry: Some(RetryConfig {
952 max_retries: 3,
953 // For token endpoints: retry transport errors, timeout, and 429
954 // Note: Token requests (POST) are effectively idempotent - getting
955 // a token twice is safe, so we put these in always_retry
956 always_retry: HashSet::from([
957 RetryTrigger::TransportError,
958 RetryTrigger::Timeout,
959 RetryTrigger::TOO_MANY_REQUESTS,
960 ]),
961 idempotent_retry: HashSet::new(), // No additional retries for 5xx
962 ignore_retry_after: false,
963 retry_response_drain_limit: DEFAULT_RETRY_RESPONSE_DRAIN_LIMIT,
964 idempotency_key_header: None, // Not needed - always_retry handles all cases
965 ..RetryConfig::default()
966 }),
967 rate_limit: Some(RateLimitConfig::conservative()),
968 transport: DEFAULT_TRANSPORT,
969 tls_roots: TlsRootConfig::default(),
970 tls: TlsConfig::default(),
971 otel: false,
972 buffer_capacity: 256,
973 redirect: RedirectConfig::default(),
974 pool_idle_timeout: Some(Duration::from_mins(1)),
975 pool_max_idle_per_host: 4,
976 connect_timeout: None,
977 extra_root_certs: Arc::default(),
978 outbound_proxy: OutboundProxy::None,
979 }
980 }
981
982 /// Create configuration for testing with mock servers.
983 ///
984 /// **This is the only built-in preset that sets
985 /// `transport: TransportSecurity::AllowInsecureHttp`** — every other
986 /// preset (`default`, `minimal`, `infra_default`, `token_endpoint`, `sse`)
987 /// uses `DEFAULT_TRANSPORT`, which is `TlsOnly` under `--features fips`.
988 ///
989 /// Intended for test code that wires up `httpmock` or other plaintext mock
990 /// servers. Under `--features fips` the client still builds, and
991 /// [`HttpClientBuilder::build`] logs a plaintext warning.
992 ///
993 /// [`HttpClientBuilder::build`]: crate::builder::HttpClientBuilder::build
994 #[must_use]
995 pub fn for_testing() -> Self {
996 Self {
997 request_timeout: Duration::from_secs(10),
998 total_timeout: None,
999 max_body_size: 1024 * 1024, // 1 MB
1000 user_agent: DEFAULT_USER_AGENT.to_owned(),
1001 retry: None,
1002 rate_limit: None,
1003 transport: TransportSecurity::AllowInsecureHttp,
1004 tls_roots: TlsRootConfig::default(),
1005 tls: TlsConfig::default(),
1006 otel: false,
1007 buffer_capacity: 256,
1008 redirect: RedirectConfig::for_testing(),
1009 pool_idle_timeout: Some(Duration::from_secs(10)),
1010 pool_max_idle_per_host: 4,
1011 connect_timeout: None,
1012 extra_root_certs: Arc::default(),
1013 outbound_proxy: OutboundProxy::None,
1014 }
1015 }
1016
1017 /// Create configuration optimized for Server-Sent Events (SSE) streaming.
1018 ///
1019 /// SSE connections are long-lived HTTP requests where the server holds the
1020 /// connection open and pushes events. This preset disables retry and rate
1021 /// limiting, and sets a permissive request timeout.
1022 ///
1023 /// # Timeout behavior
1024 ///
1025 /// `request_timeout` is set to 24 hours rather than truly unlimited,
1026 /// because `TimeoutLayer` requires a finite `Duration`. Override if needed:
1027 ///
1028 /// ```rust,ignore
1029 /// let mut config = HttpClientConfig::sse();
1030 /// config.request_timeout = Duration::from_secs(3600); // 1 hour
1031 /// let client = HttpClientBuilder::with_config(config).build()?;
1032 /// ```
1033 ///
1034 /// # Streaming
1035 ///
1036 /// Use [`HttpResponse::into_body()`] for streaming — it bypasses the
1037 /// `max_body_size` limit. SSE reconnection with `Last-Event-ID` is the
1038 /// caller's responsibility.
1039 ///
1040 /// ```rust,ignore
1041 /// let client = HttpClientBuilder::with_config(HttpClientConfig::sse()).build()?;
1042 ///
1043 /// let response = client
1044 /// .get("https://api.example.com/events")
1045 /// .header("accept", "text/event-stream")
1046 /// .send()
1047 /// .await?;
1048 ///
1049 /// let mut body = response.into_body();
1050 /// while let Some(frame) = body.frame().await {
1051 /// let frame = frame?;
1052 /// if let Some(chunk) = frame.data_ref() {
1053 /// // parse SSE event data
1054 /// }
1055 /// }
1056 /// ```
1057 #[must_use]
1058 pub fn sse() -> Self {
1059 Self {
1060 request_timeout: Duration::from_hours(24), // 24 hours
1061 total_timeout: None,
1062 max_body_size: 10 * 1024 * 1024, // 10 MB (only for bytes()/json(), not into_body())
1063 user_agent: DEFAULT_USER_AGENT.to_owned(),
1064 retry: None, // SSE reconnection is protocol-level (Last-Event-ID)
1065 rate_limit: None,
1066 transport: DEFAULT_TRANSPORT,
1067 tls_roots: TlsRootConfig::default(),
1068 tls: TlsConfig::default(),
1069 otel: false,
1070 buffer_capacity: 64,
1071 redirect: RedirectConfig::default(),
1072 pool_idle_timeout: None, // use hyper-util default
1073 pool_max_idle_per_host: 1,
1074 connect_timeout: None,
1075 extra_root_certs: Arc::default(),
1076 outbound_proxy: OutboundProxy::None,
1077 }
1078 }
1079
1080 /// Create configuration for a reverse-proxy data plane (e.g. the
1081 /// api-gateway edge forwarding to out-of-process gears).
1082 ///
1083 /// A gateway data plane has different requirements from a general-purpose
1084 /// client, because it forwards on behalf of an external caller rather than
1085 /// making its own calls:
1086 ///
1087 /// - **No retries.** The edge must not silently re-send a client's request
1088 /// (duplicating non-idempotent side effects) nor amplify load against an
1089 /// upstream that is already failing. Retry/idempotency is the client's or
1090 /// the upstream's concern.
1091 /// - **No client-side rate limit.** A single shared concurrency semaphore
1092 /// across the whole gateway would turn request N+1 into a spurious `503`
1093 /// `Overloaded`; back-pressure belongs to the upstream and the listener.
1094 /// - **No response body cap.** [`max_body_size`](Self::max_body_size) is set
1095 /// effectively unbounded so large downloads stream through untruncated
1096 /// (the forwarder streams the body via
1097 /// [`HttpResponse::into_limited_body`](crate::HttpResponse::into_limited_body)).
1098 /// The upstream gear owns its own size limits.
1099 /// - **No blanket request timeout.** Set to 24h (the `TimeoutLayer` floor is
1100 /// a finite `Duration`) so long-lived responses — SSE, chat streaming —
1101 /// are not cut off mid-stream at 30s.
1102 /// - **No redirect following.** A reverse proxy returns `3xx` to the client
1103 /// verbatim rather than resolving it server-side.
1104 #[must_use]
1105 pub fn proxy() -> Self {
1106 Self {
1107 request_timeout: Duration::from_hours(24), // effectively "no blanket timeout"
1108 total_timeout: None,
1109 max_body_size: usize::MAX, // no cap: stream large downloads untruncated
1110 user_agent: DEFAULT_USER_AGENT.to_owned(),
1111 retry: None, // the edge must not re-send or amplify load
1112 rate_limit: None, // no gateway-wide concurrency semaphore
1113 transport: DEFAULT_TRANSPORT,
1114 tls_roots: TlsRootConfig::default(),
1115 tls: TlsConfig::default(),
1116 otel: false,
1117 buffer_capacity: 1024,
1118 redirect: RedirectConfig::disabled(), // pass 3xx back to the client
1119 pool_idle_timeout: Some(Duration::from_secs(90)),
1120 pool_max_idle_per_host: 64, // fan out to many upstream gears
1121 connect_timeout: None,
1122 extra_root_certs: Arc::default(),
1123 outbound_proxy: OutboundProxy::None,
1124 }
1125 }
1126}
1127
1128#[cfg(test)]
1129#[cfg_attr(coverage_nightly, coverage(off))]
1130mod tests {
1131 use super::*;
1132
1133 #[test]
1134 fn redact_userinfo_hides_credentials() {
1135 assert_eq!(
1136 redact_userinfo("http://user:pa@ss@proxy:3128/x"),
1137 "http://***@proxy:3128/x"
1138 );
1139 assert_eq!(redact_userinfo("user:pass@proxy:3128"), "***@proxy:3128");
1140 assert_eq!(redact_userinfo("http://proxy:3128"), "http://proxy:3128");
1141 assert_eq!(redact_userinfo("user:a://b@proxy:3128"), "***@proxy:3128");
1142 for url in [
1143 "http://user:p?ss@proxy:3128",
1144 "http://user:p#ss@proxy:3128",
1145 "http://user:p/ss@proxy:3128",
1146 ] {
1147 assert_eq!(redact_userinfo(url), "http://***@proxy:3128", "{url}");
1148 }
1149 }
1150
1151 #[test]
1152 fn outbound_proxy_debug_hides_credentials() {
1153 let text = format!(
1154 "{:?}",
1155 OutboundProxy::from(ExplicitProxy::all("http://user:p?secret@proxy:3128"))
1156 );
1157 assert!(!text.contains("secret"), "{text}");
1158 assert!(text.contains("proxy:3128"), "{text}");
1159 }
1160
1161 #[test]
1162 fn test_retry_trigger_constants() {
1163 assert_eq!(RetryTrigger::TOO_MANY_REQUESTS, RetryTrigger::Status(429));
1164 assert_eq!(RetryTrigger::REQUEST_TIMEOUT, RetryTrigger::Status(408));
1165 assert_eq!(
1166 RetryTrigger::INTERNAL_SERVER_ERROR,
1167 RetryTrigger::Status(500)
1168 );
1169 assert_eq!(RetryTrigger::BAD_GATEWAY, RetryTrigger::Status(502));
1170 assert_eq!(RetryTrigger::SERVICE_UNAVAILABLE, RetryTrigger::Status(503));
1171 assert_eq!(RetryTrigger::GATEWAY_TIMEOUT, RetryTrigger::Status(504));
1172 }
1173
1174 #[test]
1175 fn test_is_idempotent_method() {
1176 // Idempotent per RFC 9110
1177 assert!(is_idempotent_method(&http::Method::GET));
1178 assert!(is_idempotent_method(&http::Method::HEAD));
1179 assert!(is_idempotent_method(&http::Method::PUT));
1180 assert!(is_idempotent_method(&http::Method::DELETE));
1181 assert!(is_idempotent_method(&http::Method::OPTIONS));
1182 assert!(is_idempotent_method(&http::Method::TRACE));
1183 // Non-idempotent
1184 assert!(!is_idempotent_method(&http::Method::POST));
1185 assert!(!is_idempotent_method(&http::Method::PATCH));
1186 }
1187
1188 #[test]
1189 fn test_retry_config_defaults() {
1190 let config = RetryConfig::default();
1191 assert_eq!(config.max_retries, 3);
1192 assert_eq!(config.backoff.initial, Duration::from_millis(100));
1193 assert_eq!(config.backoff.max, Duration::from_secs(10));
1194 assert!((config.backoff.multiplier - 2.0).abs() < f64::EPSILON);
1195 assert!(config.backoff.jitter);
1196
1197 // Check always_retry defaults - only 429 is always retried
1198 assert!(
1199 config
1200 .always_retry
1201 .contains(&RetryTrigger::TOO_MANY_REQUESTS)
1202 );
1203 assert_eq!(config.always_retry.len(), 1);
1204
1205 // Check idempotent_retry defaults - includes TransportError and Timeout for safety
1206 assert!(
1207 config
1208 .idempotent_retry
1209 .contains(&RetryTrigger::TransportError)
1210 );
1211 assert!(config.idempotent_retry.contains(&RetryTrigger::Timeout));
1212 assert!(
1213 config
1214 .idempotent_retry
1215 .contains(&RetryTrigger::REQUEST_TIMEOUT)
1216 );
1217 assert!(
1218 config
1219 .idempotent_retry
1220 .contains(&RetryTrigger::INTERNAL_SERVER_ERROR)
1221 );
1222 assert!(config.idempotent_retry.contains(&RetryTrigger::BAD_GATEWAY));
1223 assert!(
1224 config
1225 .idempotent_retry
1226 .contains(&RetryTrigger::SERVICE_UNAVAILABLE)
1227 );
1228 assert!(
1229 config
1230 .idempotent_retry
1231 .contains(&RetryTrigger::GATEWAY_TIMEOUT)
1232 );
1233 assert_eq!(config.idempotent_retry.len(), 7);
1234
1235 // Default respects Retry-After header
1236 assert!(!config.ignore_retry_after);
1237
1238 // Default drain limit
1239 assert_eq!(
1240 config.retry_response_drain_limit,
1241 DEFAULT_RETRY_RESPONSE_DRAIN_LIMIT
1242 );
1243
1244 // Default idempotency key header
1245 assert_eq!(
1246 config.idempotency_key_header,
1247 Some(http::header::HeaderName::from_static(
1248 IDEMPOTENCY_KEY_HEADER_LOWER
1249 ))
1250 );
1251 }
1252
1253 #[test]
1254 fn test_retry_config_disabled() {
1255 let config = RetryConfig::disabled();
1256 assert_eq!(config.max_retries, 0);
1257 }
1258
1259 #[test]
1260 fn test_retry_config_aggressive() {
1261 let config = RetryConfig::aggressive();
1262 assert_eq!(config.max_retries, 5);
1263 assert_eq!(config.backoff.initial, Duration::from_millis(50));
1264 assert_eq!(config.backoff.max, Duration::from_secs(30));
1265 // Aggressive moves all 5xx to always_retry
1266 assert!(
1267 config
1268 .always_retry
1269 .contains(&RetryTrigger::INTERNAL_SERVER_ERROR)
1270 );
1271 assert!(config.idempotent_retry.is_empty());
1272 }
1273
1274 #[test]
1275 fn test_should_retry_always() {
1276 let config = RetryConfig::default();
1277
1278 // 429 always retries regardless of method or idempotency key
1279 assert!(config.should_retry(RetryTrigger::TOO_MANY_REQUESTS, &http::Method::GET, false));
1280 assert!(config.should_retry(RetryTrigger::TOO_MANY_REQUESTS, &http::Method::POST, false));
1281 assert!(config.should_retry(RetryTrigger::TOO_MANY_REQUESTS, &http::Method::POST, true));
1282 }
1283
1284 #[test]
1285 fn test_should_retry_idempotent_only() {
1286 let config = RetryConfig::default();
1287
1288 // TransportError retries for idempotent methods only (by default)
1289 assert!(config.should_retry(RetryTrigger::TransportError, &http::Method::GET, false));
1290 assert!(!config.should_retry(RetryTrigger::TransportError, &http::Method::POST, false));
1291
1292 // 500 only retries for idempotent methods
1293 assert!(config.should_retry(
1294 RetryTrigger::INTERNAL_SERVER_ERROR,
1295 &http::Method::GET,
1296 false
1297 ));
1298 assert!(!config.should_retry(
1299 RetryTrigger::INTERNAL_SERVER_ERROR,
1300 &http::Method::POST,
1301 false
1302 ));
1303
1304 // 503 only retries for idempotent methods
1305 assert!(config.should_retry(
1306 RetryTrigger::SERVICE_UNAVAILABLE,
1307 &http::Method::HEAD,
1308 false
1309 ));
1310 assert!(!config.should_retry(
1311 RetryTrigger::SERVICE_UNAVAILABLE,
1312 &http::Method::POST,
1313 false
1314 ));
1315
1316 // Timeout only retries for idempotent methods
1317 assert!(config.should_retry(RetryTrigger::Timeout, &http::Method::GET, false));
1318 assert!(!config.should_retry(RetryTrigger::Timeout, &http::Method::POST, false));
1319 }
1320
1321 #[test]
1322 fn test_should_retry_with_idempotency_key() {
1323 let config = RetryConfig::default();
1324
1325 // TransportError retries for non-idempotent methods when idempotency key is present
1326 assert!(config.should_retry(RetryTrigger::TransportError, &http::Method::POST, true));
1327 assert!(config.should_retry(RetryTrigger::TransportError, &http::Method::PUT, true));
1328 assert!(config.should_retry(RetryTrigger::TransportError, &http::Method::DELETE, true));
1329 assert!(config.should_retry(RetryTrigger::TransportError, &http::Method::PATCH, true));
1330
1331 // Timeout retries for non-idempotent methods when idempotency key is present
1332 assert!(config.should_retry(RetryTrigger::Timeout, &http::Method::POST, true));
1333
1334 // 500 retries for non-idempotent methods when idempotency key is present
1335 assert!(config.should_retry(
1336 RetryTrigger::INTERNAL_SERVER_ERROR,
1337 &http::Method::POST,
1338 true
1339 ));
1340 }
1341
1342 #[test]
1343 fn test_should_retry_not_configured() {
1344 let config = RetryConfig::default();
1345
1346 // 400 Bad Request is not in any retry set
1347 assert!(!config.should_retry(RetryTrigger::Status(400), &http::Method::GET, false));
1348 assert!(!config.should_retry(RetryTrigger::Status(400), &http::Method::POST, false));
1349 assert!(!config.should_retry(RetryTrigger::Status(400), &http::Method::POST, true)); // Even with idempotency key
1350
1351 // 404 Not Found is not in any retry set
1352 assert!(!config.should_retry(RetryTrigger::Status(404), &http::Method::GET, false));
1353 }
1354
1355 #[test]
1356 fn test_rate_limit_config_defaults() {
1357 let config = RateLimitConfig::default();
1358 assert_eq!(config.max_concurrent_requests, 100);
1359 }
1360
1361 #[test]
1362 fn test_rate_limit_config_unlimited() {
1363 let config = RateLimitConfig::unlimited();
1364 assert_eq!(config.max_concurrent_requests, usize::MAX);
1365 }
1366
1367 #[test]
1368 fn test_rate_limit_config_conservative() {
1369 let config = RateLimitConfig::conservative();
1370 assert_eq!(config.max_concurrent_requests, 10);
1371 }
1372
1373 #[test]
1374 fn test_http_client_config_defaults() {
1375 let config = HttpClientConfig::default();
1376 assert_eq!(config.request_timeout, Duration::from_secs(30));
1377 assert_eq!(config.max_body_size, 10 * 1024 * 1024);
1378 assert_eq!(config.user_agent, DEFAULT_USER_AGENT);
1379 assert!(config.retry.is_some());
1380 assert!(config.rate_limit.is_some());
1381 #[cfg(not(feature = "fips"))]
1382 assert_eq!(config.transport, TransportSecurity::AllowInsecureHttp);
1383 #[cfg(feature = "fips")]
1384 assert_eq!(config.transport, TransportSecurity::TlsOnly);
1385 // TLS knobs default to a TLS 1.2 floor with no mutual-TLS identity.
1386 assert_eq!(config.tls.min_version, TlsVersion::Tls12);
1387 assert!(config.tls.client_auth.is_none());
1388 assert!(!config.otel);
1389 assert_eq!(config.buffer_capacity, 1024);
1390 }
1391
1392 #[test]
1393 fn test_http_client_config_minimal() {
1394 let config = HttpClientConfig::minimal();
1395 assert_eq!(config.request_timeout, Duration::from_secs(10));
1396 assert_eq!(config.max_body_size, 1024 * 1024);
1397 assert!(config.retry.is_none());
1398 assert!(config.rate_limit.is_none());
1399 }
1400
1401 #[test]
1402 fn test_http_client_config_infra_default() {
1403 let config = HttpClientConfig::infra_default();
1404 assert_eq!(config.request_timeout, Duration::from_mins(1));
1405 assert_eq!(config.max_body_size, 50 * 1024 * 1024);
1406 assert!(config.retry.is_some());
1407 assert_eq!(config.retry.unwrap().max_retries, 5);
1408 }
1409
1410 #[test]
1411 fn test_http_client_config_token_endpoint() {
1412 let config = HttpClientConfig::token_endpoint();
1413 assert_eq!(config.request_timeout, Duration::from_secs(30));
1414
1415 let retry = config.retry.unwrap();
1416 // Token endpoint: no idempotent-only retries (conservative for auth)
1417 assert!(retry.idempotent_retry.is_empty());
1418 // But still retry transport errors and 429
1419 assert!(retry.always_retry.contains(&RetryTrigger::TransportError));
1420 assert!(
1421 retry
1422 .always_retry
1423 .contains(&RetryTrigger::TOO_MANY_REQUESTS)
1424 );
1425
1426 let rate_limit = config.rate_limit.unwrap();
1427 assert_eq!(rate_limit.max_concurrent_requests, 10); // Conservative
1428 }
1429
1430 #[test]
1431 fn test_http_client_config_for_testing() {
1432 let config = HttpClientConfig::for_testing();
1433 assert_eq!(config.transport, TransportSecurity::AllowInsecureHttp);
1434 assert!(config.retry.is_none());
1435 }
1436
1437 #[test]
1438 fn test_http_client_config_sse() {
1439 let config = HttpClientConfig::sse();
1440 assert_eq!(config.request_timeout, Duration::from_hours(24));
1441 assert!(config.total_timeout.is_none());
1442 assert!(config.retry.is_none());
1443 assert!(config.rate_limit.is_none());
1444 assert!(!config.otel);
1445 assert_eq!(config.buffer_capacity, 64);
1446 assert!(config.pool_idle_timeout.is_none());
1447 assert_eq!(config.pool_max_idle_per_host, 1);
1448 }
1449
1450 #[test]
1451 fn test_http_client_config_proxy() {
1452 let config = HttpClientConfig::proxy();
1453 // No retries, no client-side rate limit: the edge must not re-send or
1454 // impose a gateway-wide concurrency ceiling.
1455 assert!(config.retry.is_none());
1456 assert!(config.rate_limit.is_none());
1457 // No response body cap: large downloads stream untruncated.
1458 assert_eq!(config.max_body_size, usize::MAX);
1459 // No blanket request timeout that would cut SSE/streaming at 30s.
1460 assert_eq!(config.request_timeout, Duration::from_hours(24));
1461 assert!(config.total_timeout.is_none());
1462 // A reverse proxy returns 3xx to the client rather than following it.
1463 assert_eq!(config.redirect.max_redirects, 0);
1464 }
1465}