use std::sync::Arc;
use hyper_util::client::legacy::connect::HttpConnector;
#[cfg(any(
feature = "rustls-native-certs",
feature = "rustls-platform-verifier",
feature = "webpki-roots"
))]
use rustls::crypto::CryptoProvider;
use rustls::pki_types::ServerName;
use rustls::ClientConfig;
use super::{DefaultServerNameResolver, HttpsConnector, ResolveServerName};
#[cfg(any(
feature = "rustls-native-certs",
feature = "webpki-roots",
feature = "rustls-platform-verifier"
))]
use crate::config::ConfigBuilderExt;
pub struct ConnectorBuilder<State>(State);
pub struct WantsTlsConfig(());
impl ConnectorBuilder<WantsTlsConfig> {
pub fn new() -> Self {
Self(WantsTlsConfig(()))
}
pub fn with_tls_config(self, config: ClientConfig) -> ConnectorBuilder<WantsSchemes> {
assert!(
config.alpn_protocols.is_empty(),
"ALPN protocols should not be pre-defined"
);
ConnectorBuilder(WantsSchemes { tls_config: config })
}
#[cfg(all(
any(feature = "ring", feature = "aws-lc-rs"),
feature = "rustls-platform-verifier"
))]
pub fn with_platform_verifier(self) -> ConnectorBuilder<WantsSchemes> {
self.try_with_platform_verifier()
.expect("failure to initialize platform verifier")
}
#[cfg(all(
any(feature = "ring", feature = "aws-lc-rs"),
feature = "rustls-platform-verifier"
))]
pub fn try_with_platform_verifier(
self,
) -> Result<ConnectorBuilder<WantsSchemes>, rustls::Error> {
Ok(self.with_tls_config(
ClientConfig::builder()
.try_with_platform_verifier()?
.with_no_client_auth(),
))
}
#[cfg(feature = "rustls-platform-verifier")]
pub fn with_provider_and_platform_verifier(
self,
provider: impl Into<Arc<CryptoProvider>>,
) -> std::io::Result<ConnectorBuilder<WantsSchemes>> {
Ok(self.with_tls_config(
ClientConfig::builder_with_provider(provider.into())
.with_safe_default_protocol_versions()
.and_then(|builder| builder.try_with_platform_verifier())
.map_err(std::io::Error::other)?
.with_no_client_auth(),
))
}
#[cfg(all(
any(feature = "ring", feature = "aws-lc-rs"),
feature = "rustls-native-certs"
))]
pub fn with_native_roots(self) -> std::io::Result<ConnectorBuilder<WantsSchemes>> {
Ok(self.with_tls_config(
ClientConfig::builder()
.with_native_roots()?
.with_no_client_auth(),
))
}
#[cfg(feature = "rustls-native-certs")]
pub fn with_provider_and_native_roots(
self,
provider: impl Into<Arc<CryptoProvider>>,
) -> std::io::Result<ConnectorBuilder<WantsSchemes>> {
Ok(self.with_tls_config(
ClientConfig::builder_with_provider(provider.into())
.with_safe_default_protocol_versions()
.map_err(std::io::Error::other)?
.with_native_roots()?
.with_no_client_auth(),
))
}
#[cfg(all(any(feature = "ring", feature = "aws-lc-rs"), feature = "webpki-roots"))]
pub fn with_webpki_roots(self) -> ConnectorBuilder<WantsSchemes> {
self.with_tls_config(
ClientConfig::builder()
.with_webpki_roots()
.with_no_client_auth(),
)
}
#[cfg(feature = "webpki-roots")]
pub fn with_provider_and_webpki_roots(
self,
provider: impl Into<Arc<CryptoProvider>>,
) -> Result<ConnectorBuilder<WantsSchemes>, rustls::Error> {
Ok(self.with_tls_config(
ClientConfig::builder_with_provider(provider.into())
.with_safe_default_protocol_versions()?
.with_webpki_roots()
.with_no_client_auth(),
))
}
}
impl Default for ConnectorBuilder<WantsTlsConfig> {
fn default() -> Self {
Self::new()
}
}
pub struct WantsSchemes {
tls_config: ClientConfig,
}
impl ConnectorBuilder<WantsSchemes> {
pub fn https_only(self) -> ConnectorBuilder<WantsProtocols1> {
ConnectorBuilder(WantsProtocols1 {
tls_config: self.0.tls_config,
https_only: true,
server_name_resolver: None,
})
}
pub fn https_or_http(self) -> ConnectorBuilder<WantsProtocols1> {
ConnectorBuilder(WantsProtocols1 {
tls_config: self.0.tls_config,
https_only: false,
server_name_resolver: None,
})
}
}
pub struct WantsProtocols1 {
tls_config: ClientConfig,
https_only: bool,
server_name_resolver: Option<Arc<dyn ResolveServerName + Sync + Send>>,
}
impl WantsProtocols1 {
fn wrap_connector<H>(self, conn: H) -> HttpsConnector<H> {
HttpsConnector {
force_https: self.https_only,
http: conn,
tls_config: std::sync::Arc::new(self.tls_config),
server_name_resolver: self
.server_name_resolver
.unwrap_or_else(|| Arc::new(DefaultServerNameResolver::default())),
}
}
fn build(self) -> HttpsConnector<HttpConnector> {
let mut http = HttpConnector::new();
http.enforce_http(false);
self.wrap_connector(http)
}
}
impl ConnectorBuilder<WantsProtocols1> {
#[cfg(feature = "http1")]
pub fn enable_http1(self) -> ConnectorBuilder<WantsProtocols2> {
ConnectorBuilder(WantsProtocols2 { inner: self.0 })
}
#[cfg(feature = "http2")]
pub fn enable_http2(mut self) -> ConnectorBuilder<WantsProtocols3> {
self.0.tls_config.alpn_protocols = vec![b"h2".to_vec()];
ConnectorBuilder(WantsProtocols3 {
inner: self.0,
enable_http1: false,
})
}
#[cfg(feature = "http2")]
pub fn enable_all_versions(mut self) -> ConnectorBuilder<WantsProtocols3> {
#[cfg(feature = "http1")]
let alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
#[cfg(not(feature = "http1"))]
let alpn_protocols = vec![b"h2".to_vec()];
self.0.tls_config.alpn_protocols = alpn_protocols;
ConnectorBuilder(WantsProtocols3 {
inner: self.0,
enable_http1: cfg!(feature = "http1"),
})
}
pub fn with_server_name_resolver(
mut self,
resolver: impl ResolveServerName + 'static + Sync + Send,
) -> Self {
self.0.server_name_resolver = Some(Arc::new(resolver));
self
}
#[deprecated(
since = "0.27.1",
note = "use Self::with_server_name_resolver with FixedServerNameResolver instead"
)]
pub fn with_server_name(self, mut override_server_name: String) -> Self {
if let Some(trimmed) = override_server_name
.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
{
override_server_name = trimmed.to_string();
}
self.with_server_name_resolver(move |_: &_| {
ServerName::try_from(override_server_name.clone())
})
}
}
pub struct WantsProtocols2 {
inner: WantsProtocols1,
}
impl ConnectorBuilder<WantsProtocols2> {
#[cfg(feature = "http2")]
pub fn enable_http2(mut self) -> ConnectorBuilder<WantsProtocols3> {
self.0.inner.tls_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
ConnectorBuilder(WantsProtocols3 {
inner: self.0.inner,
enable_http1: true,
})
}
pub fn build(self) -> HttpsConnector<HttpConnector> {
self.0.inner.build()
}
pub fn wrap_connector<H>(self, conn: H) -> HttpsConnector<H> {
self.0.inner.wrap_connector(conn)
}
}
#[cfg(feature = "http2")]
pub struct WantsProtocols3 {
inner: WantsProtocols1,
#[allow(dead_code)]
enable_http1: bool,
}
#[cfg(feature = "http2")]
impl ConnectorBuilder<WantsProtocols3> {
pub fn build(self) -> HttpsConnector<HttpConnector> {
self.0.inner.build()
}
pub fn wrap_connector<H>(self, conn: H) -> HttpsConnector<H> {
self.0.inner.wrap_connector(conn)
}
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(all(feature = "webpki-roots", feature = "http1"))]
fn test_builder() {
ensure_global_state();
let _connector = super::ConnectorBuilder::new()
.with_webpki_roots()
.https_only()
.enable_http1()
.build();
}
#[test]
#[cfg(feature = "http1")]
#[should_panic(expected = "ALPN protocols should not be pre-defined")]
fn test_reject_predefined_alpn() {
ensure_global_state();
let roots = rustls::RootCertStore::empty();
let mut config_with_alpn = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
config_with_alpn.alpn_protocols = vec![b"fancyprotocol".to_vec()];
let _connector = super::ConnectorBuilder::new()
.with_tls_config(config_with_alpn)
.https_only()
.enable_http1()
.build();
}
#[test]
#[cfg(all(feature = "http1", feature = "http2"))]
fn test_alpn() {
ensure_global_state();
let roots = rustls::RootCertStore::empty();
let tls_config = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
let connector = super::ConnectorBuilder::new()
.with_tls_config(tls_config.clone())
.https_only()
.enable_http1()
.build();
assert!(connector
.tls_config
.alpn_protocols
.is_empty());
let connector = super::ConnectorBuilder::new()
.with_tls_config(tls_config.clone())
.https_only()
.enable_http2()
.build();
assert_eq!(&connector.tls_config.alpn_protocols, &[b"h2".to_vec()]);
let connector = super::ConnectorBuilder::new()
.with_tls_config(tls_config.clone())
.https_only()
.enable_http1()
.enable_http2()
.build();
assert_eq!(
&connector.tls_config.alpn_protocols,
&[b"h2".to_vec(), b"http/1.1".to_vec()]
);
let connector = super::ConnectorBuilder::new()
.with_tls_config(tls_config)
.https_only()
.enable_all_versions()
.build();
assert_eq!(
&connector.tls_config.alpn_protocols,
&[b"h2".to_vec(), b"http/1.1".to_vec()]
);
}
#[test]
#[cfg(all(not(feature = "http1"), feature = "http2"))]
fn test_alpn_http2() {
let roots = rustls::RootCertStore::empty();
let tls_config = rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(roots)
.with_no_client_auth();
let connector = super::ConnectorBuilder::new()
.with_tls_config(tls_config.clone())
.https_only()
.enable_http2()
.build();
assert_eq!(&connector.tls_config.alpn_protocols, &[b"h2".to_vec()]);
let connector = super::ConnectorBuilder::new()
.with_tls_config(tls_config)
.https_only()
.enable_all_versions()
.build();
assert_eq!(&connector.tls_config.alpn_protocols, &[b"h2".to_vec()]);
}
fn ensure_global_state() {
#[cfg(feature = "ring")]
let _ = rustls::crypto::ring::default_provider().install_default();
#[cfg(feature = "aws-lc-rs")]
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
}
}