1use crate::error::{BoxError, BoxErrorExt, ErrorContext as _, ErrorExt as _};
4use crate::http::{
5 BodyExtractExt as _, Request, Response, StatusCode, client::EasyHttpWebClient,
6 service::client::HttpClientExt as _,
7};
8use crate::net::address::{AsDomainRef, Domain, DomainTrie};
9use crate::net::uri::Uri;
10use crate::rt::Executor;
11use crate::telemetry::tracing;
12use crate::tls::{
13 client::ClientHello,
14 server::{DynamicCertIssuer, ServerAuthData},
15};
16use crate::{Service, service::BoxService};
17
18use base64::Engine;
19use base64::engine::general_purpose::STANDARD as ENGINE;
20use rama_core::error::extra::OpaqueError;
21use rama_core::layer::MapErr;
22use rama_crypto::pki_types::pem::PemObject;
23use rama_crypto::pki_types::{CertificateDer, PrivateKeyDer};
24use serde::{Deserialize, Serialize};
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct CertOrderInput {
29 pub domain: Domain,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct CertOrderOutput {
36 pub crt_pem_base64: String,
37 pub key_pem_base64: String,
38}
39
40#[derive(Debug)]
41pub struct CertIssuerHttpClient {
47 endpoint: Uri,
48 allow_list: Option<DomainTrie<Option<Domain>>>,
52 http_client: BoxService<Request, Response, OpaqueError>,
53}
54
55impl CertIssuerHttpClient {
56 pub fn new(exec: Executor, endpoint: Uri) -> Self {
58 Self::new_with_client(endpoint, EasyHttpWebClient::default_with_executor(exec))
59 }
60
61 #[cfg(feature = "boring")]
62 #[cfg_attr(docsrs, doc(cfg(feature = "boring")))]
63 pub fn try_from_env(exec: Executor) -> Result<Self, BoxError> {
64 use crate::{
65 Layer as _,
66 http::{headers::Authorization, layer::set_header::SetRequestHeaderLayer},
67 net::user::Bearer,
68 tls::boring::{
69 client::BoringClientConfigExt as _,
70 core::x509::{X509, store::X509StoreBuilder},
71 },
72 tls::client::TlsClientConfig,
73 };
74 use std::sync::Arc;
75
76 let uri_raw = std::env::var("RAMA_TLS_REMOTE").context("RAMA_TLS_REMOTE is undefined")?;
77
78 let mut tls_config = TlsClientConfig::new().with_alpn_http_auto();
79
80 if let Ok(remote_ca_raw) = std::env::var("RAMA_TLS_REMOTE_CA") {
81 let mut store_builder = X509StoreBuilder::new().context("build x509 store builder")?;
82 store_builder
83 .add_cert(
84 X509::from_pem(
85 &ENGINE
86 .decode(remote_ca_raw)
87 .context("base64 decode RAMA_TLS_REMOTE_CA")?[..],
88 )
89 .context("load CA cert")?,
90 )
91 .context("add CA cert to store builder")?;
92 let store = store_builder.build();
93 tls_config.set_server_verify_cert_store(Arc::new(store));
94 }
95
96 let client = EasyHttpWebClient::connector_builder()
97 .with_default_transport_connector()
98 .with_default_dns_connector()
99 .without_tls_proxy_support()
100 .without_proxy_support()
101 .with_tls_support_using_boringssl(tls_config)
102 .with_default_http_connector(exec)
103 .build_client();
104
105 let uri: Uri = uri_raw.parse().context("parse RAMA_TLS_REMOTE as URI")?;
106 let mut client = if let Ok(auth_raw) = std::env::var("RAMA_TLS_REMOTE_AUTH") {
107 Self::new_with_client(
108 uri,
109 SetRequestHeaderLayer::overriding_typed(Authorization::new(
110 Bearer::try_from(auth_raw)
111 .context("try to create Bearer using RAMA_TLS_REMOTE_AUTH")?,
112 ))
113 .into_layer(client),
114 )
115 } else {
116 Self::new_with_client(uri, client)
117 };
118
119 if let Ok(allow_cn_csv_raw) = std::env::var("RAMA_TLS_REMOTE_CN_CSV") {
120 for raw_cn_str in allow_cn_csv_raw.split(',') {
121 let cn: Domain = raw_cn_str.parse().context("parse CN as a a valid domain")?;
122 client.set_allow_domain(cn);
123 }
124 }
125
126 Ok(client)
127 }
128
129 pub fn new_with_client(
135 endpoint: Uri,
136 client: impl Service<
137 Request,
138 Output = Response,
139 Error: std::error::Error + Send + Sync + 'static,
140 >,
141 ) -> Self {
142 let http_client = MapErr::into_opaque_error(client).boxed();
143 Self {
144 endpoint,
145 allow_list: None,
146 http_client,
147 }
148 }
149
150 crate::utils::macros::generate_set_and_with! {
151 pub fn allow_domain(mut self, domain: impl AsDomainRef) -> Self {
157 let wildcard_form = domain.as_wildcard();
161 self.allow_list
162 .get_or_insert_default()
163 .insert_domain(domain, wildcard_form);
164 self
165 }
166 }
167
168 crate::utils::macros::generate_set_and_with! {
169 pub fn allow_domains(mut self, domains: impl IntoIterator<Item: AsDomainRef>) -> Self {
175 for domain in domains {
176 self.set_allow_domain(domain);
177 }
178 self
179 }
180 }
181
182 pub async fn prefetch_certs(&self) {
184 if let Some(allow_list) = &self.allow_list {
185 for (domain, _) in allow_list.iter() {
188 match self.fetch_certs(domain.clone()).await {
189 Ok(_) => tracing::debug!("prefetched certificates for domain: {domain}"),
190 Err(err) => tracing::error!(
191 "failed to prefetch certificates for domain '{domain}': {err}"
192 ),
193 }
194 }
195 }
196 }
197
198 async fn fetch_certs(&self, domain: Domain) -> Result<ServerAuthData, BoxError> {
199 let response = self
200 .http_client
201 .post(self.endpoint.clone())
202 .json(&CertOrderInput { domain })
203 .send()
204 .await
205 .context("send order request")?;
206
207 let status = response.status();
208 if status != StatusCode::OK {
209 return Err(
210 BoxError::from_static_str("unexpected dinocert order response")
211 .context_field("status", status),
212 );
213 }
214
215 let CertOrderOutput {
216 crt_pem_base64,
217 key_pem_base64,
218 } = response
219 .into_body()
220 .try_into_json()
221 .await
222 .context("fetch json crt order response")?;
223
224 let crt = ENGINE.decode(crt_pem_base64).context("base64 decode crt")?;
225 let key = ENGINE.decode(key_pem_base64).context("base64 decode crt")?;
226
227 let cert_chain = CertificateDer::pem_slice_iter(&crt)
228 .collect::<Result<Vec<_>, _>>()
229 .context("parse crt pem chain")?;
230 let private_key =
231 PrivateKeyDer::from_pem_slice(key.as_slice()).context("parse private key")?;
232
233 Ok(ServerAuthData {
234 cert_chain,
235 private_key,
236 ocsp: None,
237 })
238 }
239}
240
241impl DynamicCertIssuer for CertIssuerHttpClient {
242 async fn issue_cert(
243 &self,
244 client_hello: ClientHello,
245 _server_name: Option<Domain>,
246 ) -> Result<ServerAuthData, BoxError> {
247 let domain = match client_hello.ext_server_name() {
248 Some(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 Some(wildcard) => wildcard.clone(),
260 None => domain.clone(),
262 },
263 }
264 } else {
265 domain.clone()
266 }
267 }
268 None => {
269 return Err(BoxError::from_static_str("no SNI found"));
270 }
271 };
272
273 self.fetch_certs(domain).await
274 }
275
276 fn norm_cn(&self, domain: &Domain) -> Option<&Domain> {
277 self.allow_list
278 .as_ref()?
279 .get(domain)
280 .and_then(|m| m.value.as_ref())
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[test]
289 fn test_issuer_kind_norm_cn() {
290 let issuer =
291 CertIssuerHttpClient::new(Executor::default(), Uri::from_static("http://example.com"))
292 .with_allow_domains(["*.foo.com", "bar.org", "*.example.io", "example.net"]);
293 for (input, expected) in [
294 ("example.com", None),
295 ("www.foo.com", Some("*.foo.com")),
296 ("bar.foo.com", Some("*.foo.com")),
297 ("bar.example.io", Some("*.example.io")),
298 ("example.net", None),
299 ("foo.example.net", None),
300 ("foo.bar.org", None),
301 ("bar.org", None),
302 ] {
303 let output = issuer
304 .norm_cn(&Domain::from_static(input))
305 .map(|d| d.as_str());
306 assert_eq!(output, expected, "{input:?} ; {expected:?}")
307 }
308 }
309}