diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ad044d6..02516345 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,20 +21,20 @@ jobs: name: Rust runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: # This job executes repository code (cargo build/test); don't persist # the token in git config. persist-credentials: false submodules: true - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable with: components: rustfmt, clippy - - uses: taiki-e/install-action@cargo-llvm-cov + - uses: taiki-e/install-action@be76f545a6a2f94fb131c5bb748ebed32edb5760 # cargo-llvm-cov - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - name: Check formatting run: cargo fmt --all -- --check @@ -56,24 +56,43 @@ jobs: - name: Upload coverage report if: ${{ always() }} - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: coverage-json path: coverage.json if-no-files-found: ignore + jail-platforms: + name: Jail (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + submodules: true + - uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - name: Constraint and jail tests + run: cargo test -p tinybox-core -p tinybox-jail --all-features + - name: Jail without Landlock feature + run: cargo test -p tinybox-jail --no-default-features + docs: name: Docs runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false submodules: true - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - name: Build documentation env: @@ -84,7 +103,7 @@ jobs: name: Minimum supported Rust version runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false submodules: true @@ -106,11 +125,11 @@ jobs: fi echo "version=$msrv" >> "$GITHUB_OUTPUT" - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f # master with: toolchain: ${{ steps.msrv.outputs.version }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - name: Build with the declared MSRV run: cargo build --all-targets --all-features @@ -119,12 +138,12 @@ jobs: name: Supply chain runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false submodules: true - name: Check advisories, licenses, bans, and sources - uses: EmbarkStudios/cargo-deny-action@v2 + uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2 with: command: check all diff --git a/README.md b/README.md index c3328c4b..4d2502e3 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ workspace: alpine:3 runner: local / docker isolation: kernel untrusted: safe -supports: filesystem snapshots, forking, resource limits +supports: filesystem snapshots, forking ``` Snapshot a box and branch it — the fork inherits the parent's filesystem and @@ -398,3 +398,6 @@ Arch Linux; macOS 15 and 26 on Intel and Apple Silicon; Windows Server 2022 and ## License GPL-3.0-only. See [LICENSE](LICENSE). + +Per-constraint hard preflight and current backend limitations are documented in +[constraint preflight](docs/specs/constraint-preflight.md). diff --git a/crates/tinybox-cli/src/command/mod_tests.rs b/crates/tinybox-cli/src/command/mod_tests.rs index 43645627..31d760cd 100644 --- a/crates/tinybox-cli/src/command/mod_tests.rs +++ b/crates/tinybox-cli/src/command/mod_tests.rs @@ -787,7 +787,7 @@ async fn inspecting_a_docker_box_reports_kernel_isolation() -> Result<()> { assert!( inspected .out - .contains("filesystem snapshots, forking, port forwarding, resource limits") + .contains("filesystem snapshots, forking, port forwarding") ); // The workspace column shows the image, not a Debug dump. assert!(inspected.out.contains("workspace: alpine:3")); diff --git a/crates/tinybox-core/src/constraint/README.md b/crates/tinybox-core/src/constraint/README.md new file mode 100644 index 00000000..c592a417 --- /dev/null +++ b/crates/tinybox-core/src/constraint/README.md @@ -0,0 +1,12 @@ +# Constraint preflight + +The public model separates individual security boundaries from lifecycle +capabilities. `ConstraintSupport::NONE` is the conservative declaration. +Backends add only enforced or best-effort behavior they actually implement. +`plan_check` is diagnostic and performs no execution; `require` rejects every +requested boundary except `Enforced`, returning a typed error. Setup failures +must still propagate from the backend rather than degrading to passthrough. + +The model is used by the object-safe `Sandbox` trait and by `tinybox-jail`. +See [the specification](../../../../docs/specs/constraint-preflight.md) for +backend limitations and the meaning of each hard requirement. diff --git a/crates/tinybox-core/src/constraint/mod.rs b/crates/tinybox-core/src/constraint/mod.rs new file mode 100644 index 00000000..3b380419 --- /dev/null +++ b/crates/tinybox-core/src/constraint/mod.rs @@ -0,0 +1,138 @@ +//! Per-constraint preflight, independent of coarse lifecycle capabilities. +//! +//! A declaration describes implemented enforcement, not merely a configurable +//! knob. Callers must still handle setup failures. Best-effort support is never +//! accepted as a hard requirement. Unknown backends default to unsupported. + +/// A security boundary requested before starting a workload. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Constraint { + /// Confine filesystem reads and writes to the granted paths. + Filesystem, + /// Deny external network access. + Network, + /// Cap CPU consumption. + Cpu, + /// Cap resident memory. + Memory, + /// Cap total processes and threads. + Pids, + /// Cap writable disk usage. + Disk, + /// Forbid creating child processes. + Subprocess, +} + +impl Constraint { + /// All modeled constraints, in diagnostic order. + pub const ALL: [Self; 7] = [ + Self::Filesystem, + Self::Network, + Self::Cpu, + Self::Memory, + Self::Pids, + Self::Disk, + Self::Subprocess, + ]; + const fn index(self) -> usize { + self as usize + } +} + +impl std::fmt::Display for Constraint { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::Filesystem => "filesystem", + Self::Network => "network", + Self::Cpu => "cpu", + Self::Memory => "memory", + Self::Pids => "pids", + Self::Disk => "disk", + Self::Subprocess => "subprocess", + }) + } +} + +/// What a backend actually implements for one constraint. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Enforcement { + /// No implementation, including unavailable platform mechanisms. + Unsupported, + /// Partial or advisory implementation, unsuitable for a hard requirement. + BestEffort, + /// Full implementation; failure to apply it must prevent execution. + Enforced, +} + +impl std::fmt::Display for Enforcement { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::Unsupported => "unsupported", + Self::BestEffort => "best effort", + Self::Enforced => "enforced", + }) + } +} + +/// Independent enforcement declarations for all constraints. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ConstraintSupport([Enforcement; 7]); +impl Default for ConstraintSupport { + fn default() -> Self { + Self::NONE + } +} +impl ConstraintSupport { + /// Conservative declaration for unknown and passthrough backends. + pub const NONE: Self = Self([Enforcement::Unsupported; 7]); + /// Declare the actual enforcement of one constraint. + #[must_use] + pub const fn with(mut self, constraint: Constraint, enforcement: Enforcement) -> Self { + self.0[constraint.index()] = enforcement; + self + } + /// Inspect an individual constraint. + #[must_use] + pub const fn enforcement(self, constraint: Constraint) -> Enforcement { + self.0[constraint.index()] + } + /// Inspect all requested constraints without executing anything. + #[must_use] + pub fn plan_check(self, requested: &[Constraint]) -> PlanCheck { + PlanCheck { + constraints: requested + .iter() + .map(|c| (*c, self.enforcement(*c))) + .collect(), + } + } + /// Refuse the first hard constraint that is not fully enforced. + /// + /// # Errors + /// Returns [`crate::Error::ConstraintNotEnforced`] for unsupported or + /// best-effort constraints. No workload is started. + pub fn require(self, backend: &str, requested: &[Constraint]) -> crate::Result<()> { + for &constraint in requested { + let enforcement = self.enforcement(constraint); + if enforcement != Enforcement::Enforced { + return Err(crate::Error::ConstraintNotEnforced { + sandbox: backend.to_owned(), + constraint, + enforcement, + }); + } + } + Ok(()) + } +} + +/// Preflight diagnostics, including best-effort and unsupported constraints. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlanCheck { + /// Each requested constraint and its actual enforcement. + pub constraints: Vec<(Constraint, Enforcement)>, +} + +#[cfg(test)] +#[path = "mod_tests.rs"] +mod tests; diff --git a/crates/tinybox-core/src/constraint/mod_tests.rs b/crates/tinybox-core/src/constraint/mod_tests.rs new file mode 100644 index 00000000..622244a4 --- /dev/null +++ b/crates/tinybox-core/src/constraint/mod_tests.rs @@ -0,0 +1,55 @@ +//! Hard requirements never accept partial enforcement. +use super::*; +#[test] +fn every_constraint_refuses_unsupported_and_best_effort() { + for constraint in Constraint::ALL { + for enforcement in [ + Enforcement::Unsupported, + Enforcement::BestEffort, + Enforcement::Enforced, + ] { + let support = ConstraintSupport::NONE.with(constraint, enforcement); + assert_eq!( + support.plan_check(&[constraint]).constraints, + [(constraint, enforcement)] + ); + let result = support.require("backend", &[constraint]); + if enforcement == Enforcement::Enforced { + assert!(result.is_ok()); + } else { + assert_eq!( + result.err(), + Some(crate::Error::ConstraintNotEnforced { + sandbox: "backend".into(), + constraint, + enforcement + }) + ); + } + } + } + assert_eq!(ConstraintSupport::default(), ConstraintSupport::NONE); + assert!(ConstraintSupport::NONE.require("backend", &[]).is_ok()); +} + +#[test] +fn every_constraint_and_enforcement_has_a_lowercase_operator_label() { + for (constraint, expected) in Constraint::ALL.into_iter().zip([ + "filesystem", + "network", + "cpu", + "memory", + "pids", + "disk", + "subprocess", + ]) { + assert_eq!(constraint.to_string(), expected); + } + for (enforcement, expected) in [ + (Enforcement::Unsupported, "unsupported"), + (Enforcement::BestEffort, "best effort"), + (Enforcement::Enforced, "enforced"), + ] { + assert_eq!(enforcement.to_string(), expected); + } +} diff --git a/crates/tinybox-core/src/error/mod.rs b/crates/tinybox-core/src/error/mod.rs index f6995adb..ba6828a9 100644 --- a/crates/tinybox-core/src/error/mod.rs +++ b/crates/tinybox-core/src/error/mod.rs @@ -39,6 +39,17 @@ pub enum Error { capability: Capability, }, + /// A hard constraint could not be fully enforced before execution. + #[error("sandbox {sandbox} cannot enforce {constraint}: {enforcement}")] + ConstraintNotEnforced { + /// Backend refusing the request. + sandbox: String, + /// Requested security boundary. + constraint: crate::Constraint, + /// Actual level of support. + enforcement: crate::Enforcement, + }, + /// A resource limit was zero, and every limit tinybox applies must be /// positive to be meaningful. #[error("resource limit {limit} must be greater than zero")] diff --git a/crates/tinybox-core/src/error/mod_tests.rs b/crates/tinybox-core/src/error/mod_tests.rs index 8eaa4f5f..8ff4ea60 100644 --- a/crates/tinybox-core/src/error/mod_tests.rs +++ b/crates/tinybox-core/src/error/mod_tests.rs @@ -84,3 +84,16 @@ fn errors_implement_the_standard_error_trait() { assert_eq!(as_std.to_string(), "no box with id build-1"); assert!(as_std.source().is_none()); } + +#[test] +fn constraint_refusals_use_lowercase_user_facing_labels() { + let error = Error::ConstraintNotEnforced { + sandbox: "seatbelt".into(), + constraint: crate::Constraint::Filesystem, + enforcement: crate::Enforcement::BestEffort, + }; + assert_eq!( + error.to_string(), + "sandbox seatbelt cannot enforce filesystem: best effort" + ); +} diff --git a/crates/tinybox-core/src/lib.rs b/crates/tinybox-core/src/lib.rs index 1faf0c63..0c218131 100644 --- a/crates/tinybox-core/src/lib.rs +++ b/crates/tinybox-core/src/lib.rs @@ -73,6 +73,9 @@ pub mod spec; pub mod store; pub mod template; +pub mod constraint; +pub use constraint::{Constraint, ConstraintSupport, Enforcement, PlanCheck}; + pub use capability::{Capability, IsolationLevel, SandboxCapabilities, SnapshotSupport}; pub use clock::{Clock, SystemClock}; pub use error::{Error, Result}; diff --git a/crates/tinybox-core/src/runtime/mod.rs b/crates/tinybox-core/src/runtime/mod.rs index d590df7e..eee2f1d8 100644 --- a/crates/tinybox-core/src/runtime/mod.rs +++ b/crates/tinybox-core/src/runtime/mod.rs @@ -102,6 +102,29 @@ pub trait Sandbox: std::fmt::Debug + Send + Sync + 'static { /// unsupported requests before they reach the implementation. fn capabilities(&self) -> SandboxCapabilities; + /// Per-constraint enforcement, conservatively unsupported by default. + fn constraint_support(&self) -> crate::ConstraintSupport { + crate::ConstraintSupport::NONE + } + + /// Inspect a requested execution plan without starting a workload. + fn plan_check(&self, requested: &[crate::Constraint]) -> crate::PlanCheck { + self.constraint_support().plan_check(requested) + } + + /// Require fully implemented constraints before allocating or executing. + /// + /// This checks declarations only; callers must still propagate backend + /// setup failures. Call it explicitly before [`Self::create`] when a + /// constraint is mandatory: lifecycle methods do not automatically treat + /// every resource field in a [`BoxSpec`] as a hard requirement. + /// + /// # Errors + /// Returns [`Error::ConstraintNotEnforced`] for partial or absent support. + fn require(&self, requested: &[crate::Constraint]) -> Result<()> { + self.constraint_support().require(self.name(), requested) + } + /// Create a box from `spec` without starting any workload in it. /// /// # Errors diff --git a/crates/tinybox-core/src/runtime/mod_tests.rs b/crates/tinybox-core/src/runtime/mod_tests.rs index c18e9ac1..7eae1849 100644 --- a/crates/tinybox-core/src/runtime/mod_tests.rs +++ b/crates/tinybox-core/src/runtime/mod_tests.rs @@ -526,3 +526,22 @@ mod defaults { Ok(()) } } + +#[test] +fn unknown_sandbox_constraints_are_conservative_through_a_trait_object() { + let sandbox: &dyn Sandbox = &FakeSandbox::new(CONTAINER); + assert_eq!(sandbox.constraint_support(), crate::ConstraintSupport::NONE); + assert_eq!( + sandbox + .plan_check(&crate::Constraint::ALL) + .constraints + .len(), + 7 + ); + for constraint in crate::Constraint::ALL { + assert!(matches!( + sandbox.require(&[constraint]), + Err(Error::ConstraintNotEnforced { .. }) + )); + } +} diff --git a/crates/tinybox-docker/src/sandbox/mod.rs b/crates/tinybox-docker/src/sandbox/mod.rs index ffb6f113..02944681 100644 --- a/crates/tinybox-docker/src/sandbox/mod.rs +++ b/crates/tinybox-docker/src/sandbox/mod.rs @@ -125,7 +125,6 @@ impl DockerSandbox { pub const fn declared_capabilities() -> SandboxCapabilities { SandboxCapabilities::new(IsolationLevel::Kernel, SnapshotSupport::Filesystem) .with_fork() - .with_resource_limits() .with_port_forward() .with_detach() } @@ -159,6 +158,17 @@ impl Sandbox for DockerSandbox { Self::declared_capabilities() } + fn constraint_support(&self) -> tinybox_core::ConstraintSupport { + use tinybox_core::Constraint::{Cpu, Filesystem, Memory, Network, Pids}; + use tinybox_core::Enforcement::Enforced; + tinybox_core::ConstraintSupport::NONE + .with(Filesystem, Enforced) + .with(Network, Enforced) + .with(Cpu, Enforced) + .with(Memory, Enforced) + .with(Pids, Enforced) + } + async fn create(&self, spec: &BoxSpec) -> Result { spec.validate()?; // Claim the record first. A container is expensive to create and has to diff --git a/crates/tinybox-docker/src/sandbox/mod_tests.rs b/crates/tinybox-docker/src/sandbox/mod_tests.rs index b3807b11..b60d9a3f 100644 --- a/crates/tinybox-docker/src/sandbox/mod_tests.rs +++ b/crates/tinybox-docker/src/sandbox/mod_tests.rs @@ -121,7 +121,7 @@ fn it_declares_kernel_isolation_and_filesystem_snapshots() { // The first backend that is a defensible place for untrusted code. assert!(caps.is_suitable_for_untrusted_code()); assert!(caps.supports(Capability::Fork)); - assert!(caps.supports(Capability::ResourceLimits)); + assert!(!caps.supports(Capability::ResourceLimits)); // `docker pause` exists, but no trait method reaches it, so it is not // claimed. assert!(!caps.supports(Capability::PauseResume)); @@ -851,3 +851,38 @@ fn detach_is_declared_because_a_container_persists_between_commands() { assert!(declared.supports(Capability::Detach)); } + +#[test] +fn preflight_reports_each_enforced_boundary_without_claiming_disk() { + use tinybox_core::{Constraint, Enforcement}; + let (backend, _, _) = sandbox(); + let support = backend.constraint_support(); + assert_eq!( + support.enforcement(Constraint::Filesystem), + Enforcement::Enforced + ); + assert_eq!( + support.enforcement(Constraint::Network), + Enforcement::Enforced + ); + assert_eq!(support.enforcement(Constraint::Cpu), Enforcement::Enforced); + assert_eq!( + support.enforcement(Constraint::Memory), + Enforcement::Enforced + ); + assert_eq!(support.enforcement(Constraint::Pids), Enforcement::Enforced); + assert_eq!( + support.enforcement(Constraint::Disk), + Enforcement::Unsupported + ); + assert_eq!( + support.enforcement(Constraint::Subprocess), + Enforcement::Unsupported + ); + assert!( + backend + .require(&[Constraint::Filesystem, Constraint::Network]) + .is_ok() + ); + assert!(backend.require(&[Constraint::Disk]).is_err()); +} diff --git a/crates/tinybox-jail/README.md b/crates/tinybox-jail/README.md index ea80fce6..3cf76992 100644 --- a/crates/tinybox-jail/README.md +++ b/crates/tinybox-jail/README.md @@ -156,3 +156,18 @@ not import that module. against a corrupted index pointing at `/`. - Free-form input is length-logged, not value-logged (labels and notes), to avoid leaking arbitrary text into logs. + +## Hard preflight + +Use `spawn_required` or `spawn_required_with` to require every jail constraint. +`JailBackend::plan_check` returns individual enforcement diagnostics and +`require` rejects partial or missing enforcement. Landlock is filesystem-only +and unsuitable for arbitrary untrusted code; denied network or subprocess +requests fail before spawning. Seatbelt permits reads everywhere and scratch +writes. Its launcher-presence check does not verify profile enforcement, so +filesystem, network and subprocess rules all report best effort; strict +preflight refuses them. It reports isolation `None` until enforcement is +verified; a launcher mechanism alone is no isolation guarantee. Noop +reports no isolation or constraints. See +[constraint preflight](../../docs/specs/constraint-preflight.md) for the backend +matrix and the trusted legacy APIs. diff --git a/crates/tinybox-jail/src/jail.rs b/crates/tinybox-jail/src/jail.rs index d0a02c70..61b35082 100644 --- a/crates/tinybox-jail/src/jail.rs +++ b/crates/tinybox-jail/src/jail.rs @@ -71,20 +71,34 @@ impl Jail { self } - /// Asks the backend to block network access where it can. + /// Requests network denial; strict preflight refuses unsupported backends. #[must_use] pub fn deny_net(mut self) -> Self { self.allow_net = false; self } - /// Asks the backend to forbid spawning further subprocesses where it can. + /// Requests subprocess denial; strict preflight refuses unsupported backends. #[must_use] pub fn deny_subprocess(mut self) -> Self { self.allow_subprocess = false; self } + /// Hard constraints implied by this jail's grants and denial flags. + #[must_use] + pub fn constraints(&self) -> Vec { + use tinybox_core::Constraint; + let mut constraints = vec![Constraint::Filesystem]; + if !self.allow_net { + constraints.push(Constraint::Network); + } + if !self.allow_subprocess { + constraints.push(Constraint::Subprocess); + } + constraints + } + /// Canonicalize `root`, `read_only` and `read_write` so backends never see `..` or /// symlink trickery. Returns an error if `root` does not exist. /// @@ -130,6 +144,39 @@ pub trait JailBackend: Send + Sync { /// a backend. fn is_available(&self) -> bool; + /// Declares implemented constraints; unknown backends claim nothing. + fn constraint_support(&self) -> tinybox_core::ConstraintSupport { + tinybox_core::ConstraintSupport::NONE + } + + /// Process isolation provided by this backend, independent of path checks. + fn isolation(&self) -> tinybox_core::IsolationLevel { + tinybox_core::IsolationLevel::None + } + + /// Whether the backend confines processes sufficiently for untrusted code. + fn is_suitable_for_untrusted_code(&self) -> bool { + self.isolation() >= tinybox_core::IsolationLevel::Kernel + && self + .constraint_support() + .enforcement(tinybox_core::Constraint::Filesystem) + == tinybox_core::Enforcement::Enforced + } + + /// Inspect all hard constraints a directory jail requests. + fn plan_check(&self, jail: &Jail) -> tinybox_core::PlanCheck { + self.constraint_support().plan_check(&jail.constraints()) + } + + /// Refuse incomplete filesystem, network or subprocess confinement. + /// + /// # Errors + /// Returns a typed constraint refusal before any child is spawned. + fn require(&self, jail: &Jail) -> tinybox_core::Result<()> { + self.constraint_support() + .require(self.name(), &jail.constraints()) + } + /// Spawn `cmd` under the jail described by `jail`. Backends own how the /// jail is materialized (Landlock ruleset, sandbox-exec wrapper, /// `AppContainer` profile + restricted token). diff --git a/crates/tinybox-jail/src/lib.rs b/crates/tinybox-jail/src/lib.rs index 94101b95..136224e4 100644 --- a/crates/tinybox-jail/src/lib.rs +++ b/crates/tinybox-jail/src/lib.rs @@ -88,6 +88,9 @@ pub fn default_backend() -> Arc { /// `NotFound` (canonicalize bubbles it up) — callers should create the /// workspace before encapsulating. /// +/// This legacy entry point does not require fully enforced constraints. Use +/// [`spawn_required`] for a hard preflight before spawning. +/// /// # Errors /// /// Returns an error if the jail root cannot be canonicalized or the backend @@ -102,6 +105,9 @@ pub fn spawn(jail: &Jail, cmd: Command) -> std::io::Result { /// tests and for callers that want to opt into a weaker backend /// explicitly (e.g. forcing [`NoopBackend`] during local dev). /// +/// This legacy entry point does not run [`JailBackend::require`]. Use +/// [`spawn_required_with`] when partial or absent enforcement must be refused. +/// /// # Errors /// /// Returns an error if the jail root cannot be canonicalized or the backend @@ -112,6 +118,36 @@ pub fn spawn_with(backend: &dyn JailBackend, jail: &Jail, cmd: Command) -> std:: backend.spawn(&jail, cmd) } +/// Spawn only after all jail constraints pass a hard preflight. +/// +/// This strict entry point rejects the explicitly trusted no-op backend and +/// Seatbelt's partial filesystem policy. Landlock can satisfy filesystem-only +/// requests, but offers no process isolation and is unsuitable for arbitrary +/// untrusted code. Availability and actual policy application are also checked +/// by the backend when spawning. +/// +/// # Errors +/// Returns `Unsupported` before spawning for partial or unsupported constraints, +/// or a filesystem/backend error while canonicalizing or applying the policy. +pub fn spawn_required_with( + backend: &dyn JailBackend, + jail: &Jail, + cmd: Command, +) -> std::io::Result { + backend + .require(jail) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::Unsupported, error))?; + spawn_with(backend, jail, cmd) +} + +/// Spawn using the detected backend after a hard preflight. +/// +/// # Errors +/// Returns the same preflight and setup errors as [`spawn_required_with`]. +pub fn spawn_required(jail: &Jail, cmd: Command) -> std::io::Result { + spawn_required_with(default_backend().as_ref(), jail, cmd) +} + #[cfg(test)] #[path = "mod_tests.rs"] mod tests; diff --git a/crates/tinybox-jail/src/linux.rs b/crates/tinybox-jail/src/linux.rs index 5aa28f10..1aecfdf4 100644 --- a/crates/tinybox-jail/src/linux.rs +++ b/crates/tinybox-jail/src/linux.rs @@ -22,8 +22,8 @@ //! directory (`~/.ssh`, `~/.aws`, ...), `/proc` and `/sys`, and `/tmp`. A host //! that wants a scratch directory grants it with `add_read_write`. //! -//! Landlock does not gate the network or process creation, so `allow_net` and -//! `allow_subprocess` are not enforced by this backend. +//! This implementation does not install Landlock network rules or gate process +//! creation. Network and subprocess denial requests are refused before spawn. //! //! # Failing closed on old kernels //! @@ -100,7 +100,26 @@ impl JailBackend for LandlockBackend { imp::kernel_supports_landlock() } + fn constraint_support(&self) -> tinybox_core::ConstraintSupport { + if self.is_available() { + tinybox_core::ConstraintSupport::NONE.with( + tinybox_core::Constraint::Filesystem, + tinybox_core::Enforcement::Enforced, + ) + } else { + tinybox_core::ConstraintSupport::NONE + } + } + fn spawn(&self, jail: &Jail, cmd: Command) -> io::Result { + let requested: Vec<_> = jail + .constraints() + .into_iter() + .filter(|c| *c != tinybox_core::Constraint::Filesystem) + .collect(); + self.constraint_support() + .require(self.name(), &requested) + .map_err(|error| io::Error::new(io::ErrorKind::Unsupported, error))?; imp::spawn(jail, cmd) } } @@ -150,7 +169,7 @@ mod imp { pub(super) fn kernel_supports_landlock() -> bool { Ruleset::default() .set_compatibility(CompatLevel::HardRequirement) - .handle_access(AccessFs::ReadFile) + .handle_access(writes() | reads()) .and_then(Ruleset::create) .is_ok() } @@ -285,9 +304,7 @@ mod imp { #[cfg(not(feature = "landlock"))] mod imp { - use std::fs::File; use std::io; - use std::os::fd::AsFd; use std::process::{Child, Command}; use crate::jail::Jail; diff --git a/crates/tinybox-jail/src/macos.rs b/crates/tinybox-jail/src/macos.rs index 3aad2060..b662ce25 100644 --- a/crates/tinybox-jail/src/macos.rs +++ b/crates/tinybox-jail/src/macos.rs @@ -41,10 +41,20 @@ impl JailBackend for SeatbeltBackend { "seatbelt" } + /// Checks launcher presence only; this is not an enforcement probe. fn is_available(&self) -> bool { std::path::Path::new("/usr/bin/sandbox-exec").exists() } + fn constraint_support(&self) -> tinybox_core::ConstraintSupport { + declared_constraint_support(self.is_available()) + } + + /// Launcher presence proves no process-isolation guarantee. + fn isolation(&self) -> tinybox_core::IsolationLevel { + tinybox_core::IsolationLevel::None + } + fn spawn(&self, jail: &Jail, cmd: Command) -> std::io::Result { let mut wrapper = prepare_command(jail, &cmd, std::ffi::OsStr::new("/usr/bin/sandbox-exec")); @@ -54,6 +64,7 @@ impl JailBackend for SeatbeltBackend { // it only the launcher dies while the shell pipeline it started runs // on. (Linux and the no-op backend spawn `cmd` itself, so the caller's // setting applies there.) + #[cfg(unix)] { use std::os::unix::process::CommandExt; wrapper.process_group(0); @@ -62,6 +73,18 @@ impl JailBackend for SeatbeltBackend { } } +/// Executable presence does not prove the host enforces Seatbelt profiles. +fn declared_constraint_support(available: bool) -> tinybox_core::ConstraintSupport { + use tinybox_core::{Constraint, ConstraintSupport, Enforcement}; + if !available { + return ConstraintSupport::NONE; + } + ConstraintSupport::NONE + .with(Constraint::Filesystem, Enforcement::BestEffort) + .with(Constraint::Network, Enforcement::BestEffort) + .with(Constraint::Subprocess, Enforcement::BestEffort) +} + /// Build the launcher separately so forwarding can be checked on any host. fn prepare_command(jail: &Jail, cmd: &Command, launcher: &std::ffi::OsStr) -> Command { let profile = render_profile(jail); diff --git a/crates/tinybox-jail/src/macos_tests.rs b/crates/tinybox-jail/src/macos_tests.rs index 09f59261..8e11b351 100644 --- a/crates/tinybox-jail/src/macos_tests.rs +++ b/crates/tinybox-jail/src/macos_tests.rs @@ -295,6 +295,25 @@ fn assert_default_name(name: &str) { fn launcher_does_not_restore_inherited_environment_after_env_clear() -> std::io::Result<()> { use std::os::unix::fs::PermissionsExt; + const SENTINEL: &str = "TINYBOX_JAIL_TEST_INHERITED_SECRET"; + if std::env::var_os(SENTINEL).is_none() { + // Set a parent-only sentinel in a subprocess; never mutate the shared + // environment of parallel test threads. + let output = Command::new(std::env::current_exe()?) + .args([ + "--exact", + "macos::tests::launcher_does_not_restore_inherited_environment_after_env_clear", + "--nocapture", + ]) + .env(SENTINEL, "parent-only-secret") + .output()?; + assert!( + output.status.success(), + "isolated test failed: {}", + String::from_utf8_lossy(&output.stdout) + ); + return Ok(()); + } let root = tempfile::tempdir()?; let launcher = root.path().join("launcher"); fs::write(&launcher, "#!/bin/sh\nshift 2\nexec \"$@\"\n")?; @@ -308,13 +327,14 @@ fn launcher_does_not_restore_inherited_environment_after_env_clear() -> std::io: ) .output()?; assert!(output.status.success()); - // Some shells add PWD while executing a script. No inherited parent keys - // should survive, and the explicitly supplied value must still be there. + // The shell may synthesize PWD/SHLVL and other local variables. The + // boundary is the parent sentinel, not a whitelist of shell internals. let env = String::from_utf8_lossy(&output.stdout); assert!(env.lines().any(|line| line == "JAIL_EXPLICIT=allowed")); assert!( - env.lines() - .all(|line| line.starts_with("JAIL_EXPLICIT=") || line.starts_with("PWD=")) + !env.lines() + .any(|line| line.starts_with(&format!("{SENTINEL}="))), + "the launcher restored the inherited parent sentinel" ); Ok(()) } @@ -376,3 +396,30 @@ fn launcher_leads_a_process_group_so_a_group_kill_reaches_grandchildren() { fs::remove_dir_all(&root).ok(); assert!(gone, "grandchild {grandchild} survived the group kill"); } + +#[test] +fn executable_presence_cannot_satisfy_hard_seatbelt_denials() { + use tinybox_core::{Constraint, ConstraintSupport, Enforcement}; + assert_eq!(declared_constraint_support(false), ConstraintSupport::NONE); + // No process-isolation guarantee can follow from a launcher-presence check, + // even on macOS where the launcher exists. + assert_eq!( + SeatbeltBackend::new().isolation(), + tinybox_core::IsolationLevel::None + ); + let present = declared_constraint_support(true); + for constraint in [ + Constraint::Filesystem, + Constraint::Network, + Constraint::Subprocess, + ] { + assert_eq!(present.enforcement(constraint), Enforcement::BestEffort); + assert!(matches!( + present.require("seatbelt", &[constraint]), + Err(tinybox_core::Error::ConstraintNotEnforced { + enforcement: Enforcement::BestEffort, + .. + }) + )); + } +} diff --git a/crates/tinybox-jail/src/mod_tests.rs b/crates/tinybox-jail/src/mod_tests.rs index 105c110a..eefabb95 100644 --- a/crates/tinybox-jail/src/mod_tests.rs +++ b/crates/tinybox-jail/src/mod_tests.rs @@ -94,3 +94,165 @@ fn noop_backend_metadata() { assert_eq!(NoopBackend.name(), "noop"); assert!(NoopBackend.is_available()); } + +#[test] +fn strict_noop_preflight_never_spawns_a_command() -> std::io::Result<()> { + use crate::{JailBackend, spawn_required_with}; + use tinybox_core::{Constraint, ConstraintSupport, Enforcement, IsolationLevel}; + let root = tempfile::tempdir()?; + let marker = root.path().join("executed"); + let mut cmd = if cfg!(windows) { + let mut command = std::process::Command::new("cmd"); + command.args(["/C", "echo executed > executed"]); + command + } else { + let mut command = std::process::Command::new("sh"); + command.args(["-c", "printf executed > executed"]); + command + }; + cmd.current_dir(root.path()); + let backend = crate::NoopBackend; + assert_eq!(backend.isolation(), IsolationLevel::None); + assert_eq!(backend.constraint_support(), ConstraintSupport::NONE); + assert!(!backend.is_suitable_for_untrusted_code()); + for jail in [ + crate::Jail::new(root.path(), "strict"), + crate::Jail::new(root.path(), "strict") + .deny_net() + .deny_subprocess(), + ] { + let error = backend.require(&jail).err(); + assert!(matches!( + error, + Some(tinybox_core::Error::ConstraintNotEnforced { + constraint: Constraint::Filesystem, + enforcement: Enforcement::Unsupported, + .. + }) + )); + } + let result = spawn_required_with(&backend, &crate::Jail::new(root.path(), "strict"), cmd); + assert_eq!( + result.err().map(|e| e.kind()), + Some(std::io::ErrorKind::Unsupported) + ); + assert!(!marker.exists()); + Ok(()) +} + +#[cfg(target_os = "linux")] +#[test] +fn landlock_refuses_network_and_subprocess_denials_before_spawning() -> std::io::Result<()> { + use crate::JailBackend; + let backend = crate::LandlockBackend::new(); + let root = tempfile::tempdir()?; + assert!(!backend.is_suitable_for_untrusted_code()); + for jail in [ + crate::Jail::new(root.path(), "net").deny_net(), + crate::Jail::new(root.path(), "child").deny_subprocess(), + ] { + let result = backend.spawn( + &jail, + std::process::Command::new("definitely-not-a-command"), + ); + assert_eq!( + result.err().map(|e| e.kind()), + Some(std::io::ErrorKind::Unsupported) + ); + } + Ok(()) +} + +/// Locate `true` only in the documented Landlock baseline, never in raw PATH. +fn permitted_true() -> std::io::Result { + ["/usr/bin/true", "/bin/true"] + .into_iter() + .map(std::path::PathBuf::from) + .find(|path| path.is_file()) + .ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::NotFound, + "neither baseline executable /usr/bin/true nor /bin/true exists", + ) + }) +} + +#[cfg(target_os = "linux")] +#[test] +fn strict_landlock_filesystem_only_spawn_still_works() -> std::io::Result<()> { + use crate::JailBackend; + let backend = crate::LandlockBackend::new(); + if !backend.is_available() { + return Ok(()); + } + let root = tempfile::tempdir()?; + let executable = permitted_true()?; + let jail = crate::Jail::new(root.path(), "strict-fs").add_read_only(&executable); + assert_eq!( + backend.plan_check(&jail).constraints, + [( + tinybox_core::Constraint::Filesystem, + tinybox_core::Enforcement::Enforced + )] + ); + let mut child = + crate::spawn_required_with(&backend, &jail, std::process::Command::new(&executable))?; + assert!(child.wait()?.success()); + Ok(()) +} + +#[test] +fn seatbelt_launcher_presence_never_claims_verified_enforcement() { + use crate::JailBackend; + use tinybox_core::{Constraint, Enforcement}; + let backend = crate::SeatbeltBackend::new(); + let support = backend.constraint_support(); + assert_eq!(backend.isolation(), tinybox_core::IsolationLevel::None); + assert!(!backend.is_suitable_for_untrusted_code()); + assert_eq!( + support.enforcement(Constraint::Filesystem), + if backend.is_available() { + Enforcement::BestEffort + } else { + Enforcement::Unsupported + } + ); + for constraint in [Constraint::Network, Constraint::Subprocess] { + assert_eq!( + support.enforcement(constraint), + if backend.is_available() { + Enforcement::BestEffort + } else { + Enforcement::Unsupported + } + ); + } +} + +#[test] +fn strict_default_spawn_obeys_the_detected_filesystem_declaration() -> std::io::Result<()> { + use tinybox_core::{Constraint, Enforcement}; + let root = tempfile::tempdir()?; + let mut jail = crate::Jail::new(root.path(), "strict-default"); + let enforced = crate::default_backend() + .constraint_support() + .enforcement(Constraint::Filesystem) + == Enforcement::Enforced; + let command = if enforced { + let executable = permitted_true()?; + jail = jail.add_read_only(&executable); + std::process::Command::new(executable) + } else { + std::process::Command::new("definitely-not-a-command") + }; + let result = crate::spawn_required(&jail, command); + if enforced { + assert!(result?.wait()?.success()); + } else { + assert_eq!( + result.err().map(|error| error.kind()), + Some(std::io::ErrorKind::Unsupported) + ); + } + Ok(()) +} diff --git a/crates/tinybox-jail/src/noop.rs b/crates/tinybox-jail/src/noop.rs index e2c412f7..23c63661 100644 --- a/crates/tinybox-jail/src/noop.rs +++ b/crates/tinybox-jail/src/noop.rs @@ -1,8 +1,7 @@ -//! Fallback backend: no enforcement, just spawns. +//! Explicit trusted passthrough: no enforcement, just spawns. //! -//! Used when no OS-level jail is available (unsupported platform, missing -//! kernel feature, etc.). Callers can still rely on application-layer -//! `validate_path_within_root` checks. +//! Never selected automatically when OS enforcement is unavailable. This +//! backend reports no isolation or constraints; hard preflight refuses it. use std::process::{Child, Command}; diff --git a/crates/tinybox-jail/src/registry.rs b/crates/tinybox-jail/src/registry.rs index 9df263af..6fe2a7ec 100644 --- a/crates/tinybox-jail/src/registry.rs +++ b/crates/tinybox-jail/src/registry.rs @@ -28,7 +28,7 @@ use std::collections::BTreeMap; use std::fs; use std::io; -use std::path::{Path, PathBuf}; +use std::path::{Component, Path, PathBuf}; use std::process::{Child, Command}; use std::sync::Arc; use std::sync::Mutex; @@ -37,8 +37,11 @@ use std::time::UNIX_EPOCH; use serde::{Deserialize, Serialize}; use tinybox_core::clock::{Clock, SystemClock}; +use super::default_backend; use super::jail::{Jail, JailBackend}; -use super::{default_backend, spawn_with}; + +#[path = "registry_path.rs"] +mod path; /// Metadata persisted for each jail. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -99,10 +102,11 @@ impl JailRegistry { /// Returns an error if the registry directory cannot be created or its /// index cannot be read or decoded. pub fn open_with_clock(base: impl AsRef, clock: Arc) -> io::Result { - let base = base.as_ref().to_path_buf(); - fs::create_dir_all(&base)?; + let requested_base = base.as_ref().to_path_buf(); + fs::create_dir_all(&requested_base)?; + let base = requested_base.canonicalize()?; let idx_path = base.join(INDEX_FILENAME); - let index = if idx_path.exists() { + let mut index = if idx_path.exists() { log::debug!( "[cwd_jail] registry.open loading index {}", idx_path.display() @@ -117,6 +121,18 @@ impl JailRegistry { schema_version: INDEX_SCHEMA_VERSION, } }; + // Older records inherited the caller's lexical base (including trusted + // aliases or parent components). Normalize only that exact prefix; + // never normalize parent traversal introduced in a record's suffix. + for record in index.records.values_mut() { + if let Ok(suffix) = record.dir.strip_prefix(&requested_base) + && suffix + .components() + .all(|part| matches!(part, Component::Normal(_))) + { + record.dir = base.join(suffix); + } + } log::debug!( "[cwd_jail] registry.open base={} records={}", base.display(), @@ -129,7 +145,7 @@ impl JailRegistry { }) } - /// Root directory of this registry. + /// Canonical root directory of this registry. pub fn base(&self) -> &Path { &self.base } @@ -342,14 +358,8 @@ impl JailRegistry { record.dir.display() ); - let resolved = record - .dir - .canonicalize() - .unwrap_or_else(|_| record.dir.clone()); - let resolved_base = self - .base - .canonicalize() - .unwrap_or_else(|_| self.base.clone()); + let resolved = path::canonicalize_missing(&record.dir)?; + let resolved_base = self.base.canonicalize()?; if !resolved.starts_with(&resolved_base) { // Index is suspicious — don't touch anything on disk and // leave the in-memory record alone too. The caller can @@ -417,7 +427,7 @@ impl JailRegistry { pub fn spawn_in(&self, id: &str, cmd: Command) -> io::Result { let jail = self.jail_for(id)?; log::debug!("[cwd_jail] registry.spawn_in id={id}"); - spawn_with(default_backend().as_ref(), &jail, cmd) + default_backend().spawn(&jail, cmd) } /// Same as [`Self::spawn_in`] but with a caller-supplied backend. @@ -437,7 +447,7 @@ impl JailRegistry { "[cwd_jail] registry.spawn_in_with id={id} backend={}", backend.name() ); - spawn_with(backend, &jail, cmd) + backend.spawn(&jail, cmd) } /// Build a canonicalized [`Jail`] for the given id, refusing if the @@ -450,15 +460,38 @@ impl JailRegistry { .get(id) .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, format!("no jail {id}")))?; - let resolved = record + if record .dir - .canonicalize() - .unwrap_or_else(|_| record.dir.clone()); - let resolved_base = self - .base - .canonicalize() - .unwrap_or_else(|_| self.base.clone()); - if !resolved.starts_with(&resolved_base) { + .components() + .any(|part| matches!(part, Component::ParentDir)) + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "registry paths must not contain parent traversal", + )); + } + // Spawning requires an existing root. Never make a synthetic missing + // path pass containment and then resolve it to a different target. + let resolved = match record.dir.canonicalize() { + Ok(resolved) => resolved, + Err(error) => { + // Resolve missing ancestors for diagnostics only. Even if the + // path appears during this check, the original failed lookup + // is never upgraded to a successful spawn. + if error.kind() == io::ErrorKind::NotFound { + let diagnostic = path::canonicalize_missing(&record.dir)?; + if !diagnostic.starts_with(&self.base) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "jail directory is outside registry base", + )); + } + } + return Err(error); + } + }; + let resolved_base = &self.base; + if !resolved.starts_with(resolved_base) { log::warn!( "[cwd_jail] refusing spawn: jail {id} dir {} not under base {}", resolved.display(), @@ -474,9 +507,7 @@ impl JailRegistry { )); } - let mut jail = Jail::new(&record.dir, &record.label); - jail.canonicalize()?; - Ok(jail) + Ok(Jail::new(&resolved, &record.label)) } /// Atomic-rename write of the index. Falls back to direct write on diff --git a/crates/tinybox-jail/src/registry_path.rs b/crates/tinybox-jail/src/registry_path.rs new file mode 100644 index 00000000..5d229e7b --- /dev/null +++ b/crates/tinybox-jail/src/registry_path.rs @@ -0,0 +1,59 @@ +//! Resolve missing registry children without mixing lexical and canonical paths. + +use std::io; +use std::path::{Component, Path, PathBuf}; + +/// Canonicalize the existing ancestor and append missing normal components. +/// Never treat a dangling symlink or an access failure as a missing directory. +pub(super) fn canonicalize_missing(path: &Path) -> io::Result { + if path + .components() + .any(|part| matches!(part, Component::ParentDir)) + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "registry paths must not contain parent traversal", + )); + } + let mut ancestor = path.to_path_buf(); + let mut missing = Vec::new(); + loop { + match ancestor.canonicalize() { + Ok(resolved) => return append_missing(resolved, &missing), + Err(error) if error.kind() == io::ErrorKind::NotFound => { + match std::fs::symlink_metadata(&ancestor) { + Ok(_) => return Err(error), + Err(metadata_error) if metadata_error.kind() == io::ErrorKind::NotFound => {} + Err(metadata_error) => return Err(metadata_error), + } + let Some(part) = ancestor.file_name() else { + return Err(error); + }; + missing.push(part.to_os_string()); + ancestor.pop(); + if ancestor.as_os_str().is_empty() { + ancestor.push("."); + } + } + Err(error) => return Err(error), + } + } +} + +/// Missing child components require an existing directory, never a file. +fn append_missing(mut resolved: PathBuf, missing: &[std::ffi::OsString]) -> io::Result { + if !missing.is_empty() && !resolved.is_dir() { + return Err(io::Error::new( + io::ErrorKind::NotADirectory, + "missing jail path has a non-directory ancestor", + )); + } + for part in missing.iter().rev() { + resolved.push(part); + } + Ok(resolved) +} + +#[cfg(test)] +#[path = "registry_path_tests.rs"] +mod tests; diff --git a/crates/tinybox-jail/src/registry_path_tests.rs b/crates/tinybox-jail/src/registry_path_tests.rs new file mode 100644 index 00000000..bf8f9947 --- /dev/null +++ b/crates/tinybox-jail/src/registry_path_tests.rs @@ -0,0 +1,74 @@ +//! Resolution pins missing components and the symlink/traversal boundary. +use super::*; + +#[test] +fn existing_and_missing_paths_share_the_same_canonical_base() -> io::Result<()> { + let root = tempfile::tempdir()?; + assert_eq!( + canonicalize_missing(root.path())?, + root.path().canonicalize()? + ); + assert_eq!( + canonicalize_missing(&root.path().join("missing/nested"))?, + root.path().canonicalize()?.join("missing/nested") + ); + let relative = Path::new("tinybox-missing-relative-child/nested"); + assert_eq!( + canonicalize_missing(relative)?, + std::env::current_dir()?.canonicalize()?.join(relative) + ); + Ok(()) +} + +#[test] +fn parent_traversal_is_rejected_even_inside_the_base() -> io::Result<()> { + let root = tempfile::tempdir()?; + assert_eq!( + canonicalize_missing(&root.path().join("child/../missing")) + .err() + .map(|error| error.kind()), + Some(io::ErrorKind::PermissionDenied) + ); + Ok(()) +} + +#[cfg(unix)] +#[test] +fn missing_children_follow_existing_symlinks_but_not_dangling_symlinks() -> io::Result<()> { + use std::os::unix::fs::symlink; + let root = tempfile::tempdir()?; + let outside = tempfile::tempdir()?; + let link = root.path().join("outside"); + symlink(outside.path(), &link)?; + assert_eq!( + canonicalize_missing(&link.join("missing"))?, + outside.path().canonicalize()?.join("missing") + ); + let dangling = root.path().join("dangling"); + symlink(root.path().join("absent"), &dangling)?; + assert_eq!( + canonicalize_missing(&dangling.join("missing")) + .err() + .map(|error| error.kind()), + Some(io::ErrorKind::NotFound) + ); + Ok(()) +} + +#[test] +fn non_directory_ancestors_propagate_the_os_error() -> io::Result<()> { + let root = tempfile::tempdir()?; + let file = root.path().join("file"); + std::fs::write(&file, b"file")?; + let child = file.join("child"); + assert!(canonicalize_missing(&child).is_err()); + // Windows may report an intermediate missing child as NotFound. Even if + // canonicalization reaches its existing file ancestor, no children fit. + assert_eq!( + append_missing(file.canonicalize()?, &["child".into()]) + .err() + .map(|error| error.kind()), + Some(io::ErrorKind::NotADirectory) + ); + Ok(()) +} diff --git a/crates/tinybox-jail/src/registry_tests.rs b/crates/tinybox-jail/src/registry_tests.rs index 906e210f..d40be361 100644 --- a/crates/tinybox-jail/src/registry_tests.rs +++ b/crates/tinybox-jail/src/registry_tests.rs @@ -249,7 +249,7 @@ fn persist_writes_index_file() { fn base_accessor_returns_open_dir() { let base = tempdir("base-accessor"); let reg = JailRegistry::open(&base).unwrap(); - assert_eq!(reg.base(), base.path()); + assert_eq!(reg.base(), base.path().canonicalize().unwrap()); } #[test] @@ -383,7 +383,10 @@ fn failed_index_write_after_delete_keeps_in_memory_removal() { let error = reg.delete(&record.id).unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::IsADirectory); + // The OS maps writing a directory differently (Windows: PermissionDenied, + // Unix: IsADirectory). Compare with the same independent filesystem failure. + let expected = fs::write(&blocked_tmp, b"independent probe").unwrap_err(); + assert_eq!(error.kind(), expected.kind()); assert!(!record.dir.exists()); assert!(reg.get(&record.id).is_none()); } @@ -410,3 +413,174 @@ fn spawn_rejects_a_jail_directory_removed_after_creation() { .map(|error| error.kind()); assert_eq!(error, Some(io::ErrorKind::NotFound)); } + +#[cfg(unix)] +#[test] +fn removed_jail_under_symlinked_registry_base_can_be_deleted() -> io::Result<()> { + let root = tempdir("linked-base"); + let real = root.path().join("real"); + fs::create_dir(&real)?; + let linked = root.path().join("linked"); + std::os::unix::fs::symlink(&real, &linked)?; + let reg = JailRegistry::open(&linked)?; + let record = reg.create("removed")?; + fs::remove_dir_all(&record.dir)?; + reg.delete(&record.id)?; + assert!(reg.get(&record.id).is_none()); + assert!(JailRegistry::open(&linked)?.get(&record.id).is_none()); + Ok(()) +} + +#[cfg(unix)] +#[test] +fn removed_jail_under_symlinked_base_reports_missing_not_outside() -> io::Result<()> { + let root = tempdir("linked-missing"); + let real = root.path().join("real"); + fs::create_dir(&real)?; + let linked = root.path().join("linked"); + std::os::unix::fs::symlink(&real, &linked)?; + let reg = JailRegistry::open(&linked)?; + let record = reg.create("removed")?; + fs::remove_dir_all(&record.dir)?; + assert_eq!( + reg.spawn_in_with(&record.id, &super::super::NoopBackend, Command::new("true")) + .err() + .map(|error| error.kind()), + Some(io::ErrorKind::NotFound) + ); + Ok(()) +} + +#[cfg(unix)] +#[test] +fn missing_jail_through_outside_symlink_remains_forbidden() -> io::Result<()> { + let root = tempdir("outside-link"); + let outside = tempdir("outside-target"); + let reg = JailRegistry::open(root.path())?; + let record = reg.create("corrupt")?; + let link = root.path().join("outside"); + std::os::unix::fs::symlink(outside.path(), &link)?; + reg.index + .lock() + .unwrap() + .records + .get_mut(&record.id) + .unwrap() + .dir = link.join("missing/nested"); + assert_eq!( + reg.delete(&record.id).err().map(|error| error.kind()), + Some(io::ErrorKind::PermissionDenied) + ); + assert_eq!( + reg.spawn_in_with(&record.id, &super::super::NoopBackend, Command::new("true")) + .err() + .map(|error| error.kind()), + Some(io::ErrorKind::PermissionDenied) + ); + assert!(reg.get(&record.id).is_some()); + assert!(record.dir.is_dir()); + Ok(()) +} + +#[test] +fn trusted_base_parent_components_are_normalized_before_creating_records() -> io::Result<()> { + let root = tempdir("normalized-base"); + let base = root.path().join("base"); + fs::create_dir(&base)?; + let lexical = base.join("..").join("base"); + let reg = JailRegistry::open(&lexical)?; + let record = reg.create("normalized")?; + assert_eq!( + reg.jail_for(&record.id)?.root, + base.canonicalize()?.join(&record.id) + ); + let mut command = Command::new(if cfg!(windows) { "cmd" } else { "true" }); + if cfg!(windows) { + command.args(["/C", "exit"]); + } + assert!( + reg.spawn_in_with(&record.id, &super::super::NoopBackend, command)? + .wait()? + .success() + ); + reg.delete(&record.id)?; + assert!(reg.get(&record.id).is_none()); + Ok(()) +} + +#[test] +fn old_records_inherit_only_normalized_trusted_base_components() -> io::Result<()> { + let root = tempdir("legacy-base"); + let base = root.path().join("base"); + fs::create_dir(&base)?; + let lexical = base.join("..").join("base"); + let reg = JailRegistry::open(&base)?; + let record = reg.create("legacy")?; + { + let mut index = reg.index.lock().unwrap(); + index.records.get_mut(&record.id).unwrap().dir = lexical.join(&record.id); + reg.persist(&index)?; + } + drop(reg); + let reopened = JailRegistry::open(&lexical)?; + assert_eq!( + reopened.jail_for(&record.id)?.root, + base.canonicalize()?.join(&record.id) + ); + fs::remove_dir_all(&record.dir)?; + reopened.delete(&record.id)?; + assert!(reopened.get(&record.id).is_none()); + Ok(()) +} + +#[test] +fn normalized_trusted_base_does_not_adopt_corrupt_suffix_traversal() -> io::Result<()> { + let root = tempdir("corrupt-suffix"); + let base = root.path().join("base"); + fs::create_dir(&base)?; + let lexical = base.join("..").join("base"); + let reg = JailRegistry::open(&base)?; + let record = reg.create("corrupt")?; + { + let mut index = reg.index.lock().unwrap(); + index.records.get_mut(&record.id).unwrap().dir = lexical.join("child/..").join(&record.id); + reg.persist(&index)?; + } + let reopened = JailRegistry::open(&lexical)?; + assert_eq!( + reopened + .jail_for(&record.id) + .err() + .map(|error| error.kind()), + Some(io::ErrorKind::PermissionDenied) + ); + assert_eq!( + reopened.delete(&record.id).err().map(|error| error.kind()), + Some(io::ErrorKind::PermissionDenied) + ); + assert!(record.dir.is_dir()); + Ok(()) +} + +#[cfg(unix)] +#[test] +fn old_symlink_base_records_work_when_reopened_by_the_real_base() -> io::Result<()> { + let root = tempdir("legacy-alias"); + let base = root.path().join("real"); + fs::create_dir(&base)?; + let alias = root.path().join("alias"); + std::os::unix::fs::symlink(&base, &alias)?; + let reg = JailRegistry::open(&base)?; + let record = reg.create("legacy-alias")?; + { + let mut index = reg.index.lock().unwrap(); + index.records.get_mut(&record.id).unwrap().dir = alias.join(&record.id); + reg.persist(&index)?; + } + let reopened = JailRegistry::open(&base)?; + assert_eq!(reopened.jail_for(&record.id)?.root, record.dir); + fs::remove_dir_all(&record.dir)?; + reopened.delete(&record.id)?; + assert!(reopened.get(&record.id).is_none()); + Ok(()) +} diff --git a/crates/tinybox-linux/src/sandbox/mod.rs b/crates/tinybox-linux/src/sandbox/mod.rs index 4baae813..532c5162 100644 --- a/crates/tinybox-linux/src/sandbox/mod.rs +++ b/crates/tinybox-linux/src/sandbox/mod.rs @@ -51,8 +51,8 @@ pub struct NamespaceSandbox { impl NamespaceSandbox { /// Run sandboxed commands on `host`, recording boxes in `store`. /// - /// Resource limits are **not** declared: they need a systemd user session - /// to delegate a cgroup, which not every machine has. Ask for them with + /// CPU, memory and process limits need a systemd user session to delegate + /// a cgroup, which not every machine has. Enable them with /// [`NamespaceSandbox::with_cgroup_limits`]. #[must_use] pub fn new(host: Arc, store: Arc) -> Self { @@ -84,20 +84,15 @@ impl NamespaceSandbox { self } - /// What this sandbox declares, given whether limits are enabled. + /// Lifecycle capabilities (disk quotas remain unsupported with cgroups). /// /// No snapshots, because each command is a fresh sandbox and there is no /// persistent filesystem to capture. No forking, for the same reason. No /// port forwarding: the network namespace is empty by design and there is /// no daemon to publish through. #[must_use] - pub const fn declared_capabilities(limits: bool) -> SandboxCapabilities { - let declared = SandboxCapabilities::new(IsolationLevel::Kernel, SnapshotSupport::None); - if limits { - declared.with_resource_limits() - } else { - declared - } + pub const fn declared_capabilities(_limits: bool) -> SandboxCapabilities { + SandboxCapabilities::new(IsolationLevel::Kernel, SnapshotSupport::None) } } @@ -111,6 +106,23 @@ impl Sandbox for NamespaceSandbox { Self::declared_capabilities(self.limits) } + fn constraint_support(&self) -> tinybox_core::ConstraintSupport { + use tinybox_core::Constraint::{Cpu, Filesystem, Memory, Network, Pids}; + use tinybox_core::Enforcement::Enforced; + if self.limits { + tinybox_core::ConstraintSupport::NONE + .with(Filesystem, Enforced) + .with(Network, Enforced) + .with(Cpu, Enforced) + .with(Memory, Enforced) + .with(Pids, Enforced) + } else { + tinybox_core::ConstraintSupport::NONE + .with(Filesystem, Enforced) + .with(Network, Enforced) + } + } + async fn create(&self, spec: &BoxSpec) -> Result { spec.validate()?; // Nothing is started here: a box is a record plus a directory, and the diff --git a/crates/tinybox-linux/src/sandbox/mod_tests.rs b/crates/tinybox-linux/src/sandbox/mod_tests.rs index 9c0b0221..7dee3dd8 100644 --- a/crates/tinybox-linux/src/sandbox/mod_tests.rs +++ b/crates/tinybox-linux/src/sandbox/mod_tests.rs @@ -98,11 +98,11 @@ fn it_declares_kernel_isolation_and_nothing_it_cannot_do() { } #[test] -fn limits_are_declared_only_when_asked_for() { +fn coarse_limits_are_declined_because_disk_is_not_enforced() { let caps = NamespaceSandbox::declared_capabilities(true); - assert!(caps.supports(Capability::ResourceLimits)); - assert_eq!(caps.declared(), [Capability::ResourceLimits]); + assert!(!caps.supports(Capability::ResourceLimits)); + assert_eq!(caps.declared(), Vec::::new()); } #[tokio::test] @@ -492,3 +492,52 @@ fn the_workspace_mount_point_is_stable() -> Result<()> { ); Ok(()) } + +#[test] +fn preflight_reports_each_enforced_boundary_without_claiming_disk() { + use tinybox_core::{Constraint, Enforcement}; + let (backend, _) = sandbox(); + let support = backend.constraint_support(); + assert_eq!( + support.enforcement(Constraint::Filesystem), + Enforcement::Enforced + ); + assert_eq!( + support.enforcement(Constraint::Network), + Enforcement::Enforced + ); + assert_eq!( + support.enforcement(Constraint::Cpu), + Enforcement::Unsupported + ); + assert_eq!( + support.enforcement(Constraint::Memory), + Enforcement::Unsupported + ); + assert_eq!( + support.enforcement(Constraint::Pids), + Enforcement::Unsupported + ); + assert_eq!( + support.enforcement(Constraint::Disk), + Enforcement::Unsupported + ); + assert_eq!( + support.enforcement(Constraint::Subprocess), + Enforcement::Unsupported + ); + assert!( + backend + .require(&[Constraint::Filesystem, Constraint::Network]) + .is_ok() + ); + assert!(backend.require(&[Constraint::Disk]).is_err()); + let constrained = backend.with_cgroup_limits().constraint_support(); + for constraint in [Constraint::Cpu, Constraint::Memory, Constraint::Pids] { + assert_eq!(constrained.enforcement(constraint), Enforcement::Enforced); + } + assert_eq!( + constrained.enforcement(Constraint::Disk), + Enforcement::Unsupported + ); +} diff --git a/crates/tinybox-microvm/src/sandbox/mod.rs b/crates/tinybox-microvm/src/sandbox/mod.rs index bacf0685..13f4660f 100644 --- a/crates/tinybox-microvm/src/sandbox/mod.rs +++ b/crates/tinybox-microvm/src/sandbox/mod.rs @@ -116,7 +116,7 @@ impl MicroVmSandbox { /// What this sandbox declares. /// - /// Resource limits are real and enforced by the hypervisor rather than by a + /// Guest sizing is implemented by the hypervisor rather than by a /// cgroup: the guest is given a fixed number of vCPUs and a fixed amount of /// memory, and it has no way to exceed either — it cannot see that any more /// exists. @@ -127,7 +127,6 @@ impl MicroVmSandbox { #[must_use] pub const fn declared_capabilities() -> SandboxCapabilities { SandboxCapabilities::new(IsolationLevel::Hardware, SnapshotSupport::None) - .with_resource_limits() } /// The workspace directory a spec names. @@ -158,6 +157,16 @@ impl Sandbox for MicroVmSandbox { Self::declared_capabilities() } + fn constraint_support(&self) -> tinybox_core::ConstraintSupport { + use tinybox_core::Constraint::{Cpu, Filesystem, Memory, Network}; + use tinybox_core::Enforcement::{BestEffort, Enforced}; + tinybox_core::ConstraintSupport::NONE + .with(Filesystem, Enforced) + .with(Network, Enforced) + .with(Memory, BestEffort) + .with(Cpu, BestEffort) + } + async fn create(&self, spec: &BoxSpec) -> Result { spec.validate()?; // Nothing boots here: a box is a record and a directory, and the VM diff --git a/crates/tinybox-microvm/src/sandbox/mod_tests.rs b/crates/tinybox-microvm/src/sandbox/mod_tests.rs index 51d3ea21..592bacb6 100644 --- a/crates/tinybox-microvm/src/sandbox/mod_tests.rs +++ b/crates/tinybox-microvm/src/sandbox/mod_tests.rs @@ -111,7 +111,7 @@ fn it_is_the_only_backend_that_declares_hardware_isolation() { assert!(caps.is_suitable_for_untrusted_code()); // The guest is given fixed vCPUs and fixed memory by the hypervisor and // cannot see that any more exists, which is a stronger limit than a cgroup. - assert!(caps.supports(Capability::ResourceLimits)); + assert!(!caps.supports(Capability::ResourceLimits)); // Each command boots a fresh VM, so there is nothing persistent to capture. assert_eq!(caps.snapshot, SnapshotSupport::None); assert!(!caps.supports(Capability::Fork)); @@ -616,3 +616,44 @@ async fn the_workspace_root_itself_is_not_written_as_a_file() -> Result<()> { assert_eq!(output.exit_code, 0); Ok(()) } + +#[test] +fn preflight_reports_each_enforced_boundary_without_claiming_disk() { + use tinybox_core::{Constraint, Enforcement}; + let backend = sandbox(ScriptedHost::booting("", 0)); + let support = backend.constraint_support(); + assert_eq!( + support.enforcement(Constraint::Filesystem), + Enforcement::Enforced + ); + assert_eq!( + support.enforcement(Constraint::Network), + Enforcement::Enforced + ); + assert_eq!( + support.enforcement(Constraint::Cpu), + Enforcement::BestEffort + ); + assert_eq!( + support.enforcement(Constraint::Memory), + Enforcement::BestEffort + ); + assert_eq!( + support.enforcement(Constraint::Pids), + Enforcement::Unsupported + ); + assert_eq!( + support.enforcement(Constraint::Disk), + Enforcement::Unsupported + ); + assert_eq!( + support.enforcement(Constraint::Subprocess), + Enforcement::Unsupported + ); + assert!( + backend + .require(&[Constraint::Filesystem, Constraint::Network]) + .is_ok() + ); + assert!(backend.require(&[Constraint::Disk]).is_err()); +} diff --git a/docs/specs/constraint-preflight.md b/docs/specs/constraint-preflight.md new file mode 100644 index 00000000..c7df4f43 --- /dev/null +++ b/docs/specs/constraint-preflight.md @@ -0,0 +1,67 @@ +# Constraint preflight + +`Sandbox::plan_check` inspects explicitly requested constraints without +allocating or starting a workload. `Sandbox::require` rejects the first +`Unsupported` **or** `BestEffort` declaration with a typed +`Error::ConstraintNotEnforced`. Unknown implementations report no constraints; +coarse lifecycle capabilities do not imply resource enforcement. + +| Backend | Filesystem | Network denial | CPU | Memory | Pids | Disk | Subprocess denial | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Docker | Enforced | Enforced | Enforced | Enforced | Enforced | Unsupported | Unsupported | +| Namespaces | Enforced | Enforced | Enforced with cgroups | Enforced with cgroups | Enforced with cgroups | Unsupported | Unsupported | +| MicroVM | Enforced | Enforced | BestEffort | BestEffort | Unsupported | Unsupported | Unsupported | +| Landlock | Enforced when full filesystem ABI available | Unsupported | Unsupported | Unsupported | Unsupported | Unsupported | Unsupported | +| Seatbelt | BestEffort when present | BestEffort when present | Unsupported | Unsupported | Unsupported | Unsupported | BestEffort when present | +| Noop / unavailable platform | Unsupported | Unsupported | Unsupported | Unsupported | Unsupported | Unsupported | Unsupported | + +Namespace resource support is opt-in; actual systemd/cgroup setup may fail and +must prevent execution. MicroVM vCPU counts round up and memory is rounded with +a minimum of one MiB, so arbitrary exact budgets cannot be promised. No backend +enforces the writable disk budget in `Resources`; consequently none declares +the coarse `ResourceLimits` capability. A caller requiring all resource fields, +including default disk, must expect refusal. This change does not implement new +OS resource controls. + +Directory jails expose `JailBackend::plan_check` and `require` for filesystem +plus any requested network/subprocess denials. `spawn_required_with` and +`spawn_required` run the hard check before starting a child. Existing +`spawn_with(NoopBackend, ...)` is an explicit trusted passthrough; it is never +selected automatically. Legacy Seatbelt spawn remains available but its +filesystem declaration is best effort: it allows reads everywhere and writes +in `/private/tmp`. Strict preflight refuses it. Launcher presence does not prove the host enforces +profiles, so network and subprocess rules also remain best effort until an +enforcement probe can establish them. `isolation()` reports `None`: the +Seatbelt launcher is the mechanism used, not proof that the host actually +isolates the workload. + +Landlock implements filesystem rules only (no network ABI rules or process +isolation). A filesystem-only strict jail may spawn, but +`is_suitable_for_untrusted_code` is false. Both direct and facade Landlock +spawns refuse network/subprocess denial flags rather than silently dropping +them. Windows AppContainer is not compiled; Windows has no enforced jail. + +Preflight is a declaration check, not proof that runtime setup will succeed. +Backend spawn/create errors must propagate. Callers select hard constraints +explicitly before legacy lifecycle methods; those methods do not automatically +turn every field of a `BoxSpec` into a hard request. + +## Registry path ownership + +Registry bases are trusted host-owned directories and must not be writable by +jailed workloads. `open` canonicalizes the caller's trusted base once. Older +records sharing that exact lexical base are normalized only when their suffix +has normal components; traversal introduced in a record remains forbidden. +Older symlink aliases are resolved and checked against the canonical base. + +Spawning requires an existing root, canonicalizes it before containment, and +passes that checked canonical root directly to the backend. It never accepts a +synthetic missing path or recanonicalizes an unchecked alias after the check. +Missing-path resolution retires already-missing entries or diagnoses an outside +missing path; a failed existing-root lookup always refuses spawning even when +the path appears during diagnosis. These path-based APIs do not promise descriptor-atomic protection +against a separate host process with write authority over the registry base +replacing existing directories during an operation. That authority must stay +with the host; untrusted processes get only their jail root and cannot replace +its parent entry. Descriptor-based hostile-host filesystem operations would +require a distinct backend contract rather than claiming atomicity here.