Skip to main content

rama/http/client/
mod.rs

1//! rama http client support
2//!
3//! Contains re-exports from `rama-http-backend::client`
4//! and adds `EasyHttpWebClient`, an opiniated http web client which
5//! supports most common use cases and provides sensible defaults.
6use std::{fmt, io};
7
8use crate::{
9    Layer, Service,
10    error::BoxError,
11    extensions::{Extensions, ExtensionsRef},
12    graceful::WeakScope,
13    http::{Body as ResponseBody, Request, Response, StreamingBody},
14    net::client::{
15        ConnectRequest, ConnectorService, EstablishedClientConnection, EstablishedProxyRoute,
16        ProxyDialer,
17    },
18    service::BoxService,
19    tcp::client::service::TcpConnector,
20    telemetry::tracing,
21};
22
23#[doc(inline)]
24pub use ::rama_http::service::client::blocking::{
25    Body as BlockingBody, Client as BlockingHttpClient, Response as BlockingResponse,
26};
27#[doc(inline)]
28pub use ::rama_http_backend::client::*;
29use rama_core::{
30    error::{ErrorContext, ErrorExt as _, extra::OpaqueError},
31    extensions::Egress,
32    layer::MapErr,
33};
34use rama_http::{
35    layer::{map_response_body::MapResponseBody, remove_header::remove_proxy_auth_request_headers},
36    proxy::PlaintextHttpProxyMode,
37};
38
39#[cfg(any(feature = "boring", feature = "rustls"))]
40use crate::tls::client::TlsClientConfig;
41
42#[cfg(feature = "boring")]
43use crate::tls::boring::client::TlsClientSessionCache;
44
45#[cfg(any(feature = "boring", all(feature = "quic", feature = "rustls")))]
46use std::sync::Arc;
47
48#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
49use crate::quic::tls::QuicClientConfigProvider;
50
51#[cfg(all(feature = "masque", feature = "quic"))]
52use crate::{
53    proxy::masque::connect_udp::{OUTER_IDLE_TIMEOUT, OUTER_INITIAL_MTU},
54    quic::{IdleTimeout, TransportConfig, proto::VarInt},
55};
56
57pub mod builder;
58#[doc(inline)]
59pub use builder::EasyHttpConnectorBuilder;
60
61mod proxy_connector;
62use proxy_connector::DefaultProxyHttpConnector;
63#[doc(inline)]
64pub use proxy_connector::{
65    DefaultProxyConnector, MaybeForwardedConnection, MaybeForwardedConnector, NoProxyConnection,
66    ProxyAltSvcConnectionLayer, ProxyConnectUdpMethod, ProxyConnectUdpNotEnabled, ProxyConnector,
67    ProxyConnectorBuilder, ProxyConnectorParts, ProxyHttpStage, ProxyMethodBuilder,
68    ProxyMethodNotEnabled, ProxyServiceConnector, ProxySocksMethod, ProxyStream,
69    ProxyStreamConnector,
70};
71
72/// An opiniated http client that can be used to serve HTTP requests.
73///
74/// Use [`EasyHttpWebClient::connector_builder`] to easily create a client with
75/// a common Http connector setup (tcp + proxy + tls + http) or bring your
76/// own http connector.
77///
78/// [`Default`] uses Rama's default multiplexing connection pool. Build the
79/// connector explicitly with
80/// [`EasyHttpConnectorBuilder::without_connection_pool`] when connection reuse
81/// is unwanted.
82///
83/// You can fork this http client in case you have use cases not possible with this service example.
84/// E.g. perhaps you wish to have middleware in into outbound requests, after they
85/// passed through your "connector" setup. All this and more is possible by defining your own
86/// http client. Rama is here to empower you, the building blocks are there, go crazy
87/// with your own service fork and use the full power of Rust at your fingertips ;)
88pub struct EasyHttpWebClient<BodyIn, ConnResponse, L> {
89    connector: BoxService<Request<BodyIn>, ConnResponse, OpaqueError>,
90    plaintext_http_proxy_mode: Option<PlaintextHttpProxyMode>,
91    jit_layers: L,
92}
93
94impl<BodyIn, ConnResponse, L> fmt::Debug for EasyHttpWebClient<BodyIn, ConnResponse, L> {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.debug_struct("EasyHttpWebClient").finish()
97    }
98}
99
100impl<BodyIn, ConnResponse, L: Clone> Clone for EasyHttpWebClient<BodyIn, ConnResponse, L> {
101    fn clone(&self) -> Self {
102        Self {
103            connector: self.connector.clone(),
104            plaintext_http_proxy_mode: self.plaintext_http_proxy_mode,
105            jit_layers: self.jit_layers.clone(),
106        }
107    }
108}
109
110impl EasyHttpWebClient<(), (), ()> {
111    /// Create a [`EasyHttpConnectorBuilder`] to easily create a [`EasyHttpWebClient`] with a
112    /// custom connector, whose connections and tunnels run in `scope`.
113    #[must_use]
114    pub fn connector_builder(scope: impl Into<WeakScope>) -> EasyHttpConnectorBuilder {
115        EasyHttpConnectorBuilder::new(scope)
116    }
117
118    /// Create a cloneable blocking HTTP(S) client with its own dedicated
119    /// runtime thread and Rama's default web connector stack.
120    ///
121    /// ```no_run
122    /// use rama::http::client::EasyHttpWebClient;
123    ///
124    /// # fn main() -> Result<(), rama::error::BoxError> {
125    /// let client = EasyHttpWebClient::try_blocking()?;
126    /// let client_for_worker = client.clone();
127    ///
128    /// let text = client_for_worker
129    ///     .get("https://example.com/")
130    ///     .send()?
131    ///     .try_into_string()?;
132    /// # _ = text;
133    /// # Ok(())
134    /// # }
135    /// ```
136    pub fn try_blocking() -> io::Result<BlockingHttpWebClient> {
137        BlockingHttpClient::try_new(EasyHttpWebClient::default())
138    }
139}
140
141/// Rama's default asynchronous HTTP(S) client, including its default
142/// multiplexing connection pool.
143///
144/// With BoringSSL or Rustls plus `ring`/`aws-lc`, HTTP/3 is available through
145/// alternative-service discovery or an explicit HTTP/3 request. Its shared UDP
146/// endpoint is bound lazily, so constructing the client requires no runtime.
147///
148/// Like a browser it resumes TLS sessions (with BoringSSL, also over TCP), which
149/// lets servers link the connections of one client. It acts for a single user:
150/// proxies relay traffic instead of sharing one client between their users.
151pub type DefaultHttpWebClient<Body = crate::http::Body> = EasyHttpWebClient<
152    Body,
153    EstablishedClientConnection<
154        rama_http::layer::alt_svc::AltSvc<
155            BindBodyToConn<
156                crate::net::client::pool::MultiplexedConnection<
157                    MaybeForwardedConnection<
158                        HttpClientService<Body>,
159                        DefaultForwardConnection<Body>,
160                    >,
161                    HttpConnId,
162                >,
163            >,
164        >,
165        Request<Body>,
166    >,
167    (),
168>;
169
170type DefaultForwardConnection<Body> = <proxy::HttpForwardProxyConnector<
171    ProxyDialer<DefaultProxyHttpConnector<TcpConnector, Body>>,
172> as ConnectorService<ConnectRequest>>::Connection;
173
174/// A blocking HTTP(S) client using Rama's default pooled web connector stack.
175pub type BlockingHttpWebClient = BlockingHttpClient<DefaultHttpWebClient>;
176
177impl<Body> Default for DefaultHttpWebClient<Body>
178where
179    Body: StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Unpin + Send + 'static,
180{
181    #[inline(always)]
182    fn default() -> Self {
183        Self::default_with_scope(WeakScope::detached())
184    }
185}
186
187impl<Body> DefaultHttpWebClient<Body>
188where
189    Body: StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Unpin + Send + 'static,
190{
191    /// Rama's default client stack, with its connections and tunnels in `scope`.
192    pub fn default_with_scope(scope: impl Into<WeakScope>) -> Self {
193        let scope = scope.into();
194        let proxies = ProxyConnector::default_with_scope(scope.clone());
195        Self::default_using_proxies(scope, proxies)
196    }
197
198    core::cfg_select! {
199        feature = "boring" => {
200            /// Rama's default client stack over `proxies`, the connector towards proxies,
201            /// such as a [`ProxyConnector`] which isolates the `407` of an upstream proxy
202            /// for the client of a proxy.
203            pub fn default_using_proxies(
204                scope: impl Into<WeakScope>,
205                proxies: DefaultProxyConnector<TcpConnector, Body>,
206            ) -> Self {
207                EasyHttpWebClient::connector_builder(scope.into())
208                    .with_default_transport_connector()
209                    .with_default_dns_connector()
210                    .with_proxy_support(proxies)
211                    .with_tls_support_using_boringssl(TlsClientConfig::default_http())
212                    .with_tls_session_store(Arc::new(TlsClientSessionCache::default()))
213                    .with_default_http_connector()
214                    .with_default_connection_pool()
215                    .build_client()
216            }
217        }
218        feature = "rustls" => {
219            /// Rama's default client stack over `proxies`, the connector towards proxies,
220            /// such as a [`ProxyConnector`] which isolates the `407` of an upstream proxy
221            /// for the client of a proxy.
222            pub fn default_using_proxies(
223                scope: impl Into<WeakScope>,
224                proxies: DefaultProxyConnector<TcpConnector, Body>,
225            ) -> Self {
226                EasyHttpWebClient::connector_builder(scope.into())
227                    .with_default_transport_connector()
228                    .with_default_dns_connector()
229                    .with_proxy_support(proxies)
230                    .with_tls_support_using_rustls(TlsClientConfig::default_http())
231                    .with_default_http_connector()
232                    .with_default_connection_pool()
233                    .build_client()
234            }
235        }
236        _ => {
237            /// Rama's default client stack over `proxies`, the connector towards proxies,
238            /// such as a [`ProxyConnector`] which isolates the `407` of an upstream proxy
239            /// for the client of a proxy.
240            pub fn default_using_proxies(
241                scope: impl Into<WeakScope>,
242                proxies: DefaultProxyConnector<TcpConnector, Body>,
243            ) -> Self {
244                EasyHttpWebClient::connector_builder(scope.into())
245                    .with_default_transport_connector()
246                    .with_default_dns_connector()
247                    .with_proxy_support(proxies)
248                    .without_tls_support()
249                    .with_default_http_connector()
250                    .with_default_connection_pool()
251                    .build_client()
252            }
253        }
254    }
255}
256
257#[cfg(all(feature = "masque", feature = "quic"))]
258#[cfg_attr(docsrs, doc(cfg(all(feature = "masque", feature = "quic"))))]
259/// The QUIC transport for HTTP/3 connections that carry MASQUE tunnels, for both the proxy
260/// and its clients: room for a tunneled QUIC packet in each datagram ([`OUTER_INITIAL_MTU`]),
261/// and an idle timeout that leaves quiet tunnels to their own policy
262/// ([`OUTER_IDLE_TIMEOUT`]).
263#[must_use]
264pub fn masque_quic_transport() -> TransportConfig {
265    let idle = u32::try_from(OUTER_IDLE_TIMEOUT.as_millis()).unwrap_or(u32::MAX);
266    TransportConfig::default()
267        .with_initial_mtu(OUTER_INITIAL_MTU)
268        .with_max_idle_timeout(IdleTimeout::from(VarInt::from_u32(idle)))
269}
270
271#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
272pub(crate) fn default_http3_builder(
273    scope: impl Into<WeakScope>,
274    tls: TlsClientConfig,
275    provider: Arc<dyn QuicClientConfigProvider>,
276) -> Http3ConnectorBuilder {
277    Http3Connector::builder(scope)
278        .with_tls_config(tls)
279        .with_tls_provider(provider)
280}
281
282impl<BodyIn, ConnResponse> EasyHttpWebClient<BodyIn, ConnResponse, ()>
283where
284    BodyIn: Send + 'static,
285{
286    /// Create a new [`EasyHttpWebClient`] using the provided connector.
287    ///
288    /// Custom proxy connectors must honor [`PlaintextHttpProxyMode`] and publish
289    /// [`EstablishedProxyRoute`].
290    /// Connection wrappers must preserve that metadata through [`ExtensionsRef`].
291    /// Forward credentials and challenge isolation come from [`ProxyConnector`]: a
292    /// connection which does not report [`EstablishedProxyRoute::Forward`] carries no
293    /// `Proxy-Authorization` at all.
294    #[must_use]
295    pub fn new<S>(connector: S) -> Self
296    where
297        S: Service<Request<BodyIn>, Output = ConnResponse, Error: Into<BoxError>>,
298    {
299        Self {
300            connector: MapErr::into_opaque_error(connector).boxed(),
301            plaintext_http_proxy_mode: None,
302            jit_layers: (),
303        }
304    }
305}
306
307impl<BodyIn, ConnResponse, L> EasyHttpWebClient<BodyIn, ConnResponse, L> {
308    /// Convert this asynchronous web client into a cloneable blocking client
309    /// with its own dedicated runtime thread.
310    pub fn try_into_blocking(self) -> io::Result<BlockingHttpClient<Self>> {
311        BlockingHttpClient::try_new(self)
312    }
313
314    /// Convert this asynchronous web client into a blocking client using a
315    /// caller-supplied runtime.
316    #[must_use]
317    pub fn into_blocking_with_runtime(
318        self,
319        runtime: &crate::rt::blocking::Runtime,
320    ) -> BlockingHttpClient<Self> {
321        BlockingHttpClient::with_runtime(self, runtime)
322    }
323
324    /// Set the connector that this [`EasyHttpWebClient`] will use.
325    ///
326    /// Custom proxy connectors follow the metadata contract described in [`Self::new`].
327    #[must_use]
328    pub fn with_connector<S, BodyInNew, ConnResponseNew>(
329        self,
330        connector: S,
331    ) -> EasyHttpWebClient<BodyInNew, ConnResponseNew, L>
332    where
333        S: Service<Request<BodyInNew>, Output = ConnResponseNew, Error: Into<BoxError>>,
334        BodyInNew: Send + 'static,
335    {
336        EasyHttpWebClient {
337            connector: MapErr::into_opaque_error(connector).boxed(),
338            plaintext_http_proxy_mode: self.plaintext_http_proxy_mode,
339            jit_layers: self.jit_layers,
340        }
341    }
342
343    /// [`Layer`] which will be applied just in time (JIT) before the request is sent, but after
344    /// the connection has been established. A forwarded request's proxy policy (credentials,
345    /// challenge isolation) is part of that connection, so it runs inside these layers: after
346    /// caller middleware has processed the request, and before it sees the response.
347    ///
348    /// That credential is the one of the request's own [`ProxyRoute`], which has to name the
349    /// proxy its connection reaches. A layer here which rewrites that route leaves the
350    /// request without credentials, rather than sending another proxy's.
351    ///
352    /// [`ProxyRoute`]: rama_net::client::ProxyRoute
353    ///
354    /// Simplified flow of how the [`EasyHttpWebClient`] works:
355    /// 1. External: let response = client.serve(request)
356    /// 2. Internal: let http_connection = self.connector.serve(request)
357    /// 3. Internal: let response = jit_layers.layer(http_connection).serve(request)
358    pub fn with_jit_layer<T>(self, jit_layers: T) -> EasyHttpWebClient<BodyIn, ConnResponse, T> {
359        EasyHttpWebClient {
360            connector: self.connector,
361            plaintext_http_proxy_mode: self.plaintext_http_proxy_mode,
362            jit_layers,
363        }
364    }
365
366    crate::utils::macros::generate_set_and_with! {
367        /// Enable or disable carrying plaintext HTTP through an HTTP(S) proxy with
368        /// CONNECT instead of using ordinary forward-proxy semantics
369        /// (absolute-form on HTTP/1).
370        ///
371        /// If this method is not called, a request-level
372        /// [`PlaintextHttpProxyMode`]
373        /// is honored and
374        /// otherwise forwarding is the connector default. Calling this method
375        /// explicitly selects Tunnel (`true`) or Forward (`false`) for the client.
376        /// Tunneling does not encrypt the origin traffic: a plaintext `http://`
377        /// request remains plaintext inside the proxy tunnel.
378        pub fn tunnel_plaintext_http(mut self, enabled: bool) -> Self {
379            self.plaintext_http_proxy_mode = Some(if enabled {
380                PlaintextHttpProxyMode::Tunnel
381            } else {
382                PlaintextHttpProxyMode::Forward
383            });
384            self
385        }
386    }
387}
388
389/// The connection a request is served on, with the facts of that connection applied to it
390/// closest to the wire: whatever middleware did to the request, its [`Egress`] snapshot is
391/// the one of this connection, and a `Proxy-Authorization` field only stays on it when it
392/// reaches an HTTP proxy which forwards the request.
393#[derive(Debug, Clone)]
394pub struct ConnectionEgress<S> {
395    inner: S,
396    extensions: Extensions,
397}
398
399impl<S: ExtensionsRef> ConnectionEgress<S> {
400    /// Serve requests on `inner` with the facts of that connection.
401    pub fn new(inner: S) -> Self {
402        let extensions = inner.extensions().clone();
403        Self { inner, extensions }
404    }
405}
406
407impl<S> ExtensionsRef for ConnectionEgress<S> {
408    fn extensions(&self) -> &Extensions {
409        &self.extensions
410    }
411}
412
413impl<S, RequestBody> Service<Request<RequestBody>> for ConnectionEgress<S>
414where
415    S: Service<Request<RequestBody>>,
416    RequestBody: Send + 'static,
417{
418    type Output = S::Output;
419    type Error = S::Error;
420
421    async fn serve(&self, mut request: Request<RequestBody>) -> Result<Self::Output, Self::Error> {
422        let forwarded = self
423            .extensions
424            .get_ref::<EstablishedProxyRoute>()
425            .is_some_and(EstablishedProxyRoute::is_http_forward);
426        request.extensions().insert(Egress(self.extensions.clone()));
427        if !forwarded {
428            remove_proxy_auth_request_headers(request.headers_mut());
429        }
430        self.inner.serve(request).await
431    }
432}
433
434impl<Body, ConnectionBody, Connection, IncomingBody, L> Service<Request<Body>>
435    for EasyHttpWebClient<Body, EstablishedClientConnection<Connection, Request<ConnectionBody>>, L>
436where
437    Body: StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Unpin + Send + 'static,
438    Connection: Service<Request<ConnectionBody>, Output = Response<IncomingBody>, Error = BoxError>
439        + ExtensionsRef,
440    IncomingBody: Send + Sync + 'static,
441    ResponseBody: From<IncomingBody>,
442    // Body type this connection will be able to send, this is not necessarily the same one that
443    // was used in the request that created this connection
444    ConnectionBody:
445        StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Unpin + Send + 'static,
446    L: Layer<
447            MapResponseBody<ConnectionEgress<Connection>, fn(IncomingBody) -> ResponseBody>,
448            Service: Service<Request<ConnectionBody>, Output = Response, Error = BoxError>,
449        > + Send
450        + Sync
451        + 'static,
452{
453    type Output = Response;
454    type Error = OpaqueError;
455
456    async fn serve(&self, req: Request<Body>) -> Result<Self::Output, Self::Error> {
457        let uri = req.uri().clone();
458
459        if let Some(mode) = self.plaintext_http_proxy_mode {
460            req.extensions().insert(mode);
461        }
462
463        let EstablishedClientConnection {
464            input: req,
465            conn: http_connection,
466        } = self.connector.serve(req).await.into_opaque_error()?;
467
468        // Published for the JIT layers above; the connection publishes its own facts again
469        // once those layers have run.
470        let http_connection = ConnectionEgress::new(http_connection);
471        req.extensions()
472            .insert(Egress(http_connection.extensions().clone()));
473
474        let http_connection = MapResponseBody::into_boxed_streaming_body(http_connection);
475        let http_connection = self.jit_layers.layer(http_connection);
476
477        // NOTE: stack might change request version based on connector data,
478        tracing::trace!(url.full = %uri, "send http req to connector stack");
479
480        let result = http_connection.serve(req).await;
481
482        match result {
483            Ok(resp) => {
484                tracing::trace!(url.full = %uri, "response received from connector stack");
485                Ok(resp)
486            }
487            Err(err) => Err(err
488                .context("http request failure")
489                .context_field("uri", uri)
490                .into_opaque_error()),
491        }
492    }
493}
494
495#[cfg(test)]
496mod tests {
497    use std::{
498        convert::Infallible,
499        fmt::Debug,
500        net::{Ipv4Addr, Ipv6Addr},
501        num::NonZeroUsize,
502        sync::{
503            Arc,
504            atomic::{AtomicUsize, Ordering},
505        },
506        time::Duration,
507    };
508
509    use crate::dns::client::{
510        lb::{DnsLoadBalancerConfig, DnsLoadBalancerLayer, RoundRobinPicker},
511        resolver::DnsAddressResolver,
512    };
513    use crate::net::{
514        ConnectorTargetInputExt as _,
515        address::{Domain, HostWithPort},
516        mode::DnsResolveIpMode,
517    };
518    use rama_core::extensions::Extensions;
519    use rama_core::futures::{Stream, stream};
520    use rama_core::{error::BoxErrorExt as _, service::service_fn};
521    use rama_http::{Body, BodyExtractExt, Version, proxy::ProxyRequestBody};
522    use rama_http_backend::server::HttpServer;
523    use rama_net::{
524        address::{ProxyAddress, ProxyProtocol},
525        client::{
526            ConnectRequest, ConnectionError, ConnectionErrorDomain, ConnectionErrorKind,
527            ConnectorService, ConnectorTarget, EstablishedProxyRoute, PlaintextProxyOnly,
528            ProxyRoute, ProxyRouteFailureCache, ProxyRouteFailureCacheConfig,
529            ProxyRouteFailureCacheScope, ProxyRoutes,
530        },
531        http::TargetHttpVersion,
532        test_utils::client::{MockConnectorService, MockSocket},
533    };
534    use rama_utils::octets::kib;
535    use serde::{Deserialize, Serialize};
536    use tokio::time::sleep;
537
538    #[cfg(any(feature = "boring", feature = "socks5"))]
539    use rama_core::layer::MapInputLayer;
540    #[cfg(feature = "boring")]
541    use {
542        crate::{
543            net::address::SocketAddress,
544            tcp::{TcpStream, server::TcpListener},
545            tls::{
546                boring::{TlsStream, server::TlsAcceptorLayer},
547                client::{NegotiatedTlsParameters, ServerVerifyMode, TlsServerVerify},
548                server::{GeneratedServerAuthConfig, ServerAuthData, TlsServerConfig},
549            },
550        },
551        rama_core::extensions::ExtensionsRef as _,
552        rama_http::header::CONNECTION,
553    };
554
555    use super::*;
556
557    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
558    struct Output {
559        conn: usize,
560        resp: usize,
561        target: String,
562    }
563
564    #[tokio::test]
565    async fn default_client_request_future_stays_within_stack_budget() {
566        let client = DefaultHttpWebClient::<Body>::default();
567        let request = Request::builder()
568            .uri("https://example.com/")
569            .body(Body::empty())
570            .unwrap();
571        let request = client.serve(request);
572        let inner_size = std::mem::size_of_val(&request);
573        let request = tokio::time::timeout(Duration::from_secs(1), request);
574        let size = std::mem::size_of_val(&request);
575        eprintln!("default client request: {inner_size} bytes; with timeout: {size} bytes");
576        assert!(
577            size <= kib(16),
578            "default client request future is {size} bytes"
579        );
580    }
581
582    #[test]
583    fn default_client_can_be_constructed_and_cloned_without_a_runtime() {
584        let client = DefaultHttpWebClient::<Body>::default();
585        drop(client.clone());
586        drop(client);
587    }
588
589    #[derive(Debug, Clone, Default, ExtensionsRef)]
590    struct EmptyHttpConnection {
591        extensions: Extensions,
592    }
593
594    impl Service<Request> for EmptyHttpConnection {
595        type Output = Response;
596        type Error = BoxError;
597
598        async fn serve(&self, _request: Request) -> Result<Self::Output, Self::Error> {
599            Ok(Response::new(Body::empty()))
600        }
601    }
602
603    #[derive(Debug, Clone)]
604    struct InspectConnectionRouteLayer(EstablishedProxyRoute);
605
606    impl<S: ExtensionsRef> Layer<S> for InspectConnectionRouteLayer {
607        type Service = S;
608
609        fn layer(&self, inner: S) -> Self::Service {
610            assert_eq!(
611                inner.extensions().get_ref::<EstablishedProxyRoute>(),
612                Some(&self.0),
613            );
614            inner
615        }
616    }
617
618    fn dummy_server() -> impl Service<
619        ConnectRequest,
620        Output = EstablishedClientConnection<MockSocket, ConnectRequest>,
621        Error = Infallible,
622    > + Clone {
623        let created_connections = Arc::new(AtomicUsize::new(0));
624        MockConnectorService::new(move |input: &ConnectRequest| {
625            let created_connections = created_connections.clone();
626            let conn = created_connections.fetch_add(1, Ordering::Relaxed);
627            let target = input.connector_target().unwrap().to_string();
628
629            // count responses created on this specific connection
630            let created_response = Arc::new(AtomicUsize::new(0));
631
632            HttpServer::auto(WeakScope::detached()).service(service_fn(move |_req: Request| {
633                let created_response = created_response.clone();
634                let resp = created_response.fetch_add(1, Ordering::Relaxed);
635                let target = target.clone();
636                async move {
637                    sleep(Duration::from_millis(5)).await;
638                    let out = Output { conn, resp, target };
639                    let resp = Response::new(Body::from(serde_json::to_vec(&out).unwrap()));
640                    Ok::<_, Infallible>(resp)
641                }
642            }))
643        })
644    }
645
646    /// The restriction the tunnel carries describes the connection to the
647    /// proxy, which the origin's TLS inputs cannot change: it serves the next
648    /// origin request whether or not that one carries the same overrides.
649    #[cfg(any(
650        feature = "boring",
651        all(feature = "rustls", any(feature = "aws-lc", feature = "ring"))
652    ))]
653    fn assert_tunnel_serves_the_same_proxy(
654        conn: &crate::extensions::Extensions,
655        route: &ProxyRoute,
656    ) {
657        use crate::extensions::Extensions;
658        use crate::net::client::pool::ConnectionReuse;
659        use crate::net::tls::ServerName;
660        use crate::tls::client::{ServerVerifyMode, TlsServerVerify};
661
662        // The rules of the connection to the proxy crossed the CONNECT boundary first; the origin's own
663        // were published on top of them.
664        let leg = conn
665            .self_first_ref::<ConnectionReuse>()
666            .expect("the tunnel carries the rules of the connection to the proxy");
667        assert!(
668            !leg.is_complete(),
669            "the connection to the proxy does not describe the origin"
670        );
671
672        let routed = || {
673            let request = Extensions::new();
674            request.insert(route.clone());
675            request
676        };
677        let same = routed();
678        same.insert(TlsServerVerify(ServerVerifyMode::Disable));
679        same.insert(ServerName::from(crate::net::address::Domain::from_static(
680            "elsewhere.example",
681        )));
682        assert!(
683            leg.matches(&same),
684            "a request with the same TLS inputs reuses the tunnel"
685        );
686        assert!(
687            leg.matches(&routed()),
688            "the rules of the connection to the proxy do not read the origin's TLS inputs"
689        );
690
691        // A request that asks for other settings towards the proxy is a
692        // different connection to the proxy, even with the same origin TLS inputs.
693        let other_hop = routed();
694        let bag = Extensions::new();
695        bag.insert(TlsServerVerify(ServerVerifyMode::Disable));
696        other_hop.insert(crate::net::client::ProxyConnectionExtensions(bag));
697        assert!(
698            !leg.matches(&other_hop),
699            "a request with other hop settings never shares this tunnel"
700        );
701    }
702
703    fn proxy_authority() -> HostWithPort {
704        HostWithPort::try_from("proxy.example:8080").unwrap()
705    }
706
707    fn origin_authority() -> HostWithPort {
708        HostWithPort::try_from("example.com:80").unwrap()
709    }
710
711    type ProxyHttpOver<T> =
712        ProxyServiceConnector<HttpConnector<PlaintextProxyOnly<T>, ProxyRequestBody<Body>>>;
713
714    fn proxies_over<T>(
715        transport: T,
716    ) -> ProxyConnector<
717        ProxySocksMethod<PlaintextProxyOnly<T>>,
718        proxy::layer::HttpConnectProxyConnector<ProxyDialer<ProxyHttpOver<T>>>,
719        ProxyConnectUdpMethod<ProxyHttpOver<T>>,
720        proxy::HttpForwardProxyConnector<ProxyDialer<ProxyHttpOver<T>>>,
721    >
722    where
723        T: Clone + Service<ConnectRequest>,
724        HttpConnector<PlaintextProxyOnly<T>, ProxyRequestBody<Body>>:
725            ConnectorService<ConnectRequest>,
726    {
727        ProxyConnector::builder(WeakScope::detached())
728            .with_custom_tcp_connector(transport)
729            .without_dns_connector()
730            .without_tls_support()
731            .with_default_http_connector()
732            .without_connection_pool()
733            .with_all_proxy_protocols()
734            .build()
735    }
736
737    #[tokio::test]
738    async fn custom_connector_receives_plaintext_http_proxy_mode() {
739        let connector = service_fn(|request: Request| async move {
740            assert_eq!(
741                request.extensions().get_ref::<PlaintextHttpProxyMode>(),
742                Some(&PlaintextHttpProxyMode::Tunnel)
743            );
744
745            let conn = EmptyHttpConnection::default();
746            Ok::<_, Infallible>(EstablishedClientConnection {
747                input: request,
748                conn,
749            })
750        });
751        let client = EasyHttpWebClient::new(connector).with_tunnel_plaintext_http(true);
752        let request = Request::builder()
753            .uri("http://example.com/")
754            .body(Body::empty())
755            .unwrap();
756
757        let response = client.serve(request).await.unwrap();
758        assert_eq!(response.status(), crate::http::StatusCode::OK);
759    }
760
761    #[tokio::test]
762    async fn jit_layer_can_read_established_connection_extensions() {
763        let connector = service_fn(|request: Request| async move {
764            let conn = EmptyHttpConnection::default();
765            conn.extensions().insert(EstablishedProxyRoute::Direct);
766            Ok::<_, Infallible>(EstablishedClientConnection {
767                input: request,
768                conn,
769            })
770        });
771        let client = EasyHttpWebClient::new(connector)
772            .with_jit_layer(InspectConnectionRouteLayer(EstablishedProxyRoute::Direct));
773        let request = Request::builder()
774            .uri("http://example.com/")
775            .extension(ProxyRoute::Direct)
776            .body(Body::empty())
777            .unwrap();
778
779        let response = client.serve(request).await.unwrap();
780        assert_eq!(response.status(), crate::http::StatusCode::OK);
781    }
782
783    #[tokio::test]
784    async fn a_custom_connector_sends_proxy_credentials_only_over_a_forward_connection() {
785        use rama_core::layer::MapInputLayer;
786        use rama_http::{HeaderValue, header::PROXY_AUTHORIZATION};
787
788        #[derive(Debug, Clone, ExtensionsRef)]
789        struct RecordingConnection {
790            extensions: Extensions,
791            observed: Arc<parking_lot::Mutex<Option<HeaderValue>>>,
792        }
793
794        impl Service<Request> for RecordingConnection {
795            type Output = Response;
796            type Error = BoxError;
797
798            async fn serve(&self, request: Request) -> Result<Self::Output, Self::Error> {
799                *self.observed.lock() = request.headers().get(PROXY_AUTHORIZATION).cloned();
800                Ok(Response::new(Body::empty()))
801            }
802        }
803
804        let proxy: ProxyAddress = "http://upstream:secret@proxy.example:8080".parse().unwrap();
805        let forward = EstablishedProxyRoute::Forward(proxy.clone());
806        for (route, jit, expected) in [
807            (
808                Some(EstablishedProxyRoute::Direct),
809                Some("Basic aml0"),
810                None,
811            ),
812            (
813                Some(EstablishedProxyRoute::Tunnel(proxy.clone())),
814                Some("Basic aml0"),
815                None,
816            ),
817            (
818                Some(forward.clone()),
819                Some("Basic aml0"),
820                Some("Basic aml0"),
821            ),
822            (Some(forward.clone()), None, Some("Basic Y2FsbGVy")),
823            (None, None, None),
824        ] {
825            let observed = Arc::new(parking_lot::Mutex::new(None));
826            let connector = service_fn({
827                let observed = observed.clone();
828                move |request: Request| {
829                    let route = route.clone();
830                    let observed = observed.clone();
831                    async move {
832                        let extensions = Extensions::new();
833                        if let Some(route) = route {
834                            extensions.insert(route);
835                        }
836                        Ok::<_, Infallible>(EstablishedClientConnection {
837                            input: request,
838                            conn: RecordingConnection {
839                                extensions,
840                                observed,
841                            },
842                        })
843                    }
844                }
845            });
846            let request = Request::builder()
847                .uri("http://origin.example/resource")
848                .header(PROXY_AUTHORIZATION, "Basic Y2FsbGVy")
849                .body(Body::empty())
850                .unwrap();
851
852            EasyHttpWebClient::new(connector)
853                .with_jit_layer(MapInputLayer::new(move |mut request: Request| {
854                    if let Some(jit) = jit {
855                        request
856                            .headers_mut()
857                            .insert(PROXY_AUTHORIZATION, HeaderValue::from_static(jit));
858                    }
859                    request
860                }))
861                .serve(request)
862                .await
863                .unwrap();
864
865            assert_eq!(*observed.lock(), expected.map(HeaderValue::from_static));
866        }
867    }
868
869    #[tokio::test]
870    async fn a_jit_layer_which_rewrites_the_requested_route_sends_no_credentials() {
871        use rama_core::layer::MapInputLayer;
872
873        let log = Arc::new(parking_lot::Mutex::new(Vec::new()));
874        let proxies = ProxyConnector::builder(WeakScope::detached())
875            .with_custom_tcp_connector(())
876            .without_dns_connector()
877            .without_tls_support()
878            .with_custom_http_connector::<Body, _>(RecordingConnector::new(None, &log))
879            .without_connection_pool()
880            .with_http_forward()
881            .build();
882        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
883            .with_custom_tcp_connector(())
884            .without_dns_connector()
885            .with_proxy_support(proxies)
886            .without_tls_support()
887            .with_custom_http_connector(RecordingConnector::new(None, &log))
888            .without_proxy_route_failure_cache()
889            .without_connection_pool()
890            .build_client()
891            .with_jit_layer(MapInputLayer::new(|request: Request| {
892                request.extensions().insert(ProxyRoute::Direct);
893                request
894            }));
895        let request = Request::builder()
896            .uri("http://origin.example/resource")
897            .body(Body::empty())
898            .unwrap();
899        request.extensions().insert(ProxyRoute::Proxy(
900            "http://u:p@proxy.example:8080".parse().unwrap(),
901        ));
902
903        client.serve(request).await.unwrap();
904
905        let log = log.lock();
906        assert_eq!(log.len(), 1);
907        let (authority, target, auth) = &log[0];
908        assert_eq!(
909            authority,
910            &HostWithPort::try_from("proxy.example:8080").unwrap(),
911            "the connection is the one the route asked for",
912        );
913        assert_eq!(target, "http://origin.example/resource");
914        assert_eq!(
915            auth.as_deref(),
916            None,
917            "a route which no longer names the proxy reached names no credentials",
918        );
919    }
920
921    #[tokio::test]
922    async fn jit_request_metadata_cannot_change_a_custom_connectors_route_or_credentials() {
923        use rama_core::layer::{MapInputLayer, MapOutputLayer};
924        use rama_http::{HeaderValue, StatusCode, header::PROXY_AUTHORIZATION, proto::h1::head};
925
926        #[derive(Debug, Clone, ExtensionsRef)]
927        struct InspectProxyConnection {
928            extensions: Extensions,
929        }
930
931        impl Service<Request> for InspectProxyConnection {
932            type Output = Response;
933            type Error = BoxError;
934
935            async fn serve(&self, request: Request) -> Result<Response, BoxError> {
936                let route = self.extensions.get_ref::<EstablishedProxyRoute>();
937                let is_forward = route.is_some_and(EstablishedProxyRoute::is_http_forward);
938                assert_eq!(
939                    request
940                        .extensions()
941                        .egress()
942                        .unwrap()
943                        .0
944                        .get_ref::<EstablishedProxyRoute>(),
945                    route,
946                    "the client publishes the facts of the connection, not stale metadata",
947                );
948                assert_eq!(
949                    request.extensions().get_ref::<ProxyRoute>(),
950                    Some(&ProxyRoute::Proxy(
951                        "http://wrong:request-secret@requested.example:8080"
952                            .parse()
953                            .unwrap(),
954                    )),
955                    "the caller's requested route is preserved",
956                );
957                let mut target = Vec::new();
958                head::encode_request_target(
959                    request.method(),
960                    request.uri(),
961                    request.extensions(),
962                    &mut target,
963                )
964                .unwrap();
965                if is_forward {
966                    // A custom connector owns the credentials of the proxy it reaches.
967                    assert_eq!(
968                        request.headers().get(PROXY_AUTHORIZATION).unwrap(),
969                        "Basic downstream-secret",
970                    );
971                    assert_eq!(&target[..], b"http://origin.example/resource");
972                } else {
973                    assert!(request.headers().get(PROXY_AUTHORIZATION).is_none());
974                    assert_eq!(&target[..], b"/resource");
975                }
976                Ok(Response::builder()
977                    .status(StatusCode::PROXY_AUTHENTICATION_REQUIRED)
978                    .header("proxy-authenticate", "Basic realm=private-upstream")
979                    .body(Body::from("private upstream challenge"))
980                    .unwrap())
981            }
982        }
983
984        let proxy: ProxyAddress = "http://upstream:secret@proxy.example:8080".parse().unwrap();
985        for route in [
986            None,
987            Some(EstablishedProxyRoute::Direct),
988            Some(EstablishedProxyRoute::Tunnel(proxy.clone())),
989            Some(EstablishedProxyRoute::Tunnel(
990                "socks5://proxy.example:1080".parse().unwrap(),
991            )),
992            Some(EstablishedProxyRoute::Forward(proxy.clone())),
993        ] {
994            let is_forward = route
995                .as_ref()
996                .is_some_and(EstablishedProxyRoute::is_http_forward);
997            let connector = service_fn(move |request: Request| {
998                let route = route.clone();
999                async move {
1000                    let extensions = Extensions::new();
1001                    if let Some(route) = route {
1002                        extensions.insert(route);
1003                    }
1004                    Ok::<_, Infallible>(EstablishedClientConnection {
1005                        input: request,
1006                        conn: InspectProxyConnection { extensions },
1007                    })
1008                }
1009            });
1010            let stale_route = if is_forward {
1011                EstablishedProxyRoute::Direct
1012            } else {
1013                EstablishedProxyRoute::Forward(proxy.clone())
1014            };
1015            let observed_responses = Arc::new(AtomicUsize::new(0));
1016            let client = EasyHttpWebClient::new(connector).with_jit_layer((
1017                MapInputLayer::new(move |mut request: Request| {
1018                    request.extensions().insert(stale_route.clone());
1019                    let stale_egress = Extensions::new();
1020                    stale_egress.insert(stale_route.clone());
1021                    request.extensions().insert(Egress(stale_egress));
1022                    request.headers_mut().insert(
1023                        PROXY_AUTHORIZATION,
1024                        HeaderValue::from_static("Basic downstream-secret"),
1025                    );
1026                    request
1027                }),
1028                MapOutputLayer::new({
1029                    let observed_responses = observed_responses.clone();
1030                    move |response: Response| {
1031                        observed_responses.fetch_add(1, Ordering::Relaxed);
1032                        response
1033                    }
1034                }),
1035            ));
1036            let request = Request::builder()
1037                .uri("http://origin.example/resource")
1038                .body(Body::empty())
1039                .unwrap();
1040            request.extensions().insert(ProxyRoute::Proxy(
1041                "http://wrong:request-secret@requested.example:8080"
1042                    .parse()
1043                    .unwrap(),
1044            ));
1045
1046            let response = client.serve(request).await.unwrap();
1047
1048            assert_eq!(response.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED);
1049            assert_eq!(observed_responses.load(Ordering::Relaxed), 1);
1050        }
1051    }
1052
1053    #[tokio::test]
1054    async fn jit_request_metadata_cannot_change_proxy_credentials_target_or_challenge_isolation() {
1055        use rama_core::layer::{MapInputLayer, MapOutputLayer};
1056        use rama_http::{HeaderValue, StatusCode, header::PROXY_AUTHORIZATION, proto::h1::head};
1057
1058        #[derive(Debug, Clone, ExtensionsRef)]
1059        struct InspectProxyConnection {
1060            extensions: Extensions,
1061        }
1062
1063        impl<B: Send + 'static> Service<Request<B>> for InspectProxyConnection {
1064            type Output = Response;
1065            type Error = BoxError;
1066
1067            async fn serve(&self, request: Request<B>) -> Result<Response, BoxError> {
1068                let route = self.extensions.get_ref::<EstablishedProxyRoute>();
1069                let is_forward = route.is_some_and(EstablishedProxyRoute::is_http_forward);
1070                let mut target = Vec::new();
1071                head::encode_request_target(
1072                    request.method(),
1073                    request.uri(),
1074                    request.extensions(),
1075                    &mut target,
1076                )
1077                .unwrap();
1078                if is_forward {
1079                    assert_eq!(
1080                        request.extensions().get_ref::<ProxyRoute>(),
1081                        Some(&ProxyRoute::Proxy(
1082                            "http://upstream:secret@proxy.example:8080".parse().unwrap(),
1083                        )),
1084                        "forward policy must preserve the caller's requested route",
1085                    );
1086                    assert_eq!(
1087                        request.headers().get(PROXY_AUTHORIZATION).unwrap(),
1088                        "Basic dXBzdHJlYW06c2VjcmV0",
1089                    );
1090                    assert_eq!(&target[..], b"http://origin.example/resource");
1091                } else {
1092                    assert!(request.headers().get(PROXY_AUTHORIZATION).is_none());
1093                    assert_eq!(&target[..], b"/resource");
1094                }
1095                Ok(Response::builder()
1096                    .status(StatusCode::PROXY_AUTHENTICATION_REQUIRED)
1097                    .header("proxy-authenticate", "Basic realm=private-upstream")
1098                    .body(Body::from("private upstream challenge"))
1099                    .unwrap())
1100            }
1101        }
1102
1103        #[derive(Debug, Clone, Copy)]
1104        struct InspectingConnector;
1105
1106        impl Service<ConnectRequest> for InspectingConnector {
1107            type Output = EstablishedClientConnection<InspectProxyConnection, ConnectRequest>;
1108            type Error = ConnectionError;
1109
1110            async fn serve(&self, input: ConnectRequest) -> Result<Self::Output, Self::Error> {
1111                Ok(EstablishedClientConnection {
1112                    conn: InspectProxyConnection {
1113                        extensions: speaks_requested_version(&input),
1114                    },
1115                    input,
1116                })
1117            }
1118        }
1119
1120        impl<S> Layer<S> for InspectingConnector {
1121            type Service = Self;
1122
1123            fn layer(&self, _: S) -> Self::Service {
1124                *self
1125            }
1126        }
1127
1128        let proxy = ProxyRoute::Proxy("http://upstream:secret@proxy.example:8080".parse().unwrap());
1129        for isolate in [false, true] {
1130            for is_forward in [false, true] {
1131                let proxies = ProxyConnector::builder(WeakScope::detached())
1132                    .with_custom_tcp_connector(())
1133                    .without_dns_connector()
1134                    .without_tls_support()
1135                    .with_custom_http_connector::<Body, _>(InspectingConnector)
1136                    .without_connection_pool()
1137                    .with_http_forward()
1138                    .build()
1139                    .with_isolate_forward_proxy_auth_error(isolate);
1140                let stale_route = if is_forward {
1141                    EstablishedProxyRoute::Direct
1142                } else {
1143                    EstablishedProxyRoute::Forward(
1144                        "http://upstream:secret@proxy.example:8080".parse().unwrap(),
1145                    )
1146                };
1147                let observed_responses = Arc::new(AtomicUsize::new(0));
1148                let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1149                    .with_custom_tcp_connector(())
1150                    .without_dns_connector()
1151                    .with_proxy_support(proxies)
1152                    .without_tls_support()
1153                    .with_custom_http_connector(InspectingConnector)
1154                    .without_connection_pool()
1155                    .build_client()
1156                    .with_jit_layer((
1157                        MapInputLayer::new(move |mut request: Request| {
1158                            request.extensions().insert(stale_route.clone());
1159                            let stale_egress = Extensions::new();
1160                            stale_egress.insert(stale_route.clone());
1161                            request.extensions().insert(Egress(stale_egress));
1162                            request.headers_mut().insert(
1163                                PROXY_AUTHORIZATION,
1164                                HeaderValue::from_static("Basic downstream-secret"),
1165                            );
1166                            request
1167                        }),
1168                        MapOutputLayer::new({
1169                            let observed_responses = observed_responses.clone();
1170                            move |response: Response| {
1171                                observed_responses.fetch_add(1, Ordering::Relaxed);
1172                                response
1173                            }
1174                        }),
1175                    ));
1176                let request = Request::builder()
1177                    .uri("http://origin.example/resource")
1178                    .body(Body::empty())
1179                    .unwrap();
1180                if is_forward {
1181                    request.extensions().insert(proxy.clone());
1182                }
1183                let result = client.serve(request).await;
1184                if isolate && is_forward {
1185                    assert!(result.is_err());
1186                    assert_eq!(observed_responses.load(Ordering::Relaxed), 0);
1187                } else {
1188                    assert_eq!(
1189                        result.unwrap().status(),
1190                        StatusCode::PROXY_AUTHENTICATION_REQUIRED
1191                    );
1192                    assert_eq!(observed_responses.load(Ordering::Relaxed), 1);
1193                }
1194            }
1195        }
1196    }
1197
1198    #[derive(Debug, Clone, ExtensionsRef)]
1199    struct RecordingConnection {
1200        extensions: Extensions,
1201        authority: HostWithPort,
1202        log: Arc<parking_lot::Mutex<Vec<(HostWithPort, String, Option<String>)>>>,
1203    }
1204
1205    impl<B: Send + 'static> Service<Request<B>> for RecordingConnection {
1206        type Output = Response;
1207        type Error = BoxError;
1208
1209        async fn serve(&self, request: Request<B>) -> Result<Self::Output, Self::Error> {
1210            use rama_http::{header::PROXY_AUTHORIZATION, proto::h1::head};
1211
1212            let mut target = Vec::new();
1213            head::encode_request_target(
1214                request.method(),
1215                request.uri(),
1216                request.extensions(),
1217                &mut target,
1218            )
1219            .unwrap();
1220            self.log.lock().push((
1221                self.authority.clone(),
1222                String::from_utf8(target).unwrap(),
1223                request
1224                    .headers()
1225                    .get(PROXY_AUTHORIZATION)
1226                    .map(|auth| auth.to_str().unwrap().to_owned()),
1227            ));
1228            Ok(Response::new(Body::empty()))
1229        }
1230    }
1231
1232    #[derive(Debug, Clone)]
1233    struct RecordingConnector {
1234        unavailable: Option<HostWithPort>,
1235        failures: Arc<AtomicUsize>,
1236        log: Arc<parking_lot::Mutex<Vec<(HostWithPort, String, Option<String>)>>>,
1237    }
1238
1239    impl RecordingConnector {
1240        fn new(
1241            unavailable: Option<HostWithPort>,
1242            log: &Arc<parking_lot::Mutex<Vec<(HostWithPort, String, Option<String>)>>>,
1243        ) -> Self {
1244            Self {
1245                unavailable,
1246                failures: Arc::new(AtomicUsize::new(0)),
1247                log: log.clone(),
1248            }
1249        }
1250    }
1251
1252    impl Service<ConnectRequest> for RecordingConnector {
1253        type Output = EstablishedClientConnection<RecordingConnection, ConnectRequest>;
1254        type Error = ConnectionError;
1255
1256        async fn serve(&self, input: ConnectRequest) -> Result<Self::Output, Self::Error> {
1257            // Only the first attempt of a route fails, so a plan can reach the same proxy
1258            // again with another credential.
1259            if self.unavailable.as_ref() == Some(&input.authority)
1260                && self.failures.fetch_add(1, Ordering::Relaxed) == 0
1261            {
1262                return Err(ConnectionError::transport(
1263                    BoxError::from_static_str("proxy unavailable"),
1264                    ConnectionErrorKind::Unavailable,
1265                ));
1266            }
1267            let conn = RecordingConnection {
1268                extensions: speaks_requested_version(&input),
1269                authority: input.authority.clone(),
1270                log: self.log.clone(),
1271            };
1272            Ok(EstablishedClientConnection { input, conn })
1273        }
1274    }
1275
1276    impl<S> Layer<S> for RecordingConnector {
1277        type Service = Self;
1278
1279        fn layer(&self, _: S) -> Self::Service {
1280            self.clone()
1281        }
1282    }
1283
1284    fn speaks_requested_version(input: &ConnectRequest) -> Extensions {
1285        let extensions = Extensions::new();
1286        if let Some(version) = input.extensions().get_ref::<TargetHttpVersion>() {
1287            extensions.insert(*version);
1288        }
1289        extensions
1290    }
1291
1292    fn recording_client(
1293        proxy_http: RecordingConnector,
1294        origin_http: RecordingConnector,
1295    ) -> impl Service<Request, Output = Response, Error = OpaqueError> {
1296        let proxies = ProxyConnector::builder(WeakScope::detached())
1297            .with_custom_tcp_connector(())
1298            .without_dns_connector()
1299            .without_tls_support()
1300            .with_custom_http_connector::<Body, _>(proxy_http)
1301            .without_connection_pool()
1302            .with_http_forward()
1303            .build();
1304        EasyHttpWebClient::connector_builder(WeakScope::detached())
1305            .with_custom_tcp_connector(())
1306            .without_dns_connector()
1307            .with_proxy_support(proxies)
1308            .without_tls_support()
1309            .with_custom_http_connector(origin_http)
1310            .without_proxy_route_failure_cache()
1311            .without_connection_pool()
1312            .build_client()
1313    }
1314
1315    #[tokio::test]
1316    async fn every_forward_attempt_of_a_plan_sends_the_credentials_of_its_own_proxy() {
1317        for second in [
1318            "http://b:sb@second.example:8080",
1319            "http://b:sb@first.example:8080",
1320        ] {
1321            let log = Arc::new(parking_lot::Mutex::new(Vec::new()));
1322            let client = recording_client(
1323                RecordingConnector::new(
1324                    Some(HostWithPort::try_from("first.example:8080").unwrap()),
1325                    &log,
1326                ),
1327                RecordingConnector::new(None, &log),
1328            );
1329            let request = Request::builder()
1330                .uri("http://origin.example/resource")
1331                .body(Body::empty())
1332                .unwrap();
1333            request.extensions().insert(ProxyRoutes::new([
1334                ProxyRoute::Proxy("http://a:sa@first.example:8080".parse().unwrap()),
1335                ProxyRoute::Proxy(second.parse().unwrap()),
1336            ]));
1337
1338            client.serve(request).await.unwrap();
1339
1340            let log = log.lock();
1341            assert_eq!(log.len(), 1, "{second}: only the reached proxy is served");
1342            let (authority, target, auth) = &log[0];
1343            assert_eq!(
1344                authority,
1345                &HostWithPort::try_from(second.rsplit('@').next().unwrap()).unwrap(),
1346            );
1347            assert_eq!(target, "http://origin.example/resource");
1348            assert_eq!(
1349                auth.as_deref(),
1350                Some("Basic YjpzYg=="),
1351                "{second}: the credentials of the proxy actually reached",
1352            );
1353        }
1354    }
1355
1356    #[tokio::test]
1357    async fn a_fallback_to_direct_carries_no_proxy_credentials() {
1358        use rama_http::header::PROXY_AUTHORIZATION;
1359
1360        let log = Arc::new(parking_lot::Mutex::new(Vec::new()));
1361        let client = recording_client(
1362            RecordingConnector::new(
1363                Some(HostWithPort::try_from("proxy.example:8080").unwrap()),
1364                &log,
1365            ),
1366            RecordingConnector::new(None, &log),
1367        );
1368        let request = Request::builder()
1369            .uri("http://origin.example/resource")
1370            .header(PROXY_AUTHORIZATION, "Basic ZG93bnN0cmVhbQ==")
1371            .body(Body::empty())
1372            .unwrap();
1373        request.extensions().insert(ProxyRoutes::new([
1374            ProxyRoute::Proxy("http://u:p@proxy.example:8080".parse().unwrap()),
1375            ProxyRoute::Direct,
1376        ]));
1377
1378        client.serve(request).await.unwrap();
1379
1380        let log = log.lock();
1381        assert_eq!(log.len(), 1);
1382        let (authority, target, auth) = &log[0];
1383        assert_eq!(
1384            authority,
1385            &HostWithPort::try_from("origin.example:80").unwrap()
1386        );
1387        assert_eq!(target, "/resource");
1388        assert_eq!(auth.as_deref(), None);
1389    }
1390
1391    #[derive(Debug, Clone)]
1392    struct TwoAddresses;
1393
1394    impl DnsAddressResolver for TwoAddresses {
1395        type Error = Infallible;
1396
1397        fn lookup_ipv4(
1398            &self,
1399            _: Domain,
1400        ) -> impl Stream<Item = Result<Ipv4Addr, Self::Error>> + Send + '_ {
1401            stream::iter([
1402                Ok(Ipv4Addr::new(10, 0, 0, 1)),
1403                Ok(Ipv4Addr::new(10, 0, 0, 2)),
1404            ])
1405        }
1406
1407        fn lookup_ipv6(
1408            &self,
1409            _: Domain,
1410        ) -> impl Stream<Item = Result<Ipv6Addr, Self::Error>> + Send + '_ {
1411            stream::empty()
1412        }
1413    }
1414
1415    fn round_robin() -> DnsLoadBalancerLayer<TwoAddresses, RoundRobinPicker> {
1416        DnsLoadBalancerLayer::new(DnsLoadBalancerConfig {
1417            mode: DnsResolveIpMode::SingleIpV4,
1418            ..DnsLoadBalancerConfig::from_parts(TwoAddresses, RoundRobinPicker::new())
1419        })
1420    }
1421
1422    async fn connections_for<S>(client: &S, proxy: Option<&str>) -> Vec<Output>
1423    where
1424        S: Service<Request, Output = Response, Error: Debug>,
1425    {
1426        let mut connections = Vec::new();
1427        for _ in 0..4 {
1428            let request = Request::builder()
1429                .uri("http://example.com/")
1430                .body(Body::empty())
1431                .unwrap();
1432            if let Some(proxy) = proxy {
1433                request
1434                    .extensions()
1435                    .insert(ProxyRoute::Proxy(proxy.parse().unwrap()));
1436            }
1437            let response = client.serve(request).await.unwrap();
1438            connections.push(response.try_into_json::<Output>().await.unwrap());
1439        }
1440        connections
1441    }
1442
1443    #[tokio::test]
1444    async fn a_load_balancer_above_the_pool_picks_a_pooled_connection_per_address() {
1445        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1446            .with_custom_tcp_connector(dummy_server())
1447            .without_dns_connector()
1448            .without_proxy_support()
1449            .without_tls_support()
1450            .with_default_http_connector()
1451            .with_default_connection_pool()
1452            .with_custom_connector(round_robin())
1453            .build_client();
1454
1455        assert_eq!(
1456            connections_for(&client, None).await,
1457            [
1458                Output {
1459                    conn: 0,
1460                    resp: 0,
1461                    target: "10.0.0.1:80".to_owned(),
1462                },
1463                Output {
1464                    conn: 1,
1465                    resp: 0,
1466                    target: "10.0.0.2:80".to_owned(),
1467                },
1468                Output {
1469                    conn: 0,
1470                    resp: 1,
1471                    target: "10.0.0.1:80".to_owned(),
1472                },
1473                Output {
1474                    conn: 1,
1475                    resp: 1,
1476                    target: "10.0.0.2:80".to_owned(),
1477                },
1478            ]
1479        );
1480    }
1481
1482    #[tokio::test]
1483    async fn a_load_balancer_above_the_proxy_pool_picks_a_pooled_connection_per_address() {
1484        let proxies = ProxyConnector::builder(WeakScope::detached())
1485            .with_custom_tcp_connector(dummy_server())
1486            .without_dns_connector()
1487            .without_tls_support()
1488            .with_default_http_connector::<Body>()
1489            .with_default_connection_pool()
1490            .with_custom_connector(round_robin())
1491            .with_http_forward()
1492            .build();
1493        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1494            .with_custom_tcp_connector(dummy_server())
1495            .without_dns_connector()
1496            .with_proxy_support(proxies)
1497            .without_tls_support()
1498            .with_default_http_connector()
1499            .without_connection_pool()
1500            .build_client();
1501
1502        assert_eq!(
1503            connections_for(&client, Some("http://proxy.example:8080")).await,
1504            [
1505                Output {
1506                    conn: 0,
1507                    resp: 0,
1508                    target: "10.0.0.1:8080".to_owned(),
1509                },
1510                Output {
1511                    conn: 1,
1512                    resp: 0,
1513                    target: "10.0.0.2:8080".to_owned(),
1514                },
1515                Output {
1516                    conn: 0,
1517                    resp: 1,
1518                    target: "10.0.0.1:8080".to_owned(),
1519                },
1520                Output {
1521                    conn: 1,
1522                    resp: 1,
1523                    target: "10.0.0.2:8080".to_owned(),
1524                },
1525            ]
1526        );
1527    }
1528
1529    #[tokio::test]
1530    async fn a_load_balancer_below_the_proxy_pool_does_not_split_its_connections() {
1531        let proxies = ProxyConnector::builder(WeakScope::detached())
1532            .with_custom_tcp_connector(dummy_server())
1533            .without_dns_connector()
1534            .without_tls_support()
1535            .with_default_http_connector::<Body>()
1536            .with_custom_connector(round_robin())
1537            .with_default_connection_pool()
1538            .with_http_forward()
1539            .build();
1540        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1541            .with_custom_tcp_connector(dummy_server())
1542            .without_dns_connector()
1543            .with_proxy_support(proxies)
1544            .without_tls_support()
1545            .with_default_http_connector()
1546            .without_connection_pool()
1547            .build_client();
1548
1549        assert_eq!(
1550            connections_for(&client, Some("http://proxy.example:8080")).await,
1551            [
1552                Output {
1553                    conn: 0,
1554                    resp: 0,
1555                    target: "10.0.0.1:8080".to_owned(),
1556                },
1557                Output {
1558                    conn: 0,
1559                    resp: 1,
1560                    target: "10.0.0.1:8080".to_owned(),
1561                },
1562                Output {
1563                    conn: 0,
1564                    resp: 2,
1565                    target: "10.0.0.1:8080".to_owned(),
1566                },
1567                Output {
1568                    conn: 0,
1569                    resp: 3,
1570                    target: "10.0.0.1:8080".to_owned(),
1571                },
1572            ]
1573        );
1574    }
1575
1576    #[test]
1577    fn blocking_client_drives_the_composed_http_stack() {
1578        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1579            .with_custom_tcp_connector(dummy_server())
1580            .without_dns_connector()
1581            .without_proxy_support()
1582            .without_tls_support()
1583            .with_default_http_connector()
1584            .without_connection_pool()
1585            .build_client()
1586            .try_into_blocking()
1587            .unwrap();
1588
1589        let cloned = client.clone();
1590        drop(client);
1591        let response = cloned.get("http://example.com").send().unwrap();
1592        assert_eq!(
1593            response.try_into_json::<Output>().unwrap(),
1594            Output {
1595                conn: 0,
1596                resp: 0,
1597                target: "example.com:80".to_owned(),
1598            }
1599        );
1600    }
1601
1602    #[test]
1603    fn default_blocking_http_client_is_cloneable_and_pooled() {
1604        fn assert_default_client(_: &DefaultHttpWebClient) {}
1605
1606        let client = EasyHttpWebClient::try_blocking().unwrap();
1607        assert_default_client(client.get_ref());
1608        let cloned = client.clone();
1609        drop(client);
1610        let request = cloned.get("https://example.com").build().unwrap();
1611        assert_eq!(request.uri(), &"https://example.com".parse().unwrap());
1612    }
1613
1614    #[cfg(feature = "ws")]
1615    #[test]
1616    fn default_blocking_http_client_builds_websocket_requests() {
1617        use crate::http::ws::handshake::client::BlockingHttpClientWebSocketExt as _;
1618
1619        let client = EasyHttpWebClient::try_blocking().unwrap();
1620        let _from_url = client
1621            .websocket("wss://example.com/chat")
1622            .with_header("authorization", "Bearer secret");
1623
1624        let request = Request::builder()
1625            .uri("wss://example.com/chat")
1626            .body(Body::empty())
1627            .unwrap();
1628        let _from_request = client.websocket_with_request(request);
1629    }
1630
1631    #[tokio::test]
1632    async fn no_pool_tries_proxy_routes_in_order() {
1633        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
1634        let transport = service_fn({
1635            let attempts = attempts.clone();
1636            let direct = dummy_server();
1637            move |input: ConnectRequest| {
1638                let attempts = attempts.clone();
1639                let direct = direct.clone();
1640                async move {
1641                    let dialed = input.authority.clone();
1642                    attempts.lock().push(dialed.clone());
1643                    if dialed == proxy_authority() {
1644                        Err(ConnectionError::transport(
1645                            BoxError::from_static_str("proxy unavailable"),
1646                            ConnectionErrorKind::Unavailable,
1647                        ))
1648                    } else {
1649                        direct.connect(input).await
1650                    }
1651                }
1652            }
1653        });
1654        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1655            .with_custom_tcp_connector(transport.clone())
1656            .without_dns_connector()
1657            .with_proxy_support(proxies_over(transport))
1658            .without_tls_support()
1659            .with_default_http_connector()
1660            .without_connection_pool()
1661            .build_client();
1662        let proxy = ProxyRoute::Proxy("http://proxy.example:8080".parse::<ProxyAddress>().unwrap());
1663        let request = || {
1664            let request = Request::builder()
1665                .uri("http://example.com")
1666                .body(Body::empty())
1667                .unwrap();
1668            request
1669                .extensions()
1670                .insert(ProxyRoutes::new([proxy.clone(), ProxyRoute::Direct]));
1671            request
1672        };
1673
1674        for _ in 0..2 {
1675            client
1676                .serve(request())
1677                .await
1678                .context("serve request through direct fallback")
1679                .unwrap();
1680        }
1681
1682        assert_eq!(
1683            attempts.lock().as_slice(),
1684            [proxy_authority(), origin_authority(), origin_authority()],
1685        );
1686    }
1687
1688    #[tokio::test]
1689    async fn no_proxy_tls_support_rejects_https_proxy() {
1690        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1691            .with_custom_tcp_connector(dummy_server())
1692            .without_dns_connector()
1693            .with_proxy_support(proxies_over(dummy_server()))
1694            .without_tls_support()
1695            .with_default_http_connector()
1696            .without_connection_pool()
1697            .build_client();
1698        let request = Request::builder()
1699            .uri("http://example.com")
1700            .body(Body::empty())
1701            .unwrap();
1702        request.extensions().insert(ProxyRoutes::new([
1703            ProxyRoute::Proxy(
1704                "https://proxy.example:8443"
1705                    .parse::<ProxyAddress>()
1706                    .unwrap(),
1707            ),
1708            ProxyRoute::Direct,
1709        ]));
1710
1711        let error =
1712            ConnectionError::from(client.serve(request).await.unwrap_err().into_box_error());
1713        assert_eq!(error.domain(), ConnectionErrorDomain::Transport);
1714        assert_eq!(error.kind(), ConnectionErrorKind::Protocol);
1715    }
1716
1717    #[tokio::test]
1718    async fn easy_client_pools_plaintext_proxy_versions_separately() {
1719        let proxy: ProxyAddress = "http://proxy.example:8080".parse().unwrap();
1720        let dials = Arc::new(AtomicUsize::new(0));
1721        let transport = service_fn({
1722            let inner = dummy_server();
1723            let proxy = proxy.clone();
1724            let dials = dials.clone();
1725            move |input: ConnectRequest| {
1726                let inner = inner.clone();
1727                let proxy = proxy.clone();
1728                let dials = dials.clone();
1729                async move {
1730                    assert_eq!(
1731                        input.extensions.get_ref::<ConnectorTarget>(),
1732                        Some(&ConnectorTarget(proxy.address.clone())),
1733                    );
1734                    assert_eq!(
1735                        input.extensions.get_ref::<ProxyRoute>(),
1736                        Some(&ProxyRoute::Direct),
1737                    );
1738                    dials.fetch_add(1, Ordering::Relaxed);
1739                    inner.connect(input).await
1740                }
1741            }
1742        });
1743        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1744            .with_custom_tcp_connector(transport.clone())
1745            .without_dns_connector()
1746            .with_proxy_support(proxies_over(transport))
1747            .without_tls_support()
1748            .with_default_http_connector()
1749            .with_default_connection_pool()
1750            .build_client();
1751
1752        for (version, expected_conn) in [(Version::HTTP_11, 0), (Version::HTTP_2, 1)] {
1753            let request = Request::builder()
1754                .uri("http://example.com")
1755                .version(version)
1756                .body(Body::empty())
1757                .unwrap();
1758            request.extensions().insert(ProxyRoutes::from(ProxyAddress {
1759                protocol: ProxyProtocol::Http {
1760                    version: Some(version),
1761                    secure: false,
1762                    path_template: None,
1763                },
1764                ..proxy.clone()
1765            }));
1766
1767            let response = client.serve(request).await.unwrap();
1768            assert_eq!(response.version(), version);
1769            assert_eq!(
1770                response.try_into_json::<Output>().await.unwrap(),
1771                Output {
1772                    conn: expected_conn,
1773                    resp: 0,
1774                    target: "proxy.example:8080".to_owned(),
1775                },
1776            );
1777        }
1778        assert_eq!(dials.load(Ordering::Relaxed), 2);
1779    }
1780
1781    #[cfg(feature = "socks5")]
1782    #[tokio::test]
1783    async fn umbrella_proxy_connector_falls_back_across_supported_plan() {
1784        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
1785        let transport = service_fn({
1786            let attempts = attempts.clone();
1787            let direct = dummy_server();
1788            move |input: ConnectRequest| {
1789                let attempts = attempts.clone();
1790                let direct = direct.clone();
1791                async move {
1792                    let dialed = input.authority.clone();
1793                    attempts.lock().push(dialed.clone());
1794                    if dialed == origin_authority() {
1795                        direct.connect(input).await
1796                    } else {
1797                        Err(ConnectionError::transport(
1798                            BoxError::from_static_str("proxy unavailable"),
1799                            ConnectionErrorKind::Unavailable,
1800                        ))
1801                    }
1802                }
1803            }
1804        });
1805        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1806            .with_custom_tcp_connector(transport.clone())
1807            .without_dns_connector()
1808            .with_proxy_support(proxies_over(transport))
1809            .without_tls_support()
1810            .with_default_http_connector()
1811            .without_connection_pool()
1812            .build_client();
1813        let request = Request::builder()
1814            .uri("http://example.com")
1815            .body(Body::empty())
1816            .unwrap();
1817        let socks = ProxyRoute::Proxy(
1818            "socks5://socks.example:1080"
1819                .parse::<ProxyAddress>()
1820                .unwrap(),
1821        );
1822        let http = ProxyRoute::Proxy("http://http.example:8080".parse::<ProxyAddress>().unwrap());
1823        request.extensions().insert(ProxyRoutes::new([
1824            socks.clone(),
1825            http.clone(),
1826            ProxyRoute::Direct,
1827        ]));
1828
1829        let response = client.serve(request).await.unwrap();
1830        let output = response.try_into_json::<Output>().await.unwrap();
1831        assert_eq!(
1832            output,
1833            Output {
1834                conn: 0,
1835                resp: 0,
1836                target: "example.com:80".to_owned(),
1837            }
1838        );
1839        assert_eq!(
1840            attempts.lock().as_slice(),
1841            [
1842                HostWithPort::try_from("socks.example:1080").unwrap(),
1843                HostWithPort::try_from("http.example:8080").unwrap(),
1844                origin_authority(),
1845            ],
1846        );
1847    }
1848
1849    #[cfg(feature = "socks5")]
1850    #[tokio::test]
1851    async fn a_stream_layer_before_the_http_stage_reaches_every_proxy_method() {
1852        let socks_proxy = HostWithPort::try_from("socks.example:1080").unwrap();
1853        let transport = service_fn({
1854            let server = dummy_server();
1855            let socks_proxy = socks_proxy.clone();
1856            move |input: ConnectRequest| {
1857                let server = server.clone();
1858                let refused = input.authority == socks_proxy;
1859                async move {
1860                    if refused {
1861                        Err(ConnectionError::transport(
1862                            BoxError::from_static_str("proxy unavailable"),
1863                            ConnectionErrorKind::Unavailable,
1864                        ))
1865                    } else {
1866                        server.connect(input).await
1867                    }
1868                }
1869            }
1870        });
1871        let dials = Arc::new(parking_lot::Mutex::new(Vec::new()));
1872        let proxies = ProxyConnector::builder(WeakScope::detached())
1873            .with_custom_tcp_connector(transport.clone())
1874            .without_dns_connector()
1875            .with_custom_connector(MapInputLayer::new({
1876                let dials = dials.clone();
1877                move |input: ConnectRequest| {
1878                    dials.lock().push(input.authority.clone());
1879                    input
1880                }
1881            }))
1882            .without_tls_support()
1883            .with_default_http_connector::<Body>()
1884            .without_connection_pool()
1885            .with_socks5()
1886            .with_http_forward()
1887            .build();
1888        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1889            .with_custom_tcp_connector(transport)
1890            .without_dns_connector()
1891            .with_proxy_support(proxies)
1892            .without_tls_support()
1893            .with_default_http_connector()
1894            .without_connection_pool()
1895            .build_client();
1896        let request_over = |proxy: &str| {
1897            let request = Request::builder()
1898                .uri("http://example.com/")
1899                .body(Body::empty())
1900                .unwrap();
1901            request
1902                .extensions()
1903                .insert(ProxyRoute::Proxy(proxy.parse().unwrap()));
1904            request
1905        };
1906
1907        client
1908            .serve(request_over("http://proxy.example:8080"))
1909            .await
1910            .unwrap();
1911        assert_eq!(dials.lock().as_slice(), [proxy_authority()]);
1912
1913        // The refused dial still passed through the layer on the SOCKS5 leg.
1914        client
1915            .serve(request_over("socks5://socks.example:1080"))
1916            .await
1917            .unwrap_err();
1918        assert_eq!(dials.lock().as_slice(), [proxy_authority(), socks_proxy]);
1919    }
1920
1921    #[tokio::test]
1922    async fn default_pool_caches_failed_route_and_reuses_selected_connection() {
1923        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
1924        let transport = service_fn({
1925            let attempts = attempts.clone();
1926            let direct = dummy_server();
1927            move |input: ConnectRequest| {
1928                let attempts = attempts.clone();
1929                let direct = direct.clone();
1930                async move {
1931                    let dialed = input.authority.clone();
1932                    attempts.lock().push(dialed.clone());
1933                    if dialed == proxy_authority() {
1934                        Err(ConnectionError::transport(
1935                            BoxError::from_static_str("proxy unavailable"),
1936                            ConnectionErrorKind::Unavailable,
1937                        ))
1938                    } else {
1939                        direct.connect(input).await
1940                    }
1941                }
1942            }
1943        });
1944        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
1945            .with_custom_tcp_connector(transport.clone())
1946            .without_dns_connector()
1947            .with_proxy_support(proxies_over(transport))
1948            .without_tls_support()
1949            .with_default_http_connector()
1950            .with_default_connection_pool()
1951            .build_client();
1952        let proxy = ProxyRoute::Proxy("http://proxy.example:8080".parse::<ProxyAddress>().unwrap());
1953        let request = || {
1954            let request = Request::builder()
1955                .uri("http://example.com")
1956                .body(Body::empty())
1957                .unwrap();
1958            request
1959                .extensions()
1960                .insert(ProxyRoutes::new([proxy.clone(), ProxyRoute::Direct]));
1961            request
1962        };
1963
1964        for expected_response_index in 0..2 {
1965            let response = client.serve(request()).await.unwrap();
1966            let output = response.try_into_json::<Output>().await.unwrap();
1967            assert_eq!(output.conn, 0);
1968            assert_eq!(output.resp, expected_response_index);
1969        }
1970
1971        assert_eq!(
1972            attempts.lock().as_slice(),
1973            [proxy_authority(), origin_authority()],
1974        );
1975    }
1976
1977    #[tokio::test]
1978    async fn easy_client_can_disable_proxy_route_failure_cache() {
1979        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
1980        let transport = service_fn({
1981            let attempts = attempts.clone();
1982            let direct = dummy_server();
1983            move |input: ConnectRequest| {
1984                let attempts = attempts.clone();
1985                let direct = direct.clone();
1986                async move {
1987                    let dialed = input.authority.clone();
1988                    attempts.lock().push(dialed.clone());
1989                    if dialed == proxy_authority() {
1990                        Err(ConnectionError::transport(
1991                            BoxError::from_static_str("proxy unavailable"),
1992                            ConnectionErrorKind::Unavailable,
1993                        ))
1994                    } else {
1995                        direct.connect(input).await
1996                    }
1997                }
1998            }
1999        });
2000        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
2001            .with_custom_tcp_connector(transport.clone())
2002            .without_dns_connector()
2003            .with_proxy_support(proxies_over(transport))
2004            .without_tls_support()
2005            .with_default_http_connector()
2006            .without_proxy_route_failure_cache()
2007            .without_connection_pool()
2008            .build_client();
2009        let proxy = ProxyRoute::Proxy("http://proxy.example:8080".parse().unwrap());
2010
2011        for _ in 0..2 {
2012            let request = Request::builder()
2013                .uri("http://example.com")
2014                .body(Body::empty())
2015                .unwrap();
2016            request
2017                .extensions()
2018                .insert(ProxyRoutes::new([proxy.clone(), ProxyRoute::Direct]));
2019            client.serve(request).await.unwrap();
2020        }
2021
2022        assert_eq!(
2023            attempts.lock().as_slice(),
2024            [
2025                proxy_authority(),
2026                origin_authority(),
2027                proxy_authority(),
2028                origin_authority(),
2029            ],
2030        );
2031    }
2032
2033    #[tokio::test]
2034    async fn a_proxy_free_client_does_not_fall_back_from_a_refused_proxy_route() {
2035        let attempts = Arc::new(parking_lot::Mutex::new(0usize));
2036        let transport = service_fn({
2037            let attempts = attempts.clone();
2038            let direct = dummy_server();
2039            move |input: ConnectRequest| {
2040                let attempts = attempts.clone();
2041                let direct = direct.clone();
2042                async move {
2043                    *attempts.lock() += 1;
2044                    direct.connect(input).await
2045                }
2046            }
2047        });
2048        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
2049            .with_custom_tcp_connector(transport)
2050            .without_dns_connector()
2051            .without_proxy_support()
2052            .without_tls_support()
2053            .with_default_http_connector()
2054            .without_connection_pool()
2055            .build_client();
2056        let request = Request::builder()
2057            .uri("http://example.com")
2058            .body(Body::empty())
2059            .unwrap();
2060        request.extensions().insert(ProxyRoutes::new([
2061            ProxyRoute::Proxy("http://proxy.example:8080".parse().unwrap()),
2062            ProxyRoute::Direct,
2063        ]));
2064
2065        client.serve(request).await.expect_err(
2066            "a refused proxy route is a configuration error, not a reason to go direct",
2067        );
2068        assert_eq!(*attempts.lock(), 0);
2069    }
2070
2071    #[tokio::test]
2072    async fn forwarded_requests_reuse_the_connection_to_their_proxy() {
2073        let proxy_dials = Arc::new(AtomicUsize::new(0));
2074        let transport = service_fn({
2075            let proxy_dials = proxy_dials.clone();
2076            let server = dummy_server();
2077            move |input: ConnectRequest| {
2078                if input.authority.host == "proxy.example" {
2079                    proxy_dials.fetch_add(1, Ordering::Relaxed);
2080                }
2081                let server = server.clone();
2082                async move { server.connect(input).await }
2083            }
2084        });
2085        let proxies = ProxyConnector::builder(WeakScope::detached())
2086            .with_custom_tcp_connector(transport.clone())
2087            .without_dns_connector()
2088            .without_tls_support()
2089            .with_default_http_connector()
2090            .with_default_connection_pool()
2091            .with_http_forward()
2092            .build();
2093        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
2094            .with_custom_tcp_connector(transport)
2095            .without_dns_connector()
2096            .with_proxy_support(proxies)
2097            .without_tls_support()
2098            .with_default_http_connector()
2099            .with_default_connection_pool()
2100            .build_client();
2101
2102        for path in ["/first", "/second"] {
2103            let request = Request::builder()
2104                .uri(format!("http://example.com{path}"))
2105                .version(Version::HTTP_11)
2106                .body(Body::empty())
2107                .unwrap();
2108            request.extensions().insert(ProxyRoute::Proxy(
2109                "http://proxy.example:8080".parse().unwrap(),
2110            ));
2111            client
2112                .serve(request)
2113                .await
2114                .expect("every forwarded request is served")
2115                .try_into_string()
2116                .await
2117                .expect("the response body reaches its end");
2118        }
2119
2120        assert_eq!(proxy_dials.load(Ordering::Relaxed), 1);
2121    }
2122
2123    #[tokio::test]
2124    async fn a_proxy_free_client_refuses_a_tunneled_route() {
2125        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
2126            .with_custom_tcp_connector(dummy_server())
2127            .without_dns_connector()
2128            .without_proxy_support()
2129            .without_tls_support()
2130            .with_default_http_connector()
2131            .without_connection_pool()
2132            .build_client();
2133        let request = Request::builder()
2134            .uri("http://example.com")
2135            .body(Body::empty())
2136            .unwrap();
2137        request.extensions().insert(ProxyRoute::Proxy(
2138            "socks5://proxy.example:1080".parse().unwrap(),
2139        ));
2140
2141        let error = client.serve(request).await.unwrap_err();
2142
2143        assert!(
2144            error
2145                .to_string()
2146                .contains("proxy route on a client without proxy support"),
2147            "a client without proxy support must refuse the route, not connect around it: {error}"
2148        );
2149    }
2150
2151    #[tokio::test]
2152    async fn a_proxy_free_client_refuses_a_forwarded_route() {
2153        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
2154            .with_custom_tcp_connector(dummy_server())
2155            .without_dns_connector()
2156            .without_proxy_support()
2157            .without_tls_support()
2158            .with_default_http_connector()
2159            .without_connection_pool()
2160            .build_client();
2161        let request = Request::builder()
2162            .uri("http://example.com")
2163            .body(Body::empty())
2164            .unwrap();
2165        request.extensions().insert(ProxyRoute::Proxy(
2166            "http://proxy.example:8080".parse().unwrap(),
2167        ));
2168
2169        let error = client.serve(request).await.unwrap_err();
2170
2171        assert!(
2172            error
2173                .to_string()
2174                .contains("http forward proxying is not enabled"),
2175            "a client without proxy support must refuse the route, not serve it another way: {error}"
2176        );
2177    }
2178
2179    #[tokio::test]
2180    async fn easy_client_accepts_custom_proxy_route_failure_cache() {
2181        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
2182        let transport = service_fn({
2183            let attempts = attempts.clone();
2184            let direct = dummy_server();
2185            move |input: ConnectRequest| {
2186                let attempts = attempts.clone();
2187                let direct = direct.clone();
2188                async move {
2189                    if input.authority.host == "proxy.example" {
2190                        attempts.lock().push("proxy");
2191                        Err(ConnectionError::transport(
2192                            BoxError::from_static_str("proxy unavailable"),
2193                            ConnectionErrorKind::Unavailable,
2194                        ))
2195                    } else {
2196                        attempts.lock().push("direct");
2197                        direct.connect(input).await
2198                    }
2199                }
2200            }
2201        });
2202        let proxies = ProxyConnector::builder(WeakScope::detached())
2203            .with_custom_tcp_connector(transport.clone())
2204            .without_dns_connector()
2205            .without_tls_support()
2206            .with_default_http_connector()
2207            .without_connection_pool()
2208            .with_http_forward()
2209            .build();
2210        let mut failure_cache_config = ProxyRouteFailureCacheConfig::default();
2211        failure_cache_config.scope = ProxyRouteFailureCacheScope::PerProxy;
2212        let failure_cache = ProxyRouteFailureCache::try_new(failure_cache_config).unwrap();
2213        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
2214            .with_custom_tcp_connector(transport)
2215            .without_dns_connector()
2216            .with_proxy_support(proxies)
2217            .without_tls_support()
2218            .with_default_http_connector()
2219            .with_proxy_route_failure_cache(failure_cache)
2220            .without_connection_pool()
2221            .build_client();
2222        let proxy = ProxyRoute::Proxy("http://proxy.example:8080".parse().unwrap());
2223
2224        for destination in ["one.example", "two.example"] {
2225            let request = Request::builder()
2226                .uri(format!("http://{destination}"))
2227                .body(Body::empty())
2228                .unwrap();
2229            request
2230                .extensions()
2231                .insert(ProxyRoutes::new([proxy.clone(), ProxyRoute::Direct]));
2232            client.serve(request).await.unwrap();
2233        }
2234
2235        assert_eq!(attempts.lock().as_slice(), ["proxy", "direct", "direct"]);
2236    }
2237
2238    #[cfg(all(feature = "rustls", any(feature = "aws-lc", feature = "ring")))]
2239    #[tokio::test]
2240    async fn rustls_https_proxy_alpn_is_scoped_across_connect() {
2241        use crate::{
2242            extensions::ExtensionsRef as _,
2243            net::{
2244                Protocol,
2245                address::HostWithPort,
2246                client::{EstablishedClientConnection, ProxyRoute},
2247                stream::service::EchoService,
2248                tls::{ApplicationProtocol, ServerName, TlsAlpn},
2249            },
2250            tls::{
2251                SecureTransport,
2252                client::{
2253                    NegotiatedTlsParameters, ServerVerifyMode, TlsClientConfig, TlsServerVerify,
2254                },
2255                rustls::{client::TlsConnector, server::TlsAcceptorLayer},
2256                server::{GeneratedServerAuthConfig, ServerAuthData, TlsServerConfig},
2257            },
2258        };
2259        use rama_core::ServiceInput;
2260        use rama_crypto::cert::generate_server_auth;
2261        use rama_http::io::upgrade::handle_upgrade;
2262        use rama_http_backend::client::proxy::layer::HttpConnectProxyConnectorLayer;
2263        use rama_net::http::TargetHttpVersion;
2264        use std::sync::Arc;
2265
2266        let (proxy_chain, proxy_key) =
2267            generate_server_auth(GeneratedServerAuthConfig::default()).expect("proxy auth");
2268        let proxy_trust = proxy_chain.last().expect("proxy trust anchor").clone();
2269        let (origin_chain, origin_key) =
2270            generate_server_auth(GeneratedServerAuthConfig::default()).expect("origin auth");
2271        let origin_trust = origin_chain.last().expect("origin trust anchor").clone();
2272
2273        let origin_server = TlsAcceptorLayer::new(
2274            TlsServerConfig::new()
2275                .with_single_cert(ServerAuthData {
2276                    cert_chain: origin_chain,
2277                    private_key: origin_key,
2278                    ocsp: None,
2279                })
2280                .with_alpn_http_1(),
2281        )
2282        .into_layer(EchoService::new());
2283        let (origin_done_tx, origin_done_rx) = tokio::sync::oneshot::channel();
2284        let origin_done_tx = Arc::new(parking_lot::Mutex::new(Some(origin_done_tx)));
2285
2286        let connect_version = Arc::new(parking_lot::Mutex::new(None));
2287        let observed_version = connect_version.clone();
2288        let proxy_sni = Arc::new(parking_lot::Mutex::new(None));
2289        let observed_sni = proxy_sni.clone();
2290        let proxy_http =
2291            HttpServer::auto(WeakScope::detached()).service(service_fn(move |req: Request| {
2292                let origin_server = origin_server.clone();
2293                let origin_done_tx = origin_done_tx.clone();
2294                let observed_version = observed_version.clone();
2295                let observed_sni = observed_sni.clone();
2296                async move {
2297                    assert_eq!(req.method(), rama_http::Method::CONNECT);
2298                    *observed_version.lock() = Some(req.version());
2299                    *observed_sni.lock() = req
2300                        .extensions()
2301                        .get_ref::<SecureTransport>()
2302                        .and_then(SecureTransport::client_hello)
2303                        .and_then(|hello| hello.ext_server_name().cloned());
2304                    let upgrade = handle_upgrade(&req);
2305                    tokio::spawn(async move {
2306                        let tunnel = upgrade.await.expect("server CONNECT upgrade");
2307                        // The client deliberately drops immediately after the
2308                        // handshake assertions, so the TLS server may finish
2309                        // with an EOF/close-notify error.
2310                        let _origin_result = origin_server.serve(tunnel).await;
2311                        if let Some(tx) = origin_done_tx.lock().take() {
2312                            tx.send(()).expect("origin completion receiver");
2313                        }
2314                    });
2315                    Ok::<_, Infallible>(Response::new(Body::empty()))
2316                }
2317            }));
2318        let proxy_server = TlsAcceptorLayer::new(
2319            TlsServerConfig::new()
2320                .with_single_cert(ServerAuthData {
2321                    cert_chain: proxy_chain,
2322                    private_key: proxy_key,
2323                    ocsp: None,
2324                })
2325                .with_alpn_http_2(),
2326        )
2327        .with_store_client_hello(true)
2328        .into_layer(proxy_http);
2329
2330        let (client_io, server_io) = tokio::io::duplex(64 * 1024);
2331        let client_io = Arc::new(parking_lot::Mutex::new(Some(client_io)));
2332        let transport = service_fn(move |input: ConnectRequest| {
2333            let conn = ServiceInput::new(client_io.lock().take().expect("one proxy connection"));
2334            async move { Ok::<_, ConnectionError>(EstablishedClientConnection { input, conn }) }
2335        });
2336
2337        let proxy_config = TlsClientConfig::new()
2338            .with_alpn_http_2()
2339            .with_server_name(crate::net::address::Domain::tld_localhost())
2340            .try_with_server_trust_anchors([proxy_trust])
2341            .expect("proxy trust");
2342        let proxy_tls = TlsConnector::auto(transport).with_base_config(proxy_config);
2343        let proxy_connections =
2344            HttpConnector::<_, ProxyRequestBody<Body>>::new(proxy_tls, WeakScope::detached());
2345        let proxy = HttpConnectProxyConnectorLayer::new().into_layer(proxy_connections);
2346        let origin_config = TlsClientConfig::new()
2347            .with_alpn(Default::default())
2348            .with_server_name(crate::net::address::Domain::tld_localhost())
2349            .try_with_server_trust_anchors([origin_trust])
2350            .expect("origin trust");
2351        let connector = TlsConnector::auto(proxy).with_base_config(origin_config);
2352
2353        let input = ConnectRequest::new(HostWithPort::try_from("localhost:443").unwrap())
2354            .with_application_protocol(Protocol::HTTPS);
2355        input.extensions.insert(ProxyRoute::Proxy(
2356            "h2://localhost:8443".parse::<ProxyAddress>().unwrap(),
2357        ));
2358        // Origin TLS inputs: they configure the origin handshake over the
2359        // tunnel and must not reach the handshake with the proxy.
2360        input.extensions.insert(TlsAlpn::http_1());
2361        input
2362            .extensions
2363            .insert(TlsServerVerify(ServerVerifyMode::Disable));
2364        input
2365            .extensions
2366            .insert(ServerName::from(crate::net::address::Domain::from_static(
2367                "elsewhere.example",
2368            )));
2369        let client = async move {
2370            let established = Box::pin(connector.serve(input))
2371                .await
2372                .expect("two TLS handshakes");
2373
2374            assert_eq!(
2375                *connect_version.lock(),
2376                Some(Version::HTTP_2),
2377                "the connection to the proxy offers its own ALPN, never the origin's"
2378            );
2379            assert_eq!(
2380                proxy_sni
2381                    .lock()
2382                    .as_ref()
2383                    .map(ToString::to_string)
2384                    .as_deref(),
2385                Some("localhost"),
2386                "the connection to the proxy names the proxy, never the origin's server name"
2387            );
2388            let conn = established.conn.extensions();
2389            assert_eq!(
2390                conn.get_ref::<NegotiatedTlsParameters>()
2391                    .expect("origin TLS parameters")
2392                    .application_layer_protocol,
2393                Some(ApplicationProtocol::HTTP_11),
2394                "the origin handshake over the tunnel offers the request's ALPN"
2395            );
2396            assert_eq!(
2397                conn.get_ref::<TargetHttpVersion>().map(|version| version.0),
2398                Some(Version::HTTP_11),
2399                "proxy HTTP/2 must not leak past CONNECT into the origin"
2400            );
2401            assert_tunnel_serves_the_same_proxy(
2402                conn,
2403                established
2404                    .input
2405                    .extensions
2406                    .get_ref::<ProxyRoute>()
2407                    .unwrap(),
2408            );
2409            drop(established);
2410        };
2411        let (proxy_result, ()) =
2412            Box::pin(tokio::time::timeout(Duration::from_secs(5), async move {
2413                tokio::join!(proxy_server.serve(ServiceInput::new(server_io)), client)
2414            }))
2415            .await
2416            .expect("proxy/origin exchange");
2417        proxy_result.expect("proxy server");
2418        tokio::time::timeout(Duration::from_secs(5), origin_done_rx)
2419            .await
2420            .expect("origin server shutdown")
2421            .expect("origin completion signal");
2422    }
2423
2424    #[cfg(all(feature = "rustls", any(feature = "aws-lc", feature = "ring")))]
2425    #[tokio::test]
2426    async fn rustls_proxy_alpn_never_reaches_a_no_alpn_origin() {
2427        use crate::{
2428            extensions::ExtensionsRef as _,
2429            net::{
2430                Protocol,
2431                address::HostWithPort,
2432                client::{EstablishedClientConnection, ProxyRoute},
2433                stream::service::EchoService,
2434                tls::ServerName,
2435            },
2436            tls::{
2437                SecureTransport,
2438                client::{
2439                    NegotiatedTlsParameters, ServerVerifyMode, TlsClientConfig, TlsServerVerify,
2440                },
2441                rustls::{client::TlsConnector, server::TlsAcceptorLayer},
2442                server::{GeneratedServerAuthConfig, ServerAuthData, TlsServerConfig},
2443            },
2444        };
2445        use rama_core::ServiceInput;
2446        use rama_crypto::cert::generate_server_auth;
2447        use rama_http::io::upgrade::handle_upgrade;
2448        use rama_http_backend::client::proxy::layer::HttpConnectProxyConnectorLayer;
2449        use rama_net::http::TargetHttpVersion;
2450        use std::sync::Arc;
2451
2452        let (proxy_chain, proxy_key) =
2453            generate_server_auth(GeneratedServerAuthConfig::default()).expect("proxy auth");
2454        let proxy_trust = proxy_chain.last().expect("proxy trust anchor").clone();
2455        let (origin_chain, origin_key) =
2456            generate_server_auth(GeneratedServerAuthConfig::default()).expect("origin auth");
2457        let origin_trust = origin_chain.last().expect("origin trust anchor").clone();
2458
2459        let origin_server =
2460            TlsAcceptorLayer::new(TlsServerConfig::new().with_single_cert(ServerAuthData {
2461                cert_chain: origin_chain,
2462                private_key: origin_key,
2463                ocsp: None,
2464            }))
2465            .into_layer(EchoService::new());
2466        let (origin_done_tx, origin_done_rx) = tokio::sync::oneshot::channel();
2467        let origin_done_tx = Arc::new(parking_lot::Mutex::new(Some(origin_done_tx)));
2468
2469        let connect_version = Arc::new(parking_lot::Mutex::new(None));
2470        let observed_version = connect_version.clone();
2471        let proxy_sni = Arc::new(parking_lot::Mutex::new(None));
2472        let observed_sni = proxy_sni.clone();
2473        let proxy_http =
2474            HttpServer::auto(WeakScope::detached()).service(service_fn(move |req: Request| {
2475                let origin_server = origin_server.clone();
2476                let origin_done_tx = origin_done_tx.clone();
2477                let observed_version = observed_version.clone();
2478                let observed_sni = observed_sni.clone();
2479                async move {
2480                    assert_eq!(req.method(), rama_http::Method::CONNECT);
2481                    *observed_version.lock() = Some(req.version());
2482                    *observed_sni.lock() = req
2483                        .extensions()
2484                        .get_ref::<SecureTransport>()
2485                        .and_then(SecureTransport::client_hello)
2486                        .and_then(|hello| hello.ext_server_name().cloned());
2487                    let upgrade = handle_upgrade(&req);
2488                    tokio::spawn(async move {
2489                        let tunnel = upgrade.await.expect("server CONNECT upgrade");
2490                        // The client deliberately drops immediately after the
2491                        // handshake assertions, so the TLS server may finish
2492                        // with an EOF/close-notify error.
2493                        let _origin_result = origin_server.serve(tunnel).await;
2494                        if let Some(tx) = origin_done_tx.lock().take() {
2495                            tx.send(()).expect("origin completion receiver");
2496                        }
2497                    });
2498                    Ok::<_, Infallible>(Response::new(Body::empty()))
2499                }
2500            }));
2501        let proxy_server = TlsAcceptorLayer::new(
2502            TlsServerConfig::new()
2503                .with_single_cert(ServerAuthData {
2504                    cert_chain: proxy_chain,
2505                    private_key: proxy_key,
2506                    ocsp: None,
2507                })
2508                .with_alpn_http_2(),
2509        )
2510        .with_store_client_hello(true)
2511        .into_layer(proxy_http);
2512
2513        let (client_io, server_io) = tokio::io::duplex(64 * 1024);
2514        let client_io = Arc::new(parking_lot::Mutex::new(Some(client_io)));
2515        let transport = service_fn(move |input: ConnectRequest| {
2516            let conn = ServiceInput::new(client_io.lock().take().expect("one proxy connection"));
2517            async move { Ok::<_, ConnectionError>(EstablishedClientConnection { input, conn }) }
2518        });
2519
2520        let proxy_config = TlsClientConfig::new()
2521            .with_alpn_http_2()
2522            .with_server_name(crate::net::address::Domain::from_static("localhost"))
2523            .try_with_server_trust_anchors([proxy_trust])
2524            .expect("proxy trust");
2525        let proxy_tls = TlsConnector::auto(transport).with_base_config(proxy_config);
2526        let proxy_connections =
2527            HttpConnector::<_, ProxyRequestBody<Body>>::new(proxy_tls, WeakScope::detached());
2528        let proxy = HttpConnectProxyConnectorLayer::new().into_layer(proxy_connections);
2529        let origin_config = TlsClientConfig::new()
2530            .with_alpn(Default::default())
2531            .with_server_name(crate::net::address::Domain::from_static("localhost"))
2532            .try_with_server_trust_anchors([origin_trust])
2533            .expect("origin trust");
2534        let connector = TlsConnector::auto(proxy).with_base_config(origin_config);
2535
2536        let input = ConnectRequest::new(HostWithPort::try_from("localhost:443").unwrap())
2537            .with_application_protocol(Protocol::HTTPS);
2538        input.extensions.insert(ProxyRoute::Proxy(
2539            "h2://localhost:8443".parse::<ProxyAddress>().unwrap(),
2540        ));
2541        // Origin TLS inputs: they configure the origin handshake over the
2542        // tunnel and must not reach the handshake with the proxy.
2543        input
2544            .extensions
2545            .insert(TlsServerVerify(ServerVerifyMode::Disable));
2546        input
2547            .extensions
2548            .insert(ServerName::from(crate::net::address::Domain::from_static(
2549                "elsewhere.example",
2550            )));
2551        let client = async move {
2552            let established = Box::pin(connector.serve(input))
2553                .await
2554                .expect("two TLS handshakes");
2555
2556            assert_eq!(
2557                *connect_version.lock(),
2558                Some(Version::HTTP_2),
2559                "the connection to the proxy offers its own ALPN, never the origin's"
2560            );
2561            assert_eq!(
2562                proxy_sni
2563                    .lock()
2564                    .as_ref()
2565                    .map(ToString::to_string)
2566                    .as_deref(),
2567                Some("localhost"),
2568                "the connection to the proxy names the proxy, never the origin's server name"
2569            );
2570            let conn = established.conn.extensions();
2571            assert_eq!(
2572                conn.get_ref::<NegotiatedTlsParameters>()
2573                    .expect("origin TLS parameters")
2574                    .application_layer_protocol,
2575                None,
2576                "an origin without an ALPN offer negotiates none"
2577            );
2578            assert!(
2579                conn.get_ref::<TargetHttpVersion>().is_none(),
2580                "proxy HTTP/2 must not leak past CONNECT into a no-ALPN origin"
2581            );
2582            assert_tunnel_serves_the_same_proxy(
2583                conn,
2584                established
2585                    .input
2586                    .extensions
2587                    .get_ref::<ProxyRoute>()
2588                    .unwrap(),
2589            );
2590            drop(established);
2591        };
2592        let (proxy_result, ()) =
2593            Box::pin(tokio::time::timeout(Duration::from_secs(5), async move {
2594                tokio::join!(proxy_server.serve(ServiceInput::new(server_io)), client)
2595            }))
2596            .await
2597            .expect("proxy/origin exchange");
2598        proxy_result.expect("proxy server");
2599        tokio::time::timeout(Duration::from_secs(5), origin_done_rx)
2600            .await
2601            .expect("origin server shutdown")
2602            .expect("origin completion signal");
2603    }
2604
2605    #[cfg(feature = "boring")]
2606    #[tokio::test]
2607    async fn boring_https_proxy_alpn_is_scoped_across_connect() {
2608        use crate::{
2609            extensions::ExtensionsRef as _,
2610            net::{
2611                Protocol,
2612                address::HostWithPort,
2613                client::{EstablishedClientConnection, ProxyRoute},
2614                stream::service::EchoService,
2615                tls::{ApplicationProtocol, ServerName, TlsAlpn},
2616            },
2617            tls::{
2618                SecureTransport,
2619                boring::{client::TlsConnector, server::TlsAcceptorLayer},
2620                client::{
2621                    NegotiatedTlsParameters, ServerVerifyMode, TlsClientConfig, TlsServerVerify,
2622                },
2623                server::{GeneratedServerAuthConfig, ServerAuthData, TlsServerConfig},
2624            },
2625        };
2626        use rama_core::ServiceInput;
2627        use rama_crypto::cert::generate_server_auth;
2628        use rama_http::io::upgrade::handle_upgrade;
2629        use rama_http_backend::client::proxy::layer::HttpConnectProxyConnectorLayer;
2630        use rama_net::http::TargetHttpVersion;
2631        use std::sync::Arc;
2632
2633        let (proxy_chain, proxy_key) =
2634            generate_server_auth(GeneratedServerAuthConfig::default()).expect("proxy auth");
2635        let proxy_trust = proxy_chain.last().expect("proxy trust anchor").clone();
2636        let (origin_chain, origin_key) =
2637            generate_server_auth(GeneratedServerAuthConfig::default()).expect("origin auth");
2638        let origin_trust = origin_chain.last().expect("origin trust anchor").clone();
2639
2640        let origin_server = TlsAcceptorLayer::new(
2641            TlsServerConfig::new()
2642                .with_single_cert(ServerAuthData {
2643                    cert_chain: origin_chain,
2644                    private_key: origin_key,
2645                    ocsp: None,
2646                })
2647                .with_alpn_http_1(),
2648        )
2649        .into_layer(EchoService::new());
2650        let (origin_done_tx, origin_done_rx) = tokio::sync::oneshot::channel();
2651        let origin_done_tx = Arc::new(parking_lot::Mutex::new(Some(origin_done_tx)));
2652
2653        let connect_version = Arc::new(parking_lot::Mutex::new(None));
2654        let observed_version = connect_version.clone();
2655        let proxy_sni = Arc::new(parking_lot::Mutex::new(None));
2656        let observed_sni = proxy_sni.clone();
2657        let proxy_http =
2658            HttpServer::auto(WeakScope::detached()).service(service_fn(move |req: Request| {
2659                let origin_server = origin_server.clone();
2660                let origin_done_tx = origin_done_tx.clone();
2661                let observed_version = observed_version.clone();
2662                let observed_sni = observed_sni.clone();
2663                async move {
2664                    assert_eq!(req.method(), rama_http::Method::CONNECT);
2665                    *observed_version.lock() = Some(req.version());
2666                    *observed_sni.lock() = req
2667                        .extensions()
2668                        .get_ref::<SecureTransport>()
2669                        .and_then(SecureTransport::client_hello)
2670                        .and_then(|hello| hello.ext_server_name().cloned());
2671                    let upgrade = handle_upgrade(&req);
2672                    tokio::spawn(async move {
2673                        let tunnel = upgrade.await.expect("server CONNECT upgrade");
2674                        // The client deliberately drops immediately after the
2675                        // handshake assertions, so the TLS server may finish
2676                        // with an EOF/close-notify error.
2677                        let _origin_result = origin_server.serve(tunnel).await;
2678                        if let Some(tx) = origin_done_tx.lock().take() {
2679                            tx.send(()).expect("origin completion receiver");
2680                        }
2681                    });
2682                    Ok::<_, Infallible>(Response::new(Body::empty()))
2683                }
2684            }));
2685        let proxy_server = TlsAcceptorLayer::new(
2686            TlsServerConfig::new()
2687                .with_single_cert(ServerAuthData {
2688                    cert_chain: proxy_chain,
2689                    private_key: proxy_key,
2690                    ocsp: None,
2691                })
2692                .with_alpn_http_2(),
2693        )
2694        .with_store_client_hello(true)
2695        .into_layer(proxy_http);
2696
2697        let (client_io, server_io) = tokio::io::duplex(64 * 1024);
2698        let client_io = Arc::new(parking_lot::Mutex::new(Some(client_io)));
2699        let transport = service_fn(move |input: ConnectRequest| {
2700            let conn = ServiceInput::new(client_io.lock().take().expect("one proxy connection"));
2701            async move { Ok::<_, ConnectionError>(EstablishedClientConnection { input, conn }) }
2702        });
2703
2704        let proxy_config = TlsClientConfig::new()
2705            .with_alpn_http_2()
2706            .with_server_name(crate::net::address::Domain::tld_localhost())
2707            .try_with_server_trust_anchors([proxy_trust])
2708            .expect("proxy trust");
2709        let proxy_tls = TlsConnector::auto(transport).with_base_config(proxy_config);
2710        let proxy_connections =
2711            HttpConnector::<_, ProxyRequestBody<Body>>::new(proxy_tls, WeakScope::detached());
2712        let proxy = HttpConnectProxyConnectorLayer::new().into_layer(proxy_connections);
2713        let origin_config = TlsClientConfig::new()
2714            .with_alpn(Default::default())
2715            .with_server_name(crate::net::address::Domain::tld_localhost())
2716            .try_with_server_trust_anchors([origin_trust])
2717            .expect("origin trust");
2718        let connector = TlsConnector::auto(proxy).with_base_config(origin_config);
2719
2720        let input = ConnectRequest::new(HostWithPort::try_from("localhost:443").unwrap())
2721            .with_application_protocol(Protocol::HTTPS);
2722        input.extensions.insert(ProxyRoute::Proxy(
2723            "h2://localhost:8443".parse::<ProxyAddress>().unwrap(),
2724        ));
2725        // Origin TLS inputs: they configure the origin handshake over the
2726        // tunnel and must not reach the handshake with the proxy.
2727        input.extensions.insert(TlsAlpn::http_1());
2728        input
2729            .extensions
2730            .insert(TlsServerVerify(ServerVerifyMode::Disable));
2731        input
2732            .extensions
2733            .insert(ServerName::from(crate::net::address::Domain::from_static(
2734                "elsewhere.example",
2735            )));
2736        let client = async move {
2737            let established = connector.serve(input).await.expect("two TLS handshakes");
2738
2739            assert_eq!(
2740                *connect_version.lock(),
2741                Some(Version::HTTP_2),
2742                "the connection to the proxy offers its own ALPN, never the origin's"
2743            );
2744            assert_eq!(
2745                proxy_sni
2746                    .lock()
2747                    .as_ref()
2748                    .map(ToString::to_string)
2749                    .as_deref(),
2750                Some("localhost"),
2751                "the connection to the proxy names the proxy, never the origin's server name"
2752            );
2753            let conn = established.conn.extensions();
2754            assert_eq!(
2755                conn.get_ref::<NegotiatedTlsParameters>()
2756                    .expect("origin TLS parameters")
2757                    .application_layer_protocol,
2758                Some(ApplicationProtocol::HTTP_11),
2759                "the origin handshake over the tunnel offers the request's ALPN"
2760            );
2761            assert_eq!(
2762                conn.get_ref::<TargetHttpVersion>().map(|version| version.0),
2763                Some(Version::HTTP_11),
2764                "proxy HTTP/2 must not leak past CONNECT into the origin"
2765            );
2766            assert_tunnel_serves_the_same_proxy(
2767                conn,
2768                established
2769                    .input
2770                    .extensions
2771                    .get_ref::<ProxyRoute>()
2772                    .unwrap(),
2773            );
2774            drop(established);
2775        };
2776        let (proxy_result, ()) =
2777            Box::pin(tokio::time::timeout(Duration::from_secs(5), async move {
2778                tokio::join!(proxy_server.serve(ServiceInput::new(server_io)), client)
2779            }))
2780            .await
2781            .expect("proxy/origin exchange");
2782        proxy_result.expect("proxy server");
2783        tokio::time::timeout(Duration::from_secs(5), origin_done_rx)
2784            .await
2785            .expect("origin server shutdown")
2786            .expect("origin completion signal");
2787    }
2788
2789    #[cfg(feature = "boring")]
2790    #[tokio::test]
2791    async fn boring_proxy_alpn_never_reaches_a_no_alpn_origin() {
2792        use crate::{
2793            extensions::ExtensionsRef as _,
2794            net::{
2795                Protocol,
2796                address::HostWithPort,
2797                client::{EstablishedClientConnection, ProxyRoute},
2798                stream::service::EchoService,
2799                tls::ServerName,
2800            },
2801            tls::{
2802                SecureTransport,
2803                boring::{client::TlsConnector, server::TlsAcceptorLayer},
2804                client::{
2805                    NegotiatedTlsParameters, ServerVerifyMode, TlsClientConfig, TlsServerVerify,
2806                },
2807                server::{GeneratedServerAuthConfig, ServerAuthData, TlsServerConfig},
2808            },
2809        };
2810        use rama_core::ServiceInput;
2811        use rama_crypto::cert::generate_server_auth;
2812        use rama_http::io::upgrade::handle_upgrade;
2813        use rama_http_backend::client::proxy::layer::HttpConnectProxyConnectorLayer;
2814        use rama_net::http::TargetHttpVersion;
2815        use std::sync::Arc;
2816
2817        let (proxy_chain, proxy_key) =
2818            generate_server_auth(GeneratedServerAuthConfig::default()).expect("proxy auth");
2819        let proxy_trust = proxy_chain.last().expect("proxy trust anchor").clone();
2820        let (origin_chain, origin_key) =
2821            generate_server_auth(GeneratedServerAuthConfig::default()).expect("origin auth");
2822        let origin_trust = origin_chain.last().expect("origin trust anchor").clone();
2823
2824        let origin_server =
2825            TlsAcceptorLayer::new(TlsServerConfig::new().with_single_cert(ServerAuthData {
2826                cert_chain: origin_chain,
2827                private_key: origin_key,
2828                ocsp: None,
2829            }))
2830            .into_layer(EchoService::new());
2831        let (origin_done_tx, origin_done_rx) = tokio::sync::oneshot::channel();
2832        let origin_done_tx = Arc::new(parking_lot::Mutex::new(Some(origin_done_tx)));
2833
2834        let connect_version = Arc::new(parking_lot::Mutex::new(None));
2835        let observed_version = connect_version.clone();
2836        let proxy_sni = Arc::new(parking_lot::Mutex::new(None));
2837        let observed_sni = proxy_sni.clone();
2838        let proxy_http =
2839            HttpServer::auto(WeakScope::detached()).service(service_fn(move |req: Request| {
2840                let origin_server = origin_server.clone();
2841                let origin_done_tx = origin_done_tx.clone();
2842                let observed_version = observed_version.clone();
2843                let observed_sni = observed_sni.clone();
2844                async move {
2845                    assert_eq!(req.method(), rama_http::Method::CONNECT);
2846                    *observed_version.lock() = Some(req.version());
2847                    *observed_sni.lock() = req
2848                        .extensions()
2849                        .get_ref::<SecureTransport>()
2850                        .and_then(SecureTransport::client_hello)
2851                        .and_then(|hello| hello.ext_server_name().cloned());
2852                    let upgrade = handle_upgrade(&req);
2853                    tokio::spawn(async move {
2854                        let tunnel = upgrade.await.expect("server CONNECT upgrade");
2855                        // The client deliberately drops immediately after the
2856                        // handshake assertions, so the TLS server may finish
2857                        // with an EOF/close-notify error.
2858                        let _origin_result = origin_server.serve(tunnel).await;
2859                        if let Some(tx) = origin_done_tx.lock().take() {
2860                            tx.send(()).expect("origin completion receiver");
2861                        }
2862                    });
2863                    Ok::<_, Infallible>(Response::new(Body::empty()))
2864                }
2865            }));
2866        let proxy_server = TlsAcceptorLayer::new(
2867            TlsServerConfig::new()
2868                .with_single_cert(ServerAuthData {
2869                    cert_chain: proxy_chain,
2870                    private_key: proxy_key,
2871                    ocsp: None,
2872                })
2873                .with_alpn_http_2(),
2874        )
2875        .with_store_client_hello(true)
2876        .into_layer(proxy_http);
2877
2878        let (client_io, server_io) = tokio::io::duplex(64 * 1024);
2879        let client_io = Arc::new(parking_lot::Mutex::new(Some(client_io)));
2880        let transport = service_fn(move |input: ConnectRequest| {
2881            let conn = ServiceInput::new(client_io.lock().take().expect("one proxy connection"));
2882            async move { Ok::<_, ConnectionError>(EstablishedClientConnection { input, conn }) }
2883        });
2884
2885        let proxy_config = TlsClientConfig::new()
2886            .with_alpn_http_2()
2887            .with_server_name(crate::net::address::Domain::from_static("localhost"))
2888            .try_with_server_trust_anchors([proxy_trust])
2889            .expect("proxy trust");
2890        let proxy_tls = TlsConnector::auto(transport).with_base_config(proxy_config);
2891        let proxy_connections =
2892            HttpConnector::<_, ProxyRequestBody<Body>>::new(proxy_tls, WeakScope::detached());
2893        let proxy = HttpConnectProxyConnectorLayer::new().into_layer(proxy_connections);
2894        let origin_config = TlsClientConfig::new()
2895            .with_alpn(Default::default())
2896            .with_server_name(crate::net::address::Domain::from_static("localhost"))
2897            .try_with_server_trust_anchors([origin_trust])
2898            .expect("origin trust");
2899        let connector = TlsConnector::auto(proxy).with_base_config(origin_config);
2900
2901        let input = ConnectRequest::new(HostWithPort::try_from("localhost:443").unwrap())
2902            .with_application_protocol(Protocol::HTTPS);
2903        input.extensions.insert(ProxyRoute::Proxy(
2904            "h2://localhost:8443".parse::<ProxyAddress>().unwrap(),
2905        ));
2906        // Origin TLS inputs: they configure the origin handshake over the
2907        // tunnel and must not reach the handshake with the proxy.
2908        input
2909            .extensions
2910            .insert(TlsServerVerify(ServerVerifyMode::Disable));
2911        input
2912            .extensions
2913            .insert(ServerName::from(crate::net::address::Domain::from_static(
2914                "elsewhere.example",
2915            )));
2916        let client = async move {
2917            let established = connector.serve(input).await.expect("two TLS handshakes");
2918
2919            assert_eq!(
2920                *connect_version.lock(),
2921                Some(Version::HTTP_2),
2922                "the connection to the proxy offers its own ALPN, never the origin's"
2923            );
2924            assert_eq!(
2925                proxy_sni
2926                    .lock()
2927                    .as_ref()
2928                    .map(ToString::to_string)
2929                    .as_deref(),
2930                Some("localhost"),
2931                "the connection to the proxy names the proxy, never the origin's server name"
2932            );
2933            let conn = established.conn.extensions();
2934            assert_eq!(
2935                conn.get_ref::<NegotiatedTlsParameters>()
2936                    .expect("origin TLS parameters")
2937                    .application_layer_protocol,
2938                None,
2939                "an origin without an ALPN offer negotiates none"
2940            );
2941            assert!(
2942                conn.get_ref::<TargetHttpVersion>().is_none(),
2943                "proxy HTTP/2 must not leak past CONNECT into a no-ALPN origin"
2944            );
2945            assert_tunnel_serves_the_same_proxy(
2946                conn,
2947                established
2948                    .input
2949                    .extensions
2950                    .get_ref::<ProxyRoute>()
2951                    .unwrap(),
2952            );
2953            drop(established);
2954        };
2955        let (proxy_result, ()) =
2956            Box::pin(tokio::time::timeout(Duration::from_secs(5), async move {
2957                tokio::join!(proxy_server.serve(ServiceInput::new(server_io)), client)
2958            }))
2959            .await
2960            .expect("proxy/origin exchange");
2961        proxy_result.expect("proxy server");
2962        tokio::time::timeout(Duration::from_secs(5), origin_done_rx)
2963            .await
2964            .expect("origin server shutdown")
2965            .expect("origin completion signal");
2966    }
2967
2968    #[cfg(feature = "boring")]
2969    #[tokio::test]
2970    async fn default_client_resumes_tls_sessions() {
2971        let scope = WeakScope::detached();
2972        let resumed = Arc::new(parking_lot::Mutex::new(Vec::new()));
2973        let record = resumed.clone();
2974        let server = TlsAcceptorLayer::new(
2975            TlsServerConfig::new()
2976                .with_server_auth(
2977                    ServerAuthData::new_generated(GeneratedServerAuthConfig::default()).unwrap(),
2978                )
2979                .with_alpn_http_1(),
2980        )
2981        .with_session_resumption(true)
2982        .into_layer(
2983            MapInputLayer::new(move |stream: TlsStream<TcpStream>| {
2984                let params = stream.extensions().get_ref::<NegotiatedTlsParameters>();
2985                record.lock().push(params.and_then(|params| params.resumed));
2986                stream
2987            })
2988            .into_layer(HttpServer::new_http1(scope.clone()).service(service_fn(
2989                async |_: Request| {
2990                    // A fresh connection per request, so each one handshakes.
2991                    Ok::<_, Infallible>(
2992                        Response::builder()
2993                            .header(CONNECTION, "close")
2994                            .body(Body::empty())
2995                            .unwrap(),
2996                    )
2997                },
2998            ))),
2999        );
3000        let listener = TcpListener::bind_address(SocketAddress::local_ipv4(0), scope)
3001            .await
3002            .unwrap();
3003        let port = listener.local_addr().unwrap().port();
3004        let server = tokio::spawn(listener.serve(server));
3005
3006        let client = DefaultHttpWebClient::<Body>::default();
3007        for _ in 0..2 {
3008            let request = Request::builder()
3009                .uri(format!("https://localhost:{port}/"))
3010                .body(Body::empty())
3011                .unwrap();
3012            request
3013                .extensions()
3014                .insert(TlsServerVerify(ServerVerifyMode::Disable));
3015            let response = tokio::time::timeout(Duration::from_secs(5), client.serve(request))
3016                .await
3017                .unwrap()
3018                .unwrap();
3019            response.try_into_string().await.unwrap();
3020        }
3021        server.abort();
3022        assert_eq!(*resumed.lock(), [Some(false), Some(true)]);
3023    }
3024
3025    #[cfg(feature = "boring")]
3026    #[test]
3027    fn proxy_failure_cache_keeps_tls_client_future_bounded() {
3028        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
3029            .with_default_transport_connector()
3030            .with_default_dns_connector()
3031            .with_proxy_support(proxies_over(TcpConnector::new()))
3032            .with_tls_support_using_boringssl_and_default_http_version(
3033                TlsClientConfig::default_http(),
3034                Version::HTTP_11,
3035            )
3036            .with_default_http_connector()
3037            .without_connection_pool()
3038            .build_client();
3039        let request = Request::builder()
3040            .uri("https://example.com")
3041            .body(Body::empty())
3042            .unwrap();
3043
3044        let future = client.serve(request);
3045        let future_size = std::mem::size_of_val(&future);
3046
3047        assert!(
3048            future_size < 64 * 1024,
3049            "easy TLS client future is unexpectedly large: {future_size} bytes"
3050        );
3051    }
3052
3053    #[tokio::test]
3054    async fn connection_is_in_use_until_response_body_is_consumed() {
3055        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
3056            .with_custom_tcp_connector(dummy_server())
3057            .without_dns_connector()
3058            .without_proxy_support()
3059            .without_tls_support()
3060            .with_default_http_connector()
3061            .with_connection_pool(HttpPooledConnectorConfig {
3062                max_streams_per_connection: NonZeroUsize::new(1),
3063                max_connections_total: NonZeroUsize::new(4),
3064                ..Default::default()
3065            })
3066            .build_client();
3067
3068        let req = || {
3069            Request::builder()
3070                .uri("http://example.com")
3071                .version(Version::HTTP_2)
3072                .body(Body::empty())
3073                .unwrap()
3074        };
3075
3076        // Get the first response but DO NOT consume its body yet: the connection
3077        // is logically still in use until the body is drained. Then issue a second
3078        // request before draining the first.
3079        let res1 = client.serve(req()).await.unwrap();
3080        let res2 = client.serve(req()).await.unwrap();
3081
3082        // Drain in reverse so `res1`'s body is still outstanding when `req2` runs.
3083        let out2 = res2.try_into_json::<Output>().await.unwrap();
3084        let out1 = res1.try_into_json::<Output>().await.unwrap();
3085
3086        assert_eq!(out1.conn, 0, "first request uses the first connection");
3087        // With `max_concurrent_streams = 1`, connection 0's response body is still
3088        // in flight, so the second request must NOT reuse it.
3089        assert_eq!(
3090            out2.conn, 1,
3091            "second request must not reuse a connection whose response body is still in flight"
3092        );
3093    }
3094
3095    // These things are already tested inside the pool itself, but here we add some high level tests
3096    // in case we ever swap the underlying pool implementation.
3097
3098    #[tokio::test]
3099    async fn default_pool_multiplexes_on_h2() {
3100        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
3101            .with_custom_tcp_connector(dummy_server())
3102            .without_dns_connector()
3103            .without_proxy_support()
3104            .without_tls_support()
3105            .with_default_http_connector()
3106            .with_default_connection_pool()
3107            .build_client();
3108
3109        let req = || {
3110            Request::builder()
3111                .uri("http://example.com")
3112                .version(Version::HTTP_2)
3113                .body(Body::empty())
3114                .unwrap()
3115        };
3116        let (res1, res2, res3) = tokio::join!(
3117            client.serve(req()),
3118            client.serve(req()),
3119            client.serve(req()),
3120        );
3121
3122        // Should only create single connection and send all requests over the same one
3123        for (i, res) in [res1, res2, res3].into_iter().enumerate() {
3124            let out = res.unwrap().try_into_json::<Output>().await.unwrap();
3125            assert_eq!(out.conn, 0);
3126            assert_eq!(out.resp, i);
3127        }
3128    }
3129
3130    #[tokio::test]
3131    async fn default_pool_does_not_multiplexes_on_h1() {
3132        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
3133            .with_custom_tcp_connector(dummy_server())
3134            .without_dns_connector()
3135            .without_proxy_support()
3136            .without_tls_support()
3137            .with_default_http_connector()
3138            .with_default_connection_pool()
3139            .build_client();
3140
3141        let req = || {
3142            Request::builder()
3143                .uri("http://example.com")
3144                .version(Version::HTTP_11)
3145                .body(Body::empty())
3146                .unwrap()
3147        };
3148        let (res1, res2, res3) = tokio::join!(
3149            client.serve(req()),
3150            client.serve(req()),
3151            client.serve(req()),
3152        );
3153
3154        // Should create a new connection for each request since they are all inprogress at the same
3155        // time and h1 does not support multiplexing
3156        for (i, res) in [res1, res2, res3].into_iter().enumerate() {
3157            let out = res.unwrap().try_into_json::<Output>().await.unwrap();
3158            assert_eq!(out.conn, i);
3159            assert_eq!(out.resp, 0);
3160        }
3161    }
3162
3163    #[tokio::test]
3164    async fn multiplex_on_h2_respects_limits() {
3165        let client = EasyHttpWebClient::connector_builder(WeakScope::detached())
3166            .with_custom_tcp_connector(dummy_server())
3167            .without_dns_connector()
3168            .without_proxy_support()
3169            .without_tls_support()
3170            .with_default_http_connector()
3171            .with_connection_pool(HttpPooledConnectorConfig {
3172                max_streams_per_connection: NonZeroUsize::new(2),
3173                ..Default::default()
3174            })
3175            .build_client();
3176
3177        let req = || {
3178            Request::builder()
3179                .uri("http://example.com")
3180                .version(Version::HTTP_2)
3181                .body(Body::empty())
3182                .unwrap()
3183        };
3184        let (res1, res2, res3, res4) = tokio::join!(
3185            client.serve(req()),
3186            client.serve(req()),
3187            client.serve(req()),
3188            client.serve(req()),
3189        );
3190
3191        // Should create a connection for every two request
3192        for (i, res) in [res1, res2, res3, res4].into_iter().enumerate() {
3193            let out = res.unwrap().try_into_json::<Output>().await.unwrap();
3194            assert_eq!(out.conn, i / 2);
3195            assert_eq!(out.resp, i % 2);
3196        }
3197    }
3198}