Skip to main content

saluki_io/net/client/http/
client.rs

1#[cfg(unix)]
2use std::path::PathBuf;
3use std::{
4    future::Future,
5    pin::Pin,
6    sync::Arc,
7    task::{Context, Poll},
8    time::Duration,
9};
10
11use bytes::{Buf, Bytes};
12use http::{Request, Response, Uri};
13use http_body::{Body, Frame, SizeHint};
14use http_body_util::combinators::BoxBody;
15use hyper::body::Incoming;
16use hyper_http_proxy::Proxy;
17use hyper_util::{
18    client::legacy::{connect::capture_connection, Builder},
19    rt::{TokioExecutor, TokioTimer},
20};
21use pin_project::pin_project;
22use rustls::ClientConfig;
23use saluki_error::GenericError;
24use saluki_metrics::MetricsBuilder;
25use saluki_tls::{
26    ensure_client_config_fips_compliant, load_platform_root_certificates_inner, ClientTLSConfigBuilder,
27    TlsMinimumVersion,
28};
29use stringtheory::MetaString;
30use tokio_rustls::TlsConnector;
31use tower::{timeout::TimeoutLayer, util::BoxCloneService, BoxError, Service, ServiceBuilder, ServiceExt as _};
32
33use super::{
34    conn::{check_connection_state, http_protocol_alpns, HttpProtocol, HttpsCapableConnectorBuilder},
35    telemetry::HttpTransactionErrorTelemetry,
36    EndpointTelemetryLayer,
37};
38
39/// The type-erased body type used internally by [`HttpClient`].
40///
41/// All request bodies are converted to this type before being sent over the wire, which ensures a single
42/// monomorphization of the underlying HTTP/2 and TLS stacks regardless of the caller's body type.
43pub type ClientBody = BoxBody<Bytes, Box<dyn std::error::Error + Send + Sync>>;
44
45#[pin_project]
46struct ClientBodyAdapter<B> {
47    #[pin]
48    inner: B,
49    size_hint: SizeHint,
50}
51
52impl<B> Body for ClientBodyAdapter<B>
53where
54    B: Body,
55    B::Data: Buf,
56    B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
57{
58    type Data = Bytes;
59    type Error = Box<dyn std::error::Error + Send + Sync>;
60
61    fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
62        self.project().inner.poll_frame(cx).map(|maybe_frame| {
63            maybe_frame.map(|result| {
64                result
65                    .map(|frame| frame.map_data(|mut data| data.copy_to_bytes(data.remaining())))
66                    .map_err(Into::into)
67            })
68        })
69    }
70
71    fn size_hint(&self) -> SizeHint {
72        self.size_hint
73    }
74}
75
76/// An HTTP client.
77#[derive(Clone)]
78pub struct HttpClient {
79    inner: BoxCloneService<Request<ClientBody>, Response<Incoming>, BoxError>,
80}
81
82impl HttpClient {
83    /// Creates a new builder for configuring an HTTP client.
84    pub fn builder() -> HttpClientBuilder {
85        HttpClientBuilder::default()
86    }
87
88    /// Sends a request to the server, and waits for a response.
89    ///
90    /// The request body is type-erased internally, so callers can use any body type that implements
91    /// [`Body`] with `Data` types that implement [`Buf`].
92    ///
93    /// # Errors
94    ///
95    /// If there was an error sending the request, an error will be returned.
96    pub async fn send<B>(&mut self, req: Request<B>) -> Result<Response<Incoming>, GenericError>
97    where
98        B: Body + Send + Sync + 'static,
99        B::Data: Buf + Send,
100        B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
101    {
102        let mut req = req.map(into_client_body);
103        let captured_conn = capture_connection(&mut req);
104        let result = self
105            .inner
106            .ready()
107            .await
108            .map_err(GenericError::from_boxed)?
109            .call(req)
110            .await;
111
112        check_connection_state(captured_conn);
113
114        result.map_err(GenericError::from_boxed)
115    }
116}
117
118impl Service<Request<ClientBody>> for HttpClient {
119    type Response = Response<Incoming>;
120    type Error = BoxError;
121    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
122
123    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
124        self.inner.poll_ready(cx)
125    }
126
127    fn call(&mut self, mut req: Request<ClientBody>) -> Self::Future {
128        let captured_conn = capture_connection(&mut req);
129        let fut = self.inner.call(req);
130
131        Box::pin(async move {
132            let result = fut.await;
133
134            check_connection_state(captured_conn);
135
136            result
137        })
138    }
139}
140
141/// Converts an arbitrary body into the type-erased [`ClientBody`].
142///
143/// This uses `Buf::copy_to_bytes` for the data conversion, which is zero-copy when the underlying
144/// data is already `Bytes`.
145pub fn into_client_body<B>(body: B) -> ClientBody
146where
147    B: Body + Send + Sync + 'static,
148    B::Data: Buf + Send,
149    B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
150{
151    let size_hint = body.size_hint();
152    BoxBody::new(ClientBodyAdapter { inner: body, size_hint })
153}
154
155/// An HTTP client builder.
156///
157/// Provides an ergonomic builder API for configuring an HTTP client.
158///
159/// # Defaults
160///
161/// A number of sensible defaults are provided:
162///
163/// - support for both HTTP and HTTPS (uses platform's root certificates for server certificate validation)
164/// - support for both HTTP/1.1 and HTTP/2 (automatically negotiated via ALPN)
165/// - non-infinite timeouts for various stages of the request lifecycle (30 second connect timeout, 60 second per-request timeout)
166/// - connection pool for reusing connections (45 second idle connection timeout, and a maximum of 5 idle connections
167///   per host)
168/// - support for FIPS-compliant cryptography if the `fips` feature is enabled in the `saluki-tls` crate
169pub struct HttpClientBuilder {
170    connector_builder: HttpsCapableConnectorBuilder,
171    hyper_builder: Builder,
172    tls_builder: ClientTLSConfigBuilder,
173    client_tls_config: Option<ClientConfig>,
174    request_timeout: Option<Duration>,
175    endpoint_telemetry: Option<EndpointTelemetryLayer>,
176    proxies: Option<Vec<Proxy>>,
177}
178
179impl HttpClientBuilder {
180    /// Sets the timeout when connecting to the remote host.
181    ///
182    /// Defaults to 30 seconds.
183    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
184        self.connector_builder = self.connector_builder.with_connect_timeout(timeout);
185        self
186    }
187
188    /// Sets the timeout for completing the TLS handshake after a connection is established.
189    ///
190    /// This bounds only the TLS handshake step, distinct from the connect timeout, which bounds the underlying TCP
191    /// (or other transport) connection setup that precedes it.
192    ///
193    /// Defaults to 10 seconds.
194    pub fn with_tls_handshake_timeout(mut self, timeout: Duration) -> Self {
195        self.connector_builder = self.connector_builder.with_tls_handshake_timeout(timeout);
196        self
197    }
198
199    /// Sets the per-request timeout.
200    ///
201    /// The request timeout applies to each individual request made to the remote host, including each request made when
202    /// retrying a failed request.
203    ///
204    /// Defaults to 20 seconds.
205    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
206        self.request_timeout = Some(timeout);
207        self
208    }
209
210    /// Allow requests to run indefinitely.
211    ///
212    /// This means there will be no overall timeout for the request, but the request still may be subject to other
213    /// configuration settings, such as the connect timeout or retry policy.
214    pub fn without_request_timeout(mut self) -> Self {
215        self.request_timeout = None;
216        self
217    }
218
219    /// Sets the HTTP protocol selection for client connections.
220    ///
221    /// Defaults to [`HttpProtocol::Auto`], which automatically negotiates HTTP/2 with HTTP/1.1 fallback.
222    ///
223    /// [`HttpProtocol::Http2`] sends HTTP/2 on every connection: plaintext connections use prior knowledge (h2c), and
224    /// TLS connections advertise only `h2` through ALPN.
225    pub fn with_http_protocol(mut self, protocol: HttpProtocol) -> Self {
226        self.connector_builder = self.connector_builder.with_http_protocol(protocol);
227        self
228    }
229
230    /// Sets the maximum age of a connection before it's closed.
231    ///
232    /// This is distinct from the maximum idle time: if any connection's age exceeds `limit`, it will be closed rather
233    /// than being reused and added to the idle connection pool.
234    ///
235    /// Defaults to no limit.
236    pub fn with_connection_age_limit<L>(mut self, limit: L) -> Self
237    where
238        L: Into<Option<Duration>>,
239    {
240        self.connector_builder = self.connector_builder.with_connection_age_limit(limit);
241        self
242    }
243
244    /// Sets the maximum number of idle connections per host.
245    ///
246    /// Defaults to 5.
247    pub fn with_max_idle_conns_per_host(mut self, max: usize) -> Self {
248        self.hyper_builder.pool_max_idle_per_host(max);
249        self
250    }
251
252    /// Sets the idle connection timeout.
253    ///
254    /// Once a connection has been idle in the pool for longer than this duration, it will be closed and removed from
255    /// the pool.
256    ///
257    /// Defaults to 45 seconds.
258    pub fn with_idle_conn_timeout(mut self, timeout: Duration) -> Self {
259        self.hyper_builder.pool_idle_timeout(timeout);
260        self
261    }
262
263    /// Sets the proxies to be used for outgoing requests.
264    ///
265    /// Defaults to no proxies. (i.e requests will be sent directly without using a proxy).
266    pub fn with_proxies(mut self, proxies: Vec<Proxy>) -> Self {
267        self.proxies = Some(proxies);
268        self
269    }
270
271    /// Enables per-endpoint telemetry for HTTP transactions.
272    ///
273    /// See [`EndpointTelemetryLayer`] for more information.
274    pub fn with_endpoint_telemetry<F>(mut self, metrics_builder: MetricsBuilder, endpoint_name_fn: Option<F>) -> Self
275    where
276        F: Fn(&Uri) -> Option<MetaString> + Send + Sync + 'static,
277    {
278        let error_telemetry = HttpTransactionErrorTelemetry::from_builder(&metrics_builder);
279        self.connector_builder = self.connector_builder.with_error_telemetry(error_telemetry.clone());
280
281        let mut layer = EndpointTelemetryLayer::default()
282            .with_metrics_builder(metrics_builder)
283            .with_error_telemetry(error_telemetry);
284
285        if let Some(endpoint_name_fn) = endpoint_name_fn {
286            layer = layer.with_endpoint_name_fn(endpoint_name_fn);
287        }
288
289        self.endpoint_telemetry = Some(layer);
290        self
291    }
292
293    /// Sets a Unix domain socket path to route all connections through.
294    ///
295    /// When set, the client will connect to this Unix socket instead of performing DNS resolution
296    /// and TCP connection. The URI host is ignored—all requests are sent through the configured
297    /// socket.
298    ///
299    /// Defaults to unset (TCP connections via DNS).
300    #[cfg(unix)]
301    pub fn with_unix_socket_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
302        self.connector_builder = self.connector_builder.with_unix_socket_path(path);
303        self
304    }
305
306    /// Sets an AF_VSOCK address to route all connections through.
307    ///
308    /// When set, the client will connect to this address instead of performing DNS resolution and TCP connection.
309    /// The URI host is ignored—all requests are sent to the configured address.
310    ///
311    /// Defaults to unset (TCP connections via DNS).
312    #[cfg(target_os = "linux")]
313    pub fn with_vsock_addr(mut self, addr: tokio_vsock::VsockAddr) -> Self {
314        self.connector_builder = self.connector_builder.with_vsock_addr(addr);
315        self
316    }
317
318    /// Sets the TLS configuration.
319    ///
320    /// A TLS configuration builder is provided to allow for more advanced configuration of the TLS connection.
321    /// [`Self::with_client_tls_config`] overrides these settings regardless of call order.
322    pub fn with_tls_config<F>(mut self, f: F) -> Self
323    where
324        F: FnOnce(ClientTLSConfigBuilder) -> ClientTLSConfigBuilder,
325    {
326        self.tls_builder = f(self.tls_builder);
327        self
328    }
329
330    /// Sets a complete Rustls client TLS configuration.
331    ///
332    /// This configuration takes precedence over all option-based settings made through [`Self::with_tls_config`] or
333    /// [`Self::with_min_tls_version`], regardless of call order. The configuration is otherwise preserved, including
334    /// its certificate verifier, client identity, enabled TLS protocol versions, and other security settings.
335    ///
336    /// Any ALPN protocols already present in `config` are discarded before the configuration is passed to
337    /// `hyper-rustls`. [`Self::with_http_protocol`] remains the sole source of HTTP protocol selection:
338    /// [`HttpProtocol::Auto`] advertises HTTP/2 with HTTP/1.1 fallback, [`HttpProtocol::Http1`] enables only
339    /// HTTP/1.1 and does not advertise ALPN, and [`HttpProtocol::Http2`] advertises only HTTP/2.
340    ///
341    /// The supplied configuration is validated for FIPS compliance during [`Self::build`].
342    pub fn with_client_tls_config(mut self, config: ClientConfig) -> Self {
343        self.client_tls_config = Some(config);
344        self
345    }
346
347    /// Sets the minimum TLS protocol version for HTTPS connections.
348    ///
349    /// Defaults to TLS 1.2.
350    ///
351    /// This updates the same TLS builder configured by [`Self::with_tls_config`], so call order matters when both
352    /// methods change the minimum TLS version. [`Self::with_client_tls_config`] overrides this setting regardless of
353    /// call order.
354    pub fn with_min_tls_version(mut self, version: TlsMinimumVersion) -> Self {
355        self.tls_builder = self.tls_builder.with_min_tls_version(version);
356        self
357    }
358
359    /// Sets the underlying Hyper client configuration.
360    ///
361    /// This is provided to allow for more advanced configuration of the Hyper client itself, and should generally be
362    /// used sparingly.
363    pub fn with_hyper_config<F>(mut self, f: F) -> Self
364    where
365        F: FnOnce(&mut Builder),
366    {
367        f(&mut self.hyper_builder);
368        self
369    }
370
371    /// Builds the `HttpClient`.
372    ///
373    /// # Errors
374    ///
375    /// If there was an error building the TLS configuration for the client, or if a supplied complete TLS
376    /// configuration fails FIPS validation in a FIPS build, an error will be returned.
377    pub fn build(self) -> Result<HttpClient, GenericError> {
378        let http_protocol = self.connector_builder.http_protocol;
379        let tls_config = match self.client_tls_config {
380            Some(mut config) => {
381                ensure_client_config_fips_compliant(&config)?;
382                config.alpn_protocols.clear();
383                config
384            }
385            None => self.tls_builder.build()?,
386        };
387        let connector = self.connector_builder.build(tls_config)?;
388        let tls_handshake_timeout = connector.tls_handshake_timeout();
389        // The inner connector verifies HTTPS proxies; this separate config verifies destinations through CONNECT.
390        // Keep native roots and verification enabled here even if the inner connector uses an insecure local config.
391        let mut proxy_tls_config = ClientTLSConfigBuilder::new()
392            .with_root_cert_store(load_platform_root_certificates_inner()?)
393            .build()?;
394        if http_protocol == HttpProtocol::Http2 {
395            // The proxy connector can't report a negotiated `h2`. Advertise `h2` only when the client requires it.
396            proxy_tls_config.alpn_protocols = http_protocol_alpns(http_protocol);
397        }
398        let mut proxy_connector = hyper_http_proxy::ProxyConnector::unsecured(connector);
399        proxy_connector.set_tls(Some(TlsConnector::from(Arc::new(proxy_tls_config))));
400        // A zero timeout means the handshake deadline is disabled, matching `HttpsCapableConnector`'s own
401        // handling of `Duration::ZERO` for direct connections.
402        let proxy_tls_handshake_timeout = (!tls_handshake_timeout.is_zero()).then_some(tls_handshake_timeout);
403        proxy_connector.set_tls_handshake_timeout(proxy_tls_handshake_timeout);
404        if let Some(proxies) = &self.proxies {
405            for proxy in proxies {
406                proxy_connector.add_proxy(proxy.to_owned());
407            }
408        }
409        let mut hyper_builder = self.hyper_builder;
410        if http_protocol == HttpProtocol::Http2 {
411            hyper_builder.http2_only(true);
412        }
413        let client = hyper_builder.build(proxy_connector);
414
415        let inner = ServiceBuilder::new()
416            .option_layer(self.request_timeout.map(TimeoutLayer::new))
417            .option_layer(self.endpoint_telemetry)
418            .service(client.map_err(BoxError::from))
419            .boxed_clone();
420
421        Ok(HttpClient { inner })
422    }
423}
424
425impl Default for HttpClientBuilder {
426    fn default() -> Self {
427        let mut hyper_builder = Builder::new(TokioExecutor::new());
428        hyper_builder
429            .pool_timer(TokioTimer::new())
430            .pool_max_idle_per_host(5)
431            .pool_idle_timeout(Duration::from_secs(45));
432
433        Self {
434            connector_builder: HttpsCapableConnectorBuilder::default(),
435            hyper_builder,
436            tls_builder: ClientTLSConfigBuilder::new(),
437            client_tls_config: None,
438            request_timeout: Some(Duration::from_secs(20)),
439            endpoint_telemetry: None,
440            proxies: None,
441        }
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    use std::{convert::Infallible, net::SocketAddr, sync::Arc, time::Duration};
448
449    use http::Version;
450    use http_body::Body as _;
451    use http_body_util::{Empty, Full};
452    use hyper::{server::conn::http2, service::service_fn};
453    use hyper_util::rt::TokioIo;
454    use rustls::{server::WebPkiClientVerifier, ClientConfig, RootCertStore, ServerConfig};
455    use saluki_tls::test_util::SelfSignedCert;
456    use tokio::{
457        io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _},
458        net::TcpListener,
459        sync::{mpsc, oneshot},
460        time::timeout,
461    };
462    use tokio_rustls::{LazyConfigAcceptor, TlsAcceptor};
463
464    use super::*;
465
466    #[test]
467    fn into_client_body_preserves_exact_size_hint() {
468        let body = Full::new(Bytes::from_static(b"hello"));
469        let converted = into_client_body(body);
470
471        assert_eq!(Some(5), converted.size_hint().exact());
472    }
473
474    fn initialize_crypto_provider() {
475        let _ = saluki_tls::initialize_default_crypto_provider();
476        assert!(
477            rustls::crypto::CryptoProvider::get_default().is_some(),
478            "default crypto provider should be installed"
479        );
480    }
481
482    #[tokio::test]
483    async fn complete_tls_config_preserves_mtls_and_overrides_option_settings() {
484        initialize_crypto_provider();
485        let (server_config, client_config) = mutual_tls_configs();
486        let builder = HttpClient::builder()
487            .with_client_tls_config(client_config)
488            .with_tls_config(|builder| builder.with_root_cert_store(RootCertStore::empty()));
489
490        let _ = send_request_to_tls_server(builder, server_config)
491            .await
492            .expect("complete config should verify the server and present the client identity");
493    }
494
495    #[tokio::test]
496    async fn complete_tls_config_alpn_is_normalized_for_http1() {
497        initialize_crypto_provider();
498        let (mut server_config, mut client_config) = mutual_tls_configs();
499        server_config.alpn_protocols = vec![b"custom".to_vec(), b"http/1.1".to_vec()];
500        client_config.alpn_protocols = vec![b"custom".to_vec()];
501        let builder = HttpClient::builder().with_client_tls_config(client_config);
502
503        let negotiated_alpn = send_request_to_tls_server(builder, server_config)
504            .await
505            .expect("client should normalize ALPN and complete an HTTP/1.1 request");
506
507        assert_eq!(negotiated_alpn, None);
508    }
509
510    #[tokio::test]
511    async fn tls_handshake_timeout_fires_against_a_stalled_server() {
512        initialize_crypto_provider();
513        let server_cert = SelfSignedCert::localhost();
514
515        let listener = TcpListener::bind("127.0.0.1:0").await.expect("should bind listener");
516        let port = listener.local_addr().expect("should have local address").port();
517        let server_task = tokio::spawn(async move {
518            let (stream, _) = listener.accept().await.expect("server should accept a connection");
519            // Accept the TCP connection but never complete the TLS handshake, so the client's handshake
520            // deadline is the only thing that can end the connection attempt.
521            tokio::time::sleep(Duration::from_secs(30)).await;
522            drop(stream);
523        });
524
525        let mut client = HttpClient::builder()
526            .with_tls_config(|builder| builder.with_root_cert_store(root_store(&server_cert)))
527            .with_tls_handshake_timeout(Duration::from_millis(200))
528            .with_http_protocol(HttpProtocol::Http1)
529            .build()
530            .expect("client should build");
531        let request = Request::get(format!("https://localhost:{port}/"))
532            .body(Empty::<Bytes>::new())
533            .expect("request should build");
534
535        let error = timeout(Duration::from_secs(5), client.send(request))
536            .await
537            .expect("request should not hit the outer test timeout")
538            .expect_err("handshake should time out before completing");
539        assert!(
540            format!("{error:#}").contains("TLS handshake timed out"),
541            "expected a TLS handshake timeout, got: {error:#}"
542        );
543
544        server_task.abort();
545    }
546
547    #[tokio::test]
548    async fn tls_handshake_timeout_fires_against_a_stalled_proxy_tunnel() {
549        initialize_crypto_provider();
550
551        let listener = TcpListener::bind("127.0.0.1:0").await.expect("should bind listener");
552        let proxy_addr = listener.local_addr().expect("should have local address");
553        let proxy_task = tokio::spawn(async move {
554            let (mut stream, _) = listener.accept().await.expect("proxy should accept a connection");
555            let mut request = [0; 4096];
556            let bytes_read = stream
557                .read(&mut request)
558                .await
559                .expect("proxy should read the CONNECT request");
560            assert!(bytes_read > 0, "proxy should receive a CONNECT request");
561            stream
562                .write_all(b"HTTP/1.1 200 OK\r\n\r\n")
563                .await
564                .expect("proxy should write the CONNECT response");
565            // Complete the CONNECT tunnel but never speak TLS, so the client's handshake deadline is
566            // the only thing that can end the connection attempt.
567            tokio::time::sleep(Duration::from_secs(30)).await;
568            drop(stream);
569        });
570
571        let proxy_uri: Uri = format!("http://{proxy_addr}").parse().expect("proxy URI should parse");
572        let mut client = HttpClient::builder()
573            .with_proxies(vec![Proxy::new(hyper_http_proxy::Intercept::All, proxy_uri)])
574            .with_tls_config(|builder| builder.with_root_cert_store(RootCertStore::empty()))
575            .with_tls_handshake_timeout(Duration::from_millis(200))
576            .with_http_protocol(HttpProtocol::Http1)
577            .build()
578            .expect("client should build");
579        let request = Request::get("https://example.invalid/")
580            .body(Empty::<Bytes>::new())
581            .expect("request should build");
582
583        let error = timeout(Duration::from_secs(5), client.send(request))
584            .await
585            .expect("request should not hit the outer test timeout")
586            .expect_err("handshake should time out before completing");
587        assert!(
588            format!("{error:#}").contains("TLS handshake timed out"),
589            "expected a TLS handshake timeout, got: {error:#}"
590        );
591
592        proxy_task.abort();
593    }
594
595    #[tokio::test]
596    async fn zero_tls_handshake_timeout_disables_the_proxy_tunnel_deadline() {
597        initialize_crypto_provider();
598
599        let listener = TcpListener::bind("127.0.0.1:0").await.expect("should bind listener");
600        let proxy_addr = listener.local_addr().expect("should have local address");
601        let proxy_task = tokio::spawn(async move {
602            let (mut stream, _) = listener.accept().await.expect("proxy should accept a connection");
603            let mut request = [0; 4096];
604            let bytes_read = stream
605                .read(&mut request)
606                .await
607                .expect("proxy should read the CONNECT request");
608            assert!(bytes_read > 0, "proxy should receive a CONNECT request");
609            stream
610                .write_all(b"HTTP/1.1 200 OK\r\n\r\n")
611                .await
612                .expect("proxy should write the CONNECT response");
613            // Complete the CONNECT tunnel but never speak TLS, so the request only fails if some
614            // deadline (mistakenly) bounds the handshake.
615            tokio::time::sleep(Duration::from_secs(30)).await;
616            drop(stream);
617        });
618
619        let proxy_uri: Uri = format!("http://{proxy_addr}").parse().expect("proxy URI should parse");
620        let mut client = HttpClient::builder()
621            .with_proxies(vec![Proxy::new(hyper_http_proxy::Intercept::All, proxy_uri)])
622            .with_tls_config(|builder| builder.with_root_cert_store(RootCertStore::empty()))
623            .with_tls_handshake_timeout(Duration::ZERO)
624            .with_http_protocol(HttpProtocol::Http1)
625            .build()
626            .expect("client should build");
627        let request = Request::get("https://example.invalid/")
628            .body(Empty::<Bytes>::new())
629            .expect("request should build");
630
631        // A zero handshake timeout means "disabled", so the request should still be pending well past
632        // the point where a mistakenly active zero-length deadline would have already failed it.
633        let result = timeout(Duration::from_millis(300), client.send(request)).await;
634        assert!(
635            result.is_err(),
636            "a disabled timeout should not fail the proxy tunnel's TLS handshake, got: {result:?}"
637        );
638
639        proxy_task.abort();
640    }
641
642    #[tokio::test]
643    async fn http2_protocol_sends_http2_to_a_plaintext_server() {
644        initialize_crypto_provider();
645        let (addr, mut seen_versions) = spawn_h2c_server().await;
646        let mut client = client_builder_without_roots(HttpProtocol::Http2)
647            .build()
648            .expect("client should build");
649
650        let response = send_empty_get(&mut client, &format!("http://{addr}/"))
651            .await
652            .expect("an HTTP/2 client should complete a request against an HTTP/2-only server");
653
654        assert_eq!(response.status(), http::StatusCode::OK);
655        assert_eq!(seen_versions.recv().await, Some(Version::HTTP_2));
656    }
657
658    #[tokio::test]
659    async fn http1_protocol_fails_against_an_http2_only_server() {
660        initialize_crypto_provider();
661        let (addr, mut seen_versions) = spawn_h2c_server().await;
662        let mut client = client_builder_without_roots(HttpProtocol::Http1)
663            .build()
664            .expect("client should build");
665
666        let result = send_empty_get(&mut client, &format!("http://{addr}/")).await;
667
668        assert!(
669            result.is_err(),
670            "an HTTP/1.1 client should fail against an HTTP/2-only server"
671        );
672        assert_eq!(seen_versions.try_recv(), Err(mpsc::error::TryRecvError::Empty));
673    }
674
675    #[cfg(unix)]
676    #[tokio::test]
677    async fn http2_protocol_sends_http2_over_a_unix_socket() {
678        initialize_crypto_provider();
679        let socket_dir = tempfile::tempdir().expect("should create temp dir");
680        let socket_path = socket_dir.path().join("h2.sock");
681        let listener = tokio::net::UnixListener::bind(&socket_path).expect("should bind Unix socket");
682        let (seen_tx, mut seen_versions) = mpsc::unbounded_channel();
683        tokio::spawn(async move {
684            loop {
685                let (stream, _) = listener.accept().await.expect("server should accept a connection");
686                tokio::spawn(serve_h2(stream, seen_tx.clone()));
687            }
688        });
689        let mut client = client_builder_without_roots(HttpProtocol::Http2)
690            .with_unix_socket_path(&socket_path)
691            .build()
692            .expect("client should build");
693
694        let response = send_empty_get(&mut client, "http://localhost/")
695            .await
696            .expect("an HTTP/2 client should complete a request over a Unix socket");
697
698        assert_eq!(response.status(), http::StatusCode::OK);
699        assert_eq!(seen_versions.recv().await, Some(Version::HTTP_2));
700    }
701
702    #[tokio::test]
703    async fn http2_protocol_negotiates_h2_over_tls() {
704        initialize_crypto_provider();
705        let server_cert = SelfSignedCert::localhost();
706        let mut server_config = ServerConfig::builder()
707            .with_no_client_auth()
708            .with_single_cert(server_cert.cert_chain(), server_cert.private_key())
709            .expect("server TLS config should build");
710        // The server also accepts HTTP/1.1, so it negotiates `h2` only if the client advertises it.
711        server_config.alpn_protocols = vec![b"http/1.1".to_vec(), b"h2".to_vec()];
712
713        let listener = TcpListener::bind("127.0.0.1:0").await.expect("should bind listener");
714        let port = listener.local_addr().expect("should have local address").port();
715        let (seen_tx, mut seen_versions) = mpsc::unbounded_channel();
716        let (alpn_tx, alpn_rx) = oneshot::channel();
717        tokio::spawn(async move {
718            let (stream, _) = listener.accept().await.expect("server should accept a connection");
719            let stream = TlsAcceptor::from(Arc::new(server_config))
720                .accept(stream)
721                .await
722                .expect("TLS handshake should succeed");
723            let _ = alpn_tx.send(stream.get_ref().1.alpn_protocol().map(ToOwned::to_owned));
724            serve_h2(stream, seen_tx).await;
725        });
726        let mut client = HttpClient::builder()
727            .with_tls_config(|builder| builder.with_root_cert_store(root_store(&server_cert)))
728            .with_http_protocol(HttpProtocol::Http2)
729            .build()
730            .expect("client should build");
731
732        let response = send_empty_get(&mut client, &format!("https://localhost:{port}/"))
733            .await
734            .expect("an HTTP/2 client should complete a request over TLS");
735
736        assert_eq!(response.status(), http::StatusCode::OK);
737        assert_eq!(alpn_rx.await.expect("server should report ALPN"), Some(b"h2".to_vec()));
738        assert_eq!(seen_versions.recv().await, Some(Version::HTTP_2));
739    }
740
741    #[tokio::test]
742    async fn http2_protocol_advertises_only_h2_through_a_proxy_tunnel() {
743        initialize_crypto_provider();
744
745        let listener = TcpListener::bind("127.0.0.1:0").await.expect("should bind listener");
746        let proxy_addr = listener.local_addr().expect("should have local address");
747        let (alpn_tx, alpn_rx) = oneshot::channel();
748        tokio::spawn(async move {
749            let (mut stream, _) = listener.accept().await.expect("proxy should accept a connection");
750            let mut request = [0; 4096];
751            let bytes_read = stream
752                .read(&mut request)
753                .await
754                .expect("proxy should read the CONNECT request");
755            assert!(bytes_read > 0, "proxy should receive a CONNECT request");
756            stream
757                .write_all(b"HTTP/1.1 200 OK\r\n\r\n")
758                .await
759                .expect("proxy should write the CONNECT response");
760            // Read the ClientHello, then drop the tunnel. The test needs only the offered ALPN protocols.
761            let handshake = LazyConfigAcceptor::new(rustls::server::Acceptor::default(), stream)
762                .await
763                .expect("tunnel should start a TLS handshake");
764            let offered_alpn: Vec<Vec<u8>> = handshake
765                .client_hello()
766                .alpn()
767                .map(|protocols| protocols.map(<[u8]>::to_vec).collect())
768                .unwrap_or_default();
769            let _ = alpn_tx.send(offered_alpn);
770        });
771
772        let proxy_uri: Uri = format!("http://{proxy_addr}").parse().expect("proxy URI should parse");
773        let mut client = client_builder_without_roots(HttpProtocol::Http2)
774            .with_proxies(vec![Proxy::new(hyper_http_proxy::Intercept::All, proxy_uri)])
775            .build()
776            .expect("client should build");
777
778        // The request fails because the proxy drops the tunnel.
779        let _ = send_empty_get(&mut client, "https://example.invalid/").await;
780
781        assert_eq!(alpn_rx.await.expect("proxy should report ALPN"), vec![b"h2".to_vec()]);
782    }
783
784    /// Returns a client builder that trusts no root certificates, so it builds without the platform root store.
785    fn client_builder_without_roots(protocol: HttpProtocol) -> HttpClientBuilder {
786        HttpClient::builder()
787            .with_tls_config(|builder| builder.with_root_cert_store(RootCertStore::empty()))
788            .with_http_protocol(protocol)
789    }
790
791    /// Serves HTTP/2 connections without TLS on an ephemeral port.
792    ///
793    /// Reports the HTTP version of each request that the server handles.
794    async fn spawn_h2c_server() -> (SocketAddr, mpsc::UnboundedReceiver<Version>) {
795        let listener = TcpListener::bind("127.0.0.1:0").await.expect("should bind listener");
796        let addr = listener.local_addr().expect("should have local address");
797        let (seen_tx, seen_versions) = mpsc::unbounded_channel();
798        tokio::spawn(async move {
799            loop {
800                let (stream, _) = listener.accept().await.expect("server should accept a connection");
801                tokio::spawn(serve_h2(stream, seen_tx.clone()));
802            }
803        });
804        (addr, seen_versions)
805    }
806
807    /// Answers each request on `io` with a 200 response, speaking only HTTP/2.
808    async fn serve_h2<T>(io: T, seen_versions: mpsc::UnboundedSender<Version>)
809    where
810        T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
811    {
812        let service = service_fn(move |request: Request<Incoming>| {
813            let _ = seen_versions.send(request.version());
814            async { Ok::<_, Infallible>(Response::new(Full::new(Bytes::from_static(b"ok")))) }
815        });
816
817        // A client that doesn't speak HTTP/2 fails the connection. Each test asserts on the client side.
818        let _ = http2::Builder::new(TokioExecutor::new())
819            .serve_connection(TokioIo::new(io), service)
820            .await;
821    }
822
823    async fn send_empty_get(client: &mut HttpClient, uri: &str) -> Result<Response<Incoming>, GenericError> {
824        let request = Request::get(uri)
825            .body(Empty::<Bytes>::new())
826            .expect("request should build");
827        timeout(Duration::from_secs(5), client.send(request))
828            .await
829            .map_err(|_| GenericError::msg("HTTP request timed out"))?
830    }
831
832    fn mutual_tls_configs() -> (ServerConfig, ClientConfig) {
833        let server_cert = SelfSignedCert::localhost();
834        let client_cert = SelfSignedCert::new(["saluki-client"]);
835        let client_verifier = WebPkiClientVerifier::builder(Arc::new(root_store(&client_cert)))
836            .build()
837            .expect("client certificate verifier should build");
838        let server_config = ServerConfig::builder()
839            .with_client_cert_verifier(client_verifier)
840            .with_single_cert(server_cert.cert_chain(), server_cert.private_key())
841            .expect("server TLS config should build");
842        let client_config = ClientConfig::builder()
843            .with_root_certificates(root_store(&server_cert))
844            .with_client_auth_cert(client_cert.cert_chain(), client_cert.private_key())
845            .expect("client TLS config should build");
846
847        (server_config, client_config)
848    }
849
850    fn root_store(cert: &SelfSignedCert) -> RootCertStore {
851        let mut root_store = RootCertStore::empty();
852        root_store
853            .add(cert.cert_chain().pop().expect("certificate chain should not be empty"))
854            .expect("self-signed certificate should be a valid trust anchor");
855        root_store
856    }
857
858    async fn send_request_to_tls_server(
859        builder: HttpClientBuilder, server_config: ServerConfig,
860    ) -> Result<Option<Vec<u8>>, GenericError> {
861        let listener = TcpListener::bind("127.0.0.1:0").await?;
862        let port = listener.local_addr()?.port();
863        let server_task = tokio::spawn(async move {
864            let (stream, _) = listener.accept().await.expect("server should accept a connection");
865            let mut stream = TlsAcceptor::from(Arc::new(server_config))
866                .accept(stream)
867                .await
868                .expect("TLS handshake should succeed");
869            let negotiated_alpn = stream.get_ref().1.alpn_protocol().map(ToOwned::to_owned);
870            let mut request = [0; 4096];
871            let bytes_read = stream.read(&mut request).await.expect("server should read the request");
872            assert!(bytes_read > 0, "server should receive an HTTP request");
873            stream
874                .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
875                .await
876                .expect("server should write the response");
877            negotiated_alpn
878        });
879
880        let mut client = builder.with_http_protocol(HttpProtocol::Http1).build()?;
881        let request = Request::get(format!("https://localhost:{port}/"))
882            .body(Empty::<Bytes>::new())
883            .expect("request should build");
884        let response = timeout(Duration::from_secs(5), client.send(request))
885            .await
886            .map_err(|_| GenericError::msg("HTTP request timed out"))??;
887        assert_eq!(response.status(), http::StatusCode::OK);
888        Ok(timeout(Duration::from_secs(5), server_task)
889            .await
890            .expect("TLS server should finish")
891            .expect("TLS server task should not panic"))
892    }
893}