Skip to main content

saluki_components/relays/apm/
mod.rs

1//! APM relay.
2//!
3//! Listens on TCP and/or a Unix domain socket where the trace-agent normally listens. Requests for endpoints the relay
4//! does not handle itself are forwarded to the relocated trace-agent.
5//!
6//! The relay serves `/info` itself, and so owns `Datadog-Agent-State`, the hash of the `/info` body that every
7//! response carries: it replaces the trace-agent's on the responses it forwards.
8
9use std::net::SocketAddr;
10use std::sync::{Arc, LazyLock};
11use std::time::Duration;
12
13use async_trait::async_trait;
14use axum::extract::{ConnectInfo, Request as AxumRequest, State};
15use axum::middleware::{from_fn_with_state, Next};
16use axum::response::{IntoResponse, Response};
17use axum::routing::any;
18use axum::Router;
19use backon::{ExponentialBuilder, Retryable as _};
20use datadog_agent_apm::semantics::SemanticRegistryProvider;
21use datadog_agent_commons::ipc::client::{fetch_agent_version, RunningAgentVersion};
22use datadog_agent_commons::ipc::config::RemoteAgentClientConfiguration;
23use http::{HeaderName, HeaderValue};
24use metrics::Counter;
25use saluki_api::APIHandler;
26use saluki_common::sync::live::Live;
27use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder};
28use saluki_core::components::relays::{Relay, RelayBuilder, RelayContext};
29use saluki_core::components::BuildContext;
30use saluki_core::data_model::payload::PayloadType;
31use saluki_core::runtime;
32use saluki_core::topology::OutputDefinition;
33use saluki_env::workload::{CaptureEntityResolver, EntityId};
34use saluki_env::WorkloadProvider;
35use saluki_error::{generic_error, ErrorContext as _, GenericError};
36use saluki_io::net::dns::resolve_host;
37use saluki_io::net::server::http::HttpServer;
38use saluki_io::net::{ConnectionAddress, ListenAddress};
39use saluki_metrics::static_metrics;
40use tokio::{pin, select};
41use tracing::{debug, warn};
42
43use crate::common::proxy::listener_reached_by;
44
45mod container_tags;
46use self::container_tags::{ContainerTagsHasher, CONTAINER_TAGS_HASH_HEADER};
47
48mod info;
49use self::info::Info;
50
51mod opm;
52pub use self::info::{
53    InfoCacheObfuscation, InfoConfiguration, InfoJsonObfuscation, InfoObfuscation, InfoReplaceRule, InfoTagFilter,
54    InfoTagFilters,
55};
56use self::opm::OrgPropagationMarkerFetcher;
57
58mod proxy;
59use self::proxy::TraceAgentProxy;
60
61mod tracer_flare;
62pub use self::tracer_flare::TracerFlareConfiguration;
63use self::tracer_flare::TracerFlareProxy;
64
65/// Header a tracer sends its container ID in.
66const CONTAINER_ID_HEADER: HeaderName = HeaderName::from_static("datadog-container-id");
67
68/// Header a tracer sends its origin in (for example, `ci-<container ID>` or `in-<cgroup inode>`), which the trace-agent
69/// prefers over `Datadog-Container-ID`.
70const ENTITY_ID_HEADER: HeaderName = HeaderName::from_static("datadog-entity-id");
71
72/// Delay before the first retry of the org propagation marker fetch, doubled for each later retry.
73const ORG_PROP_MARKER_BASE_RETRY_DELAY: Duration = Duration::from_secs(1);
74
75/// Delay before the first retry of the Agent version fetch.
76const AGENT_VERSION_MIN_RETRY_DELAY: Duration = Duration::from_secs(1);
77
78/// Longest delay between retries of the Agent version fetch.
79const AGENT_VERSION_MAX_RETRY_DELAY: Duration = Duration::from_secs(60);
80
81/// Configuration for the APM relay.
82///
83/// Holds plain values, populated by the binary that assembles the topology, plus an optional resolver for the
84/// container of a tracer connected over the Unix domain socket.
85///
86/// `receiver_socket` is an empty `String` rather than an `Option<String>`, so that "disabled" has a single
87/// representation.
88#[derive(Clone)]
89pub struct ApmRelayConfiguration {
90    /// Unix domain socket path the relay listens on.
91    ///
92    /// Empty disables the Unix domain socket listener.
93    pub receiver_socket: String,
94
95    /// URL of the trace-agent that every request not handled by ADP is proxied to: `http://host:port` or
96    /// `unix:///path/to/socket`.
97    pub proxy_destination: String,
98
99    /// Resolver for mapping the process ID of a tracer connected over the Unix domain socket to its container.
100    ///
101    /// The trace-agent finds the container of a tracer that sends no container headers from the peer credentials of
102    /// its Unix domain socket connection, but behind the relay those credentials are ADP's. With a resolver, the relay
103    /// resolves the container from the tracer's credentials itself, and passes it on as `Datadog-Container-ID`.
104    pub capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
105
106    /// The host address to bind the APM relay TCP listeners to.
107    ///
108    /// Accepts either an IP literal (for example, `192.168.1.50`, `::1`) or a hostname that resolves via DNS (for example, `agent.internal`).
109    /// Ignored when `non_local_traffic` is `true`, and binds to `127.0.0.1` when unset.
110    pub bind_host: Option<String>,
111
112    /// Whether the TCP listener accepts traffic from other hosts.
113    ///
114    /// When `true`, the listener binds every interface, overriding `bind_host`, as the trace-agent does.
115    pub non_local_traffic: bool,
116
117    /// TCP port the trace receiver listens on.
118    ///
119    /// `0` disables the TCP listener.
120    pub receiver_port: u16,
121
122    /// Settings for forwarding tracer flares to Datadog.
123    pub tracer_flare: TracerFlareConfiguration,
124
125    /// The trace-agent settings the relay reports on `/info`.
126    pub info: InfoConfiguration,
127
128    /// Workload provider the tags of a tracer's container come from, for the `Datadog-Container-Tags-Hash` of `/info`.
129    ///
130    /// `None` when ADP runs without the core Agent: every tracer then gets the hash of no tags.
131    pub workload_provider: Option<Arc<dyn WorkloadProvider + Send + Sync>>,
132
133    /// Client configuration for the core Agent's IPC API, which reports the Agent version on `/info`.
134    ///
135    /// `None` when ADP runs without the core Agent: `/info` then reports an empty version.
136    pub agent_client: Option<RemoteAgentClientConfiguration>,
137
138    /// Semantic registry the base peer tags on `/info` come from.
139    pub semantic_registry: SemanticRegistryProvider,
140
141    /// URL of Datadog's `/api/v2/validate`, which identifies the organization of the API key for the org propagation
142    /// marker on `/info`.
143    ///
144    /// The request uses the HTTP client settings and the API key of [`tracer_flare`](Self::tracer_flare).
145    pub validate_endpoint: String,
146}
147
148#[static_metrics(prefix = component, labels(component_id, component_type))]
149#[derive(Clone)]
150struct Metrics {
151    /// Requests forwarded to the trace-agent that it answered, whatever the status of its answer.
152    requests_relayed_total: Counter,
153    /// Requests forwarded to the trace-agent that it never answered, such as when it was unreachable.
154    requests_failed_total: Counter,
155    /// Requests the relay handled itself rather than forwarding to the trace-agent, whatever the outcome.
156    requests_served_locally_total: Counter,
157}
158
159impl ApmRelayConfiguration {
160    async fn tcp_listen_address(&self) -> Result<Option<ListenAddress>, GenericError> {
161        if self.receiver_port == 0 {
162            return Ok(None);
163        };
164
165        let listen_address = if self.non_local_traffic {
166            [0, 0, 0, 0].into()
167        } else if let Some(bind_host) = &self.bind_host {
168            resolve_host(bind_host)
169                .await
170                .error_context("Could not resolve bind_host for the APM relay.")?
171        } else {
172            [127, 0, 0, 1].into()
173        };
174
175        Ok(Some(ListenAddress::Tcp(SocketAddr::new(
176            listen_address,
177            self.receiver_port,
178        ))))
179    }
180
181    fn uds_listen_address(&self) -> Result<Option<ListenAddress>, GenericError> {
182        if self.receiver_socket.is_empty() {
183            return Ok(None);
184        }
185
186        ListenAddress::try_from(format!("unix://{}", self.receiver_socket))
187            .map(Some)
188            .map_err(|e| {
189                generic_error!(
190                    "Invalid APM relay Unix domain socket path `{}`: {e}",
191                    self.receiver_socket
192                )
193            })
194    }
195}
196
197impl MemoryBounds for ApmRelayConfiguration {
198    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
199        builder
200            .minimum()
201            .with_single_value::<ApmRelay>("component struct")
202            .with_single_value::<RelayState>("component struct");
203    }
204}
205
206#[async_trait]
207impl RelayBuilder for ApmRelayConfiguration {
208    fn outputs(&self) -> &[OutputDefinition<PayloadType>] {
209        static OUTPUTS: LazyLock<Vec<OutputDefinition<PayloadType>>> =
210            LazyLock::new(|| vec![OutputDefinition::named_output("traces", PayloadType::Http)]);
211        &OUTPUTS
212    }
213
214    async fn build(&self, context: BuildContext) -> Result<Box<dyn Relay + Send>, GenericError> {
215        let tcp_endpoint = self.tcp_listen_address().await?;
216        let uds_endpoint = self.uds_listen_address()?;
217
218        if tcp_endpoint.is_none() && uds_endpoint.is_none() {
219            return Err(generic_error!(
220                "APM relay requires at least one of `apm_config.receiver_port` or `apm_config.receiver_socket` to be configured."
221            ));
222        }
223
224        let proxy = TraceAgentProxy::from_destination(&self.proxy_destination)?;
225        if let Some(listener) = listener_reached_by(proxy.destination(), tcp_endpoint.iter().chain(&uds_endpoint)).await
226        {
227            return Err(generic_error!(
228                "APM proxy destination `{}` is the relay's own listener `{listener}`, so every request would be proxied back to the relay. Set `data_plane.experimental.apm.proxy_destination` to the trace-agent's address.",
229                self.proxy_destination
230            ));
231        }
232
233        let tracer_flare = TracerFlareProxy::from_config(&self.tracer_flare)?;
234        let org_prop_marker = OrgPropagationMarkerFetcher::new(
235            &self.tracer_flare.forwarder,
236            self.validate_endpoint.clone(),
237            tracer_flare.api_key(),
238        )?;
239
240        // Cloned before `/info` takes its first snapshot, so that any update published after it is waited on.
241        let semantic_registry_updates = self.semantic_registry.clone();
242        let info = Info::new(self.info.clone(), self.semantic_registry.clone());
243
244        Ok(Box::new(ApmRelay {
245            tcp_endpoint,
246            uds_endpoint,
247            proxy,
248            tracer_flare,
249            tracer_flare_api_key: self.tracer_flare.api_key.clone(),
250            info,
251            semantic_registry_updates,
252            agent_client: self.agent_client.clone(),
253            org_prop_marker,
254            container_tags: ContainerTagsHasher::new(
255                self.capture_entity_resolver.clone(),
256                self.workload_provider.clone(),
257            ),
258            capture_entity_resolver: self.capture_entity_resolver.clone(),
259            metrics: Metrics::new(context.component_id(), context.component_type().as_category_str()),
260        }))
261    }
262}
263
264/// APM relay.
265///
266/// Receives requests via HTTP, on TCP and/or a Unix domain socket, and proxies them to the trace-agent.
267pub struct ApmRelay {
268    tcp_endpoint: Option<ListenAddress>,
269    uds_endpoint: Option<ListenAddress>,
270    proxy: TraceAgentProxy,
271    tracer_flare: TracerFlareProxy,
272    tracer_flare_api_key: Live<String>,
273    info: Info,
274    semantic_registry_updates: SemanticRegistryProvider,
275    agent_client: Option<RemoteAgentClientConfiguration>,
276    org_prop_marker: OrgPropagationMarkerFetcher,
277    container_tags: ContainerTagsHasher,
278    capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
279    metrics: Metrics,
280}
281
282#[async_trait]
283impl Relay for ApmRelay {
284    async fn run(self: Box<Self>, mut context: RelayContext) -> Result<(), GenericError> {
285        let Self {
286            tcp_endpoint,
287            uds_endpoint,
288            proxy,
289            tracer_flare,
290            mut tracer_flare_api_key,
291            info,
292            mut semantic_registry_updates,
293            agent_client,
294            org_prop_marker,
295            container_tags,
296            capture_entity_resolver,
297            metrics,
298        } = *self;
299
300        let global_shutdown = context.take_shutdown_handle();
301        pin!(global_shutdown);
302
303        let mut health = context.take_health_handle();
304        let worker_pool = context.topology_context().global_thread_pool().clone();
305        let api_handler = ApmRelayAPIHandler::new(RelayState {
306            metrics,
307            proxy,
308            tracer_flare: tracer_flare.clone(),
309            info: info.clone(),
310            container_tags,
311            capture_entity_resolver,
312        });
313        let router = api_handler
314            .generate_routes()
315            .with_state(api_handler.generate_initial_state());
316
317        // The listeners are needed: one that fails to bind, for example because the trace-agent still owns its address,
318        // fails the relay rather than leaving it ready without serving that endpoint.
319        if let Some(endpoint) = tcp_endpoint {
320            debug!(%endpoint, "Binding APM relay TCP listener.");
321            let server = HttpServer::from_listen_address(endpoint)
322                .with_routes(router.clone())
323                .with_worker_pool(worker_pool.clone());
324            runtime::nested_supervisor(server.into_supervisor())
325                .needed()
326                .stops_with_owner()
327                .spawn();
328        }
329        if let Some(endpoint) = uds_endpoint {
330            debug!(%endpoint, "Binding APM relay Unix domain socket listener.");
331            let server = HttpServer::from_listen_address(endpoint)
332                .with_routes(router.clone())
333                .with_worker_pool(worker_pool);
334            runtime::nested_supervisor(server.into_supervisor())
335                .needed()
336                .stops_with_owner()
337                .spawn();
338        }
339
340        health.mark_ready();
341        debug!("APM relay started.");
342
343        // `/info` reports an empty version until the core Agent reports its own.
344        let agent_version = fetch_agent_version_with_retry(agent_client);
345        pin!(agent_version);
346        let mut agent_version_pending = true;
347
348        // As in the trace-agent, the marker is fetched once, with the API key current at each attempt.
349        let org_prop_marker = org_prop_marker.fetch_with_retries(ORG_PROP_MARKER_BASE_RETRY_DELAY);
350        pin!(org_prop_marker);
351        let mut org_prop_marker_pending = true;
352
353        loop {
354            select! {
355                _ = &mut global_shutdown => {
356                    debug!("Received shutdown signal.");
357                    break
358                },
359                _ = health.live() => continue,
360                api_key = tracer_flare_api_key.changed() => tracer_flare.refresh_api_key(&api_key),
361                // Peer tags follow the registry, so tracers must see its updates, unlike the trace-agent's `/info`.
362                _ = semantic_registry_updates.changed() => info.refresh_semantic_registry(),
363                version = &mut agent_version, if agent_version_pending => {
364                    agent_version_pending = false;
365                    if let Some(version) = version {
366                        debug!(version = %version.version, "Fetched the Agent version.");
367                        info.set_agent_version(version);
368                    }
369                },
370                marker = &mut org_prop_marker, if org_prop_marker_pending => {
371                    org_prop_marker_pending = false;
372                    if let Some(marker) = marker {
373                        info.set_org_prop_marker(marker);
374                    }
375                },
376            }
377        }
378
379        debug!("APM relay stopped.");
380
381        Ok(())
382    }
383}
384
385/// Fetches the version of the core Agent, retrying until the Agent answers.
386///
387/// Returns `None` without a client configuration, when ADP runs without the core Agent.
388async fn fetch_agent_version_with_retry(
389    agent_client: Option<RemoteAgentClientConfiguration>,
390) -> Option<RunningAgentVersion> {
391    let agent_client = agent_client?;
392    let fetch = || fetch_agent_version(&agent_client);
393    let version = fetch
394        .retry(
395            ExponentialBuilder::default()
396                .with_min_delay(AGENT_VERSION_MIN_RETRY_DELAY)
397                .with_max_delay(AGENT_VERSION_MAX_RETRY_DELAY)
398                .without_max_times(),
399        )
400        .notify(|error, delay| {
401            warn!(%error, "Failed to fetch the Agent version for `/info`. Retrying in {delay:?}...");
402        })
403        .await;
404    version.ok()
405}
406
407/// Shared HTTP handler state.
408#[derive(Clone)]
409struct RelayState {
410    proxy: TraceAgentProxy,
411    tracer_flare: TracerFlareProxy,
412    info: Info,
413    container_tags: ContainerTagsHasher,
414    capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
415    metrics: Metrics,
416}
417
418struct ApmRelayAPIHandler {
419    state: RelayState,
420}
421
422impl ApmRelayAPIHandler {
423    fn new(state: RelayState) -> Self {
424        Self { state }
425    }
426
427    async fn proxy_request(
428        State(RelayState {
429            proxy,
430            info,
431            capture_entity_resolver,
432            metrics,
433            ..
434        }): State<RelayState>,
435        mut request: AxumRequest,
436    ) -> Response {
437        if let Some(resolver) = capture_entity_resolver.as_deref() {
438            add_peer_container_id(&mut request, resolver);
439        }
440        match proxy.forward(request).await {
441            Ok(mut response) => {
442                metrics.requests_relayed_total().increment(1);
443                info.replace_headers(response.headers_mut());
444                response
445            }
446            Err(error) => {
447                metrics.requests_failed_total().increment(1);
448                error.into_response()
449            }
450        }
451    }
452
453    async fn handle_info(State(RelayState { info, .. }): State<RelayState>) -> Response {
454        info.response()
455    }
456
457    async fn handle_services() -> Response {
458        "OK\n".into_response()
459    }
460
461    async fn handle_tracer_flare(
462        State(RelayState { tracer_flare, .. }): State<RelayState>, request: AxumRequest,
463    ) -> Response {
464        tracer_flare.forward(request).await.into_response()
465    }
466
467    /// Counts a request for an endpoint the relay serves itself.
468    async fn count_served_locally(
469        State(RelayState { metrics, .. }): State<RelayState>, request: AxumRequest, next: Next,
470    ) -> Response {
471        metrics.requests_served_locally_total().increment(1);
472        next.run(request).await
473    }
474
475    /// Sets `Datadog-Agent-State` and `Datadog-Agent-Version` on a response the relay served itself.
476    async fn set_agent_headers(
477        State(RelayState { info, .. }): State<RelayState>, request: AxumRequest, next: Next,
478    ) -> Response {
479        let mut response = next.run(request).await;
480        info.set_headers(response.headers_mut());
481        response
482    }
483
484    /// Sets `Datadog-Container-Tags-Hash` to the hash of the tags of the container of the tracer that sent `request`.
485    async fn add_container_tags_hash(
486        State(RelayState { container_tags, .. }): State<RelayState>, request: AxumRequest, next: Next,
487    ) -> Response {
488        let hash = container_tags.header_value(
489            request.headers(),
490            request.extensions().get::<ConnectInfo<ConnectionAddress>>(),
491        );
492        let mut response = next.run(request).await;
493        response.headers_mut().insert(CONTAINER_TAGS_HASH_HEADER, hash);
494        response
495    }
496}
497
498/// Sets `Datadog-Container-ID` to the container of the tracer that sent `request`, when the tracer is connected over the
499/// Unix domain socket and sent no container headers of its own.
500///
501/// This stands in for the trace-agent's own lookup from the connection's peer credentials, which behind the relay
502/// would find ADP rather than the tracer.
503fn add_peer_container_id(request: &mut AxumRequest, resolver: &(dyn CaptureEntityResolver + Send + Sync)) {
504    let headers = request.headers();
505    if headers.contains_key(CONTAINER_ID_HEADER) || headers.contains_key(ENTITY_ID_HEADER) {
506        return;
507    }
508
509    let Some(process_id) = request
510        .extensions()
511        .get::<ConnectInfo<ConnectionAddress>>()
512        .and_then(|ConnectInfo(addr)| addr.process_credentials())
513        .and_then(|creds| u32::try_from(creds.pid).ok())
514    else {
515        return;
516    };
517
518    match resolver.resolve_container_entity_for_live_pid(process_id) {
519        Some(EntityId::Container(container_id)) => match HeaderValue::from_str(&container_id) {
520            Ok(value) => {
521                request.headers_mut().insert(CONTAINER_ID_HEADER, value);
522            }
523            Err(_) => debug!(process_id, %container_id, "Resolved container ID is not a valid header value."),
524        },
525        Some(entity_id) => debug!(process_id, %entity_id, "Tracer process resolved to a non-container entity."),
526        None => debug!(process_id, "Could not resolve the container of the tracer process."),
527    }
528}
529
530impl APIHandler for ApmRelayAPIHandler {
531    type State = RelayState;
532
533    fn generate_initial_state(&self) -> Self::State {
534        self.state.clone()
535    }
536
537    /// Forwards requests for endpoints not handled here to the trace-agent.
538    ///
539    /// As in the trace-agent, only `/info` carries `Datadog-Container-Tags-Hash`, and every other endpoint served here
540    /// carries `Datadog-Agent-State` and `Datadog-Agent-Version` instead.
541    fn generate_routes(&self) -> Router<Self::State> {
542        let state = &self.state;
543        let with_agent_headers = Router::new()
544            .route("/services", any(Self::handle_services))
545            .route("/v0.1/services", any(Self::handle_services))
546            .route("/v0.2/services", any(Self::handle_services))
547            .route("/v0.3/services", any(Self::handle_services))
548            .route("/v0.4/services", any(Self::handle_services))
549            .route("/tracer_flare/v1", any(Self::handle_tracer_flare))
550            .route_layer(from_fn_with_state(state.clone(), Self::set_agent_headers));
551
552        Router::new()
553            .route(
554                "/info",
555                any(Self::handle_info).layer(from_fn_with_state(state.clone(), Self::add_container_tags_hash)),
556            )
557            .merge(with_agent_headers)
558            .route_layer(from_fn_with_state(state.clone(), Self::count_served_locally))
559            .fallback(Self::proxy_request)
560    }
561}
562
563#[cfg(test)]
564mod tests {
565    use std::net::SocketAddr;
566    use std::sync::OnceLock;
567    use std::time::Duration;
568
569    use bytes::Bytes;
570    use http::{Request, StatusCode};
571    use saluki_core::components::test_util::TestComponentDriver;
572    use saluki_core::runtime::state::{DataspaceUpdate, IdentifierFilter};
573    use saluki_core::runtime::test_util::TestSupervisor;
574    use saluki_io::net::{BoundListenAddress, ProcessCredentials};
575    #[cfg(unix)]
576    use tempfile::tempdir;
577    use tokio::io::{AsyncReadExt, AsyncWriteExt};
578    use tokio::net::TcpStream;
579    #[cfg(unix)]
580    use tokio::net::UnixStream;
581    use tower::service_fn;
582    use tower::ServiceExt;
583
584    use super::proxy::test_proxy;
585    use super::*;
586    use crate::common::datadog::test_util::init_tls;
587
588    /// A proxy whose trace-agent is not listening, so a proxied request is answered `502 Bad Gateway`. That makes
589    /// "was this request proxied?" observable without running a trace-agent.
590    fn unreachable_proxy() -> TraceAgentProxy {
591        test_proxy("http://127.0.0.1:1").expect("destination should parse")
592    }
593
594    fn build_router(state: RelayState) -> Router {
595        let api_handler = ApmRelayAPIHandler::new(state);
596        api_handler
597            .generate_routes()
598            .with_state(api_handler.generate_initial_state())
599    }
600
601    fn test_info() -> Info {
602        Info::new(InfoConfiguration::default(), SemanticRegistryProvider::default())
603    }
604
605    /// A flare proxy whose intake is not listening, so a forwarded flare is answered `502 Bad Gateway`.
606    fn unreachable_tracer_flare() -> TracerFlareProxy {
607        tracer_flare::plain_http_proxy("http://127.0.0.1:1", "test-api-key")
608    }
609
610    fn test_router() -> Router {
611        build_router(RelayState {
612            proxy: unreachable_proxy(),
613            tracer_flare: unreachable_tracer_flare(),
614            info: test_info(),
615            container_tags: ContainerTagsHasher::default(),
616            capture_entity_resolver: None,
617            metrics: Metrics::new("dd_traces_relay", "relays"),
618        })
619    }
620
621    /// Resolves every process to the same container.
622    struct FixedContainerResolver;
623
624    impl CaptureEntityResolver for FixedContainerResolver {
625        fn resolve_container_entity_for_live_pid(&self, _process_id: u32) -> Option<EntityId> {
626            Some(EntityId::Container("tracer-container".into()))
627        }
628    }
629
630    /// Builds a request as the relay's server hands it over: with the address of the peer that sent it.
631    fn request_from(peer: ConnectionAddress, headers: &[(&str, &str)]) -> AxumRequest {
632        let mut builder = Request::builder().method("POST").uri("/v0.4/traces");
633        for (name, value) in headers {
634            builder = builder.header(*name, *value);
635        }
636        let mut request = builder.body(axum::body::Body::empty()).unwrap();
637        request.extensions_mut().insert(ConnectInfo(peer));
638        request
639    }
640
641    fn unix_peer() -> ConnectionAddress {
642        ProcessCredentials {
643            pid: 1234,
644            uid: 0,
645            gid: 0,
646        }
647        .into()
648    }
649
650    #[test]
651    fn sets_the_container_id_of_a_unix_socket_peer() {
652        let mut request = request_from(unix_peer(), &[]);
653
654        add_peer_container_id(&mut request, &FixedContainerResolver);
655
656        assert_eq!(request.headers()[CONTAINER_ID_HEADER], "tracer-container");
657    }
658
659    #[test]
660    fn keeps_the_container_headers_a_tracer_sent() {
661        let mut request = request_from(unix_peer(), &[("Datadog-Container-ID", "from-tracer")]);
662        add_peer_container_id(&mut request, &FixedContainerResolver);
663        assert_eq!(request.headers()[CONTAINER_ID_HEADER], "from-tracer");
664
665        let mut request = request_from(unix_peer(), &[("Datadog-Entity-ID", "in-42")]);
666        add_peer_container_id(&mut request, &FixedContainerResolver);
667        assert!(!request.headers().contains_key(CONTAINER_ID_HEADER));
668    }
669
670    #[test]
671    fn leaves_tcp_requests_alone() {
672        let mut request = request_from(ConnectionAddress::from(SocketAddr::from(([127, 0, 0, 1], 4242))), &[]);
673
674        add_peer_container_id(&mut request, &FixedContainerResolver);
675
676        assert!(!request.headers().contains_key(CONTAINER_ID_HEADER));
677    }
678
679    #[tokio::test]
680    async fn counts_a_request_the_trace_agent_never_received_as_failed() {
681        let recorder = saluki_metrics::test::TestRecorder::default();
682        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
683        let router = test_router();
684
685        let response = router
686            .oneshot(
687                Request::builder()
688                    .uri("/v0.4/traces")
689                    .body(axum::body::Body::empty())
690                    .unwrap(),
691            )
692            .await
693            .unwrap();
694        assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
695
696        let metric_key = |name| {
697            metrics::Key::from_parts(
698                name,
699                vec![
700                    metrics::Label::new("component_id", "dd_traces_relay"),
701                    metrics::Label::new("component_type", "relays"),
702                ],
703            )
704        };
705        assert_eq!(recorder.counter(metric_key("component_requests_failed_total")), Some(1));
706        assert_eq!(
707            recorder.counter(metric_key("component_requests_relayed_total")),
708            Some(0)
709        );
710    }
711
712    #[tokio::test]
713    async fn answers_the_services_endpoints_for_any_method() {
714        let recorder = saluki_metrics::test::TestRecorder::default();
715        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
716        let router = test_router();
717
718        let paths = [
719            "/services",
720            "/v0.1/services",
721            "/v0.2/services",
722            "/v0.3/services",
723            "/v0.4/services",
724        ];
725        let methods = ["GET", "PUT", "POST"];
726        for path in paths {
727            for method in methods {
728                let response = router
729                    .clone()
730                    .oneshot(
731                        Request::builder()
732                            .method(method)
733                            .uri(path)
734                            .body(axum::body::Body::empty())
735                            .unwrap(),
736                    )
737                    .await
738                    .unwrap();
739                assert_eq!(response.status(), StatusCode::OK, "{method} {path}");
740                let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
741                assert_eq!(&body[..], b"OK\n", "{method} {path}");
742            }
743        }
744
745        let metric_key = |name| {
746            metrics::Key::from_parts(
747                name,
748                vec![
749                    metrics::Label::new("component_id", "dd_traces_relay"),
750                    metrics::Label::new("component_type", "relays"),
751                ],
752            )
753        };
754        assert_eq!(
755            recorder.counter(metric_key("component_requests_served_locally_total")),
756            Some((paths.len() * methods.len()) as u64)
757        );
758        assert_eq!(
759            recorder.counter(metric_key("component_requests_relayed_total")),
760            Some(0)
761        );
762        assert_eq!(recorder.counter(metric_key("component_requests_failed_total")), Some(0));
763    }
764
765    #[tokio::test]
766    async fn proxies_requests_to_the_trace_agent() {
767        let router = test_router();
768
769        let response = router
770            .oneshot(
771                Request::builder()
772                    .method("POST")
773                    .uri("/not-a-real-path")
774                    .body(axum::body::Body::empty())
775                    .unwrap(),
776            )
777            .await
778            .unwrap();
779
780        assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
781    }
782
783    /// Starts a trace-agent that answers `/v0.4/traces` with its own `Datadog-Agent-State` and
784    /// `Datadog-Agent-Version`, and any other path with a bare `404 Not Found`.
785    async fn spawn_trace_agent_with_state() -> TraceAgentProxy {
786        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
787            .await
788            .expect("should bind an ephemeral port");
789        let addr = listener.local_addr().expect("listener should have a local address");
790        let router = Router::new().route(
791            "/v0.4/traces",
792            any(|| async {
793                (
794                    [
795                        (info::AGENT_STATE_HEADER, "trace-agent-hash"),
796                        (info::AGENT_VERSION_HEADER, "7.0.0"),
797                    ],
798                    "OK",
799                )
800            }),
801        );
802        tokio::spawn(async move { axum::serve(listener, router).await });
803        test_proxy(&format!("http://{addr}")).expect("destination should parse")
804    }
805
806    async fn send(router: &Router, method: &str, path: &str) -> axum::response::Response {
807        router
808            .clone()
809            .oneshot(
810                Request::builder()
811                    .method(method)
812                    .uri(path)
813                    .body(axum::body::Body::empty())
814                    .unwrap(),
815            )
816            .await
817            .unwrap()
818    }
819
820    #[tokio::test]
821    async fn serves_info_itself_and_owns_the_agent_state_of_every_response() {
822        let recorder = saluki_metrics::test::TestRecorder::default();
823        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
824        let info = test_info();
825        let router = build_router(RelayState {
826            proxy: spawn_trace_agent_with_state().await,
827            tracer_flare: unreachable_tracer_flare(),
828            info: info.clone(),
829            container_tags: ContainerTagsHasher::default(),
830            capture_entity_resolver: None,
831            metrics: Metrics::new("dd_traces_relay", "relays"),
832        });
833
834        // `/info` answers any method, without the state header, as in the trace-agent.
835        let mut body = Bytes::new();
836        for method in ["GET", "POST"] {
837            let response = send(&router, method, "/info").await;
838            assert_eq!(response.status(), StatusCode::OK, "{method}");
839            assert_eq!(
840                response.headers()[http::header::CONTENT_TYPE],
841                "text/plain; charset=utf-8"
842            );
843            assert!(!response.headers().contains_key(info::AGENT_STATE_HEADER));
844            // Without a workload provider, the tracer's container has no tags.
845            assert_eq!(
846                response.headers()[CONTAINER_TAGS_HASH_HEADER],
847                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
848            );
849            body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
850        }
851        let state = faster_hex::hex_string(&<sha2::Sha256 as sha2::Digest>::digest(&body));
852
853        // A proxied response carries the hash of the relay's `/info` body rather than the trace-agent's.
854        let response = send(&router, "POST", "/v0.4/traces").await;
855        assert_eq!(response.status(), StatusCode::OK);
856        assert_eq!(response.headers()[info::AGENT_STATE_HEADER], state.as_str());
857        assert_eq!(response.headers()[info::AGENT_VERSION_HEADER], "");
858
859        // A response the trace-agent sent without them stays without them.
860        let response = send(&router, "GET", "/not-a-real-path").await;
861        assert_eq!(response.status(), StatusCode::NOT_FOUND);
862        assert!(!response.headers().contains_key(info::AGENT_STATE_HEADER));
863
864        // An endpoint the relay serves itself carries them too, but only `/info` carries the container tags hash.
865        let response = send(&router, "PUT", "/v0.4/services").await;
866        assert_eq!(response.headers()[info::AGENT_STATE_HEADER], state.as_str());
867        assert!(!response.headers().contains_key(CONTAINER_TAGS_HASH_HEADER));
868
869        // Once the Agent version is known, the payload and the headers follow it.
870        info.set_agent_version(RunningAgentVersion {
871            version: "7.81.0".to_string(),
872            commit: "abc1234".to_string(),
873        });
874        let response = send(&router, "POST", "/v0.4/traces").await;
875        assert_eq!(response.headers()[info::AGENT_VERSION_HEADER], "7.81.0");
876        assert_ne!(response.headers()[info::AGENT_STATE_HEADER], state.as_str());
877        let body = axum::body::to_bytes(send(&router, "GET", "/info").await.into_body(), usize::MAX)
878            .await
879            .unwrap();
880        let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
881        assert_eq!(payload["version"], "7.81.0");
882
883        let metric_key = |name| {
884            metrics::Key::from_parts(
885                name,
886                vec![
887                    metrics::Label::new("component_id", "dd_traces_relay"),
888                    metrics::Label::new("component_type", "relays"),
889                ],
890            )
891        };
892        assert_eq!(
893            recorder.counter(metric_key("component_requests_served_locally_total")),
894            Some(4)
895        );
896        assert_eq!(
897            recorder.counter(metric_key("component_requests_relayed_total")),
898            Some(3)
899        );
900    }
901
902    #[tokio::test]
903    async fn forwards_tracer_flares_to_datadog_rather_than_the_trace_agent() {
904        let recorder = saluki_metrics::test::TestRecorder::default();
905        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
906        let router = test_router();
907
908        for method in ["POST", "GET"] {
909            let response = router
910                .clone()
911                .oneshot(
912                    Request::builder()
913                        .method(method)
914                        .uri("/tracer_flare/v1")
915                        .body(axum::body::Body::empty())
916                        .unwrap(),
917                )
918                .await
919                .unwrap();
920            assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
921        }
922
923        let metric_key = |name| {
924            metrics::Key::from_parts(
925                name,
926                vec![
927                    metrics::Label::new("component_id", "dd_traces_relay"),
928                    metrics::Label::new("component_type", "relays"),
929                ],
930            )
931        };
932        assert_eq!(
933            recorder.counter(metric_key("component_requests_served_locally_total")),
934            Some(2)
935        );
936        assert_eq!(recorder.counter(metric_key("component_requests_failed_total")), Some(0));
937        assert_eq!(
938            recorder.counter(metric_key("component_requests_relayed_total")),
939            Some(0)
940        );
941    }
942
943    #[tokio::test]
944    async fn binds_and_serves_over_tcp() {
945        const BOUND_ADDRESS_ID: &str = "apm-relay-tcp-test-bound-address";
946
947        let supervisor = TestSupervisor::start("apm-relay-tcp-test").await;
948
949        // Bind to an OS-assigned ephemeral port, and discover it via the published `BoundListenAddress`.
950        let tcp_endpoint = ListenAddress::try_from("tcp://127.0.0.1:0").expect("TCP APM endpoint should parse");
951
952        let router = test_router();
953        let server = HttpServer::from_listen_address(tcp_endpoint)
954            .with_routes(router)
955            .with_server_id(BOUND_ADDRESS_ID)
956            .with_worker_pool(tokio::runtime::Handle::current());
957
958        let mut bound_address_subscription = supervisor
959            .dataspace()
960            .subscribe::<BoundListenAddress>(IdentifierFilter::exact(format!("http-server-{BOUND_ADDRESS_ID}")));
961
962        supervisor
963            .scope(async {
964                runtime::nested_supervisor(server.into_supervisor()).spawn();
965            })
966            .await;
967
968        let bound_addr = match tokio::time::timeout(Duration::from_secs(5), bound_address_subscription.recv()).await {
969            Ok(Some(DataspaceUpdate::Asserted(_, BoundListenAddress::Tcp(address)))) => address,
970            update => panic!("expected a bound address assertion for `{BOUND_ADDRESS_ID}`, got {update:?}"),
971        };
972
973        let mut stream = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(bound_addr))
974            .await
975            .expect("should connect to TCP listener within the timeout")
976            .expect("should connect to TCP listener");
977
978        let body = b"proxied request over tcp";
979        let request = format!(
980            "POST /v0.4/traces HTTP/1.1\r\nHost: localhost\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
981            body.len()
982        );
983        stream
984            .write_all(request.as_bytes())
985            .await
986            .expect("should write request head");
987        stream.write_all(body).await.expect("should write request body");
988
989        let mut response = Vec::new();
990        tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut response))
991            .await
992            .expect("server should respond over TCP")
993            .expect("should read response");
994
995        assert!(
996            response.starts_with(b"HTTP/1.1 502"),
997            "expected a 502 Bad Gateway response, got: {}",
998            String::from_utf8_lossy(&response)
999        );
1000    }
1001
1002    #[tokio::test]
1003    async fn answers_a_request_proxied_back_to_itself_with_loop_detected() {
1004        const BOUND_ADDRESS_ID: &str = "apm-relay-loop-test-bound-address";
1005
1006        let supervisor = TestSupervisor::start("apm-relay-loop-test").await;
1007
1008        // The relay's destination has to be its own listener, whose port is only known once it's bound. So the server
1009        // is given a pass-through to the relay router, which is built once the listener is bound. The relay is served
1010        // directly rather than built, as building rejects this configuration.
1011        let relay_router = Arc::new(OnceLock::<Router>::new());
1012        let pass_through = Router::new().fallback_service(service_fn({
1013            let relay_router = Arc::clone(&relay_router);
1014            move |request: AxumRequest| {
1015                let relay_router = relay_router
1016                    .get()
1017                    .cloned()
1018                    .expect("the relay router should be set before any request arrives");
1019                relay_router.oneshot(request)
1020            }
1021        }));
1022        let server = HttpServer::from_listen_address(ListenAddress::tcp_loopback(0))
1023            .with_routes(pass_through)
1024            .with_server_id(BOUND_ADDRESS_ID)
1025            .with_worker_pool(tokio::runtime::Handle::current());
1026
1027        let mut bound_address_subscription = supervisor
1028            .dataspace()
1029            .subscribe::<BoundListenAddress>(IdentifierFilter::exact(format!("http-server-{BOUND_ADDRESS_ID}")));
1030
1031        supervisor
1032            .scope(async {
1033                runtime::nested_supervisor(server.into_supervisor()).spawn();
1034            })
1035            .await;
1036
1037        let bound_addr = match tokio::time::timeout(Duration::from_secs(5), bound_address_subscription.recv()).await {
1038            Ok(Some(DataspaceUpdate::Asserted(_, BoundListenAddress::Tcp(address)))) => address,
1039            update => panic!("expected a bound address assertion for `{BOUND_ADDRESS_ID}`, got {update:?}"),
1040        };
1041
1042        relay_router
1043            .set(build_router(RelayState {
1044                proxy: test_proxy(&format!("http://{bound_addr}")).expect("destination should parse"),
1045                tracer_flare: unreachable_tracer_flare(),
1046                info: test_info(),
1047                container_tags: ContainerTagsHasher::default(),
1048                capture_entity_resolver: None,
1049                metrics: Metrics::new("dd_traces_relay", "relays"),
1050            }))
1051            .expect("the relay router should be set only once");
1052
1053        let mut stream = TcpStream::connect(bound_addr)
1054            .await
1055            .expect("should connect to TCP listener");
1056        stream
1057            .write_all(b"GET /v0.4/traces HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
1058            .await
1059            .expect("should write request");
1060
1061        let mut response = Vec::new();
1062        tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut response))
1063            .await
1064            .expect("the relay should answer rather than proxy the request to itself forever")
1065            .expect("should read response");
1066
1067        assert!(
1068            response.starts_with(b"HTTP/1.1 508"),
1069            "expected a 508 Loop Detected response, got: {}",
1070            String::from_utf8_lossy(&response)
1071        );
1072    }
1073
1074    #[cfg(unix)]
1075    #[tokio::test]
1076    async fn binds_and_serves_over_unix_domain_socket() {
1077        const BOUND_ADDRESS_ID: &str = "apm-relay-uds-test-bound-address";
1078
1079        let supervisor = TestSupervisor::start("apm-relay-uds-test").await;
1080
1081        let dir = tempdir().expect("temp dir should be created");
1082        let socket_path = dir.path().join("apm.sock");
1083        let uds_endpoint = ListenAddress::try_from(format!("unix://{}", socket_path.display()).as_str())
1084            .expect("Unix APM endpoint should parse");
1085
1086        let router = test_router();
1087        let server = HttpServer::from_listen_address(uds_endpoint)
1088            .with_routes(router)
1089            .with_server_id(BOUND_ADDRESS_ID)
1090            .with_worker_pool(tokio::runtime::Handle::current());
1091
1092        // The bound address is published once the listener accepts connections.
1093        let mut bound_address_subscription = supervisor
1094            .dataspace()
1095            .subscribe::<BoundListenAddress>(IdentifierFilter::exact(format!("http-server-{BOUND_ADDRESS_ID}")));
1096
1097        supervisor
1098            .scope(async {
1099                runtime::nested_supervisor(server.into_supervisor()).spawn();
1100            })
1101            .await;
1102
1103        let bound_path = match tokio::time::timeout(Duration::from_secs(5), bound_address_subscription.recv()).await {
1104            Ok(Some(DataspaceUpdate::Asserted(_, BoundListenAddress::Unix(path)))) => path,
1105            update => panic!("expected a bound address assertion for `{BOUND_ADDRESS_ID}`, got {update:?}"),
1106        };
1107        assert_eq!(bound_path, socket_path);
1108
1109        let mut stream = UnixStream::connect(&socket_path)
1110            .await
1111            .expect("should connect to Unix domain socket");
1112
1113        let body = b"proxied request over uds";
1114        let request = format!(
1115            "POST /v0.4/traces HTTP/1.1\r\nHost: localhost\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1116            body.len()
1117        );
1118        stream
1119            .write_all(request.as_bytes())
1120            .await
1121            .expect("should write request head");
1122        stream.write_all(body).await.expect("should write request body");
1123
1124        let mut response = Vec::new();
1125        tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut response))
1126            .await
1127            .expect("server should respond over the Unix domain socket")
1128            .expect("should read response");
1129
1130        assert!(
1131            response.starts_with(b"HTTP/1.1 502"),
1132            "expected a 502 Bad Gateway response, got: {}",
1133            String::from_utf8_lossy(&response)
1134        );
1135    }
1136
1137    fn test_config(bind_host: Option<&str>, non_local_traffic: bool, receiver_port: u16) -> ApmRelayConfiguration {
1138        init_tls();
1139        ApmRelayConfiguration {
1140            receiver_socket: String::new(),
1141            proxy_destination: "http://127.0.0.1:8127".to_string(),
1142            capture_entity_resolver: None,
1143            bind_host: bind_host.map(str::to_string),
1144            non_local_traffic,
1145            receiver_port,
1146            tracer_flare: TracerFlareConfiguration {
1147                site: "datadoghq.com".to_string(),
1148                api_key: Live::new_fixed("test-api-key".to_string()),
1149                forwarder: crate::common::datadog::test_util::forwarder_configuration(),
1150            },
1151            info: InfoConfiguration::default(),
1152            workload_provider: None,
1153            agent_client: None,
1154            semantic_registry: SemanticRegistryProvider::default(),
1155            validate_endpoint: "http://127.0.0.1:1/api/v2/validate".to_string(),
1156        }
1157    }
1158
1159    #[tokio::test]
1160    async fn a_listener_that_fails_to_bind_fails_the_relay() {
1161        // Like a trace-agent that still owns the receiver port.
1162        let occupied = std::net::TcpListener::bind("127.0.0.1:0").expect("should bind an ephemeral port");
1163        let port = occupied.local_addr().expect("should have a local address").port();
1164
1165        let (control, _outputs) = TestComponentDriver::relay(test_config(None, false, port))
1166            .await
1167            .expect("the relay should build");
1168
1169        let result = control.wait().await;
1170        assert!(result.is_err(), "the relay should fail when its listener can't bind");
1171    }
1172
1173    async fn build_error(config: ApmRelayConfiguration) -> GenericError {
1174        match config.build(BuildContext::test_relay("apm_relay_build_error")).await {
1175            Ok(_) => panic!("build should fail"),
1176            Err(error) => error,
1177        }
1178    }
1179
1180    #[tokio::test]
1181    async fn build_fails_when_the_destination_is_the_tcp_listener() {
1182        // The trace-agent's default port used for both the relay and its destination.
1183        let config = test_config(None, false, 8127);
1184        assert!(build_error(config).await.to_string().contains("relay's own listener"));
1185
1186        // A listener on every interface is also reached through the loopback address.
1187        let config = test_config(None, true, 8127);
1188        assert!(build_error(config).await.to_string().contains("relay's own listener"));
1189
1190        let mut config = test_config(None, false, 8127);
1191        config.proxy_destination = "http://localhost:8127".to_string();
1192        assert!(build_error(config).await.to_string().contains("relay's own listener"));
1193    }
1194
1195    #[cfg(unix)]
1196    #[tokio::test]
1197    async fn build_fails_when_the_destination_is_the_unix_domain_socket_listener() {
1198        let mut config = test_config(None, false, 0);
1199        config.receiver_socket = "/var/run/datadog/apm.socket".to_string();
1200        config.proxy_destination = "unix:///var/run/datadog/apm.socket".to_string();
1201
1202        assert!(build_error(config).await.to_string().contains("relay's own listener"));
1203    }
1204
1205    #[tokio::test]
1206    async fn build_fails_without_any_configured_endpoint() {
1207        // Listening nowhere is a configuration error, not a silent no-op: `build` must reject it.
1208        let config = test_config(None, false, 0);
1209
1210        let error = match config.build(BuildContext::test_relay("apm_relay_no_endpoints")).await {
1211            Ok(_) => panic!("build should fail when no endpoint is configured"),
1212            Err(error) => error,
1213        };
1214        assert!(error.to_string().contains("at least one"));
1215    }
1216
1217    #[tokio::test]
1218    async fn build_succeeds_with_only_tcp_endpoint_configured() {
1219        let config = test_config(None, true, 8126);
1220
1221        assert!(config
1222            .build(BuildContext::test_relay("apm_relay_tcp_only"))
1223            .await
1224            .is_ok());
1225    }
1226
1227    #[tokio::test]
1228    async fn build_fails_with_invalid_proxy_destination() {
1229        let mut config = test_config(None, false, 8126);
1230        config.proxy_destination = "ftp://127.0.0.1:8127".to_string();
1231
1232        assert!(config
1233            .build(BuildContext::test_relay("apm_relay_bad_destination"))
1234            .await
1235            .is_err());
1236    }
1237
1238    #[tokio::test]
1239    async fn build_fails_with_unresolvable_bind_host() {
1240        let config = test_config(Some("not a valid host"), false, 8126);
1241
1242        let error = match config
1243            .build(BuildContext::test_relay("apm_relay_unresolvable_bind_host"))
1244            .await
1245        {
1246            Ok(_) => panic!("build should fail for an unresolvable bind host"),
1247            Err(error) => error,
1248        };
1249        assert!(error.to_string().contains("Could not resolve bind_host"));
1250    }
1251
1252    #[tokio::test]
1253    async fn tcp_listen_address_defaults_to_loopback() {
1254        let config = test_config(None, false, 8127);
1255        assert_eq!(
1256            config.tcp_listen_address().await.unwrap().unwrap().to_string(),
1257            "tcp://127.0.0.1:8127"
1258        );
1259    }
1260
1261    #[tokio::test]
1262    async fn tcp_listen_address_uses_bind_host() {
1263        let config = test_config(Some("192.168.1.50"), false, 8127);
1264        assert_eq!(
1265            config.tcp_listen_address().await.unwrap().unwrap().to_string(),
1266            "tcp://192.168.1.50:8127"
1267        );
1268    }
1269
1270    #[tokio::test]
1271    async fn tcp_listen_address_non_local_traffic_overrides_bind_host() {
1272        let config = test_config(Some("192.168.1.50"), true, 8127);
1273        assert_eq!(
1274            config.tcp_listen_address().await.unwrap().unwrap().to_string(),
1275            "tcp://0.0.0.0:8127"
1276        );
1277    }
1278
1279    #[cfg(unix)]
1280    #[test]
1281    fn uds_listen_address_parses_path() {
1282        let mut config = test_config(None, false, 0);
1283        config.receiver_socket = "/tmp/apm.sock".to_string();
1284        assert_eq!(
1285            config.uds_listen_address().unwrap().unwrap().to_string(),
1286            "unix:///tmp/apm.sock"
1287        );
1288    }
1289}