Skip to main content

ntex_tls/openssl/
connect.rs

1//! Client service that composes transport establishment with an OpenSSL handshake.
2use std::io;
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_openssl::ssl::SslConnector as OpensslConnector;
9
10use crate::{TlsConfig, openssl::SslFilter};
11
12#[derive(Clone, Debug)]
13/// Opens a transport and upgrades it to client-side TLS using OpenSSL.
14///
15/// Accepts [`Connect`] requests with [`SharedCfg`] service state. Binding,
16/// readiness, and shutdown are forwarded to the underlying transport connector.
17/// The [`TlsConfig`] timeout covers TLS negotiation after transport establishment,
18/// not DNS resolution or TCP connection setup.
19///
20/// The service strips ports and IPv6 brackets before configuring the OpenSSL
21/// session's host. Verification, client identity, and ALPN otherwise follow the
22/// supplied OpenSSL connector.
23pub struct SslConnector<S> {
24    /// Service responsible for producing the underlying I/O.
25    svc: S,
26    /// OpenSSL policy used to configure each client session.
27    openssl: OpensslConnector,
28}
29
30impl<A: Address> SslConnector<Connector<A>> {
31    /// Creates a TLS connector using the default network connector.
32    pub fn new(openssl: OpensslConnector) -> Self {
33        SslConnector {
34            openssl,
35            svc: Connector::default(),
36        }
37    }
38
39    /// Replaces the default transport connector without changing the TLS policy.
40    ///
41    /// The replacement receives the original request and shared service state.
42    /// Any filters on its returned I/O remain below TLS.
43    pub fn connector<F, S>(self, f: impl IntoService<S, SharedCfg, Connect<A>>) -> SslConnector<S>
44    where
45        S: Service<SharedCfg, Connect<A>, Res = Io<F>, Error = Error<ConnectError>>,
46    {
47        SslConnector {
48            svc: f.into_service(),
49            openssl: self.openssl,
50        }
51    }
52}
53
54impl<S> SslConnector<S> {
55    /// Completes a client handshake over existing I/O using this connector's TLS policy.
56    ///
57    /// Does not call the underlying transport service. `host` is passed directly
58    /// to OpenSSL for server-name and verification configuration: supply a DNS
59    /// name or IP address without a port or IPv6 brackets. Existing filters are
60    /// preserved, and the handshake timeout comes from `cfg`'s [`TlsConfig`].
61    ///
62    /// # Errors
63    ///
64    /// OpenSSL configuration failures become [`io::ErrorKind::InvalidInput`].
65    /// Configuration, handshake, timeout, and transport failures are wrapped as
66    /// [`ConnectError`] and tagged with the TLS configuration's service identity.
67    pub async fn connect<F: Filter>(
68        &self,
69        io: Io<F>,
70        host: &str,
71        cfg: &SharedCfg,
72    ) -> Result<Io<Layer<SslFilter, F>>, Error<ConnectError>> {
73        let cfg = cfg.get::<TlsConfig>();
74        crate::utils::connect(&cfg, host, async {
75            let ssl = self
76                .openssl
77                .configure()
78                .and_then(|config| config.into_ssl(host))
79                .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
80            super::handshake(io, ssl, false).await
81        })
82        .await
83    }
84}
85
86impl<F: Filter, A: Address, S> Service<SharedCfg, Connect<A>> for SslConnector<S>
87where
88    S: Service<SharedCfg, Connect<A>, Res = Io<F>, Error = Error<ConnectError>>,
89{
90    type Res = Io<Layer<SslFilter, F>>;
91    type Error = Error<ConnectError>;
92
93    /// Establishes transport, then upgrades it using the normalized request host.
94    async fn call(
95        &self,
96        req: Connect<A>,
97        ctx: Ctx<'_, Self, SharedCfg>,
98    ) -> Result<Self::Res, Self::Error> {
99        let host = crate::utils::server_name(req.host()).to_string();
100        let io = ctx.call(&self.svc, req).await?;
101        self.connect(io, &host, ctx.st()).await
102    }
103
104    ntex_service::forward!(SharedCfg, svc);
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    use ntex_service::Pipeline;
112    use tls_openssl::ssl::SslMethod;
113
114    /// STATEMENT: An OpenSSL connector is ready but reports failure against a non-TLS peer.
115    ///
116    /// HOW:
117    /// - Construct and clone the connector and await readiness.
118    /// - Connect to a local service that drops the transport and assert the call fails.
119    #[ntex::test]
120    async fn test_openssl_connect() {
121        let server = ntex::server::test_server(async |()| {
122            ntex::service::fn_service(async |_| Ok::<_, ()>(()))
123        });
124
125        let ssl = OpensslConnector::builder(SslMethod::tls()).unwrap();
126        let _: SslConnector<Connector<&'static str>> = SslConnector::new(ssl.build());
127        let ssl = OpensslConnector::builder(SslMethod::tls()).unwrap();
128        let svc = SslConnector::new(ssl.build()).clone();
129
130        let srv = Pipeline::new(SharedCfg::default(), svc);
131        // always ready
132        assert!(srv.ready().await.is_ok());
133        let result = srv
134            .call(Connect::new("").set_addr(Some(server.addr())))
135            .await;
136        assert!(result.is_err());
137    }
138}