sprawling-runtime 0.0.11

One run of a sprawling resident, from dispatch to freeze: turns, tools, replay and the sandbox that executes code.
Documentation
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Copyright (c) 2026 2youg1 and the sprawling contributors

//! Places commands in bounded, synchronized copies and probes their platform wrapper.
//! Selection belongs to `Confinement`; copy lifetime belongs to this adapter.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

use kernel::{AxCode, AxError};

use crate::backlog::{BacklogId, Finished};

use super::{Confinement, Missing, Offerings};

/// Owns reusable copies and holds background copies until their member ends (D10).
pub struct Confined {
    arm: Confinement,
    scratch: Option<PathBuf>,
    idle: Option<Mirror>,
    outstanding: BTreeMap<BacklogId, Mirror>,
}

/// One copy, and the working directory it mirrors.
struct Mirror {
    of: PathBuf,
    at: PathBuf,
}

/// A command's copy claim, returned after its execution ends.
pub struct Placed {
    copy: Option<Mirror>,
    work: storage::FileWork,
}

impl Placed {
    pub(in crate::tools::exec) fn into_container_copy(self) -> Result<PathBuf, AxError> {
        self.copy
            .map(|copy| copy.at)
            .ok_or_else(|| no_arm(Missing::ScratchDirectory))
    }

    /// What putting the copy in place cost the filesystem (`crates/storage/Spec.lean`
    /// ยง8-31).
    pub fn work(&self) -> storage::FileWork {
        self.work
    }
}

impl Confined {
    /// The arm this machine gives, and where its copies go.
    pub fn detect() -> Confined {
        let offered = Offerings::this_machine();
        Confined {
            arm: Confinement::choose(&offered),
            scratch: offered.scratch,
            idle: None,
            outstanding: BTreeMap::new(),
        }
    }

    /// An arm stated rather than found: a test's machine, or a report
    /// about one.
    pub fn with_arm(arm: Confinement, scratch: Option<PathBuf>) -> Confined {
        Confined {
            arm,
            scratch,
            idle: None,
            outstanding: BTreeMap::new(),
        }
    }

    pub fn arm(&self) -> &Confinement {
        &self.arm
    }

    /// What this arm promises and does not, for the caller's own
    /// description of itself.
    pub fn statement(&self) -> String {
        self.arm.statement()
    }

    /// Places one command under this machine's arm: the tool's copy of
    /// `workdir`, synced to it, for the command to run in, wrapped in the
    /// platform's isolation where the arm is one that has a wrapper.
    ///
    /// # Errors
    /// `E_SANDBOX_DENIED` when this machine has no arm, when the arm
    /// cannot be given by any build of this crate, or when the working
    /// tree is too large or too deep to copy. On Linux, namespace setup
    /// must succeed with a required unprivileged user namespace before
    /// the working tree is copied.
    pub fn place(
        &mut self,
        mut command: Command,
        workdir: &Path,
    ) -> Result<(Command, Placed), AxError> {
        let wrapper = match &self.arm {
            Confinement::Unavailable { missing } => return Err(no_arm(*missing)),
            Confinement::WindowsJobObject => {
                #[cfg(not(windows))]
                return Err(no_job_object());
                #[cfg(windows)]
                {
                    None
                }
            }
            Confinement::MacosSeatbelt { .. } => {
                #[cfg(target_os = "macos")]
                {
                    None
                }
                #[cfg(not(target_os = "macos"))]
                {
                    return Err(AxError::failure(
                        AxCode::SandboxDenied,
                        "initialize macOS Seatbelt confinement",
                        "this host is not macOS",
                    )
                    .with_recovery("select a native sandbox for this host platform"));
                }
            }
            Confinement::LinuxNamespaces { wrapper } => {
                #[cfg(target_os = "linux")]
                {
                    let denied = |detail| {
                        AxError::failure(
                            AxCode::SandboxDenied,
                            "create the Linux confinement",
                            format!(
                                "this arm requires an unprivileged user namespace; \
                                 namespace setup failed: {detail}"
                            ),
                        )
                        .with_recovery(
                            "use a Linux machine that permits unprivileged user namespaces, \
                             or ask the User to choose `where: host`",
                        )
                    };
                    let probe = namespaced(wrapper, workdir, workdir, &child::command("/bin/true"))
                        .output()
                        .map_err(|err| denied(err.to_string()))?;
                    if !probe.status.success() {
                        return Err(denied(format!(
                            "{}: {}",
                            probe.status,
                            String::from_utf8_lossy(&probe.stderr).trim()
                        )));
                    }
                }
                Some(wrapper.clone())
            }
            Confinement::CopiedTree => None,
        };
        let (copy, work) = self.synced(workdir)?;
        #[cfg(target_os = "macos")]
        if let Confinement::MacosSeatbelt { wrapper } = &self.arm {
            let native = super::super::native_macos::probe(wrapper, &copy.at)
                .and_then(|()| super::super::native_macos::wrap(wrapper, &copy.at, &command));
            return match native {
                Ok(command) => Ok((
                    command,
                    Placed {
                        copy: Some(copy),
                        work,
                    },
                )),
                Err(error) => {
                    remove(&copy.at);
                    Err(error)
                }
            };
        }
        let command = match wrapper {
            Some(wrapper) => namespaced(&wrapper, &copy.at, workdir, &command),
            None => {
                command.current_dir(&copy.at);
                command
            }
        };
        Ok((
            command,
            Placed {
                copy: Some(copy),
                work,
            },
        ))
    }

