From f817cceb3b46fe743804dd20a55094213d3484c9 Mon Sep 17 00:00:00 2001 From: cflmy Date: Sat, 21 Nov 2026 16:46:27 +0800 Subject: [PATCH] fix(cli): normalize strict failures to one JSON document 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). --- .gitignore | 2 + crates/cli/src/commands.rs | 234 +++++++++++++++++- crates/cli/src/commands/run.rs | 58 ++--- crates/cli/tests/integration_cli.rs | 94 +++++++ crates/marqdo-sandbox/src/lib.rs | 90 ++++++- crates/marqdo-sandbox/src/linux.rs | 139 ++++++----- ...ld-inspection-and-json-failure-contract.md | 88 +++++++ docs/adr/README.md | 6 +- spec/security.md | 26 ++ 9 files changed, 634 insertions(+), 103 deletions(-) create mode 100644 docs/adr/0053-strict-child-inspection-and-json-failure-contract.md diff --git a/.gitignore b/.gitignore index 0180482..47b1967 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,8 @@ examples/plugin-multi-export/solver.so # Local cargo home used on hosts with a read-only $HOME .cargo-home/ +# Local rustup home used for cross-target `cargo check` verification +.rustup-home/ # Generated plugin fixture manifests/artifacts examples/plugin-demo/build/ diff --git a/crates/cli/src/commands.rs b/crates/cli/src/commands.rs index 79c3ffa..77a6dac 100644 --- a/crates/cli/src/commands.rs +++ b/crates/cli/src/commands.rs @@ -5,7 +5,7 @@ use std::time::{Duration, Instant}; use marqdo_host::{Host, StdHost}; use marqdo_runtime::{run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value}; -use marqdo_sandbox::{PlatformCapabilities, SandboxMode}; +use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictOutcome}; use marqdo_span::Span; use serde_json::json; @@ -324,15 +324,108 @@ fn resolve_link( } /// Re-execute this CLI inside the strict Linux supervisor. +/// Emit one CLI error through the requested channel. +/// +/// `--json` consumers require exactly one JSON document; human mode keeps the +/// conventional `error:` line on stderr. This helper is shared with the run +/// assembly so every strict control-plane failure follows one contract. +pub(super) fn emit_error(json: bool, command_name: &str, code: &str, message: &str) { + if json { + output::print_json(&json!({ + "command": command_name, + "success": false, + "error": message, + "code": code, + })); + } else { + eprintln!("error: {message}"); + } +} + +/// Machine-readable routing decision for one captured strict execution. +#[derive(Debug, PartialEq, Eq)] +enum StrictRoute { + /// Forward the captured child bytes unchanged. + Forward { exit_code: i32 }, + /// Emit exactly one JSON error document instead of the raw child output. + Failure { code: &'static str, message: String }, +} + +/// Classify a captured strict execution. +/// +/// A strict child in `--json` mode must produce exactly one JSON document on +/// stdout. Anything else is a control-plane failure: forwarding bwrap text or +/// an empty stream would break the CLI protocol (the GitHub-hosted Linux CI +/// failure that motivated this contract). +fn classify_strict_outcome(outcome: &StrictOutcome, json: bool) -> StrictRoute { + let exit_code = outcome.exit_code.unwrap_or(1); + if !json { + return StrictRoute::Forward { exit_code }; + } + if !outcome.stdout.is_empty() + && serde_json::from_slice::(&outcome.stdout).is_ok() + { + return StrictRoute::Forward { exit_code }; + } + if outcome.exit_code.is_none() { + return StrictRoute::Failure { + code: "strict.resource_limit", + message: "strict child was terminated by a resource limit or signal".to_string(), + }; + } + let stderr = String::from_utf8_lossy(&outcome.stderr); + if stderr.contains("namespace") || stderr.contains("bwrap") { + return StrictRoute::Failure { + code: "strict.namespace_failure", + message: "the strict supervisor could not construct the isolation namespaces; refusing to run the project" + .to_string(), + }; + } + StrictRoute::Failure { + code: "strict.child_invalid", + message: "the strict child did not produce exactly one JSON document; refusing to forward partial output" + .to_string(), + } +} + +/// Route one captured strict execution to stdout/stderr or one error document. +fn route_strict_outcome(outcome: StrictOutcome, json: bool, command_name: &str) -> i32 { + use std::io::Write; + match classify_strict_outcome(&outcome, json) { + StrictRoute::Forward { exit_code } => { + let _ = std::io::stdout().write_all(&outcome.stdout); + let _ = std::io::stdout().flush(); + let _ = std::io::stderr().write_all(&outcome.stderr); + let _ = std::io::stderr().flush(); + exit_code + } + StrictRoute::Failure { code, message } => { + output::print_json(&json!({ + "command": command_name, + "success": false, + "error": message, + "code": code, + })); + match outcome.exit_code { + Some(code) if code != 0 => code, + _ => 1, + } + } + } +} + fn launch_strict_process( project_root: &Path, document: Option<&Path>, settings: &SandboxSettings, + json: bool, + command_name: &str, ) -> i32 { let program = match std::env::current_exe() { Ok(path) => path, Err(error) => { - eprintln!("error: cannot locate the marqdo executable: {error}"); + let message = format!("cannot locate the marqdo executable: {error}"); + emit_error(json, command_name, "strict.launch_failed", &message); return 1; } }; @@ -356,10 +449,10 @@ fn launch_strict_process( timeout, stdlib_dir: stdlib_dir.as_deref(), }; - match marqdo_sandbox::launch_strict(&command) { - Ok(code) => code, + match marqdo_sandbox::launch_strict_capture(&command) { + Ok(outcome) => route_strict_outcome(outcome, json, command_name), Err(error) => { - eprintln!("error: {error}"); + emit_error(json, command_name, error.code(), &error.to_string()); 1 } } @@ -535,3 +628,134 @@ pub fn parse_named_args(raw: &[String]) -> Result, String> .map(|entry| args::parse_named_arg(entry)) .collect() } + +#[cfg(test)] +mod tests { + use super::*; + + fn outcome( + exit_code: Option, + signal: Option, + stdout: &[u8], + stderr: &[u8], + ) -> StrictOutcome { + StrictOutcome { + exit_code, + signal, + stdout: stdout.to_vec(), + stderr: stderr.to_vec(), + } + } + + #[test] + fn strict_json_success_is_forwarded_once() { + let route = classify_strict_outcome( + &outcome(Some(0), None, br#"{"command":"run","success":true}"#, b""), + true, + ); + assert_eq!(route, StrictRoute::Forward { exit_code: 0 }); + } + + #[test] + fn strict_json_program_error_is_forwarded_unchanged() { + let route = classify_strict_outcome( + &outcome(Some(2), None, br#"{"command":"run","success":false}"#, b""), + true, + ); + assert_eq!(route, StrictRoute::Forward { exit_code: 2 }); + } + + #[test] + fn strict_json_empty_stdout_is_one_error_document() { + let route = classify_strict_outcome( + &outcome(Some(1), None, b"", b"unexpected child noise\n"), + true, + ); + match route { + StrictRoute::Failure { code, message } => { + assert_eq!(code, "strict.child_invalid"); + assert!(message.contains("exactly one JSON")); + } + other => panic!("expected Failure, got {other:?}"), + } + } + + #[test] + fn strict_json_extra_text_is_not_forwarded() { + let route = classify_strict_outcome( + &outcome( + Some(0), + None, + br#"{"success":true} +not json"#, + b"", + ), + true, + ); + assert!(matches!( + route, + StrictRoute::Failure { + code: "strict.child_invalid", + .. + } + )); + } + + #[test] + fn strict_namespace_failure_is_classified() { + let route = classify_strict_outcome( + &outcome( + Some(1), + None, + b"", + b"bwrap: Creating new namespace failed: Resource temporarily unavailable\n", + ), + true, + ); + assert!(matches!( + route, + StrictRoute::Failure { + code: "strict.namespace_failure", + .. + } + )); + } + + #[test] + fn strict_signal_is_a_resource_limit() { + let route = classify_strict_outcome(&outcome(None, Some(9), b"", b""), true); + assert!(matches!( + route, + StrictRoute::Failure { + code: "strict.resource_limit", + .. + } + )); + } + + #[test] + fn strict_human_mode_forwards_captured_bytes() { + let route = classify_strict_outcome(&outcome(Some(1), None, b"", b"boom\n"), false); + assert_eq!(route, StrictRoute::Forward { exit_code: 1 }); + } + + #[test] + fn sandbox_errors_expose_stable_codes() { + use marqdo_sandbox::{SandboxError, StrictFailureKind}; + assert_eq!( + SandboxError::StrictUnavailable { + reason: "none".to_string() + } + .code(), + "strict.probe_unavailable" + ); + assert_eq!( + SandboxError::launch(StrictFailureKind::SpawnFailed, "x").code(), + "strict.spawn_failed" + ); + assert_eq!( + SandboxError::launch(StrictFailureKind::Timeout, "x").code(), + "strict.timeout" + ); + } +} diff --git a/crates/cli/src/commands/run.rs b/crates/cli/src/commands/run.rs index 53fa40b..8b46fde 100644 --- a/crates/cli/src/commands/run.rs +++ b/crates/cli/src/commands/run.rs @@ -52,17 +52,13 @@ pub fn execute( let mode = match settings.sandbox_mode() { Ok(mode) => mode, Err(error) => { - eprintln!("error: {error}"); + emit_error(json, command_name, "cli.invalid_mode", &error); return 2; } }; if mode == SandboxMode::Strict { if let Err(error) = settings.strict_preflight() { - if json { - output::print_json(&json!({"success": false, "error": error})); - } else { - eprintln!("error: {error}"); - } + emit_error(json, command_name, "strict.unsupported_grant", &error); return 2; } match marqdo_sandbox::inspect_strict_child() { @@ -72,42 +68,35 @@ pub fn execute( Ok(StrictChildState::NotChild) => { let platform = PlatformCapabilities::detect(); if let Err(error) = marqdo_sandbox::enforce(mode, &platform) { - if json { - output::print_json(&json!({"success": false, "error": error.to_string()})); - } else { - eprintln!("error: {error}"); - } + emit_error(json, command_name, error.code(), &error.to_string()); return 1; } - return launch_strict_process(&project.root, file, settings); + return launch_strict_process(&project.root, file, settings, json, command_name); } // A marker without a verified identity is never trusted, and the // platform-neutral inspection keeps Linux-only symbols out of this // module so macOS/Windows builds compile. Err(reason) => { let message = format!("strict isolation verification failed: {reason}"); - if json { - output::print_json(&json!({"success": false, "error": message})); - } else { - eprintln!("error: {message}"); - } + emit_error(json, command_name, "strict.identity_invalid", &message); return 1; } } } let platform = PlatformCapabilities::detect(); if let Err(error) = marqdo_sandbox::enforce(mode, &platform) { - if json { - output::print_json(&json!({"success": false, "error": error.to_string()})); - } else { - eprintln!("error: {error}"); - } + emit_error( + json, + command_name, + "sandbox.unavailable", + &error.to_string(), + ); return 1; } let capabilities = match settings.capabilities() { Ok(capabilities) => capabilities, Err(error) => { - eprintln!("error: {error}"); + emit_error(json, command_name, "cli.invalid_grants", &error); return 2; } }; @@ -193,17 +182,22 @@ pub fn execute( let function_name = function.unwrap_or("main").to_string(); let entry_module = &project.program.modules[&project.entry]; if entry_module.function(&function_name).is_none() { - if function.is_none() { - eprintln!( - "error[sem.no_entry_function]: {} has no callable `main`; declare an Exec H2 \ - (`## @exec main`) or pass an explicit function name", + let message = if function.is_none() { + format!( + "{} has no callable `main`; declare an Exec H2 (`## @exec main`) or pass an \ + explicit function name", project.entry_file().path.display() - ); + ) } else { - eprintln!( - "error: no function named `{function_name}` in {}", + format!( + "no function named `{function_name}` in {}", project.entry_file().path.display() - ); + ) + }; + if json { + emit_error(true, command_name, "sem.no_entry_function", &message); + } else { + eprintln!("error[sem.no_entry_function]: {message}"); } return 1; } @@ -234,7 +228,7 @@ pub fn execute( }; let entry = format!("{}::{}", project.entry, function_name); if let Err(error) = crate::trace::write(&project, &host, &entry, status, path) { - eprintln!("error: {error}"); + emit_error(json, command_name, "cli.trace_failed", &error); return 1; } } diff --git a/crates/cli/tests/integration_cli.rs b/crates/cli/tests/integration_cli.rs index aea125e..c14baea 100644 --- a/crates/cli/tests/integration_cli.rs +++ b/crates/cli/tests/integration_cli.rs @@ -79,6 +79,16 @@ fn cli(dir: &Path, args: &[&str]) -> Output { .unwrap_or_else(|error| panic!("cannot run marqdo {args:?}: {error}")) } +/// Run the CLI in `dir` with one extra environment variable. +fn cli_env(dir: &Path, args: &[&str], key: &str, value: &str) -> Output { + Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(args) + .current_dir(dir) + .env(key, value) + .output() + .unwrap_or_else(|error| panic!("cannot run marqdo {args:?}: {error}")) +} + fn stdout_text(output: &Output) -> String { String::from_utf8_lossy(&output.stdout).to_string() } @@ -468,6 +478,90 @@ fn strict_mode_enforces_isolation_or_refuses_closed() { .contains("strict mode")); } +/// A forged `MARQDO_STRICT_ACTIVE` marker must never be trusted and every +/// `--json` refusal must still contain exactly one JSON document. This runs on +/// every platform; Linux rejects the marker during identity verification and +/// non-Linux builds reject it as unsupported. +#[test] +fn forged_strict_marker_is_rejected_with_one_json_document() { + let root = repo_root(); + let hello = root.join("examples").join("hello.mq.md"); + let hello = hello.to_str().unwrap(); + let json = cli_env( + &root, + &["run", hello, "--mode", "strict", "--json"], + "MARQDO_STRICT_ACTIVE", + "1", + ); + assert_exit(&json, 1, "forged strict marker must fail closed"); + let value = json_stdout(&json); + assert_eq!(value["command"], "run"); + assert_eq!(value["success"], false); + assert_eq!(value["code"], "strict.identity_invalid"); + + let human = cli_env( + &root, + &["run", hello, "--mode", "strict"], + "MARQDO_STRICT_ACTIVE", + "1", + ); + assert_exit(&human, 1, "forged strict marker must fail closed"); + assert!( + stdout_text(&human).is_empty(), + "project output appeared for a rejected marker: {}", + stdout_text(&human) + ); + assert!(stderr_text(&human).contains("strict isolation verification failed")); +} + +/// CLI usage errors in `--json` mode keep the same one-document contract as +/// successful and runtime-failure paths. +#[test] +fn json_mode_reports_cli_errors_as_one_document() { + let root = repo_root(); + let hello = root.join("examples").join("hello.mq.md"); + let hello = hello.to_str().unwrap(); + + let mode = cli(&root, &["run", hello, "--mode", "bogus", "--json"]); + assert_exit(&mode, 2, "unknown mode"); + let value = json_stdout(&mode); + assert_eq!(value["success"], false); + assert_eq!(value["code"], "cli.invalid_mode"); + + let grants = cli( + &root, + &[ + "run", + hello, + "--mode", + "pure", + "--allow-read", + "x", + "--json", + ], + ); + assert_exit(&grants, 2, "pure mode must reject grants"); + let value = json_stdout(&grants); + assert_eq!(value["success"], false); + assert_eq!(value["code"], "cli.invalid_grants"); + + let strict = cli( + &root, + &[ + "run", + hello, + "--mode", + "strict", + "--allow-foreign", + "--json", + ], + ); + assert_exit(&strict, 2, "strict L1 must reject foreign grants"); + let value = json_stdout(&strict); + assert_eq!(value["success"], false); + assert_eq!(value["code"], "strict.unsupported_grant"); +} + #[test] fn inspect_outputs_ast_units_signatures_ir_and_refs() { let root = repo_root(); diff --git a/crates/marqdo-sandbox/src/lib.rs b/crates/marqdo-sandbox/src/lib.rs index 9708fc8..cf62106 100644 --- a/crates/marqdo-sandbox/src/lib.rs +++ b/crates/marqdo-sandbox/src/lib.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] -pub use linux::{probe, StrictOutcome}; +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`] @@ -197,7 +197,8 @@ pub fn inspect_strict_child() -> Result { { 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" + "strict active marker is unsupported on this platform; refusing to treat this \ + process as a verified strict child" .to_string(), ); } @@ -205,6 +206,56 @@ pub fn inspect_strict_child() -> Result { } } +/// 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, + /// Terminating signal, when the program was killed by the supervisor, + /// a resource limit or the kernel. + pub signal: Option, + /// Captured stdout (bounded by the output limit). + pub stdout: Vec, + /// Captured stderr (bounded by the output limit). + pub stderr: Vec, +} + +/// 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 { @@ -215,11 +266,31 @@ pub enum SandboxError { }, /// 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) -> 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 { @@ -227,7 +298,7 @@ impl std::fmt::Display for SandboxError { 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 } => { + SandboxError::LaunchFailed { message, .. } => { write!(f, "strict isolation failed: {message}") } } @@ -291,7 +362,7 @@ pub fn launch_strict(command: &StrictHostCommand<'_>) -> Result, -) -> Result { +) -> Result { linux::launch_capture(command) } @@ -303,6 +374,17 @@ pub fn launch_strict(_command: &StrictHostCommand<'_>) -> Result, +) -> Result { + Err(SandboxError::StrictUnavailable { + reason: "strict OS isolation is only implemented on Linux".to_string(), + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/marqdo-sandbox/src/linux.rs b/crates/marqdo-sandbox/src/linux.rs index 4185abd..1551eea 100644 --- a/crates/marqdo-sandbox/src/linux.rs +++ b/crates/marqdo-sandbox/src/linux.rs @@ -28,7 +28,7 @@ use std::path::{Path, PathBuf}; use std::process::{Child, Command, ExitStatus, Stdio}; use std::time::{Duration, Instant}; -use crate::{SandboxError, StrictHostCommand}; +use crate::{SandboxError, StrictFailureKind, StrictHostCommand, StrictOutcome}; /// Path of the program inside the sandbox. const SANDBOX_PROGRAM: &str = "/run/marqdo-program"; @@ -204,20 +204,6 @@ pub fn marker_present() -> bool { std::env::var(crate::STRICT_ACTIVE_ENV).ok().as_deref() == Some("1") } -/// Result of one supervised strict execution. -#[derive(Debug, Clone)] -pub struct StrictOutcome { - /// Process exit code when the program exited normally. - pub exit_code: Option, - /// Terminating signal, when the program was killed by the supervisor, - /// a resource limit or the kernel. - pub signal: Option, - /// Captured stdout (bounded by the output limit). - pub stdout: Vec, - /// Captured stderr (bounded by the output limit). - pub stderr: Vec, -} - /// Launch `command` inside the strict sandbox and return its exit code, /// forwarding captured output to this process's stdout/stderr. pub fn launch(command: &StrictHostCommand<'_>) -> Result { @@ -248,7 +234,10 @@ fn finish(outcome: StrictOutcome) -> Result { libc::SIGKILL => "strict child was killed by the resource supervisor".to_string(), other => format!("strict child terminated by signal {other}"), }; - Err(SandboxError::LaunchFailed { message }) + Err(SandboxError::launch( + StrictFailureKind::ResourceLimit, + message, + )) } /// Probe function used by [`run`]. A function pointer keeps the production @@ -274,43 +263,52 @@ fn run_with( spawn_fn: SpawnFn, ) -> Result { if command.project_root == Path::new("/") { - return Err(SandboxError::LaunchFailed { - message: "strict mode refuses to expose the host root as the project".to_string(), - }); + return Err(SandboxError::launch( + StrictFailureKind::InvalidRequest, + "strict mode refuses to expose the host root as the project", + )); } - let project_root = - fs::canonicalize(command.project_root).map_err(|error| SandboxError::LaunchFailed { - message: format!( + let project_root = fs::canonicalize(command.project_root).map_err(|error| { + SandboxError::launch( + StrictFailureKind::InvalidRequest, + format!( "cannot resolve the strict project root `{}`: {error}", command.project_root.display() ), - })?; + ) + })?; // The document (when supplied) must be inside the project root. It is // rewritten to the sandbox path, so the host's absolute layout never leaks // into the child and no other directory needs to be mounted. let document = match command.document { Some(document) => { - let absolute = - fs::canonicalize(document).map_err(|error| SandboxError::LaunchFailed { - message: format!("cannot resolve strict document: {error}"), - })?; - let relative = - absolute - .strip_prefix(&project_root) - .map_err(|_| SandboxError::LaunchFailed { - message: format!( - "strict document `{}` is outside the project root `{}`", - absolute.display(), - project_root.display() - ), - })?; + let absolute = fs::canonicalize(document).map_err(|error| { + SandboxError::launch( + StrictFailureKind::InvalidRequest, + format!("cannot resolve strict document: {error}"), + ) + })?; + let relative = absolute.strip_prefix(&project_root).map_err(|_| { + SandboxError::launch( + StrictFailureKind::InvalidRequest, + format!( + "strict document `{}` is outside the project root `{}`", + absolute.display(), + project_root.display() + ), + ) + })?; Some(Path::new("/project").join(relative)) } None => None, }; - probe_fn().map_err(|reason| SandboxError::LaunchFailed { message: reason })?; - let bwrap = bwrap_path().ok_or_else(|| SandboxError::LaunchFailed { - message: "bubblewrap disappeared after the probe".to_string(), + probe_fn() + .map_err(|reason| SandboxError::launch(StrictFailureKind::ProbeUnavailable, reason))?; + let bwrap = bwrap_path().ok_or_else(|| { + SandboxError::launch( + StrictFailureKind::ProbeUnavailable, + "bubblewrap disappeared after the probe", + ) })?; let mut args = common_args(); @@ -354,9 +352,10 @@ fn run_with( args.push(argument.clone()); } if !replaced { - return Err(SandboxError::LaunchFailed { - message: "strict launcher could not rewrite the document argument".to_string(), - }); + return Err(SandboxError::launch( + StrictFailureKind::InvalidRequest, + "strict launcher could not rewrite the document argument", + )); } let stdout = CaptureFile::create("stdout")?; @@ -372,8 +371,11 @@ fn run_with( limit, cpu_limit, ) - .map_err(|error| SandboxError::LaunchFailed { - message: format!("cannot start the strict supervisor: {error}"), + .map_err(|error| { + SandboxError::launch( + StrictFailureKind::SpawnFailed, + format!("cannot start the strict supervisor: {error}"), + ) })?; let status = match wait_with_deadline(&mut child, timeout) { @@ -384,7 +386,7 @@ fn run_with( let _ = child.wait(); let _ = stdout.read_all(); let _ = stderr.read_all(); - return Err(SandboxError::LaunchFailed { message }); + return Err(SandboxError::launch(StrictFailureKind::Timeout, message)); } }; @@ -482,8 +484,11 @@ impl CaptureFile { .write(true) .create_new(true) .open(&path) - .map_err(|error| SandboxError::LaunchFailed { - message: format!("cannot create strict capture file: {error}"), + .map_err(|error| { + SandboxError::launch( + StrictFailureKind::Io, + format!("cannot create strict capture file: {error}"), + ) })?; Ok(Self { path, @@ -494,24 +499,32 @@ impl CaptureFile { fn reopen(&self) -> Result { self.file .as_ref() - .ok_or_else(|| SandboxError::LaunchFailed { - message: "strict capture file is closed".to_string(), + .ok_or_else(|| { + SandboxError::launch(StrictFailureKind::Io, "strict capture file is closed") })? .try_clone() - .map_err(|error| SandboxError::LaunchFailed { - message: format!("cannot clone strict capture file: {error}"), + .map_err(|error| { + SandboxError::launch( + StrictFailureKind::Io, + format!("cannot clone strict capture file: {error}"), + ) }) } fn read_all(&self) -> Result, SandboxError> { - let mut file = fs::File::open(&self.path).map_err(|error| SandboxError::LaunchFailed { - message: format!("cannot read strict capture file: {error}"), + let mut file = fs::File::open(&self.path).map_err(|error| { + SandboxError::launch( + StrictFailureKind::Io, + format!("cannot read strict capture file: {error}"), + ) })?; let mut bytes = Vec::new(); - file.read_to_end(&mut bytes) - .map_err(|error| SandboxError::LaunchFailed { - message: format!("cannot read strict capture file: {error}"), - })?; + file.read_to_end(&mut bytes).map_err(|error| { + SandboxError::launch( + StrictFailureKind::Io, + format!("cannot read strict capture file: {error}"), + ) + })?; Ok(bytes) } } @@ -566,7 +579,8 @@ mod tests { let _ = fs::remove_dir_all(&project); match &error { - SandboxError::LaunchFailed { message } => { + SandboxError::LaunchFailed { kind, message } => { + assert_eq!(*kind, StrictFailureKind::SpawnFailed); assert!( message.contains("cannot start the strict supervisor"), "unexpected launch diagnostic: {message}" @@ -601,7 +615,12 @@ mod tests { |_, _, _, _, _, _| unreachable!("host root must be rejected before spawning"), ) .expect_err("host root must be rejected"); - assert!(matches!(error, SandboxError::LaunchFailed { .. })); + match &error { + SandboxError::LaunchFailed { kind, .. } => { + assert_eq!(*kind, StrictFailureKind::InvalidRequest); + } + other => panic!("expected LaunchFailed, got {other:?}"), + } assert!(error.to_string().contains("host root")); } } diff --git a/docs/adr/0053-strict-child-inspection-and-json-failure-contract.md b/docs/adr/0053-strict-child-inspection-and-json-failure-contract.md new file mode 100644 index 0000000..44e377f --- /dev/null +++ b/docs/adr/0053-strict-child-inspection-and-json-failure-contract.md @@ -0,0 +1,88 @@ +# ADR-0053: Platform-neutral strict child inspection and the strict `--json` failure contract + +Status: **Accepted** +Date: 2026-11-21 +Relates to: ADR-0021, ADR-0019, RFC-CI-0001 (B01/B02), `spec/security.md` §1.2 +Supersedes: nothing + +## Context + +Two release-blocking defects were observed at `32d8fe1`: + +1. `crates/cli/src/commands/run.rs` called `marqdo_sandbox::marker_present` and + `verify_active` directly. Those functions are exported only under + `#[cfg(target_os = "linux")]`, so macOS and Windows builds failed with + `E0425`. `cfg!(target_os = "linux")` was not a fix: both branches are still + type-checked. +2. When the strict probe succeeded but Bubblewrap could not construct the + namespaces at launch time, the supervisor wrote its diagnostic to stderr + only. In `--json` mode the consumer received an empty stdout and failed to + parse it (`EOF while parsing a value at line 1 column 0`), even though + strict correctly refused to execute project code. + +The same design also let probe-time availability and launch-time capability +drift apart without a deterministic test seam for the failure classification. + +## Decision + +### 1. One platform-neutral child API + +`marqdo-sandbox` exposes `StrictChildState { NotChild, VerifiedChild }` and +`inspect_strict_child()`. Linux performs the existing marker **and** identity +verification (PID 1, NoNewPrivs, empty CapEff, unshared uid map, no +non-loopback interface). Every other platform returns `NotChild` only when the +marker is absent, and returns an error when `MARQDO_STRICT_ACTIVE` is set: a +forged marker never authorizes strict execution. `marker_present` and +`verify_active` are no longer re-exported from the crate root. + +### 2. Capture, classify, then route + +The CLI uses `launch_strict_capture` and classifies the captured outcome before +writing anything. The `StrictOutcome` type is platform-neutral; non-Linux +builds compile the same routing code and receive `StrictUnavailable` instead of +a Linux-only symbol. + +Control-plane failures (probe, spawn, namespace construction, timeout, capture) +are never forwarded as child output. In `--json` mode they emit exactly one +document: + +```json +{"command": "run", "success": false, "error": "...", "code": "strict.spawn_failed"} +``` + +A verified child's successful `--json` output is forwarded unchanged. Anything +that is not exactly one JSON document is rejected as `strict.child_invalid`; +raw Bubblewrap text is never emitted as the program's stdout. A child that +produced valid program JSON keeps its own exit code. + +Stable codes: + +| Code | Meaning | +|---|---| +| `strict.probe_unavailable` | strict isolation is not available on this host | +| `strict.spawn_failed` | the supervisor process could not be spawned | +| `strict.namespace_failure` | the supervisor could not construct namespaces | +| `strict.timeout` | the supervisor exceeded its wall-clock budget | +| `strict.resource_limit` | a signal/rlimit terminated the supervised child | +| `strict.child_invalid` | the child produced no single JSON document | +| `strict.identity_invalid` | a marker was present without a verified identity | +| `strict.unsupported_grant` | strict L1 rejected an external grant flag | + +The names are frozen by this ADR; adding a code requires a new ADR or an +explicit amendment. + +### 3. Fail closed remains absolute + +Probe success is not a promise. A launch failure after a successful probe is a +strict refusal, never a fallback to `pure`/`project`, and never executes project +code without the supervisor. The injectable `run_with` seam in +`crates/marqdo-sandbox/src/linux.rs` keeps that path deterministically testable. + +## Consequences + +* macOS/Windows compile the same CLI run path; they still report strict as + unavailable and never fake an isolation adapter. +* `--json` consumers always parse one document, on every platform and every + refusal path covered by the contract. +* Failure classification is testable without relying on a host's namespace + capacity; the disposable-VM lane remains the authority for real isolation. diff --git a/docs/adr/README.md b/docs/adr/README.md index f6fadca..b3da25f 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -29,5 +29,7 @@ architecture; read them as decision history. [`docs/architecture/CURRENT.md`](../architecture/CURRENT.md); for executed status see [`docs/STATUS.md`](../STATUS.md). -Files: `0001`–`0050`, plus `0051-byte-exact-http-framing.md` (HTTP framing) and -`0052-unified-markdown-semantics.md` (current language mapping). +Files: `0001`–`0050`, plus `0051-byte-exact-http-framing.md` (HTTP framing), +`0052-unified-markdown-semantics.md` (current language mapping) and +`0053-strict-child-inspection-and-json-failure-contract.md` (strict CI/JSON +failure contract). diff --git a/spec/security.md b/spec/security.md index d48fb7b..c9c3036 100644 --- a/spec/security.md +++ b/spec/security.md @@ -57,6 +57,32 @@ produces no IR and therefore cannot cause a host effect at all. No heading annotation, keyword or Markdown container can grant a file/network/process capability, and permission flags never change the AST→IR result. +### 1.2 Strict failure and `--json` contract + +Strict execution is a two-phase operation: detect, then launch. Availability +observed by `inspect --platform` is a snapshot, not a permanent promise. The +runtime therefore re-probes before launching; a failure after a successful +probe is a refusal, never a fallback. + +`--json` consumers must receive **exactly one** JSON document on stdout for +every outcome: + +* a verified child in `--json` mode produces that document itself and its + bytes and exit code are forwarded unchanged; +* a control-plane failure (probe, supervisor spawn, namespace construction, + timeout, capture) produces one CLI error document + `{"command": ..., "success": false, "error": ..., "code": ...}`; +* output that is empty or is not exactly one JSON document is rejected as + `strict.child_invalid`; raw supervisor text is never forwarded as program + stdout. + +The stable codes are `strict.probe_unavailable`, `strict.spawn_failed`, +`strict.namespace_failure`, `strict.timeout`, `strict.resource_limit`, +`strict.child_invalid`, `strict.identity_invalid` and +`strict.unsupported_grant` (ADR-0053). A marker alone never authorizes strict +execution: Linux verifies the namespace/privilege identity, and every other +platform rejects `MARQDO_STRICT_ACTIVE` outright (ADR-0053). + ## 2. Capability grants `Capabilities` (`crates/marqdo-host/src/capability.rs`) is the effective grant