tonic/transport/server/
tls.rs

1use std::{fmt, time::Duration};
2
3use super::service::TlsAcceptor;
4use crate::transport::tls::{Certificate, Identity};
5
6/// Configures TLS settings for servers.
7#[derive(Clone, Default)]
8pub struct ServerTlsConfig {
9    identity: Option<Identity>,
10    client_ca_root: Option<Certificate>,
11    client_auth_optional: bool,
12    ignore_client_order: bool,
13    use_key_log: bool,
14    timeout: Option<Duration>,
15}
16
17impl fmt::Debug for ServerTlsConfig {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        f.debug_struct("ServerTlsConfig").finish()
20    }
21}
22
23impl ServerTlsConfig {
24    /// Creates a new `ServerTlsConfig`.
25    pub fn new() -> Self {
26        ServerTlsConfig::default()
27    }
28
29    /// Sets the [`Identity`] of the server.
30    pub fn identity(self, identity: Identity) -> Self {
31        ServerTlsConfig {
32            identity: Some(identity),
33            ..self
34        }
35    }
36
37    /// Sets a certificate against which to validate client TLS certificates.
38    pub fn client_ca_root(self, cert: Certificate) -> Self {
39        ServerTlsConfig {
40            client_ca_root: Some(cert),
41            ..self
42        }
43    }
44
45    /// Sets whether client certificate verification is optional.
46    ///
47    /// This option has effect only if CA certificate is set.
48    ///
49    /// # Default
50    /// By default, this option is set to `false`.
51    pub fn client_auth_optional(self, optional: bool) -> Self {
52        ServerTlsConfig {
53            client_auth_optional: optional,
54            ..self
55        }
56    }
57
58    /// Sets whether the server's cipher preferences are followed instead of the client's.
59    ///
60    /// # Default
61    /// By default, this option is set to `false`.
62    pub fn ignore_client_order(self, ignore_client_order: bool) -> Self {
63        ServerTlsConfig {
64            ignore_client_order,
65            ..self
66        }
67    }
68
69    /// Use key log as specified by the `SSLKEYLOGFILE` environment variable.
70    pub fn use_key_log(self) -> Self {
71        ServerTlsConfig {
72            use_key_log: true,
73            ..self
74        }
75    }
76
77    /// Sets the timeout for the TLS handshake.
78    pub fn timeout(self, timeout: Duration) -> Self {
79        ServerTlsConfig {
80            timeout: Some(timeout),
81            ..self
82        }
83    }
84
85    pub(crate) fn tls_acceptor(&self) -> Result<TlsAcceptor, crate::BoxError> {
86        TlsAcceptor::new(
87            self.identity.as_ref().unwrap(),
88            self.client_ca_root.as_ref(),
89            self.client_auth_optional,
90            self.ignore_client_order,
91            self.use_key_log,
92            self.timeout,
93        )
94    }
95}