merry-process 0.1.3

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
use super::background::{self, BackgroundSupervisor};
use merry_runtime::{
    ProcessActionIntent, ProcessRunnerContext, ProcessRunnerError, ProcessRunnerOutput,
};
use std::io;
use tokio::io::AsyncWriteExt;

pub(super) async fn run_spawned_process(
    command: tokio::process::Command,
    intent: ProcessActionIntent,
    context: ProcessRunnerContext,
    program_for_error: String,
    background: BackgroundSupervisor,
) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
    run_spawned_process_with_stdin(
        command,
        None,
        intent,
        context,
        program_for_error,
        background,
    )
    .await
}

pub(super) async fn run_spawned_process_with_stdin(
    mut command: tokio::process::Command,
    stdin_payload: Option<Vec<u8>>,
    intent: ProcessActionIntent,
    context: ProcessRunnerContext,
    program_for_error: String,
    background: BackgroundSupervisor,
) -> Result<ProcessRunnerOutput, ProcessRunnerError> {
    // A new group makes session-end and cancellation kill the command and its
    // children without signaling Merry's own group.
    #[cfg(unix)]
    command.process_group(0);
    // On Windows, detach from the parent console without `DETACHED_PROCESS`
    // (which breaks stdio pipe inheritance for grandchildren like cmd -> node).
    #[cfg(windows)]
    {
        use windows_sys::Win32::System::Threading::{CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW};
        command.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
    }
    let mut child = command.spawn().map_err(|source| {
        if source.kind() == io::ErrorKind::NotFound {
            ProcessRunnerError::infrastructure(format!(
                "process executable `{program_for_error}` was not found"
            ))
        } else {
            ProcessRunnerError::infrastructure(format!(
                "failed to start process executable `{program_for_error}`: {source}"
            ))
        }
    })?;
    #[cfg(windows)]
    let windows_job = child.id().and_then(
        |pid| match super::windows_job::WindowsProcessJob::for_pid(pid) {
            Ok(job) => Some(job),
            Err(error) => {
                tracing::debug!(
                    pid,
                    error = %error,
                    "failed to attach Windows child process to job object"
                );
                None
            }
        },
    );
    if let Some(payload) = stdin_payload
        && let Some(mut stdin) = child.stdin.take()
    {
        // Stream optional stdin payloads (such as sandbox policy) over an
        // anonymous pipe rather than a predictable `/tmp` file.
        let cancelled = tokio::select! {
            biased;
            () = context.cancellation_token().cancelled() => true,
            () = async {
                let _ = stdin.write_all(&payload).await;
                let _ = stdin.shutdown().await;
            } => false,
        };
        drop(stdin);
        if cancelled {
            background::kill_child_group(&mut child);
            let _ = child.wait().await;
            return Err(ProcessRunnerError::Cancelled);
        }
    }
    let stdout = child.stdout.take().ok_or_else(|| {
        ProcessRunnerError::infrastructure("process stdout pipe was not available")
    })?;
    let stderr = child.stderr.take().ok_or_else(|| {
        ProcessRunnerError::infrastructure("process stderr pipe was not available")
    })?;
    background::finish_process(
        background::SpawnedProcess {
            child,
            #[cfg(windows)]
            windows_job,
            stdout,
            stderr,
            program_for_error,
        },
        intent,
        context,
        background,
    )
    .await
}