1use merry_runtime::{ProcessActionIntent, ProcessRunnerError};
2use std::{
3 env,
4 ffi::{OsStr, OsString},
5 path::{Path, PathBuf},
6};
7
8pub(super) const ACTION_SANDBOX_PATH_FALLBACK: &str = "/usr/local/bin:/usr/bin:/bin";
9
10#[must_use]
19pub fn action_process_path() -> OsString {
20 env::var_os("PATH")
21 .filter(|value| !value.is_empty())
22 .unwrap_or_else(|| OsString::from(ACTION_SANDBOX_PATH_FALLBACK))
23}
24
25pub(super) fn validate_os_string(value: &OsStr, label: &str) -> Result<(), ProcessRunnerError> {
26 let Some(value) = value.to_str() else {
27 return Err(ProcessRunnerError::infrastructure(format!(
28 "{label} must be valid UTF-8"
29 )));
30 };
31 if value.contains('\0') {
32 return Err(ProcessRunnerError::infrastructure(format!(
33 "{label} must not contain NUL"
34 )));
35 }
36 Ok(())
37}
38
39pub(super) fn validate_environment_name(name: &OsStr) -> Result<(), ProcessRunnerError> {
40 validate_os_string(name, "sandbox process environment name")?;
41 let name = name.to_str().ok_or_else(|| {
42 ProcessRunnerError::infrastructure("sandbox process environment name must be valid UTF-8")
43 })?;
44 let mut characters = name.chars();
45 let Some(first) = characters.next() else {
46 return Err(ProcessRunnerError::infrastructure(
47 "sandbox process environment name must not be empty",
48 ));
49 };
50 if !(first == '_' || first.is_ascii_alphabetic())
51 || !characters.all(|character| character == '_' || character.is_ascii_alphanumeric())
52 {
53 return Err(ProcessRunnerError::infrastructure(
54 "sandbox process environment names must use ASCII letters, digits, and underscores",
55 ));
56 }
57 Ok(())
58}
59
60pub(crate) fn process_current_dir(
61 cwd_root: Option<&Path>,
62 intent: &ProcessActionIntent,
63) -> PathBuf {
64 let cwd = intent.cwd().unwrap_or(".");
65 let Some(root) = cwd_root else {
66 return PathBuf::from(cwd);
67 };
68 if cwd == "." {
69 root.to_path_buf()
70 } else {
71 root.join(cwd)
72 }
73}
74
75#[cfg(any(target_os = "linux", target_os = "macos"))]
76pub use sandbox::WorkspaceProcessEnvironment;
77
78#[cfg(any(target_os = "linux", target_os = "macos"))]
79mod sandbox {
80 use super::{action_process_path, validate_environment_name, validate_os_string};
81 use merry_runtime::{HostIntegration, ProcessRunnerError};
82 use std::{
83 env,
84 ffi::{OsStr, OsString},
85 fs,
86 path::{Component, Path, PathBuf},
87 };
88
89 pub(in crate::process_runner) const ACTION_SANDBOX_HOME_FALLBACK: &str = "/home/merry";
90 pub(in crate::process_runner) const ACTION_SANDBOX_TMPDIR: &str = "/tmp";
91
92 #[derive(Debug, Clone, PartialEq, Eq)]
98 pub struct WorkspaceProcessEnvironment {
99 pub(in crate::process_runner) path: OsString,
100 pub(in crate::process_runner) home: PathBuf,
101 pub(in crate::process_runner) tmp_source: PathBuf,
102 pub(in crate::process_runner) overrides: Vec<(OsString, OsString)>,
103 pub(in crate::process_runner) host_integrations: Vec<HostIntegration>,
104 pub(in crate::process_runner) ssh_agent_socket: Option<PathBuf>,
105 pub(in crate::process_runner) session_bus_address: Option<OsString>,
106 pub(in crate::process_runner) gpg_agent_sockets: Option<crate::GpgAgentSockets>,
107 }
108
109 #[derive(Debug, Clone, PartialEq, Eq)]
116 pub(in crate::process_runner) struct HostIntegrationBinding {
117 pub(in crate::process_runner) integration: HostIntegration,
118 pub(in crate::process_runner) socket: PathBuf,
119 pub(in crate::process_runner) environment_value: Option<OsString>,
120 }
121
122 impl WorkspaceProcessEnvironment {
123 #[must_use]
129 pub fn from_current_process() -> Self {
130 let path = action_process_path();
131 let home = merry_core::host_paths::user_home_dir()
132 .unwrap_or_else(|| absolute_env_path("HOME", ACTION_SANDBOX_HOME_FALLBACK));
133 let tmp_source = if cfg!(windows) {
134 merry_core::host_paths::simplify_verbatim_path(&env::temp_dir())
135 } else {
136 absolute_env_path("TMPDIR", ACTION_SANDBOX_TMPDIR)
137 };
138 Self {
139 path,
140 home,
141 tmp_source,
142 overrides: Vec::new(),
143 host_integrations: Vec::new(),
144 ssh_agent_socket: env::var_os("SSH_AUTH_SOCK").map(PathBuf::from),
145 session_bus_address: env::var_os("DBUS_SESSION_BUS_ADDRESS"),
146 gpg_agent_sockets: None,
147 }
148 }
149
150 pub fn new(
152 path: impl Into<OsString>,
153 home: impl Into<PathBuf>,
154 tmp_source: impl Into<PathBuf>,
155 ) -> Result<Self, ProcessRunnerError> {
156 let path = path.into();
157 let home = home.into();
158 let tmp_source = tmp_source.into();
159 if path.is_empty() {
160 return Err(ProcessRunnerError::infrastructure(
161 "sandbox process PATH must not be empty",
162 ));
163 }
164 validate_os_string(&path, "sandbox process PATH")?;
165 validate_clean_absolute_path(&home, "sandbox process HOME")?;
166 validate_clean_absolute_path(&tmp_source, "sandbox process temporary directory")?;
167 Ok(Self {
168 path,
169 home,
170 tmp_source,
171 overrides: Vec::new(),
172 host_integrations: Vec::new(),
173 ssh_agent_socket: env::var_os("SSH_AUTH_SOCK").map(PathBuf::from),
174 session_bus_address: env::var_os("DBUS_SESSION_BUS_ADDRESS"),
175 gpg_agent_sockets: None,
176 })
177 }
178
179 pub fn with_overrides(
181 mut self,
182 overrides: impl IntoIterator<Item = (OsString, OsString)>,
183 ) -> Result<Self, ProcessRunnerError> {
184 let mut names = std::collections::BTreeSet::new();
185 let mut validated = Vec::new();
186 for (name, value) in overrides {
187 validate_environment_name(&name)?;
188 validate_os_string(&value, "sandbox process environment value")?;
189 if !names.insert(name.clone()) {
190 return Err(ProcessRunnerError::infrastructure(
191 "sandbox process environment contains a duplicate variable",
192 ));
193 }
194 validated.push((name, value));
195 }
196 self.overrides = validated;
197 Ok(self)
198 }
199
200 #[must_use]
202 pub fn with_gpg_agent_sockets(mut self, sockets: crate::GpgAgentSockets) -> Self {
203 self.gpg_agent_sockets = Some(sockets);
204 self
205 }
206
207 pub(crate) fn gpg_client(&self) -> Option<&crate::GpgAgentSockets> {
208 self.gpg_agent_sockets
209 .as_ref()
210 .filter(|_| self.host_integrations.contains(&HostIntegration::GpgAgent))
211 }
212
213 pub(crate) fn path_value(&self) -> &OsStr {
214 &self.path
215 }
216
217 pub(crate) fn home_path(&self) -> &Path {
218 &self.home
219 }
220
221 pub(crate) fn temporary_directory(&self) -> &Path {
222 &self.tmp_source
223 }
224
225 pub(crate) fn environment_overrides(&self) -> &[(OsString, OsString)] {
226 &self.overrides
227 }
228
229 pub(crate) fn integration_enabled(&self, integration: HostIntegration) -> bool {
230 self.host_integrations.contains(&integration)
231 }
232
233 pub(crate) fn sandbox_socket_paths(&self) -> Vec<PathBuf> {
235 let mut paths = self
236 .host_integration_bindings()
237 .into_iter()
238 .map(|binding| binding.socket)
239 .collect::<Vec<_>>();
240 if let Some(sockets) = self.gpg_client() {
241 paths.extend(sockets.paths().map(Path::to_path_buf));
242 }
243 paths
244 }
245
246 pub(crate) fn ssh_known_hosts_paths(&self) -> Vec<PathBuf> {
248 if !self.integration_enabled(HostIntegration::SshAgent) {
249 return Vec::new();
250 }
251 crate::ssh_known_hosts(&self.home)
252 .into_iter()
253 .filter(|path| path.exists())
254 .collect()
255 }
256
257 pub(crate) fn gpg_public_keyrings(&self) -> Vec<PathBuf> {
259 self.gpg_client()
260 .map(|sockets| {
261 sockets
262 .public_keyrings()
263 .filter(|path| path.exists())
264 .collect()
265 })
266 .unwrap_or_default()
267 }
268
269 pub(crate) fn integration_environment(&self) -> Vec<(String, String)> {
271 let mut pairs = Vec::new();
272 for binding in self.host_integration_bindings() {
273 let Some(value) = integration_environment_value(&binding) else {
274 continue;
275 };
276 pairs.push(value);
277 }
278 pairs
279 }
280
281 pub fn with_ssh_agent_socket(
283 mut self,
284 path: impl Into<PathBuf>,
285 ) -> Result<Self, ProcessRunnerError> {
286 let path = path.into();
287 validate_clean_absolute_path(&path, "SSH agent socket")?;
288 self.ssh_agent_socket = Some(path);
289 Ok(self)
290 }
291
292 #[must_use]
294 pub fn with_host_integrations(
295 mut self,
296 integrations: impl IntoIterator<Item = HostIntegration>,
297 ) -> Self {
298 self.host_integrations.extend(integrations);
299 self.host_integrations.sort_unstable();
300 self.host_integrations.dedup();
301 self
302 }
303
304 pub fn validate_for_workspace(
310 &self,
311 workspace_root: &Path,
312 ) -> Result<Self, ProcessRunnerError> {
313 validate_clean_absolute_path(workspace_root, "action workspace root")?;
314 validate_clean_absolute_path(&self.home, "sandbox process HOME")?;
315 if self.home == Path::new("/")
316 || self.home == Path::new("/home")
317 || self.home == Path::new("/Users")
318 {
319 return Err(ProcessRunnerError::infrastructure(
320 "sandbox process HOME must identify a user directory",
321 ));
322 }
323 validate_clean_absolute_path(&self.tmp_source, "sandbox process temporary directory")?;
324 if self.tmp_source == Path::new("/") {
325 return Err(ProcessRunnerError::infrastructure(
326 "sandbox process temporary directory must not be the filesystem root",
327 ));
328 }
329 let tmp_source = fs::canonicalize(&self.tmp_source).map_err(|source| {
330 ProcessRunnerError::infrastructure(format!(
331 "failed to resolve sandbox process temporary directory: {source}"
332 ))
333 })?;
334 if !tmp_source.is_dir() {
335 return Err(ProcessRunnerError::infrastructure(
336 "sandbox process temporary directory must be a directory",
337 ));
338 }
339 if !is_supported_temp_path(&tmp_source) {
340 return Err(ProcessRunnerError::infrastructure(
341 "sandbox process TMPDIR must resolve under /tmp, /var/tmp, /dev/shm, a macOS per-user temporary directory, or a runtime temporary subdirectory",
342 ));
343 }
344
345 let mut validated = self.clone();
346 validated.tmp_source = tmp_source;
347 Ok(validated)
348 }
349
350 pub(in crate::process_runner) fn validate_requested_host_integrations(
351 &self,
352 integrations: &[HostIntegration],
353 ) -> Result<(), ProcessRunnerError> {
354 for integration in integrations {
355 let available = match integration {
356 HostIntegration::SshAgent => self
357 .ssh_agent_socket
358 .as_ref()
359 .is_some_and(|path| is_clean_absolute_path(path)),
360 HostIntegration::SessionBus => self
361 .session_bus_address
362 .as_ref()
363 .and_then(|address| session_bus_socket_path(address))
364 .is_some_and(|path| is_clean_absolute_path(&path)),
365 HostIntegration::GpgAgent => self.gpg_agent_sockets.is_some(),
366 };
367 if !available {
368 return Err(ProcessRunnerError::infrastructure(format!(
369 "host integration `{}` is not available in the current sandbox environment",
370 integration.as_str()
371 )));
372 }
373 }
374 for binding in self
375 .host_integration_candidates()
376 .into_iter()
377 .filter(|binding| integrations.contains(&binding.integration))
378 {
379 validate_host_socket(&binding.socket)?;
380 }
381 Ok(())
382 }
383
384 pub(in crate::process_runner) fn host_integration_candidates(
387 &self,
388 ) -> Vec<HostIntegrationBinding> {
389 let mut candidates = Vec::new();
390 if let Some(path) = self
391 .ssh_agent_socket
392 .as_ref()
393 .filter(|path| is_clean_absolute_path(path))
394 {
395 candidates.push(HostIntegrationBinding {
396 integration: HostIntegration::SshAgent,
397 socket: path.clone(),
398 environment_value: None,
399 });
400 }
401 if let Some((socket, address)) = self
402 .session_bus_address
403 .as_ref()
404 .and_then(|address| {
405 session_bus_socket_path(address).map(|socket| (socket, address))
406 })
407 .filter(|(socket, _)| is_clean_absolute_path(socket))
408 {
409 candidates.push(HostIntegrationBinding {
410 integration: HostIntegration::SessionBus,
411 socket,
412 environment_value: Some(address.clone()),
413 });
414 }
415 if let Some(sockets) = &self.gpg_agent_sockets {
416 candidates.push(HostIntegrationBinding {
417 integration: HostIntegration::GpgAgent,
418 socket: sockets.agent().to_path_buf(),
419 environment_value: Some(sockets.home().as_os_str().to_owned()),
420 });
421 }
422 candidates
423 }
424
425 pub(in crate::process_runner) fn host_integration_bindings(
429 &self,
430 ) -> Vec<HostIntegrationBinding> {
431 self.host_integration_candidates()
432 .into_iter()
433 .filter(|binding| {
434 self.host_integrations.contains(&binding.integration)
435 && validate_host_socket(&binding.socket).is_ok()
436 })
437 .collect()
438 }
439 }
440
441 fn integration_environment_value(binding: &HostIntegrationBinding) -> Option<(String, String)> {
442 match binding.integration {
443 HostIntegration::SshAgent => binding
444 .socket
445 .to_str()
446 .map(|path| ("SSH_AUTH_SOCK".to_owned(), path.to_owned())),
447 HostIntegration::SessionBus => binding
448 .environment_value
449 .as_ref()
450 .and_then(|value| value.to_str())
451 .map(|value| ("DBUS_SESSION_BUS_ADDRESS".to_owned(), value.to_owned())),
452 HostIntegration::GpgAgent => binding
453 .environment_value
454 .as_ref()
455 .and_then(|value| value.to_str())
456 .map(|value| ("GNUPGHOME".to_owned(), value.to_owned())),
457 }
458 }
459
460 fn validate_host_socket(path: &Path) -> Result<(), ProcessRunnerError> {
461 #[cfg(unix)]
462 {
463 let metadata = crate::HostPathMetadata::inspect(path).map_err(|error| {
464 ProcessRunnerError::infrastructure(format!(
465 "host integration socket `{}` is unavailable: {error}",
466 path.display()
467 ))
468 })?;
469 let current_uid = rustix::process::getuid().as_raw();
470 if !metadata.is_owned_socket(current_uid) {
471 return Err(ProcessRunnerError::infrastructure(format!(
472 "host integration `{}` must be a socket owned by the current user",
473 path.display()
474 )));
475 }
476 }
477 Ok(())
478 }
479
480 fn validate_clean_absolute_path(path: &Path, label: &str) -> Result<(), ProcessRunnerError> {
481 let Some(value) = path.to_str() else {
482 return Err(ProcessRunnerError::infrastructure(format!(
483 "{label} must be valid UTF-8"
484 )));
485 };
486 if value.contains('\0') {
487 return Err(ProcessRunnerError::infrastructure(format!(
488 "{label} must not contain NUL"
489 )));
490 }
491 if !merry_core::host_paths::is_clean_absolute_path(path) {
492 return Err(ProcessRunnerError::infrastructure(format!(
493 "{label} must be a clean absolute path"
494 )));
495 }
496 Ok(())
497 }
498
499 fn is_clean_absolute_path(path: &Path) -> bool {
500 merry_core::host_paths::is_clean_absolute_path(path)
501 }
502
503 fn session_bus_socket_path(address: &OsStr) -> Option<PathBuf> {
504 let address = address.to_str()?;
505 address.split(';').find_map(|candidate| {
506 let options = candidate.strip_prefix("unix:")?;
507 options.split(',').find_map(|option| {
508 let (name, value) = option.split_once('=')?;
509 (name == "path").then(|| PathBuf::from(value))
510 })
511 })
512 }
513
514 fn is_supported_temp_path(path: &Path) -> bool {
515 is_supported_temp_path_for(
516 path,
517 cfg!(target_os = "macos"),
518 env::var_os("XDG_RUNTIME_DIR").as_deref(),
519 )
520 }
521
522 fn is_supported_temp_path_for(
523 path: &Path,
524 allow_macos_temp_roots: bool,
525 xdg_runtime_dir: Option<&OsStr>,
526 ) -> bool {
527 is_standard_temp_path(path)
528 || (allow_macos_temp_roots && is_macos_temp_path(path))
529 || xdg_runtime_dir
530 .map(PathBuf::from)
531 .filter(|root| {
532 root != path
533 && root.is_absolute()
534 && root.components().all(|component| {
535 matches!(component, Component::RootDir | Component::Normal(_))
536 })
537 })
538 .is_some_and(|root| path.starts_with(root))
539 }
540
541 fn is_standard_temp_path(path: &Path) -> bool {
542 [
543 Path::new("/tmp"),
544 Path::new("/var/tmp"),
545 Path::new("/dev/shm"),
546 ]
547 .into_iter()
548 .any(|root| path == root || path.starts_with(root))
549 }
550
551 fn is_macos_temp_path(path: &Path) -> bool {
557 if [Path::new("/private/tmp"), Path::new("/private/var/tmp")]
558 .into_iter()
559 .any(|root| path == root || path.starts_with(root))
560 {
561 return true;
562 }
563 let mut components = path.components();
564 if !matches!(components.next(), Some(Component::RootDir)) {
565 return false;
566 }
567 let is_literal = |component: Option<Component<'_>>, expected: &str| matches!(component, Some(Component::Normal(value)) if value == OsStr::new(expected));
568 let is_non_empty = |component: Option<Component<'_>>| matches!(component, Some(Component::Normal(value)) if !value.is_empty());
569 if !is_literal(components.next(), "private")
570 || !is_literal(components.next(), "var")
571 || !is_literal(components.next(), "folders")
572 || !is_non_empty(components.next())
573 || !is_non_empty(components.next())
574 || !is_literal(components.next(), "T")
575 {
576 return false;
577 }
578 components.all(|component| matches!(component, Component::Normal(_)))
579 }
580
581 fn absolute_env_path(name: &str, fallback: &str) -> PathBuf {
582 env::var_os(name)
583 .map(PathBuf::from)
584 .filter(|path| path.is_absolute())
585 .unwrap_or_else(|| PathBuf::from(fallback))
586 }
587
588 #[cfg(test)]
589 mod tests {
590 use super::{is_macos_temp_path, is_supported_temp_path_for};
591 use std::{ffi::OsStr, path::Path};
592
593 #[test]
594 fn macos_temp_paths_accept_private_tmp_var_tmp_and_darwin_user_temp_dirs() {
595 for valid in [
596 "/private/tmp",
597 "/private/tmp/merry-sub",
598 "/private/var/tmp",
599 "/private/var/tmp/nested/dir",
600 "/private/var/folders/pp/tfktnmsx7dx1xcbx05v7rzn40000gn/T",
601 "/private/var/folders/pp/tfktnmsx7dx1xcbx05v7rzn40000gn/T/merry-work",
602 ] {
603 let path = Path::new(valid);
604 assert!(
605 is_macos_temp_path(path),
606 "expected macOS temp path: {valid}"
607 );
608 assert!(
609 is_supported_temp_path_for(path, true, None),
610 "expected supported on macOS: {valid}"
611 );
612 assert!(
613 !is_supported_temp_path_for(path, false, None),
614 "macOS-only root must not be accepted on non-macOS hosts: {valid}"
615 );
616 }
617 }
618
619 #[test]
620 fn macos_temp_paths_reject_cache_user_root_and_arbitrary_directories() {
621 for invalid in [
622 "/private",
623 "/private/var",
624 "/private/var/folders",
625 "/private/var/folders/pp",
626 "/private/var/folders/pp/tfktnmsx7dx1xcbx05v7rzn40000gn",
627 "/private/var/folders/pp/tfktnmsx7dx1xcbx05v7rzn40000gn/C",
628 "/private/var/folders/pp/tfktnmsx7dx1xcbx05v7rzn40000gn/0",
629 "/Users/alice",
630 "/Users/alice/tmp",
631 ] {
632 let path = Path::new(invalid);
633 assert!(
634 !is_macos_temp_path(path),
635 "unexpectedly accepted macOS temp path: {invalid}"
636 );
637 assert!(
638 !is_supported_temp_path_for(path, true, Some(OsStr::new("/run/user/1000"))),
639 "unexpectedly accepted path: {invalid}"
640 );
641 }
642 }
643
644 #[cfg(unix)]
645 #[test]
646 fn standard_and_xdg_runtime_temp_paths_remain_supported() {
647 assert!(is_supported_temp_path_for(Path::new("/tmp"), false, None));
648 assert!(is_supported_temp_path_for(
649 Path::new("/var/tmp/work"),
650 false,
651 None
652 ));
653 assert!(is_supported_temp_path_for(
654 Path::new("/run/user/1000/merry-tmp"),
655 false,
656 Some(OsStr::new("/run/user/1000"))
657 ));
658 assert!(!is_supported_temp_path_for(
659 Path::new("/run/user/1000"),
660 false,
661 Some(OsStr::new("/run/user/1000"))
662 ));
663 }
664 }
665}