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 + 'static,
122{
123    match mode {
124        Mode::Plain => Ok(MaybeTlsStream::new_plain(socket)),
125        Mode::Tls => {
126            let stream = {
127                let connector = if let Some(connector) = connector {
128                    connector
129                } else {
130                    #[cfg(feature = "native-tls")]
131                    {
132                        match encryption::native_tls::new_connector() {
133                            Ok(c) => c,
134                            Err(_e) => {
135                                compio_log::warn!(
136                                    "Falling back to rustls TLS connector due to native-tls \
137                                     error: {}",
138                                    _e
139                                );
140                                #[cfg(feature = "rustls")]
141                                {
142                                    encryption::rustls::new_connector()?
143                                }
144                                #[cfg(not(feature = "rustls"))]
145                                {
146                                    return Err(_e);
147                                }
148                            }
149                        }
150                    }
151                    #[cfg(all(feature = "rustls", not(feature = "native-tls")))]
152                    {
153                        encryption::rustls::new_connector()?
154                    }
155                    #[cfg(not(any(feature = "native-tls", feature = "rustls")))]
156                    {
157                        return Err(Error::Url(
158                            tungstenite::error::UrlError::TlsFeatureNotEnabled,
159                        ));
160                    }
161                };
162
163                connector.connect(domain, socket).await.map_err(Error::Io)?
164            };
165            Ok(MaybeTlsStream::new_tls(stream))
166        }
167    }
168}
169
170/// Creates a WebSocket handshake from a request and a stream,
171/// upgrading the stream to TLS if required.
172pub async fn client_async_tls<R, S>(
173    request: R,
174    stream: S,
175) -> Result<(WebSocketStream<MaybeTlsStream<S>>, Response), Error>
176where
177    R: IntoClientRequest,
178    S: AsyncRead + AsyncWrite + Unpin + 'static,
179{
180    client_async_tls_with_config(request, stream, None, None).await
181}
182
183/// Similar to [`client_async_tls()`] but the one can specify a websocket
184/// configuration, and an optional connector.
185pub async fn client_async_tls_with_config<R, S>(
186    request: R,
187    stream: S,
188    connector: Option<TlsConnector>,
189    config: impl Into<Config>,
190) -> Result<(WebSocketStream<MaybeTlsStream<S>>, Response), Error>
191where
192    R: IntoClientRequest,
193    S: AsyncRead + AsyncWrite + Unpin + 'static,
194{
195    let request: Request = request.into_client_request()?;
196
197    let domain = domain(&request)?;
198
199    let mode = uri_mode(request.uri())?;
200
201    let stream = wrap_stream(stream, domain, connector, mode).await?;
202    client_async_with_config(request, stream, config).await
203}
204
205/// Type alias for a connected stream.
206type ConnectStream = MaybeTlsStream<TcpStream>;
207
208/// Connect to a given URL.
209pub async fn connect_async<R>(
210    request: R,
211) -> Result<(WebSocketStream<ConnectStream>, Response), Error>
212where
213    R: IntoClientRequest,
214{
215    connect_async_with_config(request, None).await
216}
217
218/// Similar to [`connect_async()`], but user can specify a [`Config`].
219pub async fn connect_async_with_config<R>(
220    request: R,
221    config: impl Into<Config>,
222) -> Result<(WebSocketStream<ConnectStream>, Response), Error>
223where
224    R: IntoClientRequest,
225{
226    connect_async_tls_with_config(request, config, None).await
227}
228
229/// Similar to [`connect_async()`], but user can specify a [`Config`] and an
230/// optional [`TlsConnector`].
231pub async fn connect_async_tls_with_config<R>(
232    request: R,
233    config: impl Into<Config>,
234    connector: Option<TlsConnector>,
235) -> Result<(WebSocketStream<ConnectStream>, Response), Error>
236where
237    R: IntoClientRequest,
238{
239    let config = config.into();
240    let request: Request = request.into_client_request()?;
241
242    // We don't check if it's an IPv6 address because `std` handles it internally.
243    let domain = request
244        .uri()
245        .host()
246        .ok_or(Error::Url(tungstenite::error::UrlError::NoHostName))?;
247    let port = port(&request)?;
248
249    let opts = SocketOpts::new().nodelay(config.disable_nagle);
250    let socket = TcpStream::connect_with_options((domain, port), &opts)
251        .await
252        .map_err(Error::Io)?;
253    client_async_tls_with_config(request, socket, connector, config).await
254}
255
256#[inline]
257fn port(request: &Request) -> Result<u16, Error> {
258    request
259        .uri()
260        .port_u16()
261        .or_else(|| match uri_mode(request.uri()).ok()? {
262            Mode::Plain => Some(80),
263            Mode::Tls => Some(443),
264        })
265        .ok_or(Error::Url(
266            tungstenite::error::UrlError::UnsupportedUrlScheme,
267        ))
268}
269
270#[inline]
271fn domain(request: &Request) -> Result<&str, Error> {
272    request
273        .uri()
274        .host()
275        .map(|host| {
276            // If host is an IPv6 address, it might be surrounded by brackets. These
277            // brackets are *not* part of a valid IP, so they must be stripped
278            // out.
279            //
280            // The URI from the request is guaranteed to be valid, so we don't need a
281            // separate check for the closing bracket.
282
283            if host.starts_with('[') && host.ends_with(']') {
284                &host[1..host.len() - 1]
285            } else {
286                host
287            }
288        })
289        .ok_or(tungstenite::Error::Url(
290            tungstenite::error::UrlError::NoHostName,
291        ))
292}