Skip to main content

quack_rs/
tls.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Type-erased TLS configuration provider for HTTP-capable extensions.
7//!
8//! Extensions that make outbound HTTPS connections (e.g., `duck_net`) need a way
9//! to inject custom TLS configurations — client certificates for mTLS, custom CA
10//! bundles, or restricted cipher suites. This module provides the
11//! [`TlsConfigProvider`] trait so that extensions can supply their TLS setup
12//! through a uniform interface, regardless of which TLS library they use.
13//!
14//! # Design
15//!
16//! The trait is **type-erased** via [`std::any::Any`] so that `quack-rs` does not
17//! depend on any specific TLS library (e.g., `rustls`, `native-tls`). The
18//! implementing extension downcasts the returned `Arc<dyn Any>` to its concrete
19//! config type.
20//!
21//! # Security requirements for implementors
22//!
23//! Implementations **must**:
24//!
25//! - Return `false` from [`accepts_invalid_certs`][TlsConfigProvider::accepts_invalid_certs]
26//!   unless explicitly configured otherwise by the user. Certificate validation
27//!   bypass (CWE-295) should never be the default.
28//! - Return [`TlsVersion::Tls12`] or higher from
29//!   [`min_tls_version`][TlsConfigProvider::min_tls_version]. TLS 1.0 and 1.1
30//!   are deprecated ([RFC 8996](https://datatracker.ietf.org/doc/html/rfc8996)).
31//! - Emit an [`ExtensionWarning`][crate::warning::ExtensionWarning] via
32//!   [`WarningCollector`][crate::warning::WarningCollector] when certificate
33//!   validation is disabled or when using a TLS version below 1.2.
34//!
35//! # Example
36//!
37//! ```rust
38//! use quack_rs::tls::{TlsConfigProvider, TlsVersion};
39//! use quack_rs::error::ExtensionError;
40//! use std::any::Any;
41//! use std::sync::Arc;
42//!
43//! struct MyTlsProvider {
44//!     // In practice: Arc<rustls::ClientConfig>
45//!     config: Arc<String>,
46//!     mtls_enabled: bool,
47//! }
48//!
49//! impl TlsConfigProvider for MyTlsProvider {
50//!     fn client_config(&self) -> Result<Arc<dyn Any + Send + Sync>, ExtensionError> {
51//!         Ok(self.config.clone())
52//!     }
53//!
54//!     fn provider_name(&self) -> &str {
55//!         "my-extension-tls"
56//!     }
57//!
58//!     fn config_type_name(&self) -> &str {
59//!         "String" // In practice: "rustls::ClientConfig"
60//!     }
61//!
62//!     fn min_tls_version(&self) -> TlsVersion {
63//!         TlsVersion::Tls12
64//!     }
65//!
66//!     fn supports_mtls(&self) -> bool {
67//!         self.mtls_enabled
68//!     }
69//!
70//!     fn accepts_invalid_certs(&self) -> bool {
71//!         false
72//!     }
73//! }
74//! ```
75
76use std::any::Any;
77use std::sync::Arc;
78
79use crate::error::ExtensionError;
80
81/// Minimum TLS protocol version supported by a [`TlsConfigProvider`].
82///
83/// Used for security auditing and warning generation. Providers that allow
84/// versions below [`Tls12`][TlsVersion::Tls12] should emit a warning via
85/// [`WarningCollector`][crate::warning::WarningCollector].
86///
87/// `#[non_exhaustive]`: a later TLS version may be added, so a `match`
88/// outside quack-rs needs a wildcard arm; comparisons (`>=
89/// TlsVersion::Tls12`) keep working.
90///
91/// ```rust,compile_fail,E0004
92/// use quack_rs::tls::TlsVersion;
93///
94/// fn modern(version: TlsVersion) -> bool {
95///     match version {
96///         TlsVersion::Tls10 | TlsVersion::Tls11 => false,
97///         TlsVersion::Tls12 | TlsVersion::Tls13 => true,
98///         // error[E0004]: a wildcard arm is required
99///     }
100/// }
101/// ```
102#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
103#[non_exhaustive]
104pub enum TlsVersion {
105    /// TLS 1.0 — **deprecated** per [RFC 8996](https://datatracker.ietf.org/doc/html/rfc8996).
106    Tls10,
107    /// TLS 1.1 — **deprecated** per [RFC 8996](https://datatracker.ietf.org/doc/html/rfc8996).
108    Tls11,
109    /// TLS 1.2 — minimum recommended version.
110    Tls12,
111    /// TLS 1.3 — preferred version.
112    Tls13,
113}
114
115impl TlsVersion {
116    /// Returns `true` if this version is considered deprecated (TLS 1.0 or 1.1).
117    #[must_use]
118    #[inline]
119    pub const fn is_deprecated(self) -> bool {
120        matches!(self, Self::Tls10 | Self::Tls11)
121    }
122}
123
124impl std::fmt::Display for TlsVersion {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        match self {
127            Self::Tls10 => f.write_str("TLS 1.0"),
128            Self::Tls11 => f.write_str("TLS 1.1"),
129            Self::Tls12 => f.write_str("TLS 1.2"),
130            Self::Tls13 => f.write_str("TLS 1.3"),
131        }
132    }
133}
134
135/// A type-erased provider of TLS client configuration.
136///
137/// Extensions that make outbound HTTPS connections implement this trait to
138/// supply their TLS setup (client certificates, custom CA bundles, etc.)
139/// without coupling `quack-rs` to a specific TLS library.
140///
141/// # Downcasting
142///
143/// The returned `Arc<dyn Any + Send + Sync>` should be downcast by the
144/// consumer to the concrete config type. Use [`config_type_name`][Self::config_type_name]
145/// to verify the expected type before downcasting, and handle `None` from
146/// `downcast_ref` gracefully (never use `.expect()` or
147/// `.unwrap()` in FFI callback contexts — see Pitfall L3).
148///
149/// ```rust,no_run
150/// use std::any::Any;
151/// use std::sync::Arc;
152/// use quack_rs::error::ExtensionError;
153///
154/// fn use_config(config: Arc<dyn Any + Send + Sync>) -> Result<(), ExtensionError> {
155///     // let rustls_config = config.downcast_ref::<rustls::ClientConfig>()
156///     //     .ok_or(ExtensionError::new("expected rustls::ClientConfig"))?;
157///     Ok(())
158/// }
159/// ```
160///
161/// # Security
162///
163/// See the [module-level documentation][crate::tls] for security requirements.
164/// Implementations that bypass certificate validation or allow deprecated TLS
165/// versions should clearly document this and emit warnings.
166pub trait TlsConfigProvider: Send + Sync {
167    /// Returns the TLS client configuration as a type-erased `Arc`.
168    ///
169    /// Implementations should return an `Arc` wrapping their concrete TLS
170    /// config type (e.g., `Arc<rustls::ClientConfig>`).
171    ///
172    /// # Errors
173    ///
174    /// Returns an [`ExtensionError`] if the configuration cannot be created
175    /// (e.g., certificate file not found, invalid key format, expired CA).
176    fn client_config(&self) -> Result<Arc<dyn Any + Send + Sync>, ExtensionError>;
177
178    /// Returns a human-readable name for this TLS provider.
179    ///
180    /// Used in diagnostics, warning messages, and error context.
181    fn provider_name(&self) -> &str;
182
183    /// Returns the concrete type name of the config returned by [`client_config`][Self::client_config].
184    ///
185    /// This allows consumers to verify they have the right provider before
186    /// attempting a downcast. For example, a `rustls`-based provider would
187    /// return `"rustls::ClientConfig"`.
188    fn config_type_name(&self) -> &str;
189
190    /// Returns the minimum TLS protocol version this config allows.
191    ///
192    /// Implementations should return [`TlsVersion::Tls12`] or higher.
193    /// Returning a deprecated version ([`TlsVersion::Tls10`] or
194    /// [`TlsVersion::Tls11`]) should trigger a warning via
195    /// [`WarningCollector`][crate::warning::WarningCollector].
196    fn min_tls_version(&self) -> TlsVersion;
197
198    /// Returns `true` if this config includes a client certificate for mTLS.
199    fn supports_mtls(&self) -> bool;
200
201    /// Returns `true` if this config accepts invalid (self-signed, expired,
202    /// or hostname-mismatched) server certificates.
203    ///
204    /// # Security
205    ///
206    /// This should return `false` by default. Returning `true` disables
207    /// server certificate validation (CWE-295: Improper Certificate
208    /// Validation) and should **only** be enabled when explicitly requested
209    /// by the user (e.g., via a `SET` variable or connection parameter).
210    ///
211    /// When this returns `true`, the extension should emit an
212    /// [`ExtensionWarning`][crate::warning::ExtensionWarning] with
213    /// `code: "TLS_NO_VERIFY"`, `severity: High`, and `cwe: Some(295)`.
214    fn accepts_invalid_certs(&self) -> bool;
215}
216
217/// Validates a [`TlsConfigProvider`] and returns a list of security concerns.
218///
219/// This is a convenience function that checks common misconfigurations and
220/// returns human-readable warning messages. Extensions can call this during
221/// initialization and feed the results into a
222/// [`WarningCollector`][crate::warning::WarningCollector].
223///
224/// # Example
225///
226/// ```rust,no_run
227/// use quack_rs::tls::audit_tls_provider;
228/// use quack_rs::warning::{WarningCollector, ExtensionWarning, WarningSeverity};
229///
230/// // let warnings = audit_tls_provider(&my_provider);
231/// // let collector = WarningCollector::new();
232/// // for w in warnings {
233/// //     collector.emit(w);
234/// // }
235/// ```
236#[must_use]
237pub fn audit_tls_provider(
238    provider: &dyn TlsConfigProvider,
239) -> Vec<crate::warning::ExtensionWarning> {
240    let mut warnings = Vec::new();
241
242    if provider.accepts_invalid_certs() {
243        warnings.push(crate::warning::ExtensionWarning {
244            code: "TLS_NO_VERIFY",
245            severity: crate::warning::WarningSeverity::High,
246            message: format!(
247                "TLS provider {:?} has certificate verification disabled",
248                provider.provider_name()
249            ),
250            cwe: Some(295),
251        });
252    }
253
254    let min_version = provider.min_tls_version();
255    if min_version.is_deprecated() {
256        warnings.push(crate::warning::ExtensionWarning {
257            code: "TLS_DEPRECATED_VERSION",
258            severity: crate::warning::WarningSeverity::Medium,
259            message: format!(
260                "TLS provider {:?} allows deprecated {} (RFC 8996)",
261                provider.provider_name(),
262                min_version,
263            ),
264            cwe: Some(327), // CWE-327: Use of a Broken or Risky Cryptographic Algorithm
265        });
266    }
267
268    warnings
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    struct SecureProvider {
276        config: Arc<String>,
277    }
278
279    #[allow(clippy::unnecessary_literal_bound)]
280    impl TlsConfigProvider for SecureProvider {
281        fn client_config(&self) -> Result<Arc<dyn Any + Send + Sync>, ExtensionError> {
282            Ok(self.config.clone())
283        }
284
285        fn provider_name(&self) -> &str {
286            "test-secure"
287        }
288
289        fn config_type_name(&self) -> &str {
290            "String"
291        }
292
293        fn min_tls_version(&self) -> TlsVersion {
294            TlsVersion::Tls12
295        }
296
297        fn supports_mtls(&self) -> bool {
298            false
299        }
300
301        fn accepts_invalid_certs(&self) -> bool {
302            false
303        }
304    }
305
306    struct InsecureProvider;
307
308    #[allow(clippy::unnecessary_literal_bound)]
309    impl TlsConfigProvider for InsecureProvider {
310        fn client_config(&self) -> Result<Arc<dyn Any + Send + Sync>, ExtensionError> {
311            Ok(Arc::new(42u32))
312        }
313
314        fn provider_name(&self) -> &str {
315            "test-insecure"
316        }
317
318        fn config_type_name(&self) -> &str {
319            "u32"
320        }
321
322        fn min_tls_version(&self) -> TlsVersion {
323            TlsVersion::Tls10
324        }
325
326        fn supports_mtls(&self) -> bool {
327            false
328        }
329
330        fn accepts_invalid_certs(&self) -> bool {
331            true
332        }
333    }
334
335    struct FailingProvider;
336
337    #[allow(clippy::unnecessary_literal_bound)]
338    impl TlsConfigProvider for FailingProvider {
339        fn client_config(&self) -> Result<Arc<dyn Any + Send + Sync>, ExtensionError> {
340            Err(ExtensionError::new("certificate file not found"))
341        }
342
343        fn provider_name(&self) -> &str {
344            "test-failing"
345        }
346
347        fn config_type_name(&self) -> &str {
348            "never"
349        }
350
351        fn min_tls_version(&self) -> TlsVersion {
352            TlsVersion::Tls13
353        }
354
355        fn supports_mtls(&self) -> bool {
356            true
357        }
358
359        fn accepts_invalid_certs(&self) -> bool {
360            false
361        }
362    }
363
364    #[test]
365    fn secure_provider_returns_config() {
366        let provider = SecureProvider {
367            config: Arc::new("test-config".to_string()),
368        };
369        let config = provider.client_config().unwrap();
370        let s = config.downcast_ref::<String>().unwrap();
371        assert_eq!(s, "test-config");
372    }
373
374    #[test]
375    fn secure_provider_metadata() {
376        let provider = SecureProvider {
377            config: Arc::new(String::new()),
378        };
379        assert_eq!(provider.provider_name(), "test-secure");
380        assert_eq!(provider.config_type_name(), "String");
381        assert_eq!(provider.min_tls_version(), TlsVersion::Tls12);
382        assert!(!provider.supports_mtls());
383        assert!(!provider.accepts_invalid_certs());
384    }
385
386    #[test]
387    fn failing_provider_returns_error() {
388        let provider = FailingProvider;
389        let err = provider.client_config().unwrap_err();
390        assert_eq!(err.as_str(), "certificate file not found");
391        assert!(provider.supports_mtls());
392    }
393
394    #[test]
395    fn downcast_wrong_type_returns_none() {
396        let provider = SecureProvider {
397            config: Arc::new("hello".to_string()),
398        };
399        let config = provider.client_config().unwrap();
400        // Trying to downcast String to u32 should return None, not panic.
401        assert!(config.downcast_ref::<u32>().is_none());
402    }
403
404    #[test]
405    fn audit_secure_provider_no_warnings() {
406        let provider = SecureProvider {
407            config: Arc::new(String::new()),
408        };
409        let warnings = audit_tls_provider(&provider);
410        assert!(warnings.is_empty());
411    }
412
413    #[test]
414    fn audit_insecure_provider_flags_issues() {
415        let provider = InsecureProvider;
416        let warnings = audit_tls_provider(&provider);
417
418        assert_eq!(warnings.len(), 2);
419
420        // Should flag invalid cert acceptance (CWE-295).
421        let cert_warning = warnings.iter().find(|w| w.code == "TLS_NO_VERIFY");
422        assert!(cert_warning.is_some());
423        assert_eq!(cert_warning.unwrap().cwe, Some(295));
424        assert_eq!(
425            cert_warning.unwrap().severity,
426            crate::warning::WarningSeverity::High
427        );
428
429        // Should flag deprecated TLS version (CWE-327).
430        let version_warning = warnings.iter().find(|w| w.code == "TLS_DEPRECATED_VERSION");
431        assert!(version_warning.is_some());
432        assert_eq!(version_warning.unwrap().cwe, Some(327));
433        assert!(version_warning.unwrap().message.contains("TLS 1.0"));
434    }
435
436    #[test]
437    fn tls_version_ordering() {
438        assert!(TlsVersion::Tls10 < TlsVersion::Tls11);
439        assert!(TlsVersion::Tls11 < TlsVersion::Tls12);
440        assert!(TlsVersion::Tls12 < TlsVersion::Tls13);
441    }
442
443    #[test]
444    fn tls_version_deprecated() {
445        assert!(TlsVersion::Tls10.is_deprecated());
446        assert!(TlsVersion::Tls11.is_deprecated());
447        assert!(!TlsVersion::Tls12.is_deprecated());
448        assert!(!TlsVersion::Tls13.is_deprecated());
449    }
450
451    #[test]
452    fn tls_version_display() {
453        assert_eq!(TlsVersion::Tls10.to_string(), "TLS 1.0");
454        assert_eq!(TlsVersion::Tls11.to_string(), "TLS 1.1");
455        assert_eq!(TlsVersion::Tls12.to_string(), "TLS 1.2");
456        assert_eq!(TlsVersion::Tls13.to_string(), "TLS 1.3");
457    }
458
459    #[test]
460    fn provider_is_send_sync() {
461        fn assert_send_sync<T: Send + Sync>() {}
462        assert_send_sync::<SecureProvider>();
463    }
464
465    #[test]
466    fn trait_object_is_send_sync() {
467        fn assert_send_sync<T: Send + Sync + ?Sized>() {}
468        assert_send_sync::<dyn TlsConfigProvider>();
469    }
470
471    #[test]
472    fn tls11_is_deprecated() {
473        // TLS 1.1 must also be flagged as deprecated (not just TLS 1.0)
474        struct Tls11Provider;
475
476        #[allow(clippy::unnecessary_literal_bound)]
477        impl TlsConfigProvider for Tls11Provider {
478            fn client_config(&self) -> Result<Arc<dyn Any + Send + Sync>, ExtensionError> {
479                Ok(Arc::new(()))
480            }
481            fn provider_name(&self) -> &str {
482                "tls11-test"
483            }
484            fn config_type_name(&self) -> &str {
485                "()"
486            }
487            fn min_tls_version(&self) -> TlsVersion {
488                TlsVersion::Tls11
489            }
490            fn supports_mtls(&self) -> bool {
491                false
492            }
493            fn accepts_invalid_certs(&self) -> bool {
494                false
495            }
496        }
497
498        let warnings = audit_tls_provider(&Tls11Provider);
499        assert_eq!(warnings.len(), 1);
500        assert_eq!(warnings[0].code, "TLS_DEPRECATED_VERSION");
501        assert!(warnings[0].message.contains("TLS 1.1"));
502    }
503
504    #[test]
505    fn tls13_no_warnings() {
506        struct Tls13Provider;
507
508        #[allow(clippy::unnecessary_literal_bound)]
509        impl TlsConfigProvider for Tls13Provider {
510            fn client_config(&self) -> Result<Arc<dyn Any + Send + Sync>, ExtensionError> {
511                Ok(Arc::new(()))
512            }
513            fn provider_name(&self) -> &str {
514                "tls13-test"
515            }
516            fn config_type_name(&self) -> &str {
517                "()"
518            }
519            fn min_tls_version(&self) -> TlsVersion {
520                TlsVersion::Tls13
521            }
522            fn supports_mtls(&self) -> bool {
523                true
524            }
525            fn accepts_invalid_certs(&self) -> bool {
526                false
527            }
528        }
529
530        let warnings = audit_tls_provider(&Tls13Provider);
531        assert!(warnings.is_empty());
532    }
533
534    #[test]
535    fn audit_only_invalid_certs_not_deprecated_version() {
536        // Provider with valid TLS version but invalid certs accepted
537        struct CertOnlyInsecure;
538
539        #[allow(clippy::unnecessary_literal_bound)]
540        impl TlsConfigProvider for CertOnlyInsecure {
541            fn client_config(&self) -> Result<Arc<dyn Any + Send + Sync>, ExtensionError> {
542                Ok(Arc::new(()))
543            }
544            fn provider_name(&self) -> &str {
545                "cert-insecure"
546            }
547            fn config_type_name(&self) -> &str {
548                "()"
549            }
550            fn min_tls_version(&self) -> TlsVersion {
551                TlsVersion::Tls13
552            }
553            fn supports_mtls(&self) -> bool {
554                false
555            }
556            fn accepts_invalid_certs(&self) -> bool {
557                true
558            }
559        }
560
561        let warnings = audit_tls_provider(&CertOnlyInsecure);
562        assert_eq!(warnings.len(), 1);
563        assert_eq!(warnings[0].code, "TLS_NO_VERIFY");
564        assert_eq!(warnings[0].cwe, Some(295));
565    }
566
567    #[test]
568    fn tls_version_is_not_deprecated() {
569        assert!(!TlsVersion::Tls12.is_deprecated());
570        assert!(!TlsVersion::Tls13.is_deprecated());
571    }
572
573    #[test]
574    fn failing_provider_metadata() {
575        let provider = FailingProvider;
576        assert_eq!(provider.provider_name(), "test-failing");
577        assert_eq!(provider.config_type_name(), "never");
578        assert_eq!(provider.min_tls_version(), TlsVersion::Tls13);
579        assert!(!provider.accepts_invalid_certs());
580    }
581}