From b04c1c6582e486e3466f9e5770703eef3925cbe9 Mon Sep 17 00:00:00 2001 From: Juan Alvarez Date: Fri, 23 Apr 2021 09:42:01 -0500 Subject: [PATCH] configure tls automatically when possible (#445) --- tonic/src/transport/service/connector.rs | 29 +++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/tonic/src/transport/service/connector.rs b/tonic/src/transport/service/connector.rs index 8bd82dea1..5dd0e2702 100644 --- a/tonic/src/transport/service/connector.rs +++ b/tonic/src/transport/service/connector.rs @@ -36,6 +36,26 @@ impl Connector { fn new(inner: C, tls: Option) -> Self { Self { inner, tls } } + + #[cfg(feature = "tls-roots")] + fn tls_or_default(&self, scheme: Option<&str>, host: Option<&str>) -> Option { + use tokio_rustls::webpki::DNSNameRef; + + if self.tls.is_some() { + return self.tls.clone(); + } + + match (scheme, host) { + (Some("https"), Some(host)) => { + if DNSNameRef::try_from_ascii(host.as_bytes()).is_ok() { + TlsConnector::new_with_rustls_cert(None, None, host.to_owned()).ok() + } else { + None + } + } + _ => None, + } + } } impl Service for Connector @@ -54,11 +74,14 @@ where } fn call(&mut self, uri: Uri) -> Self::Future { - let connect = self.inner.make_connection(uri); - - #[cfg(feature = "tls")] + #[cfg(all(feature = "tls", not(feature = "tls-roots")))] let tls = self.tls.clone(); + #[cfg(feature = "tls-roots")] + let tls = self.tls_or_default(uri.scheme_str(), uri.host()); + + let connect = self.inner.make_connection(uri); + Box::pin(async move { let io = connect.await?;