From 2ea4067c6aa6e0f9efdc7cc9cae2def3230d0b5e Mon Sep 17 00:00:00 2001 From: Luca Joss Date: Thu, 31 Oct 2024 17:20:06 +0100 Subject: [PATCH] Improve TLS configuration to only configure if required --- crates/relayer/src/error.rs | 4 ++++ crates/relayer/src/util.rs | 23 +++++++++++------------ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/crates/relayer/src/error.rs b/crates/relayer/src/error.rs index 6d46f90fe0..7fd2a0d729 100644 --- a/crates/relayer/src/error.rs +++ b/crates/relayer/src/error.rs @@ -606,6 +606,10 @@ define_error! { [ TraceError ] |_| { "HTTP response body error" }, + InvalidHttpHost + { endpoint: String } + |e| { format!("HTTP host is invalid for the endpoint `{}`", e.endpoint) }, + JsonDeserialize [ TraceError ] |_| { "JSON deserialization error" }, diff --git a/crates/relayer/src/util.rs b/crates/relayer/src/util.rs index 497999af6f..9799e6cc4e 100644 --- a/crates/relayer/src/util.rs +++ b/crates/relayer/src/util.rs @@ -21,28 +21,27 @@ pub async fn create_grpc_client( grpc_addr: &tonic::transport::Uri, client_constructor: impl FnOnce(tonic::transport::Channel) -> T, ) -> Result { - let tls_config = tonic::transport::ClientTlsConfig::new().with_native_roots(); let builder = tonic::transport::Channel::builder(grpc_addr.clone()); // Don't configures TLS for the endpoint if using IPv6 - let builder = if is_ipv6(grpc_addr) { - builder - } else { + let builder = if grpc_addr.scheme() == Some(&http::uri::Scheme::HTTPS) { + let domain = grpc_addr + .host() + .map(|d| d.replace(['[', ']'], "")) + .ok_or_else(|| crate::error::Error::invalid_http_host(grpc_addr.to_string()))?; + let tls_config = tonic::transport::ClientTlsConfig::new() + .with_native_roots() + .domain_name(domain); builder .tls_config(tls_config) .map_err(crate::error::Error::grpc_transport)? + } else { + builder }; + let channel = builder .connect() .await .map_err(crate::error::Error::grpc_transport)?; Ok(client_constructor(channel)) } - -fn is_ipv6(uri: &tonic::transport::Uri) -> bool { - if let Some(host) = uri.host() { - host.starts_with('[') && host.ends_with(']') - } else { - false - } -}