phoebus_os/installer-rs/crates/phoebus-executor/src/agent_jail.rs
Phoebus 6d48ad38fc feat(stability): add boot assessment, preflight storage gates, tiered channels and userspace agent framework
- systemd Automatic Boot Assessment: BLS +<tries> parsing/formatting and phoebus-boot-confirm.service
- Preflight safety gates: 10 GiB storage preflight check and atomic @ and @var pre-update snapshots
- Tiered update channels: Core, Proven (default), Edge
- Userspace AI agent framework: agent_jail Bubblewrap isolation, desktop_config undoable mutations, phoebus-mcp server, sys propose staging bridge
- Fixed parent directory creation race condition in personal storage
- Verified with cargo fmt, clippy, and full workspace test suite
2026-09-30 03:40:41 -07:00

232 lines
7.6 KiB
Rust

//! Bubblewrap isolation boundary for userspace developer and desktop AI agents.
//!
//! While system-administration AI (`sys`) is isolated via `ProtectHome=yes` and
//! closed typed schemas, userspace developer agents (such as Claude Code, OpenCode,
//! Aider, or MCP tools) need broad permissions within a user's workspace to edit
//! code, run tests, and invoke compilers.
//!
//! To prevent the severe vulnerabilities seen in unconfined developer setups
//! (such as Omarchy 4.0's credential exposure and command injection risks), this
//! module provides an unprivileged Bubblewrap (`bwrap`) containment boundary that:
//! 1. Masks sensitive credential paths (`~/.ssh`, `~/.gnupg`, keyrings, `.aws`, etc.)
//! with private empty tmpfs mounts.
//! 2. Exposes core system binaries and libraries (`/usr`, `/lib`, `/nix/store`) as read-only.
//! 3. Binds the targeted workspace directory as writable and sets it as the working directory.
//! 4. Supports network isolation (offline mode) while enabling loopback communication.
use std::path::{Path, PathBuf};
use crate::command::{CommandOutput, CommandSpec};
use crate::error::{ExecError, Result};
use crate::exec::Exec;
/// List of sensitive subdirectories under `$HOME` that must be masked from
/// developer agents to prevent credential exfiltration.
pub const DEFAULT_SENSITIVE_SUBDIRS: &[&str] = &[
".ssh",
".gnupg",
".password-store",
".local/share/keyrings",
".config/gh",
".aws",
".config/gcloud",
".mozilla",
".config/BraveSoftware",
".kube",
];
/// Configuration for the userspace agent jail.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentJailConfig {
/// The workspace root where the agent has write permissions (e.g. `~/Source/project`).
pub workspace: PathBuf,
/// Whether external network access is permitted.
pub allow_network: bool,
/// Whether `/nix` store paths should be mounted read-only.
pub allow_nix_store: bool,
/// Additional subdirectories under home to mask with empty tmpfs.
pub extra_masked_subdirs: Vec<String>,
}
impl Default for AgentJailConfig {
fn default() -> Self {
Self {
workspace: PathBuf::from("."),
allow_network: true,
allow_nix_store: true,
extra_masked_subdirs: Vec::new(),
}
}
}
/// Whether the `bwrap` tool is installed in PATH.
pub fn is_bwrap_available() -> bool {
crate::exec::find_in_path("bwrap").is_some()
}
/// Pure builder for Bubblewrap arguments.
pub fn build_jail_argv(
config: &AgentJailConfig,
home: &Path,
program: &str,
args: &[String],
) -> Vec<String> {
let mut out: Vec<String> = vec![
"--die-with-parent".into(),
"--dev".into(),
"/dev".into(),
"--proc".into(),
"/proc".into(),
"--tmpfs".into(),
"/tmp".into(),
];
// Read-only system mounts
for sys_dir in ["/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc"] {
if Path::new(sys_dir).exists() {
out.push("--ro-bind".into());
out.push(sys_dir.into());
out.push(sys_dir.into());
}
}
// Read-only Nix store if enabled and present
if config.allow_nix_store && Path::new("/nix").exists() {
out.push("--ro-bind".into());
out.push("/nix".into());
out.push("/nix".into());
}
// Bind home directory
let home_str = home.to_string_lossy().to_string();
out.push("--bind".into());
out.push(home_str.clone());
out.push(home_str);
// Mask sensitive subdirectories under home with private empty tmpfs
let mut masked_subdirs: Vec<&str> = DEFAULT_SENSITIVE_SUBDIRS.to_vec();
let extra_refs: Vec<&str> = config
.extra_masked_subdirs
.iter()
.map(|s| s.as_str())
.collect();
masked_subdirs.extend(extra_refs);
for sensitive in masked_subdirs {
let sensitive_path = home.join(sensitive);
let path_str = sensitive_path.to_string_lossy().to_string();
out.push("--tmpfs".into());
out.push(path_str);
}
// Bind the workspace read-write and set working directory
let ws_str = config.workspace.to_string_lossy().to_string();
out.push("--bind".into());
out.push(ws_str.clone());
out.push(ws_str.clone());
out.push("--chdir".into());
out.push(ws_str);
// Network isolation
if !config.allow_network {
out.push("--unshare-net".into());
}
// Target executable and arguments
out.push(program.to_string());
out.extend(args.iter().cloned());
out
}
/// Run a program inside the Bubblewrap agent jail.
pub fn run_jailed(
exec: &Exec,
config: &AgentJailConfig,
home: &Path,
program: &str,
args: &[String],
) -> Result<CommandOutput> {
if !is_bwrap_available() {
return Err(ExecError::MissingTool(
"bwrap (required for user agent isolation; refusing to run unconfined)".into(),
));
}
let argv = build_jail_argv(config, home, program, args);
exec.run(CommandSpec::new("agent-jail", "run jailed user agent", "bwrap").args(argv))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jail_argv_masks_sensitive_credential_paths() {
let home = Path::new("/home/developer");
let ws = Path::new("/home/developer/Source/my-project");
let config = AgentJailConfig {
workspace: ws.to_path_buf(),
allow_network: true,
allow_nix_store: true,
extra_masked_subdirs: vec![".custom-secrets".into()],
};
let argv = build_jail_argv(&config, home, "cargo", &["build".into()]);
// Verify die-with-parent and dev/proc/tmp
assert!(argv.contains(&"--die-with-parent".to_string()));
assert!(argv.contains(&"--proc".to_string()));
assert!(argv.contains(&"--dev".to_string()));
// Verify home directory is bound
let home_idx = argv.iter().position(|a| a == "/home/developer").unwrap();
assert_eq!(argv[home_idx - 1], "--bind");
// Verify sensitive paths are masked with tmpfs
for sensitive in [
"/home/developer/.ssh",
"/home/developer/.gnupg",
"/home/developer/.password-store",
"/home/developer/.local/share/keyrings",
"/home/developer/.config/gh",
"/home/developer/.aws",
"/home/developer/.custom-secrets",
] {
let pos = argv
.iter()
.position(|a| a == sensitive)
.unwrap_or_else(|| panic!("missing tmpfs mask for {sensitive}"));
assert_eq!(
argv[pos - 1],
"--tmpfs",
"path {sensitive} not mounted with --tmpfs"
);
}
// Verify workspace is bound and chdir is set
let ws_str = "/home/developer/Source/my-project";
let ws_idx = argv.iter().position(|a| a == ws_str).unwrap();
assert_eq!(argv[ws_idx - 1], "--bind");
let chdir_idx = argv.iter().position(|a| a == "--chdir").unwrap();
assert_eq!(argv[chdir_idx + 1], ws_str);
// Verify program and args
let pos = argv.iter().position(|a| a == "cargo").unwrap();
assert_eq!(&argv[pos + 1..], &["build"]);
}
#[test]
fn jail_argv_unshares_net_when_offline() {
let home = Path::new("/home/developer");
let config = AgentJailConfig {
workspace: home.join("offline-repo"),
allow_network: false,
allow_nix_store: false,
extra_masked_subdirs: vec![],
};
let argv = build_jail_argv(&config, home, "python", &["-m".into(), "test".into()]);
assert!(argv.contains(&"--unshare-net".to_string()));
}
}