Skip to main content

toolkit_http/
client.rs

1use crate::builder::HttpClientBuilder;
2use crate::config::TransportSecurity;
3use crate::error::HttpError;
4use crate::request::RequestBuilder;
5use crate::response::ResponseBody;
6use bytes::Bytes;
7use http::{Request, Response};
8use http_body_util::Full;
9use std::future::Future;
10use std::pin::Pin;
11use tower::Service;
12use tower::buffer::Buffer;
13
14/// Type alias for the future type of the inner service
15pub type ServiceFuture =
16    Pin<Box<dyn Future<Output = Result<Response<ResponseBody>, HttpError>> + Send>>;
17
18/// Type alias for the buffered service
19/// Buffer<Req, F> in tower 0.5 where Req is the request type and F is the service future type
20pub type BufferedService = Buffer<Request<Full<Bytes>>, ServiceFuture>;
21
22/// HTTP client with tower middleware stack
23///
24/// This client provides a clean interface over a tower service stack that includes:
25/// - Timeout handling
26/// - Automatic retries with exponential backoff
27/// - User-Agent header injection
28/// - Concurrency limiting (optional)
29///
30/// Use [`HttpClientBuilder`] to construct instances with custom configuration.
31///
32/// # Thread Safety
33///
34/// `HttpClient` is `Clone + Send + Sync`. Cloning is cheap (internal channel clone).
35/// The client uses `tower::buffer::Buffer` internally, which allows true concurrent
36/// access without any mutex serialization. Callers do NOT need to wrap `HttpClient`
37/// in `Mutex` or `Arc<Mutex<_>>`.
38///
39/// # Example
40///
41/// ```no_run
42/// # use toolkit_http::HttpClient;
43/// # use toolkit_http::HttpError;
44///
45/// // Just store the client directly - no Mutex needed!
46/// struct MyService {
47///     http: HttpClient,
48/// }
49///
50/// # #[derive(serde::Deserialize)]
51/// struct Data;
52///
53/// impl MyService {
54///     async fn fetch(&self) -> Result<Data, HttpError> {
55///         // reqwest-like API: response has body-reading methods
56///         self.http.get("https://example.com/api").send().await?.json().await
57///     }
58/// }
59/// ```
60#[derive(Clone)]
61pub struct HttpClient {
62    /// Buffered middleware stack that executes requests.
63    pub(crate) service: BufferedService,
64    /// Maximum response body size in bytes accepted by this client.
65    pub(crate) max_body_size: usize,
66    /// Transport security policy the client was built with.
67    pub(crate) transport_security: TransportSecurity,
68}
69
70impl HttpClient {
71    /// Create a new HTTP client with default configuration
72    ///
73    /// # Errors
74    /// Returns an error if TLS initialization fails
75    pub fn new() -> Result<Self, HttpError> {
76        HttpClientBuilder::new().build()
77    }
78
79    /// Create a builder for configuring the HTTP client
80    #[must_use]
81    pub fn builder() -> HttpClientBuilder {
82        HttpClientBuilder::new()
83    }
84
85    /// Create a GET request builder
86    ///
87    /// Returns a [`RequestBuilder`] that can be configured with headers
88    /// before sending with `.send().await`.
89    ///
90    /// # URL Requirements
91    ///
92    /// The URL must be an absolute URI with scheme and authority (host).
93    /// Relative URLs like `/path` or `example.com/path` are rejected with
94    /// [`HttpError::InvalidUri`].
95    ///
96    /// Valid examples:
97    /// - `https://api.example.com/users`
98    /// - `http://localhost:8080/health` (requires [`TransportSecurity::AllowInsecureHttp`])
99    ///
100    /// # URL Construction
101    ///
102    /// Query parameters must be encoded into the URL externally (e.g. via `url::Url`):
103    ///
104    /// ```no_run
105    /// # use toolkit_http::HttpClient;
106    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
107    /// # let client = HttpClient::new()?;
108    /// use url::Url;
109    ///
110    /// let mut url = Url::parse("https://api.example.com/search")?;
111    /// url.query_pairs_mut().append_pair("q", "rust").append_pair("page", "1");
112    ///
113    /// let resp = client
114    ///     .get(url.as_str())
115    ///     .header("authorization", "Bearer token")
116    ///     .send()
117    ///     .await?;
118    /// # Ok(())
119    /// # }
120    /// ```
121    ///
122    /// # Example
123    ///
124    /// ```no_run
125    /// # use toolkit_http::HttpClient;
126    /// # async fn example() -> Result<(), toolkit_http::HttpError> {
127    /// # let client = HttpClient::new()?;
128    /// // Simple GET
129    /// let resp = client.get("https://api.example.com/data").send().await?;
130    /// # Ok(())
131    /// # }
132    /// ```
133    ///
134    /// [`HttpError::InvalidUri`]: crate::error::HttpError::InvalidUri
135    /// [`TransportSecurity::AllowInsecureHttp`]: crate::config::TransportSecurity::AllowInsecureHttp
136    pub fn get(&self, url: &str) -> RequestBuilder {
137        RequestBuilder::new(
138            self.service.clone(),
139            self.max_body_size,
140            http::Method::GET,
141            url.to_owned(),
142            self.transport_security,
143        )
144    }
145
146    /// Create a POST request builder
147    ///
148    /// Returns a [`RequestBuilder`] that can be configured with headers,
149    /// body (JSON, form, bytes), etc. before sending with `.send().await`.
150    ///
151    /// # Example
152    ///
153    /// ```no_run
154    /// # use toolkit_http::HttpClient;
155    /// # #[derive(serde::Serialize)]
156    /// # struct NewUser { name: &'static str }
157    /// # async fn example() -> Result<(), toolkit_http::HttpError> {
158    /// # let client = HttpClient::new()?;
159    /// // POST with JSON body
160    /// let resp = client
161    ///     .post("https://api.example.com/users")
162    ///     .json(&NewUser { name: "Alice" })?
163    ///     .send()
164    ///     .await?;
165    ///
166    /// // POST with form body
167    /// let resp = client
168    ///     .post("https://auth.example.com/token")
169    ///     .form(&[("grant_type", "client_credentials")])?
170    ///     .send()
171    ///     .await?;
172    /// # Ok(())
173    /// # }
174    /// ```
175    pub fn post(&self, url: &str) -> RequestBuilder {
176        RequestBuilder::new(
177            self.service.clone(),
178            self.max_body_size,
179            http::Method::POST,
180            url.to_owned(),
181            self.transport_security,
182        )
183    }
184
185    /// Create a PUT request builder
186    ///
187    /// Returns a [`RequestBuilder`] that can be configured with headers,
188    /// body (JSON, form, bytes), etc. before sending with `.send().await`.
189    ///
190    /// # Example
191    ///
192    /// ```no_run
193    /// # use toolkit_http::HttpClient;
194    /// # #[derive(serde::Serialize)]
195    /// # struct UpdateData { value: i32 }
196    /// # async fn example() -> Result<(), toolkit_http::HttpError> {
197    /// # let client = HttpClient::new()?;
198    /// let resp = client
199    ///     .put("https://api.example.com/resource/1")
200    ///     .json(&UpdateData { value: 42 })?
201    ///     .send()
202    ///     .await?;
203    /// # Ok(())
204    /// # }
205    /// ```
206    pub fn put(&self, url: &str) -> RequestBuilder {
207        RequestBuilder::new(
208            self.service.clone(),
209            self.max_body_size,
210            http::Method::PUT,
211            url.to_owned(),
212            self.transport_security,
213        )
214    }
215
216    /// Create a PATCH request builder
217    ///
218    /// Returns a [`RequestBuilder`] that can be configured with headers,
219    /// body (JSON, form, bytes), etc. before sending with `.send().await`.
220    ///
221    /// # Example
222    ///
223    /// ```no_run
224    /// # use toolkit_http::HttpClient;
225    /// # #[derive(serde::Serialize)]
226    /// # struct PatchData { field: &'static str }
227    /// # async fn example() -> Result<(), toolkit_http::HttpError> {
228    /// # let client = HttpClient::new()?;
229    /// let resp = client
230    ///     .patch("https://api.example.com/resource/1")
231    ///     .json(&PatchData { field: "new_value" })?
232    ///     .send()
233    ///     .await?;
234    /// # Ok(())
235    /// # }
236    /// ```
237    pub fn patch(&self, url: &str) -> RequestBuilder {
238        RequestBuilder::new(
239            self.service.clone(),
240            self.max_body_size,
241            http::Method::PATCH,
242            url.to_owned(),
243            self.transport_security,
244        )
245    }
246
247    /// Create a DELETE request builder
248    ///
249    /// Returns a [`RequestBuilder`] that can be configured with headers
250    /// before sending with `.send().await`.
251    ///
252    /// # Example
253    ///
254    /// ```no_run
255    /// # use toolkit_http::HttpClient;
256    /// # async fn example() -> Result<(), toolkit_http::HttpError> {
257    /// # let client = HttpClient::new()?;
258    /// let resp = client
259    ///     .delete("https://api.example.com/resource/42")
260    ///     .header("authorization", "Bearer token")
261    ///     .send()
262    ///     .await?;
263    /// # Ok(())
264    /// # }
265    /// ```
266    pub fn delete(&self, url: &str) -> RequestBuilder {
267        RequestBuilder::new(
268            self.service.clone(),
269            self.max_body_size,
270            http::Method::DELETE,
271            url.to_owned(),
272            self.transport_security,
273        )
274    }
275
276    /// Create a HEAD request builder.
277    ///
278    /// HEAD requests are like GET but the server returns only headers — the
279    /// response body is empty per RFC 9110 §9.3.2. Use for cheap existence
280    /// checks (`Content-Length` / `ETag` probes) without paying for the
281    /// payload.
282    ///
283    /// HEAD is idempotent, so the SDK's retry policy retries it on transient
284    /// upstream failures the same way it retries GET.
285    ///
286    /// # Example
287    ///
288    /// ```no_run
289    /// # use toolkit_http::HttpClient;
290    /// # async fn example() -> Result<(), toolkit_http::HttpError> {
291    /// # let client = HttpClient::new()?;
292    /// let resp = client.head("https://api.example.com/big-blob").send().await?;
293    /// let len = resp
294    ///     .headers()
295    ///     .get(http::header::CONTENT_LENGTH)
296    ///     .and_then(|v| v.to_str().ok())
297    ///     .and_then(|s| s.parse::<u64>().ok());
298    /// # Ok(())
299    /// # }
300    /// ```
301    pub fn head(&self, url: &str) -> RequestBuilder {
302        RequestBuilder::new(
303            self.service.clone(),
304            self.max_body_size,
305            http::Method::HEAD,
306            url.to_owned(),
307            self.transport_security,
308        )
309    }
310
311    /// Create an OPTIONS request builder.
312    ///
313    /// OPTIONS is the wire form of CORS preflight and capability discovery.
314    /// Servers typically respond with `Allow:` and CORS-preflight headers and
315    /// no body. The SDK installs no CORS middleware — the response is
316    /// returned to the caller verbatim.
317    ///
318    /// OPTIONS is idempotent and is retried by default on transient failures
319    /// the same way GET is.
320    ///
321    /// # Example
322    ///
323    /// ```no_run
324    /// # use toolkit_http::HttpClient;
325    /// # async fn example() -> Result<(), toolkit_http::HttpError> {
326    /// # let client = HttpClient::new()?;
327    /// let resp = client
328    ///     .options("https://api.example.com/resource")
329    ///     .send()
330    ///     .await?;
331    /// let allow = resp
332    ///     .headers()
333    ///     .get(http::header::ALLOW)
334    ///     .and_then(|v| v.to_str().ok())
335    ///     .map(str::to_owned);
336    /// # Ok(())
337    /// # }
338    /// ```
339    pub fn options(&self, url: &str) -> RequestBuilder {
340        RequestBuilder::new(
341            self.service.clone(),
342            self.max_body_size,
343            http::Method::OPTIONS,
344            url.to_owned(),
345            self.transport_security,
346        )
347    }
348}
349
350/// Map buffer errors to `HttpError`
351///
352/// Buffer can return `ServiceError` which wraps the inner service error,
353/// or `Closed` if the buffer worker has shut down.
354pub fn map_buffer_error(err: tower::BoxError) -> HttpError {
355    // Try to downcast to HttpError (from inner service)
356    match err.downcast::<HttpError>() {
357        Ok(http_err) => *http_err,
358        Err(err) => {
359            // Buffer closed or other internal failure.
360            // This happens when buffer worker panics or channel is dropped.
361            //
362            // Return ServiceClosed (not Overloaded) to distinguish from normal
363            // overload (buffer full). This is a serious condition indicating
364            // the background worker has died unexpectedly.
365            tracing::error!(
366                error = %err,
367                "buffer worker closed unexpectedly; service unavailable"
368            );
369            HttpError::ServiceClosed
370        }
371    }
372}
373
374/// Try to acquire a buffer slot with fail-fast semantics.
375///
376/// If the buffer is full, returns `HttpError::Overloaded` immediately instead
377/// of blocking. This prevents request pile-up under load.
378pub async fn try_acquire_buffer_slot(service: &mut BufferedService) -> Result<(), HttpError> {
379    use std::task::Poll;
380
381    // Poll once to check if buffer has space available
382    let poll_result = std::future::poll_fn(|cx| match service.poll_ready(cx) {
383        Poll::Ready(result) => Poll::Ready(Some(result)),
384        Poll::Pending => Poll::Ready(None), // Buffer full, don't block
385    })
386    .await;
387
388    match poll_result {
389        Some(Ok(())) => Ok(()),
390        Some(Err(e)) => Err(map_buffer_error(e)),
391        None => Err(HttpError::Overloaded), // Buffer full, fail fast
392    }
393}
394
395// The in-crate tests below rely on `httpmock` (plaintext HTTP only) and on
396// constructing clients that accept `http://` URLs. Most of them use
397// `HttpClientBuilder::new()`, whose transport is `TlsOnly` under
398// `--features fips`, so the module is compiled out there. The FIPS-mode
399// contract is covered by the integration test in
400// `tests/fips_default_transport.rs` and by `tests/no_crypto_provider_fips.rs`.
401//
402// The two cfg gates are kept separate — `#[cfg(test)]` then
403// `#[cfg(not(feature = "fips"))]` — so that clippy's test-aware lint
404// exemptions (e.g. tolerating `unwrap()` in test code) still trigger on the
405// bare `cfg(test)` marker.
406#[cfg(test)]
407#[cfg(not(feature = "fips"))]
408#[cfg_attr(coverage_nightly, coverage(off))]
409mod tests {
410    use super::*;
411    use crate::error::HttpError;
412    use httpmock::prelude::*;
413    use serde_json::json;
414
415    fn test_client() -> HttpClient {
416        HttpClientBuilder::new().retry(None).build().unwrap()
417    }
418
419    #[tokio::test]
420    async fn test_http_client_get() {
421        let server = MockServer::start();
422        let _m = server.mock(|when, then| {
423            when.method(Method::GET).path("/test");
424            then.status(200).json_body(json!({"success": true}));
425        });
426
427        let client = test_client();
428        let url = format!("{}/test", server.base_url());
429        let resp = client.get(&url).send().await.unwrap();
430
431        assert_eq!(resp.status(), hyper::StatusCode::OK);
432    }
433
434    #[tokio::test]
435    async fn test_http_client_post() {
436        let server = MockServer::start();
437        let _m = server.mock(|when, then| {
438            when.method(Method::POST).path("/action");
439            then.status(200).json_body(json!({"ok": true}));
440        });
441
442        let client = test_client();
443        let url = format!("{}/action", server.base_url());
444        let resp = client.post(&url).send().await.unwrap();
445
446        assert_eq!(resp.status(), hyper::StatusCode::OK);
447    }
448
449    #[tokio::test]
450    async fn test_http_client_post_form() {
451        let server = MockServer::start();
452        let _m = server.mock(|when, then| {
453            when.method(Method::POST)
454                .path("/submit")
455                .header("content-type", "application/x-www-form-urlencoded")
456                .body("key1=value1&key2=value2");
457            then.status(200).json_body(json!({"received": true}));
458        });
459
460        let client = test_client();
461        let url = format!("{}/submit", server.base_url());
462
463        let resp = client
464            .post(&url)
465            .form(&[("key1", "value1"), ("key2", "value2")])
466            .unwrap()
467            .send()
468            .await
469            .unwrap();
470        assert_eq!(resp.status(), hyper::StatusCode::OK);
471    }
472
473    #[tokio::test]
474    async fn test_json_body_parsing() {
475        #[derive(serde::Deserialize)]
476        struct TestResponse {
477            name: String,
478            value: i32,
479        }
480
481        let server = MockServer::start();
482        let _m = server.mock(|when, then| {
483            when.method(Method::GET).path("/json");
484            then.status(200)
485                .json_body(json!({"name": "test", "value": 42}));
486        });
487
488        let client = test_client();
489        let url = format!("{}/json", server.base_url());
490
491        let data: TestResponse = client.get(&url).send().await.unwrap().json().await.unwrap();
492        assert_eq!(data.name, "test");
493        assert_eq!(data.value, 42);
494    }
495
496    #[tokio::test]
497    async fn test_body_size_limit() {
498        let server = MockServer::start();
499        let large_body = "x".repeat(1024 * 1024); // 1MB
500        let _m = server.mock(|when, then| {
501            when.method(Method::GET).path("/large");
502            then.status(200).body(&large_body);
503        });
504
505        let client = HttpClientBuilder::new()
506            .retry(None)
507            .max_body_size(1024) // 1KB limit
508            .build()
509            .unwrap();
510
511        let url = format!("{}/large", server.base_url());
512        let result = client.get(&url).send().await.unwrap().bytes().await;
513
514        assert!(matches!(result, Err(HttpError::BodyTooLarge { .. })));
515    }
516
517    #[tokio::test]
518    async fn test_custom_user_agent() {
519        let server = MockServer::start();
520        let _m = server.mock(|when, then| {
521            when.method(Method::GET)
522                .path("/test")
523                .header("user-agent", "custom/1.0");
524            then.status(200);
525        });
526
527        let client = HttpClientBuilder::new()
528            .retry(None)
529            .user_agent("custom/1.0")
530            .build()
531            .unwrap();
532
533        let url = format!("{}/test", server.base_url());
534        let resp = client.get(&url).send().await.unwrap();
535        assert_eq!(resp.status(), hyper::StatusCode::OK);
536    }
537
538    #[tokio::test]
539    async fn test_non_2xx_returns_http_status_error() {
540        let server = MockServer::start();
541        let _m = server.mock(|when, then| {
542            when.method(Method::GET).path("/error");
543            then.status(404)
544                .header("content-type", "application/json")
545                .body(r#"{"error": "not found"}"#);
546        });
547
548        let client = test_client();
549        let url = format!("{}/error", server.base_url());
550
551        let result: Result<serde_json::Value, _> =
552            client.get(&url).send().await.unwrap().json().await;
553        match result {
554            Err(HttpError::HttpStatus {
555                status,
556                body_preview,
557                content_type,
558                ..
559            }) => {
560                assert_eq!(status, hyper::StatusCode::NOT_FOUND);
561                assert!(body_preview.contains("not found"));
562                assert_eq!(content_type, Some("application/json".to_owned()));
563            }
564            other => panic!("Expected HttpStatus error, got: {other:?}"),
565        }
566    }
567
568    #[tokio::test]
569    async fn test_checked_body_success() {
570        let server = MockServer::start();
571        let _m = server.mock(|when, then| {
572            when.method(Method::GET).path("/data");
573            then.status(200).body("hello world");
574        });
575
576        let client = test_client();
577        let url = format!("{}/data", server.base_url());
578
579        let body = client
580            .get(&url)
581            .send()
582            .await
583            .unwrap()
584            .checked_bytes()
585            .await
586            .unwrap();
587        assert_eq!(&body[..], b"hello world");
588    }
589
590    #[tokio::test]
591    async fn test_client_is_clone() {
592        let client = test_client();
593        let client2 = client.clone();
594
595        // Both should work independently
596        let server = MockServer::start();
597        let _m = server.mock(|when, then| {
598            when.method(Method::GET).path("/test");
599            then.status(200);
600        });
601
602        let url = format!("{}/test", server.base_url());
603        let resp1 = client.get(&url).send().await.unwrap();
604        let resp2 = client2.get(&url).send().await.unwrap();
605
606        assert_eq!(resp1.status(), hyper::StatusCode::OK);
607        assert_eq!(resp2.status(), hyper::StatusCode::OK);
608    }
609
610    /// Compile-time assertion that `HttpClient` is `Send + Sync`
611    ///
612    /// This test ensures callers do NOT need to wrap `HttpClient` in `Mutex`.
613    #[test]
614    fn test_http_client_is_send_sync() {
615        fn assert_send_sync<T: Send + Sync>() {}
616        assert_send_sync::<HttpClient>();
617    }
618
619    /// Test that 50 concurrent requests all succeed
620    #[tokio::test]
621    async fn test_concurrent_requests_50() {
622        let server = MockServer::start();
623        let _m = server.mock(|when, then| {
624            when.method(Method::GET).path("/concurrent");
625            then.status(200).body("ok");
626        });
627
628        let client = test_client();
629        let url = format!("{}/concurrent", server.base_url());
630
631        // Spawn 50 concurrent requests
632        let handles: Vec<_> = (0..50)
633            .map(|_| {
634                let client = client.clone();
635                let url = url.clone();
636                tokio::spawn(async move { client.get(&url).send().await })
637            })
638            .collect();
639
640        // All should succeed
641        for handle in handles {
642            let resp = handle.await.unwrap().unwrap();
643            assert_eq!(resp.status(), hyper::StatusCode::OK);
644        }
645    }
646
647    /// `x-request-id` set by an inbound middleware's `with_request_id` scope is
648    /// forwarded on the outbound request, so a downstream gear sees the edge id.
649    #[tokio::test]
650    async fn test_request_id_forwarded_when_in_scope() {
651        let server = MockServer::start();
652        let _m = server.mock(|when, then| {
653            when.method(Method::GET)
654                .path("/test")
655                .header("x-request-id", "req-42");
656            then.status(200);
657        });
658
659        let client = test_client();
660        let url = format!("{}/test", server.base_url());
661
662        let resp = toolkit_trace_context::with_request_id(
663            Some("req-42".to_owned()),
664            client.get(&url).send(),
665        )
666        .await
667        .unwrap();
668        assert_eq!(resp.status(), hyper::StatusCode::OK);
669    }
670
671    /// An explicit `x-request-id` header set by the caller wins over the
672    /// scoped id — the carrier must never overwrite a deliberate choice.
673    #[tokio::test]
674    async fn test_request_id_explicit_header_wins_over_scope() {
675        let server = MockServer::start();
676        let _m = server.mock(|when, then| {
677            when.method(Method::GET)
678                .path("/test")
679                .header("x-request-id", "explicit-id");
680            then.status(200);
681        });
682
683        let client = test_client();
684        let url = format!("{}/test", server.base_url());
685
686        let resp = toolkit_trace_context::with_request_id(
687            Some("scoped-id".to_owned()),
688            client
689                .get(&url)
690                .header("x-request-id", "explicit-id")
691                .send(),
692        )
693        .await
694        .unwrap();
695        assert_eq!(resp.status(), hyper::StatusCode::OK);
696    }
697
698    /// Outside a request scope nothing is minted: the header stays absent, so
699    /// background/startup calls don't invent request ids.
700    #[tokio::test]
701    async fn test_request_id_absent_outside_scope() {
702        let server = MockServer::start();
703        let mock = server.mock(|when, then| {
704            when.method(Method::GET)
705                .path("/test")
706                .header_missing("x-request-id");
707            then.status(200);
708        });
709
710        let client = test_client();
711        let url = format!("{}/test", server.base_url());
712        let resp = client.get(&url).send().await.unwrap();
713        assert_eq!(resp.status(), hyper::StatusCode::OK);
714        mock.assert_async().await;
715    }
716
717    /// Test small buffer capacity with fail-fast behavior
718    ///
719    /// With fail-fast buffer semantics, some requests may fail with Overloaded
720    /// when buffer is full. This test verifies:
721    /// 1. No deadlock (all complete within timeout)
722    /// 2. At least some requests succeed
723    /// 3. Failed requests get Overloaded error (not other errors)
724    #[tokio::test]
725    async fn test_small_buffer_capacity_no_deadlock() {
726        use crate::config::HttpClientConfig;
727
728        let server = MockServer::start();
729        let _m = server.mock(|when, then| {
730            when.method(Method::GET).path("/test");
731            then.status(200).body("ok");
732        });
733
734        // Create client with very small buffer (capacity 2)
735        let config = HttpClientConfig {
736            transport: crate::config::TransportSecurity::AllowInsecureHttp,
737            retry: None,
738            rate_limit: None,
739            buffer_capacity: 2,
740            ..Default::default()
741        };
742
743        let client = HttpClientBuilder::with_config(config).build().unwrap();
744        let url = format!("{}/test", server.base_url());
745
746        // Fire 10 concurrent requests - some may fail with Overloaded (fail-fast)
747        let handles: Vec<_> = (0..10)
748            .map(|_| {
749                let client = client.clone();
750                let url = url.clone();
751                tokio::spawn(async move { client.get(&url).send().await })
752            })
753            .collect();
754
755        // All should complete (not hang) within timeout
756        let timeout_result = tokio::time::timeout(std::time::Duration::from_secs(10), async {
757            let mut results = Vec::new();
758            for handle in handles {
759                results.push(handle.await);
760            }
761            results
762        })
763        .await;
764
765        let results = timeout_result.expect("requests should complete within timeout");
766
767        let mut success_count = 0;
768        let mut overloaded_count = 0;
769        for result in results {
770            match result.unwrap() {
771                Ok(resp) => {
772                    assert_eq!(resp.status(), hyper::StatusCode::OK);
773                    success_count += 1;
774                }
775                Err(HttpError::Overloaded) => {
776                    overloaded_count += 1;
777                }
778                Err(e) => panic!("unexpected error: {e:?}"),
779            }
780        }
781
782        // At least some should succeed (buffer processes requests)
783        assert!(success_count > 0, "at least one request should succeed");
784        // Total should be 10
785        assert_eq!(success_count + overloaded_count, 10);
786    }
787
788    /// Test buffer overflow returns Overloaded error immediately (fail-fast)
789    ///
790    /// Verifies that when buffer is full and inner service is blocked,
791    /// new requests fail immediately with Overloaded instead of hanging.
792    #[tokio::test]
793    async fn test_buffer_overflow_returns_overloaded() {
794        use crate::config::HttpClientConfig;
795
796        let server = MockServer::start();
797
798        let _m = server.mock(|when, then| {
799            when.method(Method::GET).path("/slow");
800            then.status(200).body("ok");
801        });
802
803        // Create client with buffer capacity of 1
804        let config = HttpClientConfig {
805            transport: crate::config::TransportSecurity::AllowInsecureHttp,
806            retry: None,
807            rate_limit: None,
808            buffer_capacity: 1,
809            ..Default::default()
810        };
811
812        let client = HttpClientBuilder::with_config(config).build().unwrap();
813        let url = format!("{}/slow", server.base_url());
814
815        // First request - will occupy the single buffer slot
816        let client1 = client.clone();
817        let url1 = url.clone();
818        let handle1 = tokio::spawn(async move { client1.get(&url1).send().await });
819
820        // Give first request time to acquire buffer slot
821        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
822
823        // Second request - should fail immediately with Overloaded (buffer full)
824        let result2 = tokio::time::timeout(
825            std::time::Duration::from_millis(50),
826            client.get(&url).send(),
827        )
828        .await;
829
830        // Should complete immediately (not timeout) with Overloaded
831        let inner_result = result2.expect("request should not timeout waiting for buffer");
832        match inner_result {
833            // Expected: buffer full (fail-fast) or request got through (timing dependent)
834            Err(HttpError::Overloaded) | Ok(_) => {}
835            Err(e) => panic!("unexpected error: {e:?}"),
836        }
837
838        // Let first request complete
839        _ = handle1.await;
840    }
841
842    /// Test that large body reading doesn't cause deadlock
843    #[tokio::test]
844    async fn test_large_body_no_deadlock() {
845        let server = MockServer::start();
846        let large_body = "x".repeat(100 * 1024); // 100KB
847        let _m = server.mock(|when, then| {
848            when.method(Method::GET).path("/large");
849            then.status(200).body(&large_body);
850        });
851
852        let client = HttpClientBuilder::new()
853            .retry(None)
854            .max_body_size(1024 * 1024) // 1MB limit
855            .build()
856            .unwrap();
857
858        let url = format!("{}/large", server.base_url());
859
860        // Fire multiple concurrent requests that read large bodies
861        let handles: Vec<_> = (0..5)
862            .map(|_| {
863                let client = client.clone();
864                let url = url.clone();
865                tokio::spawn(async move { client.get(&url).send().await?.checked_bytes().await })
866            })
867            .collect();
868
869        // All should complete
870        let timeout_result = tokio::time::timeout(std::time::Duration::from_secs(10), async {
871            let mut results = Vec::new();
872            for handle in handles {
873                results.push(handle.await);
874            }
875            results
876        })
877        .await;
878
879        let results = timeout_result.expect("body reads should complete within timeout");
880        for result in results {
881            let body = result.unwrap().unwrap();
882            assert_eq!(body.len(), 100 * 1024);
883        }
884    }
885
886    /// Test that `token_endpoint` config does NOT retry POST requests
887    ///
888    /// `OAuth2` token endpoints use POST, and we must not retry POST to avoid
889    /// duplicate token requests. This test verifies the retry config in
890    /// `HttpClientConfig::token_endpoint()` only retries GET.
891    #[tokio::test]
892    async fn test_token_endpoint_post_not_retried() {
893        use crate::config::HttpClientConfig;
894
895        let server = MockServer::start();
896
897        // Mock that always returns 500 (retriable error)
898        let mock = server.mock(|when, then| {
899            when.method(Method::POST).path("/token");
900            then.status(500).body("server error");
901        });
902
903        // Use token_endpoint config (retry enabled but only for GET)
904        let mut config = HttpClientConfig::token_endpoint();
905        config.transport = crate::config::TransportSecurity::AllowInsecureHttp; // Allow HTTP for test server
906
907        let client = HttpClientBuilder::with_config(config).build().unwrap();
908        let url = format!("{}/token", server.base_url());
909
910        // POST form to token endpoint
911        let result = client
912            .post(&url)
913            .form(&[("grant_type", "client_credentials"), ("client_id", "test")])
914            .unwrap()
915            .send()
916            .await;
917
918        // Request should fail (500 error)
919        assert!(result.is_ok()); // HTTP request succeeded
920        let response = result.unwrap();
921        assert_eq!(response.status(), hyper::StatusCode::INTERNAL_SERVER_ERROR);
922
923        // Verify mock was called exactly once (no retries)
924        // httpmock tracks calls internally
925        assert_eq!(
926            mock.calls(),
927            1,
928            "POST should not be retried; expected 1 call, got {}",
929            mock.calls()
930        );
931    }
932
933    // NOTE: GET retry behavior is tested at the layer level in
934    // `layers::tests::test_retry_layer_retries_transport_errors` which uses
935    // a mock service to simulate transport errors. HTTP status codes (like 500)
936    // don't trigger retries since they're returned as Ok(Response), not Err.
937
938    #[tokio::test]
939    async fn test_http_client_put() {
940        let server = MockServer::start();
941        let _m = server.mock(|when, then| {
942            when.method(Method::PUT).path("/resource");
943            then.status(200).json_body(json!({"updated": true}));
944        });
945
946        let client = test_client();
947        let url = format!("{}/resource", server.base_url());
948        let resp = client.put(&url).send().await.unwrap();
949
950        assert_eq!(resp.status(), hyper::StatusCode::OK);
951    }
952
953    #[tokio::test]
954    async fn test_http_client_put_form() {
955        let server = MockServer::start();
956        let _m = server.mock(|when, then| {
957            when.method(Method::PUT)
958                .path("/resource")
959                .header("content-type", "application/x-www-form-urlencoded")
960                .body("name=updated&value=123");
961            then.status(200).json_body(json!({"updated": true}));
962        });
963
964        let client = test_client();
965        let url = format!("{}/resource", server.base_url());
966
967        let resp = client
968            .put(&url)
969            .form(&[("name", "updated"), ("value", "123")])
970            .unwrap()
971            .send()
972            .await
973            .unwrap();
974        assert_eq!(resp.status(), hyper::StatusCode::OK);
975    }
976
977    #[tokio::test]
978    async fn test_http_client_patch() {
979        let server = MockServer::start();
980        let _m = server.mock(|when, then| {
981            when.method(Method::PATCH).path("/resource/1");
982            then.status(200).json_body(json!({"patched": true}));
983        });
984
985        let client = test_client();
986        let url = format!("{}/resource/1", server.base_url());
987        let resp = client.patch(&url).send().await.unwrap();
988
989        assert_eq!(resp.status(), hyper::StatusCode::OK);
990    }
991
992    #[tokio::test]
993    async fn test_http_client_patch_form() {
994        let server = MockServer::start();
995        let _m = server.mock(|when, then| {
996            when.method(Method::PATCH)
997                .path("/resource/1")
998                .header("content-type", "application/x-www-form-urlencoded")
999                .body("field=patched");
1000            then.status(200).json_body(json!({"patched": true}));
1001        });
1002
1003        let client = test_client();
1004        let url = format!("{}/resource/1", server.base_url());
1005
1006        let resp = client
1007            .patch(&url)
1008            .form(&[("field", "patched")])
1009            .unwrap()
1010            .send()
1011            .await
1012            .unwrap();
1013        assert_eq!(resp.status(), hyper::StatusCode::OK);
1014    }
1015
1016    #[tokio::test]
1017    async fn test_http_client_delete() {
1018        let server = MockServer::start();
1019        let _m = server.mock(|when, then| {
1020            when.method(Method::DELETE).path("/resource/42");
1021            then.status(204);
1022        });
1023
1024        let client = test_client();
1025        let url = format!("{}/resource/42", server.base_url());
1026        let resp = client.delete(&url).send().await.unwrap();
1027
1028        assert_eq!(resp.status(), hyper::StatusCode::NO_CONTENT);
1029    }
1030
1031    #[tokio::test]
1032    async fn test_http_client_delete_returns_200() {
1033        let server = MockServer::start();
1034        let _m = server.mock(|when, then| {
1035            when.method(Method::DELETE).path("/resource/99");
1036            then.status(200).json_body(json!({"deleted": true}));
1037        });
1038
1039        let client = test_client();
1040        let url = format!("{}/resource/99", server.base_url());
1041        let resp = client.delete(&url).send().await.unwrap();
1042
1043        assert_eq!(resp.status(), hyper::StatusCode::OK);
1044    }
1045
1046    #[tokio::test]
1047    async fn test_http_client_head_returns_headers_no_body() {
1048        let server = MockServer::start();
1049        let _m = server.mock(|when, then| {
1050            when.method(Method::HEAD).path("/probe");
1051            then.status(200)
1052                .header("content-length", "12345")
1053                .header("etag", "\"abc\"");
1054        });
1055
1056        let client = test_client();
1057        let url = format!("{}/probe", server.base_url());
1058        let resp = client.head(&url).send().await.unwrap();
1059
1060        assert_eq!(resp.status(), hyper::StatusCode::OK);
1061        assert_eq!(
1062            resp.headers()
1063                .get("content-length")
1064                .and_then(|v| v.to_str().ok()),
1065            Some("12345"),
1066        );
1067        let body = resp.bytes().await.unwrap();
1068        assert!(body.is_empty(), "HEAD response body must be empty");
1069    }
1070
1071    #[tokio::test]
1072    async fn test_http_client_options_returns_allow_header() {
1073        let server = MockServer::start();
1074        let _m = server.mock(|when, then| {
1075            when.method(Method::OPTIONS).path("/resource");
1076            then.status(204).header("allow", "GET, POST, PUT, DELETE");
1077        });
1078
1079        let client = test_client();
1080        let url = format!("{}/resource", server.base_url());
1081        let resp = client.options(&url).send().await.unwrap();
1082
1083        assert_eq!(resp.status(), hyper::StatusCode::NO_CONTENT);
1084        assert_eq!(
1085            resp.headers().get("allow").and_then(|v| v.to_str().ok()),
1086            Some("GET, POST, PUT, DELETE"),
1087        );
1088    }
1089
1090    #[tokio::test]
1091    async fn test_put_form_with_custom_headers() {
1092        let server = MockServer::start();
1093        let _m = server.mock(|when, then| {
1094            when.method(Method::PUT)
1095                .path("/api/data")
1096                .header("content-type", "application/x-www-form-urlencoded")
1097                .header("x-custom-header", "custom-value")
1098                .body("key=value");
1099            then.status(200);
1100        });
1101
1102        let client = test_client();
1103        let url = format!("{}/api/data", server.base_url());
1104
1105        let resp = client
1106            .put(&url)
1107            .header("x-custom-header", "custom-value")
1108            .form(&[("key", "value")])
1109            .unwrap()
1110            .send()
1111            .await
1112            .unwrap();
1113        assert_eq!(resp.status(), hyper::StatusCode::OK);
1114    }
1115
1116    #[tokio::test]
1117    async fn test_patch_form_with_custom_headers() {
1118        let server = MockServer::start();
1119        let _m = server.mock(|when, then| {
1120            when.method(Method::PATCH)
1121                .path("/api/data")
1122                .header("content-type", "application/x-www-form-urlencoded")
1123                .header("authorization", "Bearer token123")
1124                .body("status=active");
1125            then.status(200);
1126        });
1127
1128        let client = test_client();
1129        let url = format!("{}/api/data", server.base_url());
1130
1131        let resp = client
1132            .patch(&url)
1133            .header("authorization", "Bearer token123")
1134            .form(&[("status", "active")])
1135            .unwrap()
1136            .send()
1137            .await
1138            .unwrap();
1139        assert_eq!(resp.status(), hyper::StatusCode::OK);
1140    }
1141
1142    #[tokio::test]
1143    async fn test_request_builder_json_body() {
1144        #[derive(serde::Serialize)]
1145        struct CreateUser {
1146            name: String,
1147            email: String,
1148        }
1149
1150        let server = MockServer::start();
1151        let _m = server.mock(|when, then| {
1152            when.method(Method::POST)
1153                .path("/users")
1154                .header("content-type", "application/json")
1155                .json_body(json!({"name": "Alice", "email": "alice@example.com"}));
1156            then.status(201).json_body(json!({"id": 1}));
1157        });
1158
1159        let client = test_client();
1160        let url = format!("{}/users", server.base_url());
1161
1162        let resp = client
1163            .post(&url)
1164            .json(&CreateUser {
1165                name: "Alice".into(),
1166                email: "alice@example.com".into(),
1167            })
1168            .unwrap()
1169            .send()
1170            .await
1171            .unwrap();
1172        assert_eq!(resp.status(), hyper::StatusCode::CREATED);
1173    }
1174
1175    #[tokio::test]
1176    async fn test_request_builder_body_bytes() {
1177        let server = MockServer::start();
1178        let _m = server.mock(|when, then| {
1179            when.method(Method::POST)
1180                .path("/upload")
1181                .body("raw binary data");
1182            then.status(200);
1183        });
1184
1185        let client = test_client();
1186        let url = format!("{}/upload", server.base_url());
1187
1188        let resp = client
1189            .post(&url)
1190            .body_bytes(bytes::Bytes::from("raw binary data"))
1191            .send()
1192            .await
1193            .unwrap();
1194        assert_eq!(resp.status(), hyper::StatusCode::OK);
1195    }
1196
1197    /// Test that user-provided Content-Type is not duplicated when using `json()`.
1198    ///
1199    /// When the user supplies a Content-Type header before calling `.json()`,
1200    /// the default `application/json` should NOT be added. The final request
1201    /// should have exactly one Content-Type header with the user's value.
1202    #[tokio::test]
1203    async fn test_content_type_not_duplicated_with_json() {
1204        #[derive(serde::Serialize)]
1205        struct TestData {
1206            value: i32,
1207        }
1208
1209        let server = MockServer::start();
1210        let mock = server.mock(|when, then| {
1211            when.method(Method::POST)
1212                .path("/custom-content-type")
1213                // Match the custom Content-Type (not application/json)
1214                .header("content-type", "application/vnd.custom+json");
1215            then.status(200);
1216        });
1217
1218        let client = test_client();
1219        let url = format!("{}/custom-content-type", server.base_url());
1220
1221        let resp = client
1222            .post(&url)
1223            .header("content-type", "application/vnd.custom+json") // Custom Content-Type
1224            .json(&TestData { value: 42 })
1225            .unwrap()
1226            .send()
1227            .await
1228            .unwrap();
1229
1230        assert_eq!(resp.status(), hyper::StatusCode::OK);
1231        assert_eq!(
1232            mock.calls(),
1233            1,
1234            "Request with custom Content-Type should match"
1235        );
1236    }
1237
1238    /// Test that user-provided Content-Type is not duplicated when using `form()`.
1239    #[tokio::test]
1240    async fn test_content_type_not_duplicated_with_form() {
1241        let server = MockServer::start();
1242        let mock = server.mock(|when, then| {
1243            when.method(Method::POST)
1244                .path("/custom-form-type")
1245                // Match the custom Content-Type (not application/x-www-form-urlencoded)
1246                .header("content-type", "application/x-custom-form");
1247            then.status(200);
1248        });
1249
1250        let client = test_client();
1251        let url = format!("{}/custom-form-type", server.base_url());
1252
1253        let resp = client
1254            .post(&url)
1255            .header("content-type", "application/x-custom-form") // Custom Content-Type
1256            .form(&[("key", "value")])
1257            .unwrap()
1258            .send()
1259            .await
1260            .unwrap();
1261
1262        assert_eq!(resp.status(), hyper::StatusCode::OK);
1263        assert_eq!(
1264            mock.calls(),
1265            1,
1266            "Request with custom Content-Type should match"
1267        );
1268    }
1269
1270    #[tokio::test]
1271    async fn test_request_builder_body_string() {
1272        let server = MockServer::start();
1273        let _m = server.mock(|when, then| {
1274            when.method(Method::POST)
1275                .path("/text")
1276                .body("Hello, World!");
1277            then.status(200);
1278        });
1279
1280        let client = test_client();
1281        let url = format!("{}/text", server.base_url());
1282
1283        let resp = client
1284            .post(&url)
1285            .body_string("Hello, World!".into())
1286            .send()
1287            .await
1288            .unwrap();
1289        assert_eq!(resp.status(), hyper::StatusCode::OK);
1290    }
1291
1292    #[tokio::test]
1293    async fn test_response_text_method() {
1294        let server = MockServer::start();
1295        let _m = server.mock(|when, then| {
1296            when.method(Method::GET).path("/text");
1297            then.status(200).body("Hello, World!");
1298        });
1299
1300        let client = test_client();
1301        let url = format!("{}/text", server.base_url());
1302
1303        let text = client.get(&url).send().await.unwrap().text().await.unwrap();
1304        assert_eq!(text, "Hello, World!");
1305    }
1306
1307    #[tokio::test]
1308    async fn test_request_builder_multiple_headers() {
1309        let server = MockServer::start();
1310        let _m = server.mock(|when, then| {
1311            when.method(Method::GET)
1312                .path("/headers")
1313                .header("x-first", "one")
1314                .header("x-second", "two");
1315            then.status(200);
1316        });
1317
1318        let client = test_client();
1319        let url = format!("{}/headers", server.base_url());
1320
1321        let resp = client
1322            .get(&url)
1323            .header("x-first", "one")
1324            .header("x-second", "two")
1325            .send()
1326            .await
1327            .unwrap();
1328        assert_eq!(resp.status(), hyper::StatusCode::OK);
1329    }
1330
1331    #[tokio::test]
1332    async fn test_request_builder_headers_vec() {
1333        let server = MockServer::start();
1334        let _m = server.mock(|when, then| {
1335            when.method(Method::GET)
1336                .path("/headers")
1337                .header("x-first", "one")
1338                .header("x-second", "two");
1339            then.status(200);
1340        });
1341
1342        let client = test_client();
1343        let url = format!("{}/headers", server.base_url());
1344
1345        let resp = client
1346            .get(&url)
1347            .headers(vec![
1348                ("x-first".to_owned(), "one".to_owned()),
1349                ("x-second".to_owned(), "two".to_owned()),
1350            ])
1351            .send()
1352            .await
1353            .unwrap();
1354        assert_eq!(resp.status(), hyper::StatusCode::OK);
1355    }
1356
1357    /// Test that `checked_bytes` returns `HttpStatus` error (not `BodyTooLarge`) when
1358    /// a non-2xx response has a body larger than the preview limit.
1359    #[tokio::test]
1360    async fn test_error_response_with_large_body_returns_http_status() {
1361        use crate::security::ERROR_BODY_PREVIEW_LIMIT;
1362
1363        let server = MockServer::start();
1364
1365        // Create a body larger than ERROR_BODY_PREVIEW_LIMIT (8KB)
1366        let large_body = "x".repeat(ERROR_BODY_PREVIEW_LIMIT + 1000);
1367
1368        let _m = server.mock(|when, then| {
1369            when.method(Method::GET).path("/error-with-large-body");
1370            then.status(500).body(&large_body);
1371        });
1372
1373        let client = test_client();
1374        let url = format!("{}/error-with-large-body", server.base_url());
1375
1376        let result = client.get(&url).send().await.unwrap().checked_bytes().await;
1377
1378        // Should return HttpStatus error, NOT BodyTooLarge
1379        match result {
1380            Err(HttpError::HttpStatus {
1381                status,
1382                body_preview,
1383                ..
1384            }) => {
1385                assert_eq!(status, hyper::StatusCode::INTERNAL_SERVER_ERROR);
1386                // Body preview should indicate it was too large
1387                assert_eq!(body_preview, "<body too large for preview>");
1388            }
1389            Err(HttpError::BodyTooLarge { .. }) => {
1390                panic!("Should return HttpStatus, not BodyTooLarge for non-2xx responses");
1391            }
1392            Err(other) => panic!("Unexpected error: {other:?}"),
1393            Ok(_) => panic!("Should have returned an error for 500 status"),
1394        }
1395    }
1396
1397    // ==========================================================================
1398    // Gzip/Br/Deflate Decompression Tests
1399    // ==========================================================================
1400
1401    /// Helper to gzip-compress data
1402    fn gzip_compress(data: &[u8]) -> Vec<u8> {
1403        use flate2::Compression;
1404        use flate2::write::GzEncoder;
1405        use std::io::Write;
1406
1407        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
1408        encoder.write_all(data).unwrap();
1409        encoder.finish().unwrap()
1410    }
1411
1412    /// Test that gzip-encoded response is automatically decompressed.
1413    ///
1414    /// Server returns a gzip-compressed body with `Content-Encoding: gzip`.
1415    /// Client should automatically decompress and return the original bytes.
1416    #[tokio::test]
1417    async fn test_gzip_decompression_basic() {
1418        let server = MockServer::start();
1419
1420        let original_body = b"Hello, this is a test body that will be gzip compressed!";
1421        let compressed_body = gzip_compress(original_body);
1422
1423        let _m = server.mock(|when, then| {
1424            when.method(Method::GET).path("/gzip");
1425            then.status(200)
1426                .header("content-encoding", "gzip")
1427                .body(compressed_body);
1428        });
1429
1430        let client = test_client();
1431        let url = format!("{}/gzip", server.base_url());
1432
1433        let body = client
1434            .get(&url)
1435            .send()
1436            .await
1437            .unwrap()
1438            .bytes()
1439            .await
1440            .unwrap();
1441
1442        assert_eq!(
1443            body.as_ref(),
1444            original_body,
1445            "Decompressed body should match original"
1446        );
1447    }
1448
1449    /// Test that gzip-compressed JSON can be parsed via `response.json()`.
1450    ///
1451    /// Server returns gzipped JSON with `Content-Encoding: gzip`.
1452    /// Client should decompress and successfully parse the JSON.
1453    #[tokio::test]
1454    async fn test_gzip_decompression_json() {
1455        #[derive(serde::Deserialize, PartialEq, Debug)]
1456        struct TestData {
1457            name: String,
1458            value: i32,
1459            nested: NestedData,
1460        }
1461
1462        #[derive(serde::Deserialize, PartialEq, Debug)]
1463        struct NestedData {
1464            items: Vec<String>,
1465        }
1466
1467        let server = MockServer::start();
1468
1469        let json_body = r#"{"name":"test","value":42,"nested":{"items":["a","b","c"]}}"#;
1470        let compressed_body = gzip_compress(json_body.as_bytes());
1471
1472        let _m = server.mock(|when, then| {
1473            when.method(Method::GET).path("/gzip-json");
1474            then.status(200)
1475                .header("content-type", "application/json")
1476                .header("content-encoding", "gzip")
1477                .body(compressed_body);
1478        });
1479
1480        let client = test_client();
1481        let url = format!("{}/gzip-json", server.base_url());
1482
1483        let data: TestData = client.get(&url).send().await.unwrap().json().await.unwrap();
1484
1485        assert_eq!(data.name, "test");
1486        assert_eq!(data.value, 42);
1487        assert_eq!(data.nested.items, vec!["a", "b", "c"]);
1488    }
1489
1490    /// Test that body size limit is enforced on DECOMPRESSED bytes, not compressed.
1491    ///
1492    /// This protects against "zip bombs" where a small compressed payload
1493    /// expands to a huge decompressed size.
1494    ///
1495    /// The test creates a highly compressible payload (repeated 'x' chars)
1496    /// that compresses small but expands beyond the `max_body_size` limit.
1497    #[tokio::test]
1498    async fn test_gzip_decompression_body_size_limit() {
1499        let server = MockServer::start();
1500
1501        // Create a body that compresses well but is large when decompressed.
1502        // 100KB of repeated 'x' compresses to a few hundred bytes.
1503        let large_decompressed = vec![b'x'; 100 * 1024]; // 100KB
1504        let compressed_body = gzip_compress(&large_decompressed);
1505
1506        // Verify compression is significant (sanity check)
1507        assert!(
1508            compressed_body.len() < 2000,
1509            "Compressed body should be small (got {} bytes)",
1510            compressed_body.len()
1511        );
1512
1513        let _m = server.mock(|when, then| {
1514            when.method(Method::GET).path("/gzip-bomb");
1515            then.status(200)
1516                .header("content-encoding", "gzip")
1517                .body(compressed_body);
1518        });
1519
1520        // Create client with 10KB body limit - smaller than decompressed size
1521        let client = HttpClientBuilder::new()
1522            .retry(None)
1523            .max_body_size(10 * 1024) // 10KB limit
1524            .build()
1525            .unwrap();
1526
1527        let url = format!("{}/gzip-bomb", server.base_url());
1528        let result = client.get(&url).send().await.unwrap().bytes().await;
1529
1530        // Should fail with BodyTooLarge because decompressed size exceeds limit
1531        match result {
1532            Err(HttpError::BodyTooLarge { limit, actual }) => {
1533                assert_eq!(limit, 10 * 1024, "Limit should be 10KB");
1534                assert!(
1535                    actual > limit,
1536                    "Actual size ({actual}) should exceed limit ({limit})"
1537                );
1538            }
1539            Err(other) => panic!("Expected BodyTooLarge error, got: {other:?}"),
1540            Ok(body) => panic!(
1541                "Expected BodyTooLarge error, but got {} bytes of body",
1542                body.len()
1543            ),
1544        }
1545    }
1546
1547    /// Test that Accept-Encoding header is automatically set by the client.
1548    ///
1549    /// The `DecompressionLayer` automatically adds `Accept-Encoding: gzip, br, deflate`
1550    /// to outgoing requests.
1551    #[tokio::test]
1552    async fn test_accept_encoding_header_sent() {
1553        let server = MockServer::start();
1554
1555        // Mock that requires Accept-Encoding header to be present
1556        let mock = server.mock(|when, then| {
1557            when.method(Method::GET)
1558                .path("/check-accept-encoding")
1559                .header_exists("accept-encoding");
1560            then.status(200).body("ok");
1561        });
1562
1563        let client = test_client();
1564        let url = format!("{}/check-accept-encoding", server.base_url());
1565
1566        let resp = client.get(&url).send().await.unwrap();
1567        assert_eq!(resp.status(), hyper::StatusCode::OK);
1568
1569        // Verify the mock was hit (meaning Accept-Encoding was present)
1570        assert_eq!(
1571            mock.calls(),
1572            1,
1573            "Request should have included Accept-Encoding header"
1574        );
1575    }
1576
1577    /// Test that non-compressed responses still work normally.
1578    ///
1579    /// When server doesn't return Content-Encoding, the body should pass through unchanged.
1580    #[tokio::test]
1581    async fn test_no_compression_passthrough() {
1582        let server = MockServer::start();
1583
1584        let plain_body = b"This is plain text, not compressed";
1585
1586        let _m = server.mock(|when, then| {
1587            when.method(Method::GET).path("/plain");
1588            then.status(200)
1589                .header("content-type", "text/plain")
1590                .body(plain_body.as_slice());
1591        });
1592
1593        let client = test_client();
1594        let url = format!("{}/plain", server.base_url());
1595
1596        let body = client
1597            .get(&url)
1598            .send()
1599            .await
1600            .unwrap()
1601            .bytes()
1602            .await
1603            .unwrap();
1604
1605        assert_eq!(
1606            body.as_ref(),
1607            plain_body,
1608            "Plain body should pass through unchanged"
1609        );
1610    }
1611
1612    /// Test that `checked_bytes` works correctly with gzip decompression.
1613    #[tokio::test]
1614    async fn test_gzip_decompression_checked_bytes() {
1615        let server = MockServer::start();
1616
1617        let original_body = b"Checked bytes test with gzip";
1618        let compressed_body = gzip_compress(original_body);
1619
1620        let _m = server.mock(|when, then| {
1621            when.method(Method::GET).path("/gzip-checked");
1622            then.status(200)
1623                .header("content-encoding", "gzip")
1624                .body(compressed_body);
1625        });
1626
1627        let client = test_client();
1628        let url = format!("{}/gzip-checked", server.base_url());
1629
1630        let body = client
1631            .get(&url)
1632            .send()
1633            .await
1634            .unwrap()
1635            .checked_bytes()
1636            .await
1637            .unwrap();
1638
1639        assert_eq!(
1640            body.as_ref(),
1641            original_body,
1642            "checked_bytes should return decompressed content"
1643        );
1644    }
1645
1646    /// Test that `text()` method works correctly with gzip decompression.
1647    #[tokio::test]
1648    async fn test_gzip_decompression_text() {
1649        let server = MockServer::start();
1650
1651        let original_text = "Hello, World! \u{1F600}"; // Contains emoji
1652        let compressed_body = gzip_compress(original_text.as_bytes());
1653
1654        let _m = server.mock(|when, then| {
1655            when.method(Method::GET).path("/gzip-text");
1656            then.status(200)
1657                .header("content-type", "text/plain; charset=utf-8")
1658                .header("content-encoding", "gzip")
1659                .body(compressed_body);
1660        });
1661
1662        let client = test_client();
1663        let url = format!("{}/gzip-text", server.base_url());
1664
1665        let text = client.get(&url).send().await.unwrap().text().await.unwrap();
1666
1667        assert_eq!(
1668            text, original_text,
1669            "text() should return decompressed UTF-8 content"
1670        );
1671    }
1672
1673    // ==========================================================================
1674    // Buffer Error Mapping Tests
1675    // ==========================================================================
1676
1677    /// Test that `map_buffer_error` returns inner `HttpError` when present.
1678    #[test]
1679    fn test_map_buffer_error_passes_through_http_error() {
1680        let http_err = HttpError::Timeout(std::time::Duration::from_secs(10));
1681        let boxed: tower::BoxError = Box::new(http_err);
1682        let result = map_buffer_error(boxed);
1683
1684        assert!(
1685            matches!(result, HttpError::Timeout(_)),
1686            "Should pass through HttpError::Timeout, got: {result:?}"
1687        );
1688    }
1689
1690    /// Test that `map_buffer_error` returns `ServiceClosed` for non-HttpError.
1691    ///
1692    /// This covers the case where buffer is closed or worker panicked.
1693    /// The error log is emitted (verified by code coverage, not assertion).
1694    #[test]
1695    fn test_map_buffer_error_returns_service_closed_for_unknown_error() {
1696        // Simulate a buffer closed error (any non-HttpError box)
1697        let other_err: tower::BoxError = Box::new(std::io::Error::new(
1698            std::io::ErrorKind::BrokenPipe,
1699            "buffer worker died",
1700        ));
1701        let result = map_buffer_error(other_err);
1702
1703        assert!(
1704            matches!(result, HttpError::ServiceClosed),
1705            "Should return ServiceClosed for non-HttpError, got: {result:?}"
1706        );
1707    }
1708
1709    // ==========================================================================
1710    // Status-based Retry Integration Tests
1711    //
1712    // These tests verify that retry-on-status works END-TO-END with real HTTP
1713    // responses (not just mock services that return Err directly).
1714    //
1715    // Key insight: hyper returns Ok(Response) for all HTTP statuses.
1716    // RetryLayer handles retries on Ok(Response) by checking status codes,
1717    // then returns Ok(Response) with the final status after retries exhaust.
1718    // send() NEVER returns Err(HttpStatus) - that's only created by error_for_status().
1719    // ==========================================================================
1720
1721    /// Test: GET request with 500 errors is retried.
1722    ///
1723    /// Server always returns 500. Asserts total calls == `max_retries` + 1.
1724    /// After retries exhaust, returns Ok(Response) with 500 status.
1725    #[tokio::test]
1726    async fn test_status_retry_get_500_retried() {
1727        use crate::config::{ExponentialBackoff, HttpClientConfig, RetryConfig};
1728
1729        let server = MockServer::start();
1730        let mock = server.mock(|when, then| {
1731            when.method(Method::GET).path("/retry-500");
1732            then.status(500).body("server error");
1733        });
1734
1735        let config = HttpClientConfig {
1736            transport: crate::config::TransportSecurity::AllowInsecureHttp,
1737            retry: Some(RetryConfig {
1738                max_retries: 2, // 1 initial + 2 retries = 3 total attempts
1739                backoff: ExponentialBackoff::fast(),
1740                ..RetryConfig::default() // 500 is in idempotent_retry
1741            }),
1742            rate_limit: None,
1743            ..Default::default()
1744        };
1745
1746        let client = HttpClientBuilder::with_config(config).build().unwrap();
1747        let url = format!("{}/retry-500", server.base_url());
1748
1749        let result = client.get(&url).send().await;
1750
1751        // GET on 500 SHOULD be retried (GET is idempotent, 500 is in idempotent_retry)
1752        assert_eq!(
1753            mock.calls(),
1754            3,
1755            "GET should retry on 500; expected 3 calls (1 + 2 retries), got {}",
1756            mock.calls()
1757        );
1758
1759        // After retries exhaust: returns Ok(Response) with 500 status
1760        let response = result.expect("send() should return Ok(Response) after retries exhaust");
1761        assert_eq!(response.status(), hyper::StatusCode::INTERNAL_SERVER_ERROR);
1762
1763        // User can convert to error via error_for_status()
1764        let err = response.error_for_status().unwrap_err();
1765        assert!(
1766            matches!(err, HttpError::HttpStatus { status, .. } if status == hyper::StatusCode::INTERNAL_SERVER_ERROR)
1767        );
1768    }
1769
1770    /// Test: POST request with 500 is NOT retried and returns Ok(Response).
1771    ///
1772    /// With default retry config, 500 is only retried for idempotent methods.
1773    /// POST is not idempotent, so:
1774    /// 1. No retry (calls == 1)
1775    /// 2. Returns Ok(Response) with status 500 (not converted to Err)
1776    ///
1777    /// User can use `.error_for_status()` or `.json()` to handle the error.
1778    #[tokio::test]
1779    async fn test_status_retry_post_500_not_retried() {
1780        use crate::config::{ExponentialBackoff, HttpClientConfig, RetryConfig};
1781
1782        let server = MockServer::start();
1783        let mock = server.mock(|when, then| {
1784            when.method(Method::POST).path("/post-500");
1785            then.status(500).body("server error");
1786        });
1787
1788        let config = HttpClientConfig {
1789            transport: crate::config::TransportSecurity::AllowInsecureHttp,
1790            retry: Some(RetryConfig {
1791                max_retries: 3,
1792                backoff: ExponentialBackoff::fast(),
1793                ..RetryConfig::default() // 500 is in idempotent_retry, not always_retry
1794            }),
1795            rate_limit: None,
1796            ..Default::default()
1797        };
1798
1799        let client = HttpClientBuilder::with_config(config).build().unwrap();
1800        let url = format!("{}/post-500", server.base_url());
1801
1802        let result = client.post(&url).send().await;
1803
1804        // POST on 500 should NOT be retried (only idempotent methods)
1805        assert_eq!(
1806            mock.calls(),
1807            1,
1808            "POST should not be retried on 500; expected 1 call, got {}",
1809            mock.calls()
1810        );
1811
1812        // Result should be Ok(Response) with status 500 - NOT converted to error
1813        // because 500 is not retryable for non-idempotent methods
1814        let response = result.expect("POST + 500 should return Ok(Response), not Err");
1815        assert_eq!(
1816            response.status(),
1817            hyper::StatusCode::INTERNAL_SERVER_ERROR,
1818            "Response should have 500 status"
1819        );
1820
1821        // User can still use error_for_status() to convert to error if needed
1822    }
1823
1824    /// Test: POST request with 429 IS retried (`always_retry` policy).
1825    ///
1826    /// 429 (Too Many Requests) is in `always_retry` set, so it's retried
1827    /// regardless of HTTP method. Asserts calls == `max_retries` + 1.
1828    /// After retries exhaust, returns Ok(Response) with 429 status.
1829    #[tokio::test]
1830    async fn test_status_retry_post_429_retried() {
1831        use crate::config::{ExponentialBackoff, HttpClientConfig, RetryConfig};
1832
1833        let server = MockServer::start();
1834        let mock = server.mock(|when, then| {
1835            when.method(Method::POST).path("/post-429");
1836            then.status(429).body("rate limited");
1837        });
1838
1839        let config = HttpClientConfig {
1840            transport: crate::config::TransportSecurity::AllowInsecureHttp,
1841            retry: Some(RetryConfig {
1842                max_retries: 2, // 1 initial + 2 retries = 3 total
1843                backoff: ExponentialBackoff::fast(),
1844                ..RetryConfig::default() // 429 is in always_retry
1845            }),
1846            rate_limit: None,
1847            ..Default::default()
1848        };
1849
1850        let client = HttpClientBuilder::with_config(config).build().unwrap();
1851        let url = format!("{}/post-429", server.base_url());
1852
1853        let result = client.post(&url).send().await;
1854
1855        // POST on 429 SHOULD be retried (429 is in always_retry)
1856        assert_eq!(
1857            mock.calls(),
1858            3,
1859            "POST should retry on 429; expected 3 calls (1 + 2 retries), got {}",
1860            mock.calls()
1861        );
1862
1863        // After retries exhaust: returns Ok(Response) with 429 status
1864        let response = result.expect("send() should return Ok(Response) after retries exhaust");
1865        assert_eq!(response.status(), hyper::StatusCode::TOO_MANY_REQUESTS);
1866
1867        // User can convert to error via error_for_status()
1868        let err = response.error_for_status().unwrap_err();
1869        assert!(
1870            matches!(err, HttpError::HttpStatus { status, .. } if status == hyper::StatusCode::TOO_MANY_REQUESTS)
1871        );
1872    }
1873
1874    /// Test: Retry-After header is preserved and accessible via `error_for_status()`.
1875    ///
1876    /// Server returns 429 with `Retry-After: 60`. `send()` returns Ok(Response).
1877    /// User calls `error_for_status()` which parses Retry-After from headers.
1878    #[tokio::test]
1879    async fn test_status_retry_extracts_retry_after_header() {
1880        use crate::config::{ExponentialBackoff, HttpClientConfig, RetryConfig};
1881
1882        let server = MockServer::start();
1883        let _mock = server.mock(|when, then| {
1884            when.method(Method::GET).path("/retry-after");
1885            then.status(429)
1886                .header("Retry-After", "60")
1887                .header("Content-Type", "application/json")
1888                .body(r#"{"error": "rate limited"}"#);
1889        });
1890
1891        let config = HttpClientConfig {
1892            transport: crate::config::TransportSecurity::AllowInsecureHttp,
1893            retry: Some(RetryConfig {
1894                max_retries: 0, // No retries - we want to see the response immediately
1895                backoff: ExponentialBackoff::fast(),
1896                ..RetryConfig::default()
1897            }),
1898            rate_limit: None,
1899            ..Default::default()
1900        };
1901
1902        let client = HttpClientBuilder::with_config(config).build().unwrap();
1903        let url = format!("{}/retry-after", server.base_url());
1904
1905        let result = client.get(&url).send().await;
1906
1907        // send() returns Ok(Response) - status codes don't become Err
1908        let response = result.expect("send() should return Ok(Response)");
1909        assert_eq!(response.status(), hyper::StatusCode::TOO_MANY_REQUESTS);
1910
1911        // error_for_status() extracts Retry-After and Content-Type
1912        match response.error_for_status() {
1913            Err(HttpError::HttpStatus {
1914                status,
1915                retry_after,
1916                content_type,
1917                ..
1918            }) => {
1919                assert_eq!(status, hyper::StatusCode::TOO_MANY_REQUESTS);
1920                assert_eq!(
1921                    retry_after,
1922                    Some(std::time::Duration::from_mins(1)),
1923                    "Should extract Retry-After header"
1924                );
1925                assert_eq!(
1926                    content_type,
1927                    Some("application/json".to_owned()),
1928                    "Should extract Content-Type header"
1929                );
1930            }
1931            other => panic!("Expected HttpStatus error from error_for_status(), got: {other:?}"),
1932        }
1933    }
1934
1935    // NOTE: test_status_retry_honors_retry_after_timing was removed because it relied
1936    // on seconds-scale elapsed time assertions which are flaky in CI environments.
1937    // The Retry-After header parsing and usage is tested at the unit level in:
1938    // - response::tests::test_parse_retry_after_*
1939    // - layers::tests::test_retry_layer_uses_retry_after_header (50ms, fast)
1940    // - test_status_retry_extracts_retry_after_header (verifies field extraction)
1941
1942    /// Test: Retry delay ignores Retry-After when `ignore_retry_after=true`.
1943    ///
1944    /// Server always returns 429 with `Retry-After: 10`. Config has fast backoff.
1945    /// Elapsed time should be fast (< 1s), not ~20s (2 * 10s).
1946    #[tokio::test]
1947    async fn test_status_retry_ignores_retry_after_when_configured() {
1948        use crate::config::{ExponentialBackoff, HttpClientConfig, RetryConfig};
1949
1950        let server = MockServer::start();
1951        let mock = server.mock(|when, then| {
1952            when.method(Method::GET).path("/ignore-retry-after");
1953            then.status(429)
1954                .header("Retry-After", "10") // 10 seconds
1955                .body("rate limited");
1956        });
1957
1958        let config = HttpClientConfig {
1959            transport: crate::config::TransportSecurity::AllowInsecureHttp,
1960            retry: Some(RetryConfig {
1961                max_retries: 2,
1962                backoff: ExponentialBackoff::fast(), // 1ms initial
1963                ignore_retry_after: true,            // Ignore Retry-After header
1964                ..RetryConfig::default()
1965            }),
1966            rate_limit: None,
1967            ..Default::default()
1968        };
1969
1970        let client = HttpClientBuilder::with_config(config).build().unwrap();
1971        let url = format!("{}/ignore-retry-after", server.base_url());
1972
1973        let start = std::time::Instant::now();
1974        let _result = client.get(&url).send().await;
1975        let elapsed = start.elapsed();
1976
1977        // With ignore_retry_after=true and fast backoff, should be very fast
1978        // NOT 2 * 10s = 20s from Retry-After
1979        assert!(
1980            elapsed < std::time::Duration::from_secs(2),
1981            "Should have used fast backoff, not 10s Retry-After; elapsed: {elapsed:?}"
1982        );
1983
1984        // Verify we made 3 calls (1 initial + 2 retries)
1985        assert_eq!(mock.calls(), 3, "Expected 3 calls, got {}", mock.calls());
1986    }
1987
1988    /// Test: Non-retryable status (404) is NOT converted to error by `StatusToErrorLayer`.
1989    ///
1990    /// 404 is not in retry triggers, so it passes through as Ok(Response).
1991    /// User can still use `.error_for_status()` or `.json()` to check.
1992    #[tokio::test]
1993    async fn test_non_retryable_status_passes_through() {
1994        use crate::config::{ExponentialBackoff, HttpClientConfig, RetryConfig};
1995
1996        let server = MockServer::start();
1997        let mock = server.mock(|when, then| {
1998            when.method(Method::GET).path("/not-found");
1999            then.status(404)
2000                .header("content-type", "application/json")
2001                .body(r#"{"error": "not found"}"#);
2002        });
2003
2004        let config = HttpClientConfig {
2005            transport: crate::config::TransportSecurity::AllowInsecureHttp,
2006            retry: Some(RetryConfig {
2007                max_retries: 3,
2008                backoff: ExponentialBackoff::fast(),
2009                ..RetryConfig::default()
2010            }),
2011            rate_limit: None,
2012            ..Default::default()
2013        };
2014
2015        let client = HttpClientBuilder::with_config(config).build().unwrap();
2016        let url = format!("{}/not-found", server.base_url());
2017
2018        // send() should succeed (404 is not a retryable error)
2019        let result = client.get(&url).send().await;
2020
2021        // Only called once - no retry
2022        assert_eq!(
2023            mock.calls(),
2024            1,
2025            "404 should not trigger retry; expected 1 call, got {}",
2026            mock.calls()
2027        );
2028
2029        // Response is Ok, but status is 404
2030        let response = result.expect("send() should succeed for 404");
2031        assert_eq!(response.status(), hyper::StatusCode::NOT_FOUND);
2032
2033        // User can check status manually if needed via error_for_status
2034    }
2035
2036    /// Test: Multiple retries exhausted returns Ok(Response) with final status.
2037    ///
2038    /// Server always returns 500. After `max_retries` (2) + initial = 3 attempts,
2039    /// returns Ok(Response) with 500 status. User can use `error_for_status()`.
2040    #[tokio::test]
2041    async fn test_status_retry_exhausted_returns_ok_response() {
2042        use crate::config::{ExponentialBackoff, HttpClientConfig, RetryConfig};
2043
2044        let server = MockServer::start();
2045        let mock = server.mock(|when, then| {
2046            when.method(Method::GET).path("/always-500");
2047            then.status(500).body("always fails");
2048        });
2049
2050        let config = HttpClientConfig {
2051            transport: crate::config::TransportSecurity::AllowInsecureHttp,
2052            retry: Some(RetryConfig {
2053                max_retries: 2, // 1 initial + 2 retries = 3 total
2054                backoff: ExponentialBackoff::fast(),
2055                ..RetryConfig::default()
2056            }),
2057            rate_limit: None,
2058            ..Default::default()
2059        };
2060
2061        let client = HttpClientBuilder::with_config(config).build().unwrap();
2062        let url = format!("{}/always-500", server.base_url());
2063
2064        let result = client.get(&url).send().await;
2065
2066        // Should have tried 3 times (1 initial + 2 retries)
2067        assert_eq!(
2068            mock.calls(),
2069            3,
2070            "Expected 3 calls (1 initial + 2 retries), got {}",
2071            mock.calls()
2072        );
2073
2074        // After retries exhaust: returns Ok(Response) with 500 status
2075        let response = result.expect("send() should return Ok(Response) after retries exhaust");
2076        assert_eq!(response.status(), hyper::StatusCode::INTERNAL_SERVER_ERROR);
2077
2078        // User can convert to error via error_for_status()
2079        let err = response.error_for_status().unwrap_err();
2080        assert!(
2081            matches!(err, HttpError::HttpStatus { status, .. } if status == hyper::StatusCode::INTERNAL_SERVER_ERROR)
2082        );
2083    }
2084
2085    /// Test: Without retry config, retryable statuses pass through as Ok(Response).
2086    ///
2087    /// When retry is disabled (None), `StatusToErrorLayer` is not added.
2088    /// 500 returns Ok(Response), not Err(HttpStatus).
2089    #[tokio::test]
2090    async fn test_no_retry_config_status_passes_through() {
2091        use crate::config::HttpClientConfig;
2092
2093        let server = MockServer::start();
2094        let mock = server.mock(|when, then| {
2095            when.method(Method::GET).path("/no-retry");
2096            then.status(500).body("server error");
2097        });
2098
2099        let config = HttpClientConfig {
2100            transport: crate::config::TransportSecurity::AllowInsecureHttp,
2101            retry: None, // No retry - StatusToErrorLayer not added
2102            rate_limit: None,
2103            ..Default::default()
2104        };
2105
2106        let client = HttpClientBuilder::with_config(config).build().unwrap();
2107        let url = format!("{}/no-retry", server.base_url());
2108
2109        let result = client.get(&url).send().await;
2110
2111        // Only called once (no retry)
2112        assert_eq!(mock.calls(), 1);
2113
2114        // Response is Ok (500 passes through without StatusToErrorLayer)
2115        let response = result.expect("send() should succeed when retry disabled");
2116        assert_eq!(response.status(), hyper::StatusCode::INTERNAL_SERVER_ERROR);
2117
2118        // User can use error_for_status() to convert to error
2119        let err = response.error_for_status().unwrap_err();
2120        assert!(
2121            matches!(err, HttpError::HttpStatus { status, .. } if status == hyper::StatusCode::INTERNAL_SERVER_ERROR)
2122        );
2123    }
2124
2125    // ==========================================================================
2126    // URL Scheme Validation Tests
2127    // ==========================================================================
2128
2129    /// Test: http:// URL rejected when transport security is `TlsOnly`
2130    #[tokio::test]
2131    async fn test_url_scheme_http_rejected_with_tls_only() {
2132        let client = HttpClientBuilder::new()
2133            .transport(crate::config::TransportSecurity::TlsOnly)
2134            .retry(None)
2135            .build()
2136            .unwrap();
2137
2138        // Try to send a request to http:// URL
2139        let result = client.get("http://example.com/test").send().await;
2140
2141        // Should fail with InvalidScheme error
2142        match result {
2143            Err(HttpError::InvalidScheme { scheme, reason }) => {
2144                assert_eq!(scheme, "http");
2145                assert!(
2146                    reason.contains("TlsOnly"),
2147                    "Error should mention TlsOnly: {reason}"
2148                );
2149            }
2150            Err(other) => panic!("Expected InvalidScheme error, got: {other:?}"),
2151            Ok(_) => panic!("Expected InvalidScheme error, but request succeeded"),
2152        }
2153    }
2154
2155    /// Test: http:// URL allowed when transport security is `AllowInsecureHttp`
2156    #[tokio::test]
2157    async fn test_url_scheme_http_allowed_with_allow_insecure() {
2158        let server = MockServer::start();
2159        let _m = server.mock(|when, then| {
2160            when.method(Method::GET).path("/test");
2161            then.status(200).body("ok");
2162        });
2163
2164        let client = HttpClientBuilder::new()
2165            .transport(crate::config::TransportSecurity::AllowInsecureHttp)
2166            .retry(None)
2167            .build()
2168            .unwrap();
2169
2170        let url = format!("{}/test", server.base_url()); // http://127.0.0.1:xxxx
2171        let result = client.get(&url).send().await;
2172
2173        assert!(result.is_ok(), "http:// should be allowed: {result:?}");
2174    }
2175
2176    /// Test: https:// URL always allowed regardless of transport security
2177    #[tokio::test]
2178    async fn test_url_scheme_https_always_allowed() {
2179        // Note: We can't actually test HTTPS without a real server,
2180        // but we can verify the validation passes and fails later on connection
2181        let client = HttpClientBuilder::new()
2182            .transport(crate::config::TransportSecurity::TlsOnly)
2183            .retry(None)
2184            .build()
2185            .unwrap();
2186
2187        // The scheme validation should pass (not InvalidScheme)
2188        // but the actual connection will fail because example.com won't respond
2189        let result = client.get("https://localhost:0/test").send().await;
2190
2191        // Should NOT be InvalidScheme - should be a transport/connection error
2192        if let Err(HttpError::InvalidScheme { .. }) = result {
2193            panic!("https:// should not trigger InvalidScheme error")
2194        }
2195        // Any other error (transport, timeout, etc.) or Ok is expected
2196    }
2197
2198    /// Test: Invalid scheme (e.g., ftp://) rejected
2199    ///
2200    /// Note: transport security is left at preset default — `ftp://` is rejected
2201    /// independently of `TlsOnly`/`AllowInsecureHttp`, so the test runs identically
2202    /// under both `--features fips` (`TlsOnly` default) and without.
2203    #[tokio::test]
2204    async fn test_url_scheme_invalid_rejected() {
2205        let client = HttpClientBuilder::new().retry(None).build().unwrap();
2206
2207        let result = client.get("ftp://files.example.com/file.txt").send().await;
2208
2209        match result {
2210            Err(HttpError::InvalidScheme { scheme, reason }) => {
2211                assert_eq!(scheme, "ftp");
2212                assert!(
2213                    reason.contains("http://") || reason.contains("https://"),
2214                    "Error should mention supported schemes: {reason}"
2215                );
2216            }
2217            Err(other) => panic!("Expected InvalidScheme error, got: {other:?}"),
2218            Ok(_) => panic!("Expected InvalidScheme error, but request succeeded"),
2219        }
2220    }
2221
2222    /// Test: Missing scheme rejected (now returns `InvalidUri` with proper parsing)
2223    ///
2224    /// Note: transport security is left at preset default — a missing scheme is
2225    /// rejected independently of `TlsOnly`/`AllowInsecureHttp`, so the test runs
2226    /// identically under both `--features fips` (`TlsOnly` default) and without.
2227    #[tokio::test]
2228    async fn test_url_scheme_missing_rejected() {
2229        let client = HttpClientBuilder::new().retry(None).build().unwrap();
2230
2231        let result = client.get("example.com/test").send().await;
2232
2233        match result {
2234            Err(HttpError::InvalidUri { url, reason, kind }) => {
2235                // With proper URI parsing, this is an invalid URI (no scheme)
2236                assert_eq!(url, "example.com/test");
2237                assert!(!reason.is_empty(), "Should have a reason for invalid URI");
2238                assert_eq!(kind, crate::error::InvalidUriKind::ParseError);
2239            }
2240            Err(other) => panic!("Expected InvalidUri error, got: {other:?}"),
2241            Ok(_) => panic!("Expected InvalidUri error, but request succeeded"),
2242        }
2243    }
2244}