Skip to main content

merry_process/process_runner/
execution.rs

1use super::background::{self, BackgroundSupervisor};
2#[cfg(any(target_os = "linux", target_os = "macos"))]
3use super::permissions::WorkspaceProcessRunner;
4#[cfg(any(target_os = "linux", target_os = "macos"))]
5use crate::confinement::{self, SandboxLaunch};
6#[cfg(any(target_os = "linux", target_os = "macos"))]
7use merry_runtime::{BackgroundProcessControl, ProcessRunner, ProcessRunnerFuture};
8use merry_runtime::{
9    ProcessActionIntent, ProcessRunnerContext, ProcessRunnerError, ProcessRunnerOutput,
10};
11use std::io;
12#[cfg(any(target_os = "linux", target_os = "macos"))]
13use std::{process::Stdio, sync::Arc};
14#[cfg(any(target_os = "linux", target_os = "macos"))]
15use tokio::io::AsyncWriteExt;
16
17#[cfg(any(target_os = "linux", target_os = "macos"))]
18impl ProcessRunner for WorkspaceProcessRunner {
19    fn run<'a>(
20        &'a self,
21        intent: ProcessActionIntent,
22        context: ProcessRunnerContext,
23    ) -> ProcessRunnerFuture<'a> {
24        Box::pin(async move {
25            if context.cancellation_token().is_cancelled() {
26                return Err(ProcessRunnerError::Cancelled);
27            }
28            let runner = self.clone();
29            let plan_intent = intent.clone();
30            let launch = tokio::task::spawn_blocking(move || runner.plan_for(&plan_intent))
31                .await
32                .map_err(|error| {
33                    ProcessRunnerError::infrastructure(format!("sandbox planning failed: {error}"))
34                })??;
35            let background = self.background.clone();
36            run_sandbox_launch(launch, intent, context, background).await
37        })
38    }
39
40    fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
41        Some(Arc::new(self.background.clone()))
42    }
43}
44
45#[cfg(any(target_os = "linux", target_os = "macos"))]
46async fn run_sandbox_launch(
47    launch: SandboxLaunch,
48    intent: ProcessActionIntent,
49    context: ProcessRunnerContext,
50    background: BackgroundSupervisor,
51) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
52    if context.cancellation_token().is_cancelled() {
53        return Err(ProcessRunnerError::Cancelled);
54    }
55    // On macOS, invoke `/usr/bin/sandbox-exec` directly instead of re-execing
56    // the running `merry` binary. Overwriting the running binary on disk
57    // (for example `cp -p target/release/merry ~/.cargo/bin/merry`) invalidates
58    // its kernel code signature cache on macOS and causes any re-exec of
59    // `current_exe()` to die immediately with SIGKILL.
60    #[cfg(target_os = "macos")]
61    if confinement::explicit_helper_program().is_none() {
62        let command = confinement::direct_seatbelt_command(&launch);
63        return run_spawned_process(
64            command,
65            intent,
66            context,
67            "/usr/bin/sandbox-exec".to_owned(),
68            background,
69        )
70        .await;
71    }
72    let helper = confinement::helper_program()?;
73    let policy_bytes = confinement::encode_policy(&launch)?;
74    let mut command = tokio::process::Command::new(&helper);
75    // Strip isolated environment variables (such as MERRY_* provider secrets)
76    // before spawning the helper so they never enter the helper process's
77    // environment or `/proc/<pid>/environ`.
78    for name in launch.remove_env() {
79        if name != confinement::helper_env_name() && name != confinement::policy_env_name() {
80            command.env_remove(name);
81        }
82    }
83    command
84        .env(confinement::helper_env_name(), "1")
85        .env(
86            confinement::policy_env_name(),
87            confinement::policy_stdin_sentinel(),
88        )
89        .stdin(Stdio::piped())
90        .stdout(Stdio::piped())
91        .stderr(Stdio::piped())
92        .kill_on_drop(true);
93    let backend_program = helper.to_string_lossy().into_owned();
94    run_spawned_process_with_stdin(
95        command,
96        Some(policy_bytes),
97        intent,
98        context,
99        backend_program,
100        background,
101    )
102    .await
103}
104
105pub(super) async fn run_spawned_process(
106    command: tokio::process::Command,
107    intent: ProcessActionIntent,
108    context: ProcessRunnerContext,
109    program_for_error: String,
110    background: BackgroundSupervisor,
111) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
112    run_spawned_process_with_stdin(
113        command,
114        None,
115        intent,
116        context,
117        program_for_error,
118        background,
119    )
120    .await
121}
122
123async fn run_spawned_process_with_stdin(
124    mut command: tokio::process::Command,
125    stdin_payload: Option<Vec<u8>>,
126    intent: ProcessActionIntent,
127    context: ProcessRunnerContext,
128    program_for_error: String,
129    background: BackgroundSupervisor,
130) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
131    // A new group makes session-end and cancellation kill the command and its
132    // children without signaling Merry's own group.
133    #[cfg(unix)]
134    command.process_group(0);
135    // On Windows, detach from the parent console without `DETACHED_PROCESS`
136    // (which breaks stdio pipe inheritance for grandchildren like cmd -> node).
137    #[cfg(windows)]
138    {
139        use windows_sys::Win32::System::Threading::{CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW};
140        command.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
141    }
142    let mut child = command.spawn().map_err(|source| {
143        if source.kind() == io::ErrorKind::NotFound {
144            ProcessRunnerError::infrastructure(format!(
145                "process executable `{program_for_error}` was not found"
146            ))
147        } else {
148            ProcessRunnerError::infrastructure(format!(
149                "failed to start process executable `{program_for_error}`: {source}"
150            ))
151        }
152    })?;
153    #[cfg(windows)]
154    let windows_job = child.id().and_then(
155        |pid| match super::windows_job::WindowsProcessJob::for_pid(pid) {
156            Ok(job) => Some(job),
157            Err(error) => {
158                tracing::debug!(
159                    pid,
160                    error = %error,
161                    "failed to attach Windows child process to job object"
162                );
163                None
164            }
165        },
166    );
167    #[cfg(any(target_os = "linux", target_os = "macos"))]
168    if let Some(payload) = stdin_payload
169        && let Some(mut stdin) = child.stdin.take()
170    {
171        // Stream the sandbox policy over an anonymous pipe instead of a
172        // predictable `/tmp` file so concurrent sandboxed processes running
173        // under the same UID cannot tamper with or pre-create it.
174        let cancelled = tokio::select! {
175            biased;
176            () = context.cancellation_token().cancelled() => true,
177            () = async {
178                let _ = stdin.write_all(&payload).await;
179                let _ = stdin.shutdown().await;
180            } => false,
181        };
182        drop(stdin);
183        if cancelled {
184            background::kill_child_group(&mut child);
185            let _ = child.wait().await;
186            return Err(ProcessRunnerError::Cancelled);
187        }
188    }
189    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
190    let _ = stdin_payload;
191    let stdout = child.stdout.take().ok_or_else(|| {
192        ProcessRunnerError::infrastructure("process stdout pipe was not available")
193    })?;
194    let stderr = child.stderr.take().ok_or_else(|| {
195        ProcessRunnerError::infrastructure("process stderr pipe was not available")
196    })?;
197    background::finish_process(
198        background::SpawnedProcess {
199            child,
200            #[cfg(windows)]
201            windows_job,
202            stdout,
203            stderr,
204            program_for_error,
205        },
206        intent,
207        context,
208        background,
209    )
210    .await
211}