    /// Retains a settled command's copy for reuse.
    pub fn settled(&mut self, placed: Placed) {
        if let Some(copy) = placed.copy {
            self.keep(copy);
        }
    }

    /// Holds a background command's copy until its member reports.
    pub fn handed(&mut self, id: BacklogId, placed: Placed) {
        if let Some(copy) = placed.copy {
            self.outstanding.insert(id, copy);
        }
    }

    /// Releases copies whose background members have ended.
    pub fn reaped(&mut self, finished: &[Finished]) {
        for member in finished {
            if let Some(copy) = self.outstanding.remove(&member.id) {
                self.keep(copy);
            }
        }
    }

    /// Keeps `copy` for the next command when no copy is kept yet, and
    /// removes it otherwise.
    ///
    /// A copy that cannot be removed costs disk space rather than the
    /// answer, so the command's ending is not turned into a failure of
    /// the tool: the judgment is `backlog/member.rs`'s about the place
    /// a child's output was written, and it is recorded here rather than
    /// repeated there.
    fn keep(&mut self, copy: Mirror) {
        match self.idle {
            None => self.idle = Some(copy),
            Some(_) => remove(&copy.at),
        }
    }

    /// The copy kept for the next command, or a fresh one, brought to
    /// what `workdir` holds.
    fn synced(&mut self, workdir: &Path) -> Result<(Mirror, storage::FileWork), AxError> {
        let root = self
            .scratch
            .as_deref()
            .ok_or_else(|| no_arm(Missing::ScratchDirectory))?;
        let copy = match self.idle.take() {
            Some(kept) if kept.of == workdir => kept,
            Some(other) => {
                remove(&other.at);
                Mirror {
                    of: workdir.to_path_buf(),
                    at: fresh(root)?,
                }
            }
            None => Mirror {
                of: workdir.to_path_buf(),
                at: fresh(root)?,
            },
        };
        let mut budget = Budget::new();
        match mirror(
            &Stage {
                from: workdir,
                into: &copy.at,
                copy: &copy.at,
            },
            0,
            &mut budget,
        ) {
            Ok(()) => Ok((copy, budget.work())),
            Err(fault) => {
                // The half-synced copy goes before the refusal is
                // returned: a scratch root that grew a tree per refusal
                // would be a leak nothing reports. A removal that fails
                // here is the secondary failure and stays unstated rather
                // than replacing the one that caused it.
                remove(&copy.at);
                Err(fault)
            }
        }
    }
}

impl Drop for Confined {
    fn drop(&mut self) {
        // The copy kept for a next command that will not come, and those
        // of commands still running when the tool ended. There is no
        // caller left to tell, and the alternative is a panic, which this
        // crate forbids: a directory that will not go stays behind in the
        // scratch root, where an operating system clears it.
        for copy in self.idle.iter().chain(self.outstanding.values()) {
            remove(&copy.at);
        }
    }
}

/// The refusal for a machine that cannot take a command at all.
fn no_arm(missing: Missing) -> AxError {
    AxError::failure(
        AxCode::SandboxDenied,
        "run outside the confinement",
        missing.phrase(),
    )
    .with_recovery(missing.recovery())
}

/// Refuses the unavailable job-object arm instead of silently weakening it.
#[cfg(not(windows))]
fn no_job_object() -> AxError {
    AxError::failure(
        AxCode::SandboxDenied,
        "run under a job object",
        "this build makes no job object",
    )
    .with_recovery(
        "run under the copied tree instead: it copies the working directory and does \
         not isolate the network, so keep the command off the network or run it on a \
         machine that has the arm",
    )
}

pub(super) mod copy;

use copy::{Budget, Stage, fresh, mirror, remove};

/// The command as the platform's wrapper runs it: the whole machine
/// readable, the copy bound over the working directory, and every
/// namespace the wrapper knows how to separate.
fn namespaced(wrapper: &Path, copy: &Path, workdir: &Path, command: &Command) -> Command {
    let mut wrapped = child::command(wrapper);
    wrapped
        .current_dir(workdir)
        .arg("--ro-bind")
        .arg("/")
        .arg("/")
        .arg("--bind")
        .arg(copy)
        .arg(workdir)
        .arg("--chdir")
        .arg(workdir)
        .arg("--proc")
        .arg("/proc")
        .arg("--dev")
        .arg("/dev")
        .arg("--unshare-all");
    #[cfg(target_os = "linux")]
    wrapped.arg("--unshare-user");
    wrapped
        .arg("--die-with-parent")
        .arg("--")
        .arg(command.get_program());
    for arg in command.get_args() {
        wrapped.arg(arg);
    }
    for (name, value) in command.get_envs() {
        match value {
            Some(value) => wrapped.env(name, value),
            None => wrapped.env_remove(name),
        };
    }
    wrapped
}