Skip to main content

saluki_components/relays/apm/
tracer_flare.rs

1//! Tracer flare proxy.
2//!
3//! Tracers upload flares, a multipart form holding a zip archive and the support case it belongs to, to
4//! `/tracer_flare/v1`. Like the trace-agent, the relay forwards them as they are to the Datadog serverless flare
5//! endpoint, adding the API key.
6
7use axum::extract::{ConnectInfo, Request as AxumRequest};
8use axum::response::{IntoResponse, Response};
9use datadog_agent_commons::agent_version::{self, AgentVersion};
10use http::header::{self, HeaderMap, HeaderName};
11use http::{HeaderValue, StatusCode, Uri, Version};
12use saluki_common::sync::live::Live;
13use saluki_error::{generic_error, GenericError};
14use saluki_io::net::client::http::HttpClientBuilder;
15use saluki_io::net::ConnectionAddress;
16use tracing::{debug, warn};
17use url::Url;
18
19use crate::common::datadog::api_key::ApiKeyCell;
20use crate::common::datadog::config::ForwarderConfiguration;
21use crate::common::datadog::endpoints::{add_version_prefix, endpoint_with_default_scheme, is_datadog_site};
22use crate::common::datadog::io::intake_http_client_builder;
23use crate::common::proxy::{strip_hop_by_hop_headers, UpstreamClient};
24
25/// Path of the Datadog endpoint flares are forwarded to.
26const FLARE_ENDPOINT_PATH: &str = "/api/ui/support/serverless/flare";
27
28/// Site flares are sent to when none is configured, as in the trace-agent.
29const DEFAULT_SITE: &str = "datadoghq.com";
30
31/// Name the API key source is logged under.
32const API_KEY_SOURCE: &str = "tracer_flare";
33
34const DD_API_KEY_HEADER: HeaderName = HeaderName::from_static("dd-api-key");
35const FORWARDED_HEADER: HeaderName = HeaderName::from_static("forwarded");
36const X_FORWARDED_FOR_HEADER: HeaderName = HeaderName::from_static("x-forwarded-for");
37const X_FORWARDED_HOST_HEADER: HeaderName = HeaderName::from_static("x-forwarded-host");
38const X_FORWARDED_PROTO_HEADER: HeaderName = HeaderName::from_static("x-forwarded-proto");
39
40/// Settings of the tracer flare proxy.
41#[derive(Clone)]
42pub struct TracerFlareConfiguration {
43    /// Datadog site flares are sent to, such as `datadoghq.com`.
44    ///
45    /// Empty means `datadoghq.com`.
46    pub site: String,
47
48    /// API key flares are sent with.
49    pub api_key: Live<String>,
50
51    /// Settings of the Datadog intake forwarder.
52    ///
53    /// Only the settings of its HTTP client are used: the request timeout, the TLS settings (handshake timeout, key log
54    /// file, and certificate validation, including `skip_ssl_validation`), the proxy, the HTTP protocol, and the
55    /// connection reset interval. The destination comes from `site`, and the API key from `api_key`.
56    pub forwarder: ForwarderConfiguration,
57}
58
59/// Forwards tracer flares to Datadog.
60#[derive(Clone)]
61pub(super) struct TracerFlareProxy {
62    client: UpstreamClient,
63
64    /// Where flares are forwarded to.
65    endpoint: Uri,
66
67    /// API key flares are sent with.
68    api_key: ApiKeyCell,
69}
70
71/// Error from forwarding a flare to Datadog.
72#[derive(Debug)]
73pub(super) struct ForwardError;
74
75impl IntoResponse for ForwardError {
76    fn into_response(self) -> Response {
77        StatusCode::BAD_GATEWAY.into_response()
78    }
79}
80
81impl TracerFlareProxy {
82    /// Creates a proxy forwarding flares to the flare endpoint of the configured site.
83    ///
84    /// # Errors
85    ///
86    /// If the site isn't a valid host, the API key isn't a valid header value, or the HTTP client can't be built, an
87    /// error is returned.
88    pub(super) fn from_config(config: &TracerFlareConfiguration) -> Result<Self, GenericError> {
89        let site = match config.site.trim() {
90            "" => DEFAULT_SITE,
91            site => site,
92        };
93        let endpoint = flare_endpoint(site, &flare_version_label(agent_version::version()))?;
94        let client_builder =
95            intake_http_client_builder(&config.forwarder, config.forwarder.effective_min_tls_version())?;
96        Self::new(client_builder, endpoint, config.api_key.as_str())
97    }
98
99    fn new(client_builder: HttpClientBuilder, endpoint: Uri, api_key: &str) -> Result<Self, GenericError> {
100        let api_key = ApiKeyCell::new(api_key)
101            .map_err(|e| generic_error!("The configured API key is not a valid HTTP header value: {e}"))?;
102        debug!(%endpoint, "Tracer flares are forwarded to Datadog.");
103
104        Ok(Self {
105            client: UpstreamClient::new(client_builder.build()?),
106            endpoint,
107            api_key,
108        })
109    }
110
111    /// Returns the API key flares are sent with, shared: a refresh through this proxy updates every clone.
112    pub(super) fn api_key(&self) -> ApiKeyCell {
113        self.api_key.clone()
114    }
115
116    /// Replaces the API key flares are sent with.
117    pub(super) fn refresh_api_key(&self, api_key: &str) {
118        self.api_key.refresh(API_KEY_SOURCE, api_key);
119    }
120
121    /// Forwards the flare in `request` to Datadog and returns its response.
122    ///
123    /// Any response from Datadog is returned as is, including an error status. The request keeps its method, headers,
124    /// and body, but not its path or query, as the trace-agent does.
125    ///
126    /// # Errors
127    ///
128    /// If Datadog can't be reached, an error is returned, answered with `502 Bad Gateway`.
129    pub(super) async fn forward(&self, request: AxumRequest) -> Result<Response, ForwardError> {
130        let (mut parts, body) = request.into_parts();
131
132        let forwarded_host = request_host(&parts.uri, &parts.headers);
133        let peer_ip =
134            parts
135                .extensions
136                .get::<ConnectInfo<ConnectionAddress>>()
137                .and_then(|ConnectInfo(addr)| match addr {
138                    ConnectionAddress::SocketLike(addr) => Some(addr.ip().to_string()),
139                    ConnectionAddress::ProcessLike(_) => None,
140                });
141
142        parts.uri = self.endpoint.clone();
143        // The relay's server also accepts HTTP/2: the client picks the protocol of its own connection.
144        parts.version = Version::default();
145        set_upstream_headers(
146            &mut parts.headers,
147            peer_ip.as_deref(),
148            forwarded_host.as_ref(),
149            &self.api_key.load(),
150        );
151
152        self.client
153            .send(http::Request::from_parts(parts, body))
154            .await
155            .map_err(|e| {
156                warn!(endpoint = %self.endpoint, error = %e, "Failed to forward tracer flare to Datadog.");
157                ForwardError
158            })
159    }
160}
161
162/// Returns the host a request was sent to, from its URI for HTTP/2 or its `Host` header for HTTP/1.1.
163fn request_host(uri: &Uri, headers: &HeaderMap) -> Option<HeaderValue> {
164    match uri.authority() {
165        Some(authority) => HeaderValue::from_str(authority.as_str()).ok(),
166        None => headers.get(header::HOST).cloned(),
167    }
168}
169
170/// Rewrites the headers of a flare request for Datadog, as Go's `httputil.ReverseProxy` does for the trace-agent.
171///
172/// Headers set by an earlier proxy are replaced rather than added to, so the client can't pass itself off as another.
173fn set_upstream_headers(
174    headers: &mut HeaderMap, peer_ip: Option<&str>, forwarded_host: Option<&HeaderValue>, api_key: &str,
175) {
176    strip_hop_by_hop_headers(headers);
177    // The client sets `Host` from the upstream URI.
178    headers.remove(header::HOST);
179    headers.remove(FORWARDED_HEADER);
180    headers.remove(X_FORWARDED_FOR_HEADER);
181    headers.remove(X_FORWARDED_HOST_HEADER);
182
183    if let Some(peer_ip) = peer_ip.and_then(|ip| HeaderValue::from_str(ip).ok()) {
184        headers.insert(X_FORWARDED_FOR_HEADER, peer_ip);
185    }
186    if let Some(host) = forwarded_host {
187        headers.insert(X_FORWARDED_HOST_HEADER, host.clone());
188    }
189    // The relay only serves plain HTTP.
190    headers.insert(X_FORWARDED_PROTO_HEADER, HeaderValue::from_static("http"));
191
192    match HeaderValue::from_str(api_key) {
193        Ok(mut value) => {
194            value.set_sensitive(true);
195            headers.insert(DD_API_KEY_HEADER, value);
196        }
197        // `ApiKeyCell` only holds valid header values.
198        Err(_) => {
199            headers.remove(DD_API_KEY_HEADER);
200        }
201    }
202}
203
204/// Returns the version label of the flare host, such as `7-50-0-flare`.
205///
206/// The trace-agent uses its own version. When the Agent version wasn't known at build time, or carries no version
207/// number, ADP's version is used instead.
208fn flare_version_label(agent_version: Option<AgentVersion>) -> String {
209    // A development build with no version number, such as `nightly`, has a major version of `0`.
210    let (major, minor, patch) = match agent_version.filter(|version| version.major() != 0) {
211        Some(version) => (version.major(), version.minor(), version.patch()),
212        None => {
213            let version = saluki_metadata::get_app_details().version();
214            (version.major().into(), version.minor().into(), version.patch().into())
215        }
216    };
217    format!("{major}-{minor}-{patch}-flare")
218}
219
220/// Returns the flare endpoint of `site`, a Datadog site such as `datadoghq.com` or a URL.
221///
222/// This follows the trace-agent's `getServerlessFlareEndpoint`: an official Datadog application host has its leftmost
223/// label replaced with `version_label` (a bare official site is treated as its `app.` host), and any other host is
224/// kept. The scheme is always `https`, and the path is always that of the flare endpoint.
225///
226/// It differs from the trace-agent in two ways:
227///
228/// - A site with a subdomain but no scheme, such as `us3.datadoghq.com`, is taken as the host, where the trace-agent
229///   leaves the host empty.
230/// - Official hosts are recognized as the forwarder recognizes them, so a Multi-Region Failover host such as
231///   `app.mrf.datadoghq.com` is versioned too, where the trace-agent keeps it.
232///
233/// # Errors
234///
235/// If `site` isn't a valid URL with a host, an error is returned.
236fn flare_endpoint(site: &str, version_label: &str) -> Result<Uri, GenericError> {
237    let site = site.trim();
238    let invalid = |e: &dyn std::fmt::Display| {
239        generic_error!("Datadog site `{site}` is not a valid host to send tracer flares to: {e}")
240    };
241
242    let mut url = Url::parse(&endpoint_with_default_scheme(site)).map_err(|e| invalid(&e))?;
243    if let Some(app_host) = url
244        .host_str()
245        .filter(|host| is_datadog_site(host))
246        .map(|host| format!("app.{host}"))
247    {
248        url.set_host(Some(&app_host)).map_err(|e| invalid(&e))?;
249    }
250    let mut url = add_version_prefix(url, version_label).map_err(|e| invalid(&e))?;
251
252    // `http` and `https` are both special schemes, so switching between them can't fail.
253    let _ = url.set_scheme("https");
254    // The URL has a host, so it can carry neither credentials nor a fragment that would fail to clear.
255    let _ = url.set_username("");
256    let _ = url.set_password(None);
257    url.set_path(FLARE_ENDPOINT_PATH);
258    url.set_query(None);
259    url.set_fragment(None);
260
261    url.as_str().parse().map_err(|e| invalid(&e))
262}
263
264/// A proxy forwarding to `base` over plain HTTP, standing in for the flare endpoint, as the trace-agent's test does.
265///
266/// It installs the TLS crypto provider first, as application bootstrap does. Without it, a FIPS build falls back to a
267/// provider whose cipher suites aren't all FIPS-approved, and the HTTP client refuses to build.
268#[cfg(test)]
269pub(super) fn plain_http_proxy(base: &str, api_key: &str) -> TracerFlareProxy {
270    crate::common::datadog::test_util::init_tls();
271    let builder = saluki_io::net::client::http::HttpClient::builder()
272        .with_tls_config(|builder| builder.with_root_cert_store(rustls::RootCertStore::empty()))
273        .with_http_protocol(saluki_io::net::client::http::HttpProtocol::Http1);
274    let endpoint = format!("{base}{FLARE_ENDPOINT_PATH}")
275        .parse()
276        .expect("endpoint should parse");
277    TracerFlareProxy::new(builder, endpoint, api_key).expect("proxy should build")
278}
279
280#[cfg(test)]
281mod tests {
282    use std::net::SocketAddr;
283    use std::sync::Arc;
284
285    use axum::body::{to_bytes, Body};
286    use axum::routing::any;
287    use axum::Router;
288    use tokio::net::TcpListener;
289    use tokio::sync::Mutex as AsyncMutex;
290
291    use super::*;
292
293    const VERSION_LABEL: &str = "7-50-0-flare";
294
295    fn endpoint(site: &str) -> String {
296        flare_endpoint(site, VERSION_LABEL)
297            .expect("site should give an endpoint")
298            .to_string()
299    }
300
301    #[test]
302    fn flare_endpoint_matches_the_trace_agent() {
303        // The trace-agent's own test cases.
304        assert_eq!(
305            endpoint("datadoghq.com"),
306            "https://7-50-0-flare.datadoghq.com/api/ui/support/serverless/flare"
307        );
308        assert_eq!(
309            endpoint("https://app.datadoghq.com/test"),
310            "https://7-50-0-flare.datadoghq.com/api/ui/support/serverless/flare"
311        );
312        assert_eq!(
313            endpoint("https://us3.datadoghq.com/test"),
314            "https://us3.datadoghq.com/api/ui/support/serverless/flare"
315        );
316        assert_eq!(
317            endpoint("https://datadog.random.com/test"),
318            "https://datadog.random.com/api/ui/support/serverless/flare"
319        );
320    }
321
322    #[test]
323    fn flare_endpoint_versions_every_official_app_host() {
324        for (site, expected) in [
325            ("datadoghq.eu", "7-50-0-flare.datadoghq.eu"),
326            ("datad0g.com", "7-50-0-flare.datad0g.com"),
327            ("ddog-gov.com", "7-50-0-flare.ddog-gov.com"),
328            ("app.datadoghq.com", "7-50-0-flare.datadoghq.com"),
329            ("app.us5.datadoghq.com", "7-50-0-flare.us5.datadoghq.com"),
330            // The trace-agent keeps a Multi-Region Failover host; ADP versions it as the forwarder does.
331            ("app.mrf.datadoghq.com", "7-50-0-flare.mrf.datadoghq.com"),
332            ("http://app.datadoghq.eu", "7-50-0-flare.datadoghq.eu"),
333            (" DATADOGHQ.COM ", "7-50-0-flare.datadoghq.com"),
334        ] {
335            assert_eq!(
336                endpoint(site),
337                format!("https://{expected}/api/ui/support/serverless/flare"),
338                "{site}"
339            );
340        }
341    }
342
343    #[test]
344    fn flare_endpoint_keeps_other_hosts() {
345        // The trace-agent leaves the host of a bare `us3.datadoghq.com` empty; ADP uses the site as the host.
346        assert_eq!(
347            endpoint("us3.datadoghq.com"),
348            "https://us3.datadoghq.com/api/ui/support/serverless/flare"
349        );
350        assert_eq!(
351            endpoint("localhost:8080"),
352            "https://localhost:8080/api/ui/support/serverless/flare"
353        );
354        assert_eq!(
355            endpoint("http://[::1]:8443/flare"),
356            "https://[::1]:8443/api/ui/support/serverless/flare"
357        );
358    }
359
360    #[test]
361    fn flare_endpoint_drops_credentials_and_keeps_the_port() {
362        assert_eq!(
363            endpoint("https://user:secret@app.datadoghq.com"),
364            "https://7-50-0-flare.datadoghq.com/api/ui/support/serverless/flare"
365        );
366        assert_eq!(
367            endpoint("https://app.datadoghq.com:8443"),
368            "https://7-50-0-flare.datadoghq.com:8443/api/ui/support/serverless/flare"
369        );
370    }
371
372    #[test]
373    fn flare_endpoint_rejects_a_site_without_a_host() {
374        assert!(flare_endpoint("", VERSION_LABEL).is_err());
375        assert!(flare_endpoint("https://", VERSION_LABEL).is_err());
376        assert!(flare_endpoint("not a host", VERSION_LABEL).is_err());
377    }
378
379    #[test]
380    fn flare_version_label_uses_the_agent_version() {
381        assert_eq!(
382            flare_version_label(AgentVersion::parse("7.50.0-devel+git.488.be5861b")),
383            "7-50-0-flare"
384        );
385        assert_eq!(flare_version_label(AgentVersion::parse("7.81.2-full")), "7-81-2-flare");
386    }
387
388    #[test]
389    fn flare_version_label_falls_back_to_the_data_plane_version() {
390        let version = saluki_metadata::get_app_details().version();
391        let expected = format!("{}-{}-{}-flare", version.major(), version.minor(), version.patch());
392
393        assert_eq!(flare_version_label(None), expected);
394        assert_eq!(flare_version_label(AgentVersion::parse("nightly")), expected);
395    }
396
397    /// What the fake intake saw of the last request it received.
398    #[derive(Clone, Debug, Default)]
399    struct Seen {
400        method: String,
401        uri: String,
402        headers: HeaderMap,
403        body: Vec<u8>,
404    }
405
406    /// A stand-in flare intake: records each request and answers with `status`.
407    async fn spawn_intake(status: StatusCode) -> (String, Arc<AsyncMutex<Seen>>) {
408        let seen = Arc::new(AsyncMutex::new(Seen::default()));
409        let router = Router::new().fallback(any({
410            let seen = Arc::clone(&seen);
411            move |request: AxumRequest| {
412                let seen = Arc::clone(&seen);
413                async move {
414                    let (parts, body) = request.into_parts();
415                    let body = to_bytes(body, usize::MAX)
416                        .await
417                        .expect("request body should be readable");
418                    *seen.lock().await = Seen {
419                        method: parts.method.to_string(),
420                        uri: parts.uri.to_string(),
421                        headers: parts.headers,
422                        body: body.to_vec(),
423                    };
424                    (status, [("x-intake", "yes"), ("connection", "close")], "from intake")
425                }
426            }
427        }));
428        let listener = TcpListener::bind("127.0.0.1:0")
429            .await
430            .expect("should bind an ephemeral port");
431        let addr = listener.local_addr().expect("listener should have a local address");
432        tokio::spawn(async move { axum::serve(listener, router).await });
433        (format!("http://{addr}"), seen)
434    }
435
436    const MULTIPART_BODY: &str = "--boundary\r\n\
437        Content-Disposition: form-data; name=\"case_id\"\r\n\r\ncase_id\r\n\
438        --boundary\r\n\
439        Content-Disposition: form-data; name=\"flare_file\"; filename=\"flare.zip\"\r\n\
440        Content-Type: application/octet-stream\r\n\r\nzip bytes\r\n\
441        --boundary--\r\n";
442
443    fn flare_request(uri: &str, headers: &[(&str, &str)], peer: Option<ConnectionAddress>) -> AxumRequest {
444        let mut builder = http::Request::builder()
445            .method("POST")
446            .uri(uri)
447            .header("content-type", "multipart/form-data; boundary=boundary")
448            .header("host", "localhost:8126");
449        for (name, value) in headers {
450            builder = builder.header(*name, *value);
451        }
452        let mut request = builder.body(Body::from(MULTIPART_BODY)).expect("request should build");
453        if let Some(peer) = peer {
454            request.extensions_mut().insert(ConnectInfo(peer));
455        }
456        request
457    }
458
459    #[tokio::test]
460    async fn forwards_the_flare_to_the_flare_endpoint() {
461        let (base, seen) = spawn_intake(StatusCode::OK).await;
462        let proxy = plain_http_proxy(&base, "test-api-key");
463
464        let response = proxy
465            .forward(flare_request(
466                "/tracer_flare/v1?foo=bar",
467                &[],
468                Some(SocketAddr::from(([192, 0, 2, 7], 4242)).into()),
469            ))
470            .await
471            .expect("flare should be forwarded");
472
473        assert_eq!(response.status(), StatusCode::OK);
474        assert_eq!(response.headers()["x-intake"], "yes");
475        assert!(!response.headers().contains_key("connection"));
476        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
477        assert_eq!(&body[..], b"from intake");
478
479        let seen = seen.lock().await.clone();
480        assert_eq!(seen.method, "POST");
481        assert_eq!(seen.uri, FLARE_ENDPOINT_PATH, "the path and query should be replaced");
482        assert_eq!(seen.headers["dd-api-key"], "test-api-key");
483        assert_eq!(seen.headers["x-forwarded-for"], "192.0.2.7");
484        assert_eq!(seen.headers["x-forwarded-host"], "localhost:8126");
485        assert_eq!(seen.headers["x-forwarded-proto"], "http");
486        assert_eq!(seen.headers["content-type"], "multipart/form-data; boundary=boundary");
487        assert_ne!(seen.headers["host"], "localhost:8126");
488        assert_eq!(seen.body, MULTIPART_BODY.as_bytes());
489    }
490
491    #[tokio::test]
492    async fn replaces_the_headers_a_client_sets_for_the_proxy() {
493        let (base, seen) = spawn_intake(StatusCode::OK).await;
494        let proxy = plain_http_proxy(&base, "test-api-key");
495
496        proxy
497            .forward(flare_request(
498                "/tracer_flare/v1",
499                &[
500                    ("dd-api-key", "client-key"),
501                    ("x-forwarded-for", "203.0.113.1"),
502                    ("x-forwarded-host", "spoofed"),
503                    ("forwarded", "for=203.0.113.1"),
504                ],
505                None,
506            ))
507            .await
508            .expect("flare should be forwarded");
509
510        let seen = seen.lock().await.clone();
511        assert_eq!(seen.headers["dd-api-key"], "test-api-key");
512        // Without a TCP peer, there is no client IP to forward.
513        assert!(!seen.headers.contains_key("x-forwarded-for"));
514        assert_eq!(seen.headers["x-forwarded-host"], "localhost:8126");
515        assert!(!seen.headers.contains_key("forwarded"));
516    }
517
518    #[tokio::test]
519    async fn passes_an_error_status_through() {
520        let (base, _seen) = spawn_intake(StatusCode::FORBIDDEN).await;
521        let proxy = plain_http_proxy(&base, "test-api-key");
522
523        let response = proxy
524            .forward(flare_request("/tracer_flare/v1", &[], None))
525            .await
526            .expect("a response from Datadog should be returned as is");
527
528        assert_eq!(response.status(), StatusCode::FORBIDDEN);
529    }
530
531    #[tokio::test]
532    async fn an_unreachable_intake_is_a_bad_gateway() {
533        let proxy = plain_http_proxy("http://127.0.0.1:1", "test-api-key");
534
535        let error = proxy
536            .forward(flare_request("/tracer_flare/v1", &[], None))
537            .await
538            .expect_err("forwarding should fail");
539
540        assert_eq!(error.into_response().status(), StatusCode::BAD_GATEWAY);
541    }
542
543    #[tokio::test]
544    async fn sends_a_refreshed_api_key() {
545        let (base, seen) = spawn_intake(StatusCode::OK).await;
546        let proxy = plain_http_proxy(&base, "old-key");
547
548        proxy.refresh_api_key("new-key");
549        // A blank key is rejected, keeping the last usable one.
550        proxy.refresh_api_key("  ");
551        proxy
552            .forward(flare_request("/tracer_flare/v1", &[], None))
553            .await
554            .expect("flare should be forwarded");
555
556        assert_eq!(seen.lock().await.headers["dd-api-key"], "new-key");
557    }
558}