1use 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#[derive(Clone, Debug)]
17pub struct IpcAuthConfiguration {
18 auth_token_file_path: PathBuf,
25
26 ipc_cert_file_path: PathBuf,
35}
36
37impl IpcAuthConfiguration {
38 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 pub fn auth_token_file_path(&self) -> &Path {
62 &self.auth_token_file_path
63 }
64
65 pub fn ipc_cert_file_path(&self) -> &Path {
67 &self.ipc_cert_file_path
68 }
69}
70
71#[derive(Clone, Debug)]
73pub struct RemoteAgentClientConfiguration {
74 pub cmd_host: IpcHost,
76
77 pub cmd_port: u16,
79
80 pub auth: IpcAuthConfiguration,
82
83 pub grpc_max_message_size: usize,
85
86 #[cfg(target_os = "linux")]
88 pub vsock_cid: Option<u32>,
89}
90
91impl RemoteAgentClientConfiguration {
92 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 pub fn endpoint(&self) -> Uri {
144 let authority = match self.cmd_host {
145 IpcHost::Localhost => format!("localhost:{}", self.cmd_port),
146 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 #[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
162fn 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 .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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
190pub enum IpcHost {
191 Localhost,
197
198 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 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 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 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 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 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 ("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 ("::1", "https://[::1]:5001/"),
318 ("::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 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}