ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Capture the strict child through launch_strict_capture and classify the outcome before writing anything. In --json mode a control-plane failure now emits exactly one error document with a stable code instead of forwarding bubblewrap stderr and leaving stdout empty; a verified child's valid JSON is forwarded unchanged with its own exit code. Empty, partial or non-JSON child output becomes strict.child_invalid. Route the remaining run --json error paths (mode, grants, missing entry, trace) through the same contract, classify sandbox launch failures with StrictFailureKind so probe/spawn/timeout/resource failures stay distinguishable, and add deterministic routing tests plus forged-marker CLI coverage. Document the decision in ADR-0053 and spec/security.md 1.2. This is step 2 of the CI/security RFC (B02/B03).
454 lines
16 KiB
Rust
454 lines
16 KiB
Rust
//! Sandbox modes and platform isolation capability detection.
|
|
//!
|
|
//! Marqdo advertises security guarantees only when they can be enforced. In
|
|
//! particular, `strict` mode must **refuse to run** when the build cannot
|
|
//! provide OS-level isolation: a cooperative in-process check is not a sandbox
|
|
//! (blueprint section 9). This crate is deliberately honest about that.
|
|
|
|
use std::path::Path;
|
|
use std::time::Duration;
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
#[cfg(target_os = "linux")]
|
|
mod linux;
|
|
#[cfg(target_os = "linux")]
|
|
pub use linux::probe;
|
|
|
|
/// Environment variable set by the strict supervisor for its re-executed
|
|
/// child. The marker alone never authorizes strict execution; [`inspect_strict_child`]
|
|
/// verifies the child identity before anything is trusted.
|
|
pub const STRICT_ACTIVE_ENV: &str = "MARQDO_STRICT_ACTIVE";
|
|
|
|
/// Execution mode requested on the command line.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum SandboxMode {
|
|
/// Pure Marqdo and native math only; no external I/O.
|
|
Pure,
|
|
/// Project resources explicitly granted by the host/web caller.
|
|
Project,
|
|
/// Untrusted documents/code/plugins; requires real OS isolation.
|
|
Strict,
|
|
}
|
|
|
|
impl SandboxMode {
|
|
/// Parse a mode name.
|
|
pub fn parse(value: &str) -> Option<Self> {
|
|
match value {
|
|
"pure" => Some(SandboxMode::Pure),
|
|
"project" => Some(SandboxMode::Project),
|
|
"strict" => Some(SandboxMode::Strict),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Stable lowercase name.
|
|
pub const fn as_str(self) -> &'static str {
|
|
match self {
|
|
SandboxMode::Pure => "pure",
|
|
SandboxMode::Project => "project",
|
|
SandboxMode::Strict => "strict",
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for SandboxMode {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.write_str(self.as_str())
|
|
}
|
|
}
|
|
|
|
/// Whether real OS-level isolation is available for strict mode.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(tag = "state", rename_all = "snake_case")]
|
|
pub enum StrictIsolation {
|
|
/// Isolation is implemented and verified on this platform.
|
|
Available {
|
|
/// Mechanism, e.g. `linux-namespaces-seccomp`.
|
|
mechanism: String,
|
|
},
|
|
/// Isolation is not available; strict mode must refuse to run.
|
|
Unavailable {
|
|
/// Human readable reason.
|
|
reason: String,
|
|
},
|
|
}
|
|
|
|
impl StrictIsolation {
|
|
/// Whether strict execution can be offered.
|
|
pub fn is_available(&self) -> bool {
|
|
matches!(self, StrictIsolation::Available { .. })
|
|
}
|
|
|
|
/// Human readable explanation.
|
|
pub fn describe(&self) -> String {
|
|
match self {
|
|
StrictIsolation::Available { mechanism } => {
|
|
format!("strict isolation available via {mechanism}")
|
|
}
|
|
StrictIsolation::Unavailable { reason } => {
|
|
format!("strict isolation unavailable: {reason}")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Platform capability report, shown by `marqdo inspect --platform` and used to
|
|
/// gate strict mode.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct PlatformCapabilities {
|
|
/// Operating system family.
|
|
pub os: String,
|
|
/// Architecture.
|
|
pub arch: String,
|
|
/// Strict-mode isolation status.
|
|
pub strict: StrictIsolation,
|
|
/// Whether spawning isolated worker processes is implemented.
|
|
pub worker_processes: bool,
|
|
}
|
|
|
|
impl PlatformCapabilities {
|
|
/// Detect capabilities for the current build and platform.
|
|
///
|
|
/// Strict OS isolation remains intentionally unavailable: no OS isolation
|
|
/// adapter is implemented, and pretending otherwise would violate the
|
|
/// security contract. The isolated worker transport is implemented, but a
|
|
/// plain child process is not an OS sandbox.
|
|
pub fn detect() -> Self {
|
|
Self {
|
|
os: std::env::consts::OS.to_string(),
|
|
arch: std::env::consts::ARCH.to_string(),
|
|
strict: detect_strict(),
|
|
worker_processes: true,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Detect strict isolation using only code that is compiled for the current
|
|
/// platform.
|
|
///
|
|
/// `cfg!` is a boolean constant and does **not** remove the other branch from
|
|
/// type checking. Using it around `linux::probe()` made macOS/Windows builds
|
|
/// reference a module that is not compiled there (`E0433`). The platform
|
|
/// dispatch therefore lives in dedicated `#[cfg]` functions.
|
|
#[cfg(target_os = "linux")]
|
|
fn detect_strict() -> StrictIsolation {
|
|
match linux::probe() {
|
|
Ok(mechanism) => StrictIsolation::Available { mechanism },
|
|
Err(reason) => StrictIsolation::Unavailable { reason },
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "macos")]
|
|
fn detect_strict() -> StrictIsolation {
|
|
StrictIsolation::Unavailable {
|
|
reason: "no verified macOS sandbox adapter is implemented in this build".to_string(),
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "windows")]
|
|
fn detect_strict() -> StrictIsolation {
|
|
StrictIsolation::Unavailable {
|
|
reason: "no verified Windows job-object/appcontainer adapter is implemented in this build"
|
|
.to_string(),
|
|
}
|
|
}
|
|
|
|
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
|
|
fn detect_strict() -> StrictIsolation {
|
|
StrictIsolation::Unavailable {
|
|
reason: format!(
|
|
"platform isolation is not implemented for `{}`",
|
|
std::env::consts::OS
|
|
),
|
|
}
|
|
}
|
|
|
|
/// Whether the current process is a verified strict child.
|
|
///
|
|
/// This is the **only** supported platform boundary for strict-child
|
|
/// detection. Linux performs the full identity verification; every other
|
|
/// platform refuses even a forged marker instead of treating it as a child.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum StrictChildState {
|
|
/// The process was not launched by the strict supervisor.
|
|
NotChild,
|
|
/// The process is the verified strict child and may run project code.
|
|
VerifiedChild,
|
|
}
|
|
|
|
/// Inspect whether this process is the strict supervisor's verified child.
|
|
///
|
|
/// Linux requires the marker **and** the full namespace/privilege identity
|
|
/// check in [`linux::verify_active`]. Non-Linux builds reject any marker:
|
|
/// without a verified OS isolation adapter there is no legitimate strict
|
|
/// child, so a forged `MARQDO_STRICT_ACTIVE` must fail closed.
|
|
pub fn inspect_strict_child() -> Result<StrictChildState, String> {
|
|
#[cfg(target_os = "linux")]
|
|
{
|
|
if !linux::marker_present() {
|
|
return Ok(StrictChildState::NotChild);
|
|
}
|
|
linux::verify_active().map(|()| StrictChildState::VerifiedChild)
|
|
}
|
|
#[cfg(not(target_os = "linux"))]
|
|
{
|
|
if std::env::var_os(STRICT_ACTIVE_ENV).is_some() {
|
|
return Err(
|
|
"strict active marker is unsupported on this platform; refusing to treat this \
|
|
process as a verified strict child"
|
|
.to_string(),
|
|
);
|
|
}
|
|
Ok(StrictChildState::NotChild)
|
|
}
|
|
}
|
|
|
|
/// Result of one supervised strict execution.
|
|
///
|
|
/// The outcome is a byte capture, **not** proof that the child completed
|
|
/// isolation verification: the caller must still route it through the public
|
|
/// strict contract (one JSON document in `--json` mode, no fallback).
|
|
#[derive(Debug, Clone)]
|
|
pub struct StrictOutcome {
|
|
/// Process exit code when the program exited normally.
|
|
pub exit_code: Option<i32>,
|
|
/// Terminating signal, when the program was killed by the supervisor,
|
|
/// a resource limit or the kernel.
|
|
pub signal: Option<i32>,
|
|
/// Captured stdout (bounded by the output limit).
|
|
pub stdout: Vec<u8>,
|
|
/// Captured stderr (bounded by the output limit).
|
|
pub stderr: Vec<u8>,
|
|
}
|
|
|
|
/// Stable classification of a strict control-plane failure.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum StrictFailureKind {
|
|
/// The runtime probe could not construct the isolation mechanism.
|
|
ProbeUnavailable,
|
|
/// The supervisor process could not be spawned.
|
|
SpawnFailed,
|
|
/// The supervisor exceeded the wall-clock budget.
|
|
Timeout,
|
|
/// A resource limit or signal terminated the supervised child.
|
|
ResourceLimit,
|
|
/// The requested launch is invalid (host root, document outside project).
|
|
InvalidRequest,
|
|
/// Capturing or reading the supervised output failed.
|
|
Io,
|
|
}
|
|
|
|
impl StrictFailureKind {
|
|
/// Stable machine-readable code consumed by `--json` error documents.
|
|
pub const fn code(self) -> &'static str {
|
|
match self {
|
|
StrictFailureKind::ProbeUnavailable => "strict.probe_unavailable",
|
|
StrictFailureKind::SpawnFailed => "strict.spawn_failed",
|
|
StrictFailureKind::Timeout => "strict.timeout",
|
|
StrictFailureKind::ResourceLimit => "strict.resource_limit",
|
|
StrictFailureKind::InvalidRequest => "strict.launch_failed",
|
|
StrictFailureKind::Io => "strict.launch_failed",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Failure to apply the requested sandbox mode.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum SandboxError {
|
|
/// Strict mode was requested but the platform cannot provide isolation.
|
|
StrictUnavailable {
|
|
/// Explanation from [`PlatformCapabilities`].
|
|
reason: String,
|
|
},
|
|
/// The strict supervisor could not launch, verify or supervise the child.
|
|
LaunchFailed {
|
|
/// Machine-readable classification.
|
|
kind: StrictFailureKind,
|
|
/// Actionable explanation.
|
|
message: String,
|
|
},
|
|
}
|
|
|
|
impl SandboxError {
|
|
/// Build a classified launch failure.
|
|
pub fn launch(kind: StrictFailureKind, message: impl Into<String>) -> Self {
|
|
SandboxError::LaunchFailed {
|
|
kind,
|
|
message: message.into(),
|
|
}
|
|
}
|
|
|
|
/// Stable machine-readable failure code for `--json` error documents.
|
|
pub const fn code(&self) -> &'static str {
|
|
match self {
|
|
SandboxError::StrictUnavailable { .. } => "strict.probe_unavailable",
|
|
SandboxError::LaunchFailed { kind, .. } => kind.code(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for SandboxError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
SandboxError::StrictUnavailable { reason } => write!(
|
|
f,
|
|
"refusing to run in strict mode: {reason}. Strict mode requires verified OS-level isolation and never falls back to an unrestricted process."
|
|
),
|
|
SandboxError::LaunchFailed { message, .. } => {
|
|
write!(f, "strict isolation failed: {message}")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for SandboxError {}
|
|
|
|
/// Validate that the requested mode can be honoured on this platform.
|
|
pub fn enforce(mode: SandboxMode, platform: &PlatformCapabilities) -> Result<(), SandboxError> {
|
|
match mode {
|
|
SandboxMode::Strict => {
|
|
#[cfg(target_os = "linux")]
|
|
if linux::verify_active().is_ok() {
|
|
return Ok(());
|
|
}
|
|
if platform.strict.is_available() {
|
|
Ok(())
|
|
} else {
|
|
let reason = match &platform.strict {
|
|
StrictIsolation::Available { .. } => String::new(),
|
|
StrictIsolation::Unavailable { reason } => reason.clone(),
|
|
};
|
|
Err(SandboxError::StrictUnavailable { reason })
|
|
}
|
|
}
|
|
SandboxMode::Pure | SandboxMode::Project => Ok(()),
|
|
}
|
|
}
|
|
|
|
/// A command to execute inside the strict Linux sandbox.
|
|
#[derive(Debug, Clone)]
|
|
pub struct StrictHostCommand<'a> {
|
|
/// Program bound read-only into the sandbox and executed.
|
|
pub program: &'a Path,
|
|
/// Arguments passed to the program.
|
|
pub args: &'a [std::ffi::OsString],
|
|
/// Project directory mounted read-only at `/project`.
|
|
pub project_root: &'a Path,
|
|
/// Entry document as passed on the command line; rewritten to the sandbox
|
|
/// path. `None` keeps the CLI default (index.mq.md).
|
|
pub document: Option<&'a Path>,
|
|
/// Original document token to replace in `args` (same value as `document`
|
|
/// when present).
|
|
pub original_document: Option<&'a Path>,
|
|
/// Combined per-stream output cap in bytes.
|
|
pub output_limit: usize,
|
|
/// Wall-clock budget for the supervised process tree.
|
|
pub timeout: Duration,
|
|
/// Verified bundled stdlib directory to bind read-only when present.
|
|
pub stdlib_dir: Option<&'a Path>,
|
|
}
|
|
|
|
/// Launch a command inside the strict sandbox (Linux only).
|
|
#[cfg(target_os = "linux")]
|
|
pub fn launch_strict(command: &StrictHostCommand<'_>) -> Result<i32, SandboxError> {
|
|
linux::launch(command)
|
|
}
|
|
|
|
/// Launch a command inside the strict sandbox and return its captured outcome.
|
|
#[cfg(target_os = "linux")]
|
|
pub fn launch_strict_capture(
|
|
command: &StrictHostCommand<'_>,
|
|
) -> Result<StrictOutcome, SandboxError> {
|
|
linux::launch_capture(command)
|
|
}
|
|
|
|
/// Launch a command inside the strict sandbox (unsupported elsewhere).
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn launch_strict(_command: &StrictHostCommand<'_>) -> Result<i32, SandboxError> {
|
|
Err(SandboxError::StrictUnavailable {
|
|
reason: "strict OS isolation is only implemented on Linux".to_string(),
|
|
})
|
|
}
|
|
|
|
/// Capture a strict execution (unsupported elsewhere): every platform must
|
|
/// compile the same CLI routing code and fail closed instead of falling back.
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn launch_strict_capture(
|
|
_command: &StrictHostCommand<'_>,
|
|
) -> Result<StrictOutcome, SandboxError> {
|
|
Err(SandboxError::StrictUnavailable {
|
|
reason: "strict OS isolation is only implemented on Linux".to_string(),
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn mode_names_round_trip() {
|
|
for mode in [SandboxMode::Pure, SandboxMode::Project, SandboxMode::Strict] {
|
|
assert_eq!(SandboxMode::parse(mode.as_str()), Some(mode));
|
|
}
|
|
assert_eq!(SandboxMode::parse("nope"), None);
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
#[test]
|
|
fn ordinary_process_is_not_a_strict_child() {
|
|
if std::env::var_os(STRICT_ACTIVE_ENV).is_none() {
|
|
assert_eq!(
|
|
inspect_strict_child().expect("inspection must not fail without a marker"),
|
|
StrictChildState::NotChild
|
|
);
|
|
}
|
|
}
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[test]
|
|
fn forged_marker_is_rejected_on_non_linux() {
|
|
std::env::set_var(STRICT_ACTIVE_ENV, "1");
|
|
let result = inspect_strict_child();
|
|
std::env::remove_var(STRICT_ACTIVE_ENV);
|
|
let error = result.expect_err("a forged marker must never authorize strict execution");
|
|
assert!(error.contains("unsupported"), "unexpected error: {error}");
|
|
}
|
|
|
|
#[test]
|
|
fn strict_refuses_when_isolation_is_unavailable() {
|
|
let platform = PlatformCapabilities {
|
|
os: "test".to_string(),
|
|
arch: "test".to_string(),
|
|
strict: StrictIsolation::Unavailable {
|
|
reason: "test host has no verified isolation".to_string(),
|
|
},
|
|
worker_processes: true,
|
|
};
|
|
let result = enforce(SandboxMode::Strict, &platform);
|
|
assert!(result.is_err());
|
|
assert!(format!("{}", result.unwrap_err()).contains("strict"));
|
|
assert!(enforce(SandboxMode::Pure, &platform).is_ok());
|
|
assert!(enforce(SandboxMode::Project, &platform).is_ok());
|
|
}
|
|
|
|
/// macOS and Windows must compile without the Linux-only `linux` module,
|
|
/// report strict as unavailable, and still refuse strict execution. This
|
|
/// is the regression guard for the `E0433` platform-detection defect.
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[test]
|
|
fn non_linux_detection_is_compiled_and_fails_closed() {
|
|
let platform = PlatformCapabilities::detect();
|
|
assert!(matches!(
|
|
platform.strict,
|
|
StrictIsolation::Unavailable { .. }
|
|
));
|
|
let error = enforce(SandboxMode::Strict, &platform).expect_err("strict must refuse");
|
|
assert!(matches!(error, SandboxError::StrictUnavailable { .. }));
|
|
assert!(!platform.strict.describe().contains("available via"));
|
|
}
|
|
}
|