Skip to main content

datadog_agent_commons/ipc/
config.rs

1//! IPC configuration.
2
3use std::{
4    net::{IpAddr, SocketAddr},
5    path::{Path, PathBuf},
6};
7
8use saluki_error::{generic_error, GenericError};
9use tonic::transport::Uri;
10#[cfg(not(target_os = "linux"))]
11use tracing::warn;
12
13use crate::platform::PlatformSettings;
14
15/// Datadog Agent IPC bearer-token and exact shared-certificate mTLS configuration.
16#[derive(Clone, Debug)]
17pub struct IpcAuthConfiguration {
18    /// Path to the Agent authentication token file.
19    ///
20    /// The contents of the file are passed as a bearer token in RPC requests to the IPC endpoint.
21    ///
22    /// Defaults to `<conf dir>/auth_token`, where `<conf dir>` is the platform-specific directory containing the Agent
23    /// configuration.
24    auth_token_file_path: PathBuf,
25
26    /// Path to the shared Agent IPC mTLS identity file.
27    ///
28    /// The PEM file contains one certificate and its private key. IPC peers require exact leaf-certificate DER equality
29    /// rather than CA-based trust, and each peer proves possession of the corresponding private key during the TLS
30    /// handshake. The same identity authenticates both the client and server, so a CA chain cannot broaden it.
31    ///
32    /// Defaults to `ipc_cert.pem` in the same directory as the Agent authentication token file. (for example, if
33    /// `auth_token_file_path` is `/etc/datadog-agent/auth_token`, this will be `/etc/datadog-agent/ipc_cert.pem`.)
34    ipc_cert_file_path: PathBuf,
35}
36
37impl IpcAuthConfiguration {
38    /// Creates an `IpcAuthConfiguration`, resolving empty paths to Agent defaults.
39    ///
40    /// An empty token path selects the platform-specific token path. An empty certificate path selects `ipc_cert.pem`
41    /// beside the resolved token, or in the platform configuration directory when the token has no parent.
42    pub fn new(mut auth_token_file_path: PathBuf, mut ipc_cert_file_path: PathBuf) -> Self {
43        if auth_token_file_path.as_os_str().is_empty() {
44            auth_token_file_path = PlatformSettings::get_auth_token_path();
45        }
46
47        if ipc_cert_file_path.as_os_str().is_empty() {
48            let auth_token_dir = auth_token_file_path
49                .parent()
50                .unwrap_or(PlatformSettings::get_config_dir_path());
51            ipc_cert_file_path = auth_token_dir.join(PlatformSettings::get_ipc_cert_filename());
52        }
53
54        Self {
55            auth_token_file_path,
56            ipc_cert_file_path,
57        }
58    }
59
60    /// Gets the path to the Agent authentication token file from the configuration.
61    pub fn auth_token_file_path(&self) -> &Path {
62        &self.auth_token_file_path
63    }
64
65    /// Gets the shared IPC mTLS identity file path from the configuration.
66    pub fn ipc_cert_file_path(&self) -> &Path {
67        &self.ipc_cert_file_path
68    }
69}
70
71/// Datadog Agent IPC client configuration.
72#[derive(Clone, Debug)]
73pub struct RemoteAgentClientConfiguration {
74    /// Core Agent CMD API host used for remote-agent gRPC IPC. Always `localhost` or a loopback address.
75    pub cmd_host: IpcHost,
76
77    /// Core Agent CMD API port used for remote-agent gRPC IPC.
78    pub cmd_port: u16,
79
80    /// Authentication configuration for the IPC endpoint.
81    pub auth: IpcAuthConfiguration,
82
83    /// Maximum message size for gRPC messages.
84    pub grpc_max_message_size: usize,
85
86    /// Resolved CID for connecting to the Agent IPC endpoint via AF_VSOCK.
87    #[cfg(target_os = "linux")]
88    pub vsock_cid: Option<u32>,
89}
90
91impl RemoteAgentClientConfiguration {
92    /// Creates a `RemoteAgentClientConfiguration` from its parts, validating the CMD API host and resolving the named
93    /// vsock address to a CID.
94    ///
95    /// `cmd_host` follows the Datadog Agent's `cmd_host` setting. Like the Datadog Agent, the host must be `localhost`
96    /// or a loopback IP address: an IPv4 address in `127.0.0.0/8`, or `::1`. Also like the Datadog Agent's own IPC
97    /// clients, `localhost` is resolved when connecting, so ADP reaches the CMD API whether the Agent listens on IPv4
98    /// or IPv6 loopback. See [`IpcHost::Localhost`].
99    ///
100    /// `vsock_addr` follows the Datadog Agent's `vsock_addr` setting: an empty value disables vsock, and `host`,
101    /// `hypervisor`, and `local` select the well-known context identifiers 2, 0, and 3. vsock is only supported on
102    /// Linux; on other platforms, a non-empty value is ignored with a warning.
103    ///
104    /// # Errors
105    ///
106    /// Returns an error if `cmd_host` isn't `localhost` or a loopback IP address. On Linux, also returns an error if
107    /// `vsock_addr` is not empty and is not one of the supported names.
108    pub fn from_parts(
109        cmd_host: &str, cmd_port: u16, auth: IpcAuthConfiguration, grpc_max_message_size: usize, vsock_addr: &str,
110    ) -> Result<Self, GenericError> {
111        let cmd_host = parse_cmd_host(cmd_host)?;
112
113        #[cfg(target_os = "linux")]
114        let vsock_cid = match vsock_addr {
115            "" => None,
116            "host" => Some(2),
117            "hypervisor" => Some(0),
118            "local" => Some(3),
119            other => {
120                return Err(generic_error!(
121                    "invalid vsock address '{}'; expected one of: host, hypervisor, local",
122                    other
123                ))
124            }
125        };
126
127        #[cfg(not(target_os = "linux"))]
128        if !vsock_addr.is_empty() {
129            warn!("`vsock_addr` is configured but vsock is only supported on Linux. Setting will be ignored.");
130        }
131
132        Ok(Self {
133            cmd_host,
134            cmd_port,
135            auth,
136            grpc_max_message_size,
137            #[cfg(target_os = "linux")]
138            vsock_cid,
139        })
140    }
141
142    /// Returns the Core Agent CMD API gRPC endpoint URI.
143    pub fn endpoint(&self) -> Uri {
144        let authority = match self.cmd_host {
145            IpcHost::Localhost => format!("localhost:{}", self.cmd_port),
146            // `SocketAddr` brackets an IPv6 host, as a URI requires.
147            IpcHost::Ip(ip) => SocketAddr::new(ip, self.cmd_port).to_string(),
148        };
149        format!("https://{}", authority)
150            .parse()
151            .expect("a URI built from `localhost` or an IP address and a u16 port is valid")
152    }
153
154    /// Returns the vsock address to use for connecting to the IPC endpoint, if configured.
155    #[cfg(target_os = "linux")]
156    pub fn vsock_addr(&self) -> Option<tokio_vsock::VsockAddr> {
157        self.vsock_cid
158            .map(|cid| tokio_vsock::VsockAddr::new(cid, u32::from(self.cmd_port)))
159    }
160}
161
162/// Parses a CMD API host into the loopback address to connect to.
163fn parse_cmd_host(cmd_host: &str) -> Result<IpcHost, GenericError> {
164    if cmd_host == "localhost" {
165        return Ok(IpcHost::Localhost);
166    }
167
168    let ip = cmd_host
169        .parse::<IpAddr>()
170        .map_err(|_| {
171            generic_error!(
172                "invalid IPC host '{}'; expected `localhost` or a loopback IP address",
173                cmd_host
174            )
175        })?
176        // Treat an IPv4-mapped IPv6 address (for example, `::ffff:127.0.0.1`) as the IPv4 address it maps to.
177        .to_canonical();
178    if !ip.is_loopback() {
179        return Err(generic_error!(
180            "IPC host '{}' isn't a loopback address; expected `localhost`, an IPv4 address in 127.0.0.0/8, or ::1",
181            cmd_host
182        ));
183    }
184
185    Ok(IpcHost::Ip(ip))
186}
187
188/// The Core Agent CMD API host.
189#[derive(Clone, Copy, Debug, Eq, PartialEq)]
190pub enum IpcHost {
191    /// `localhost`, which is resolved when connecting, as the Datadog Agent's own IPC clients do.
192    ///
193    /// Each address `localhost` resolves to is tried in turn, so ADP reaches the CMD API whether the Datadog Agent
194    /// listens on IPv4 or IPv6 loopback. The name is resolved through the system resolver, which answers it from the
195    /// hosts file, so this doesn't need a DNS server.
196    Localhost,
197
198    /// A loopback IP address: an IPv4 address in `127.0.0.0/8`, or `::1`.
199    Ip(IpAddr),
200}
201
202#[cfg(test)]
203mod tests {
204    use std::{
205        net::{IpAddr, Ipv4Addr},
206        path::{Path, PathBuf},
207    };
208
209    use super::{IpcAuthConfiguration, IpcHost, RemoteAgentClientConfiguration};
210    use crate::platform::PlatformSettings;
211
212    #[test]
213    fn ipc_cert_file_path_empty_config() {
214        let default_auth_token_path = PlatformSettings::get_auth_token_path();
215
216        // When the auth token file path _and_ IPC cert file path are both unset, we should default to looking for the
217        // IPC cert in the same directory as the auth token.
218        let config = IpcAuthConfiguration::new(PathBuf::new(), PathBuf::new());
219        assert_eq!(config.auth_token_file_path(), default_auth_token_path);
220        assert_eq!(
221            config.ipc_cert_file_path().parent(),
222            default_auth_token_path.as_path().parent()
223        );
224        assert_eq!(
225            config.ipc_cert_file_path().file_name().map(Path::new),
226            Some(PlatformSettings::get_ipc_cert_filename())
227        );
228    }
229
230    #[test]
231    fn ipc_cert_file_path_defaults() {
232        let default_auth_token_path = PlatformSettings::get_auth_token_path();
233
234        // When the IPC cert file path is not set, it should default to the same directory as the auth token file using
235        // the default certificate file name.
236        let config = IpcAuthConfiguration::new(default_auth_token_path.clone(), PathBuf::new());
237        assert_eq!(
238            config.ipc_cert_file_path().parent(),
239            default_auth_token_path.as_path().parent()
240        );
241        assert_eq!(
242            config.ipc_cert_file_path().file_name().map(Path::new),
243            Some(PlatformSettings::get_ipc_cert_filename())
244        );
245    }
246
247    #[test]
248    fn ipc_cert_file_path_explicitly_set() {
249        let default_auth_token_path = PlatformSettings::get_auth_token_path();
250        let custom_ipc_cert_path = PathBuf::from("/tmp/custom_ipc_cert.pem");
251
252        // When the IPC cert file path is explicitly set, it should be used.
253        let config = IpcAuthConfiguration::new(default_auth_token_path, custom_ipc_cert_path.clone());
254        assert_eq!(custom_ipc_cert_path, config.ipc_cert_file_path());
255    }
256
257    #[test]
258    fn ipc_cert_file_path_custom_auth_token_path() {
259        let custom_auth_token_path = PathBuf::from("/secret/auth_token");
260
261        // When the IPC cert file path is not set, but there's a custom auth token path (explicitly set, different from the default),
262        // we should still look in the same directory as the auth token file using the default certificate file name.
263        let config = IpcAuthConfiguration::new(custom_auth_token_path.clone(), PathBuf::new());
264        assert_eq!(
265            config.ipc_cert_file_path().parent(),
266            custom_auth_token_path.as_path().parent()
267        );
268        assert_eq!(
269            config.ipc_cert_file_path().file_name().map(Path::new),
270            Some(PlatformSettings::get_ipc_cert_filename())
271        );
272    }
273
274    #[test]
275    fn ipc_cert_file_path_invalid_auth_token_path() {
276        let invalid_auth_token_path = PathBuf::from("/");
277
278        // If the auth token file path is somehow unset or invalid (for example, no parent directory), we should use the same
279        // logic but with the default Datadog Agent configuration directory.
280        let config = IpcAuthConfiguration::new(invalid_auth_token_path, PathBuf::new());
281        assert_eq!(
282            config.ipc_cert_file_path().parent(),
283            Some(PlatformSettings::get_config_dir_path())
284        );
285        assert_eq!(
286            config.ipc_cert_file_path().file_name().map(Path::new),
287            Some(PlatformSettings::get_ipc_cert_filename())
288        );
289    }
290
291    fn remote_agent_config(cmd_port: u16) -> RemoteAgentClientConfiguration {
292        RemoteAgentClientConfiguration {
293            cmd_host: IpcHost::Ip(IpAddr::V4(Ipv4Addr::LOCALHOST)),
294            cmd_port,
295            auth: IpcAuthConfiguration::new(PathBuf::new(), PathBuf::new()),
296            grpc_max_message_size: 128 * 1024 * 1024,
297            #[cfg(target_os = "linux")]
298            vsock_cid: None,
299        }
300    }
301
302    #[test]
303    fn endpoint_uses_cmd_port() {
304        for (cmd_port, expected) in [(5001, "https://127.0.0.1:5001/"), (7777, "https://127.0.0.1:7777/")] {
305            assert_eq!(remote_agent_config(cmd_port).endpoint().to_string(), expected);
306        }
307    }
308
309    #[test]
310    fn endpoint_uses_cmd_host() {
311        let cases = [
312            // Like the Datadog Agent's IPC clients, `localhost` is kept as a name and resolved when connecting.
313            ("localhost", "https://localhost:5001/"),
314            ("127.0.0.1", "https://127.0.0.1:5001/"),
315            ("127.0.0.2", "https://127.0.0.2:5001/"),
316            // IPv6 hosts are bracketed.
317            ("::1", "https://[::1]:5001/"),
318            // An IPv4-mapped IPv6 address is treated as the IPv4 address it maps to.
319            ("::ffff:127.0.0.1", "https://127.0.0.1:5001/"),
320        ];
321        for (cmd_host, expected) in cases {
322            let auth = IpcAuthConfiguration::new(PathBuf::new(), PathBuf::new());
323            let config = RemoteAgentClientConfiguration::from_parts(cmd_host, 5001, auth, 4 * 1024 * 1024, "")
324                .unwrap_or_else(|e| panic!("{cmd_host:?} should be a valid IPC host: {e}"));
325            assert_eq!(config.endpoint().to_string(), expected, "for {cmd_host:?}");
326        }
327    }
328
329    #[test]
330    fn from_parts_rejects_non_loopback_hosts() {
331        // Like the Datadog Agent, only `localhost` and loopback IP addresses are accepted.
332        for cmd_host in [
333            "",
334            "0.0.0.0",
335            "10.0.0.1",
336            "::",
337            "fe80::1",
338            "example.com",
339            "127.0.0.1:5001",
340        ] {
341            let auth = IpcAuthConfiguration::new(PathBuf::new(), PathBuf::new());
342            assert!(
343                RemoteAgentClientConfiguration::from_parts(cmd_host, 5001, auth, 4 * 1024 * 1024, "").is_err(),
344                "{cmd_host:?} should be rejected"
345            );
346        }
347    }
348
349    #[test]
350    fn from_parts_keeps_the_given_parts() {
351        let auth = IpcAuthConfiguration::new("/secret/auth_token".into(), "/secret/ipc_cert.pem".into());
352        let config = RemoteAgentClientConfiguration::from_parts("127.0.0.2", 5001, auth, 4 * 1024 * 1024, "")
353            .expect("a loopback host and an empty vsock address are valid");
354
355        assert_eq!(config.cmd_host, IpcHost::Ip(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))));
356        assert_eq!(config.cmd_port, 5001);
357        assert_eq!(config.grpc_max_message_size, 4 * 1024 * 1024);
358        assert_eq!(config.auth.auth_token_file_path(), Path::new("/secret/auth_token"));
359        assert_eq!(config.auth.ipc_cert_file_path(), Path::new("/secret/ipc_cert.pem"));
360    }
361
362    #[cfg(target_os = "linux")]
363    #[test]
364    fn from_parts_resolves_vsock_addresses() {
365        for (value, expected_cid) in [
366            ("", None),
367            ("host", Some(2)),
368            ("hypervisor", Some(0)),
369            ("local", Some(3)),
370        ] {
371            let auth = IpcAuthConfiguration::new(PathBuf::new(), PathBuf::new());
372            let config = RemoteAgentClientConfiguration::from_parts("localhost", 5001, auth, 4 * 1024 * 1024, value)
373                .expect("valid vsock address");
374            assert_eq!(config.vsock_cid, expected_cid, "input: {value:?}");
375        }
376    }
377
378    #[cfg(target_os = "linux")]
379    #[test]
380    fn from_parts_rejects_invalid_vsock_addresses() {
381        for value in ["invalid", "2", "HOST", "host ", "vm0"] {
382            let auth = IpcAuthConfiguration::new(PathBuf::new(), PathBuf::new());
383            assert!(
384                RemoteAgentClientConfiguration::from_parts("localhost", 5001, auth, 4 * 1024 * 1024, value).is_err(),
385                "expected error for input: {value:?}",
386            );
387        }
388    }
389
390    #[cfg(not(target_os = "linux"))]
391    #[test]
392    fn from_parts_ignores_vsock_addresses_off_linux() {
393        let auth = IpcAuthConfiguration::new(PathBuf::new(), PathBuf::new());
394        assert!(RemoteAgentClientConfiguration::from_parts("localhost", 5001, auth, 4 * 1024 * 1024, "host").is_ok());
395    }
396
397    #[cfg(target_os = "linux")]
398    #[test]
399    fn vsock_addr_uses_resolved_cid_and_cmd_port() {
400        let mut config = remote_agent_config(5001);
401        assert_eq!(config.vsock_addr(), None);
402
403        config.vsock_cid = Some(2);
404        let addr = config.vsock_addr().expect("vsock address should be configured");
405        assert_eq!(addr.cid(), 2);
406        assert_eq!(addr.port(), 5001);
407    }
408}