Skip to main content

saluki_components/common/datadog/
endpoints.rs

1use std::{
2    collections::{HashMap, HashSet},
3    fmt,
4    str::FromStr,
5    sync::LazyLock,
6};
7
8use http::uri::Authority;
9use regex::Regex;
10use saluki_error::{ErrorContext as _, GenericError};
11use saluki_metadata;
12use snafu::{ResultExt, Snafu};
13use stringtheory::MetaString;
14use tracing::{debug, error};
15use url::Url;
16
17use super::api_key::ApiKeyCell;
18use super::protocol::{MetricsPayloadInfo, MetricsProtocolVersion, UseV3ApiSeriesConfig, V3SeriesMode};
19use super::routing::RoutingTargetId;
20
21/// The official Datadog sites with no subdomain, such as `datadoghq.com`, as a regex alternation.
22const DD_SITE_PATTERN: &str = r"datad(?:oghq|0g)\.(?:com|eu)|ddog-gov\.com";
23
24/// An optional region prefix, such as `us3.`.
25const DD_REGION_PATTERN: &str = r"(?:[a-z]{2,}\d{1,2}\.)?";
26
27/// An official Datadog application host, such as `app.datadoghq.com` or `app.us5.datadoghq.com`.
28static DD_URL_REGEX: LazyLock<Regex> =
29    LazyLock::new(|| Regex::new(&format!(r"^app(\.mrf)?\.{DD_REGION_PATTERN}({DD_SITE_PATTERN})$")).unwrap());
30
31/// An official Datadog site with no subdomain, such as `datadoghq.com`.
32static DD_SITE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(&format!("^({DD_SITE_PATTERN})$")).unwrap());
33
34/// An official Datadog site, with its optional region and Multi-Region Failover label, such as `us5.datadoghq.com`.
35static DD_AGENT_SITE_REGEX: LazyLock<Regex> =
36    LazyLock::new(|| Regex::new(&format!(r"^(?:mrf\.)?{DD_REGION_PATTERN}(?:{DD_SITE_PATTERN})$")).unwrap());
37
38/// The site suffix of a configured or resolved endpoint, including its region.
39static DD_SITE_SUFFIX_REGEX: LazyLock<Regex> =
40    LazyLock::new(|| Regex::new(&format!(r"(?:^|\.)(?P<site>{DD_REGION_PATTERN}(?:{DD_SITE_PATTERN}))$")).unwrap());
41
42/// Per-endpoint V3 protocol settings.
43///
44/// These settings control which protocol versions an endpoint will accept for metrics payloads.
45/// Settings are derived from a global `V3ApiConfig` by matching the endpoint URL against the
46/// configured V3 endpoint lists.
47#[derive(Clone, Debug, Default)]
48pub struct EndpointV3Settings {
49    /// Whether this endpoint accepts V3 series payloads.
50    pub use_v3_series: bool,
51
52    /// Whether this endpoint accepts V3 sketches payloads.
53    pub use_v3_sketches: bool,
54}
55
56/// Inputs used to derive V3 settings for one endpoint.
57pub(crate) struct V3EndpointConfig<'a> {
58    /// Endpoint string as it appeared in configuration for this routed endpoint.
59    pub(crate) configured_endpoint: &'a str,
60    /// Agent-compatible V3 series config.
61    pub(crate) series_config: &'a UseV3ApiSeriesConfig,
62    /// OPW/Vector route-specific V3 override.
63    pub(crate) metrics_primary_v3_override: Option<bool>,
64    /// Serializer V3 sketches endpoint list.
65    pub(crate) serializer_v3_sketches_endpoints: &'a [String],
66}
67
68impl EndpointV3Settings {
69    /// Returns endpoint settings with all V3 routing disabled.
70    pub const fn disabled() -> Self {
71        Self {
72            use_v3_series: false,
73            use_v3_sketches: false,
74        }
75    }
76
77    /// Creates V3 settings using Agent-compatible series V3 configuration.
78    pub fn from_v3_config(config: V3EndpointConfig<'_>) -> Self {
79        let use_v3_series = if let Some(metrics_primary_use_v3) = config.metrics_primary_v3_override {
80            metrics_primary_use_v3
81        } else if let Some(endpoint_mode) = config.series_config.endpoints.get(config.configured_endpoint) {
82            evaluate_series_v3_mode(*endpoint_mode, config.configured_endpoint)
83        } else {
84            evaluate_series_v3_mode(config.series_config.enabled, config.configured_endpoint)
85        };
86
87        let use_v3_sketches = config
88            .serializer_v3_sketches_endpoints
89            .iter()
90            .any(|e| config.configured_endpoint == e);
91
92        Self {
93            use_v3_series,
94            use_v3_sketches,
95        }
96    }
97
98    /// Determines if this endpoint should receive a payload with the given payload info.
99    ///
100    /// Returns `true` if the endpoint should receive the payload, `false` otherwise.
101    ///
102    /// The logic is:
103    /// - V2 series payload: accept if series V3 is disabled
104    /// - V2 sketches payload: accept if sketches V3 is disabled
105    /// - V3 series payload: accept if series V3 is enabled
106    /// - V3 sketches payload: accept if sketches V3 is enabled
107    /// - Non-metrics payloads (None): always accept
108    pub fn should_receive_payload(&self, payload_info: Option<MetricsPayloadInfo>) -> bool {
109        let Some(info) = payload_info else {
110            // No payload info - this is a non-metrics payload or legacy payload, always accept.
111            return true;
112        };
113
114        let is_sketch = info.is_sketch();
115
116        match info.version {
117            MetricsProtocolVersion::V2 => {
118                if is_sketch {
119                    // V2 sketches: accept if V3 sketches is disabled.
120                    !self.use_v3_sketches
121                } else {
122                    // V2 series: accept if V3 series is disabled.
123                    !self.use_v3_series
124                }
125            }
126
127            MetricsProtocolVersion::V3 => {
128                if is_sketch {
129                    // V3 sketches: accept if V3 sketches is enabled.
130                    self.use_v3_sketches
131                } else {
132                    // V3 series: accept if V3 series is enabled.
133                    self.use_v3_series
134                }
135            }
136        }
137    }
138}
139
140fn configured_endpoint_is_datadog_url(configured_endpoint: &str) -> bool {
141    Url::parse(configured_endpoint.trim()).is_ok_and(|url| is_datadog_url(&url))
142}
143
144/// Resolves a V3 series mode against the endpoint it applies to.
145///
146/// Only `datadog_only` depends on the endpoint, which is why the mode cannot be reduced to a boolean
147/// when it is read.
148pub(crate) fn evaluate_series_v3_mode(mode: V3SeriesMode, configured_endpoint: &str) -> bool {
149    match mode {
150        V3SeriesMode::Enabled => true,
151        V3SeriesMode::Disabled => false,
152        V3SeriesMode::DatadogOnly => configured_endpoint_is_datadog_url(configured_endpoint),
153    }
154}
155
156pub(crate) fn series_v3_config_can_enable_v3(series_config: &UseV3ApiSeriesConfig) -> bool {
157    if series_config
158        .endpoints
159        .iter()
160        .any(|(endpoint, mode)| evaluate_series_v3_mode(*mode, endpoint))
161    {
162        return true;
163    }
164
165    match series_config.enabled {
166        V3SeriesMode::Enabled | V3SeriesMode::DatadogOnly => true,
167        V3SeriesMode::Disabled => false,
168    }
169}
170
171/// Returns `true` if `host` is an official Datadog application host, such as `app.datadoghq.com`,
172/// `app.us5.datadoghq.com`, or the Multi-Region Failover host `app.mrf.datadoghq.com`.
173///
174/// The match ignores case and a trailing dot.
175pub(crate) fn is_datadog_host(host: &str) -> bool {
176    host_matches(&DD_URL_REGEX, host)
177}
178
179/// Returns `true` if `host` is an official Datadog site with no subdomain, such as `datadoghq.com` or `ddog-gov.com`.
180///
181/// The match ignores case and a trailing dot.
182pub(crate) fn is_datadog_site(host: &str) -> bool {
183    host_matches(&DD_SITE_REGEX, host)
184}
185
186fn host_matches(regex: &Regex, host: &str) -> bool {
187    let host = host.trim_end_matches('.');
188    if host.bytes().any(|byte| byte.is_ascii_uppercase()) {
189        regex.is_match(&host.to_ascii_lowercase())
190    } else {
191        regex.is_match(host)
192    }
193}
194
195pub(crate) fn is_datadog_url(url: &Url) -> bool {
196    url.host_str().is_some_and(is_datadog_host)
197}
198
199/// Extracts the Datadog site from configured or version-prefixed endpoint URLs.
200pub(crate) fn extract_datadog_site(url: &Url) -> Option<String> {
201    let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase();
202    DD_SITE_SUFFIX_REGEX
203        .captures(&host)?
204        .name("site")
205        .map(|site| site.as_str().to_owned())
206}
207
208/// Error type for invalid endpoints.
209#[derive(Debug, Snafu)]
210#[snafu(context(suffix(false)))]
211pub(crate) enum EndpointError {
212    Parse {
213        source: url::ParseError,
214        endpoint: String,
215    },
216
217    #[snafu(display("API key contains characters that are invalid in HTTP headers."))]
218    InvalidApiKey,
219}
220
221/// Returns the resolved endpoints for each configured additional endpoint and API key.
222///
223/// This generates a [`ResolvedEndpoint`] for each unique endpoint/API key pair, assigning each
224/// endpoint an `api_key_index` equal to the position of its key in the configured key list for that
225/// URL (the `enumerate()` index, not a post-dedup counter). Empty and duplicate keys are skipped;
226/// their positions are consumed but no endpoint is created.
227///
228/// # Errors
229///
230/// Returns an error if an endpoint URL is invalid.
231pub(crate) fn resolve_additional_endpoints(
232    additional_endpoints: &HashMap<String, Vec<String>>,
233) -> Result<Vec<ResolvedEndpoint>, EndpointError> {
234    let mut resolved = Vec::new();
235
236    for (raw_endpoint, api_keys) in additional_endpoints {
237        let endpoint = parse_and_normalize_endpoint(raw_endpoint)?;
238        let logs_authority = compute_logs_authority(&endpoint);
239        let traces_authority = compute_traces_authority(&endpoint);
240
241        // Create a resolved endpoint for each unique, non-empty key. The index is the configured
242        // position in the key list so that live lookups can use `vec[index]` directly.
243        let mut seen = HashSet::new();
244        for (index, api_key) in api_keys.iter().enumerate() {
245            let trimmed_api_key = api_key.trim();
246            if trimmed_api_key.is_empty() || seen.contains(trimmed_api_key) {
247                continue;
248            }
249
250            seen.insert(trimmed_api_key);
251            let api_key = match ApiKeyCell::new(trimmed_api_key) {
252                Ok(api_key) => api_key,
253                Err(_) => {
254                    error!(
255                        config_key = "additional_endpoints",
256                        endpoint = raw_endpoint,
257                        api_key_index = index,
258                        "Skipping API key because it cannot be used as an HTTP header value."
259                    );
260                    continue;
261                }
262            };
263            resolved.push(ResolvedEndpoint {
264                endpoint: endpoint.clone(),
265                configured_endpoint: raw_endpoint.to_string(),
266                api_key,
267                api_key_index: Some(index),
268                raw_additional_url: Some(raw_endpoint.to_string()),
269                logs_authority: logs_authority.clone(),
270                traces_authority: traces_authority.clone(),
271            });
272        }
273    }
274
275    Ok(resolved)
276}
277
278/// A single destination that replaces every configured Datadog intake endpoint.
279///
280/// Multi-Region Failover and the Cluster Agent each send to one destination that the operator did
281/// not configure as a Datadog intake, so the configured primary endpoint, additional endpoints, and
282/// OPW/Vector metrics override do not apply to them.
283#[derive(Clone)]
284#[cfg_attr(test, derive(Debug, PartialEq))]
285pub(crate) struct SingleDestination {
286    /// Endpoint URL, used as provided.
287    pub(crate) url: String,
288
289    /// API key or token presented to the destination.
290    pub(crate) api_key: String,
291
292    /// Whether the destination accepts V3 series payloads.
293    pub(crate) accepts_v3_series: bool,
294}
295
296/// Endpoint configuration for sending payloads to the Datadog platform.
297///
298/// `Debug` includes endpoint URLs but omits API keys.
299#[derive(Clone, PartialEq)]
300pub struct EndpointConfiguration {
301    /// The API key to use.
302    api_key: String,
303
304    /// The primary endpoint to send payloads to, as configured and not altered in any way.
305    primary_endpoint: String,
306
307    /// Additional endpoints to dual-ship to, keyed by endpoint URL with their API keys.
308    additional_endpoints: HashMap<String, Vec<String>>,
309
310    /// Whether payloads skip the primary endpoint and go only to the additional endpoints.
311    skip_primary: bool,
312}
313
314impl EndpointConfiguration {
315    /// Creates a new `EndpointConfiguration`.
316    ///
317    /// `primary_endpoint` is the effective endpoint, already chosen by the caller. It is normalized when the endpoint
318    /// is built.
319    pub fn new(api_key: String, primary_endpoint: String, additional_endpoints: HashMap<String, Vec<String>>) -> Self {
320        Self {
321            api_key,
322            primary_endpoint,
323            additional_endpoints,
324            skip_primary: false,
325        }
326    }
327
328    /// Sends payloads only to the additional endpoints, skipping the primary endpoint.
329    ///
330    /// The caller is responsible for configuring at least one additional endpoint, or nothing is sent.
331    pub fn without_primary(mut self) -> Self {
332        self.skip_primary = true;
333        self
334    }
335
336    /// Returns whether payloads go to the primary endpoint.
337    pub(crate) const fn sends_to_primary(&self) -> bool {
338        !self.skip_primary
339    }
340
341    /// Creates a new `EndpointConfiguration` that targets a single destination.
342    ///
343    /// The destination is the only endpoint: dual shipping does not apply to it.
344    pub(crate) fn for_single_destination(destination: &SingleDestination) -> Self {
345        Self {
346            api_key: destination.api_key.clone(),
347            primary_endpoint: destination.url.clone(),
348            additional_endpoints: HashMap::new(),
349            skip_primary: false,
350        }
351    }
352
353    /// Builds the resolved primary endpoint.
354    ///
355    /// # Errors
356    ///
357    /// If the primary endpoint isn't a valid URL, or a valid URL couldn't be constructed after applying the
358    /// necessary normalization / modifications to the endpoint, an error will be returned.
359    pub(crate) fn build_primary_endpoint(&self) -> Result<ResolvedEndpoint, GenericError> {
360        ResolvedEndpoint::from_raw_endpoint(&self.primary_endpoint, &self.api_key)
361            .error_context("Failed parsing/resolving the primary destination endpoint.")
362    }
363
364    /// Builds the resolved primary endpoint from a URL override.
365    pub(crate) fn build_primary_endpoint_override(&self, url: &str) -> Result<ResolvedEndpoint, EndpointError> {
366        ResolvedEndpoint::from_raw_endpoint(url, &self.api_key)
367    }
368
369    /// Builds the resolved additional endpoints.
370    ///
371    /// # Errors
372    ///
373    /// If any additional endpoint isn't a valid URL, or a valid URL couldn't be constructed after applying the
374    /// necessary normalization / modifications to a particular endpoint, an error will be returned.
375    pub(crate) fn build_additional_endpoints(&self) -> Result<Vec<ResolvedEndpoint>, GenericError> {
376        resolve_additional_endpoints(&self.additional_endpoints)
377            .error_context("Failed parsing/resolving the additional destination endpoints.")
378    }
379}
380
381impl fmt::Debug for EndpointConfiguration {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        f.debug_struct("EndpointConfiguration")
384            .field("primary_endpoint", &self.primary_endpoint)
385            .field("additional_endpoints", &self.additional_endpoints.keys())
386            .finish_non_exhaustive()
387    }
388}
389
390/// A single API endpoint and its associated API key.
391///
392/// An endpoint is defined as a unique, fully qualified domain name that metrics will be sent to, such as
393/// `https://app.datadoghq.com`.
394#[derive(Clone, Debug)]
395pub struct ResolvedEndpoint {
396    endpoint: Url,
397    configured_endpoint: String,
398    /// The key this endpoint presents. A forwarder may bind it to a live view through `ApiKeyRefresher`.
399    api_key: ApiKeyCell,
400    /// Position of this key in the `additional_endpoints` config key list for its URL (raw
401    /// `enumerate()` index, not a post-dedup counter). `None` for primary and OPW endpoints.
402    api_key_index: Option<usize>,
403    /// The raw (pre-normalization) URL string from `additional_endpoints`, used as the HashMap
404    /// key for live API key lookups. `None` for primary and OPW endpoints.
405    raw_additional_url: Option<String>,
406    /// Pre-computed logs intake authority (for example, `agent-http-intake.logs.datadoghq.com`).
407    /// This is derived from the endpoint host when it contains `.agent.` marker.
408    logs_authority: Option<Authority>,
409    /// Pre-computed traces intake authority (for example, `trace.agent.datadoghq.com`).
410    /// This is derived from the endpoint host when it contains `.agent.` marker.
411    traces_authority: Option<Authority>,
412}
413
414/// Routing role for a resolved endpoint.
415#[derive(Clone, Copy, Debug, Eq, PartialEq)]
416pub(crate) enum EndpointRoute {
417    /// The normal primary Datadog endpoint.
418    Primary,
419    /// The OPW metrics primary endpoint.
420    MetricsPrimary,
421    /// A configured dual-shipping endpoint.
422    Additional,
423}
424
425/// A resolved endpoint with routing metadata.
426#[derive(Clone, Debug)]
427pub(crate) struct RoutableEndpoint {
428    route: EndpointRoute,
429    endpoint: ResolvedEndpoint,
430    target: Option<RoutingTargetId>,
431}
432
433impl RoutableEndpoint {
434    /// Creates a new routable endpoint that is not a routing target.
435    pub(crate) const fn new(route: EndpointRoute, endpoint: ResolvedEndpoint) -> Self {
436        Self {
437            route,
438            endpoint,
439            target: None,
440        }
441    }
442
443    /// Sets the routing target this endpoint delivers for.
444    pub(crate) const fn with_target(mut self, target: Option<RoutingTargetId>) -> Self {
445        self.target = target;
446        self
447    }
448
449    /// Returns the routing role.
450    pub(crate) const fn route(&self) -> EndpointRoute {
451        self.route
452    }
453
454    /// Returns the routing target this endpoint delivers for, if it has one.
455    ///
456    /// An endpoint without a target receives only payloads that are not addressed to specific targets.
457    #[cfg(test)]
458    pub(crate) const fn target(&self) -> Option<RoutingTargetId> {
459        self.target
460    }
461
462    /// Returns the resolved endpoint.
463    pub(crate) const fn endpoint(&self) -> &ResolvedEndpoint {
464        &self.endpoint
465    }
466
467    /// Consumes the routable endpoint and returns its parts.
468    pub(crate) fn into_parts(self) -> (EndpointRoute, ResolvedEndpoint, Option<RoutingTargetId>) {
469        (self.route, self.endpoint, self.target)
470    }
471}
472
473impl ResolvedEndpoint {
474    /// Creates a new `ResolvedEndpoint` instance from the given endpoint and API key, normalizing and modifying the
475    /// endpoint as necessary.
476    ///
477    /// # Errors
478    ///
479    /// Returns an error if the endpoint URL is invalid or the API key cannot be used as an HTTP header value.
480    pub(crate) fn from_raw_endpoint(raw_endpoint: &str, api_key: &str) -> Result<Self, EndpointError> {
481        let endpoint = parse_and_normalize_endpoint(raw_endpoint)?;
482        let logs_authority = compute_logs_authority(&endpoint);
483        let traces_authority = compute_traces_authority(&endpoint);
484        Ok(Self {
485            endpoint,
486            configured_endpoint: raw_endpoint.to_string(),
487            api_key: ApiKeyCell::new(api_key).map_err(|_| EndpointError::InvalidApiKey)?,
488            api_key_index: None,
489            raw_additional_url: None,
490            logs_authority,
491            traces_authority,
492        })
493    }
494
495    /// Returns the endpoint of the resolver.
496    pub fn endpoint(&self) -> &Url {
497        &self.endpoint
498    }
499
500    /// Returns the endpoint string as it was provided by configuration.
501    ///
502    /// Unlike [`ResolvedEndpoint::endpoint`], this is not rewritten with the data plane version prefix.
503    pub fn configured_endpoint(&self) -> &str {
504        &self.configured_endpoint
505    }
506
507    /// Returns the API key associated with the endpoint.
508    ///
509    /// The returned key is the one stored for this endpoint. After an
510    /// [`ApiKeyRefresher`][super::api_key::ApiKeyRefresher] processes a configuration change, it replaces
511    /// the stored key. An endpoint not bound to a refresher, such as one presenting a token that
512    /// configuration does not own, keeps the key it was built with.
513    pub fn api_key(&self) -> MetaString {
514        self.api_key.load()
515    }
516
517    /// Returns the cell holding this endpoint's API key, for a refresher to write.
518    pub(crate) const fn api_key_cell(&self) -> &ApiKeyCell {
519        &self.api_key
520    }
521
522    /// Returns the position of this endpoint's API key in the `additional_endpoints` config list for
523    /// its URL. `None` for primary and OPW endpoints.
524    #[cfg(test)]
525    pub(crate) fn api_key_index(&self) -> Option<usize> {
526        self.api_key_index
527    }
528
529    /// Returns the raw (pre-normalization) URL and key index for additional endpoints.
530    ///
531    /// Using the raw URL in queue IDs prevents collisions when two different raw URLs (for example,
532    /// `app.datadoghq.com` and `https://app.datadoghq.com`) normalize to the same host.
533    /// Returns `None` for primary and OPW endpoints.
534    pub(crate) fn additional_endpoint_queue_key(&self) -> Option<(&str, usize)> {
535        match (self.raw_additional_url.as_deref(), self.api_key_index) {
536            (Some(raw_url), Some(index)) => Some((raw_url, index)),
537            _ => None,
538        }
539    }
540
541    /// Returns the pre-computed logs intake authority, if available.
542    ///
543    /// This authority is derived from the endpoint host when it contains the `.agent.` marker,
544    /// and is used for routing log payloads to the appropriate logs intake host.
545    pub fn logs_authority(&self) -> Option<&Authority> {
546        self.logs_authority.as_ref()
547    }
548
549    /// Returns the pre-computed traces intake authority, if available.
550    pub fn traces_authority(&self) -> Option<&Authority> {
551        self.traces_authority.as_ref()
552    }
553}
554
555/// Returns `raw_endpoint` with the `https` scheme if it has neither `http` nor `https`.
556pub(crate) fn endpoint_with_default_scheme(raw_endpoint: &str) -> String {
557    if !raw_endpoint.starts_with("http://") && !raw_endpoint.starts_with("https://") {
558        format!("https://{}", raw_endpoint)
559    } else {
560        raw_endpoint.to_string()
561    }
562}
563
564fn parse_and_normalize_endpoint(raw_endpoint: &str) -> Result<Url, EndpointError> {
565    // Start out by parsing the given domain/endpoint, which means ensuring first that it has a scheme.
566    //
567    // If no scheme is present, we assume HTTPS.
568    let raw_endpoint = endpoint_with_default_scheme(raw_endpoint);
569
570    let endpoint = Url::parse(&raw_endpoint).context(Parse { endpoint: raw_endpoint })?;
571
572    // With our valid endpoint URL, we'll optionally prefix it with a subdomain that represents the data plane version,
573    // which differentiates the traffic between different versions of the data plane application.
574    //
575    // This prefixing only occurs for official Datadog API endpoints.
576    add_data_plane_version_prefix(endpoint)
577}
578
579/// Returns a specialized domain prefix based on the versioning of the current application.
580///
581/// This generates a prefix that's similar in format to the one generated by Datadog Agent for determining the endpoint
582/// to send metrics to.
583fn get_data_plane_version_prefix() -> String {
584    let app_details = saluki_metadata::get_app_details();
585    let version = app_details.version();
586    format!(
587        "{}-{}-{}-{}.agent",
588        version.major(),
589        version.minor(),
590        version.patch(),
591        app_details.identifier(),
592    )
593}
594
595/// Prefixes the given API endpoint with the version of the data plane process.
596///
597/// If the endpoint doesn't represent an official Datadog API endpoint, it won't be modified.
598///
599/// # Errors
600///
601/// If the given API endpoint has no host, an error will be returned.
602fn add_data_plane_version_prefix(endpoint: Url) -> Result<Url, EndpointError> {
603    add_version_prefix(endpoint, &get_data_plane_version_prefix())
604}
605
606/// Returns the base path of `endpoint`, without trailing slashes.
607///
608/// A request path, which starts with `/`, is appended to the base path as is: `https://proxy.example.com/prefix/` and
609/// `/api/v2/series` give `/prefix/api/v2/series`. An endpoint with no path, or only `/`, gives an empty base path.
610pub(crate) fn endpoint_base_path(endpoint: &Url) -> &str {
611    endpoint.path().trim_end_matches('/')
612}
613
614/// Replaces the leftmost label of the host of `endpoint` with `prefix`, if it is an official Datadog application host.
615///
616/// This differentiates traffic between versions of the sending application: `app.datadoghq.com` becomes
617/// `{prefix}.datadoghq.com`. Any other endpoint is returned unmodified.
618///
619/// # Errors
620///
621/// If `endpoint` has no host, or the prefixed host is invalid, an error will be returned.
622pub(crate) fn add_version_prefix(mut endpoint: Url, prefix: &str) -> Result<Url, EndpointError> {
623    let new_host = match endpoint.host_str() {
624        Some(host) => {
625            // Do not update non-official Datadog URLs.
626            if !DD_URL_REGEX.is_match(host) {
627                debug!("Configured endpoint '{}' appears to be a non-Datadog endpoint. Utilizing endpoint without modification.", host);
628                return Ok(endpoint);
629            }
630
631            // We expect to be getting a domain that has at least one subdomain portion (i.e., `app.datadoghq.com`) if
632            // not more. We're aiming to simply replace the leftmost subdomain portion with the version prefix.
633            let leftmost_segment = host.split('.').next().unwrap_or("");
634            host.replacen(leftmost_segment, prefix, 1)
635        }
636        None => {
637            return Err(EndpointError::Parse {
638                source: url::ParseError::EmptyHost,
639                endpoint: endpoint.to_string(),
640            })
641        }
642    };
643
644    // Update the host with the prefixed version.
645    if let Err(e) = endpoint.set_host(Some(new_host.as_str())) {
646        return Err(EndpointError::Parse {
647            source: e,
648            endpoint: endpoint.to_string(),
649        });
650    }
651
652    Ok(endpoint)
653}
654
655/// Computes the logs intake authority from a resolved endpoint URL.
656///
657/// If the endpoint host contains the `.agent.` marker (for example, `7-52-0-adp.agent.datadoghq.com`),
658/// this extracts the site suffix and constructs the logs intake host in the form
659/// `agent-http-intake.logs.{site}`.
660///
661/// Returns `None` if the host doesn't contain the marker or if the authority can't be parsed.
662fn compute_logs_authority(endpoint: &Url) -> Option<Authority> {
663    const AGENT_HOST_MARKER: &str = ".agent.";
664
665    let host = endpoint.host_str()?;
666    let idx = host.find(AGENT_HOST_MARKER)?;
667    let site = &host[idx + AGENT_HOST_MARKER.len()..];
668    let logs_host = format!("agent-http-intake.logs.{}", site);
669
670    Authority::from_str(&logs_host).ok()
671}
672
673/// Computes the traces intake authority from a resolved endpoint URL.
674///
675/// Only a host that this crate version-prefixed, which has the form `{prefix}.agent.{site}` with an official Datadog
676/// site, gets one. A configured host that merely contains `.agent.` is the operator's own and is used as is.
677///
678/// Returns `None` if the host isn't of that form or if the authority can't be parsed.
679fn compute_traces_authority(endpoint: &Url) -> Option<Authority> {
680    const AGENT_HOST_MARKER: &str = ".agent.";
681
682    let host = endpoint.host_str()?;
683    let idx = host.find(AGENT_HOST_MARKER)?;
684    let site = &host[idx + AGENT_HOST_MARKER.len()..];
685    if !host_matches(&DD_AGENT_SITE_REGEX, site) {
686        return None;
687    }
688    let traces_host = format!("trace.agent.{}", site);
689
690    Authority::from_str(&traces_host).ok()
691}
692
693#[cfg(test)]
694mod tests {
695    use super::*;
696
697    /// Returns the V3 series settings the Agent's schema defaults resolve to.
698    fn agent_series_config() -> UseV3ApiSeriesConfig {
699        UseV3ApiSeriesConfig {
700            enabled: V3SeriesMode::DatadogOnly,
701            endpoints: HashMap::new(),
702        }
703    }
704
705    fn additional_endpoints(endpoints: &[(&str, &[&str])]) -> HashMap<String, Vec<String>> {
706        endpoints
707            .iter()
708            .map(|(url, api_keys)| {
709                (
710                    url.to_string(),
711                    api_keys.iter().map(|api_key| api_key.to_string()).collect(),
712                )
713            })
714            .collect()
715    }
716
717    #[test]
718    fn extracts_datadog_sites_from_endpoint_urls() {
719        for (url, expected) in [
720            ("https://app.datadoghq.com", Some("datadoghq.com")),
721            ("https://APP.DATADOGHQ.COM./", Some("datadoghq.com")),
722            ("https://agent.datad0g.com.", Some("datad0g.com")),
723            ("https://1-9-0-adp.agent.us3.datadoghq.com", Some("us3.datadoghq.com")),
724            ("https://app.datadoghq.eu", Some("datadoghq.eu")),
725            ("https://app.ddog-gov.com", Some("ddog-gov.com")),
726            ("https://notdatadoghq.com", None),
727            ("https://app.datadoghq.com.example.org", None),
728        ] {
729            assert_eq!(
730                extract_datadog_site(&Url::parse(url).unwrap()).as_deref(),
731                expected,
732                "{url}"
733            );
734        }
735    }
736
737    #[test]
738    fn endpoint_configuration_debug_omits_api_keys() {
739        let config = EndpointConfiguration::new(
740            "primary-secret".to_string(),
741            "https://primary.example.com".to_string(),
742            additional_endpoints(&[(
743                "https://additional.example.com",
744                &["additional-secret", "another-secret"],
745            )]),
746        );
747
748        for debug in [format!("{config:?}"), format!("{config:#?}")] {
749            assert!(debug.contains("https://primary.example.com"), "{debug}");
750            assert!(debug.contains("https://additional.example.com"), "{debug}");
751            for key in ["primary-secret", "additional-secret", "another-secret"] {
752                assert!(!debug.contains(key), "API key exposed in Debug output");
753            }
754        }
755    }
756
757    #[test]
758    fn additional_endpoints_api_key_index_uses_raw_config_position() {
759        // Keys at positions 0, 1 are valid; position 2 is empty (skipped); position 3 is a
760        // duplicate of position 0 (skipped); position 4 is valid. Only positions 0, 1, 4 produce
761        // ResolvedEndpoints, and their api_key_index should be 0, 1, 4 respectively.
762        let endpoints = additional_endpoints(&[("app.datadoghq.com", &["key-a", "key-b", "", "key-a", "key-c"])]);
763
764        let resolved = resolve_additional_endpoints(&endpoints).expect("should resolve");
765
766        assert_eq!(
767            resolved.len(),
768            3,
769            "should have 3 endpoints (skipping empty and duplicate)"
770        );
771        assert_eq!(&*resolved[0].api_key(), "key-a");
772        assert_eq!(resolved[0].api_key_index(), Some(0));
773        assert_eq!(&*resolved[1].api_key(), "key-b");
774        assert_eq!(resolved[1].api_key_index(), Some(1));
775        assert_eq!(&*resolved[2].api_key(), "key-c");
776        assert_eq!(
777            resolved[2].api_key_index(),
778            Some(4),
779            "index 4 — not 2 — because original positions are used"
780        );
781
782        // Two URLs have independent index spaces (both start from 0).
783        let endpoints2 = additional_endpoints(&[("app.datadoghq.eu", &["eu-key-a", "eu-key-b"])]);
784        let resolved2 = resolve_additional_endpoints(&endpoints2).expect("should resolve");
785        assert_eq!(resolved2[0].api_key_index(), Some(0));
786        assert_eq!(resolved2[1].api_key_index(), Some(1));
787    }
788
789    #[test]
790    fn header_invalid_additional_api_keys_are_skipped() {
791        let endpoints = additional_endpoints(&[("app.datadoghq.com", &["key-a", "key\nvalue", "key-b"])]);
792
793        let resolved = resolve_additional_endpoints(&endpoints).expect("should resolve");
794
795        assert_eq!(resolved.len(), 2);
796        assert_eq!(&*resolved[0].api_key(), "key-a");
797        assert_eq!(resolved[0].api_key_index(), Some(0));
798        assert_eq!(&*resolved[1].api_key(), "key-b");
799        assert_eq!(resolved[1].api_key_index(), Some(2));
800    }
801
802    #[test]
803    fn add_version_prefix() {
804        let input_urls = [
805            "https://app.datadoghq.com",     // US
806            "https://app.datadoghq.eu",      // EU
807            "app.ddog-gov.com",              // Gov
808            "app.us2.datadoghq.com",         // Additional Site
809            "https://app.xx9.datadoghq.com", // Arbitrary site
810        ];
811        let expected_hosts = [
812            "datadoghq.com",
813            "datadoghq.eu",
814            "ddog-gov.com",
815            "us2.datadoghq.com",
816            "xx9.datadoghq.com",
817        ]
818        .iter()
819        .map(|s| format!("{}.{}", get_data_plane_version_prefix(), s))
820        .collect::<Vec<_>>();
821
822        for (input_url, expected_host) in input_urls.iter().zip(expected_hosts) {
823            let resolved =
824                ResolvedEndpoint::from_raw_endpoint(input_url, "fake_api_key").expect("error resolving endpoint");
825            assert_eq!(
826                expected_host,
827                resolved.endpoint().host_str().expect("error getting host")
828            );
829        }
830    }
831
832    #[test]
833    fn datadog_sites_have_no_subdomain() {
834        for site in [
835            "datadoghq.com",
836            "datadoghq.eu",
837            "datad0g.com",
838            "ddog-gov.com",
839            "DATADOGHQ.COM",
840            "datadoghq.com.",
841        ] {
842            assert!(is_datadog_site(site), "{site}");
843        }
844        for host in [
845            "app.datadoghq.com",
846            "us3.datadoghq.com",
847            "datadoghq.internal",
848            "example.com",
849        ] {
850            assert!(!is_datadog_site(host), "{host}");
851        }
852    }
853
854    #[test]
855    fn skip_version_prefix() {
856        let input_urls = [
857            "https://custom.datadoghq.com",       // Custom
858            "https://custom.agent.datadoghq.com", // Custom with 'agent' subdomain
859            "https://app.custom.datadoghq.com",   // Custom
860            "https://app.datadoghq.internal",     // Custom top-level domain
861            "https://app.myproxy.com",            // Proxy
862        ];
863        let expected_hosts = [
864            "custom.datadoghq.com",
865            "custom.agent.datadoghq.com",
866            "app.custom.datadoghq.com",
867            "app.datadoghq.internal",
868            "app.myproxy.com",
869        ];
870
871        for (input_url, expected_host) in input_urls.iter().zip(expected_hosts) {
872            let resolved =
873                ResolvedEndpoint::from_raw_endpoint(input_url, "fake_api_key").expect("error resolving endpoint");
874            assert_eq!(
875                expected_host,
876                resolved.endpoint().host_str().expect("error getting host")
877            );
878        }
879    }
880
881    #[test]
882    fn the_primary_endpoint_is_version_prefixed_only_for_datadog_endpoints() {
883        let prefix = get_data_plane_version_prefix();
884        let cases = [
885            (
886                "Datadog endpoint",
887                "https://app.us3.datadoghq.com",
888                format!("https://{prefix}.us3.datadoghq.com/"),
889            ),
890            (
891                "non-Datadog endpoint used verbatim",
892                "https://dogpound.io/",
893                "https://dogpound.io/".to_string(),
894            ),
895        ];
896
897        for (name, primary_endpoint, expected_endpoint) in cases {
898            let config =
899                EndpointConfiguration::new("fake-api-key".to_string(), primary_endpoint.to_string(), HashMap::new());
900
901            let resolved = config.build_primary_endpoint().expect(name);
902            assert_eq!(expected_endpoint, resolved.endpoint().to_string(), "{name}");
903            assert_eq!("fake-api-key", &*resolved.api_key(), "{name}");
904        }
905    }
906
907    #[test]
908    fn a_single_destination_is_the_only_endpoint() {
909        let destination = SingleDestination {
910            url: "https://cluster-agent.example.com:5005".to_string(),
911            api_key: "secret-token".to_string(),
912            accepts_v3_series: false,
913        };
914        let config = EndpointConfiguration::for_single_destination(&destination);
915
916        assert_eq!(
917            "https://cluster-agent.example.com:5005",
918            config
919                .build_primary_endpoint()
920                .expect("endpoint should resolve")
921                .configured_endpoint()
922        );
923        assert!(config
924            .build_additional_endpoints()
925            .expect("additional endpoints should resolve")
926            .is_empty());
927    }
928
929    #[test]
930    fn should_receive_payload_covers_all_documented_branches() {
931        // Walks every branch enumerated in `should_receive_payload`'s doc comment:
932        // - V2 series: accept if series V3 is disabled
933        // - V2 sketches: accept if sketches V3 is disabled
934        // - V3 series: accept if series V3 is enabled
935        // - V3 sketches: accept if sketches V3 is enabled
936        // - Non-metrics payloads (None): always accept
937        let cases: [(&str, EndpointV3Settings, Option<MetricsPayloadInfo>, bool); 9] = [
938            (
939                "v2 series accepted when series v3 disabled",
940                EndpointV3Settings::disabled(),
941                Some(MetricsPayloadInfo::v2_series()),
942                true,
943            ),
944            (
945                "v2 series rejected when series v3 enabled",
946                EndpointV3Settings {
947                    use_v3_series: true,
948                    ..EndpointV3Settings::disabled()
949                },
950                Some(MetricsPayloadInfo::v2_series()),
951                false,
952            ),
953            (
954                "v2 sketches accepted when sketches v3 disabled",
955                EndpointV3Settings::disabled(),
956                Some(MetricsPayloadInfo::v2_sketches()),
957                true,
958            ),
959            (
960                "v2 sketches rejected when sketches v3 enabled",
961                EndpointV3Settings {
962                    use_v3_sketches: true,
963                    ..EndpointV3Settings::disabled()
964                },
965                Some(MetricsPayloadInfo::v2_sketches()),
966                false,
967            ),
968            (
969                "v3 series accepted when series v3 enabled",
970                EndpointV3Settings {
971                    use_v3_series: true,
972                    ..EndpointV3Settings::disabled()
973                },
974                Some(MetricsPayloadInfo::v3_series()),
975                true,
976            ),
977            (
978                "v3 series rejected when series v3 disabled",
979                EndpointV3Settings::disabled(),
980                Some(MetricsPayloadInfo::v3_series()),
981                false,
982            ),
983            (
984                "v3 sketches accepted when sketches v3 enabled",
985                EndpointV3Settings {
986                    use_v3_sketches: true,
987                    ..EndpointV3Settings::disabled()
988                },
989                Some(MetricsPayloadInfo::v3_sketches()),
990                true,
991            ),
992            (
993                "v3 sketches rejected when sketches v3 disabled",
994                EndpointV3Settings::disabled(),
995                Some(MetricsPayloadInfo::v3_sketches()),
996                false,
997            ),
998            (
999                "non-metrics payload always accepted",
1000                EndpointV3Settings {
1001                    use_v3_series: true,
1002                    use_v3_sketches: true,
1003                },
1004                None,
1005                true,
1006            ),
1007        ];
1008
1009        for (name, settings, payload_info, expected) in cases {
1010            assert_eq!(settings.should_receive_payload(payload_info), expected, "{name}");
1011        }
1012    }
1013
1014    fn v3_endpoint_config<'a>(
1015        endpoint: &'a ResolvedEndpoint, series_config: &'a UseV3ApiSeriesConfig,
1016    ) -> V3EndpointConfig<'a> {
1017        V3EndpointConfig {
1018            configured_endpoint: endpoint.configured_endpoint(),
1019            series_config,
1020            metrics_primary_v3_override: None,
1021            serializer_v3_sketches_endpoints: &[],
1022        }
1023    }
1024
1025    #[test]
1026    fn agent_v3_default_enables_authoritative_v3() {
1027        let resolved = ResolvedEndpoint::from_raw_endpoint("https://app.datadoghq.com", "fake-api-key")
1028            .expect("endpoint should resolve");
1029        let series_config = agent_series_config();
1030
1031        let settings = EndpointV3Settings::from_v3_config(v3_endpoint_config(&resolved, &series_config));
1032        assert!(settings.use_v3_series);
1033    }
1034
1035    #[test]
1036    fn agent_v3_endpoint_overrides_win_over_global_default() {
1037        let resolved = ResolvedEndpoint::from_raw_endpoint("https://app.datadoghq.com", "fake-api-key")
1038            .expect("endpoint should resolve");
1039        let mut series_config = agent_series_config();
1040        series_config
1041            .endpoints
1042            .insert(resolved.configured_endpoint().to_string(), V3SeriesMode::Disabled);
1043
1044        let settings = EndpointV3Settings::from_v3_config(v3_endpoint_config(&resolved, &series_config));
1045        assert!(!settings.use_v3_series);
1046
1047        series_config = UseV3ApiSeriesConfig {
1048            enabled: V3SeriesMode::Disabled,
1049            endpoints: HashMap::new(),
1050        };
1051        series_config
1052            .endpoints
1053            .insert(resolved.configured_endpoint().to_string(), V3SeriesMode::Enabled);
1054
1055        let settings = EndpointV3Settings::from_v3_config(v3_endpoint_config(&resolved, &series_config));
1056        assert!(settings.use_v3_series);
1057    }
1058
1059    #[test]
1060    fn agent_v3_datadog_only_matches_datadog_intake_urls() {
1061        let datadog = ResolvedEndpoint::from_raw_endpoint("https://app.datadoghq.com", "fake-api-key")
1062            .expect("endpoint should resolve");
1063        let custom = ResolvedEndpoint::from_raw_endpoint("https://example.com", "fake-api-key")
1064            .expect("endpoint should resolve");
1065        let series_config = UseV3ApiSeriesConfig {
1066            enabled: V3SeriesMode::DatadogOnly,
1067            endpoints: HashMap::new(),
1068        };
1069
1070        let datadog_settings = EndpointV3Settings::from_v3_config(v3_endpoint_config(&datadog, &series_config));
1071        let custom_settings = EndpointV3Settings::from_v3_config(v3_endpoint_config(&custom, &series_config));
1072
1073        assert!(datadog_settings.use_v3_series);
1074        assert!(!custom_settings.use_v3_series);
1075    }
1076
1077    #[test]
1078    fn agent_v3_datadog_only_config_viability_matches_core_agent_url_rules() {
1079        let mut series_config = UseV3ApiSeriesConfig {
1080            enabled: V3SeriesMode::Disabled,
1081            endpoints: HashMap::new(),
1082        };
1083        for endpoint in [
1084            "https://app.datadoghq.com",
1085            "https://APP.DATADOGHQ.COM",
1086            "https://app.datadoghq.com.:443",
1087            "https://app.us12.datadoghq.com",
1088            "https://app.apne1.datadoghq.com",
1089        ] {
1090            series_config.endpoints = HashMap::from([(endpoint.to_string(), V3SeriesMode::DatadogOnly)]);
1091            assert!(series_v3_config_can_enable_v3(&series_config), "{endpoint}");
1092        }
1093
1094        for endpoint in ["app.datadoghq.com", "app.datadoghq.com:443", "example.com"] {
1095            series_config.endpoints = HashMap::from([(endpoint.to_string(), V3SeriesMode::DatadogOnly)]);
1096            assert!(!series_v3_config_can_enable_v3(&series_config), "{endpoint}");
1097        }
1098    }
1099
1100    #[test]
1101    fn agent_v3_datadog_only_endpoint_override_rejects_schemeless_host_port() {
1102        let resolved = ResolvedEndpoint::from_raw_endpoint("app.datadoghq.com:443", "fake-api-key")
1103            .expect("endpoint should resolve");
1104        let mut series_config = UseV3ApiSeriesConfig {
1105            enabled: V3SeriesMode::Disabled,
1106            endpoints: HashMap::new(),
1107        };
1108        series_config
1109            .endpoints
1110            .insert(resolved.configured_endpoint().to_string(), V3SeriesMode::DatadogOnly);
1111
1112        let settings = EndpointV3Settings::from_v3_config(v3_endpoint_config(&resolved, &series_config));
1113
1114        assert!(!settings.use_v3_series);
1115    }
1116
1117    #[test]
1118    fn metrics_primary_v3_uses_route_specific_override() {
1119        let resolved = ResolvedEndpoint::from_raw_endpoint("https://vector.example.com", "fake-api-key")
1120            .expect("endpoint should resolve");
1121        let series_config = agent_series_config();
1122
1123        let settings = EndpointV3Settings::from_v3_config(V3EndpointConfig {
1124            metrics_primary_v3_override: Some(false),
1125            ..v3_endpoint_config(&resolved, &series_config)
1126        });
1127        assert!(!settings.use_v3_series);
1128
1129        let settings = EndpointV3Settings::from_v3_config(V3EndpointConfig {
1130            metrics_primary_v3_override: Some(true),
1131            ..v3_endpoint_config(&resolved, &series_config)
1132        });
1133        assert!(settings.use_v3_series);
1134    }
1135
1136    #[test]
1137    fn only_official_datadog_hosts_get_a_traces_authority() {
1138        let cases = [
1139            ("https://app.datadoghq.com", Some("trace.agent.datadoghq.com")),
1140            ("https://app.us5.datadoghq.com", Some("trace.agent.us5.datadoghq.com")),
1141            ("https://app.datadoghq.eu", Some("trace.agent.datadoghq.eu")),
1142            ("https://trace.agent.datadoghq.com", Some("trace.agent.datadoghq.com")),
1143            // Hosts the operator wrote are used as is, even when they contain the marker.
1144            ("https://foo.agent.corp.example", None),
1145            ("http://opw.agent.internal:8080", None),
1146            ("https://custom.example.com", None),
1147        ];
1148
1149        for (raw, expected) in cases {
1150            let endpoint = ResolvedEndpoint::from_raw_endpoint(raw, "fake-api-key").expect("endpoint should resolve");
1151            assert_eq!(expected, endpoint.traces_authority().map(Authority::as_str), "{raw}");
1152        }
1153    }
1154
1155    #[test]
1156    fn the_configured_endpoint_keeps_the_agent_endpoint_shape() {
1157        // The configured endpoint is matched against V3 endpoint lists, so it must stay in the shape
1158        // the Agent uses, before version prefixing.
1159        let config = EndpointConfiguration::new(String::new(), "https://app.datadoghq.com".to_string(), HashMap::new());
1160
1161        assert_eq!(
1162            "https://app.datadoghq.com",
1163            config
1164                .build_primary_endpoint()
1165                .expect("endpoint should resolve")
1166                .configured_endpoint()
1167        );
1168    }
1169}