mod client_tls;
pub use client_tls::{ClientTls, ClientTlsError, ClientTlsFiles};
use std::{sync::Arc, time::Duration};
use bytes::Bytes;
use http::{HeaderMap, HeaderValue, Request, StatusCode, Uri, header};
use http_body_util::{BodyExt, Full, Limited};
use hyper_util::{
client::legacy::{Client, connect::HttpConnector},
rt::TokioExecutor,
};
use rustls::client::ResolvesClientCert;
use rustls::pki_types::CertificateDer;
use thiserror::Error;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Endpoint(Uri);
impl Endpoint {
pub fn parse(value: &str) -> Result<Self, EndpointError> {
let uri: Uri = value
.parse()
.map_err(|_| EndpointError::Malformed(value.to_owned()))?;
let scheme = uri.scheme_str().unwrap_or_default();
if !matches!(scheme, "http" | "https") {
return Err(EndpointError::Scheme(value.to_owned()));
}
uri.host().ok_or(EndpointError::NoHost(value.to_owned()))?;
Ok(Self(uri))
}
pub fn uri(&self) -> &Uri {
&self.0
}
pub fn is_encrypted(&self) -> bool {
self.0.scheme_str() == Some("https")
}
}
impl std::fmt::Display for Endpoint {
fn fmt(&self, output: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(output, "{}", self.0)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Error)]
pub enum EndpointError {
#[error("`{0}` is not a URL")]
Malformed(String),
#[error("`{0}` must use http or https")]
Scheme(String),
#[error("`{0}` names no host")]
NoHost(String),
}
#[derive(Clone, derive_more::Debug)]
#[debug("BearerToken([REDACTED])")]
pub struct BearerToken(#[debug(skip)] HeaderValue);
impl BearerToken {
pub fn new(token: &str) -> Result<Self, InvalidToken> {
let mut value =
HeaderValue::try_from(format!("Bearer {token}")).map_err(|_| InvalidToken)?;
value.set_sensitive(true);
Ok(Self(value))
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Error)]
#[error("a bearer token must be printable ASCII without control characters")]
pub struct InvalidToken;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ClientConfig {
pub connect_timeout: Duration,
pub request_timeout: Duration,
pub maximum_response_bytes: usize,
}
impl Default for ClientConfig {
fn default() -> Self {
Self {
connect_timeout: Duration::from_millis(500),
request_timeout: Duration::from_secs(2),
maximum_response_bytes: 64 * 1024,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Response {
pub status: StatusCode,
pub headers: HeaderMap,
pub body: Bytes,
}
impl Response {
pub fn retry_after(&self, maximum: Duration) -> Option<Duration> {
let seconds: u64 = self
.headers
.get(header::RETRY_AFTER)?
.to_str()
.ok()?
.trim()
.parse()
.ok()?;
Some(Duration::from_secs(seconds).min(maximum))
}
}
#[derive(Clone, Debug, Eq, PartialEq, Error)]
pub enum OutboundError {
#[error("the request did not complete within its deadline")]
Timeout,
#[error("could not reach the endpoint: {0}")]
Unreachable(String),
#[error("the response was not readable: {0}")]
Response(String),
#[error("the response exceeded {limit} bytes")]
ResponseTooLarge { limit: usize },
}
#[derive(Default)]
pub struct LazyHttpClient(Option<HttpClient>);
impl LazyHttpClient {
pub fn with_limits(
&mut self,
request_timeout: Duration,
maximum_response_bytes: usize,
) -> Result<HttpClient, OutboundError> {
let shared = match &mut self.0 {
Some(client) => client,
slot @ None => slot.insert(HttpClient::new(ClientConfig::default())?),
};
Ok(shared.with_limits(request_timeout, maximum_response_bytes))
}
}
#[derive(Clone, derive_more::Debug)]
pub struct HttpClient {
#[debug(skip)]
inner: Client<hyper_rustls::HttpsConnector<HttpConnector>, Full<Bytes>>,
config: ClientConfig,
}
impl HttpClient {
#[must_use]
pub fn with_limits(&self, request_timeout: Duration, maximum_response_bytes: usize) -> Self {
Self {
inner: self.inner.clone(),
config: ClientConfig {
request_timeout,
maximum_response_bytes,
..self.config
},
}
}
pub fn with_identity(
config: ClientConfig,
identity: Option<Arc<dyn ResolvesClientCert>>,
roots: Option<Vec<CertificateDer<'static>>>,
) -> Result<Self, OutboundError> {
let mut connector = HttpConnector::new();
connector.set_connect_timeout(Some(config.connect_timeout));
connector.enforce_http(false);
let builder = rustls::ClientConfig::builder();
let builder = match roots {
Some(roots) => {
let mut store = rustls::RootCertStore::empty();
for root in roots {
store
.add(root)
.map_err(|error| OutboundError::Unreachable(error.to_string()))?;
}
builder.with_root_certificates(store)
}
None => {
let mut store = rustls::RootCertStore::empty();
let loaded = rustls_native_certs::load_native_certs();
if loaded.certs.is_empty() {
let reason = loaded
.errors
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("; ");
return Err(OutboundError::Unreachable(format!(
"no platform trust roots could be loaded: {reason}"
)));
}
store.add_parsable_certificates(loaded.certs);
builder.with_root_certificates(store)
}
};
let tls = match identity {
Some(resolver) => builder.with_client_cert_resolver(resolver),
None => builder.with_no_client_auth(),
};
let connector = hyper_rustls::HttpsConnectorBuilder::new()
.with_tls_config(tls)
.https_or_http()
.enable_http1()
.wrap_connector(connector);
Ok(Self {
inner: Client::builder(TokioExecutor::new()).build(connector),
config,
})
}
pub fn new(config: ClientConfig) -> Result<Self, OutboundError> {
Self::with_identity(config, None, None)
}
pub async fn get(&self, endpoint: &Endpoint) -> Result<Response, OutboundError> {
let request = Request::get(endpoint.uri())
.body(Full::new(Bytes::new()))
.map_err(|error| OutboundError::Unreachable(error.to_string()))?;
tokio::time::timeout(self.config.request_timeout, self.send(request))
.await
.map_err(|_| OutboundError::Timeout)?
}
pub async fn post(
&self,
endpoint: &Endpoint,
content_type: &'static str,
bearer: Option<&BearerToken>,
body: Bytes,
) -> Result<Response, OutboundError> {
self.post_with_headers(endpoint, content_type, bearer, body, &HeaderMap::new())
.await
}
pub async fn post_with_headers(
&self,
endpoint: &Endpoint,
content_type: &'static str,
bearer: Option<&BearerToken>,
body: Bytes,
headers: &HeaderMap,
) -> Result<Response, OutboundError> {
let mut request = Request::post(endpoint.uri())
.header(header::CONTENT_TYPE, HeaderValue::from_static(content_type))
.body(Full::new(body))
.map_err(|error| OutboundError::Unreachable(error.to_string()))?;
request.headers_mut().extend(headers.clone());
request
.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
request.headers_mut().remove(header::AUTHORIZATION);
if let Some(bearer) = bearer {
request
.headers_mut()
.insert(header::AUTHORIZATION, bearer.0.clone());
}
tokio::time::timeout(self.config.request_timeout, self.send(request))
.await
.map_err(|_| OutboundError::Timeout)?
}
async fn send(&self, request: Request<Full<Bytes>>) -> Result<Response, OutboundError> {
let response = self
.inner
.request(request)
.await
.map_err(|error| OutboundError::Unreachable(error.to_string()))?;
let status = response.status();
let headers = response.headers().clone();
let limit = self.config.maximum_response_bytes;
let body = Limited::new(response.into_body(), limit)
.collect()
.await
.map_err(|error| {
if error.is::<http_body_util::LengthLimitError>() {
OutboundError::ResponseTooLarge { limit }
} else {
OutboundError::Response(error.to_string())
}
})?
.to_bytes();
Ok(Response {
status,
headers,
body,
})
}
}
#[cfg(test)]
mod tests;