Skip to main content

ntex_tls/rustls/
connect.rs

1//! Client service that composes transport establishment with a rustls handshake.
2use std::{fmt, io, sync::Arc};
3
4use ntex_error::Error;
5use ntex_io::{Filter, Io, Layer};
6use ntex_net::connect::{Address, Connect, ConnectError, Connector};
7use ntex_service::{Ctx, IntoService, Service, cfg::SharedCfg};
8use tls_rustls::{ClientConfig, pki_types::ServerName};
9
10use crate::{TlsConfig, rustls::TlsClientFilter};
11
12/// Opens a transport and upgrades it to client-side TLS using rustls.
13///
14/// The service accepts [`Connect`] requests with [`SharedCfg`] state. It strips
15/// ports and IPv6 brackets from the request host for rustls server-name handling.
16/// The supplied [`ClientConfig`] determines trust, client identity, and ALPN.
17///
18/// Binding, readiness, and shutdown are forwarded to the underlying connector.
19/// The [`TlsConfig`] timeout starts after that connector returns, so it does not
20/// bound DNS resolution or TCP connection establishment. Handshake errors are
21/// returned as [`ConnectError`] with the TLS configuration's service identity.
22pub struct TlsConnector<S> {
23    /// Service responsible for producing the underlying, possibly filtered, I/O.
24    svc: S,
25    /// Shared TLS policy and session configuration.
26    config: Arc<ClientConfig>,
27}
28
29impl<A: Address> TlsConnector<Connector<A>> {
30    /// Creates a TLS connector using the default network connector.
31    ///
32    /// Use the `From<Arc<ClientConfig>>` implementation to share an existing
33    /// rustls configuration instead of transferring an owned value.
34    pub fn new(config: ClientConfig) -> Self {
35        TlsConnector::from(Arc::new(config))
36    }
37
38    /// Replaces the default transport connector without changing the TLS policy.
39    ///
40    /// The replacement receives the original request and shared service state.
41    /// Any filters on its returned I/O remain below TLS.
42    pub fn connector<F, S>(self, f: impl IntoService<S, SharedCfg, Connect<A>>) -> TlsConnector<S>
43    where
44        S: Service<SharedCfg, Connect<A>, Res = Io<F>, Error = Error<ConnectError>>,
45    {
46        TlsConnector {
47            svc: f.into_service(),
48            config: self.config,
49        }
50    }
51}
52
53impl<A: Address> From<Arc<ClientConfig>> for TlsConnector<Connector<A>> {
54    fn from(config: Arc<ClientConfig>) -> Self {
55        TlsConnector {
56            config,
57            svc: Connector::default(),
58        }
59    }
60}
61
62impl<'a, A: Address> From<&'a Arc<ClientConfig>> for TlsConnector<Connector<A>> {
63    fn from(config: &'a Arc<ClientConfig>) -> Self {
64        TlsConnector {
65            config: config.clone(),
66            svc: Connector::default(),
67        }
68    }
69}
70
71impl<S: Clone> Clone for TlsConnector<S> {
72    fn clone(&self) -> Self {
73        Self {
74            svc: self.svc.clone(),
75            config: self.config.clone(),
76        }
77    }
78}
79
80impl<S: fmt::Debug> fmt::Debug for TlsConnector<S> {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.debug_struct("TlsConnector(rustls)")
83            .field("svc", &self.svc)
84            .finish()
85    }
86}
87
88impl<F: Filter, A: Address, S> Service<SharedCfg, Connect<A>> for TlsConnector<S>
89where
90    S: Service<SharedCfg, Connect<A>, Res = Io<F>, Error = Error<ConnectError>>,
91{
92    type Res = Io<Layer<TlsClientFilter, F>>;
93    type Error = Error<ConnectError>;
94
95    /// Establishes transport first, then validates the server name and times the TLS handshake.
96    async fn call(
97        &self,
98        req: Connect<A>,
99        ctx: Ctx<'_, Self, SharedCfg>,
100    ) -> Result<Self::Res, Self::Error> {
101        let cfg = ctx.st().get::<TlsConfig>();
102        let host = crate::utils::server_name(req.host()).to_owned();
103
104        let io = ctx.call(&self.svc, req).await?;
105        crate::utils::connect(&cfg, &host, async {
106            let name = ServerName::try_from(host.as_str()).map_err(io::Error::other)?;
107            TlsClientFilter::create(io, self.config.clone(), name.to_owned()).await
108        })
109        .await
110    }
111
112    ntex_service::forward!(SharedCfg, svc);
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    use ntex_service::Pipeline;
120    use ntex_util::future::lazy;
121    use tls_rustls::RootCertStore;
122
123    /// STATEMENT: A rustls connector is ready but reports failure against a non-TLS peer.
124    ///
125    /// HOW:
126    /// - Build and clone connectors from owned and shared configuration and check the debug name.
127    /// - Check immediate readiness, then assert a call to a transport-dropping local service fails.
128    #[ntex::test]
129    async fn test_rustls_connect() {
130        let server = ntex::server::test_server(async |()| {
131            ntex::service::fn_service(async |_| Ok::<_, ()>(()))
132        });
133
134        let cert_store = webpki_roots::TLS_SERVER_ROOTS
135            .iter()
136            .cloned()
137            .collect::<RootCertStore>();
138        let config = ClientConfig::builder()
139            .with_root_certificates(cert_store)
140            .with_no_client_auth();
141        let _: TlsConnector<Connector<&'static str>> = TlsConnector::new(config.clone()).clone();
142        let svc = TlsConnector::from(Arc::new(config)).clone();
143        assert!(format!("{svc:?}").contains("TlsConnector"), "{svc:?}");
144
145        let srv = Pipeline::new(SharedCfg::default(), svc);
146        // always ready
147        assert!(lazy(|cx| srv.poll_ready(cx)).await.is_ready());
148        let result = srv
149            .call(Connect::new("").set_addr(Some(server.addr())))
150            .await;
151        assert!(result.is_err());
152    }
153}