Skip to main content

libdd_common/connector/
mod.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4#[cfg(feature = "http-client")]
5use futures::future::BoxFuture;
6#[cfg(feature = "http-client")]
7use futures::{FutureExt, future};
8#[cfg(feature = "http-client")]
9use hyper_util::client::legacy::connect;
10
11#[cfg(feature = "http-client")]
12use core::future::Future;
13#[cfg(feature = "http-client")]
14use core::pin::Pin;
15#[cfg(feature = "http-client")]
16use core::task::{Context, Poll};
17#[cfg(feature = "http-client")]
18use std::sync::LazyLock;
19
20#[cfg(unix)]
21pub mod uds;
22
23pub mod named_pipe;
24
25pub mod errors;
26
27#[cfg(feature = "http-client")]
28mod conn_stream;
29#[cfg(feature = "http-client")]
30use conn_stream::{ConnStream, ConnStreamError};
31
32#[cfg(any(
33    all(feature = "tls-core", not(feature = "use_webpki_roots")),
34    feature = "tls-distrust"
35))]
36mod certificate_distrust;
37
38#[cfg(feature = "tls-distrust")]
39pub use certificate_distrust::platform_verifier_with_distrust;
40
41#[cfg(feature = "hyper-proxy")]
42mod proxy;
43
44// Skipped under Miri: the certificate distrust tests exercise ring-backed
45// signature verification, whose FFI cannot execute there.
46#[cfg(all(test, feature = "https", not(feature = "use_webpki_roots"), not(miri)))]
47mod certificate_distrust_tests;
48
49#[cfg(feature = "http-client")]
50#[derive(Clone)]
51// `proxy::HttpProxyConnector` is crate internal, and the field anyway not pub.
52#[allow(private_interfaces)]
53pub enum Connector {
54    Http(connect::HttpConnector),
55    #[cfg(feature = "tls-core")]
56    Https(hyper_rustls::HttpsConnector<connect::HttpConnector>),
57    #[cfg(feature = "hyper-proxy")]
58    Proxy(Box<proxy::HttpProxyConnector>),
59}
60
61#[cfg(feature = "http-client")]
62static DEFAULT_CONNECTOR: LazyLock<Connector> = LazyLock::new(Connector::new);
63
64#[cfg(feature = "http-client")]
65impl Default for Connector {
66    fn default() -> Self {
67        DEFAULT_CONNECTOR.clone()
68    }
69}
70
71#[cfg(feature = "http-client")]
72impl Connector {
73    /// Make sure this function is not called frequently. Fetching the root certificates is an
74    /// expensive operation. Access the globally cached connector via Connector::default().
75    fn new() -> Self {
76        #[cfg(feature = "hyper-proxy")]
77        {
78            Connector::Proxy(Box::new(proxy::HttpProxyConnector::new(
79                Self::new_no_proxy(),
80            )))
81        }
82        #[cfg(not(feature = "hyper-proxy"))]
83        {
84            Self::new_no_proxy()
85        }
86    }
87
88    pub(super) fn new_no_proxy() -> Self {
89        #[cfg(feature = "tls-core")]
90        {
91            match https::build_https_connector() {
92                Ok(connector) => Connector::Https(connector),
93                Err(_) => Connector::Http(connect::HttpConnector::new()),
94            }
95        }
96        #[cfg(not(feature = "tls-core"))]
97        {
98            Connector::Http(connect::HttpConnector::new())
99        }
100    }
101
102    fn build_conn_stream(
103        &mut self,
104        uri: hyper::Uri,
105        require_tls: bool,
106    ) -> BoxFuture<'static, Result<ConnStream, ConnStreamError>> {
107        match self {
108            Self::Http(c) => {
109                if require_tls {
110                    future::err::<ConnStream, ConnStreamError>(
111                        errors::Error::CannotEstablishTlsConnection.into(),
112                    )
113                    .boxed()
114                } else {
115                    ConnStream::from_http_connector_with_uri(c, uri).boxed()
116                }
117            }
118            #[cfg(feature = "tls-core")]
119            Self::Https(c) => {
120                ConnStream::from_https_connector_with_uri(c, uri, require_tls).boxed()
121            }
122            #[cfg(feature = "hyper-proxy")]
123            Self::Proxy(p) => p.build_conn_stream(uri, require_tls),
124        }
125    }
126}
127
128#[cfg(feature = "tls-core")]
129pub(crate) mod https {
130    #[cfg(feature = "use_webpki_roots")]
131    use hyper_rustls::ConfigBuilderExt;
132
133    use rustls::ClientConfig;
134
135    /// Ensures the rustls default CryptoProvider is installed (ring for non-FIPS).
136    /// In FIPS mode, the caller must install the FIPS provider before any TLS use.
137    #[cfg(feature = "https")]
138    fn ensure_crypto_provider_initialized() {
139        use std::sync::Once;
140
141        static INIT_CRYPTO_PROVIDER: Once = Once::new();
142
143        INIT_CRYPTO_PROVIDER.call_once(|| {
144            let _ = rustls::crypto::ring::default_provider().install_default();
145        });
146    }
147
148    /// In FIPS mode, the caller must install the FIPS-compliant crypto provider
149    /// (e.g., aws-lc-rs FIPS) before any TLS connections are established.
150    #[cfg(not(feature = "https"))]
151    fn ensure_crypto_provider_initialized() {}
152
153    #[cfg(any(feature = "https", feature = "fips"))]
154    fn require_crypto_provider() -> anyhow::Result<()> {
155        Ok(())
156    }
157
158    #[cfg(not(any(feature = "https", feature = "fips")))]
159    fn require_crypto_provider() -> anyhow::Result<()> {
160        if rustls::crypto::CryptoProvider::get_default().is_none() {
161            anyhow::bail!("no rustls CryptoProvider installed");
162        }
163        Ok(())
164    }
165
166    /// Builds the TLS configuration shared by every libdd-common HTTPS client:
167    /// the hyper connector, the hyper-proxy tunnel and dialer, and the reqwest
168    /// client builder (see `Endpoint::to_reqwest_client_builder`).
169    #[cfg(feature = "use_webpki_roots")]
170    pub(crate) fn build_tls_config() -> anyhow::Result<ClientConfig> {
171        ensure_crypto_provider_initialized(); // One-time initialization of a crypto provider if needed
172        require_crypto_provider()?;
173
174        Ok(ClientConfig::builder()
175            .with_webpki_roots()
176            .with_no_client_auth())
177    }
178
179    #[cfg(not(feature = "use_webpki_roots"))]
180    /// Builds the client TLS config using the system trust roots.
181    /// `SSL_CERT_FILE` and `SSL_CERT_DIR` variable are only supported on linux, see
182    /// `rustls_platform_verifier` doc for details.
183    ///
184    /// The platform verifier is wrapped with an application-level distrust check that
185    /// rejects known-compromised public keys, until `rustls-webpki` can be updated to
186    /// a version carrying the upstream fix (see `certificate_distrust`).
187    pub(crate) fn build_tls_config() -> anyhow::Result<ClientConfig> {
188        use alloc::sync::Arc;
189
190        use super::certificate_distrust::DistrustServerCertVerifier;
191
192        ensure_crypto_provider_initialized(); // One-time initialization of a crypto provider if needed
193        require_crypto_provider()?;
194
195        let builder = ClientConfig::builder();
196        let verifier =
197            DistrustServerCertVerifier::platform_with_distrust(builder.crypto_provider().clone())?;
198        Ok(builder
199            .dangerous()
200            .with_custom_certificate_verifier(Arc::new(verifier))
201            .with_no_client_auth())
202    }
203
204    pub(super) fn build_https_connector() -> anyhow::Result<
205        hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>,
206    > {
207        Ok(hyper_rustls::HttpsConnectorBuilder::new()
208            .with_tls_config(build_tls_config()?)
209            .https_or_http()
210            .enable_http1()
211            .build())
212    }
213}
214
215#[cfg(feature = "http-client")]
216impl tower_service::Service<hyper::Uri> for Connector {
217    type Response = ConnStream;
218    type Error = ConnStreamError;
219
220    // This lint gets lifted in this place in a newer version, see:
221    // https://github.com/rust-lang/rust-clippy/pull/8030
222    #[allow(clippy::type_complexity)]
223    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
224
225    fn call(&mut self, uri: hyper::Uri) -> Self::Future {
226        match uri.scheme_str() {
227            Some("unix") => conn_stream::ConnStream::from_uds_uri(uri).boxed(),
228            Some("windows") => conn_stream::ConnStream::from_named_pipe_uri(uri).boxed(),
229            Some("https") => self.build_conn_stream(uri, true),
230            _ => self.build_conn_stream(uri, false),
231        }
232    }
233
234    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
235        match self {
236            Connector::Http(c) => c.poll_ready(cx).map_err(|e| e.into()),
237            #[cfg(feature = "tls-core")]
238            Connector::Https(c) => c.poll_ready(cx),
239            #[cfg(feature = "hyper-proxy")]
240            Connector::Proxy(p) => p.poll_ready(cx),
241        }
242    }
243}
244
245#[cfg(all(test, feature = "http-client"))]
246mod tests {
247    use crate::http_common;
248    #[cfg(any(feature = "use_webpki_roots", target_os = "linux"))]
249    use {super::*, std::env};
250    #[cfg(feature = "tls-core")]
251    use {crate::http_common::Body, hyper::Request};
252
253    #[test]
254    #[cfg_attr(miri, ignore)]
255    #[cfg(not(feature = "use_webpki_roots"))]
256    /// Verify that the Connector type implements the correct bound Connect + Clone
257    /// to be able to use the hyper::Client
258    fn test_hyper_client_from_connector() {
259        let _ = http_common::new_default_client();
260    }
261
262    #[test]
263    #[cfg_attr(miri, ignore)]
264    #[cfg(feature = "use_webpki_roots")]
265    fn test_hyper_client_from_connector_with_webpki_roots() {
266        let _ = http_common::new_default_client();
267    }
268
269    #[test]
270    #[cfg_attr(miri, ignore)]
271    #[cfg(not(feature = "use_webpki_roots"))]
272    // Only Linux eagerly loads roots at connector construction; macOS/Windows verify lazily
273    // during the TLS handshake, so SSL_CERT_FILE/SSL_CERT_DIR cannot be exercised there.
274    #[cfg(target_os = "linux")]
275    /// Verify that Connector falls back to Http when native root certificates
276    /// are not available and webpki roots are not enabled.
277    fn test_missing_root_certificates_only_allow_http_connections() {
278        const ENV_SSL_CERT_FILE: &str = "SSL_CERT_FILE";
279        const ENV_SSL_CERT_DIR: &str = "SSL_CERT_DIR";
280        let old_value = env::var(ENV_SSL_CERT_FILE).unwrap_or_default();
281        let old_dir_value = env::var(ENV_SSL_CERT_DIR).unwrap_or_default();
282
283        unsafe { env::set_var(ENV_SSL_CERT_FILE, "this/folder/does/not/exist") };
284        unsafe { env::set_var(ENV_SSL_CERT_DIR, "this/folder/does/not/exist") };
285        let connector = Connector::new_no_proxy();
286
287        assert!(matches!(connector, Connector::Http(_)));
288
289        unsafe { env::set_var(ENV_SSL_CERT_FILE, old_value) };
290        unsafe { env::set_var(ENV_SSL_CERT_DIR, old_dir_value) };
291    }
292
293    #[test]
294    #[cfg_attr(miri, ignore)]
295    #[cfg(feature = "use_webpki_roots")]
296    #[cfg(feature = "tls-core")]
297    /// Verify that Connector builds an Https connector using webpki certificates
298    /// even when native root certificates are not available.
299    fn test_missing_root_certificates_use_webpki_certificates() {
300        const ENV_SSL_CERT_FILE: &str = "SSL_CERT_FILE";
301        let old_value = env::var(ENV_SSL_CERT_FILE).unwrap_or_default();
302
303        unsafe { env::set_var(ENV_SSL_CERT_FILE, "this/folder/does/not/exist") };
304        let connector = Connector::new_no_proxy();
305        assert!(matches!(connector, Connector::Https(_)));
306
307        unsafe { env::set_var(ENV_SSL_CERT_FILE, old_value) };
308    }
309
310    #[tokio::test]
311    #[cfg_attr(miri, ignore)]
312    #[cfg(feature = "tls-core")]
313    /// Verify that a HTTPS GET request succeeds using
314    /// the default Connector (native platform TLS verifier or webpki roots).
315    async fn test_https_request_succeeds() {
316        let client = http_common::new_default_client();
317        let request = Request::get("https://www.datadoghq.com")
318            .body(Body::empty())
319            .expect("failed to build request");
320        let response = client
321            .request(request)
322            .await
323            .expect("HTTPS request to datadoghq.com failed");
324        let status = response.status();
325        // Accept any successful (2xx) or redirect (3xx) response.
326        assert!(
327            status.is_success() || status.is_redirection(),
328            "unexpected status code: {status}"
329        );
330    }
331}