ntex_tls/lib.rs
1//! TLS services and I/O filters for the ntex ecosystem.
2//!
3//! Acceptor services upgrade existing [`ntex_io::Io`] connections on the server
4//! side. Connector services open a transport and perform a client handshake.
5//! Both preserve any filters already installed below TLS.
6//!
7//! # Backends
8//!
9//! No backend is enabled by default:
10//!
11//! - `openssl` exposes OpenSSL acceptors, connectors, and a bidirectional filter.
12//! - `rustls` exposes rustls acceptors, connectors, and client/server filters.
13//! Supply a crypto provider through rustls configuration; `rustls-ring` enables
14//! its ring provider and also enables `rustls`.
15//! - `schannel` is kept for compatibility; Windows Schannel support is always
16//! compiled on Windows (required by `x509`). Protocols, cipher suites, and
17//! trust defaults depend on the operating system.
18//!
19//! The `x509` module (certificate parsing, trust verification, identities) is
20//! enabled by either TLS feature and always available on Windows. Windows uses
21//! Crypt32/CNG; elsewhere rustls takes precedence over OpenSSL.
22//! Explicitly enabling `x509` without a backend is an error.
23//!
24//! Certificate verification, identities, and ALPN are configured through the
25//! selected backend. [`TlsConfig`] controls service handshake timeouts, while
26//! [`max_concurrent_ssl_accept`] controls acceptor readiness backpressure.
27//! Low-level filter constructors and handshake functions have their own timeout
28//! contracts and do not participate in the acceptor concurrency limit.
29//!
30//! After negotiation, [`ntex_io::IoRef::query`] exposes connection metadata such
31//! as [`PeerCertDer`], [`Servername`], [`TlsVersion`], and [`TlsCipher`].
32//! Metadata availability depends on the backend and negotiated session.
33//!
34//! # Handshake configuration
35//!
36//! Attach this configuration to accepted I/O connections, or use it as the
37//! shared state of a connector service:
38//!
39//! ```
40//! use ntex_service::cfg::SharedCfg;
41//! use ntex_tls::TlsConfig;
42//! use ntex_util::time::Seconds;
43//!
44//! let config: SharedCfg = SharedCfg::new("TLS")
45//! .add(TlsConfig::new().set_handshake_timeout(Seconds(10)))
46//! .into();
47//! assert_eq!(
48//! config.get::<TlsConfig>().handshake_timeout(),
49//! ntex_util::time::Millis(10_000),
50//! );
51//! ```
52#![deny(clippy::pedantic)]
53#![allow(
54 clippy::clone_on_copy,
55 clippy::missing_fields_in_debug,
56 clippy::must_use_candidate,
57 clippy::missing_errors_doc,
58 clippy::unused_async_trait_impl
59)]
60use std::sync::atomic::{AtomicUsize, Ordering};
61
62#[cfg(feature = "openssl")]
63pub mod openssl;
64
65#[cfg(feature = "rustls")]
66pub mod rustls;
67
68#[cfg(windows)]
69pub mod schannel;
70
71#[cfg(windows)]
72mod win;
73
74#[cfg(all(
75 feature = "x509",
76 not(any(windows, feature = "openssl", feature = "rustls"))
77))]
78compile_error!("ntex-tls x509 requires the openssl or rustls feature outside Windows");
79
80#[cfg(any(windows, feature = "openssl", feature = "rustls"))]
81pub mod x509;
82
83use ntex_util::services::Counter;
84
85/// Shared timeout configuration for TLS services.
86mod config;
87/// Backend-independent connection metadata.
88mod types;
89mod utils;
90
91pub use self::config::TlsConfig;
92pub use self::types::{
93 PeerCertChainDer, PeerCertDer, PskIdentity, Servername, TlsCipher, TlsVersion,
94};
95
96/// Sets the per-worker soft limit on concurrent TLS handshakes.
97///
98/// TLS acceptors apply readiness backpressure when this limit is reached.
99/// Readiness does not reserve a slot: independent listener or service pipelines
100/// with cached readiness can still start handshakes and exceed the limit.
101/// This controls handshake load but is not a strict admission limit.
102///
103/// The counter is shared by all TLS acceptors constructed on the same thread.
104/// This call updates the current thread's counter and the initial limit for
105/// threads whose counters have not yet been initialized. It does not update
106/// counters already initialized on other threads; configure the limit before
107/// starting workers, or update each existing worker separately.
108///
109/// The default is 256. A limit of zero keeps acceptor readiness pending;
110/// it does not mean unlimited capacity. Direct handshake functions do not
111/// acquire slots.
112pub fn max_concurrent_ssl_accept(num: usize) {
113 MAX_SSL_ACCEPT.store(num, Ordering::Relaxed);
114 MAX_SSL_ACCEPT_COUNTER.with(|counts| counts.set_capacity(num));
115}
116
117/// Initial capacity read when a thread first creates its handshake counter.
118static MAX_SSL_ACCEPT: AtomicUsize = AtomicUsize::new(256);
119
120thread_local! {
121 /// Handshake load shared by acceptors on this thread, independent of other workers.
122 static MAX_SSL_ACCEPT_COUNTER: Counter = Counter::new(MAX_SSL_ACCEPT.load(Ordering::Relaxed));
123}
124
125/// Distinguishes a TLS failure from an application service failure.
126#[derive(Debug)]
127pub enum TlsError<E> {
128 /// TLS setup, handshake, or transport failure.
129 Tls(std::io::Error),
130 /// Error returned by the wrapped application service.
131 Service(E),
132}
133
134#[cfg(test)]
135mod tests {
136 use super::*;
137
138 /// STATEMENT: The configured handshake limit updates both the global limit and local capacity.
139 ///
140 /// HOW:
141 /// - Set the limit to 256 and check the atomic value.
142 /// - Hold 255 counter guards, then the final guard, and check availability at each step.
143 #[test]
144 fn max_concurrent_accept() {
145 // the default value, other tests use the limit
146 max_concurrent_ssl_accept(256);
147 assert_eq!(MAX_SSL_ACCEPT.load(Ordering::Relaxed), 256);
148 MAX_SSL_ACCEPT_COUNTER.with(|c| {
149 let _guards: Vec<_> = (0..255).map(|_| c.get()).collect();
150 assert!(c.is_available());
151 let _last = c.get();
152 assert!(!c.is_available());
153 });
154 }
155}