ntex_tls/config.rs
1use ntex_service::cfg::{CfgContext, Configuration};
2use ntex_util::time::{Millis, Seconds};
3
4#[derive(Debug)]
5/// Handshake timeout shared by TLS acceptor and connector services.
6///
7/// Acceptors obtain this value from the accepted connection's I/O configuration;
8/// connectors obtain it from their [`ntex_service::cfg::SharedCfg`] service state.
9/// The timeout covers TLS negotiation, not the underlying TCP connection attempt
10/// or the lifetime of an established connection.
11///
12/// This does not configure certificates, verification, ALPN, or protocol versions.
13/// Use the selected backend's configuration for those settings.
14pub struct TlsConfig {
15 /// Handshake deadline duration; zero disables the deadline.
16 pub(crate) handshake_timeout: Millis,
17 /// Configuration registry context used for service identity and diagnostics.
18 pub(crate) config: CfgContext,
19}
20
21impl Default for TlsConfig {
22 fn default() -> Self {
23 TlsConfig::new()
24 }
25}
26
27impl Configuration for TlsConfig {
28 const NAME: &str = "TLS Configuration";
29
30 fn ctx(&self) -> &CfgContext {
31 &self.config
32 }
33
34 fn set_ctx(&mut self, ctx: CfgContext) {
35 self.config = ctx;
36 }
37}
38
39impl TlsConfig {
40 #[must_use]
41 /// Creates a configuration with a five-second handshake timeout.
42 pub fn new() -> Self {
43 TlsConfig {
44 handshake_timeout: Millis(5_000),
45 config: CfgContext::default(),
46 }
47 }
48
49 #[inline]
50 /// Returns the handshake timeout; zero means no handshake deadline.
51 pub fn handshake_timeout(&self) -> Millis {
52 self.handshake_timeout
53 }
54
55 #[must_use]
56 /// Sets the handshake timeout using a duration convertible to seconds.
57 ///
58 /// Use [`Seconds::ZERO`] to disable the deadline. Expiration is reported as
59 /// [`std::io::ErrorKind::TimedOut`], wrapped in a connector error when applicable.
60 ///
61 /// The default is five seconds. Low-level handshake functions do not consult
62 /// this configuration unless their documentation explicitly says otherwise.
63 pub fn set_handshake_timeout<T: Into<Seconds>>(mut self, timeout: T) -> Self {
64 self.handshake_timeout = timeout.into().into();
65 self
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 /// STATEMENT: The default handshake timeout can be overridden or disabled.
74 ///
75 /// HOW:
76 /// - Check the default five-second timeout, change it to one second, then set it to zero.
77 /// - Compare the reported timeout in milliseconds after each change.
78 #[test]
79 fn tls_config() {
80 let cfg = TlsConfig::default();
81 assert_eq!(cfg.handshake_timeout(), Millis(5_000));
82 let cfg = cfg.set_handshake_timeout(Seconds(1));
83 assert_eq!(cfg.handshake_timeout(), Millis(1_000));
84 assert_eq!(
85 cfg.set_handshake_timeout(Seconds::ZERO).handshake_timeout(),
86 Millis::ZERO
87 );
88 }
89}