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