Skip to main content

libdd_common/
endpoint.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4use alloc::borrow::Cow;
5use anyhow::Context;
6use core::{ops::Deref, str::FromStr};
7use http::uri::{self, PathAndQuery, Uri};
8use serde::de::Error;
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10use std::path::PathBuf;
11
12use crate::HttpRequestBuilder;
13
14#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
15pub struct Endpoint {
16    #[serde(serialize_with = "serialize_uri", deserialize_with = "deserialize_uri")]
17    pub url: http::Uri,
18    pub api_key: Option<Cow<'static, str>>,
19    pub timeout_ms: u64,
20    /// Sets X-Datadog-Test-Session-Token header on any request
21    pub test_token: Option<Cow<'static, str>>,
22    /// Use the system DNS resolver when building the HTTP client. If false, the default
23    /// in-process resolver is used.
24    #[serde(default)]
25    pub use_system_resolver: bool,
26}
27
28impl core::fmt::Debug for Endpoint {
29    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
30        f.debug_struct("Endpoint")
31            .field("url", &self.url)
32            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
33            .field("timeout_ms", &self.timeout_ms)
34            .field("test_token", &self.test_token)
35            .field("use_system_resolver", &self.use_system_resolver)
36            .finish()
37    }
38}
39
40impl Default for Endpoint {
41    fn default() -> Self {
42        Endpoint {
43            url: http::Uri::default(),
44            api_key: None,
45            timeout_ms: Self::DEFAULT_TIMEOUT,
46            test_token: None,
47            use_system_resolver: false,
48        }
49    }
50}
51
52#[derive(serde::Deserialize, serde::Serialize)]
53struct SerializedUri<'a> {
54    scheme: Option<Cow<'a, str>>,
55    authority: Option<Cow<'a, str>>,
56    path_and_query: Option<Cow<'a, str>>,
57}
58
59fn serialize_uri<S>(uri: &http::Uri, serializer: S) -> Result<S::Ok, S::Error>
60where
61    S: Serializer,
62{
63    let parts = uri.clone().into_parts();
64    let uri = SerializedUri {
65        scheme: parts.scheme.as_ref().map(|s| Cow::Borrowed(s.as_str())),
66        authority: parts.authority.as_ref().map(|s| Cow::Borrowed(s.as_str())),
67        path_and_query: parts
68            .path_and_query
69            .as_ref()
70            .map(|s| Cow::Borrowed(s.as_str())),
71    };
72    uri.serialize(serializer)
73}
74
75fn deserialize_uri<'de, D>(deserializer: D) -> Result<http::Uri, D::Error>
76where
77    D: Deserializer<'de>,
78{
79    let uri = SerializedUri::deserialize(deserializer)?;
80    let mut builder = http::Uri::builder();
81    if let Some(v) = uri.authority {
82        builder = builder.authority(v.deref());
83    }
84    if let Some(v) = uri.scheme {
85        builder = builder.scheme(v.deref());
86    }
87    if let Some(v) = uri.path_and_query {
88        builder = builder.path_and_query(v.deref());
89    }
90
91    builder.build().map_err(Error::custom)
92}
93
94/// Converts a human-facing URL string into the internal [`http::Uri`]
95/// representation.
96///
97/// NOTE: the name is misleading. For `http`/`https` this is an ordinary parse,
98/// but for the `file`/`unix`/`windows` schemes it *encodes* the path into the
99/// URI authority (see `encode_uri_path_in_authority`), so it is a
100/// URL-string-to-`Uri` *constructor*, not a pure parser.
101///
102/// WARNING: this is NOT idempotent for those three schemes. The `Uri` it
103/// returns stringifies back to the encoded form (`file://<hex>/`), and feeding
104/// that string in again re-encodes it, double-encoding the path. Only ever call
105/// this on an original URL string — never on the `.to_string()` of a `Uri` that
106/// already came out of here.
107///
108/// TODO: we should properly handle malformed urls
109/// * For windows and unix schemes:
110///     * For compatibility reasons with existing implementation this parser stores the encoded path
111///       in authority section as there is no existing standard [see](https://github.com/whatwg/url/issues/577)
112///       that covers this. We need to pick one hack or another
113///     * For windows, interprets everything after windows: as path
114///     * For unix, interprets everything after unix:// as path
115/// * For file scheme implementation will simply backfill missing authority section
116pub fn parse_uri(uri: &str) -> anyhow::Result<http::Uri> {
117    if let Some(path) = uri.strip_prefix("unix://") {
118        encode_uri_path_in_authority("unix", path)
119    } else if let Some(path) = uri.strip_prefix("windows:") {
120        encode_uri_path_in_authority("windows", path)
121    } else if let Some(path) = uri.strip_prefix("file://") {
122        encode_uri_path_in_authority("file", path)
123    } else {
124        Ok(http::Uri::from_str(uri)?)
125    }
126}
127
128fn encode_uri_path_in_authority(scheme: &str, path: &str) -> anyhow::Result<http::Uri> {
129    let mut parts = uri::Parts::default();
130    parts.scheme = uri::Scheme::from_str(scheme).ok();
131
132    let path = hex::encode(path);
133
134    parts.authority = uri::Authority::from_str(path.as_str()).ok();
135    parts.path_and_query = Some(uri::PathAndQuery::from_static("/"));
136    Ok(http::Uri::from_parts(parts)?)
137}
138
139pub fn decode_uri_path_in_authority(uri: &http::Uri) -> anyhow::Result<PathBuf> {
140    let path = hex::decode(uri.authority().context("missing uri authority")?.as_str())?;
141    #[cfg(unix)]
142    {
143        use std::os::unix::ffi::OsStringExt;
144        Ok(PathBuf::from(std::ffi::OsString::from_vec(path)))
145    }
146    #[cfg(not(unix))]
147    {
148        match String::from_utf8(path) {
149            Ok(s) => Ok(PathBuf::from(s.as_str())),
150            _ => Err(anyhow::anyhow!("file uri should be utf-8")),
151        }
152    }
153}
154
155impl Endpoint {
156    /// Default value for the timeout field in milliseconds.
157    pub const DEFAULT_TIMEOUT: u64 = 3_000;
158
159    pub fn agentless(site: &str, api_key: String) -> anyhow::Result<Self> {
160        Ok(Self {
161            url: Uri::builder()
162                .scheme("https")
163                .authority(
164                    uri::Authority::try_from(site)
165                        .with_context(|| format!("dd_site is an invalid url: {site}"))?,
166                )
167                .path_and_query(PathAndQuery::from_static(""))
168                .build()
169                .with_context(|| format!("rc url is invalid for site: {site}"))?,
170            api_key: Some(api_key.into()),
171            timeout_ms: Self::DEFAULT_TIMEOUT,
172            test_token: None,
173            use_system_resolver: true,
174        })
175    }
176
177    /// Returns an iterator of optional endpoint-specific headers (api-key, test-token)
178    /// as (header_name, header_value) string tuples for any that are available.
179    pub fn get_optional_headers(&self) -> impl Iterator<Item = (&'static str, &str)> {
180        [
181            self.api_key.as_ref().map(|v| ("dd-api-key", v.as_ref())),
182            self.test_token
183                .as_ref()
184                .map(|v| ("x-datadog-test-session-token", v.as_ref())),
185        ]
186        .into_iter()
187        .flatten()
188    }
189
190    /// Apply standard headers (user-agent, api-key, test-token, entity headers) to an
191    /// [`http::request::Builder`].
192    pub fn set_standard_headers(
193        &self,
194        mut builder: http::request::Builder,
195        user_agent: &str,
196    ) -> http::request::Builder {
197        builder = builder.header("user-agent", user_agent);
198        for (name, value) in self.get_optional_headers() {
199            builder = builder.header(name, value);
200        }
201        for (name, value) in crate::entity_id::get_entity_headers() {
202            builder = builder.header(name, value);
203        }
204        builder
205    }
206
207    /// Return a request builder with the following headers:
208    /// - User agent
209    /// - Api key
210    /// - Container Id/Entity Id
211    pub fn to_request_builder(&self, user_agent: &str) -> anyhow::Result<HttpRequestBuilder> {
212        let mut builder = http::Request::builder()
213            .uri(self.url.clone())
214            .header(http::header::USER_AGENT, user_agent);
215
216        // Add optional endpoint headers (api-key, test-token)
217        for (name, value) in self.get_optional_headers() {
218            builder = builder.header(name, value);
219        }
220
221        // Add entity-related headers (container-id, entity-id, external-env)
222        for (name, value) in crate::entity_id::get_entity_headers() {
223            builder = builder.header(name, value);
224        }
225
226        Ok(builder)
227    }
228
229    #[inline]
230    pub fn from_slice(url: &str) -> Endpoint {
231        Endpoint {
232            #[allow(clippy::unwrap_used)]
233            url: parse_uri(url).unwrap(),
234            ..Default::default()
235        }
236    }
237
238    #[inline]
239    pub fn from_url(url: http::Uri) -> Endpoint {
240        Endpoint {
241            url,
242            ..Default::default()
243        }
244    }
245
246    pub fn is_file_endpoint(&self) -> bool {
247        self.url.scheme_str() == Some("file")
248    }
249
250    /// Set a custom timeout for this endpoint.
251    /// If not called, uses the default timeout of 3000ms.
252    ///
253    /// # Arguments
254    /// * `timeout_ms` - Timeout in milliseconds. Pass 0 to use the default timeout (3000ms).
255    ///
256    /// # Returns
257    /// Self with the timeout set, allowing for method chaining
258    pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
259        self.timeout_ms = if timeout_ms == 0 {
260            Self::DEFAULT_TIMEOUT
261        } else {
262            timeout_ms
263        };
264        self
265    }
266
267    /// Use the system DNS resolver when building the reqwest client. Only has effect for
268    /// HTTP(S) endpoints.
269    pub fn with_system_resolver(mut self, use_system_resolver: bool) -> Self {
270        self.use_system_resolver = use_system_resolver;
271        self
272    }
273
274    /// Creates a reqwest ClientBuilder configured for this endpoint.
275    ///
276    /// This method handles various endpoint schemes:
277    /// - `http`/`https`: Standard HTTP(S) endpoints. HTTPS requests use the same TLS configuration
278    ///   as the hyper connector, including the compromised-key distrust check.
279    /// - `unix`: Unix domain sockets (Unix only)
280    /// - `windows`: Windows named pipes (Windows only)
281    /// - `file`: File dump endpoints for debugging (spawns a local server to capture requests)
282    ///
283    /// The default in-process resolver is used for DNS (fork-safe). To use the system DNS resolver
284    /// instead (less fork-safe), set [`Endpoint::use_system_resolver`] to true via
285    /// [`Endpoint::with_system_resolver`].
286    ///
287    /// # Returns
288    /// A tuple of (ClientBuilder, request_url) where:
289    /// - ClientBuilder is configured with the appropriate transport and timeout
290    /// - request_url is the URL string to use for HTTP requests
291    ///
292    /// # Errors
293    /// Returns an error if:
294    /// - The endpoint scheme is unsupported
295    /// - Path decoding fails
296    /// - The dump server fails to start (for file:// scheme)
297    #[cfg(feature = "reqwest")]
298    pub fn to_reqwest_client_builder(&self) -> anyhow::Result<(reqwest::ClientBuilder, String)> {
299        use anyhow::Context;
300
301        // Don't use proxies, as this calls `getenv` which is unsafe and not
302        // just in theory. It can cause crashes with PHP where php-fpm's env
303        // configuration will mutate the system environment (it doesn't pass
304        // it as part of the SAPI env, it changes the actual system env).
305        let mut builder = reqwest::Client::builder()
306            .timeout(core::time::Duration::from_millis(self.timeout_ms))
307            .hickory_dns(!self.use_system_resolver)
308            .no_proxy();
309
310        let request_url = match self.url.scheme_str() {
311            // HTTPS endpoints: route reqwest through the same TLS configuration
312            // as the hyper connector, so the compromised-key distrust check and
313            // the selected crypto provider apply to both clients. Without this,
314            // reqwest would build its own platform verifier, bypassing the
315            // distrust wrapper.
316            Some("https") => {
317                #[cfg(feature = "tls-core")]
318                {
319                    builder = builder
320                        .tls_backend_preconfigured(crate::connector::https::build_tls_config()?);
321                }
322                self.url.to_string()
323            }
324            // Plain-HTTP endpoints never negotiate TLS, so don't preconfigure a
325            // TLS backend: building the configuration eagerly loads the system
326            // CA roots, which fails in minimal container environments that have
327            // no CA certificates installed.
328            Some("http") => self.url.to_string(),
329
330            // File dump endpoint (debugging) - uses platform-specific local transport
331            Some("file") => {
332                let output_path = decode_uri_path_in_authority(&self.url)
333                    .context("Failed to decode file path from URI")?;
334                let socket_or_pipe_path = crate::dump_server::spawn_dump_server(output_path)?;
335
336                // Configure the client to use the local socket/pipe
337                #[cfg(unix)]
338                {
339                    builder = builder.unix_socket(socket_or_pipe_path);
340                }
341                #[cfg(windows)]
342                {
343                    builder = builder
344                        .windows_named_pipe(socket_or_pipe_path.to_string_lossy().to_string());
345                }
346
347                "http://localhost/".to_string()
348            }
349
350            // Unix domain sockets
351            #[cfg(unix)]
352            Some("unix") => {
353                use crate::connector::uds::socket_path_from_uri;
354                let socket_path = socket_path_from_uri(&self.url)?;
355                builder = builder.unix_socket(socket_path);
356                format!("http://localhost{}", self.url.path())
357            }
358
359            // Windows named pipes
360            #[cfg(windows)]
361            Some("windows") => {
362                use crate::connector::named_pipe::named_pipe_path_from_uri;
363                let pipe_path = named_pipe_path_from_uri(&self.url)?;
364                builder = builder.windows_named_pipe(pipe_path.to_string_lossy().to_string());
365                format!("http://localhost{}", self.url.path())
366            }
367
368            // Unsupported schemes
369            scheme => anyhow::bail!("Unsupported endpoint scheme: {:?}", scheme),
370        };
371
372        Ok((builder, request_url))
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::parse_uri;
379
380    /// A scheme prefix with an empty path produces an empty (and therefore
381    /// dropped) authority. parsing must reject these as malformed rather
382    /// than accept them.
383    #[test]
384    fn empty_authority_uris_are_rejected() {
385        for input in ["unix://", "windows:", "file://"] {
386            let result = parse_uri(input);
387            assert!(
388                result.is_err(),
389                "expected {input:?} to be rejected, got {result:?}"
390            );
391        }
392    }
393}