Skip to main content

compio_ws/
tls.rs

1//! TLS support for WebSocket connections (native-tls and rustls).
2
3use compio_io::{AsyncRead, AsyncWrite};
4use compio_net::{SocketOpts, TcpStream};
5use compio_tls::{MaybeTlsStream, TlsConnector};
6use tungstenite::{
7    Error,
8    client::{IntoClientRequest, uri_mode},
9    handshake::client::{Request, Response},
10    stream::Mode,
11};
12
13use crate::{Config, WebSocketStream, client_async_with_config};
14
15mod encryption {
16    #[cfg(feature = "native-tls")]
17    pub mod native_tls {
18        use compio_tls::{TlsConnector, native_tls};
19        use tungstenite::{Error, error::TlsError};
20
21        pub fn new_connector() -> Result<TlsConnector, Error> {
22            let native_connector = native_tls::TlsConnector::new().map_err(TlsError::from)?;
23            Ok(TlsConnector::from(native_connector))
24        }
25    }
26
27    #[cfg(feature = "rustls")]
28    pub mod rustls {
29        use std::sync::Arc;
30
31        use compio_tls::{
32            TlsConnector,
33            rustls::{ClientConfig, RootCertStore},
34        };
35        use tungstenite::Error;
36
37        fn config_with_certs() -> Result<Arc<ClientConfig>, Error> {
38            #[allow(unused_mut)]
39            let mut root_store = RootCertStore::empty();
40            #[cfg(feature = "rustls-native-certs")]
41            {
42                let rustls_native_certs::CertificateResult { certs, errors, .. } =
43                    rustls_native_certs::load_native_certs();
44
45                if !errors.is_empty() {
46                    compio_log::warn!("native root CA certificate loading errors: {errors:?}");
47                }
48
49                // Not finding any native root CA certificates is not fatal
50                // if the "webpki-roots" feature is enabled.
51                #[cfg(not(feature = "webpki-roots"))]
52                if certs.is_empty() {
53                    return Err(std::io::Error::new(
54                        std::io::ErrorKind::NotFound,
55                        format!("no native root CA certificates found (errors: {errors:?})"),
56                    )
57                    .into());
58                }
59
60                let total_number = certs.len();
61                let (number_added, number_ignored) = root_store.add_parsable_certificates(certs);
62                compio_log::debug!(
63                    "Added {number_added}/{total_number} native root certificates (ignored \
64                     {number_ignored})"
65                );
66            }
67            #[cfg(feature = "webpki-roots")]
68            {
69                root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
70            }
71
72            Ok(Arc::new(
73                ClientConfig::builder()
74                    .with_root_certificates(root_store)
75                    .with_no_client_auth(),
76            ))
77        }
78
79        #[cfg(feature = "rustls-platform-verifier")]
80        fn config_with_platform_verifier() -> Result<Arc<ClientConfig>, Error> {
81            use rustls_platform_verifier::BuilderVerifierExt;
82
83            // Use platform's native certificate verification
84            // This provides better security and enterprise integration
85            let config_result = ClientConfig::builder()
86                .with_platform_verifier()
87                .map_err(tungstenite::error::TlsError::from)?;
88            Ok(Arc::new(config_result.with_no_client_auth()))
89        }
90
91        pub fn new_connector() -> Result<TlsConnector, Error> {
92            // Create TLS connector with platform verifier when feature is enabled
93            #[cfg(feature = "rustls-platform-verifier")]
94            {
95                let config = match config_with_platform_verifier() {
96                    Ok(config_builder) => config_builder,
97                    Err(_e) => {
98                        compio_log::warn!("Error creating platform verifier: {_e}");
99                        config_with_certs()?
100                    }
101                };
102                Ok(TlsConnector::from(config))
103            }
104            #[cfg(not(feature = "rustls-platform-verifier"))]
105            {
106                // Create TLS connector with certs from enabled features
107                let config = config_with_certs()?;
108                Ok(TlsConnector::from(config))
109            }
110        }
111    }
112}
113
114async fn wrap_stream<S>(
115    socket: S,
116    domain: &str,
117    connector: Option<TlsConnector>,
118    mode: Mode,
119) -> Result<MaybeTlsStream<S>, Error>
120where
121    S: AsyncRead + AsyncWrite + Unpin + 'static,
122    for<'a> &'a S: AsyncRead + AsyncWrite,
123{
124    match mode {
125        Mode::Plain => Ok(MaybeTlsStream::new_plain(socket)),
126        Mode::Tls => {
127            let stream = {
128                let connector = if let Some(connector) = connector {
129                    connector
130                } else {
131                    #[cfg(feature = "native-tls")]
132                    {
133                        match encryption::native_tls::new_connector() {
134                            Ok(c) => c,
135                            Err(_e) => {
136                                compio_log::warn!(
137                                    "Falling back to rustls TLS connector due to native-tls \
138                                     error: {}",
139                                    _e
140                                );
141                                #[cfg(feature = "rustls")]
142                                {
143                                    encryption::rustls::new_connector()?
144                                }
145                                #[cfg(not(feature = "rustls"))]
146                                {
147                                    return Err(_e);
148                                }
149                            }
150                        }
151                    }
152                    #[cfg(all(feature = "rustls", not(feature = "native-tls")))]
153                    {
154                        encryption::rustls::new_connector()?
155                    }
156                    #[cfg(not(any(feature = "native-tls", feature = "rustls")))]
157                    {
158                        return Err(Error::Url(
159                            tungstenite::error::UrlError::TlsFeatureNotEnabled,
160                        ));
161                    }
162                };
163
164                connector.connect(domain, socket).await.map_err(Error::Io)?
165            };
166            Ok(MaybeTlsStream::new_tls(stream))
167        }
168    }
169}
170
171/// Creates a WebSocket handshake from a request and a stream,
172/// upgrading the stream to TLS if required.
173pub async fn client_async_tls<R, S>(
174    request: R,
175    stream: S,
176) -> Result<(WebSocketStream<MaybeTlsStream<S>>, Response), Error>
177where
178    R: IntoClientRequest,
179    S: AsyncRead + AsyncWrite + Unpin + 'static,
180    for<'a> &'a S: AsyncRead + AsyncWrite,
181{
182    client_async_tls_with_config(request, stream, None, None).await
183}
184
185/// Similar to [`client_async_tls()`] but the one can specify a websocket
186/// configuration, and an optional connector.
187pub async fn client_async_tls_with_config<R, S>(
188    request: R,
189    stream: S,
190    connector: Option<TlsConnector>,
191    config: impl Into<Config>,
192) -> Result<(WebSocketStream<MaybeTlsStream<S>>, Response), Error>
193where
194    R: IntoClientRequest,
195    S: AsyncRead + AsyncWrite + Unpin + 'static,
196    for<'a> &'a S: AsyncRead + AsyncWrite,
197{
198    let request: Request = request.into_client_request()?;
199
200    let domain = domain(&request)?;
201
202    let mode = uri_mode(request.uri())?;
203
204    let stream = wrap_stream(stream, domain, connector, mode).await?;
205    client_async_with_config(request, stream, config).await
206}
207
208/// Type alias for a connected stream.
209type ConnectStream = MaybeTlsStream<TcpStream>;
210
211/// Connect to a given URL.
212pub async fn connect_async<R>(
213    request: R,
214) -> Result<(WebSocketStream<ConnectStream>, Response), Error>
215where
216    R: IntoClientRequest,
217{
218    connect_async_with_config(request, None).await
219}
220
221/// Similar to [`connect_async()`], but user can specify a [`Config`].
222pub async fn connect_async_with_config<R>(
223    request: R,
224    config: impl Into<Config>,
225) -> Result<(WebSocketStream<ConnectStream>, Response), Error>
226where
227    R: IntoClientRequest,
228{
229    connect_async_tls_with_config(request, config, None).await
230}
231
232/// Similar to [`connect_async()`], but user can specify a [`Config`] and an
233/// optional [`TlsConnector`].
234pub async fn connect_async_tls_with_config<R>(
235    request: R,
236    config: impl Into<Config>,
237    connector: Option<TlsConnector>,
238) -> Result<(WebSocketStream<ConnectStream>, Response), Error>
239where
240    R: IntoClientRequest,
241{
242    let config = config.into();
243    let request: Request = request.into_client_request()?;
244
245    // We don't check if it's an IPv6 address because `std` handles it internally.
246    let domain = request
247        .uri()
248        .host()
249        .ok_or(Error::Url(tungstenite::error::UrlError::NoHostName))?;
250    let port = port(&request)?;
251
252    let opts = SocketOpts::new().nodelay(config.disable_nagle);
253    let socket = TcpStream::connect_with_options((domain, port), &opts)
254        .await
255        .map_err(Error::Io)?;
256    client_async_tls_with_config(request, socket, connector, config).await
257}
258
259#[inline]
260fn port(request: &Request) -> Result<u16, Error> {
261    request
262        .uri()
263        .port_u16()
264        .or_else(|| match uri_mode(request.uri()).ok()? {
265            Mode::Plain => Some(80),
266            Mode::Tls => Some(443),
267        })
268        .ok_or(Error::Url(
269            tungstenite::error::UrlError::UnsupportedUrlScheme,
270        ))
271}
272
273#[inline]
274fn domain(request: &Request) -> Result<&str, Error> {
275    request
276        .uri()
277        .host()
278        .map(|host| {
279            // If host is an IPv6 address, it might be surrounded by brackets. These
280            // brackets are *not* part of a valid IP, so they must be stripped
281            // out.
282            //
283            // The URI from the request is guaranteed to be valid, so we don't need a
284            // separate check for the closing bracket.
285
286            if host.starts_with('[') && host.ends_with(']') {
287                &host[1..host.len() - 1]
288            } else {
289                host
290            }
291        })
292        .ok_or(tungstenite::Error::Url(
293            tungstenite::error::UrlError::NoHostName,
294        ))
295}