Skip to main content

merry_process/process_runner/
sandbox_execution.rs

1//! Sandboxed [`ProcessRunner`] execution for [`WorkspaceProcessRunner`].
2
3use super::{
4    background::BackgroundSupervisor, execution::run_spawned_process_with_stdin,
5    permissions::WorkspaceProcessRunner,
6};
7use crate::confinement::{self, SandboxLaunch};
8use merry_runtime::{
9    BackgroundProcessControl, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
10    ProcessRunnerError, ProcessRunnerFuture, ProcessRunnerOutput,
11};
12use std::{process::Stdio, sync::Arc};
13
14impl ProcessRunner for WorkspaceProcessRunner {
15    fn run<'a>(
16        &'a self,
17        intent: ProcessActionIntent,
18        context: ProcessRunnerContext,
19    ) -> ProcessRunnerFuture<'a> {
20        Box::pin(async move {
21            if context.cancellation_token().is_cancelled() {
22                return Err(ProcessRunnerError::Cancelled);
23            }
24            let runner = self.clone();
25            let plan_intent = intent.clone();
26            let launch = tokio::task::spawn_blocking(move || runner.plan_for(&plan_intent))
27                .await
28                .map_err(|error| {
29                    ProcessRunnerError::infrastructure(format!("sandbox planning failed: {error}"))
30                })??;
31            let background = self.background.clone();
32            run_sandbox_launch(launch, intent, context, background).await
33        })
34    }
35
36    fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
37        Some(Arc::new(self.background.clone()))
38    }
39}
40
41async fn run_sandbox_launch(
42    launch: SandboxLaunch,
43    intent: ProcessActionIntent,
44    context: ProcessRunnerContext,
45    background: BackgroundSupervisor,
46) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
47    if context.cancellation_token().is_cancelled() {
48        return Err(ProcessRunnerError::Cancelled);
49    }
50    // On macOS, invoke `/usr/bin/sandbox-exec` directly instead of re-execing
51    // the running `merry` binary. Overwriting the running binary on disk
52    // (for example `cp -p target/release/merry ~/.cargo/bin/merry`) invalidates
53    // its kernel code signature cache on macOS and causes any re-exec of
54    // `current_exe()` to die immediately with SIGKILL.
55    #[cfg(target_os = "macos")]
56    if confinement::explicit_helper_program().is_none() {
57        let command = confinement::direct_seatbelt_command(&launch);
58        return super::execution::run_spawned_process(
59            command,
60            intent,
61            context,
62            "/usr/bin/sandbox-exec".to_owned(),
63            background,
64        )
65        .await;
66    }
67    let helper = confinement::helper_program()?;
68    let policy_bytes = confinement::encode_policy(&launch)?;
69    let mut command = tokio::process::Command::new(&helper);
70    // Strip isolated environment variables (such as MERRY_* provider secrets)
71    // before spawning the helper so they never enter the helper process's
72    // environment or `/proc/<pid>/environ`.
73    for name in launch.remove_env() {
74        if name != confinement::helper_env_name() && name != confinement::policy_env_name() {
75            command.env_remove(name);
76        }
77    }
78    command
79        .env(confinement::helper_env_name(), "1")
80        .env(
81            confinement::policy_env_name(),
82            confinement::policy_stdin_sentinel(),
83        )
84        .stdin(Stdio::piped())
85        .stdout(Stdio::piped())
86        .stderr(Stdio::piped())
87        .kill_on_drop(true);
88    let backend_program = helper.to_string_lossy().into_owned();
89    run_spawned_process_with_stdin(
90        command,
91        Some(policy_bytes),
92        intent,
93        context,
94        backend_program,
95        background,
96    )
97    .await
98}