Skip to main content

socketio_next/engineio/
tls.rs

1//! TLS backend selection for `https://` and `wss://` connections.
2//!
3//! The backend is a cargo feature: `rustls` (default, pure Rust, ring provider, Mozilla roots from
4//! `webpki-roots`) or `native-tls` (OpenSSL on Linux, Security.framework on macOS, SChannel on
5//! Windows). With neither feature the crate builds without TLS and refuses `https`/`wss` URLs with
6//! [`Error::TlsNotEnabled`].
7
8use std::fmt;
9#[cfg(feature = "rustls")]
10use std::sync::{Arc, LazyLock};
11
12use url::Url;
13
14use crate::engineio::error::{Error, Result};
15
16/// A TLS client configuration for one of the compiled-in backends.
17///
18/// Built from a backend type with `From` (`rustls::ClientConfig`, `Arc<rustls::ClientConfig>`,
19/// `native_tls::TlsConnector`), or with [`TlsConfig::with_root_certificates_pem`] for a private CA.
20#[derive(Clone)]
21#[non_exhaustive]
22pub enum TlsConfig {
23    /// A rustls client configuration.
24    #[cfg(feature = "rustls")]
25    Rustls(Arc<rustls::ClientConfig>),
26    /// A native-tls connector.
27    #[cfg(feature = "native-tls")]
28    NativeTls(native_tls::TlsConnector),
29}
30
31impl fmt::Debug for TlsConfig {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        #[allow(unreachable_patterns)]
34        match self {
35            #[cfg(feature = "rustls")]
36            TlsConfig::Rustls(_) => f.write_str("TlsConfig::Rustls"),
37            #[cfg(feature = "native-tls")]
38            TlsConfig::NativeTls(_) => f.write_str("TlsConfig::NativeTls"),
39            _ => f.write_str("TlsConfig"),
40        }
41    }
42}
43
44#[cfg(feature = "rustls")]
45impl From<rustls::ClientConfig> for TlsConfig {
46    fn from(config: rustls::ClientConfig) -> Self {
47        TlsConfig::Rustls(Arc::new(config))
48    }
49}
50
51#[cfg(feature = "rustls")]
52impl From<Arc<rustls::ClientConfig>> for TlsConfig {
53    fn from(config: Arc<rustls::ClientConfig>) -> Self {
54        TlsConfig::Rustls(config)
55    }
56}
57
58#[cfg(feature = "native-tls")]
59impl From<native_tls::TlsConnector> for TlsConfig {
60    fn from(connector: native_tls::TlsConnector) -> Self {
61        TlsConfig::NativeTls(connector)
62    }
63}
64
65impl TlsConfig {
66    /// A configuration that trusts only the PEM certificates in `pem` (a private or self-signed
67    /// CA). Uses rustls when it is compiled in, native-tls otherwise.
68    pub fn with_root_certificates_pem(pem: &[u8]) -> Result<Self> {
69        #[cfg(feature = "rustls")]
70        {
71            use rustls_pki_types::{CertificateDer, pem::PemObject};
72            let mut roots = rustls::RootCertStore::empty();
73            for cert in CertificateDer::pem_slice_iter(pem) {
74                let cert = cert.map_err(|e| Error::InvalidTlsConfig(e.to_string()))?;
75                roots
76                    .add(cert)
77                    .map_err(|e| Error::InvalidTlsConfig(e.to_string()))?;
78            }
79            if roots.is_empty() {
80                return Err(Error::InvalidTlsConfig("no certificate in PEM".into()));
81            }
82            Ok(TlsConfig::Rustls(Arc::new(rustls_config(roots)?)))
83        }
84        #[cfg(all(feature = "native-tls", not(feature = "rustls")))]
85        {
86            let cert = native_tls::Certificate::from_pem(pem)
87                .map_err(|e| Error::InvalidTlsConfig(e.to_string()))?;
88            let connector = native_tls::TlsConnector::builder()
89                .add_root_certificate(cert)
90                .build()
91                .map_err(|e| Error::InvalidTlsConfig(e.to_string()))?;
92            Ok(TlsConfig::NativeTls(connector))
93        }
94        #[cfg(not(any(feature = "rustls", feature = "native-tls")))]
95        {
96            let _ = pem;
97            Err(Error::TlsNotEnabled("custom root certificates".into()))
98        }
99    }
100}
101
102#[cfg(feature = "rustls")]
103fn rustls_config(roots: rustls::RootCertStore) -> Result<rustls::ClientConfig> {
104    // An explicit provider: `ClientConfig::builder()` panics when another crate in the graph
105    // also enables aws-lc-rs and no process default is installed.
106    Ok(rustls::ClientConfig::builder_with_provider(Arc::new(
107        rustls::crypto::ring::default_provider(),
108    ))
109    .with_safe_default_protocol_versions()
110    .map_err(|e| Error::InvalidTlsConfig(e.to_string()))?
111    .with_root_certificates(roots)
112    .with_no_client_auth())
113}
114
115/// The rustls configuration used when the caller gives none: Mozilla roots, or the operating
116/// system's verifier with `platform-verifier` (not on Android).
117#[cfg(feature = "rustls")]
118fn default_rustls() -> Arc<rustls::ClientConfig> {
119    static CONFIG: LazyLock<Arc<rustls::ClientConfig>> = LazyLock::new(|| {
120        #[cfg(all(feature = "platform-verifier", not(target_os = "android")))]
121        match platform_config() {
122            Ok(config) => return Arc::new(config),
123            Err(err) => {
124                tracing::warn!(error = %err, "platform verifier unavailable; using webpki roots")
125            }
126        }
127        let roots = rustls::RootCertStore {
128            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
129        };
130        Arc::new(rustls_config(roots).expect("ring supports the default protocol versions"))
131    });
132    Arc::clone(&CONFIG)
133}
134
135#[cfg(all(feature = "platform-verifier", not(target_os = "android")))]
136fn platform_config() -> std::result::Result<rustls::ClientConfig, rustls::Error> {
137    let provider = Arc::new(rustls::crypto::ring::default_provider());
138    let verifier = rustls_platform_verifier::Verifier::new(Arc::clone(&provider))?;
139    Ok(rustls::ClientConfig::builder_with_provider(provider)
140        .with_safe_default_protocol_versions()?
141        .dangerous()
142        .with_custom_certificate_verifier(Arc::new(verifier))
143        .with_no_client_auth())
144}
145
146/// The configuration to use: the caller's, or the default of the preferred backend.
147pub(crate) fn effective(config: Option<&TlsConfig>) -> Option<TlsConfig> {
148    if let Some(config) = config {
149        return Some(config.clone());
150    }
151    #[cfg(feature = "rustls")]
152    {
153        Some(TlsConfig::Rustls(default_rustls()))
154    }
155    #[cfg(all(feature = "native-tls", not(feature = "rustls")))]
156    {
157        native_tls::TlsConnector::new()
158            .ok()
159            .map(TlsConfig::NativeTls)
160    }
161    #[cfg(not(any(feature = "rustls", feature = "native-tls")))]
162    {
163        None
164    }
165}
166
167/// Fails for `https`/`wss` when no TLS backend is compiled in.
168pub(crate) fn check_scheme(url: &Url) -> Result<()> {
169    match url.scheme() {
170        "http" | "ws" => Ok(()),
171        "https" | "wss" if cfg!(any(feature = "rustls", feature = "native-tls")) => Ok(()),
172        "https" | "wss" => Err(Error::TlsNotEnabled(url.scheme().to_owned())),
173        other => Err(Error::InvalidUrlScheme(other.to_owned())),
174    }
175}
176
177/// Builds the reqwest client. reqwest panics when a crate elsewhere in the graph enabled its
178/// `rustls-no-provider` feature and no provider is installed (feature unification); that becomes
179/// [`Error::TlsProviderMissing`] instead of a panic in the caller's task.
180// ponytail: catch_unwind does not help under `panic = "abort"`; the README names the feature fix.
181pub(crate) fn build_reqwest(builder: reqwest::ClientBuilder) -> Result<reqwest::Client> {
182    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| builder.build())) {
183        Ok(client) => Ok(client?),
184        Err(_) => Err(Error::TlsProviderMissing),
185    }
186}
187
188/// Applies the TLS configuration to a reqwest client builder.
189macro_rules! apply_reqwest_tls {
190    ($builder:expr, $config:expr) => {{
191        #[allow(unused_mut)]
192        let mut builder = $builder;
193        #[allow(unreachable_patterns, unused_variables)]
194        match $crate::engineio::tls::effective($config) {
195            #[cfg(feature = "rustls")]
196            Some($crate::engineio::tls::TlsConfig::Rustls(config)) => {
197                builder = builder.tls_backend_preconfigured((*config).clone());
198            }
199            #[cfg(feature = "native-tls")]
200            Some($crate::engineio::tls::TlsConfig::NativeTls(connector)) => {
201                builder = builder.tls_backend_preconfigured(connector);
202            }
203            _ => {}
204        }
205        builder
206    }};
207}
208pub(crate) use apply_reqwest_tls;
209
210/// The tokio-tungstenite connector for a `wss` connection.
211#[cfg(any(feature = "rustls", feature = "native-tls"))]
212pub(crate) fn ws_connector(config: Option<&TlsConfig>) -> Option<tokio_tungstenite::Connector> {
213    #[allow(unreachable_patterns, unused_variables)]
214    match effective(config)? {
215        #[cfg(feature = "rustls")]
216        TlsConfig::Rustls(config) => Some(tokio_tungstenite::Connector::Rustls(config)),
217        #[cfg(feature = "native-tls")]
218        TlsConfig::NativeTls(connector) => Some(tokio_tungstenite::Connector::NativeTls(connector)),
219        _ => None,
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    // reqwest's own builder with rustls compiled in and no provider installed: what a downstream
228    // build gets when another crate enables `rustls-no-provider` (nothing here installs a default).
229    #[cfg(all(feature = "rustls", not(feature = "native-tls")))]
230    #[test]
231    fn missing_provider_is_an_error_not_a_panic() {
232        assert!(matches!(
233            build_reqwest(reqwest::Client::builder()),
234            Err(Error::TlsProviderMissing)
235        ));
236        assert!(build_reqwest(apply_reqwest_tls!(reqwest::Client::builder(), None)).is_ok());
237    }
238
239    #[test]
240    fn scheme_check() {
241        assert!(check_scheme(&Url::parse("http://h/").unwrap()).is_ok());
242        assert!(check_scheme(&Url::parse("ws://h/").unwrap()).is_ok());
243        assert!(matches!(
244            check_scheme(&Url::parse("ftp://h/").unwrap()),
245            Err(Error::InvalidUrlScheme(_))
246        ));
247        let secure = check_scheme(&Url::parse("https://h/").unwrap());
248        if cfg!(any(feature = "rustls", feature = "native-tls")) {
249            assert!(secure.is_ok());
250        } else {
251            assert!(matches!(secure, Err(Error::TlsNotEnabled(_))));
252        }
253    }
254
255    #[cfg(any(feature = "rustls", feature = "native-tls"))]
256    #[test]
257    fn pem_without_certificates_is_an_error() {
258        assert!(TlsConfig::with_root_certificates_pem(b"not a pem").is_err());
259    }
260
261    /// `platform-verifier`: the default config verifies through the OS, not the bundled roots.
262    #[cfg(feature = "rustls")]
263    #[test]
264    fn default_verifier_matches_the_features() {
265        let debug = format!("{:?}", default_rustls());
266        let platform = cfg!(all(
267            feature = "platform-verifier",
268            not(target_os = "android")
269        ));
270        // the platform crate's type is `Verifier` (on Linux it wraps a WebPki verifier over
271        // the OS roots); the bundled roots are a bare `WebPkiServerVerifier`
272        assert_eq!(debug.contains("verifier: Verifier {"), platform, "{debug}");
273    }
274
275    #[cfg(any(feature = "rustls", feature = "native-tls"))]
276    #[test]
277    fn default_config_exists() {
278        assert!(effective(None).is_some());
279    }
280}