Skip to main content

rama/http/
tls.rs

1//! tls features provided from the http layer.
2
3use crate::error::{BoxError, BoxErrorExt, ErrorContext as _, ErrorExt as _};
4use crate::graceful::WeakScope;
5use crate::http::{
6    BodyExtractExt as _, Request, Response, StatusCode, client::EasyHttpWebClient,
7    service::client::HttpClientExt as _,
8};
9use crate::net::address::{AsDomainRef, Domain, DomainTrie};
10use crate::net::uri::Uri;
11use crate::telemetry::tracing;
12use crate::tls::server::{
13    CertificateIdentity, CertificateIssuanceContext, DynamicCertIssuer, ServerAuthData,
14};
15use crate::{Service, service::BoxService};
16
17use base64::Engine;
18use base64::engine::general_purpose::STANDARD as ENGINE;
19use rama_core::error::extra::OpaqueError;
20use rama_core::layer::MapErr;
21use rama_crypto::pki_types::pem::PemObject;
22use rama_crypto::pki_types::{CertificateDer, PrivateKeyDer};
23use serde::{Deserialize, Serialize};
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26/// Json input used as http (POST) request payload sent by the [`CertIssuerHttpClient`].
27pub struct CertOrderInput {
28    pub domain: Domain,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32/// Json payload expected in
33/// the http (POST) response payload as received by the [`CertIssuerHttpClient`].
34pub struct CertOrderOutput {
35    pub crt_pem_base64: String,
36    pub key_pem_base64: String,
37}
38
39#[derive(Debug)]
40/// An http client used to fetch certs dynamically ([`DynamicCertIssuer`]).
41///
42/// There is no server implementation in Rama.
43/// It is up to the user of this client to provide their own server, including
44/// authentication and authorization for every certificate order.
45pub struct CertIssuerHttpClient {
46    endpoint: Uri,
47    // Trie value `None` means an exact entry; `Some(wildcard)` is a subtree
48    // entry, storing the issuing-form wildcard (e.g. `"*.foo.com"`) so
49    // `normalize_identity` can return the wildcard as the cache key.
50    allow_list: Option<DomainTrie<Option<Domain>>>,
51    http_client: BoxService<Request, Response, OpaqueError>,
52}
53
54impl CertIssuerHttpClient {
55    /// Create a new [`CertIssuerHttpClient`] using the default [`EasyHttpWebClient`].
56    pub fn new(scope: impl Into<WeakScope>, endpoint: Uri) -> Self {
57        let scope = scope.into();
58        Self::new_with_client(endpoint, EasyHttpWebClient::default_with_scope(scope))
59    }
60
61    #[cfg(feature = "boring")]
62    #[cfg_attr(docsrs, doc(cfg(feature = "boring")))]
63    pub fn try_from_env(scope: impl Into<WeakScope>) -> Result<Self, BoxError> {
64        let scope = scope.into();
65        use crate::{
66            Layer as _,
67            http::{headers::Authorization, layer::set_header::SetRequestHeaderLayer},
68            net::user::Bearer,
69            tls::boring::{
70                client::BoringClientConfigExt as _,
71                core::x509::{X509, store::X509StoreBuilder},
72            },
73            tls::client::TlsClientConfig,
74        };
75        use std::sync::Arc;
76
77        let uri_raw = std::env::var("RAMA_TLS_REMOTE").context("RAMA_TLS_REMOTE is undefined")?;
78
79        let mut tls_config = TlsClientConfig::new().with_alpn_http_auto();
80
81        if let Ok(remote_ca_raw) = std::env::var("RAMA_TLS_REMOTE_CA") {
82            let mut store_builder = X509StoreBuilder::new().context("build x509 store builder")?;
83            store_builder
84                .add_cert(
85                    X509::from_pem(
86                        &ENGINE
87                            .decode(remote_ca_raw)
88                            .context("base64 decode RAMA_TLS_REMOTE_CA")?[..],
89                    )
90                    .context("load CA cert")?,
91                )
92                .context("add CA cert to store builder")?;
93            let store = store_builder.build();
94            tls_config.set_server_verify_cert_store(Arc::new(store));
95        }
96
97        let client = EasyHttpWebClient::connector_builder(scope)
98            .with_default_tcp_connector()
99            .with_default_dns_connector()
100            .without_proxy_support()
101            .with_tls_support_using_boringssl(tls_config)
102            .with_default_http_connector()
103            .without_connection_pool()
104            .build_client();
105
106        let uri: Uri = uri_raw.parse().context("parse RAMA_TLS_REMOTE as URI")?;
107        let mut client = if let Ok(auth_raw) = std::env::var("RAMA_TLS_REMOTE_AUTH") {
108            Self::new_with_client(
109                uri,
110                SetRequestHeaderLayer::overriding_typed(Authorization::new(
111                    Bearer::try_from(auth_raw)
112                        .context("try to create Bearer using RAMA_TLS_REMOTE_AUTH")?,
113                ))
114                .into_layer(client),
115            )
116        } else {
117            Self::new_with_client(uri, client)
118        };
119
120        if let Ok(allow_cn_csv_raw) = std::env::var("RAMA_TLS_REMOTE_CN_CSV") {
121            for raw_cn_str in allow_cn_csv_raw.split(',') {
122                let cn: Domain = raw_cn_str.parse().context("parse CN as a a valid domain")?;
123                client.set_allow_domain(cn);
124            }
125        }
126
127        Ok(client)
128    }
129
130    /// Create a new [`CertIssuerHttpClient`] using a custom http client.
131    ///
132    /// The custom http client allows you to add whatever layers and client implementation
133    /// you wish, to allow for custom headers, behaviour and security measures
134    /// such as authorization.
135    pub fn new_with_client(
136        endpoint: Uri,
137        client: impl Service<
138            Request,
139            Output = Response,
140            Error: std::error::Error + Send + Sync + 'static,
141        >,
142    ) -> Self {
143        let http_client = MapErr::into_opaque_error(client).boxed();
144        Self {
145            endpoint,
146            allow_list: None,
147            http_client,
148        }
149    }
150
151    crate::utils::macros::generate_set_and_with! {
152        /// Only allow fetching certs for the given domain.
153        ///
154        /// By default, if none of the `allow_*` setters are called
155        /// the client will fetch for any client. This is a local pre-filter;
156        /// the remote issuer remains responsible for authorizing each order.
157        pub fn allow_domain(mut self, domain: impl AsDomainRef) -> Self {
158            // The trie's smart insert handles "*.x" -> subtree at x and bare
159            // "x" -> exact at x. The stored value is just the wildcard form
160            // for subtree entries (so normalize_identity can return it).
161            let wildcard_form = domain.as_wildcard();
162            self.allow_list
163                .get_or_insert_default()
164                .insert_domain(domain, wildcard_form);
165            self
166        }
167    }
168
169    crate::utils::macros::generate_set_and_with! {
170        /// Only allow fetching certs for the given domains.
171        ///
172        /// By default, if none of the `allow_*` setters are called
173        /// the client will fetch for any client. This is a local pre-filter;
174        /// the remote issuer remains responsible for authorizing each order.
175        pub fn allow_domains(mut self, domains: impl IntoIterator<Item: AsDomainRef>) -> Self {
176            for domain in domains {
177                self.set_allow_domain(domain);
178            }
179            self
180        }
181    }
182
183    /// Prefetch all certificates, useful to warm them up at startup time.
184    pub async fn prefetch_certs(&self) {
185        if let Some(allow_list) = &self.allow_list {
186            // iter() yields the wildcard form for subtree entries and the
187            // apex for exact entries; both are the issuing form we want.
188            for (domain, _) in allow_list.iter() {
189                match self.fetch_certs(domain.clone()).await {
190                    Ok(_) => tracing::debug!("prefetched certificates for domain: {domain}"),
191                    Err(err) => tracing::error!(
192                        "failed to prefetch certificates for domain '{domain}': {err}"
193                    ),
194                }
195            }
196        }
197    }
198
199    async fn fetch_certs(&self, domain: Domain) -> Result<ServerAuthData, BoxError> {
200        let response = self
201            .http_client
202            .post(self.endpoint.clone())
203            .json(&CertOrderInput { domain })
204            .send()
205            .await
206            .context("send order request")?;
207
208        let status = response.status();
209        if status != StatusCode::OK {
210            return Err(
211                BoxError::from_static_str("unexpected dinocert order response")
212                    .context_field("status", status),
213            );
214        }
215
216        let CertOrderOutput {
217            crt_pem_base64,
218            key_pem_base64,
219        } = response
220            .into_body()
221            .try_into_json()
222            .await
223            .context("fetch json crt order response")?;
224
225        let crt = ENGINE.decode(crt_pem_base64).context("base64 decode crt")?;
226        let key = ENGINE.decode(key_pem_base64).context("base64 decode crt")?;
227
228        let cert_chain = CertificateDer::pem_slice_iter(&crt)
229            .collect::<Result<Vec<_>, _>>()
230            .context("parse crt pem chain")?;
231        let private_key =
232            PrivateKeyDer::from_pem_slice(key.as_slice()).context("parse private key")?;
233
234        Ok(ServerAuthData {
235            cert_chain,
236            private_key,
237            ocsp: None,
238        })
239    }
240}
241
242impl DynamicCertIssuer for CertIssuerHttpClient {
243    async fn issue_cert(
244        &self,
245        context: CertificateIssuanceContext,
246    ) -> Result<ServerAuthData, BoxError> {
247        let domain = match context.server_identity {
248            Some(CertificateIdentity::Dns(domain)) => {
249                if let Some(ref allow_list) = self.allow_list {
250                    match allow_list.get(&domain) {
251                        None => {
252                            return Err(BoxError::from_static_str(
253                                "sni found: unexpected unknown domain",
254                            )
255                            .with_context_field("domain", || domain.clone()));
256                        }
257                        Some(m) => match m.value {
258                            // Subtree match — issue using the stored wildcard form.
259                            Some(wildcard) => wildcard.clone(),
260                            // Exact match — issue for the queried domain itself.
261                            None => domain,
262                        },
263                    }
264                } else {
265                    domain
266                }
267            }
268            Some(CertificateIdentity::Ip(ip)) => {
269                return Err(BoxError::from_static_str(
270                    "remote certificate issuer only supports DNS identities",
271                )
272                .context_field("ip", ip));
273            }
274            None => {
275                return Err(BoxError::from_static_str("no server identity found"));
276            }
277        };
278
279        self.fetch_certs(domain).await
280    }
281
282    fn normalize_identity(&self, identity: &CertificateIdentity) -> Option<CertificateIdentity> {
283        let CertificateIdentity::Dns(domain) = identity else {
284            return None;
285        };
286        self.allow_list
287            .as_ref()?
288            .get(domain)
289            .and_then(|m| m.value.as_ref())
290            .cloned()
291            .map(CertificateIdentity::Dns)
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn test_issuer_kind_normalize_identity() {
301        let issuer = CertIssuerHttpClient::new(
302            WeakScope::detached(),
303            Uri::from_static("http://example.com"),
304        )
305        .with_allow_domains(["*.foo.com", "bar.org", "*.example.io", "example.net"]);
306        for (input, expected) in [
307            ("example.com", None),
308            ("www.foo.com", Some("*.foo.com")),
309            ("bar.foo.com", Some("*.foo.com")),
310            ("bar.example.io", Some("*.example.io")),
311            ("example.net", None),
312            ("foo.example.net", None),
313            ("foo.bar.org", None),
314            ("bar.org", None),
315        ] {
316            let output = issuer
317                .normalize_identity(&CertificateIdentity::Dns(Domain::from_static(input)))
318                .and_then(|identity| match identity {
319                    CertificateIdentity::Dns(domain) => Some(domain),
320                    CertificateIdentity::Ip(_) => None,
321                });
322            assert_eq!(
323                output.as_ref().map(Domain::as_str),
324                expected,
325                "{input:?} ; {expected:?}"
326            )
327        }
328    }
329}