diff --git a/bottlecap/.config/nextest.toml b/bottlecap/.config/nextest.toml index e493b13d6..44e103270 100644 --- a/bottlecap/.config/nextest.toml +++ b/bottlecap/.config/nextest.toml @@ -13,7 +13,7 @@ fixed-ports = { max-threads = 1 } # A regex so the config stays valid when one of these binaries is absent # (nextest rejects an exact `binary(name)` that matches nothing). [[profile.default.overrides]] -filter = 'binary(/(^|_)(lifecycle_contract|fault_injection|config_robustness|port_conflict)_test$/)' +filter = 'binary(/(^|_)(lifecycle_contract|fault_injection|config_robustness|port_conflict|proxy_tls)_test$/)' test-group = "fixed-ports" # A debug build of the extension, a blocking flush and a shutdown deadline add # up; the longest test (a storm with a memory window) stays under this. diff --git a/bottlecap/Cargo.lock b/bottlecap/Cargo.lock index 9346e7ecf..4d7cbeaf4 100644 --- a/bottlecap/Cargo.lock +++ b/bottlecap/Cargo.lock @@ -542,6 +542,7 @@ dependencies = [ "tracing-core", "tracing-subscriber", "ustr", + "webpki-roots 1.0.10", "zstd", ] diff --git a/bottlecap/Cargo.toml b/bottlecap/Cargo.toml index f437d5ad4..57963af3d 100644 --- a/bottlecap/Cargo.toml +++ b/bottlecap/Cargo.toml @@ -83,6 +83,10 @@ tower-http = { version = "0.6.6", default-features = false, features = ["limit"] hyper-http-proxy = { version = "1.1.0", default-features = false, features = [ "rustls-tls-webpki-roots", ] } +# Used to install the custom-root TLS connector for the post-CONNECT proxy handshake (SLES-3105). +tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12"] } +# The public roots `hyper-http-proxy` trusts in the tunnel by default; `DD_TLS_CERT_FILE` is added to them. +webpki-roots = { version = "1", default-features = false } # If you are adding or updating a datadog-owned code dependency, please ensure # that it has a clippy.toml rule for disallowing the reqwest::Client::builder # method in favor of our @@ -115,10 +119,6 @@ tower = { version = "0.5", features = ["util"] } mock_instant = "0.6" serial_test = "3.1" tempfile = "3.20" -# Local TLS server for the http.rs root-trust tests (H1: webpki default + -# tls_cert_file mitigation). Already present transitively via reqwest's -# hyper-rustls, so promoting it to a dev-dep adds nothing to the shipped binary. -tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12"] } # fake-intake test harness: decode msgpack+gzip stats payloads on arrival rmp-serde = { version = "1.3.1", default-features = false } flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] } diff --git a/bottlecap/src/traces/http_client.rs b/bottlecap/src/traces/http_client.rs index 5980c95e5..424f63dde 100644 --- a/bottlecap/src/traces/http_client.rs +++ b/bottlecap/src/traces/http_client.rs @@ -16,13 +16,14 @@ use libdd_capabilities::{ }; use libdd_common::http_common::{self, Body, GenericHttpClient}; use rustls::RootCertStore; -use rustls_pki_types::CertificateDer; +use rustls_pki_types::{CertificateDer, TrustAnchor}; use std::error::Error; use std::fs::File; use std::future::Future; use std::io::BufReader; use std::sync::{Arc, LazyLock}; use std::time::Duration; +use tokio_rustls::TlsConnector; use tracing::debug; type InnerClient = @@ -188,6 +189,23 @@ pub fn create_client( proxy_https: Option<&String>, tls_cert_file: Option<&String>, skip_ssl_validation: bool, +) -> Result> { + create_client_with_public_roots( + proxy_https, + tls_cert_file, + skip_ssl_validation, + webpki_roots::TLS_SERVER_ROOTS, + ) +} + +/// [`create_client`] with the public roots the proxy tunnel starts from. They are the +/// bundle `ProxyConnector::from_proxy()` trusts by default; a `DD_TLS_CERT_FILE` is added +/// to them, not substituted for them. +fn create_client_with_public_roots( + proxy_https: Option<&String>, + tls_cert_file: Option<&String>, + skip_ssl_validation: bool, + public_roots: &[TrustAnchor<'static>], ) -> Result> { if skip_ssl_validation && tls_cert_file.is_some() { debug!( @@ -197,7 +215,7 @@ pub fn create_client( } // Create the base connector with optional custom TLS config - let connector = if skip_ssl_validation { + let (connector, tunnel_tls) = if skip_ssl_validation { ensure_crypto_provider_initialized(); let tls_config = rustls::ClientConfig::builder() @@ -206,14 +224,17 @@ pub fn create_client( .with_no_client_auth(); let https_connector = HttpsConnectorBuilder::new() - .with_tls_config(tls_config) + .with_tls_config(tls_config.clone()) .https_or_http() .enable_http1() .build(); debug!("HTTP_CLIENT | TLS certificate validation disabled (skip_ssl_validation=true)"); - libdd_common::connector::Connector::Https(https_connector) + ( + libdd_common::connector::Connector::Https(https_connector), + Some(TlsConnector::from(Arc::new(tls_config))), + ) } else if let Some(ca_cert_path) = tls_cert_file { // Ensure crypto provider is initialized before creating TLS config ensure_crypto_provider_initialized(); @@ -226,9 +247,21 @@ pub fn create_client( // Create a root certificate store and add custom certs let mut root_store = RootCertStore::empty(); + for cert in &certs { + root_store.add(cert.clone())?; + } + + // The tunnel's handshake with the destination trusts the public roots plus the + // custom certs: a proxy that tunnels without intercepting passes Datadog's publicly + // signed certificate through, and an intercepting one re-signs it with the custom CA. + let mut tunnel_roots = RootCertStore::empty(); + tunnel_roots.extend(public_roots.iter().cloned()); for cert in certs { - root_store.add(cert)?; + tunnel_roots.add(cert)?; } + let tunnel_config = rustls::ClientConfig::builder() + .with_root_certificates(tunnel_roots) + .with_no_client_auth(); // Build the TLS config with custom root certificates let tls_config = rustls::ClientConfig::builder() @@ -237,7 +270,7 @@ pub fn create_client( // Build the HTTPS connector with custom config let https_connector = HttpsConnectorBuilder::new() - .with_tls_config(tls_config) + .with_tls_config(tls_config.clone()) .https_or_http() .enable_http1() .build(); @@ -245,16 +278,25 @@ pub fn create_client( debug!("HTTP_CLIENT | Added root certificate from {}", ca_cert_path); // Construct the Connector::Https variant directly - libdd_common::connector::Connector::Https(https_connector) + ( + libdd_common::connector::Connector::Https(https_connector), + Some(TlsConnector::from(Arc::new(tunnel_config))), + ) } else { // Use default connector - libdd_common::connector::Connector::default() + (libdd_common::connector::Connector::default(), None) }; if let Some(proxy) = proxy_https { let proxy = hyper_http_proxy::Proxy::new(hyper_http_proxy::Intercept::Https, proxy.parse()?); - let proxy_connector = hyper_http_proxy::ProxyConnector::from_proxy(connector, proxy)?; + let mut proxy_connector = hyper_http_proxy::ProxyConnector::from_proxy(connector, proxy)?; + // from_proxy() builds its own tunnel TLS connector with public webpki roots, so a CA + // from DD_TLS_CERT_FILE (or DD_SKIP_SSL_VALIDATION) never applied to the handshake + // with the destination. Replace it with the connector built from the same policy. + if let Some(tls) = tunnel_tls { + proxy_connector.set_tls(Some(tls)); + } // Disable connection pooling to avoid stale connections after Lambda freeze/resume. // In Lambda, the execution environment can be frozen for seconds to minutes between // invocations. Pooled connections become stale during this time, causing failures @@ -279,3 +321,321 @@ pub fn create_client( )) } } + +#[cfg(test)] +mod tests { + //! SLES-3105: `DD_TLS_CERT_FILE` must be honoured for the TLS handshake that + //! happens *inside* the CONNECT tunnel, not just for the connection to the proxy. + //! + //! Topology under test (all on loopback): + //! client --HTTP--> CONNECT proxy --TCP--> TLS server (leaf signed by a private CA) + use super::*; + use std::io::Write; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tempfile::NamedTempFile; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + + const TEST_CA_CERT_PEM: &str = r" +-----BEGIN CERTIFICATE----- +MIIBnzCCAUWgAwIBAgIUf5l+dmNjL/xU10EM0qk4Iseh3nQwCgYIKoZIzj0EAwIw +HDEaMBgGA1UEAwwRQm90dGxlY2FwIFRlc3QgQ0EwIBcNMjYwNjI1MTgzNjMwWhgP +MjEyNjA2MDExODM2MzBaMBwxGjAYBgNVBAMMEUJvdHRsZWNhcCBUZXN0IENBMFkw +EwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEK9O0WnLz1pRAD3RZzYzsCf8vEieLLwnV +D8RNYJBaEBZBJbE+4snr+0vhVm2mGtIojZTJ0bc5Z98JHpZ57LBpwqNjMGEwHQYD +VR0OBBYEFJtZHbWEv1FI0KacM/4ctJkUuMg2MB8GA1UdIwQYMBaAFJtZHbWEv1FI +0KacM/4ctJkUuMg2MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoG +CCqGSM49BAMCA0gAMEUCIQDFLc+zjel9LGmytihROgErrPc6WDxmziypva+k2cSN +CAIgYb1nsDag2/bwlzf4OOcYvqU9xNRdXMarkRxn4o5rPR4= +-----END CERTIFICATE----- +"; + const TEST_SERVER_CERT_PEM: &str = r" +-----BEGIN CERTIFICATE----- +MIIBvTCCAWSgAwIBAgIUOkYng/RZxQcYlMY5I+RAXzR7dSkwCgYIKoZIzj0EAwIw +HDEaMBgGA1UEAwwRQm90dGxlY2FwIFRlc3QgQ0EwIBcNMjYwNjI1MTgzNjMwWhgP +MjEyNjA2MDExODM2MzBaMBQxEjAQBgNVBAMMCWxvY2FsaG9zdDBZMBMGByqGSM49 +AgEGCCqGSM49AwEHA0IABOuKun0roY5MAEOgA3NNebQa9l56HVsNFwGJ4a5chM2T +s+vToAoyflPMZfxuS6PUv2WHrahmUH5WZKr0XaT/RIijgYkwgYYwCQYDVR0TBAIw +ADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwEwFAYDVR0RBA0w +C4IJbG9jYWxob3N0MB0GA1UdDgQWBBTcqKduDXHEOeUXAL6fqwAYl50VVTAfBgNV +HSMEGDAWgBSbWR21hL9RSNCmnDP+HLSZFLjINjAKBggqhkjOPQQDAgNHADBEAiAT +nwOMjOwnQoeLvZgHhNqrzlVGNqnT4FPudJTgTKrAAAIgVMw8wqk70JXLm4pEdN8/ +oMUo5j7nV6S8Hd02b5hW5pM= +-----END CERTIFICATE----- +"; + const TEST_SERVER_KEY_PEM: &str = r" +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgkflx4lEcI8Fafj8E +EgBejgnIKCAkaQXo+p0h3a6IsQOhRANCAATrirp9K6GOTABDoANzTXm0GvZeeh1b +DRcBieGuXITNk7Pr06AKMn5TzGX8bkuj1L9lh62oZlB+VmSq9F2k/0SI +-----END PRIVATE KEY----- +"; + + /// A CA that has nothing to do with the server certificate (negative control). + const UNRELATED_CA_PEM: &str = r" +-----BEGIN CERTIFICATE----- +MIIBfjCCASSgAwIBAgIUYP+TuKcxEIhJmpDhImnx0kx1VGMwCgYIKoZIzj0EAwIw +HDEaMBgGA1UEAwwRVW5yZWxhdGVkIFRlc3QgQ0EwIBcNMjYxMTE2MTIwMDQwWhgP +MjEyNjEwMjMxMjAwNDBaMBwxGjAYBgNVBAMMEVVucmVsYXRlZCBUZXN0IENBMFkw +EwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqqQSp7ePJKl/mYLhafkULk5tsx8N/eAG +D4AISM6bDMAMTYNy+b5D/o8OFi6Er9jR3SzlPP2eEpIrgw+llkFoVKNCMEAwHQYD +VR0OBBYEFM13NV0lLVfhl8ucmEirnnYgOl1HMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgEGMAoGCCqGSM49BAMCA0gAMEUCIQDpxEu50JhvSlIxMzDWboFF +NTK5yjb/KSEqOWs7Rs8B5QIgCTMvqLDKf5X3dZPGAAlYl/zmnv9DtU7Q1qT5FoK+ +QUI= +-----END CERTIFICATE----- +"; + + fn pem_file(pem: &str) -> NamedTempFile { + let mut f = NamedTempFile::new().expect("create temp pem file"); + f.write_all(pem.as_bytes()).expect("write temp pem file"); + f + } + + fn path_string(f: &NamedTempFile) -> String { + f.path().to_str().expect("utf8 path").to_string() + } + + /// HTTPS server presenting the private-CA-signed leaf. `requests` counts HTTP + /// requests that actually reached the server (i.e. handshake succeeded). + async fn spawn_tls_server(requests: Arc) -> u16 { + ensure_crypto_provider_initialized(); + let certs = rustls_pemfile::certs(&mut BufReader::new(TEST_SERVER_CERT_PEM.as_bytes())) + .collect::, _>>() + .expect("parse server cert"); + let key = rustls_pemfile::private_key(&mut BufReader::new(TEST_SERVER_KEY_PEM.as_bytes())) + .expect("read server key") + .expect("server key present"); + let server_config = rustls::ServerConfig::builder() + .with_no_client_auth() + .with_single_cert(certs, key) + .expect("server tls config"); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config)); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind tls"); + let port = listener.local_addr().expect("addr").port(); + tokio::spawn(async move { + loop { + let Ok((sock, _)) = listener.accept().await else { + return; + }; + let acceptor = acceptor.clone(); + let requests = requests.clone(); + tokio::spawn(async move { + let Ok(mut tls) = acceptor.accept(sock).await else { + return; + }; + let mut buf = vec![0u8; 8192]; + let mut acc = Vec::new(); + loop { + let n = match tls.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => n, + }; + acc.extend_from_slice(&buf[..n]); + if acc.windows(4).any(|w| w == b"\r\n\r\n") { + requests.fetch_add(1, Ordering::SeqCst); + let _ = tls + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await; + let _ = tls.shutdown().await; + return; + } + } + }); + } + }); + port + } + + /// Minimal TLS-*passthrough* CONNECT proxy: it never terminates TLS, so the + /// destination certificate is verified by the client inside the tunnel -- exactly + /// the handshake that was using the wrong roots. `connects` counts CONNECTs seen. + async fn spawn_connect_proxy(connects: Arc) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind proxy"); + let port = listener.local_addr().expect("addr").port(); + tokio::spawn(async move { + loop { + let Ok((mut client, _)) = listener.accept().await else { + return; + }; + let connects = connects.clone(); + tokio::spawn(async move { + let mut head = Vec::new(); + let mut buf = [0u8; 1024]; + while !head.windows(4).any(|w| w == b"\r\n\r\n") { + match client.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => head.extend_from_slice(&buf[..n]), + } + } + let head = String::from_utf8_lossy(&head).to_string(); + let first = head.lines().next().unwrap_or_default(); + let mut parts = first.split_whitespace(); + if parts.next() != Some("CONNECT") { + return; + } + connects.fetch_add(1, Ordering::SeqCst); + let target_port: u16 = parts + .next() + .and_then(|t| t.rsplit(':').next()) + .and_then(|p| p.parse().ok()) + .expect("CONNECT target port"); + let Ok(mut upstream) = TcpStream::connect(("127.0.0.1", target_port)).await + else { + return; + }; + if client + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .await + .is_err() + { + return; + } + let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await; + }); + } + }); + port + } + + async fn get( + client: &HttpClient, + port: u16, + ) -> Result, HttpError> { + let req = http::Request::builder() + .method("GET") + .uri(format!("https://localhost:{port}/")) + .body(bytes::Bytes::new()) + .expect("request"); + client.request(req).await + } + + fn proxy_url(port: u16) -> String { + format!("http://127.0.0.1:{port}") + } + + /// THE BUG. Private CA supplied via `DD_TLS_CERT_FILE`, destination reached through a + /// CONNECT proxy: the tunnel handshake must trust that CA. + #[tokio::test] + async fn proxy_tunnel_trusts_tls_cert_file_ca() { + let (connects, hits) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let server = spawn_tls_server(hits.clone()).await; + let proxy = spawn_connect_proxy(connects.clone()).await; + let ca = pem_file(TEST_CA_CERT_PEM); + + let client = + create_client(Some(&proxy_url(proxy)), Some(&path_string(&ca)), false).expect("client"); + let resp = get(&client, server) + .await + .expect("request through proxy should succeed"); + + assert_eq!(resp.status(), 200); + assert_eq!(resp.body().as_ref(), b"ok"); + assert_eq!( + connects.load(Ordering::SeqCst), + 1, + "request must go via the proxy" + ); + assert_eq!(hits.load(Ordering::SeqCst), 1); + } + + /// Trust anchors for the CA in `pem`, standing in for the public bundle. + fn anchors_from(pem: &str) -> Vec> { + let cert = rustls_pemfile::certs(&mut BufReader::new(pem.as_bytes())) + .next() + .expect("a certificate") + .expect("parse certificate"); + let mut store = RootCertStore::empty(); + store.add(cert).expect("add certificate"); + store.roots + } + + /// A proxy that tunnels without intercepting passes the destination's own certificate + /// through. Setting `DD_TLS_CERT_FILE` (here an unrelated CA, as for a proxy that is + /// itself signed by a private CA) must not drop the public roots that certificate needs. + #[tokio::test] + async fn proxy_tunnel_keeps_public_roots_when_tls_cert_file_is_set() { + let (connects, hits) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let server = spawn_tls_server(hits.clone()).await; + let proxy = spawn_connect_proxy(connects.clone()).await; + let proxy_ca = pem_file(UNRELATED_CA_PEM); + + let client = create_client_with_public_roots( + Some(&proxy_url(proxy)), + Some(&path_string(&proxy_ca)), + false, + &anchors_from(TEST_CA_CERT_PEM), + ) + .expect("client"); + let resp = get(&client, server) + .await + .expect("the tunnel must still trust the public roots"); + + assert_eq!(resp.status(), 200); + assert_eq!(connects.load(Ordering::SeqCst), 1); + assert_eq!(hits.load(Ordering::SeqCst), 1); + } + + /// Verification must stay ON: an unrelated CA must NOT make the tunnel trust the server. + #[tokio::test] + async fn proxy_tunnel_rejects_unrelated_ca() { + let (connects, hits) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let server = spawn_tls_server(hits.clone()).await; + let proxy = spawn_connect_proxy(connects.clone()).await; + let ca = pem_file(UNRELATED_CA_PEM); + + let client = + create_client(Some(&proxy_url(proxy)), Some(&path_string(&ca)), false).expect("client"); + assert!( + get(&client, server).await.is_err(), + "unrelated CA must be rejected" + ); + assert_eq!( + hits.load(Ordering::SeqCst), + 0, + "no HTTP request may reach the server" + ); + } + + /// Without a custom CA the default (public) roots apply and a private-CA server is rejected. + #[tokio::test] + async fn proxy_tunnel_rejects_private_ca_without_tls_cert_file() { + let (connects, hits) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let server = spawn_tls_server(hits.clone()).await; + let proxy = spawn_connect_proxy(connects.clone()).await; + + let client = create_client(Some(&proxy_url(proxy)), None, false).expect("client"); + assert!(get(&client, server).await.is_err()); + assert_eq!(hits.load(Ordering::SeqCst), 0); + } + + /// Same bug, other knob: `DD_SKIP_SSL_VALIDATION=true` must also apply inside the tunnel. + #[tokio::test] + async fn proxy_tunnel_honours_skip_ssl_validation() { + let (connects, hits) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let server = spawn_tls_server(hits.clone()).await; + let proxy = spawn_connect_proxy(connects.clone()).await; + + let client = create_client(Some(&proxy_url(proxy)), None, true).expect("client"); + let resp = get(&client, server) + .await + .expect("skip_ssl_validation must work via proxy"); + assert_eq!(resp.status(), 200); + assert_eq!(connects.load(Ordering::SeqCst), 1); + } + + /// Control (the customer's "direct HTTPS + trusted CA" row): already worked, must keep working. + #[tokio::test] + async fn direct_connection_trusts_tls_cert_file_ca() { + let hits = Arc::new(AtomicUsize::new(0)); + let server = spawn_tls_server(hits.clone()).await; + let ca = pem_file(TEST_CA_CERT_PEM); + + let client = create_client(None, Some(&path_string(&ca)), false).expect("client"); + let resp = get(&client, server) + .await + .expect("direct request should succeed"); + assert_eq!(resp.status(), 200); + assert_eq!(hits.load(Ordering::SeqCst), 1); + } +} diff --git a/bottlecap/tests/HARNESS.md b/bottlecap/tests/HARNESS.md index 41994b5fd..57c634766 100644 --- a/bottlecap/tests/HARNESS.md +++ b/bottlecap/tests/HARNESS.md @@ -28,6 +28,7 @@ a test whose expected behavior is a design choice, not a plain bug. | `tests/fault_injection_test.rs` | Intake faults: a 503 storm, an oversized trace, a response cut off mid-body. | | `tests/config_robustness_test.rs` | Wrong-typed config values. | | `tests/port_conflict_test.rs` | Another process holds port 8124 or 8126. | +| `tests/proxy_tls_test.rs` | `DD_PROXY_HTTPS` + `DD_TLS_CERT_FILE`: a trace reaches a private-CA HTTPS intake through a CONNECT proxy (a TLS front over `FaultIntake`, a CONNECT proxy that only tunnels to it). | | `.config/nextest.toml` | `fixed-ports` test group (`max-threads = 1`) for these binaries. | ## Write a new fault test in 10 lines @@ -163,7 +164,8 @@ while the `http://` intake URLs bypass it). Managed Instance mode adds ```sh cd bottlecap cargo nextest run --test lifecycle_contract_test --test fault_injection_test \ - --test config_robustness_test --test port_conflict_test # CI set, ignored skipped + --test config_robustness_test --test port_conflict_test \ + --test proxy_tls_test # CI set, ignored skipped cargo nextest run --test fault_injection_test --run-ignored only # not-yet-fixed tests (none yet) cargo test --test fault_injection_test # also serialized ``` diff --git a/bottlecap/tests/proxy_tls_test.rs b/bottlecap/tests/proxy_tls_test.rs new file mode 100644 index 000000000..3e864b0b6 --- /dev/null +++ b/bottlecap/tests/proxy_tls_test.rs @@ -0,0 +1,242 @@ +// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 +// Integration tests are exempt from the production lint policy in Cargo.toml. +#![allow( + unreachable_pub, + clippy::pedantic, + clippy::panic, + clippy::unwrap_used, + clippy::expect_used +)] + +//! With `DD_PROXY_HTTPS` set to a CONNECT proxy and `DD_TLS_CERT_FILE` holding the CA +//! that signed the intake's certificate, a trace reaches the intake through the tunnel. +//! The handshake inside the tunnel must trust that CA, as the TLS-intercepting proxies +//! some customers run in front of Datadog require. + +mod fixtures; +#[path = "common/harness.rs"] +mod harness; + +use std::io::BufReader; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; + +use harness::prelude::*; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +const TRACES_PATH: &str = "/api/v0.2/traces"; + +// Test PKI shared with `src/http.rs`: a private CA that is in no public root store, and a +// `localhost` leaf it signed. See the comment on these constants there to regenerate. +const CA_PEM: &str = r" +-----BEGIN CERTIFICATE----- +MIIBnzCCAUWgAwIBAgIUf5l+dmNjL/xU10EM0qk4Iseh3nQwCgYIKoZIzj0EAwIw +HDEaMBgGA1UEAwwRQm90dGxlY2FwIFRlc3QgQ0EwIBcNMjYwNjI1MTgzNjMwWhgP +MjEyNjA2MDExODM2MzBaMBwxGjAYBgNVBAMMEUJvdHRsZWNhcCBUZXN0IENBMFkw +EwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEK9O0WnLz1pRAD3RZzYzsCf8vEieLLwnV +D8RNYJBaEBZBJbE+4snr+0vhVm2mGtIojZTJ0bc5Z98JHpZ57LBpwqNjMGEwHQYD +VR0OBBYEFJtZHbWEv1FI0KacM/4ctJkUuMg2MB8GA1UdIwQYMBaAFJtZHbWEv1FI +0KacM/4ctJkUuMg2MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoG +CCqGSM49BAMCA0gAMEUCIQDFLc+zjel9LGmytihROgErrPc6WDxmziypva+k2cSN +CAIgYb1nsDag2/bwlzf4OOcYvqU9xNRdXMarkRxn4o5rPR4= +-----END CERTIFICATE----- +"; + +const SERVER_CERT_PEM: &str = r" +-----BEGIN CERTIFICATE----- +MIIBvTCCAWSgAwIBAgIUOkYng/RZxQcYlMY5I+RAXzR7dSkwCgYIKoZIzj0EAwIw +HDEaMBgGA1UEAwwRQm90dGxlY2FwIFRlc3QgQ0EwIBcNMjYwNjI1MTgzNjMwWhgP +MjEyNjA2MDExODM2MzBaMBQxEjAQBgNVBAMMCWxvY2FsaG9zdDBZMBMGByqGSM49 +AgEGCCqGSM49AwEHA0IABOuKun0roY5MAEOgA3NNebQa9l56HVsNFwGJ4a5chM2T +s+vToAoyflPMZfxuS6PUv2WHrahmUH5WZKr0XaT/RIijgYkwgYYwCQYDVR0TBAIw +ADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwEwFAYDVR0RBA0w +C4IJbG9jYWxob3N0MB0GA1UdDgQWBBTcqKduDXHEOeUXAL6fqwAYl50VVTAfBgNV +HSMEGDAWgBSbWR21hL9RSNCmnDP+HLSZFLjINjAKBggqhkjOPQQDAgNHADBEAiAT +nwOMjOwnQoeLvZgHhNqrzlVGNqnT4FPudJTgTKrAAAIgVMw8wqk70JXLm4pEdN8/ +oMUo5j7nV6S8Hd02b5hW5pM= +-----END CERTIFICATE----- +"; + +const SERVER_KEY_PEM: &str = r" +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgkflx4lEcI8Fafj8E +EgBejgnIKCAkaQXo+p0h3a6IsQOhRANCAATrirp9K6GOTABDoANzTXm0GvZeeh1b +DRcBieGuXITNk7Pr06AKMn5TzGX8bkuj1L9lh62oZlB+VmSq9F2k/0SI +-----END PRIVATE KEY----- +"; + +/// An HTTPS endpoint presenting the private-CA leaf for `localhost`. It decrypts and +/// relays to `intake`, the plain-HTTP fault intake, which records and decodes the +/// requests. Returns the port. +async fn tls_front(intake: SocketAddr) -> u16 { + #[cfg(feature = "fips")] + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + #[cfg(not(feature = "fips"))] + let _ = rustls::crypto::ring::default_provider().install_default(); + let certs = rustls_pemfile::certs(&mut BufReader::new(SERVER_CERT_PEM.as_bytes())) + .collect::, _>>() + .expect("parse server cert"); + let key = rustls_pemfile::private_key(&mut BufReader::new(SERVER_KEY_PEM.as_bytes())) + .expect("read server key") + .expect("server key present"); + let config = rustls::ServerConfig::builder() + .with_no_client_auth() + .with_single_cert(certs, key) + .expect("server tls config"); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config)); + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind tls front"); + let port = listener.local_addr().expect("addr").port(); + tokio::spawn(async move { + loop { + let Ok((sock, _)) = listener.accept().await else { + return; + }; + let acceptor = acceptor.clone(); + tokio::spawn(async move { + let Ok(mut tls) = acceptor.accept(sock).await else { + return; + }; + let Ok(mut plain) = TcpStream::connect(intake).await else { + return; + }; + let _ = tokio::io::copy_bidirectional(&mut tls, &mut plain).await; + }); + } + }); + port +} + +/// A CONNECT proxy that tunnels only to `127.0.0.1:allowed_port` and answers `403` to any +/// other target, so no request leaves the machine. It never terminates TLS: the client +/// verifies the destination's certificate inside the tunnel. +struct ConnectProxy { + port: u16, + /// The `host:port` of every CONNECT it received. + targets: Arc>>, +} + +async fn connect_proxy(allowed_port: u16) -> ConnectProxy { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind proxy"); + let port = listener.local_addr().expect("addr").port(); + let targets = Arc::new(Mutex::new(Vec::new())); + let seen = Arc::clone(&targets); + tokio::spawn(async move { + loop { + let Ok((mut client, _)) = listener.accept().await else { + return; + }; + let seen = Arc::clone(&seen); + tokio::spawn(async move { + let mut head = Vec::new(); + let mut buf = [0u8; 1024]; + while !head.windows(4).any(|w| w == b"\r\n\r\n") { + match client.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => head.extend_from_slice(&buf[..n]), + } + } + let head = String::from_utf8_lossy(&head).into_owned(); + let mut first = head.lines().next().unwrap_or_default().split_whitespace(); + if first.next() != Some("CONNECT") { + return; + } + let target = first.next().unwrap_or_default().to_string(); + seen.lock().expect("targets lock").push(target.clone()); + let upstream = if target.rsplit(':').next() == Some(&allowed_port.to_string()) { + TcpStream::connect(("127.0.0.1", allowed_port)).await.ok() + } else { + None + }; + let Some(mut upstream) = upstream else { + let _ = client.write_all(b"HTTP/1.1 403 Forbidden\r\n\r\n").await; + return; + }; + if client + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .await + .is_ok() + { + let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await; + } + }); + } + }); + ConnectProxy { port, targets } +} + +/// A trace flushed at the end of an invocation reaches an HTTPS intake whose certificate a +/// private CA signed, through `DD_PROXY_HTTPS`, when `DD_TLS_CERT_FILE` names that CA. +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial(bottlecap_ports)] +async fn trace_reaches_private_ca_intake_through_connect_proxy() { + const TRACE_ID: u64 = 7; + let s = Scenario::start(FaultMode::Ok).await; + let front = tls_front(s.intake.addr).await; + let proxy = connect_proxy(front).await; + let ca_dir = tempfile::tempdir().expect("tempdir"); + let ca_path = ca_dir.path().join("ca.pem"); + std::fs::write(&ca_path, CA_PEM).expect("write ca"); + + let mut bc = s + .bottlecap() + .env("DD_APM_DD_URL", &format!("https://localhost:{front}")) + .env( + "DD_PROXY_HTTPS", + &format!("http://127.0.0.1:{}", proxy.port), + ) + .env("DD_TLS_CERT_FILE", ca_path.to_str().expect("utf8 path")) + .spawn(); + let deadline = s + .invoke("req-1", secs(10), 1, bc.startup_deadline()) + .await + .unwrap_or_else(|| panic!("no /next poll. {}", bc.log_tail(40))); + + let status = post_trace(msgpack_trace(TRACE_ID, 0), STARTUP_BUDGET) + .await + .unwrap(); + assert_eq!( + status, + 200, + "the trace agent refused the trace. {}", + bc.log_tail(40) + ); + deliver_start(&s.api, "req-1", true).await.unwrap(); + deliver_runtime_done(&s.api, "req-1", true).await.unwrap(); + + let delivered = s + .intake + .wait_for( + 1, + |r| { + r.path.contains(TRACES_PATH) + && r.status == 202 + && r.api_key() == Some(TEST_API_KEY) + && r.trace_ids().is_ok_and(|ids| ids.contains(&TRACE_ID)) + }, + deadline, + ) + .await; + let released = s.api.wait_for_next_calls(2, deadline).await; + let targets = proxy.targets.lock().unwrap().clone(); + s.shutdown_cleanly(&mut bc).await; + + assert!( + delivered, + "the trace did not reach the private-CA intake through the proxy. CONNECTs: {targets:?}\nIntake:\n{}\n{}", + s.intake.summary(), + bc.log_tail(40) + ); + assert!( + targets.contains(&format!("localhost:{front}")), + "the trace did not go through the proxy. CONNECTs: {targets:?}" + ); + assert!( + released, + "/next was not called by the invoke deadline. {}", + bc.log_tail(40) + ); +}