Skip to main content

rushls_common/outbound/
client_tls.rs

1//! Mutual TLS material for one outbound destination.
2//!
3//! Admission and hooks both call operator-run services over a network the
4//! operator may not consider private, and the trust question is the same on
5//! each: prove this node to the service with a client certificate, and prove
6//! the service to this node by pinning its issuer. Both applications configure
7//! it with the same three keys, `client_cert`, `client_key`, and `ca`; this is
8//! what those keys resolve to.
9
10use std::{path::PathBuf, sync::Arc, time::Duration};
11
12use crate::tls::{ClientIdentity, TlsError, TlsObserver, load_roots};
13use rustls::pki_types::CertificateDer;
14use thiserror::Error;
15
16use crate::outbound::{ClientConfig, HttpClient, OutboundError};
17
18/// The paths one destination configures; all optional.
19#[derive(Clone, Debug, Default, Eq, PartialEq)]
20pub struct ClientTlsFiles {
21    /// PEM certificate chain this node presents, leaf first.
22    pub certificate: Option<PathBuf>,
23    /// PEM private key for that chain.
24    pub key: Option<PathBuf>,
25    /// PEM authority to trust instead of the platform store.
26    pub ca: Option<PathBuf>,
27}
28
29/// Why a destination's TLS material is unusable.
30#[derive(Debug, Error)]
31pub enum ClientTlsError {
32    /// Half a pair is a misconfiguration rather than a partial identity:
33    /// presenting a certificate needs its key, and a key alone proves nothing.
34    /// Refused rather than ignored, because a node that silently presented no
35    /// identity would be rejected by the service later, with nothing to
36    /// explain why.
37    #[error("client_cert is set without client_key")]
38    MissingKey,
39    #[error("client_key is set without client_cert")]
40    MissingCertificate,
41    #[error(transparent)]
42    Tls(#[from] TlsError),
43}
44
45impl ClientTlsFiles {
46    /// Whether anything here needs a client of its own.
47    pub fn is_configured(&self) -> bool {
48        self.certificate.is_some() || self.key.is_some() || self.ca.is_some()
49    }
50
51    /// Loads the identity and roots, starting a watch for identity rotations.
52    ///
53    /// The watch lives in the returned [`ClientTls`]; hold it for as long as
54    /// its clients are used, or rotations stop being noticed. With a client
55    /// certificate configured this must run inside a Tokio runtime, which
56    /// drives the watch.
57    pub fn load<O: TlsObserver>(&self, observer: Arc<O>) -> Result<ClientTls, ClientTlsError> {
58        let identity = match (&self.certificate, &self.key) {
59            (Some(certificate), Some(key)) => Some(ClientIdentity::new(
60                certificate.clone(),
61                key.clone(),
62                observer,
63            )?),
64            (None, None) => None,
65            (Some(_), None) => return Err(ClientTlsError::MissingKey),
66            (None, Some(_)) => return Err(ClientTlsError::MissingCertificate),
67        };
68        let roots = self.ca.as_deref().map(load_roots).transpose()?;
69        Ok(ClientTls { identity, roots })
70    }
71}
72
73/// Loaded outbound TLS material, holding its own rotation watch.
74pub struct ClientTls {
75    /// Held for its watch as much as its resolver: dropping it stops reloads.
76    identity: Option<ClientIdentity>,
77    roots: Option<Vec<CertificateDer<'static>>>,
78}
79
80impl ClientTls {
81    /// A client presenting this destination's identity, under its own limits.
82    ///
83    /// Deliberately not drawn from a shared connector: an identity and a
84    /// pinned authority belong to the destination that configured them, and
85    /// pooling connections across destinations would mean presenting one
86    /// service's certificate to another. The cost is one connection pool per
87    /// destination that asks for mutual TLS, which is what asking for it means.
88    pub fn client(
89        &self,
90        request_timeout: Duration,
91        maximum_response_bytes: usize,
92    ) -> Result<HttpClient, OutboundError> {
93        HttpClient::with_identity(
94            ClientConfig::default(),
95            self.identity.as_ref().map(ClientIdentity::resolver),
96            self.roots.clone(),
97        )
98        .map(|client| client.with_limits(request_timeout, maximum_response_bytes))
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use crate::tls::IgnoreTlsEvents;
106
107    fn files(certificate: Option<&str>, key: Option<&str>, ca: Option<&str>) -> ClientTlsFiles {
108        ClientTlsFiles {
109            certificate: certificate.map(PathBuf::from),
110            key: key.map(PathBuf::from),
111            ca: ca.map(PathBuf::from),
112        }
113    }
114
115    #[test]
116    fn half_a_pair_is_refused() {
117        let observer = Arc::new(IgnoreTlsEvents);
118        assert!(matches!(
119            files(Some("cert.pem"), None, None).load(Arc::clone(&observer)),
120            Err(ClientTlsError::MissingKey)
121        ));
122        assert!(matches!(
123            files(None, Some("key.pem"), None).load(observer),
124            Err(ClientTlsError::MissingCertificate)
125        ));
126    }
127
128    #[test]
129    fn nothing_configured_needs_no_client_of_its_own() -> Result<(), ClientTlsError> {
130        assert!(!ClientTlsFiles::default().is_configured());
131        assert!(files(None, None, Some("ca.pem")).is_configured());
132        // Unconfigured material loads to nothing rather than failing.
133        ClientTlsFiles::default().load(Arc::new(IgnoreTlsEvents))?;
134        Ok(())
135    }
136
137    #[test]
138    fn an_unreadable_authority_is_refused() {
139        let missing = files(None, None, Some("/nonexistent/rushls-ca.pem"));
140        assert!(matches!(
141            missing.load(Arc::new(IgnoreTlsEvents)),
142            Err(ClientTlsError::Tls(_))
143        ));
144    }
145}