Skip to main content

saluki_io/net/client/http/
conn.rs

1#[cfg(unix)]
2use std::path::PathBuf;
3use std::{
4    future::Future,
5    io,
6    pin::Pin,
7    sync::Arc,
8    task::{Context, Poll},
9    time::{Duration, Instant},
10};
11
12use http::{Extensions, Uri};
13use hyper_rustls::MaybeHttpsStream;
14use hyper_util::{
15    client::legacy::connect::{CaptureConnection, Connected, Connection, HttpConnector},
16    rt::TokioIo,
17};
18use pin_project_lite::pin_project;
19use rustls::{pki_types::ServerName, ClientConfig};
20use saluki_error::GenericError;
21use tokio::net::TcpStream;
22use tokio_rustls::TlsConnector;
23#[cfg(target_os = "linux")]
24use tokio_vsock::{VsockAddr, VsockStream};
25use tower::{BoxError, Service};
26use tracing::debug;
27
28use super::telemetry::HttpTransactionErrorTelemetry;
29use crate::net::dns::{DnsError, SystemHttpConnector, SystemResolver};
30
31/// Imposes a limit on the age of a connection.
32///
33/// In many cases, it's undesirable to hold onto a connection indefinitely, even if it can be theoretically reused.
34/// Doing so can make it more difficult to perform maintenance on infrastructure, as the expectation of old connections
35/// being eventually closed and replaced isn't upheld.
36///
37/// This extension allows tracking the age of a connection (based on when the connector creates the connection) and
38/// checking if it's expired, or past the configured limit. Callers can then decide how to handle the expiration, such
39/// as by closing the connection.
40#[derive(Clone)]
41struct ConnectionAgeLimit {
42    limit: Duration,
43    created: Instant,
44}
45
46impl ConnectionAgeLimit {
47    fn new(limit: Duration) -> Self {
48        ConnectionAgeLimit {
49            limit,
50            created: Instant::now(),
51        }
52    }
53
54    fn is_expired(&self) -> bool {
55        self.created.elapsed() >= self.limit
56    }
57}
58
59/// An inner transport that abstracts over TCP, Unix domain socket, and vsock connections.
60///
61/// This allows using a single monomorphization of the HTTP/2 and TLS stacks regardless of the
62/// underlying transport, avoiding duplicate code generation for each transport type.
63enum Transport {
64    Tcp(TokioIo<TcpStream>),
65    #[cfg(unix)]
66    Unix(TokioIo<tokio::net::UnixStream>),
67    #[cfg(target_os = "linux")]
68    Vsock(TokioIo<VsockStream>),
69}
70
71impl Connection for Transport {
72    fn connected(&self) -> Connected {
73        match self {
74            Self::Tcp(s) => s.connected(),
75            #[cfg(unix)]
76            Self::Unix(_) => Connected::new(),
77            #[cfg(target_os = "linux")]
78            Self::Vsock(_) => Connected::new(),
79        }
80    }
81}
82
83impl hyper::rt::Read for Transport {
84    fn poll_read(
85        self: Pin<&mut Self>, cx: &mut Context<'_>, buf: hyper::rt::ReadBufCursor<'_>,
86    ) -> Poll<io::Result<()>> {
87        match Pin::get_mut(self) {
88            Self::Tcp(s) => Pin::new(s).poll_read(cx, buf),
89            #[cfg(unix)]
90            Self::Unix(s) => Pin::new(s).poll_read(cx, buf),
91            #[cfg(target_os = "linux")]
92            Self::Vsock(s) => Pin::new(s).poll_read(cx, buf),
93        }
94    }
95}
96
97impl hyper::rt::Write for Transport {
98    fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
99        match Pin::get_mut(self) {
100            Self::Tcp(s) => Pin::new(s).poll_write(cx, buf),
101            #[cfg(unix)]
102            Self::Unix(s) => Pin::new(s).poll_write(cx, buf),
103            #[cfg(target_os = "linux")]
104            Self::Vsock(s) => Pin::new(s).poll_write(cx, buf),
105        }
106    }
107
108    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
109        match Pin::get_mut(self) {
110            Self::Tcp(s) => Pin::new(s).poll_flush(cx),
111            #[cfg(unix)]
112            Self::Unix(s) => Pin::new(s).poll_flush(cx),
113            #[cfg(target_os = "linux")]
114            Self::Vsock(s) => Pin::new(s).poll_flush(cx),
115        }
116    }
117
118    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
119        match Pin::get_mut(self) {
120            Self::Tcp(s) => Pin::new(s).poll_shutdown(cx),
121            #[cfg(unix)]
122            Self::Unix(s) => Pin::new(s).poll_shutdown(cx),
123            #[cfg(target_os = "linux")]
124            Self::Vsock(s) => Pin::new(s).poll_shutdown(cx),
125        }
126    }
127
128    fn is_write_vectored(&self) -> bool {
129        match self {
130            Self::Tcp(s) => s.is_write_vectored(),
131            #[cfg(unix)]
132            Self::Unix(s) => s.is_write_vectored(),
133            #[cfg(target_os = "linux")]
134            Self::Vsock(s) => s.is_write_vectored(),
135        }
136    }
137
138    fn poll_write_vectored(
139        self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>],
140    ) -> Poll<io::Result<usize>> {
141        match Pin::get_mut(self) {
142            Self::Tcp(s) => Pin::new(s).poll_write_vectored(cx, bufs),
143            #[cfg(unix)]
144            Self::Unix(s) => Pin::new(s).poll_write_vectored(cx, bufs),
145            #[cfg(target_os = "linux")]
146            Self::Vsock(s) => Pin::new(s).poll_write_vectored(cx, bufs),
147        }
148    }
149}
150
151pin_project! {
152    /// A connection that supports both HTTP and HTTPS.
153    pub struct HttpsCapableConnection {
154        #[pin]
155        inner: MaybeHttpsStream<Transport>,
156        error_telemetry: Option<HttpTransactionErrorTelemetry>,
157        conn_age_limit: Option<Duration>,
158    }
159}
160
161impl Connection for HttpsCapableConnection {
162    fn connected(&self) -> Connected {
163        let connected = self.inner.connected();
164
165        if let Some(conn_age_limit) = self.conn_age_limit {
166            debug!("setting connection age limit to {:?}", conn_age_limit);
167            connected.extra(ConnectionAgeLimit::new(conn_age_limit))
168        } else {
169            connected
170        }
171    }
172}
173
174impl hyper::rt::Read for HttpsCapableConnection {
175    fn poll_read(
176        self: Pin<&mut Self>, cx: &mut Context<'_>, buf: hyper::rt::ReadBufCursor<'_>,
177    ) -> Poll<io::Result<()>> {
178        let this = self.project();
179        this.inner.poll_read(cx, buf)
180    }
181}
182
183impl hyper::rt::Write for HttpsCapableConnection {
184    fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
185        let this = self.project();
186        match this.inner.poll_write(cx, buf) {
187            Poll::Ready(Ok(n)) => Poll::Ready(Ok(n)),
188            Poll::Ready(Err(error)) => {
189                if let Some(error_telemetry) = this.error_telemetry.as_ref() {
190                    error_telemetry.increment_wrote_request_error();
191                }
192                Poll::Ready(Err(error))
193            }
194            other => other,
195        }
196    }
197
198    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
199        let this = self.project();
200        match this.inner.poll_flush(cx) {
201            Poll::Ready(Err(error)) => {
202                if let Some(error_telemetry) = this.error_telemetry.as_ref() {
203                    error_telemetry.increment_wrote_request_error();
204                }
205                Poll::Ready(Err(error))
206            }
207            other => other,
208        }
209    }
210
211    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
212        let this = self.project();
213        this.inner.poll_shutdown(cx)
214    }
215
216    fn is_write_vectored(&self) -> bool {
217        self.inner.is_write_vectored()
218    }
219
220    fn poll_write_vectored(
221        self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>],
222    ) -> Poll<io::Result<usize>> {
223        let this = self.project();
224        match this.inner.poll_write_vectored(cx, bufs) {
225            Poll::Ready(Ok(n)) => Poll::Ready(Ok(n)),
226            Poll::Ready(Err(error)) => {
227                if let Some(error_telemetry) = this.error_telemetry.as_ref() {
228                    error_telemetry.increment_wrote_request_error();
229                }
230                Poll::Ready(Err(error))
231            }
232            other => other,
233        }
234    }
235}
236
237/// An inner connector that routes to TCP (via DNS), a Unix domain socket, or a vsock socket.
238///
239/// When a Unix socket path is configured, all connections are routed through that socket regardless
240/// of the URI host. When a vsock CID is configured, all connections are routed through that vsock
241/// socket using the port from the destination URI. Otherwise, connections use the standard DNS +
242/// TCP path.
243#[derive(Clone)]
244struct InnerConnector {
245    http: SystemHttpConnector,
246    #[cfg(unix)]
247    connect_timeout: Duration,
248    error_telemetry: Option<HttpTransactionErrorTelemetry>,
249    #[cfg(unix)]
250    unix_socket_path: Option<Arc<std::path::Path>>,
251    #[cfg(target_os = "linux")]
252    vsock_addr: Option<VsockAddr>,
253}
254
255impl Service<Uri> for InnerConnector {
256    type Response = Transport;
257    type Error = BoxError;
258    type Future = Pin<Box<dyn Future<Output = Result<Transport, BoxError>> + Send>>;
259
260    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
261        // When routing via vsock or a Unix domain socket, the TCP/DNS connector is not used, so we
262        // consider the service immediately ready. vsock takes priority over Unix (matching Agent
263        // behavior) when both are configured.
264        #[cfg(target_os = "linux")]
265        if self.vsock_addr.is_some() {
266            return Poll::Ready(Ok(()));
267        }
268
269        #[cfg(unix)]
270        if self.unix_socket_path.is_some() {
271            return Poll::Ready(Ok(()));
272        }
273
274        self.http.poll_ready(cx).map_err(Into::into)
275    }
276
277    fn call(&mut self, dst: Uri) -> Self::Future {
278        #[cfg(target_os = "linux")]
279        if let Some(addr) = self.vsock_addr {
280            let connect_timeout = self.connect_timeout;
281            let error_telemetry = self.error_telemetry.clone();
282            return Box::pin(async move {
283                let stream = tokio::time::timeout(connect_timeout, VsockStream::connect(addr))
284                    .await
285                    .map_err(|_| -> BoxError {
286                        if let Some(error_telemetry) = &error_telemetry {
287                            error_telemetry.increment_connection_error();
288                        }
289                        Box::new(io::Error::new(io::ErrorKind::TimedOut, "vsock connect timed out"))
290                    })?
291                    .map_err(|e| -> BoxError {
292                        if let Some(error_telemetry) = &error_telemetry {
293                            error_telemetry.increment_connection_error();
294                        }
295                        Box::new(e)
296                    })?;
297                Ok(Transport::Vsock(TokioIo::new(stream)))
298            });
299        }
300
301        #[cfg(unix)]
302        if let Some(path) = self.unix_socket_path.clone() {
303            let connect_timeout = self.connect_timeout;
304            let error_telemetry = self.error_telemetry.clone();
305            return Box::pin(async move {
306                let stream = tokio::time::timeout(connect_timeout, tokio::net::UnixStream::connect(&*path))
307                    .await
308                    .map_err(|_| -> BoxError {
309                        if let Some(error_telemetry) = &error_telemetry {
310                            error_telemetry.increment_connection_error();
311                        }
312                        Box::new(io::Error::new(io::ErrorKind::TimedOut, "unix socket connect timed out"))
313                    })?
314                    .map_err(|e| -> BoxError {
315                        if let Some(error_telemetry) = &error_telemetry {
316                            error_telemetry.increment_connection_error();
317                        }
318                        Box::new(e)
319                    })?;
320                Ok(Transport::Unix(TokioIo::new(stream)))
321            });
322        }
323
324        let fut = self.http.call(dst);
325        let error_telemetry = self.error_telemetry.clone();
326        Box::pin(async move {
327            let tcp = fut.await.map_err(|error| {
328                if !is_dns_error(&error) {
329                    if let Some(error_telemetry) = &error_telemetry {
330                        error_telemetry.increment_connection_error();
331                    }
332                }
333                BoxError::from(error)
334            })?;
335            Ok(Transport::Tcp(tcp))
336        })
337    }
338}
339
340/// HTTP protocol selection for client connections.
341#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
342pub enum HttpProtocol {
343    /// Automatically negotiate HTTP/2 with HTTP/1.1 fallback.
344    #[default]
345    Auto,
346
347    /// Use HTTP/1.1 only.
348    Http1,
349
350    /// Use HTTP/2 only, with no HTTP/1.1 fallback.
351    ///
352    /// TLS connections advertise only `h2` through ALPN. [`HttpClientBuilder`](super::HttpClientBuilder) speaks HTTP/2
353    /// with prior knowledge (h2c) on plaintext connections.
354    Http2,
355}
356
357/// A connector that supports HTTP or HTTPS.
358///
359/// Unlike [`hyper_rustls::HttpsConnector`], which fuses the transport connect and TLS handshake into a single
360/// opaque future, this connector performs them as two distinct steps. That split allows a timeout to be scoped to
361/// just the handshake, rather than the combined connect-and-handshake duration.
362#[derive(Clone)]
363pub struct HttpsCapableConnector {
364    inner: InnerConnector,
365    tls_config: Arc<ClientConfig>,
366    tls_handshake_timeout: Duration,
367    error_telemetry: Option<HttpTransactionErrorTelemetry>,
368    conn_age_limit: Option<Duration>,
369}
370
371impl HttpsCapableConnector {
372    /// Returns the timeout applied to the TLS handshake for HTTPS connections.
373    pub(crate) fn tls_handshake_timeout(&self) -> Duration {
374        self.tls_handshake_timeout
375    }
376}
377
378impl Service<Uri> for HttpsCapableConnector {
379    type Response = HttpsCapableConnection;
380    type Error = BoxError;
381    type Future = Pin<Box<dyn Future<Output = Result<HttpsCapableConnection, BoxError>> + Send>>;
382
383    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
384        self.inner.poll_ready(cx)
385    }
386
387    fn call(&mut self, dst: Uri) -> Self::Future {
388        let is_https = match dst.scheme_str() {
389            Some("https") => true,
390            Some("http") => false,
391            scheme => {
392                let scheme = scheme.map(str::to_owned);
393                return Box::pin(async move {
394                    Err(Box::new(io::Error::new(
395                        io::ErrorKind::InvalidInput,
396                        format!("unsupported URI scheme: {scheme:?}"),
397                    )) as BoxError)
398                });
399            }
400        };
401        let transport_fut = self.inner.call(dst.clone());
402        let tls_config = Arc::clone(&self.tls_config);
403        let tls_handshake_timeout = self.tls_handshake_timeout;
404        let error_telemetry = self.error_telemetry.clone();
405        let conn_age_limit = self.conn_age_limit;
406
407        Box::pin(async move {
408            let transport = transport_fut.await?;
409
410            let inner = if is_https {
411                let host = dst.host().ok_or_else(|| -> BoxError {
412                    Box::new(io::Error::new(io::ErrorKind::InvalidInput, "URI has no host"))
413                })?;
414                let host = strip_ipv6_brackets(host);
415                let server_name = ServerName::try_from(host)
416                    .map_err(|error| -> BoxError { Box::new(error) })?
417                    .to_owned();
418
419                let handshake = TlsConnector::from(tls_config).connect(server_name, TokioIo::new(transport));
420
421                match await_handshake_with_deadline(tls_handshake_timeout, handshake).await {
422                    Ok(stream) => MaybeHttpsStream::from(stream),
423                    Err(error) => {
424                        if let Some(error_telemetry) = &error_telemetry {
425                            error_telemetry.increment_tls_error();
426                        }
427                        return Err(error);
428                    }
429                }
430            } else {
431                MaybeHttpsStream::from(transport)
432            };
433
434            Ok(HttpsCapableConnection {
435                inner,
436                error_telemetry,
437                conn_age_limit,
438            })
439        })
440    }
441}
442
443/// Strips the surrounding brackets from a bracketed IPv6 host, as found in a URI authority.
444///
445/// [`rustls::pki_types::ServerName`] accepts unbracketed IPv6 addresses but rejects the bracketed form that
446/// [`http::Uri::host`] returns (for example, `[::1]`), so this normalizes the host before constructing the server name.
447fn strip_ipv6_brackets(host: &str) -> &str {
448    host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host)
449}
450
451/// Awaits a TLS handshake future, bounding it by `timeout` unless `timeout` is zero.
452///
453/// A zero duration means the handshake deadline is disabled.
454/// `tokio::time::timeout` with a zero duration fires immediately rather than never, so that case is handled by
455/// awaiting the handshake directly instead of wrapping it in a timeout.
456async fn await_handshake_with_deadline<F, T, E>(timeout: Duration, handshake: F) -> Result<T, BoxError>
457where
458    F: Future<Output = Result<T, E>>,
459    E: std::error::Error + Send + Sync + 'static,
460{
461    if timeout.is_zero() {
462        return handshake.await.map_err(|error| Box::new(error) as BoxError);
463    }
464
465    match tokio::time::timeout(timeout, handshake).await {
466        Ok(result) => result.map_err(|error| Box::new(error) as BoxError),
467        Err(_) => Err(Box::new(io::Error::new(io::ErrorKind::TimedOut, "TLS handshake timed out")) as BoxError),
468    }
469}
470
471fn build_dns_resolver(error_telemetry: &Option<HttpTransactionErrorTelemetry>) -> SystemResolver {
472    let mut r = SystemResolver::new();
473    if let Some(et) = error_telemetry {
474        r = r.with_lookup_errors_counter(et.dns_errors());
475    }
476    r
477}
478
479/// A builder for `HttpsCapableConnector`.
480#[derive(Default)]
481pub struct HttpsCapableConnectorBuilder {
482    connect_timeout: Option<Duration>,
483    tls_handshake_timeout: Option<Duration>,
484    error_telemetry: Option<HttpTransactionErrorTelemetry>,
485    conn_age_limit: Option<Duration>,
486    pub(super) http_protocol: HttpProtocol,
487    #[cfg(unix)]
488    unix_socket_path: Option<PathBuf>,
489    #[cfg(target_os = "linux")]
490    vsock_addr: Option<VsockAddr>,
491}
492
493impl HttpsCapableConnectorBuilder {
494    /// Sets the timeout when connecting to the remote host.
495    ///
496    /// Defaults to 30 seconds.
497    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
498        self.connect_timeout = Some(timeout);
499        self
500    }
501
502    /// Sets the timeout for completing the TLS handshake after a connection is established.
503    ///
504    /// Defaults to 10 seconds.
505    pub fn with_tls_handshake_timeout(mut self, timeout: Duration) -> Self {
506        self.tls_handshake_timeout = Some(timeout);
507        self
508    }
509
510    /// Sets the HTTP protocol selection for client connections.
511    ///
512    /// Defaults to [`HttpProtocol::Auto`].
513    pub fn with_http_protocol(mut self, protocol: HttpProtocol) -> Self {
514        self.http_protocol = protocol;
515        self
516    }
517
518    /// Sets the maximum age of a connection before it's closed.
519    ///
520    /// This is distinct from the maximum idle time: if any connection's age exceeds `limit`, it will be closed rather
521    /// than being reused and added to the idle connection pool.
522    ///
523    /// Defaults to no limit.
524    pub fn with_connection_age_limit<L>(mut self, limit: L) -> Self
525    where
526        L: Into<Option<Duration>>,
527    {
528        self.conn_age_limit = limit.into();
529        self
530    }
531
532    /// Sets the telemetry counters used to track HTTP request lifecycle failures.
533    pub(super) fn with_error_telemetry(mut self, error_telemetry: HttpTransactionErrorTelemetry) -> Self {
534        self.error_telemetry = Some(error_telemetry);
535        self
536    }
537
538    /// Sets a Unix domain socket path to route all connections through.
539    ///
540    /// When set, the connector will connect to this Unix socket instead of performing DNS resolution
541    /// and TCP connection. The URI host is ignored in this case—all requests are sent through the
542    /// configured socket.
543    ///
544    /// Defaults to unset (TCP connections via DNS).
545    #[cfg(unix)]
546    pub fn with_unix_socket_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
547        self.unix_socket_path = Some(path.into());
548        self
549    }
550
551    /// Sets a vsock address to route all connections through.
552    ///
553    /// When set, the connector will connect via AF_VSOCK using the given address, bypassing
554    /// DNS and TCP. This allows connecting to a server process running in a host or hypervisor
555    /// context from within a guest VM (for example, Nitro Enclaves).
556    ///
557    /// Defaults to unset (TCP connections via DNS).
558    #[cfg(target_os = "linux")]
559    pub fn with_vsock_addr(mut self, addr: VsockAddr) -> Self {
560        self.vsock_addr = Some(addr);
561        self
562    }
563
564    /// Builds the `HttpsCapableConnector` from the given TLS configuration.
565    pub fn build(self, mut tls_config: ClientConfig) -> Result<HttpsCapableConnector, GenericError> {
566        let connect_timeout = self.connect_timeout.unwrap_or(Duration::from_secs(30));
567        let tls_handshake_timeout = self.tls_handshake_timeout.unwrap_or(Duration::from_secs(10));
568
569        // Create the HTTP connector, and ensure that we don't enforce _only_ HTTP, since that will break being able to
570        // wrap this in an HTTPS connector.
571        let mut http_connector = HttpConnector::new_with_resolver(build_dns_resolver(&self.error_telemetry));
572        http_connector.set_connect_timeout(Some(connect_timeout));
573        http_connector.enforce_http(false);
574
575        let inner_connector = InnerConnector {
576            http: http_connector,
577            #[cfg(unix)]
578            connect_timeout,
579            error_telemetry: self.error_telemetry.clone(),
580            #[cfg(unix)]
581            unix_socket_path: self.unix_socket_path.map(PathBuf::into_boxed_path).map(Arc::from),
582            #[cfg(target_os = "linux")]
583            vsock_addr: self.vsock_addr,
584        };
585
586        tls_config.alpn_protocols = http_protocol_alpns(self.http_protocol);
587
588        Ok(HttpsCapableConnector {
589            inner: inner_connector,
590            tls_config: Arc::new(tls_config),
591            tls_handshake_timeout,
592            error_telemetry: self.error_telemetry,
593            conn_age_limit: self.conn_age_limit,
594        })
595    }
596}
597
598/// Selects the ALPN protocols to advertise for the given HTTP protocol.
599pub(super) fn http_protocol_alpns(protocol: HttpProtocol) -> Vec<Vec<u8>> {
600    match protocol {
601        HttpProtocol::Auto => vec![b"h2".to_vec(), b"http/1.1".to_vec()],
602        HttpProtocol::Http1 => Vec::new(),
603        HttpProtocol::Http2 => vec![b"h2".to_vec()],
604    }
605}
606
607fn is_dns_error(error: &(dyn std::error::Error + 'static)) -> bool {
608    let mut current = Some(error);
609    while let Some(error) = current {
610        if error.downcast_ref::<DnsError>().is_some() {
611            return true;
612        }
613        current = error.source();
614    }
615    false
616}
617
618pub(super) fn check_connection_state(captured_conn: CaptureConnection) {
619    let maybe_conn_metadata = captured_conn.connection_metadata();
620    if let Some(conn_metadata) = maybe_conn_metadata.as_ref() {
621        let mut extensions = Extensions::new();
622        conn_metadata.get_extras(&mut extensions);
623
624        // If the connection has an age limit, check to see if the connection is expired (i.e. too old) and "poison"
625        // it if so. Poisoning indicates to `hyper` that the connection should be closed/dropped instead of
626        // returning it back to the idle connection pool.
627        if let Some(conn_age_limit) = extensions.get::<ConnectionAgeLimit>() {
628            if conn_age_limit.is_expired() {
629                debug!("connection is expired; poisoning it");
630                conn_metadata.poison();
631            }
632        }
633    }
634}
635
636#[cfg(test)]
637mod tests {
638    use std::{io, time::Duration};
639
640    use super::{await_handshake_with_deadline, http_protocol_alpns, HttpProtocol};
641
642    #[tokio::test(start_paused = true)]
643    async fn handshake_deadline_of_zero_disables_the_timeout() {
644        let handshake = async {
645            tokio::time::sleep(Duration::from_secs(3600)).await;
646            Ok::<_, io::Error>(())
647        };
648
649        let result = await_handshake_with_deadline(Duration::ZERO, handshake).await;
650        assert!(result.is_ok());
651    }
652
653    #[tokio::test(start_paused = true)]
654    async fn handshake_deadline_times_out_when_exceeded() {
655        let handshake = async {
656            tokio::time::sleep(Duration::from_secs(3600)).await;
657            Ok::<_, io::Error>(())
658        };
659
660        let result = await_handshake_with_deadline(Duration::from_secs(10), handshake).await;
661        let error = result.expect_err("expected handshake to time out");
662        assert!(error.to_string().contains("TLS handshake timed out"));
663    }
664
665    #[tokio::test]
666    async fn handshake_deadline_propagates_success() {
667        let handshake = async { Ok::<_, io::Error>(42) };
668
669        let result = await_handshake_with_deadline(Duration::from_secs(10), handshake).await;
670        assert_eq!(result.unwrap(), 42);
671    }
672
673    #[test]
674    fn strip_ipv6_brackets_unwraps_bracketed_addresses() {
675        use super::strip_ipv6_brackets;
676
677        assert_eq!(strip_ipv6_brackets("[::1]"), "::1");
678        assert_eq!(strip_ipv6_brackets("[2001:db8::1]"), "2001:db8::1");
679    }
680
681    #[test]
682    fn strip_ipv6_brackets_leaves_unbracketed_hosts_alone() {
683        use super::strip_ipv6_brackets;
684
685        assert_eq!(strip_ipv6_brackets("example.com"), "example.com");
686        assert_eq!(strip_ipv6_brackets("::1"), "::1");
687    }
688
689    #[cfg(unix)]
690    #[tokio::test]
691    async fn call_rejects_unsupported_uri_scheme() {
692        use std::sync::Arc;
693
694        use rustls::{ClientConfig, RootCertStore};
695        use tower::Service as _;
696
697        use super::{HttpsCapableConnector, InnerConnector};
698        use crate::net::dns::SystemResolver;
699
700        let inner = InnerConnector {
701            http: SystemResolver::new().into_http_connector(),
702            connect_timeout: Duration::from_secs(1),
703            error_telemetry: None,
704            unix_socket_path: None,
705            #[cfg(target_os = "linux")]
706            vsock_addr: None,
707        };
708
709        let tls_config = Arc::new(
710            ClientConfig::builder()
711                .with_root_certificates(RootCertStore::empty())
712                .with_no_client_auth(),
713        );
714
715        let mut connector = HttpsCapableConnector {
716            inner,
717            tls_config,
718            tls_handshake_timeout: Duration::from_secs(1),
719            error_telemetry: None,
720            conn_age_limit: None,
721        };
722
723        let uri: http::Uri = "ftp://example.com/".parse().unwrap();
724        let error = connector.call(uri).await.err().expect("expected scheme to be rejected");
725        assert!(error.to_string().contains("unsupported URI scheme"));
726    }
727
728    #[test]
729    fn auto_protocol_advertises_h2_and_http1_alpn() {
730        let alpn_protocols = http_protocol_alpns(HttpProtocol::Auto);
731
732        assert_eq!(alpn_protocols, vec![b"h2".to_vec(), b"http/1.1".to_vec()]);
733    }
734
735    #[test]
736    fn http1_protocol_leaves_alpn_empty() {
737        let alpn_protocols = http_protocol_alpns(HttpProtocol::Http1);
738
739        assert!(alpn_protocols.is_empty());
740    }
741
742    #[test]
743    fn http2_protocol_advertises_only_h2_alpn() {
744        let alpn_protocols = http_protocol_alpns(HttpProtocol::Http2);
745
746        assert_eq!(alpn_protocols, vec![b"h2".to_vec()]);
747    }
748
749    // vsock takes priority over unix when both are configured, matching Agent behavior.
750    // We verify by checking the error does not mention "unix" — if unix had priority it would
751    // fail with a socket-path error; vsock produces a connection or device error instead.
752    #[cfg(target_os = "linux")]
753    #[tokio::test]
754    async fn vsock_takes_priority_over_unix_when_both_set() {
755        use std::sync::Arc;
756
757        use tower::Service as _;
758
759        use super::{InnerConnector, VsockAddr};
760        use crate::net::dns::SystemResolver;
761
762        let mut connector = InnerConnector {
763            http: SystemResolver::new().into_http_connector(),
764            connect_timeout: std::time::Duration::from_secs(1),
765            error_telemetry: None,
766            unix_socket_path: Some(Arc::from(std::path::Path::new("/tmp/test.sock"))),
767            vsock_addr: Some(VsockAddr::new(2, 5001)),
768        };
769
770        // Verify vsock path was taken: if unix had priority the error would mention the socket
771        // path or "unix"; a vsock attempt produces a connection or device error instead.
772        let uri: http::Uri = "https://127.0.0.1:5001/".parse().unwrap();
773        let err = connector.call(uri).await.err().expect("expected a connection error");
774        assert!(
775            !err.to_string().contains("unix"),
776            "expected vsock error (not unix socket error), got: {err}"
777        );
778    }
779}