-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathhttp_client.rs
45 lines (40 loc) · 2.11 KB
/
http_client.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use anyhow::{anyhow, Context};
use std::sync::OnceLock;
static NATIVE_CERTS: OnceLock<anyhow::Result<rustls::RootCertStore>> = OnceLock::new();
pub fn make_http_client(config: &crate::app_config::AppConfig) -> anyhow::Result<awc::Client> {
let connector = if config.system_root_ca_certificates {
let roots = NATIVE_CERTS
.get_or_init(|| {
log::debug!("Loading native certificates because system_root_ca_certificates is enabled");
let certs = rustls_native_certs::load_native_certs()
.with_context(|| "Initial native certificates load failed")?;
log::info!("Loaded {} native certificates", certs.len());
let mut roots = rustls::RootCertStore::empty();
for cert in certs {
log::trace!("Adding native certificate to root store: {cert:?}");
roots.add(cert.clone()).with_context(|| {
format!("Unable to add certificate to root store: {cert:?}")
})?;
}
Ok(roots)
})
.as_ref()
.map_err(|e| anyhow!("Unable to load native certificates, make sure the system root CA certificates are available: {e}"))?;
log::trace!("Creating HTTP client with custom TLS connector using native certificates. SSL_CERT_FILE={:?}, SSL_CERT_DIR={:?}",
std::env::var("SSL_CERT_FILE").unwrap_or_default(),
std::env::var("SSL_CERT_DIR").unwrap_or_default());
let tls_conf = rustls::ClientConfig::builder()
.with_root_certificates(roots.clone())
.with_no_client_auth();
awc::Connector::new().rustls_0_22(std::sync::Arc::new(tls_conf))
} else {
log::debug!("Using the default tls connector with builtin certs because system_root_ca_certificates is disabled");
awc::Connector::new()
};
let client = awc::Client::builder()
.connector(connector)
.add_default_header((awc::http::header::USER_AGENT, env!("CARGO_PKG_NAME")))
.finish();
log::debug!("Created HTTP client");
Ok(client)
}