Skip to main content

redis_tower_core/
tls.rs

1//! TLS configuration for Redis connections.
2//!
3//! Enable `tls-rustls` for a pure-Rust backend or `tls-native-tls` for the
4//! platform TLS stack. [`TlsConfig`] can use system roots, custom root CAs,
5//! mutual TLS certificates, or a caller-built backend configuration.
6//!
7//! # Example
8//!
9//! ```no_run
10//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
11//! use redis_tower_core::RedisConnection;
12//! use redis_tower_core::tls::TlsConfig;
13//!
14//! let tls = TlsConfig::default_rustls();
15//! let connection = RedisConnection::connect_tls(
16//!     "redis.example.com:6380",
17//!     "redis.example.com",
18//!     &tls,
19//! )
20//! .await?;
21//! # let _ = connection;
22//! # Ok(())
23//! # }
24//! ```
25
26use crate::error::RedisError;
27use crate::stream::RedisStream;
28use tokio::net::TcpStream;
29
30/// TLS configuration for connecting to Redis.
31///
32/// Supports two backends via feature flags:
33/// - `tls-native-tls`: Uses the platform's native TLS (OpenSSL on Linux,
34///   Secure Transport on macOS, SChannel on Windows).
35/// - `tls-rustls`: Uses rustls (pure Rust, no system dependencies).
36///
37/// # Example
38///
39/// Each constructor is available only when its own backend feature is enabled;
40/// this example shows both together.
41///
42/// ```no_run
43/// use redis_tower_core::tls::TlsConfig;
44///
45/// // Use platform defaults (system root certs, verify hostname).
46/// let native = TlsConfig::default_native_tls();
47///
48/// // Or with rustls:
49/// let rustls = TlsConfig::default_rustls();
50///
51/// // Disable certificate verification (DANGEROUS, for testing only).
52/// let insecure = TlsConfig::default_native_tls().danger_accept_invalid_certs(true);
53/// # let _ = (native, rustls, insecure);
54/// ```
55pub struct TlsConfig {
56    pub(crate) backend: TlsBackend,
57    pub(crate) accept_invalid_certs: bool,
58    pub(crate) accept_invalid_hostnames: bool,
59    /// Custom root CA certificate(s) in PEM, replacing the default trust roots.
60    /// Applies to the default backends; ignored for a custom `ClientConfig` /
61    /// `TlsConnector` (the caller controls those).
62    pub(crate) root_ca_pem: Option<Vec<u8>>,
63    /// Client certificate chain + PKCS#8 private key in PEM, for mutual TLS.
64    pub(crate) client_auth_pem: Option<(Vec<u8>, Vec<u8>)>,
65}
66
67pub(crate) enum TlsBackend {
68    #[cfg(feature = "tls-native-tls")]
69    NativeTls,
70    #[cfg(feature = "tls-native-tls")]
71    NativeTlsCustom(native_tls::TlsConnector),
72    #[cfg(feature = "tls-rustls")]
73    Rustls,
74    #[cfg(feature = "tls-rustls")]
75    RustlsCustom(std::sync::Arc<rustls::ClientConfig>),
76}
77
78impl TlsConfig {
79    /// Create a TLS config using the native-tls backend with platform defaults.
80    #[cfg(feature = "tls-native-tls")]
81    #[cfg_attr(docsrs, doc(cfg(feature = "tls-native-tls")))]
82    pub fn default_native_tls() -> Self {
83        Self {
84            backend: TlsBackend::NativeTls,
85            accept_invalid_certs: false,
86            accept_invalid_hostnames: false,
87            root_ca_pem: None,
88            client_auth_pem: None,
89        }
90    }
91
92    /// Create a TLS config using the rustls backend with system root certs.
93    #[cfg(feature = "tls-rustls")]
94    #[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
95    pub fn default_rustls() -> Self {
96        Self {
97            backend: TlsBackend::Rustls,
98            accept_invalid_certs: false,
99            accept_invalid_hostnames: false,
100            root_ca_pem: None,
101            client_auth_pem: None,
102        }
103    }
104
105    /// Create from a pre-built rustls `ClientConfig`.
106    ///
107    /// This allows full control over the TLS configuration (custom root
108    /// certs, client certificates, protocol versions, etc.). The
109    /// `danger_accept_invalid_certs` and `danger_accept_invalid_hostnames`
110    /// settings are ignored when using a custom config since the caller
111    /// controls verification through the provided `ClientConfig`.
112    #[cfg(feature = "tls-rustls")]
113    #[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
114    pub fn from_rustls_config(config: std::sync::Arc<rustls::ClientConfig>) -> Self {
115        Self {
116            backend: TlsBackend::RustlsCustom(config),
117            accept_invalid_certs: false,
118            accept_invalid_hostnames: false,
119            root_ca_pem: None,
120            client_auth_pem: None,
121        }
122    }
123
124    /// Create from a pre-built native-tls `TlsConnector`.
125    ///
126    /// This allows full control over the TLS configuration (custom root
127    /// certs, client certificates, protocol versions, etc.). The
128    /// `danger_accept_invalid_certs` and `danger_accept_invalid_hostnames`
129    /// settings are ignored when using a custom connector since the caller
130    /// controls verification through the provided `TlsConnector`.
131    #[cfg(feature = "tls-native-tls")]
132    #[cfg_attr(docsrs, doc(cfg(feature = "tls-native-tls")))]
133    pub fn from_native_tls_connector(connector: native_tls::TlsConnector) -> Self {
134        Self {
135            backend: TlsBackend::NativeTlsCustom(connector),
136            accept_invalid_certs: false,
137            accept_invalid_hostnames: false,
138            root_ca_pem: None,
139            client_auth_pem: None,
140        }
141    }
142
143    /// Accept invalid TLS certificates.
144    ///
145    /// **DANGEROUS**: This disables certificate verification. Only use for
146    /// testing with self-signed certificates.
147    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
148        self.accept_invalid_certs = accept;
149        self
150    }
151
152    /// Accept invalid hostnames in TLS certificates.
153    ///
154    /// **DANGEROUS**: This disables hostname verification.
155    pub fn danger_accept_invalid_hostnames(mut self, accept: bool) -> Self {
156        self.accept_invalid_hostnames = accept;
157        self
158    }
159
160    /// Trust a custom root CA, given its certificate(s) in PEM.
161    ///
162    /// Replaces the default trust roots (system store + webpki bundle) with the
163    /// provided CA(s) -- the standard private-CA / enterprise posture. Works
164    /// with either backend. Ignored if the config was built from a pre-made
165    /// `ClientConfig` / `TlsConnector`.
166    ///
167    /// # Example
168    ///
169    /// ```no_run
170    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
171    /// use redis_tower_core::tls::TlsConfig;
172    ///
173    /// let tls = TlsConfig::default_rustls()
174    ///     .with_root_ca_pem(std::fs::read("ca.pem")?);
175    /// # let _ = tls;
176    /// # Ok(())
177    /// # }
178    /// ```
179    pub fn with_root_ca_pem(mut self, pem: impl Into<Vec<u8>>) -> Self {
180        self.root_ca_pem = Some(pem.into());
181        self
182    }
183
184    /// Present a client certificate for mutual TLS (mTLS).
185    ///
186    /// `cert_pem` is the client certificate chain and `key_pem` its PKCS#8
187    /// private key, both in PEM. Works with either backend. Combine with
188    /// [`with_root_ca_pem`](Self::with_root_ca_pem) for the typical
189    /// custom-CA + mTLS enterprise posture.
190    ///
191    /// # Example
192    ///
193    /// ```no_run
194    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
195    /// use redis_tower_core::tls::TlsConfig;
196    ///
197    /// let tls = TlsConfig::default_rustls()
198    ///     .with_root_ca_pem(std::fs::read("ca.pem")?)
199    ///     .with_client_auth_pem(std::fs::read("client.pem")?, std::fs::read("client.key")?);
200    /// # let _ = tls;
201    /// # Ok(())
202    /// # }
203    /// ```
204    pub fn with_client_auth_pem(
205        mut self,
206        cert_pem: impl Into<Vec<u8>>,
207        key_pem: impl Into<Vec<u8>>,
208    ) -> Self {
209        self.client_auth_pem = Some((cert_pem.into(), key_pem.into()));
210        self
211    }
212
213    /// Perform the TLS handshake on a TCP stream.
214    pub(crate) async fn connect(
215        &self,
216        tcp: TcpStream,
217        hostname: &str,
218    ) -> Result<RedisStream, RedisError> {
219        match &self.backend {
220            #[cfg(feature = "tls-native-tls")]
221            TlsBackend::NativeTls => self.connect_native_tls(tcp, hostname).await,
222            #[cfg(feature = "tls-native-tls")]
223            TlsBackend::NativeTlsCustom(connector) => {
224                Self::connect_native_tls_custom(connector.clone(), tcp, hostname).await
225            }
226            #[cfg(feature = "tls-rustls")]
227            TlsBackend::Rustls => self.connect_rustls(tcp, hostname).await,
228            #[cfg(feature = "tls-rustls")]
229            TlsBackend::RustlsCustom(config) => {
230                Self::connect_rustls_custom(config.clone(), tcp, hostname).await
231            }
232        }
233    }
234
235    #[cfg(feature = "tls-native-tls")]
236    async fn connect_native_tls(
237        &self,
238        tcp: TcpStream,
239        hostname: &str,
240    ) -> Result<RedisStream, RedisError> {
241        let mut builder = native_tls::TlsConnector::builder();
242        builder.danger_accept_invalid_certs(self.accept_invalid_certs);
243        builder.danger_accept_invalid_hostnames(self.accept_invalid_hostnames);
244        if let Some(ref ca) = self.root_ca_pem {
245            let cert = native_tls::Certificate::from_pem(ca)
246                .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
247            builder.add_root_certificate(cert);
248        }
249        if let Some((ref cert_pem, ref key_pem)) = self.client_auth_pem {
250            let identity = native_tls::Identity::from_pkcs8(cert_pem, key_pem)
251                .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
252            builder.identity(identity);
253        }
254
255        let connector = builder
256            .build()
257            .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
258        let connector = tokio_native_tls::TlsConnector::from(connector);
259
260        let tls_stream = connector
261            .connect(hostname, tcp)
262            .await
263            .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
264
265        Ok(RedisStream::NativeTls(Box::new(tls_stream)))
266    }
267
268    #[cfg(feature = "tls-native-tls")]
269    async fn connect_native_tls_custom(
270        connector: native_tls::TlsConnector,
271        tcp: TcpStream,
272        hostname: &str,
273    ) -> Result<RedisStream, RedisError> {
274        let connector = tokio_native_tls::TlsConnector::from(connector);
275
276        let tls_stream = connector
277            .connect(hostname, tcp)
278            .await
279            .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
280
281        Ok(RedisStream::NativeTls(Box::new(tls_stream)))
282    }
283
284    /// Build the rustls root cert store: the custom CA if one was provided,
285    /// otherwise the system store with a webpki-roots fallback.
286    #[cfg(feature = "tls-rustls")]
287    fn rustls_root_store(&self) -> Result<rustls::RootCertStore, RedisError> {
288        let mut root_store = rustls::RootCertStore::empty();
289        if let Some(ref ca) = self.root_ca_pem {
290            for cert in parse_certs_pem(ca)? {
291                root_store
292                    .add(cert)
293                    .map_err(|e| RedisError::from(std::io::Error::other(e)))?;
294            }
295        } else {
296            let native_result = rustls_native_certs::load_native_certs();
297            for cert in native_result.certs {
298                let _ = root_store.add(cert);
299            }
300            if root_store.is_empty() {
301                root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
302            }
303        }
304        Ok(root_store)
305    }
306
307    #[cfg(feature = "tls-rustls")]
308    async fn connect_rustls(
309        &self,
310        tcp: TcpStream,
311        hostname: &str,
312    ) -> Result<RedisStream, RedisError> {
313        use std::sync::Arc;
314
315        // Choose the server-cert verifier; both arms yield a builder awaiting
316        // the client-auth choice, so client certs are applied uniformly below.
317        // redis-tower enables rustls' ring backend explicitly. Select it on
318        // this builder as well: downstream SDKs may enable aws-lc-rs through
319        // Cargo feature unification, in which case rustls cannot infer one
320        // process-wide default provider and `ClientConfig::builder()` panics.
321        let builder = rustls::ClientConfig::builder_with_provider(Arc::new(
322            rustls::crypto::ring::default_provider(),
323        ))
324        .with_safe_default_protocol_versions()
325        .map_err(|error| RedisError::from(std::io::Error::other(error)))?;
326        let builder = if self.accept_invalid_certs {
327            builder
328                .dangerous()
329                .with_custom_certificate_verifier(Arc::new(DangerousVerifier))
330        } else {
331            builder.with_root_certificates(self.rustls_root_store()?)
332        };
333        let config = match &self.client_auth_pem {
334            Some((cert_pem, key_pem)) => builder
335                .with_client_auth_cert(parse_certs_pem(cert_pem)?, parse_private_key_pem(key_pem)?)
336                .map_err(|e| RedisError::from(std::io::Error::other(e)))?,
337            None => builder.with_no_client_auth(),
338        };
339
340        let connector = tokio_rustls::TlsConnector::from(Arc::new(config));
341        let server_name =
342            rustls::pki_types::ServerName::try_from(hostname.to_string()).map_err(|e| {
343                RedisError::from(std::io::Error::new(std::io::ErrorKind::InvalidInput, e))
344            })?;
345
346        let tls_stream = connector
347            .connect(server_name, tcp)
348            .await
349            .map_err(RedisError::from)?;
350
351        Ok(RedisStream::Rustls(Box::new(tls_stream)))
352    }
353
354    #[cfg(feature = "tls-rustls")]
355    async fn connect_rustls_custom(
356        config: std::sync::Arc<rustls::ClientConfig>,
357        tcp: TcpStream,
358        hostname: &str,
359    ) -> Result<RedisStream, RedisError> {
360        let connector = tokio_rustls::TlsConnector::from(config);
361        let server_name =
362            rustls::pki_types::ServerName::try_from(hostname.to_string()).map_err(|e| {
363                RedisError::from(std::io::Error::new(std::io::ErrorKind::InvalidInput, e))
364            })?;
365
366        let tls_stream = connector
367            .connect(server_name, tcp)
368            .await
369            .map_err(RedisError::from)?;
370
371        Ok(RedisStream::Rustls(Box::new(tls_stream)))
372    }
373}
374
375/// Parse one or more certificates from PEM into rustls DER form.
376#[cfg(feature = "tls-rustls")]
377fn parse_certs_pem(
378    pem: &[u8],
379) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>, RedisError> {
380    use rustls::pki_types::pem::PemObject;
381    rustls::pki_types::CertificateDer::pem_slice_iter(pem)
382        .collect::<Result<Vec<_>, _>>()
383        .map_err(|e| RedisError::from(std::io::Error::other(e)))
384}
385
386/// Parse a single PKCS#8 / SEC1 / RSA private key from PEM into rustls DER form.
387#[cfg(feature = "tls-rustls")]
388fn parse_private_key_pem(
389    pem: &[u8],
390) -> Result<rustls::pki_types::PrivateKeyDer<'static>, RedisError> {
391    use rustls::pki_types::pem::PemObject;
392    rustls::pki_types::PrivateKeyDer::from_pem_slice(pem)
393        .map_err(|e| RedisError::from(std::io::Error::other(e)))
394}
395
396/// Certificate verifier that accepts everything. Used when
397/// `danger_accept_invalid_certs` is enabled.
398#[cfg(feature = "tls-rustls")]
399#[derive(Debug)]
400struct DangerousVerifier;
401
402#[cfg(feature = "tls-rustls")]
403impl rustls::client::danger::ServerCertVerifier for DangerousVerifier {
404    fn verify_server_cert(
405        &self,
406        _end_entity: &rustls::pki_types::CertificateDer<'_>,
407        _intermediates: &[rustls::pki_types::CertificateDer<'_>],
408        _server_name: &rustls::pki_types::ServerName<'_>,
409        _ocsp_response: &[u8],
410        _now: rustls::pki_types::UnixTime,
411    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
412        Ok(rustls::client::danger::ServerCertVerified::assertion())
413    }
414
415    fn verify_tls12_signature(
416        &self,
417        _message: &[u8],
418        _cert: &rustls::pki_types::CertificateDer<'_>,
419        _dss: &rustls::DigitallySignedStruct,
420    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
421        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
422    }
423
424    fn verify_tls13_signature(
425        &self,
426        _message: &[u8],
427        _cert: &rustls::pki_types::CertificateDer<'_>,
428        _dss: &rustls::DigitallySignedStruct,
429    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
430        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
431    }
432
433    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
434        rustls::crypto::ring::default_provider()
435            .signature_verification_algorithms
436            .supported_schemes()
437    }
438}
439
440#[cfg(test)]
441pub(crate) mod tests {
442    use super::*;
443
444    // A self-signed P-256 cert + its PKCS#8 key, used to exercise PEM parsing.
445    const TEST_CERT: &str = "-----BEGIN CERTIFICATE-----\n\
446MIIBijCCATGgAwIBAgIUeYWzxqGH+ak/HDH9RMB1+u5Lhf4wCgYIKoZIzj0EAwIw\n\
447GzEZMBcGA1UEAwwQcmVkaXMtdG93ZXItdGVzdDAeFw0yNjA2MTIyMTAxNTNaFw0z\n\
448NjA2MDkyMTAxNTNaMBsxGTAXBgNVBAMMEHJlZGlzLXRvd2VyLXRlc3QwWTATBgcq\n\
449hkjOPQIBBggqhkjOPQMBBwNCAARTJOAo81mVG4sncY5w6LVlG+y3O4llaHzx7UOq\n\
450MKxs4Csh4kTiDRmwUoIq9DISRM1uYUR5dR9MjoMk/NEt3Jxpo1MwUTAdBgNVHQ4E\n\
451FgQUkxm6d0TuRcV/ZOvIdRHtudvybO0wHwYDVR0jBBgwFoAUkxm6d0TuRcV/ZOvI\n\
452dRHtudvybO0wDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNHADBEAiBMx2WV\n\
4538zEWSydXPqn7rabmh91JYNG3ikU1ggxscXSnDAIgVKG6VLZwvTHDRA6HSFdoAqyc\n\
4542c6Rr4ZJh79vhNSj8jM=\n\
455-----END CERTIFICATE-----\n";
456
457    const TEST_KEY: &str = "-----BEGIN PRIVATE KEY-----\n\
458MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgju5KBtu0Tyd5YVXR\n\
459JwQS3S1hW6Ts2I3ASTerbjBlJPahRANCAARTJOAo81mVG4sncY5w6LVlG+y3O4ll\n\
460aHzx7UOqMKxs4Csh4kTiDRmwUoIq9DISRM1uYUR5dR9MjoMk/NEt3Jxp\n\
461-----END PRIVATE KEY-----\n";
462
463    #[cfg(feature = "tls-rustls")]
464    pub(crate) fn server_config() -> std::sync::Arc<rustls::ServerConfig> {
465        let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider());
466        let config = rustls::ServerConfig::builder_with_provider(provider)
467            .with_safe_default_protocol_versions()
468            .unwrap()
469            .with_no_client_auth()
470            .with_single_cert(
471                parse_certs_pem(TEST_CERT.as_bytes()).unwrap(),
472                parse_private_key_pem(TEST_KEY.as_bytes()).unwrap(),
473            )
474            .unwrap();
475        std::sync::Arc::new(config)
476    }
477
478    #[cfg(feature = "tls-rustls")]
479    #[test]
480    fn with_root_ca_pem_sets_field_and_builds_store() {
481        let tls = TlsConfig::default_rustls().with_root_ca_pem(TEST_CERT.as_bytes().to_vec());
482        assert!(tls.root_ca_pem.is_some());
483        // The custom CA replaces the default roots: the store holds exactly it.
484        let store = tls.rustls_root_store().expect("custom CA should parse");
485        assert_eq!(store.len(), 1);
486    }
487
488    #[cfg(feature = "tls-rustls")]
489    #[test]
490    fn with_client_auth_pem_builds_a_client_config() {
491        let tls = TlsConfig::default_rustls()
492            .with_root_ca_pem(TEST_CERT.as_bytes().to_vec())
493            .with_client_auth_pem(TEST_CERT.as_bytes().to_vec(), TEST_KEY.as_bytes().to_vec());
494        assert!(tls.client_auth_pem.is_some());
495        // The full mTLS client config (custom roots + client cert) builds.
496        let certs = parse_certs_pem(TEST_CERT.as_bytes()).unwrap();
497        let key = parse_private_key_pem(TEST_KEY.as_bytes()).unwrap();
498        rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(
499            rustls::crypto::ring::default_provider(),
500        ))
501        .with_safe_default_protocol_versions()
502        .unwrap()
503        .with_root_certificates(tls.rustls_root_store().unwrap())
504        .with_client_auth_cert(certs, key)
505        .expect("mTLS client config should build");
506    }
507
508    #[cfg(feature = "tls-rustls")]
509    #[test]
510    fn parse_helpers_reject_garbage() {
511        // Non-cert PEM yields no certs (not an error -- the PEM iterator skips it).
512        assert!(parse_certs_pem(b"not a pem").unwrap().is_empty());
513        // A missing private key is an error.
514        assert!(parse_private_key_pem(b"-----BEGIN CERTIFICATE-----\nx\n").is_err());
515    }
516}