use super::{
background::BackgroundSupervisor, execution::run_spawned_process_with_stdin,
permissions::WorkspaceProcessRunner,
};
use crate::confinement::{self, SandboxLaunch};
use merry_runtime::{
BackgroundProcessControl, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
ProcessRunnerError, ProcessRunnerFuture, ProcessRunnerOutput,
};
use std::{process::Stdio, sync::Arc};
impl ProcessRunner for WorkspaceProcessRunner {
fn run<'a>(
&'a self,
intent: ProcessActionIntent,
context: ProcessRunnerContext,
) -> ProcessRunnerFuture<'a> {
Box::pin(async move {
if context.cancellation_token().is_cancelled() {
return Err(ProcessRunnerError::Cancelled);
}
let runner = self.clone();
let plan_intent = intent.clone();
let launch = tokio::task::spawn_blocking(move || runner.plan_for(&plan_intent))
.await
.map_err(|error| {
ProcessRunnerError::infrastructure(format!("sandbox planning failed: {error}"))
})??;
let background = self.background.clone();
run_sandbox_launch(launch, intent, context, background).await
})
}
fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
Some(Arc::new(self.background.clone()))
}
}
async fn run_sandbox_launch(
launch: SandboxLaunch,
intent: ProcessActionIntent,
context: ProcessRunnerContext,
background: BackgroundSupervisor,
) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
if context.cancellation_token().is_cancelled() {
return Err(ProcessRunnerError::Cancelled);
}
#[cfg(target_os = "macos")]
if confinement::explicit_helper_program().is_none() {
let command = confinement::direct_seatbelt_command(&launch);
return super::execution::run_spawned_process(
command,
intent,
context,
"/usr/bin/sandbox-exec".to_owned(),
background,
)
.await;
}
let helper = confinement::helper_program()?;
let policy_bytes = confinement::encode_policy(&launch)?;
let mut command = tokio::process::Command::new(&helper);
for name in launch.remove_env() {
if name != confinement::helper_env_name() && name != confinement::policy_env_name() {
command.env_remove(name);
}
}
command
.env(confinement::helper_env_name(), "1")
.env(
confinement::policy_env_name(),
confinement::policy_stdin_sentinel(),
)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let backend_program = helper.to_string_lossy().into_owned();
run_spawned_process_with_stdin(
command,
Some(policy_bytes),
intent,
context,
backend_program,
background,
)
.await
}