phoebus_os/installer-rs/crates/phoebus-executor/src/sandbox.rs
Phoebus 25f7381b4a
Some checks are pending
ci / test (push) Waiting to run
feat(desktop): add Mango + DankMaterialShell profile with rollback, assistant and release foundations
- Mango + DankMaterialShell desktop option (desktop.profile = "mango") through
  the GURU overlay with scoped ~amd64 keywords, a sealed session entry point and
  a dwl fallback session (ADR 0009).
- Coherent rollback/recovery: coordinated @ + @var snapshots, fstab and BLS
  root-subvolume rewriting, matching-kernel selection, snapshot recovery entry,
  retention/space gates and sys undo (ADR 0007).
- Installed assistant (sys ask) with an OS-level systemd sandbox boundary and
  fail-closed typed plans; resolved package effects bound to approval.
- Nix build isolation enforced (sandbox, no fallback) plus lifecycle/cleanup.
- Desktop helpers (menu/lock/idle), transaction log, release gates with atomic
  publish and signing helpers, and a Debian-Live appliance VM harness.
2026-09-21 03:46:52 -07:00

132 lines
4.7 KiB
Rust

//! OS-level isolation for model execution.
//!
//! Typed schemas and privacy filters constrain *what* the model may ask for, but
//! they do not stop a compromised or malicious provider endpoint from reaching
//! the filesystem, the home directory, or privilege. The network call is
//! therefore executed inside a hardened, unprivileged transient systemd unit:
//! a dynamic user, no home access, a read-only system, no new privileges, and a
//! restricted syscall/address-family set. The model never runs as root and can
//! never read a private file.
//!
//! The argument builder is pure so the exact sandbox is unit-testable without a
//! running systemd.
use std::path::Path;
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
/// The hardening properties applied to the model-call unit.
pub const SANDBOX_PROPERTIES: &[&str] = &[
"DynamicUser=yes",
"ProtectSystem=strict",
"ProtectHome=yes",
"PrivateDevices=yes",
"PrivateTmp=yes",
"NoNewPrivileges=yes",
"ProtectKernelTunables=yes",
"ProtectKernelModules=yes",
"ProtectControlGroups=yes",
"RestrictNamespaces=yes",
"LockPersonality=yes",
"MemoryDenyWriteExecute=yes",
"SystemCallArchitectures=native",
"RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6",
"SystemCallFilter=@system-service",
];
/// Whether `systemd-run` is available to build the boundary.
pub fn available() -> bool {
crate::exec::find_in_path("systemd-run").is_some()
}
/// The argv for `systemd-run` that runs `program args` inside the sandbox.
pub fn argv(program: &str, args: &[String]) -> Vec<String> {
let mut out: Vec<String> = vec![
"--quiet".into(),
"--wait".into(),
"--pipe".into(),
"--collect".into(),
"--service-type=exec".into(),
];
for property in SANDBOX_PROPERTIES {
out.push(format!("--property={property}"));
}
out.push(program.to_string());
out.extend(args.iter().cloned());
out
}
/// Run a program inside the model sandbox, reading the hidden `stdin` payload.
///
/// Fails closed when `systemd-run` is unavailable: an unisolated model call is
/// refused rather than silently run with full access.
pub fn run(
exec: &Exec,
program: &str,
args: &[String],
stdin: Vec<u8>,
) -> Result<crate::command::CommandOutput> {
if !available() {
return Err(ExecError::MissingTool(
"systemd-run (required for the AI sandbox; refusing to run the model unisolated)"
.into(),
));
}
exec.run(
CommandSpec::new("ai", "query model (sandboxed)", "systemd-run")
.args(argv(program, args))
.stdin(stdin),
)
}
/// Whether a path is safe to expose to the sandboxed process (never a home or
/// credential path).
pub fn path_is_exposable(path: &Path) -> bool {
let text = path.to_string_lossy();
!phoebus_ai::privacy::is_forbidden_path(&text)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn argv_contains_the_hardening_properties() {
let args = argv("curl", &["-sS".into(), "-K".into(), "-".into()]);
assert!(args.iter().any(|a| a == "--quiet"));
assert!(args.iter().any(|a| a == "--wait"));
assert!(args.iter().any(|a| a.contains("DynamicUser=yes")));
assert!(args.iter().any(|a| a.contains("ProtectHome=yes")));
assert!(args.iter().any(|a| a.contains("NoNewPrivileges=yes")));
assert!(args.iter().any(|a| a.contains("ProtectSystem=strict")));
assert!(args.iter().any(|a| a.contains("RestrictAddressFamilies=")));
// The wrapped program and its arguments come last.
let pos = args.iter().position(|a| a == "curl").unwrap();
assert_eq!(&args[pos + 1..], &["-sS", "-K", "-"]);
}
#[test]
fn run_fails_closed_without_systemd_run() {
// In this environment systemd-run may or may not exist; if it does not,
// run must refuse. If it does, the refusal path is covered by argv.
if available() {
return;
}
let runner = crate::command::RecordingRunner::new();
let dir = tempfile::tempdir().unwrap().keep();
let logger =
crate::log::Logger::open(dir.join("l.log"), phoebus_core::Redactor::new(), false);
let exec = Exec::new(Box::new(runner), logger, false, dir.join("root"), dir);
let err = run(&exec, "curl", &[], Vec::new()).unwrap_err();
assert!(matches!(err, ExecError::MissingTool(_)));
}
#[test]
fn private_paths_are_not_exposable() {
assert!(!path_is_exposable(Path::new("/home/alice/.ssh/id_rsa")));
assert!(!path_is_exposable(Path::new("/root/.gnupg/secring.gpg")));
assert!(path_is_exposable(Path::new("/etc/nix/nix.conf")));
}
}