socketio_next/engineio/
tls.rs1use std::fmt;
9#[cfg(feature = "rustls")]
10use std::sync::{Arc, LazyLock};
11
12use url::Url;
13
14use crate::engineio::error::{Error, Result};
15
16#[derive(Clone)]
21#[non_exhaustive]
22pub enum TlsConfig {
23 #[cfg(feature = "rustls")]
25 Rustls(Arc<rustls::ClientConfig>),
26 #[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 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 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#[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
146pub(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
167pub(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
177pub(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
188macro_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#[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(http1_only(config))),
217 #[cfg(feature = "native-tls")]
218 TlsConfig::NativeTls(connector) => Some(tokio_tungstenite::Connector::NativeTls(connector)),
219 _ => None,
220 }
221}
222
223#[cfg(feature = "rustls")]
226fn http1_only(
227 config: std::sync::Arc<rustls::ClientConfig>,
228) -> std::sync::Arc<rustls::ClientConfig> {
229 if config.alpn_protocols.is_empty() || config.alpn_protocols == [b"http/1.1".to_vec()] {
230 return config;
231 }
232 let mut config = (*config).clone();
233 config.alpn_protocols = vec![b"http/1.1".to_vec()];
234 std::sync::Arc::new(config)
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240
241 #[cfg(feature = "rustls")]
244 #[test]
245 fn the_websocket_connector_offers_http1_only() {
246 let roots = rustls::RootCertStore::empty();
247 let mut config = rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(
248 rustls::crypto::ring::default_provider(),
249 ))
250 .with_safe_default_protocol_versions()
251 .unwrap()
252 .with_root_certificates(roots)
253 .with_no_client_auth();
254 config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
255 let fixed = http1_only(std::sync::Arc::new(config));
256 assert_eq!(fixed.alpn_protocols, [b"http/1.1".to_vec()]);
257 }
258
259 #[cfg(all(feature = "rustls", not(feature = "native-tls")))]
262 #[test]
263 fn missing_provider_is_an_error_not_a_panic() {
264 assert!(matches!(
265 build_reqwest(reqwest::Client::builder()),
266 Err(Error::TlsProviderMissing)
267 ));
268 assert!(build_reqwest(apply_reqwest_tls!(reqwest::Client::builder(), None)).is_ok());
269 }
270
271 #[test]
272 fn scheme_check() {
273 assert!(check_scheme(&Url::parse("http://h/").unwrap()).is_ok());
274 assert!(check_scheme(&Url::parse("ws://h/").unwrap()).is_ok());
275 assert!(matches!(
276 check_scheme(&Url::parse("ftp://h/").unwrap()),
277 Err(Error::InvalidUrlScheme(_))
278 ));
279 let secure = check_scheme(&Url::parse("https://h/").unwrap());
280 if cfg!(any(feature = "rustls", feature = "native-tls")) {
281 assert!(secure.is_ok());
282 } else {
283 assert!(matches!(secure, Err(Error::TlsNotEnabled(_))));
284 }
285 }
286
287 #[cfg(any(feature = "rustls", feature = "native-tls"))]
288 #[test]
289 fn pem_without_certificates_is_an_error() {
290 assert!(TlsConfig::with_root_certificates_pem(b"not a pem").is_err());
291 }
292
293 #[cfg(feature = "rustls")]
295 #[test]
296 fn default_verifier_matches_the_features() {
297 let debug = format!("{:?}", default_rustls());
298 let platform = cfg!(all(
299 feature = "platform-verifier",
300 not(target_os = "android")
301 ));
302 assert_eq!(debug.contains("verifier: Verifier {"), platform, "{debug}");
305 }
306
307 #[cfg(any(feature = "rustls", feature = "native-tls"))]
308 #[test]
309 fn default_config_exists() {
310 assert!(effective(None).is_some());
311 }
312}