tonic/transport/server/
tls.rs

1use std::fmt;
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}
13
14impl fmt::Debug for ServerTlsConfig {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        f.debug_struct("ServerTlsConfig").finish()
17    }
18}
19
20impl ServerTlsConfig {
21    /// Creates a new `ServerTlsConfig`.
22    pub fn new() -> Self {
23        ServerTlsConfig {
24            identity: None,
25            client_ca_root: None,
26            client_auth_optional: false,
27        }
28    }
29
30    /// Sets the [`Identity`] of the server.
31    pub fn identity(self, identity: Identity) -> Self {
32        ServerTlsConfig {
33            identity: Some(identity),
34            ..self
35        }
36    }
37
38    /// Sets a certificate against which to validate client TLS certificates.
39    pub fn client_ca_root(self, cert: Certificate) -> Self {
40        ServerTlsConfig {
41            client_ca_root: Some(cert),
42            ..self
43        }
44    }
45
46    /// Sets whether client certificate verification is optional.
47    ///
48    /// This option has effect only if CA certificate is set.
49    ///
50    /// # Default
51    /// By default, this option is set to `false`.
52    pub fn client_auth_optional(self, optional: bool) -> Self {
53        ServerTlsConfig {
54            client_auth_optional: optional,
55            ..self
56        }
57    }
58
59    pub(crate) fn tls_acceptor(&self) -> Result<TlsAcceptor, crate::Error> {
60        TlsAcceptor::new(
61            self.identity.clone().unwrap(),
62            self.client_ca_root.clone(),
63            self.client_auth_optional,
64        )
65    }
66}