use std::sync::Arc;
use anyhow::Context;
use rustls::RootCertStore;
use tracing::warn;
use super::client_identity::ClientIdentity;
use super::tls::NoVerifier;
#[derive(Debug, Clone, Default)]
pub struct OutboundTls {
pub ca_pem: Option<String>,
pub skip_verify: bool,
}
impl OutboundTls {
pub fn client_config(&self) -> anyhow::Result<rustls::ClientConfig> {
self.client_config_with_identity(None)
}
pub fn client_config_with_identity(
&self,
identity: Option<&ClientIdentity>,
) -> anyhow::Result<rustls::ClientConfig> {
let finish = |builder: rustls::ConfigBuilder<
rustls::ClientConfig,
rustls::client::WantsClientCert,
>| match identity {
Some(identity) => builder.with_client_cert_resolver(Arc::new(
rustls::sign::SingleCertAndKey::from(identity.certified_key()),
)),
None => builder.with_no_client_auth(),
};
let provider = Arc::new(rustls::crypto::ring::default_provider());
let builder = rustls::ClientConfig::builder_with_provider(Arc::clone(&provider))
.with_safe_default_protocol_versions()
.context("building the outbound TLS configuration")?;
if self.skip_verify {
warn!(
"TLS certificate verification DISABLED for outbound connections \
(development/testing only)"
);
if self.ca_pem.is_some() {
warn!(
"an outbound CA was also supplied (--upstream-ca-file / upstreamCaPem); it is \
NOT read or used while verification is disabled"
);
}
return Ok(finish(
builder
.dangerous()
.with_custom_certificate_verifier(Arc::new(NoVerifier::new(&provider))),
));
}
let mut roots = RootCertStore::empty();
let native = rustls_native_certs::load_native_certs();
for error in &native.errors {
warn!(%error, "ignoring an unreadable entry in the OS trust store");
}
let (added, ignored) = roots.add_parsable_certificates(native.certs);
if ignored > 0 {
warn!(added, ignored, "some OS trust anchors were not usable");
}
if let Some(pem) = &self.ca_pem {
let extra: Vec<_> = rustls_pemfile::certs(&mut pem.as_bytes())
.collect::<Result<_, _>>()
.context("parsing the outbound CA certificate PEM")?;
if extra.is_empty() {
anyhow::bail!(
"no certificates found in the outbound CA PEM (--upstream-ca-file / \
upstreamCaPem): expected at least one -----BEGIN CERTIFICATE----- block"
);
}
let (_, ignored) = roots.add_parsable_certificates(extra);
if ignored > 0 {
anyhow::bail!(
"the outbound CA PEM contains {ignored} certificate(s) rustls cannot use"
);
}
}
if roots.is_empty() {
anyhow::bail!(
"no TLS trust anchors available: the OS trust store is empty or unreadable and no \
CA PEM was supplied. Install a CA bundle (e.g. ca-certificates), set \
SSL_CERT_FILE, or pass --upstream-ca-file"
);
}
Ok(finish(builder.with_root_certificates(roots)))
}
#[must_use]
pub fn is_configured(&self) -> bool {
self.ca_pem.is_some() || self.skip_verify
}
pub fn reqwest_client_config(&self) -> anyhow::Result<rustls::ClientConfig> {
self.reqwest_client_config_with_identity(None)
}
pub fn reqwest_client_config_with_identity(
&self,
identity: Option<&ClientIdentity>,
) -> anyhow::Result<rustls::ClientConfig> {
let mut config = self.client_config_with_identity(identity)?;
config.alpn_protocols = vec![b"http/1.1".to_vec()];
Ok(config)
}
pub fn reqwest_builder(&self) -> anyhow::Result<reqwest::ClientBuilder> {
self.reqwest_builder_with_identity(None)
}
pub fn reqwest_builder_with_identity(
&self,
identity: Option<&ClientIdentity>,
) -> anyhow::Result<reqwest::ClientBuilder> {
Ok(reqwest::Client::builder()
.use_preconfigured_tls(self.reqwest_client_config_with_identity(identity)?))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn a_certificate_pem() -> String {
rcgen::generate_simple_self_signed(vec!["localhost".to_string()])
.expect("generate a test certificate")
.cert
.pem()
}
#[test]
fn default_policy_builds_from_the_os_trust_store() {
let config = OutboundTls::default()
.client_config()
.expect("the default policy builds");
assert!(
config.alpn_protocols.is_empty(),
"the shared config must not pin ALPN, got {:?}",
config.alpn_protocols
);
}
#[test]
fn the_reqwest_config_offers_http11_alpn() {
let config = OutboundTls::default()
.reqwest_client_config()
.expect("builds");
assert_eq!(
config.alpn_protocols,
vec![b"http/1.1".to_vec()],
"reqwest consumers must keep offering http/1.1"
);
}
#[tracing_test::traced_test]
#[test]
fn skip_verify_names_the_ca_it_is_ignoring() {
let _ = OutboundTls {
ca_pem: Some("-----BEGIN CERTIFICATE-----".into()),
skip_verify: true,
}
.client_config();
assert!(
logs_contain("NOT read or used"),
"an ignored CA must be called out by name, not left to inference"
);
}
#[test]
fn ca_pem_is_accepted_alongside_the_os_roots() {
let policy = OutboundTls {
ca_pem: Some(a_certificate_pem()),
skip_verify: false,
};
assert!(
policy.client_config().is_ok(),
"a valid CA PEM must build a config"
);
}
#[test]
fn ca_pem_without_any_certificate_is_an_error() {
let key_only = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])
.expect("generate")
.signing_key
.serialize_pem();
let policy = OutboundTls {
ca_pem: Some(key_only),
skip_verify: false,
};
let err = policy
.client_config()
.expect_err("a PEM with no certificate must fail");
assert!(
err.to_string().contains("no certificates found"),
"error must name the problem, got: {err}"
);
}
#[test]
fn ca_pem_that_is_not_pem_at_all_is_an_error() {
let policy = OutboundTls {
ca_pem: Some("clearly not a PEM document".to_string()),
skip_verify: false,
};
let err = policy
.client_config()
.expect_err("garbage must not be accepted as a trust anchor");
assert!(
err.to_string().contains("no certificates found"),
"error must name the problem, got: {err}"
);
}
#[test]
fn empty_ca_pem_is_an_error() {
let policy = OutboundTls {
ca_pem: Some(String::new()),
skip_verify: false,
};
assert!(
policy.client_config().is_err(),
"an empty CA PEM must not silently mean 'no extra anchor'"
);
}
#[test]
fn skip_verify_builds_without_consulting_any_trust_store() {
let policy = OutboundTls {
ca_pem: None,
skip_verify: true,
};
assert!(
policy.client_config().is_ok(),
"skip-verify must not depend on the OS store"
);
}
#[test]
fn skip_verify_ignores_a_malformed_ca_pem() {
let policy = OutboundTls {
ca_pem: Some("not a pem".to_string()),
skip_verify: true,
};
assert!(
policy.client_config().is_ok(),
"skip-verify takes precedence over ca_pem"
);
}
#[test]
fn is_configured_is_false_only_for_the_untouched_default() {
assert!(!OutboundTls::default().is_configured());
assert!(
OutboundTls {
ca_pem: Some("x".into()),
skip_verify: false
}
.is_configured()
);
assert!(
OutboundTls {
ca_pem: None,
skip_verify: true
}
.is_configured()
);
}
#[test]
fn reqwest_builder_surfaces_the_same_error() {
let policy = OutboundTls {
ca_pem: Some("not a pem".to_string()),
skip_verify: false,
};
assert!(
policy.reqwest_builder().is_err(),
"the reqwest path must not swallow a policy error"
);
}
#[tracing_test::traced_test]
#[test]
fn skip_verify_warns() {
let _ = OutboundTls {
ca_pem: None,
skip_verify: true,
}
.client_config();
assert!(
logs_contain("verification DISABLED"),
"disabling verification must be loud"
);
}
}