From 574a77eaeb1112e3e185e3605ccdde30a9facd0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A0=95=EC=9D=B8=EA=B6=8C?= Date: Sun, 29 Nov 2026 00:34:50 +0900 Subject: [PATCH 1/3] feat(sandbox): declarative isolation policy with a Linux bwrap driver MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The agent runs arbitrary shell commands. Without isolation a hallucinated flag, an injected instruction, or an unlucky `rm` reaches straight into the host: ~/.ssh, cloud credentials, package-registry tokens, the network. This is the first cut of #33 — the policy, the seam, and the Linux driver; seatbelt and docker follow. Declared once, resolved per session: - `sandbox = "auto" | "bwrap" | "seatbelt" | "docker" | "none"` at the top level (the default for every backend), per backend (`[backends.X] sandbox`), and per session (`session.create`'s new `sandbox` param). `auto` means this platform's driver when the host can run it; `none` is an explicit opt-out. - `sandbox::decide` is the only place the rules live: an explicit request the backend or host cannot honor is an error naming the cause and the choices (missing binary, `unprivileged_userns_clone=0`, no spawn point) — never a silent fallback to unconfined. `auto` may fall back, and reports why through `damond doctor`. - Serve-mode backends (opencode, mimo) resolve to `unsupported`, not `none`: they attach to a shared `serve` process, so there is no per-session child to wrap. Asking for a driver there fails the create. The bwrap driver compiles one policy into launcher argv: workdir, granted roots and the CLI's own auth/state dir writable; host root read-only; credential stores masked after the binds (tmpfs for directories, /dev/null for files) so a deny always wins; SSH_AUTH_SOCK scrubbed; --unshare-all + --cap-drop ALL + --die-with-parent + --new-session. The compiler is pure and golden-tested; the planner symlink-resolves every path and refuses `/` or a credential store as a writable root. Every spawn-mode backend launches through ResolvedBackend::spawn_ndjson, so the transport is the single place the policy is applied. Tests: policy/compiler unit tests, path-escape cases, four end-to-end bwrap tests plus a transport wiring test that skip themselves when the host has no usable bwrap (CI installs bubblewrap on the Linux leg), and a wire test for the new session.create param. Refs #33 Signed-off-by: 정인권 --- AGENTS.md | 3 + CHANGELOG.md | 37 ++ README.ko.md | 1 + README.md | 1 + config.example.toml | 33 ++ examples/backend_probe.rs | 4 + src/backend/codex.rs | 3 +- src/backend/droid.rs | 5 +- src/backend/omp.rs | 5 +- src/backend/opencode.rs | 13 + src/backend/registry.rs | 154 +++++- src/backend/streamjson.rs | 15 +- src/backend/transport.rs | 21 + src/backend/types.rs | 6 + src/backend/zcode.rs | 16 +- src/bin/damond.rs | 57 ++- src/config.rs | 60 +++ src/lib.rs | 1 + src/rpc.rs | 20 +- src/rpc/session.rs | 23 +- src/sandbox/bwrap.rs | 512 +++++++++++++++++++ src/sandbox/mod.rs | 1003 +++++++++++++++++++++++++++++++++++++ src/session.rs | 4 +- tests/common/mod.rs | 5 + tests/rpc.rs | 37 ++ tests/sandbox_bwrap.rs | 305 +++++++++++ 26 files changed, 2315 insertions(+), 29 deletions(-) create mode 100644 src/sandbox/bwrap.rs create mode 100644 src/sandbox/mod.rs create mode 100644 tests/sandbox_bwrap.rs diff --git a/AGENTS.md b/AGENTS.md index 0771060..183d086 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,8 @@ Persistence goes through `src/store.rs` (`Store`, tokio-rusqlite wrapper, sessio `backend/registry.rs` holds the static `BackendSpec` catalog and `resolve_backends()`/`client_for()`. Unsupported features return typed `NOT_SUPPORTED` errors; `Capabilities` structs advertise what works. +**Sandbox (`src/sandbox/`)**: one declarative policy (`sandbox = "auto" | "bwrap" | "seatbelt" | "docker" | "none"`, global / per backend / per session) compiled into the driver's native launcher. `decide()` is the only place the rules live: an explicit request that the backend or host cannot honor is an error naming the cause and choices (never a silent fallback), `auto` may fall back and reports why, and a serve-mode backend (opencode, mimo) resolves to `unsupported` rather than `none` because it has no per-session child to wrap. Spawn-mode backends launch through `ResolvedBackend::spawn_ndjson`, so every one of them inherits the policy; the compiler (`bwrap::compile_args`) is pure and golden-tested, the planner (`compile_policy`) resolves symlinks and refuses `/` or credential paths as writable. + ## Key Directories | Path | Purpose | @@ -44,6 +46,7 @@ Persistence goes through `src/store.rs` (`Store`, tokio-rusqlite wrapper, sessio | `src/skills_hub/` | Skill package manager: discovery, fetch, install lifecycle, target roots | | `src/channel.rs` + `telegram.rs`/`slack.rs`/`discord.rs` | Chat bridge + per-platform adapters | | `src/relay.rs`, `src/bin/damon-relay.rs` | E2E-encrypted outbound tunnel (X25519 + AES-256-GCM) | +| `src/sandbox/` | OS-level isolation: the declarative policy (`SandboxRequest` → `SandboxDecision`), the thin `SandboxDriver` trait, and the bwrap driver (`bwrap.rs`: policy → launcher argv, availability probe). Resolved per session at the spawn point (`ResolvedBackend::spawn_ndjson`); seatbelt/docker are follow-ups to #33 | | `tests/` | Integration tests (separate crate), shared harness in `tests/common/mod.rs` | | `npm/`, `python/` | Client SDKs mirroring the Rust client contract (see Testing & QA) | | `scripts/` | `set-version.sh` (version sync), `verify-release.sh` (release verification) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f209d5..2f93a52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,42 @@ # Changelog +## Unreleased + +### Added — pluggable OS sandbox, first cut: the bwrap driver (#33) + +- `sandbox = "auto" | "bwrap" | "seatbelt" | "docker" | "none"` at the + top level of the config (the default for every backend), per backend + (`[backends.X] sandbox`), and per session (`session.create`'s `sandbox` + param). `auto` (default) means this platform's driver when the host can + run it; `none` is an explicit opt-out. +- A request that the backend or host cannot honor **fails the session at + start** with the cause and the choices — a missing binary, disabled + unprivileged user namespaces, or a backend with no spawn point. Nothing + falls back to running unconfined silently; `auto`, whose meaning is "use + what this host has", reports its fallback through `damond doctor`. +- Serve-mode backends (`opencode`, `mimo`) resolve to `unsupported`, not + `none`: they attach to a shared `serve` process, so there is no + per-session child to wrap yet. +- The Linux driver compiles one declarative policy into bwrap: the workdir, + granted roots and the CLI's own auth/state dir (`~/.claude`, `~/.codex`, + `~/.omp`, …) writable; host root read-only; credential stores (`~/.ssh`, + `~/.aws`, `~/.gnupg`, `~/.netrc`, `~/.config/gh`, `~/.config/damon`, …) + masked after the binds (tmpfs for directories, `/dev/null` for files) so a + deny always wins; `SSH_AUTH_SOCK` scrubbed; `--unshare-all` with + `--cap-drop ALL`, `--die-with-parent`, `--new-session`. +- `damond doctor` prints the platform driver's status and what each detected + backend would actually get (or why it would get nothing). +- Tests: golden argv and policy rules in `src/sandbox/`, path-escape cases + (relative, `..` traversal, symlinks, `/` as workdir, workdir inside a + credential store), and four end-to-end bwrap tests plus a transport wiring + test in `tests/sandbox_bwrap.rs` — those skip themselves on hosts without + a usable bwrap (no binary, or unprivileged user namespaces disabled), and + CI installs bubblewrap on the Linux leg so they normally run there. +- Egress inside the sandbox defaults to each backend's declared need + (`sandbox_network = "backend"`): every agent CLI allows it, because its + model API call is the point of running it. Per-command network denial + needs a proxy in front of the agent and is a follow-up. + ## 0.9.0 — 2026-11-22 ### Changed — `session.*` request params are typed, and the schema is held to them diff --git a/README.ko.md b/README.ko.md index 8e24465..3329c57 100644 --- a/README.ko.md +++ b/README.ko.md @@ -32,6 +32,7 @@ Damon은 Rust로 만든 로컬 에이전트 컨트롤 데몬이다. 아홉 코 - **시크릿은 Damon에 없다** — 에이전트가 자기 인증을 관리한다. Damon config는 포트와 토큰 정도뿐. - **어디서든 접근** — 자체 인증서로 `wss` 서빙, 또는 공개 호스트에 `damon-relay`를 띄우면 데몬이 아웃바운드로 연결한다(인바운드 포트 불필요). 터널은 X25519 + AES-256-GCM으로 E2E 암호화. - **상주하도록 설계** — Rust 데몬 본체는 가볍다(에이전트 프로세스는 에이전트 몫). +- **에이전트 명령용 OS 샌드박스 (Linux, 1차)** — `sandbox = "auto"`면 각 에이전트 CLI 자식을 bubblewrap으로 감싼다: 워크디렉터리(와 CLI 자신의 인증 디렉터리)만 쓰기 가능, 호스트 루트는 읽기 전용, 자격증명 저장소(`~/.ssh`, `~/.aws`, `~/.gnupg` 등)는 마스킹, `SSH_AUTH_SOCK`은 제거. 호스트가 감당할 수 없는 드라이버를 지정하면 조용히 무방비로 도는 대신 세션 시작이 실패하고, `damond doctor`가 백엔드별로 무엇이 적용되는지 보여준다. Seatbelt(macOS)와 Docker 드라이버는 후속. ## 설치 diff --git a/README.md b/README.md index 84bede2..7422215 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ If you already subscribe to an agent CLI, **there is nothing to configure**. Dam - **Damon holds no secrets** — agents manage their own auth. The Damon config is a port and maybe a token. - **Reachable from anywhere** — serve `wss` with your own certs, or run `damon-relay` on a public host and the daemon dials out (no inbound port). The tunnel is X25519 + AES-256-GCM end-to-end encrypted. - **Built to stay resident** — the Rust daemon itself stays lean (agent processes are the agents' business). +- **OS sandbox for the agent's own commands (Linux, first cut)** — `sandbox = "auto"` wraps each agent CLI child in bubblewrap: the workdir (and the CLI's own auth dir) writable, the host root read-only, credential stores (`~/.ssh`, `~/.aws`, `~/.gnupg`, …) masked, `SSH_AUTH_SOCK` scrubbed. Naming a driver the host cannot honor fails the session at start instead of silently running unconfined; `damond doctor` reports what each backend would get. Seatbelt (macOS) and Docker drivers follow. ## Install diff --git a/config.example.toml b/config.example.toml index 32a4024..988ad3e 100644 --- a/config.example.toml +++ b/config.example.toml @@ -28,6 +28,39 @@ # Each catalog backend implements one native protocol, so adding a new # agent is a code change, not a config block. +# OS-level sandbox for agent CLI child processes. The agent runs arbitrary +# shell commands; without isolation a hallucinated flag or an injected +# instruction reaches straight into the host (~/.ssh, ~/.aws, cloud and +# package-registry tokens, the network). +# +# auto (default) this platform's driver when the host can run it — +# bwrap on Linux today; seatbelt and docker are follow-ups. When +# the host cannot, the session runs unconfined and `damond doctor` +# says why (never silently). +# bwrap Linux/bubblewrap, explicitly. Fails the session at start when it +# is not installed or unprivileged user namespaces are disabled, +# naming the cause and the choices. +# none explicit opt-out — today's behavior. +# +# `[backends.X] sandbox = "..."` overrides this per backend, and +# `session.create {"sandbox": "..."}` per session. Serve-mode backends +# (opencode, mimo) report `unsupported`, not `none`: they attach to a shared +# `serve` process, so there is no per-session child to confine. +# sandbox = "auto" +# +# Egress inside the sandbox: backend (each backend's declared need — every +# agent CLI allows it, because calling its model API is the point), allow, or +# deny (offline/proxied setups). +# sandbox_network = "backend" +# +# What the bwrap policy does: the workdir, granted roots and the CLI's own +# auth/state dir (~/.claude, ~/.codex, …) writable; host root read-only; +# credential stores (~/.ssh, ~/.aws, ~/.gnupg, ~/.netrc, ~/.config/gh, +# ~/.config/damon, …) masked with an empty tmpfs or /dev/null; SSH_AUTH_SOCK +# scrubbed. +# [backends.claude] +# sandbox = "bwrap" # this backend only + # MCP servers are per-session: pass them in session.create's # `mcpServers` param — the agent spawns and permissions them (Damon # never launches them itself). Only claude forwards them today; other diff --git a/examples/backend_probe.rs b/examples/backend_probe.rs index d746727..4bf2704 100644 --- a/examples/backend_probe.rs +++ b/examples/backend_probe.rs @@ -23,6 +23,10 @@ async fn main() -> anyhow::Result<()> { .collect(), auth_hint: spec.auth_hint.into(), detected: true, + // Probe unconfined: the point is the protocol, not the policy. + sandbox: damon_core::sandbox::SandboxRequest::None, + sandbox_support: spec.sandbox_support, + sandbox_network: spec.sandbox_network, }; let client = client_for(&resolved).expect("client"); println!("== {} available: {}", provider, client.is_available().await); diff --git a/src/backend/codex.rs b/src/backend/codex.rs index 3f22bba..abf6cfe 100644 --- a/src/backend/codex.rs +++ b/src/backend/codex.rs @@ -189,8 +189,7 @@ pub struct CodexSession { impl CodexSession { async fn spawn(resolved: &ResolvedBackend, config: SessionConfig) -> Result> { let env: HashMap = resolved.env.iter().cloned().collect(); - let transport = - NdjsonTransport::spawn(&resolved.command, &resolved.args, &env, &config.cwd).await?; + let transport = resolved.spawn_ndjson(&resolved.args, &env, &config).await?; let (events, _) = broadcast::channel(512); let session = Arc::new(Self { diff --git a/src/backend/droid.rs b/src/backend/droid.rs index 96cdd7f..0637c75 100644 --- a/src/backend/droid.rs +++ b/src/backend/droid.rs @@ -417,7 +417,7 @@ impl DroidSession { args.push("--auto".to_string()); args.push(mode.clone()); } - let transport = NdjsonTransport::spawn(&resolved.command, &args, &env, &config.cwd).await?; + let transport = resolved.spawn_ndjson(&args, &env, &config).await?; let (events, _) = broadcast::channel(512); let session = Arc::new(Self { @@ -1301,6 +1301,9 @@ mod tests { env: vec![], auth_hint: String::new(), detected: true, + sandbox: crate::sandbox::SandboxRequest::None, + sandbox_support: crate::sandbox::SandboxSupport::Spawn, + sandbox_network: crate::sandbox::NetworkPolicy::Allow, } } } diff --git a/src/backend/omp.rs b/src/backend/omp.rs index a2ce36d..8512b20 100644 --- a/src/backend/omp.rs +++ b/src/backend/omp.rs @@ -387,7 +387,7 @@ impl OmpSession { let env: HashMap = resolved.env.iter().cloned().collect(); let mut args = resolved.args.clone(); args.extend(mode_args(profile, config.mode.as_deref())); - let transport = NdjsonTransport::spawn(&resolved.command, &args, &env, &config.cwd).await?; + let transport = resolved.spawn_ndjson(&args, &env, &config).await?; let (events, _) = broadcast::channel(512); let session = Arc::new(Self { @@ -1183,6 +1183,9 @@ mod tests { env: vec![], auth_hint: String::new(), detected: true, + sandbox: crate::sandbox::SandboxRequest::None, + sandbox_support: crate::sandbox::SandboxSupport::Spawn, + sandbox_network: crate::sandbox::NetworkPolicy::Allow, }; for profile in [&OMP, &PI] { let client = OmpClient::with_profile(resolved.clone(), profile); diff --git a/src/backend/opencode.rs b/src/backend/opencode.rs index 7a77423..c738d72 100644 --- a/src/backend/opencode.rs +++ b/src/backend/opencode.rs @@ -63,6 +63,9 @@ use super::{AgentClient, AgentSession}; pub struct OpencodeClient { command: String, + /// The resolved backend, kept so the sandbox decision can refuse an + /// explicit request: serve mode has no per-session child to wrap. + resolved: ResolvedBackend, server: tokio::sync::OnceCell>, http: reqwest::Client, caps: Capabilities, @@ -73,6 +76,7 @@ impl OpencodeClient { pub fn new(resolved: &ResolvedBackend, provider: &'static str) -> Self { Self { command: resolved.command.clone(), + resolved: resolved.clone(), server: tokio::sync::OnceCell::new(), http: reqwest::Client::builder() .timeout(Duration::from_secs(30)) @@ -221,6 +225,12 @@ impl AgentClient for OpencodeClient { } async fn create_session(&self, config: SessionConfig) -> Result> { + // Serve mode: sessions are directories inside a shared server, so + // there is nothing here to confine. The decision still runs, because + // an explicit `sandbox` request must fail by name here rather than be + // silently ignored (sandbox::decide explains why serve mode has no + // spawn point). + self.resolved.sandbox_decision(&config)?; let server = self.srv().await?; // opencode has no MCP remove endpoint, and POST /mcp mutates // state shared by every session on the server — so damon only @@ -266,6 +276,9 @@ impl AgentClient for OpencodeClient { handle: &PersistenceHandle, config: SessionConfig, ) -> Result> { + // Same rule as create_session: an explicit sandbox request on a serve + // backend is refused, not ignored. + self.resolved.sandbox_decision(&config)?; let server = self.srv().await?; Ok(self.session(&handle.native_handle, config, &server)) } diff --git a/src/backend/registry.rs b/src/backend/registry.rs index 3b792f5..c16c2be 100644 --- a/src/backend/registry.rs +++ b/src/backend/registry.rs @@ -12,6 +12,7 @@ use std::sync::Arc; use crate::backend::{AgentClient, claude, codex, droid, omp, opencode, qwen, zcode}; use crate::config::AgentConfig; +use crate::sandbox::{NetworkPolicy, SandboxDecision, SandboxRequest, SandboxSpec, SandboxSupport}; /// One backend entry: how to detect it and how to launch a session. pub struct BackendSpec { @@ -33,6 +34,15 @@ pub struct BackendSpec { /// Copy-paste update command for CLIs npm doesn't distribute. /// Empty string + `npm_package: None` = no known update path. pub manual_update: &'static str, + /// How the backend launches — the thing that decides whether a sandbox + /// driver has a per-session child to wrap. Serve-mode backends are + /// `unsupported`, never silently `none` (see `sandbox::decide`). + pub sandbox_support: SandboxSupport, + /// Egress this backend needs when the user leaves + /// `sandbox_network = "backend"`. Every spawn-mode agent CLI talks to + /// its model API, so denying it here would leave a CLI that cannot + /// think; one-off command confinement opts into `deny` instead. + pub sandbox_network: NetworkPolicy, } pub const BACKENDS: &[BackendSpec] = &[ @@ -53,6 +63,8 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "log in with `claude` once; the subscription follows", npm_package: Some("@anthropic-ai/claude-code"), manual_update: "", + sandbox_support: SandboxSupport::Spawn, + sandbox_network: NetworkPolicy::Allow, }, BackendSpec { id: "codex", @@ -69,6 +81,8 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "log in with `codex` once; the subscription follows", npm_package: Some("@openai/codex"), manual_update: "", + sandbox_support: SandboxSupport::Spawn, + sandbox_network: NetworkPolicy::Allow, }, BackendSpec { id: "omp", @@ -80,6 +94,8 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "configure `omp` once; its provider auth follows", npm_package: Some("@oh-my-pi/pi-coding-agent"), manual_update: "", + sandbox_support: SandboxSupport::Spawn, + sandbox_network: NetworkPolicy::Allow, }, BackendSpec { id: "pi", @@ -95,6 +111,8 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "configure `pi` with a provider API key; auth follows the CLI", npm_package: Some("@earendil-works/pi-coding-agent"), manual_update: "", + sandbox_support: SandboxSupport::Spawn, + sandbox_network: NetworkPolicy::Allow, }, BackendSpec { id: "qwen", @@ -117,6 +135,8 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "log in with `qwen` (qwen-oauth) or configure an API key in its settings; auth follows the CLI", npm_package: Some("@qwen-code/qwen-code"), manual_update: "", + sandbox_support: SandboxSupport::Spawn, + sandbox_network: NetworkPolicy::Allow, }, BackendSpec { id: "droid", @@ -138,6 +158,8 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "log in with `droid` or set FACTORY_API_KEY; custom models live in ~/.factory/settings.json", npm_package: None, manual_update: "curl -fsSL https://app.factory.ai/cli | sh", + sandbox_support: SandboxSupport::Spawn, + sandbox_network: NetworkPolicy::Allow, }, BackendSpec { id: "opencode", @@ -152,6 +174,10 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "configure providers in opencode itself; Damon adopts or spawns `opencode serve`", npm_package: Some("opencode-ai"), manual_update: "", + // HTTP+SSE against a shared `opencode serve`: no per-session child + // to confine, so a sandbox request is refused rather than ignored. + sandbox_support: SandboxSupport::Serve, + sandbox_network: NetworkPolicy::Allow, }, BackendSpec { id: "mimo", @@ -165,6 +191,9 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "configure providers in mimo itself; Damon adopts or spawns `mimo serve`", npm_package: None, manual_update: "curl -fsSL https://mimo.xiaomi.com/install | bash", + // opencode's serve surface, and the same sandbox answer: unsupported. + sandbox_support: SandboxSupport::Serve, + sandbox_network: NetworkPolicy::Allow, }, BackendSpec { id: "zcode", @@ -181,6 +210,8 @@ pub const BACKENDS: &[BackendSpec] = &[ auth_hint: "log in with `zcode` (GLM Coding Plan); auth follows the CLI", npm_package: None, manual_update: "", + sandbox_support: SandboxSupport::Spawn, + sandbox_network: NetworkPolicy::Allow, }, ]; @@ -195,12 +226,24 @@ pub struct ResolvedBackend { pub auth_hint: String, /// Whether the detect binary was found on PATH at resolve time. pub detected: bool, + /// The sandbox declaration for this backend: its own `[backends.X] + /// sandbox`, else the top-level default. + pub sandbox: SandboxRequest, + /// Spawn vs serve — whether a driver has a child to wrap at all. + pub sandbox_support: SandboxSupport, + /// Egress inside the sandbox, with `backend` already resolved to the + /// catalog's declaration. + pub sandbox_network: NetworkPolicy, } /// Resolve catalog + config overrides into launch lines. Shared by boot /// and hot-reload so a reloaded config produces exactly the same backend /// set a restart would. -pub fn resolve_backends(overrides: &BTreeMap) -> Vec { +pub fn resolve_backends( + overrides: &BTreeMap, + default_sandbox: SandboxRequest, + default_network: NetworkPolicy, +) -> Vec { BACKENDS .iter() .map(|spec| { @@ -233,11 +276,70 @@ pub fn resolve_backends(overrides: &BTreeMap) -> Vec spec.sandbox_network, + explicit => explicit, + }, } }) .collect() } +/// [`resolve_backends`] against a loaded config — the sandbox defaults ride +/// with the launch lines, so every surface (boot, hot reload, `doctor`, the +/// backend.* RPCs) resolves a backend exactly the same way. +pub fn resolve_from_config(cfg: &crate::config::Config) -> Vec { + resolve_backends(&cfg.backends, cfg.sandbox, cfg.sandbox_network) +} + +impl ResolvedBackend { + /// The isolation decision for one session on this backend. + /// + /// `Err` is the fail-loudly case: the user (per session, per backend, or + /// globally) asked for a driver this backend or host cannot honor. The + /// message names the cause and the choices — this is the spawn point's + /// chance to refuse before the agent CLI ever starts. + pub fn sandbox_decision( + &self, + session: &crate::backend::types::SessionConfig, + ) -> anyhow::Result { + let spec = SandboxSpec { + backend: &self.id, + support: self.sandbox_support, + request: session.sandbox.unwrap_or(self.sandbox), + network: self.sandbox_network, + cwd: &session.cwd, + extra_writable: &session.granted_roots, + }; + crate::sandbox::decide(&spec) + } + + /// Spawn this backend's stdio child through the sandbox driver. + /// + /// Every spawn-mode backend's launch goes through here instead of + /// `NdjsonTransport::spawn` directly, so "the agent CLI runs under the + /// resolved policy" is one call site per backend rather than one more + /// thing each backend has to remember. + pub async fn spawn_ndjson( + &self, + args: &[String], + env: &std::collections::HashMap, + session: &crate::backend::types::SessionConfig, + ) -> anyhow::Result> { + let decision = self.sandbox_decision(session)?; + crate::backend::transport::NdjsonTransport::spawn( + &self.command, + args, + env, + &session.cwd, + Some(&decision), + ) + .await + } +} + /// Build the client for a resolved backend. Returns None for an id the /// registry doesn't know — overrides can change launch lines, not add /// protocols. @@ -386,6 +488,53 @@ mod tests { ); } + /// Only the serve-mode backends have no spawn point to confine; every + /// stdio backend does, and every agent CLI declares that it needs its + /// model API (network allow). + #[test] + fn sandbox_support_follows_the_process_model() { + for spec in BACKENDS { + let want = match spec.id { + "opencode" | "mimo" => SandboxSupport::Serve, + _ => SandboxSupport::Spawn, + }; + assert_eq!(spec.sandbox_support, want, "{}", spec.id); + assert_eq!(spec.sandbox_network, NetworkPolicy::Allow, "{}", spec.id); + } + } + + /// The global `sandbox_network` override reaches every backend, while + /// the default (`backend`) keeps each one's own declaration. + #[test] + fn network_override_wins_over_the_catalog() { + let resolved = + resolve_backends(&BTreeMap::new(), SandboxRequest::Auto, NetworkPolicy::Deny); + assert!( + resolved + .iter() + .all(|b| b.sandbox_network == NetworkPolicy::Deny) + ); + } + + /// A per-backend `sandbox` beats the top-level default at resolve time, + /// which is what the spawn point later sees. + #[test] + fn backend_sandbox_override_beats_the_default() { + let mut overrides = BTreeMap::new(); + overrides.insert( + "codex".to_string(), + AgentConfig { + sandbox: Some(SandboxRequest::None), + ..Default::default() + }, + ); + let resolved = resolve_backends(&overrides, SandboxRequest::Bwrap, NetworkPolicy::Backend); + let codex = resolved.iter().find(|b| b.id == "codex").unwrap(); + assert_eq!(codex.sandbox, SandboxRequest::None); + let claude = resolved.iter().find(|b| b.id == "claude").unwrap(); + assert_eq!(claude.sandbox, SandboxRequest::Bwrap); + } + #[test] fn overrides_replace_launch_line() { let mut overrides = BTreeMap::new(); @@ -395,9 +544,10 @@ mod tests { command: Some("/opt/claude-custom".to_string()), args: Some(vec!["--flag".to_string()]), env: std::collections::HashMap::from([("K".to_string(), "V".to_string())]), + sandbox: None, }, ); - let resolved = resolve_backends(&overrides); + let resolved = resolve_backends(&overrides, SandboxRequest::Auto, NetworkPolicy::Backend); let claude = resolved.iter().find(|b| b.id == "claude").unwrap(); assert_eq!(claude.command, "/opt/claude-custom"); assert_eq!(claude.args, vec!["--flag"]); diff --git a/src/backend/streamjson.rs b/src/backend/streamjson.rs index da53efb..f87f6f6 100644 --- a/src/backend/streamjson.rs +++ b/src/backend/streamjson.rs @@ -637,8 +637,9 @@ impl StreamJsonSession { let mut args = resolved.args.clone(); args.extend(dialect.launch_args(&config, resume)); - let transport = - NdjsonTransport::spawn(&resolved.command, &args, &HashMap::new(), &config.cwd).await?; + let transport = resolved + .spawn_ndjson(&args, &HashMap::new(), &config) + .await?; let session = Arc::new(Self { transport: transport.clone(), @@ -961,9 +962,10 @@ impl AgentSession for OneShotSession { args.extend(self.dialect.launch_args(&config, resume.as_deref())); args.extend(self.dialect.prompt_args(&prompt)?); - let transport = - NdjsonTransport::spawn(&self.resolved.command, &args, &HashMap::new(), &config.cwd) - .await?; + let transport = self + .resolved + .spawn_ndjson(&args, &HashMap::new(), &config) + .await?; *self.active.lock().await = Some(transport.clone()); let turn_id = uuid::Uuid::new_v4().to_string(); @@ -1285,6 +1287,9 @@ pub(crate) mod tests { env: vec![], auth_hint: String::new(), detected: true, + sandbox: crate::sandbox::SandboxRequest::None, + sandbox_support: crate::sandbox::SandboxSupport::Spawn, + sandbox_network: crate::sandbox::NetworkPolicy::Allow, }; let session = StreamJsonSession::spawn( &resolved, diff --git a/src/backend/transport.rs b/src/backend/transport.rs index a6a86cd..059b724 100644 --- a/src/backend/transport.rs +++ b/src/backend/transport.rs @@ -22,6 +22,8 @@ use tokio::io::{AsyncWriteExt, BufReader}; use tokio::process::{Child, Command}; use tokio::sync::{Mutex, broadcast, oneshot, watch}; +use crate::sandbox::SandboxDecision; + /// Hard cap on one stdout line. Protocol frames are small; a runaway /// agent emitting a megabyte-long line must not grow the read buffer /// without bound — the line is dropped, the stream lives. @@ -134,12 +136,29 @@ mod winjob { impl NdjsonTransport { /// Spawn the process and start the stdout/stderr reader tasks. /// No handshake happens here — the backend drives its own. + /// + /// `sandbox` is this session's resolved isolation decision: a confined + /// decision rewrites the launch into the driver's launcher (bwrap), an + /// unconfined one passes the command through. It is resolved by the + /// caller, so an explicit-but-impossible request fails there, before + /// anything spawns — a spawn here never "falls back" on its own. pub async fn spawn( command: &str, args: &[String], env: &HashMap, cwd: &Path, + sandbox: Option<&SandboxDecision>, ) -> anyhow::Result> { + // The launcher rewrite happens before any Windows batch handling: + // a sandboxed launch never execs the CLI directly. + let confined; + let (command, args) = match sandbox { + Some(decision) => { + confined = decision.confine(command, args)?; + (confined.program.as_str(), confined.args.as_slice()) + } + None => (command, args), + }; // Windows resolves `npx` to `npx.cmd`, which CreateProcess cannot // exec directly — batch files need the cmd interpreter. #[cfg(windows)] @@ -604,6 +623,7 @@ mod tests { &[script.to_string_lossy().into_owned()], &Default::default(), &cwd, + None, ) .await .unwrap(); @@ -668,6 +688,7 @@ mod tests { &[script.to_string_lossy().into_owned()], &Default::default(), &cwd, + None, ) .await .unwrap(); diff --git a/src/backend/types.rs b/src/backend/types.rs index 94c79b4..6ae0447 100644 --- a/src/backend/types.rs +++ b/src/backend/types.rs @@ -41,6 +41,12 @@ pub struct SessionConfig { /// refuses read-only nodes on backends whose capability says they /// cannot enforce the list, so nothing silently downgrades. pub allowed_tools: Vec, + /// Sandbox override for this session. `None` follows the backend's + /// config (which itself defaults to the top-level `sandbox`); a value + /// here wins for this session only. An explicit value the backend or + /// host cannot honor fails the spawn with the reason (see + /// `sandbox::decide`). + pub sandbox: Option, } /// One stdio MCP server, normalized. Backends translate to their own diff --git a/src/backend/zcode.rs b/src/backend/zcode.rs index 7a0c2d9..661886f 100644 --- a/src/backend/zcode.rs +++ b/src/backend/zcode.rs @@ -136,8 +136,17 @@ impl AgentClient for ZcodeClient { /// listing as best-effort, matching the codex backend). async fn list_importable_sessions(&self, cwd: &Path) -> Result> { let env: HashMap = self.resolved.env.iter().cloned().collect(); - let Ok(transport) = - NdjsonTransport::spawn(&self.resolved.command, &self.resolved.args, &env, cwd).await + let Ok(transport) = NdjsonTransport::spawn( + &self.resolved.command, + &self.resolved.args, + &env, + cwd, + // Discovery probe only — it answers `session/list` and never + // runs an agent command, so it is not one of the spawns the + // sandbox policy exists to confine. + None, + ) + .await else { return Ok(vec![]); }; @@ -352,8 +361,7 @@ impl ZcodeSession { resume: Option<&str>, ) -> Result> { let env: HashMap = resolved.env.iter().cloned().collect(); - let transport = - NdjsonTransport::spawn(&resolved.command, &resolved.args, &env, &config.cwd).await?; + let transport = resolved.spawn_ndjson(&resolved.args, &env, &config).await?; let (events, _) = broadcast::channel(512); let session = Arc::new(Self { diff --git a/src/bin/damond.rs b/src/bin/damond.rs index d6655d1..70d4b9d 100644 --- a/src/bin/damond.rs +++ b/src/bin/damond.rs @@ -357,7 +357,7 @@ async fn doctor(path: &Path) -> anyhow::Result<()> { let cfg_for_backends = cfg .clone() .unwrap_or_else(|| toml::from_str("").expect("empty config parses")); - let resolved = damon_core::backend::registry::resolve_backends(&cfg_for_backends.backends); + let resolved = damon_core::backend::registry::resolve_from_config(&cfg_for_backends); let runner: std::sync::Arc = std::sync::Arc::new(damon_core::cli_lifecycle::RealRunner); let probes = resolved.iter().map(|b| { @@ -399,6 +399,13 @@ async fn doctor(path: &Path) -> anyhow::Result<()> { ); } + // Sandbox: one header for the requested mode and the platform driver, + // then one line per detected backend saying what would actually be + // applied. This is the surface that keeps `auto` honest — a host with + // no usable driver says so here instead of leaving the user to assume + // the agent is confined. + sandbox_report(&mut ok, &resolved); + if let Some(cfg) = &cfg { match &cfg.auth_token { None => report(&mut ok, true, "auth_token — not set (loopback only)"), @@ -450,6 +457,54 @@ fn report(ok: &mut bool, pass: bool, msg: impl std::fmt::Display) { *ok &= pass; } +/// `doctor` sandbox section: what each detected backend would get. +/// +/// A requested driver that cannot be honored is a FAIL — that config would +/// fail every session start, which is exactly what a diagnostic should +/// catch before the first turn. `auto` without a driver is fine (it is the +/// zero-config default), and so is the serve-mode `unsupported` state, but +/// both are printed with the reason rather than as silence. +fn sandbox_report(ok: &mut bool, resolved: &[damon_core::backend::registry::ResolvedBackend]) { + use damon_core::backend::types::SessionConfig; + use damon_core::sandbox; + + // The platform driver's own status, independent of any backend. + let header = match sandbox::platform_default() { + Some(kind) => match sandbox::driver_for(kind) { + Some(driver) => { + let status = driver.status(); + let mark = if status.usable { + "usable" + } else { + "not usable" + }; + format!("sandbox driver {kind} — {mark}: {}", status.detail) + } + None => format!("sandbox driver {kind} — not implemented in this release"), + }, + None => "sandbox driver — none for this platform yet".to_string(), + }; + outln(format!(" {header}")); + + // A per-session `sandbox` value is not known here; each backend's own + // declaration is what `session.create` inherits when it passes none. + let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")); + for backend in resolved.iter().filter(|b| b.detected) { + let session = SessionConfig { + cwd: cwd.clone(), + ..Default::default() + }; + match backend.sandbox_decision(&session) { + Ok(decision) => report( + ok, + true, + format!("sandbox {} — {}", backend.id, decision.describe()), + ), + Err(e) => report(ok, false, format!("sandbox {} — {e:#}", backend.id)), + } + } +} + /// Write one line to stdout, exiting quietly with 141 (128+SIGPIPE, the /// killed-by-SIGPIPE convention) when the pipe is gone. Rust ignores /// println! with a noisy exit 101. diff --git a/src/config.rs b/src/config.rs index be77964..0a38a5a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,6 +8,8 @@ use notify::Watcher; use serde::Deserialize; use tracing::{info, warn}; +use crate::sandbox::{NetworkPolicy, SandboxRequest}; + /// Daemon configuration. Hot-reloaded: changes to the config file are picked /// up without restart, except `bind` which requires a restart. #[derive(Clone, Debug, Deserialize)] @@ -30,6 +32,19 @@ pub struct Config { pub backends: BTreeMap, /// Default backend id for session.create without an explicit backend. pub default_backend: Option, + /// OS-level sandbox for agent CLI child processes — the default for + /// every backend that does not set its own `sandbox`: `auto` (this + /// platform's driver, when the host can run it), `bwrap`, `seatbelt`, + /// `docker`, or `none` (explicit opt-out). An explicitly named driver + /// that this backend or host cannot honor fails the session at start + /// instead of silently running unconfined. Hot-reloaded. + #[serde(default)] + pub sandbox: SandboxRequest, + /// Egress policy inside the sandbox: `backend` (whatever that backend + /// declares — every agent CLI allows it, because its model API call is + /// the point), `allow`, or `deny`. Hot-reloaded. + #[serde(default)] + pub sandbox_network: NetworkPolicy, #[serde(rename = "relay")] pub relay: Option, /// Deny tool calls if the permission prompt goes unanswered this long. @@ -180,6 +195,8 @@ pub struct AgentConfig { pub args: Option>, #[serde(default)] pub env: HashMap, + /// Per-backend sandbox override; unset follows the top-level `sandbox`. + pub sandbox: Option, } /// `[relay]` — outbound tunnel to a public relay. @@ -457,10 +474,18 @@ const STARTER_CONFIG: &str = r#"# Damon agent core configuration. # permission_timeout_secs = 300 # deny agent permission asks after this # session_retention_days = 30 # delete sessions older than this +# OS sandbox for agent CLI child processes — default "auto": use this +# platform's driver (bwrap on Linux, seatbelt on macOS) when the host can run +# it, and report it in `damond doctor` when it cannot. "none" is an explicit +# opt-out; naming a driver this host cannot honor fails the session at start. +# sandbox = "auto" +# sandbox_network = "backend" # backend | allow | deny (see config.example.toml) + # Launch overrides: # [backends.claude] # command = "claude" # default launch line for claude # args = ["-p", "--output-format", "stream-json", "--input-format", "stream-json", "--verbose"] +# sandbox = "bwrap" # per-backend override of the top-level sandbox # [backends.claude.env] # ANTHROPIC_MODEL = "claude-sonnet-4-5" "#; @@ -562,6 +587,41 @@ mod tests { assert!(toml::from_str::(r#"providers = {}"#).is_err()); } + /// `sandbox` reads at three levels (global default, per backend, per + /// session) and an unknown spelling is a config error, not a silent + /// "whatever the default was". + #[test] + fn parses_sandbox_declarations() { + let cfg: Config = toml::from_str("").unwrap(); + assert_eq!(cfg.sandbox, SandboxRequest::Auto); + assert_eq!(cfg.sandbox_network, NetworkPolicy::Backend); + + let cfg: Config = toml::from_str( + r#" + sandbox = "bwrap" + sandbox_network = "deny" + [backends.claude] + sandbox = "seatbelt" + "#, + ) + .unwrap(); + assert_eq!(cfg.sandbox, SandboxRequest::Bwrap); + assert_eq!(cfg.sandbox_network, NetworkPolicy::Deny); + assert_eq!( + cfg.backends["claude"].sandbox, + Some(SandboxRequest::Seatbelt) + ); + // A backend without its own declaration follows the default. + let resolved = crate::backend::registry::resolve_from_config(&cfg); + assert_eq!( + resolved.iter().find(|b| b.id == "codex").unwrap().sandbox, + SandboxRequest::Bwrap + ); + + assert!(toml::from_str::(r#"sandbox = "bubblewrap""#).is_err()); + assert!(toml::from_str::(r#"sandbox_network = "maybe""#).is_err()); + } + #[test] fn secret_refs_parse_and_describe() { assert!(matches!(SecretRef::parse("env:X"), Ok(SecretRef::Env(_)))); diff --git a/src/lib.rs b/src/lib.rs index 88c0d3e..316523c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,6 +18,7 @@ pub mod prompts; pub mod ratelimit; pub mod relay; pub mod rpc; +pub mod sandbox; pub mod service; pub mod session; pub mod skills_hub; diff --git a/src/rpc.rs b/src/rpc.rs index a0ce866..c0cf82b 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -756,8 +756,10 @@ async fn dispatch( .get() .cloned() .unwrap_or_else(|| std::sync::Arc::new(crate::cli_lifecycle::RealRunner)); - let resolved = - crate::backend::registry::resolve_backends(&state.config.read().backends); + let resolved = { + let cfg = state.config.read(); + crate::backend::registry::resolve_from_config(&cfg) + }; let targets: Vec<_> = resolved .iter() .filter(|b| only.is_none_or(|o| b.id == o)) @@ -819,8 +821,10 @@ async fn dispatch( .get() .cloned() .unwrap_or_else(|| std::sync::Arc::new(crate::cli_lifecycle::RealRunner)); - let resolved = - crate::backend::registry::resolve_backends(&state.config.read().backends); + let resolved = { + let cfg = state.config.read(); + crate::backend::registry::resolve_from_config(&cfg) + }; let entry = resolved.iter().find(|b| b.id == backend).ok_or_else(|| { RpcError::error( error_code::INVALID_PARAMS, @@ -850,8 +854,10 @@ async fn dispatch( .get() .cloned() .unwrap_or_else(|| std::sync::Arc::new(crate::cli_lifecycle::RealRunner)); - let resolved = - crate::backend::registry::resolve_backends(&state.config.read().backends); + let resolved = { + let cfg = state.config.read(); + crate::backend::registry::resolve_from_config(&cfg) + }; let entry = resolved.iter().find(|b| b.id == backend).ok_or_else(|| { RpcError::error( error_code::INVALID_PARAMS, @@ -3510,7 +3516,7 @@ pub fn rpc_methods() -> Vec { json!({"name": "mcp.inventory", "params": {}, "result": {"entries": "array of {backend, name, transport, command?, url?, envKeys?, source, format, version, enabled?, readonlyReason?} — REDACTED: env values never leave the file, URLs lose userinfo/query, stdio shows the program and an arg count", "sources": "array of {backend, source, format, error?} — one per config file; a broken file reports its error and the inventory continues"}}), json!({"name": "mcp.probe", "params": {"backend": "string", "name": "string"}, "result": "{backend, name, result: 'connected'|'needs_auth'|'failed'|'unsupported', tools: string[] — names only, ≤40, serverName?, protocolVersion?, elapsedMs, error?} — REAL handshake, explicit request only (never scheduled); stdio 25s cap, HTTP 12s cap; the server's command/args/env never reach the wire"}), json!({"name": "mcp.setEnabled", "params": {"backend": "string — claude only this round", "name": "string", "enabled": "boolean", "expectedVersion": "string — CAS from mcp.inventory", "cwd": "string? — project scope for the toggle, default the daemon cwd"}, "result": {"set": "boolean"}, "errors": "-32010 the entry changed since the snapshot (external edit); -32602 readonly backend (reason in the message) or parse-failed config (never written)"}), - json!({"name": "session.create", "params": {"backend": "string?", "cwd": "string?", "model": "string?", "mode": "string?", "mcpServers": "object?", "allowedTools": "string[]? — per-session tool allowlist for backends that enforce one at launch (claude: --allowedTools); non-string entries are dropped", "projectId": "string? — scopes the session: root becomes the cwd default, project defaults fill unset params", "persona": "string? — bot id from bot.list; the bot's SOUL/AGENTS block rides in front of every turn, bound for the session's life and restored on resume"}, "result": {"sessionId": "string", "backend": "string", "persona?": "string — the bound bot id, when one was given", "replayed": "number — replay-tagged session.event frames sent for missed history", "cursor": "number — the newest session event seq handed out so far; the next live frame continues from it (gaps → session.gap)"}, "errors": "-32602 unknown persona id"}), + json!({"name": "session.create", "params": {"backend": "string?", "cwd": "string?", "model": "string?", "mode": "string?", "mcpServers": "object?", "allowedTools": "string[]? — per-session tool allowlist for backends that enforce one at launch (claude: --allowedTools); non-string entries are dropped", "projectId": "string? — scopes the session: root becomes the cwd default, project defaults fill unset params", "persona": "string? — bot id from bot.list; the bot's SOUL/AGENTS block rides in front of every turn, bound for the session's life and restored on resume", "sandbox": "string? — auto|bwrap|seatbelt|docker|none; unset follows the backend's configured sandbox, and a value this backend or host cannot honor fails the create instead of silently running unconfined"}, "result": {"sessionId": "string", "backend": "string", "persona?": "string — the bound bot id, when one was given", "replayed": "number — replay-tagged session.event frames sent for missed history", "cursor": "number — the newest session event seq handed out so far; the next live frame continues from it (gaps → session.gap)"}, "errors": "-32602 unknown persona id; unknown sandbox mode"}), json!({"name": "session.resume", "params": {"sessionId": "string? — resume a session damon already knows", "handle": "{provider, native_handle}? — import a native session that has no damon row yet", "cwd": "string?", "title": "string?"}, "result": {"sessionId": "string", "backend": "string", "replayed": "number", "cursor": "number"}, "errors": "-32602 sessionId or handle required; handle must be {provider, native_handle, metadata?}"}), json!({"name": "session.list", "params": {"limit": "number?", "offset": "number?", "backend": "string?", "cwd": "string?", "tag": "string?", "projectId": "string?", "includeArchived": "boolean? — include archived rows, default false"}, "result": {"sessions": "array of {sessionId, createdAt, backend, title, cwd, tags, pinned, archived}"}}), json!({"name": "session.messages", "params": {"sessionId": "string", "limit": "number?", "offset": "number?"}, "result": {"messages": "array of {id, session_id, role, ts, data} — ts is unix ms, 0 when unknown"}}), diff --git a/src/rpc/session.rs b/src/rpc/session.rs index 3722e35..e01392c 100644 --- a/src/rpc/session.rs +++ b/src/rpc/session.rs @@ -52,6 +52,11 @@ pub(super) struct Create { /// (claude: `--allowedTools`). Loose elements are dropped, not /// refused — the pre-refactor read filtered non-strings out. allowed_tools: Option>, + /// Per-session sandbox override (`auto|bwrap|seatbelt|docker|none`). + /// Unset follows the backend's config. A value the backend or host + /// cannot honor fails the create with the reason — see + /// `sandbox::decide`. + sandbox: Option, } impl Params for Create { @@ -65,6 +70,7 @@ impl Params for Create { Field::str_opt("projectId"), Field::str_opt("persona"), Field::array_opt("allowedTools"), + Field::str_opt("sandbox"), ]; } @@ -72,8 +78,8 @@ impl Create { /// The launch config this request asks for, before project defaults /// and grants are layered on. `cwd` falls back to the daemon's own /// working directory exactly as before. - fn config(&self) -> SessionConfig { - SessionConfig { + fn config(&self) -> Result { + Ok(SessionConfig { cwd: self .cwd .as_deref() @@ -92,7 +98,16 @@ impl Create { .collect() }) .unwrap_or_default(), - } + // A misspelled mode is an error, not a silent "whatever the + // config says": the caller asked this session to be confined. + sandbox: match self.sandbox.as_deref() { + None => None, + Some(raw) => Some( + crate::sandbox::SandboxRequest::parse(raw) + .map_err(|e| RpcError::error(error_code::INVALID_PARAMS, e.to_string()))?, + ), + }, + }) } } @@ -450,7 +465,7 @@ pub(super) async fn create( params: &Value, ) -> Result { let req = Create::parse(params)?; - let mut cfg = req.config(); + let mut cfg = req.config()?; let mut backend = req.backend.clone(); // A project scopes the session: its root becomes the cwd default and // its defaults fill whatever the request left unset (explicit params diff --git a/src/sandbox/bwrap.rs b/src/sandbox/bwrap.rs new file mode 100644 index 0000000..8c0bc1c --- /dev/null +++ b/src/sandbox/bwrap.rs @@ -0,0 +1,512 @@ +//! The Linux driver: bubblewrap (`bwrap`) — mount namespaces for the +//! filesystem, `unshare` for the rest, no root and no daemon. +//! +//! This file is the whole bwrap surface: a pure compiler from +//! [`SandboxPolicy`] to `bwrap` argv (unit- and golden-tested, no process +//! involved), and the availability probe a real launch depends on. +//! +//! The compiled shape is deliberately "default deny, named allows": +//! +//! ```text +//! --ro-bind / / host root, read-only +//! --dev /dev --proc /proc fresh device and proc trees +//! --tmpfs /tmp writable scratch, discarded with the session +//! --bind the workdir, granted roots, the CLI's own state +//! --tmpfs each deny, compiled AFTER the binds so it wins +//! --unshare-all pid/ipc/uts/cgroup/user (+ net unless allowed) +//! --cap-drop ALL +//! --die-with-parent --new-session +//! ``` + +use std::path::Path; +use std::process::{Command, Stdio}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use anyhow::{Result, bail}; + +use super::{ + DenyKind, DriverStatus, NetworkPolicy, SCRUBBED_ENV, SandboxCommand, SandboxDriver, + SandboxKind, SandboxPolicy, +}; + +/// How long the availability probe may take before it counts as unusable. +/// A working bwrap answers in milliseconds; a hung one must not stall +/// `doctor` or the first session. +const PROBE_TIMEOUT: Duration = Duration::from_secs(10); + +pub struct Bwrap; + +impl SandboxDriver for Bwrap { + fn kind(&self) -> SandboxKind { + SandboxKind::Bwrap + } + + fn status(&self) -> DriverStatus { + static STATUS: OnceLock = OnceLock::new(); + STATUS.get_or_init(probe).clone() + } + + fn wrap( + &self, + policy: &SandboxPolicy, + command: &str, + args: &[String], + ) -> Result { + Ok(SandboxCommand { + program: launcher(), + args: compile_args(policy, command, args)?, + }) + } +} + +/// The launcher binary name. Resolved through PATH by the spawn, which is +/// also how the probe found it. +fn launcher() -> String { + "bwrap".to_string() +} + +/// Policy + command → the full `bwrap` argument list (everything after the +/// program name). Pure: no filesystem access, no process, so it is the piece +/// the golden test pins. +pub fn compile_args(policy: &SandboxPolicy, command: &str, args: &[String]) -> Result> { + if !policy.cwd.is_absolute() { + bail!("sandbox cwd must be absolute, got {}", policy.cwd.display()); + } + if policy.writable.iter().any(|p| p == Path::new("/")) { + bail!("refusing to bind the host root writable"); + } + for path in policy + .writable + .iter() + .chain(policy.denied.iter()) + .chain(policy.denied_files.iter()) + { + if !path.is_absolute() { + bail!("sandbox path must be absolute, got {}", path.display()); + } + } + + let mut out: Vec = Vec::new(); + // Allows first, denies after them (see below). `--dev`/`--proc` take a + // single DEST, unlike the SRC DEST mount flags. + pair(&mut out, "--ro-bind", "/", "/"); + one(&mut out, "--dev", "/dev"); + one(&mut out, "--proc", "/proc"); + for path in &policy.writable { + let path = path.to_string_lossy().into_owned(); + pair(&mut out, "--bind", &path, &path); + } + // Scratch space: writable, but a tmpfs, so nothing survives the session. + // + // Only when no writable path lives under /tmp. bwrap resolves a mount's + // source in the namespace it has built so far, so a tmpfs on /tmp would + // both hide an already-bound workdir and make its source unresolvable; + // a workdir inside /tmp therefore keeps the host's read-only /tmp. + // (TMPDIR-nameable scratch is the cost, and it is the safe side of the + // trade: a read-only /tmp fails a write, it does not leak one.) + if !policy.writable.iter().any(|p| p.starts_with("/tmp")) { + one(&mut out, "--tmpfs", "/tmp"); + } + // Denies last — a mount stacked on top of a wider bind, so it wins even + // when a granted root happens to contain a credential store. A file + // credential takes /dev/null over it (a tmpfs mounts on directories). + for (path, kind) in policy.deny_overlays() { + match kind { + DenyKind::EmptyDir => one(&mut out, "--tmpfs", &path.to_string_lossy()), + DenyKind::NullFile => pair(&mut out, "--ro-bind", "/dev/null", &path.to_string_lossy()), + } + } + out.push("--unshare-all".to_string()); + if policy.network == NetworkPolicy::Allow { + // `--unshare-all` took the network with everything else; share it + // back when the backend needs its model API. + out.push("--share-net".to_string()); + } + out.push("--cap-drop".to_string()); + out.push("ALL".to_string()); + // The sandbox dies with the daemon instead of outliving it, and no + // terminal can be injected into the child. + out.push("--die-with-parent".to_string()); + out.push("--new-session".to_string()); + for var in SCRUBBED_ENV { + one(&mut out, "--unsetenv", var); + } + one(&mut out, "--chdir", &policy.cwd.to_string_lossy()); + out.push("--".to_string()); + out.push(command.to_string()); + out.extend(args.iter().cloned()); + Ok(out) +} + +/// `flag value` — one argument flag. +fn one(out: &mut Vec, flag: &str, value: &str) { + out.push(flag.to_string()); + out.push(value.to_string()); +} + +/// `flag src dest` — a mount flag. +fn pair(out: &mut Vec, flag: &str, src: &str, dest: &str) { + one(out, flag, src); + out.push(dest.to_string()); +} + +/// Is bwrap installed here, and can it actually build a sandbox? +/// +/// Two separate questions, because they fail differently and users fix them +/// differently: a missing binary is an install, a rejected `unshare` is a +/// kernel/sysctl (or packaging) problem — on many distros unprivileged user +/// namespaces are off (`kernel.unprivileged_userns_clone=0`, Ubuntu 24.04's +/// AppArmor restriction), and bwrap then cannot start at all. +fn probe() -> DriverStatus { + let Some(path) = crate::backend::registry::which("bwrap") else { + return DriverStatus::unavailable( + SandboxKind::Bwrap, + "bubblewrap is not installed (bwrap not found on PATH)", + ); + }; + let version = run_probe(&path, &["--version"]) + .and_then(|(ok, out)| ok.then_some(out)) + .map(|out| out.trim().to_string()) + .filter(|v| !v.is_empty()); + let label = match &version { + Some(v) => format!("bubblewrap {v}"), + None => "bubblewrap".to_string(), + }; + + // A full confinement cycle, cheap and side-effect free: if this fails, + // every real launch would fail the same way. + let smoke = vec![ + "--ro-bind", + "/", + "/", + "--dev", + "/dev", + "--proc", + "/proc", + "--unshare-all", + "--die-with-parent", + "--new-session", + "--", + "/bin/true", + ]; + match run_probe(&path, &smoke) { + Some((true, _)) => DriverStatus { + kind: SandboxKind::Bwrap, + installed: true, + usable: true, + detail: format!("{label}, usable"), + }, + Some((false, err)) => DriverStatus { + kind: SandboxKind::Bwrap, + installed: true, + usable: false, + detail: format!( + "{label} installed, but it cannot create a sandbox: {}", + explain(&err) + ), + }, + None => DriverStatus { + kind: SandboxKind::Bwrap, + installed: true, + usable: false, + detail: format!("{label} installed, but the launch probe timed out or hung"), + }, + } +} + +/// Turn bwrap's stderr into something a user can act on. +fn explain(stderr: &str) -> String { + let line = stderr + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or("no output"); + if line.contains("Operation not permitted") || line.to_lowercase().contains("namespace") { + format!( + "{line} (unprivileged user namespaces look disabled — check \ + kernel.unprivileged_userns_clone / the distro's userns policy)" + ) + } else { + line.to_string() + } +} + +/// Run the launcher with a hard deadline. `Some((success, combined output))`, +/// or None when it could not be started or hung past [`PROBE_TIMEOUT`]. +fn run_probe(program: &Path, args: &[&str]) -> Option<(bool, String)> { + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .ok()?; + // Drain both pipes on helper threads: a probe that fills a pipe buffer + // would otherwise block against the wait loop below. + let mut stdout = child.stdout.take()?; + let mut stderr = child.stderr.take()?; + let out_reader = std::thread::spawn(move || { + let mut buf = Vec::new(); + use std::io::Read; + let _ = stdout.read_to_end(&mut buf); + buf + }); + let err_reader = std::thread::spawn(move || { + let mut buf = Vec::new(); + use std::io::Read; + let _ = stderr.read_to_end(&mut buf); + buf + }); + let deadline = Instant::now() + PROBE_TIMEOUT; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(20)); + } + _ => { + let _ = child.kill(); + let _ = child.wait(); + let _ = out_reader.join(); + let _ = err_reader.join(); + return None; + } + } + }; + let stdout = out_reader.join().unwrap_or_default(); + let stderr = err_reader.join().unwrap_or_default(); + let combined = if stderr.is_empty() { stdout } else { stderr }; + Some(( + status.success(), + String::from_utf8_lossy(&combined).into_owned(), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sandbox::{SandboxDecision, SandboxRequest, SandboxSpec, Unconfined, decide}; + + fn policy(network: NetworkPolicy) -> SandboxPolicy { + SandboxPolicy { + backend: "claude".to_string(), + cwd: "/home/u/project".into(), + writable: vec!["/home/u/project".into(), "/home/u/.claude".into()], + denied: vec!["/home/u/.ssh".into(), "/home/u/.aws".into()], + denied_files: Vec::new(), + network, + } + } + + /// Golden: the compiled launcher argv, in order. Order is the policy — + /// read-only root first, binds next, deny overlays after them, the + /// command last — so this test is the review of the whole shape. + #[test] + fn compiles_the_golden_argv() { + let args = compile_args( + &policy(NetworkPolicy::Deny), + "claude", + &["-p".to_string(), "--verbose".to_string()], + ) + .unwrap(); + assert_eq!( + args, + vec![ + "--ro-bind", + "/", + "/", + "--dev", + "/dev", + "--proc", + "/proc", + "--bind", + "/home/u/project", + "/home/u/project", + "--bind", + "/home/u/.claude", + "/home/u/.claude", + "--tmpfs", + "/tmp", + "--tmpfs", + "/home/u/.ssh", + "--tmpfs", + "/home/u/.aws", + "--unshare-all", + "--cap-drop", + "ALL", + "--die-with-parent", + "--new-session", + "--unsetenv", + "SSH_AUTH_SOCK", + "--chdir", + "/home/u/project", + "--", + "claude", + "-p", + "--verbose", + ] + ); + } + + /// A workdir under /tmp keeps the host's read-only /tmp: a tmpfs there + /// would hide the bind, and bwrap resolves a mount's source in the + /// namespace it has built so far. + #[test] + fn a_tmp_workdir_does_not_shadow_itself() { + let mut p = policy(NetworkPolicy::Allow); + p.cwd = "/tmp/work".into(); + p.writable = vec!["/tmp/work".into()]; + let args = compile_args(&p, "sh", &[]).unwrap(); + let binds = args.iter().position(|a| a == "--bind").unwrap(); + let tmpfs_tmp = args + .windows(2) + .position(|w| w[0] == "--tmpfs" && w[1] == "/tmp"); + assert!( + tmpfs_tmp.is_none_or(|i| i > binds), + "no /tmp tmpfs when the workdir lives there: {args:?}" + ); + // The deny overlays are still there. + assert!( + args.windows(2) + .any(|w| w[0] == "--tmpfs" && w[1] == "/home/u/.ssh"), + "{args:?}" + ); + } + + /// Network is denied by `--unshare-all` and shared back only on ask. + #[test] + fn shares_the_network_only_when_the_policy_allows_it() { + let denied = compile_args(&policy(NetworkPolicy::Deny), "sh", &[]).unwrap(); + assert!(!denied.iter().any(|a| a == "--share-net")); + let allowed = compile_args(&policy(NetworkPolicy::Allow), "sh", &[]).unwrap(); + let pos = allowed.iter().position(|a| a == "--share-net").unwrap(); + let unshare = allowed.iter().position(|a| a == "--unshare-all").unwrap(); + assert!(pos > unshare, "--share-net must follow --unshare-all"); + } + + /// Every deny overlay is compiled after every writable bind, so a deny + /// masks a wider allow instead of being masked by it. + #[test] + fn deny_overlays_come_after_the_binds_they_mask() { + let mut p = policy(NetworkPolicy::Allow); + // A granted root that contains a credential store: the store's + // overlay must land on top of it. + p.writable = vec!["/home/u".into()]; + p.denied = vec!["/home/u/.ssh".into()]; + let args = compile_args(&p, "sh", &[]).unwrap(); + let last_bind = args.iter().rposition(|a| a == "--bind").unwrap(); + let deny = args + .iter() + .position(|a| a == "--tmpfs" && a != "/tmp") + .unwrap(); + assert!( + deny > last_bind, + "deny overlay must be compiled after the writable binds: {args:?}" + ); + } + + /// A credential that is a plain file is masked by /dev/null, not by a + /// tmpfs (which cannot mount on a file and would fail the whole launch). + #[test] + fn a_file_credential_is_masked_with_dev_null() { + let mut p = policy(NetworkPolicy::Allow); + p.denied_files = vec!["/home/u/.netrc".into()]; + let args = compile_args(&p, "sh", &[]).unwrap(); + let i = args.iter().position(|a| a == "/home/u/.netrc").unwrap(); + assert_eq!( + &args[i - 2..=i], + ["--ro-bind", "/dev/null", "/home/u/.netrc"] + ); + } + + #[test] + fn refuses_a_relative_cwd_or_path() { + let mut p = policy(NetworkPolicy::Deny); + p.cwd = "project".into(); + assert!(compile_args(&p, "sh", &[]).is_err()); + let mut p = policy(NetworkPolicy::Deny); + p.writable.push("../etc".into()); + assert!(compile_args(&p, "sh", &[]).is_err()); + } + + #[test] + fn refuses_to_bind_the_host_root_writable() { + let mut p = policy(NetworkPolicy::Deny); + p.writable = vec!["/".into()]; + assert!(compile_args(&p, "sh", &[]).is_err()); + } + + /// The decision → command path the transport uses: unconfined passes the + /// command through untouched, confined rewrites it to bwrap. + #[test] + fn confine_rewrites_the_command_only_when_confined() { + let unconfined = SandboxDecision::Unconfined(Unconfined::ExplicitNone); + let cmd = unconfined.confine("claude", &["-p".to_string()]).unwrap(); + assert_eq!(cmd.program, "claude"); + assert_eq!(cmd.args, vec!["-p"]); + + let confined = SandboxDecision::Confined { + kind: SandboxKind::Bwrap, + policy: Box::new(policy(NetworkPolicy::Allow)), + }; + let cmd = confined.confine("claude", &[]).unwrap(); + assert_eq!(cmd.program, "bwrap"); + assert_eq!(cmd.args.last().unwrap(), "claude"); + } + + /// A serve backend is `unsupported`, and an explicit request on one is a + /// hard error naming the choices — never a silent "none". + #[test] + fn serve_backends_cannot_be_asked_to_confine() { + let spec = SandboxSpec { + backend: "opencode", + support: crate::sandbox::SandboxSupport::Serve, + request: SandboxRequest::Auto, + network: NetworkPolicy::Backend, + cwd: Path::new("/tmp"), + extra_writable: &[], + }; + let decision = decide(&spec).unwrap(); + assert!(matches!( + decision, + SandboxDecision::Unconfined(Unconfined::ServeUnsupported(_)) + )); + + let spec = SandboxSpec { + request: SandboxRequest::Bwrap, + ..spec + }; + let err = decide(&spec).unwrap_err().to_string(); + assert!(err.contains("opencode"), "{err}"); + assert!(err.contains("sandbox = \"none\""), "{err}"); + } + + /// An explicit opt-out is honored everywhere, serve mode included. + #[test] + fn explicit_none_is_honored_on_any_backend() { + let spec = SandboxSpec { + backend: "opencode", + support: crate::sandbox::SandboxSupport::Serve, + request: SandboxRequest::None, + network: NetworkPolicy::Backend, + cwd: Path::new("/tmp"), + extra_writable: &[], + }; + assert_eq!( + decide(&spec).unwrap(), + SandboxDecision::Unconfined(Unconfined::ExplicitNone) + ); + } + + /// The probe answers without hanging, on a host with or without bwrap. + #[test] + fn probe_reports_a_status() { + let status = Bwrap.status(); + assert_eq!(status.kind, SandboxKind::Bwrap); + assert!(!status.detail.is_empty()); + if !status.installed { + assert!(!status.usable); + } + } +} diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs new file mode 100644 index 0000000..0231a24 --- /dev/null +++ b/src/sandbox/mod.rs @@ -0,0 +1,1003 @@ +//! OS-level sandbox drivers — one declarative policy, compiled into each +//! platform's native confinement form. +//! +//! The agent runs arbitrary shell commands, so without isolation a +//! hallucinated flag, an injected instruction, or an unlucky `rm` reaches +//! straight into the host: `~/.ssh`, cloud credentials, the network. This +//! module is the seam that puts an OS isolation layer between an agent CLI +//! and the machine (issue #33). +//! +//! The shape, cut for a reviewable first PR: +//! +//! - [`SandboxRequest`] is what a user declares — +//! `sandbox = "auto" | "bwrap" | "seatbelt" | "docker" | "none"` — at the +//! top level of the config (the default for every backend), per backend +//! (`[backends.X] sandbox = "..."`), or per session (`session.create`'s +//! `sandbox` param). +//! - [`SandboxSpec`] is a request resolved against one backend's process +//! model ([`SandboxSupport`]); [`decide`] turns it into a +//! [`SandboxDecision`]: either confined by a [`SandboxPolicy`], or +//! explicitly unconfined with the reason recorded ([`Unconfined`]) — never +//! "unconfined because nobody looked". +//! - A [`SandboxDriver`] compiles a policy into its native launcher argv +//! ([`SandboxCommand`]). [`bwrap`] is the only driver here; seatbelt and +//! docker are follow-ups to #33, and asking for one explicitly fails with a +//! message that says so instead of quietly running unconfined. +//! +//! Two rules the rest of the file is built around: +//! +//! 1. **An explicit request never degrades silently.** `sandbox = "bwrap"` on +//! a backend or host that cannot honor it is an error naming the cause and +//! the choices. Only `auto` — whose whole meaning is "use what this host +//! has" — may fall back, and it reports the fallback through `doctor`. +//! 2. **A serve-mode backend is `unsupported`, not `none`.** `opencode` and +//! `mimo` attach to a long-lived `serve` process instead of spawning a +//! child per session, so there is no spawn point to wrap. Recording that +//! as `none` would read as "isolation considered and declined" when it was +//! never possible. + +pub mod bwrap; + +use std::path::{Component, Path, PathBuf}; + +use anyhow::{Result, bail}; +use serde::Deserialize; + +// --------------------------------------------------------------------------- +// What the user asked for +// --------------------------------------------------------------------------- + +/// `sandbox = "..."` — the declaration. `Auto` is the zero-config default: +/// use the platform's driver when this host can run it, and say so in +/// `doctor` when it cannot. `None` is a deliberate opt-out, never a fallback. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum SandboxRequest { + #[default] + Auto, + Bwrap, + Seatbelt, + Docker, + None, +} + +impl SandboxRequest { + /// The wire/config spelling — also the parse accepted by + /// `session.create`'s `sandbox` param. + pub fn parse(raw: &str) -> Result { + Ok(match raw.trim().to_ascii_lowercase().as_str() { + "auto" => Self::Auto, + "bwrap" => Self::Bwrap, + "seatbelt" => Self::Seatbelt, + "docker" => Self::Docker, + "none" => Self::None, + other => bail!( + "unknown sandbox {other:?} — expected one of auto, bwrap, seatbelt, docker, none" + ), + }) + } +} + +impl std::fmt::Display for SandboxRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Auto => "auto", + Self::Bwrap => "bwrap", + Self::Seatbelt => "seatbelt", + Self::Docker => "docker", + Self::None => "none", + }) + } +} + +/// Egress policy inside the sandbox. `Backend` defers to what the backend +/// declares in the catalog — every agent CLI in `registry.rs` declares +/// `Allow`, because its entire job is calling its model API over HTTPS +/// (denying that at the bwrap layer leaves a CLI that cannot think). +/// `filename = "sandbox_network"`-style keys stay top-level strings; see +/// `config.rs`. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum NetworkPolicy { + /// Whatever the backend declares (agents: allow). + #[default] + Backend, + Allow, + Deny, +} + +/// How a backend launches its process — the thing that decides whether an +/// isolation layer can be applied at all. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SandboxSupport { + /// One stdio child per session (claude, codex, omp, pi, qwen, droid, + /// zcode): the spawn point is ours to wrap. + Spawn, + /// A long-lived server the backend attaches to (opencode, mimo `serve`). + /// Sessions are directories inside that server, so there is no + /// per-session child to confine yet. + Serve, +} + +// --------------------------------------------------------------------------- +// Drivers +// --------------------------------------------------------------------------- + +/// The isolation mechanisms the policy can be compiled into. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SandboxKind { + Bwrap, + Seatbelt, + Docker, +} + +impl std::fmt::Display for SandboxKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Bwrap => "bwrap", + Self::Seatbelt => "seatbelt", + Self::Docker => "docker", + }) + } +} + +/// Result of checking whether a driver can actually run here. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DriverStatus { + pub kind: SandboxKind, + /// The launcher binary was found on PATH. + pub installed: bool, + /// It ran a real confinement cycle (namespaces, mounts) successfully. + pub usable: bool, + /// One line for `doctor` and error messages: version, or the reason it + /// cannot run. + pub detail: String, +} + +impl DriverStatus { + fn unavailable(kind: SandboxKind, detail: impl Into) -> Self { + Self { + kind, + installed: false, + usable: false, + detail: detail.into(), + } + } +} + +/// One compiled launcher invocation: what to exec instead of the bare command. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SandboxCommand { + pub program: String, + pub args: Vec, +} + +/// The thin driver seam. A driver only has to (a) say whether it works here +/// and (b) turn a policy + command into the launcher invocation. Everything +/// host-shaped lives above it, so the policy stays one source of truth. +pub trait SandboxDriver: Send + Sync { + fn kind(&self) -> SandboxKind; + /// Cached by the implementation — `doctor` and every session start ask. + fn status(&self) -> DriverStatus; + fn wrap( + &self, + policy: &SandboxPolicy, + command: &str, + args: &[String], + ) -> Result; +} + +/// The driver for `kind`, when this release actually has one. +/// +/// Seatbelt and docker are follow-ups to #33: the request parses (so a +/// config written for a later release does not turn into a typo error) and +/// the failure names the gap, instead of pretending. +pub fn driver_for(kind: SandboxKind) -> Option> { + match kind { + SandboxKind::Bwrap => Some(Box::new(bwrap::Bwrap)), + SandboxKind::Seatbelt | SandboxKind::Docker => None, + } +} + +/// `auto`'s per-platform choice, which driver this OS can run at all. +fn platform_supports(kind: SandboxKind) -> bool { + match kind { + SandboxKind::Bwrap => cfg!(target_os = "linux"), + SandboxKind::Seatbelt => cfg!(target_os = "macos"), + // Container sockets exist on every platform with a Docker runtime. + SandboxKind::Docker => true, + } +} + +fn platform_of(kind: SandboxKind) -> &'static str { + match kind { + SandboxKind::Bwrap => "Linux", + SandboxKind::Seatbelt => "macOS", + SandboxKind::Docker => "a Docker host", + } +} + +/// The platform's `auto` choice, irrespective of whether this release +/// implements the driver (the caller reports that difference). +pub fn platform_default() -> Option { + #[cfg(target_os = "linux")] + { + Some(SandboxKind::Bwrap) + } + #[cfg(target_os = "macos")] + { + Some(SandboxKind::Seatbelt) + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + { + None + } +} + +// --------------------------------------------------------------------------- +// Policy +// --------------------------------------------------------------------------- + +/// What a driver needs to confine one session child. Paths are absolute and +/// symlink-resolved (see [`compile_policy`]) so the compiled mounts cannot be +/// steered by a `..` or a link somewhere else. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SandboxPolicy { + /// Backend id, for logs and error text. + pub backend: String, + /// The session's working directory — writable. + pub cwd: PathBuf, + /// Everything bound read-write: the workdir, granted roots, the + /// backend's own auth/state directory. + pub writable: Vec, + /// Host credential stores masked by an empty tmpfs. Compiled *after* + /// the writable binds, so a deny always wins over a wider allow. + pub denied: Vec, + /// Deny entries that are regular files (`.netrc`, `.git-credentials`): + /// a tmpfs cannot mount on a file, so these bind `/dev/null` over it. + pub denied_files: Vec, + /// Egress inside the sandbox, already resolved (`Allow`/`Deny`). + pub network: NetworkPolicy, +} + +impl SandboxPolicy { + /// The deny paths and how each is masked, in compile order. + pub fn deny_overlays(&self) -> impl Iterator { + self.denied + .iter() + .map(|p| (p.as_path(), DenyKind::EmptyDir)) + .chain( + self.denied_files + .iter() + .map(|p| (p.as_path(), DenyKind::NullFile)), + ) + } +} + +/// How a deny path is masked inside the sandbox. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DenyKind { + /// An empty tmpfs covers a directory (whether or not it exists). + EmptyDir, + /// `/dev/null` is bound over a regular file. + NullFile, +} + +// --------------------------------------------------------------------------- +// Decision +// --------------------------------------------------------------------------- + +/// Why a session runs *without* confinement. Every variant is a deliberate +/// reason, so `doctor` can show it instead of a blank "none". +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Unconfined { + /// `sandbox = "none"` — an explicit opt-out. + ExplicitNone, + /// `auto` found no driver this host (or this release) can use. + AutoNoDriver(String), + /// The backend has no per-session child to wrap (serve mode). + ServeUnsupported(String), +} + +impl Unconfined { + /// One line for `doctor` / logs. + pub fn describe(&self) -> String { + match self { + Self::ExplicitNone => "none — sandbox = \"none\" (explicit opt-out)".to_string(), + Self::AutoNoDriver(why) => format!("none — auto found no usable driver ({why})"), + Self::ServeUnsupported(why) => format!("unsupported — {why}"), + } + } +} + +/// The resolved isolation state of one session child. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SandboxDecision { + Confined { + kind: SandboxKind, + policy: Box, + }, + Unconfined(Unconfined), +} + +impl SandboxDecision { + /// Rewrite `(command, args)` into the driver's launcher invocation. + /// Unconfined decisions pass through untouched. + pub fn confine(&self, command: &str, args: &[String]) -> Result { + match self { + Self::Confined { kind, policy } => { + let Some(driver) = driver_for(*kind) else { + bail!("sandbox driver {kind} is not implemented in this release"); + }; + driver.wrap(policy, command, args) + } + Self::Unconfined(_) => Ok(SandboxCommand { + program: command.to_string(), + args: args.to_vec(), + }), + } + } + + pub fn is_confined(&self) -> bool { + matches!(self, Self::Confined { .. }) + } + + /// One line for `doctor` and logs: what this session child gets. + pub fn describe(&self) -> String { + match self { + Self::Confined { kind, policy } => format!("{kind}: {}", summary(policy)), + Self::Unconfined(reason) => reason.describe(), + } + } +} + +/// One backend session's sandbox inputs, before resolution. +pub struct SandboxSpec<'a> { + /// Backend id (routing name). + pub backend: &'a str, + /// How this backend launches (catalog). + pub support: SandboxSupport, + /// The declaration that won: session > backend config > global default. + pub request: SandboxRequest, + /// Egress for this backend: the global override, or the catalog default. + pub network: NetworkPolicy, + pub cwd: &'a Path, + /// Extra writable roots granted to the session (claude `--add-dir` + /// style grants). Safe to pass even when the backend ignores them. + pub extra_writable: &'a [PathBuf], +} + +/// Turn a spec into a decision. Errors are the "explicitly requested but +/// cannot be honored" cases and always name the cause and the choices. +pub fn decide(spec: &SandboxSpec<'_>) -> Result { + let kind = match (spec.support, spec.request) { + // An explicit opt-out is honored on any backend, spawn or serve. + (_, SandboxRequest::None) => { + return Ok(SandboxDecision::Unconfined(Unconfined::ExplicitNone)); + } + // The honest default for serve mode: there is no per-session child. + (SandboxSupport::Serve, SandboxRequest::Auto) => { + return Ok(SandboxDecision::Unconfined(Unconfined::ServeUnsupported( + serve_reason(spec.backend), + ))); + } + // The explicit failure: the user asked for isolation on a backend + // that cannot have it. Warning and continuing would silently run the + // agent exactly as unprotected as before. + (SandboxSupport::Serve, requested) => bail!( + "sandbox = \"{requested}\" cannot confine backend `{}`: {} To proceed, set \ + sandbox = \"none\" explicitly (accepting no isolation), or use a spawn-mode \ + backend (claude, codex, omp, pi, qwen, droid, zcode).", + spec.backend, + serve_reason(spec.backend) + ), + (SandboxSupport::Spawn, SandboxRequest::Auto) => match platform_default() { + Some(kind) => kind, + None => { + return Ok(SandboxDecision::Unconfined(Unconfined::AutoNoDriver( + "no sandbox driver for this platform yet (bwrap on Linux, seatbelt on macOS)" + .to_string(), + ))); + } + }, + (SandboxSupport::Spawn, explicit) => match explicit { + SandboxRequest::Bwrap => SandboxKind::Bwrap, + SandboxRequest::Seatbelt => SandboxKind::Seatbelt, + SandboxRequest::Docker => SandboxKind::Docker, + SandboxRequest::Auto | SandboxRequest::None => unreachable!("handled above"), + }, + }; + + // `auto` may fall back (that is what auto means) — an explicit request + // may not. Both start from the same platform and status checks. + let fallback_ok = spec.request == SandboxRequest::Auto; + if !platform_supports(kind) { + let why = format!("the {kind} driver runs on {}", platform_of(kind)); + if fallback_ok { + return Ok(SandboxDecision::Unconfined(Unconfined::AutoNoDriver(why))); + } + bail!( + "sandbox = \"{}\" is not supported on this platform: {why}. Use sandbox = \"auto\" \ + or \"none\".", + spec.request + ); + } + let Some(driver) = driver_for(kind) else { + let why = format!( + "the {kind} driver is not implemented in this release (seatbelt and docker follow in \ + later PRs on #33)" + ); + if fallback_ok { + return Ok(SandboxDecision::Unconfined(Unconfined::AutoNoDriver(why))); + } + bail!( + "sandbox = \"{}\" is not available: {why}. Use sandbox = \"auto\" or \"none\", or the \ + bwrap driver on Linux.", + spec.request + ); + }; + + let status = driver.status(); + if !status.usable { + let why = format!("{kind}: {}", status.detail); + if fallback_ok { + return Ok(SandboxDecision::Unconfined(Unconfined::AutoNoDriver(why))); + } + bail!( + "sandbox = \"{}\" is not usable here: {why}. Fix the driver (see `damond doctor`) or \ + set sandbox = \"none\" to run without isolation.", + spec.request + ); + } + + let policy = compile_policy(spec)?; + Ok(SandboxDecision::Confined { + kind, + policy: Box::new(policy), + }) +} + +fn serve_reason(backend: &str) -> String { + format!( + "`{backend}` attaches to a long-lived `{backend} serve` process that Damon probes or \ + spawns once, and sessions are directories inside it — there is no per-session child to \ + wrap." + ) +} + +// --------------------------------------------------------------------------- +// Policy compilation (filesystem-aware) +// --------------------------------------------------------------------------- + +/// Build the policy a driver compiles, from host paths. +/// +/// This is where the policy's promises are enforced rather than assumed: +/// +/// * every path is absolute (`..`-relative input is rejected, not resolved +/// against the daemon's cwd); +/// * every path is symlink-resolved, so a link inside the worktree cannot +/// turn a writable bind into a bind of `/etc` — the compiled mount names +/// the real target; +/// * the workdir cannot be `/` (that would make the read-only root a lie) and +/// cannot be, or sit inside, a credential path; +/// * credential stores are denied *after* the writable binds, so a granted +/// root that happens to contain one still sees it masked. +fn compile_policy(spec: &SandboxSpec<'_>) -> Result { + compile_policy_with(spec, credential_paths()) +} + +/// [`compile_policy`] with the deny set supplied — the tests drive credential +/// policy with their own paths instead of the machine's real `~/.ssh`. +fn compile_policy_with(spec: &SandboxSpec<'_>, denied: Vec) -> Result { + let cwd = resolve_existing(spec.cwd) + .map_err(|e| anyhow::anyhow!("sandbox workdir {} — {e}", spec.cwd.display()))?; + if cwd == Path::new("/") { + bail!("sandbox workdir cannot be `/`: the host root is read-only inside the sandbox"); + } + + // A tmpfs mounts on a directory only, and `.netrc`-shaped credentials + // are plain files: those are masked by binding /dev/null over them + // instead of by a tmpfs mount. + let (denied_files, denied): (Vec, Vec) = + denied + .into_iter() + .fold((Vec::new(), Vec::new()), |(mut files, mut dirs), path| { + match std::fs::symlink_metadata(&path) { + Ok(meta) if meta.file_type().is_file() => files.push(path), + _ => dirs.push(path), + } + (files, dirs) + }); + + let mut writable: Vec = vec![cwd.clone()]; + for root in spec.extra_writable { + // Granted roots are advisory: a missing one (deleted workspace) must + // not fail the session — it is simply not bound. + if let Ok(resolved) = resolve_existing(root) + && resolved != Path::new("/") + { + writable.push(resolved); + } + } + for dir in backend_state_dirs(spec.backend) { + // The CLI's own home: created when absent so a first run inside the + // sandbox can write its login instead of failing on a read-only + // parent. + if std::fs::create_dir_all(&dir).is_err() { + continue; + } + if let Ok(resolved) = resolve_existing(&dir) { + writable.push(resolved); + } + } + for file in backend_state_files(spec.backend) { + if let Ok(resolved) = resolve_existing(&file) { + writable.push(resolved); + } + } + + // Symlinks can make two spellings one path; keep the first of each. + writable.sort(); + writable.dedup(); + + // A writable path inside a credential store would be masked by its own + // deny overlay — the session could not work, so say why instead of + // handing the agent an empty directory. + if let Some((path, deny)) = writable + .iter() + .find_map(|w| denied.iter().map(|d| (w, d)).find(|(w, d)| is_within(w, d))) + { + bail!( + "refusing to bind {} writable: it is inside the credential path {} (which the sandbox \ + masks). Move the workspace, or set sandbox = \"none\" to run without isolation.", + path.display(), + deny.display() + ); + } + + // Nested binds are redundant — the parent already covers the child. + let mut roots: Vec = Vec::with_capacity(writable.len()); + for path in writable { + if !roots.iter().any(|r| is_within(&path, r)) { + roots.push(path); + } + } + + Ok(SandboxPolicy { + backend: spec.backend.to_string(), + cwd, + writable: roots, + denied, + denied_files, + network: spec.network, + }) +} + +/// Absolute + existing + symlink-resolved. +fn resolve_existing(path: &Path) -> Result { + if path.as_os_str().is_empty() { + bail!("path is empty"); + } + if !path.is_absolute() { + bail!( + "path is not absolute — relative paths are rejected because they would resolve \ + against whatever cwd the daemon happens to have" + ); + } + std::fs::canonicalize(path).map_err(|e| anyhow::anyhow!("{e}")) +} + +/// `child == parent` or `child` sits under `parent`. Both sides are expected +/// to be absolute and normalized already. +fn is_within(child: &Path, parent: &Path) -> bool { + child == parent || child.starts_with(parent) +} + +/// Collapse `.`/`..` without touching the filesystem — the fallback for deny +/// paths that do not exist on this host (a tmpfs mount point does not need to +/// exist). Traversal above `/` is clamped, so `/a/../..` becomes `/`. +pub fn lexical_normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => match out.components().next_back() { + // `..` with nothing to pop stays (a relative path that + // already climbs) unless it is clamped by a root. + None | Some(Component::ParentDir) => out.push(".."), + Some(Component::RootDir) | Some(Component::Prefix(_)) => {} + Some(Component::Normal(_)) => { + out.pop(); + } + Some(Component::CurDir) => unreachable!("CurDir is never pushed"), + }, + other => out.push(other.as_os_str()), + } + } + out +} + +// --------------------------------------------------------------------------- +// Host paths: what agents need, and what must never be reachable +// --------------------------------------------------------------------------- + +fn home_dir() -> Option { + directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf()) +} + +/// The pre-seeded deny set. Deliberately a fixed list, not config: a task must +/// not be able to widen it, so the only way to widen it is a code change here. +/// Every entry is masked by an empty tmpfs inside the sandbox. +pub fn credential_paths() -> Vec { + let Some(home) = home_dir() else { + return Vec::new(); + }; + [ + ".ssh", + ".aws", + ".gnupg", + ".netrc", + ".git-credentials", + ".npmrc", + ".pypirc", + ".docker", + ".kube", + ".password-store", + ".config/gh", + ".config/gcloud", + // Damon's own config holds the auth token and the discovery file. + ".config/damon", + ".damon", + ] + .into_iter() + .map(|rel| { + let path = home.join(rel); + // A symlinked credential dir (dotfile managers) is still that dir. + std::fs::canonicalize(&path).unwrap_or_else(|_| lexical_normalize(&path)) + }) + .collect() +} + +/// Env vars scrubbed inside the sandbox: the ssh-agent socket is a live +/// credential no filesystem mount can hide (a unix socket stays connectable +/// through a read-only bind), and agent CLIs never need it themselves. +pub const SCRUBBED_ENV: &[&str] = &["SSH_AUTH_SOCK"]; + +/// The agent CLIs' own auth/state directories, per backend — bound writable +/// so the CLI keeps its login across sessions. Env overrides win over the +/// `~/` default, mirroring `skills_hub::targets`. +pub fn backend_state_dirs(backend: &str) -> Vec { + let home = home_dir(); + let env_dir = |var: &str| { + std::env::var_os(var) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + }; + let under_home = |rel: &str| home.as_ref().map(|h| h.join(rel)); + let dirs: Vec> = match backend { + "claude" => vec![env_dir("CLAUDE_CONFIG_DIR").or_else(|| under_home(".claude"))], + "codex" => vec![env_dir("CODEX_HOME").or_else(|| under_home(".codex"))], + "qwen" => vec![env_dir("QWEN_HOME").or_else(|| under_home(".qwen"))], + "droid" => vec![under_home(".factory")], + "zcode" => vec![under_home(".zcode")], + // omp and pi keep their agent state under one root each; the env + // overrides name a subdirectory of it. + "omp" => vec![ + env_dir("OMP_CODING_AGENT_DIR") + .or_else(|| env_dir("PI_CODING_AGENT_DIR")) + .or_else(|| under_home(".omp")), + ], + "pi" => vec![env_dir("PI_CODING_AGENT_DIR").or_else(|| under_home(".pi"))], + // Serve-mode backends have no driver here, so no state to bind yet. + _ => Vec::new(), + }; + dirs.into_iter().flatten().collect() +} + +/// State that is a single file rather than a directory (bound only when it +/// exists — a missing file is not something to create). +pub fn backend_state_files(backend: &str) -> Vec { + let Some(home) = home_dir() else { + return Vec::new(); + }; + match backend { + // Claude Code keeps its credentials and project index in + // ~/.claude/.claude.json. + "claude" => vec![home.join(".claude.json")], + _ => Vec::new(), + } +} + +/// Every writable path a decision binds, for `doctor` and logs. +pub fn summary(policy: &SandboxPolicy) -> String { + let network = match policy.network { + NetworkPolicy::Allow => "network allow", + NetworkPolicy::Deny => "network deny", + NetworkPolicy::Backend => "network backend", + }; + let mut paths: Vec = policy + .writable + .iter() + .map(|p| p.display().to_string()) + .collect(); + if paths.len() > 4 { + let extra = paths.len() - 3; + paths.truncate(3); + paths.push(format!("+{extra} more")); + } + format!("{network}; writable {}", paths.join(", ")) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A scratch tree that cleans itself up: `/damon-sandbox-/`. + struct Scratch(PathBuf); + + impl Scratch { + fn new(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("damon-sandbox-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn path(&self) -> &Path { + &self.0 + } + + fn dir(&self, rel: &str) -> PathBuf { + let p = self.0.join(rel); + std::fs::create_dir_all(&p).unwrap(); + p + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn spec<'a>(backend: &'a str, cwd: &'a Path, extra: &'a [PathBuf]) -> SandboxSpec<'a> { + SandboxSpec { + backend, + support: SandboxSupport::Spawn, + request: SandboxRequest::None, + network: NetworkPolicy::Deny, + cwd, + extra_writable: extra, + } + } + + #[test] + fn parses_every_documented_spelling() { + for (raw, want) in [ + ("auto", SandboxRequest::Auto), + ("bwrap", SandboxRequest::Bwrap), + ("seatbelt", SandboxRequest::Seatbelt), + ("docker", SandboxRequest::Docker), + ("none", SandboxRequest::None), + (" BWRAP ", SandboxRequest::Bwrap), + ] { + assert_eq!(SandboxRequest::parse(raw).unwrap(), want, "{raw}"); + } + let err = SandboxRequest::parse("bubblewrap").unwrap_err().to_string(); + assert!(err.contains("auto, bwrap, seatbelt, docker, none"), "{err}"); + } + + /// `..` is collapsed the way a shell would, and cannot climb above `/`. + #[test] + fn lexical_normalize_collapses_dot_dot() { + assert_eq!(lexical_normalize(Path::new("/a/b/../c")), Path::new("/a/c")); + assert_eq!(lexical_normalize(Path::new("/a/./b")), Path::new("/a/b")); + assert_eq!(lexical_normalize(Path::new("/a/../..")), Path::new("/")); + assert_eq!(lexical_normalize(Path::new("/../etc")), Path::new("/etc")); + assert_eq!(lexical_normalize(Path::new("../x")), Path::new("../x")); + } + + /// A relative workdir would silently resolve against the daemon's own + /// cwd — rejected, not resolved. + #[test] + fn a_relative_workdir_is_rejected() { + let scratch = Scratch::new("relative"); + let s = spec("", Path::new("worktree"), &[]); + let err = compile_policy_with(&s, Vec::new()).unwrap_err().to_string(); + assert!(err.contains("not absolute"), "{err}"); + drop(scratch); + } + + /// `..` in the workdir is resolved before the promise "root is read-only" + /// is made: `/tmp/x/../..` is `/`, and `/` cannot be bound writable. + #[test] + fn a_workdir_that_traverses_to_the_host_root_is_rejected() { + let scratch = Scratch::new("traverse"); + let cwd = scratch.dir("a"); + let climb = cwd.join("..").join("..").join("..").join(".."); + // `/` on the host: the workdir resolves to the root itself. + let root = Path::new("/"); + let s = spec("", root, &[]); + let err = compile_policy_with(&s, Vec::new()).unwrap_err().to_string(); + assert!(err.contains("cannot be `/`"), "{err}"); + // The climb itself canonicalizes to `/` too. + let s = spec("", &climb, &[]); + assert!(compile_policy_with(&s, Vec::new()).is_err()); + } + + /// A symlinked writable root is bound at its target: the name cannot + /// carry the mount somewhere the policy did not intend. + #[test] + fn a_symlinked_writable_root_binds_its_target() { + let scratch = Scratch::new("symlink"); + let work = scratch.dir("work"); + let target = scratch.dir("target"); + let link = scratch.path().join("link"); + #[cfg(unix)] + std::os::unix::fs::symlink(&target, &link).unwrap(); + let extra = vec![link.clone()]; + let s = spec("", &work, &extra); + let policy = compile_policy_with(&s, Vec::new()).unwrap(); + let want = std::fs::canonicalize(&target).unwrap(); + assert!(policy.writable.contains(&want), "{:?}", policy.writable); + assert!( + !policy.writable.contains(&link), + "the link itself is never bound" + ); + } + + /// A link pointing at `/` must not become a writable root. + #[test] + fn a_symlink_to_the_host_root_is_not_writable() { + let scratch = Scratch::new("rootlink"); + let work = scratch.dir("work"); + let link = scratch.path().join("rootlink"); + #[cfg(unix)] + std::os::unix::fs::symlink("/", &link).unwrap(); + let extra = vec![link]; + let s = spec("", &work, &extra); + let policy = compile_policy_with(&s, Vec::new()).unwrap(); + assert!(!policy.writable.contains(&PathBuf::from("/"))); + } + + /// A writable root that *contains* a credential store keeps the store + /// denied: the deny list is compiled after the binds (see the bwrap + /// golden test), and the plan stays valid. + #[test] + fn a_wider_writable_root_does_not_widen_the_credential_deny() { + let scratch = Scratch::new("wider"); + let work = scratch.dir("work"); + let home = scratch.dir("home"); + let ssh = home.join(".ssh"); + std::fs::create_dir_all(&ssh).unwrap(); + let extra = vec![home.clone()]; + let s = spec("", &work, &extra); + let policy = compile_policy_with(&s, vec![std::fs::canonicalize(&ssh).unwrap()]).unwrap(); + assert!( + policy + .writable + .contains(&std::fs::canonicalize(&home).unwrap()) + ); + assert!( + policy + .denied + .contains(&std::fs::canonicalize(&ssh).unwrap()) + ); + } + + /// A workdir that *is* inside a credential store cannot be served — the + /// deny overlay would empty it. Refused with both paths named instead of + /// handing the agent an empty directory. + #[test] + fn a_workdir_inside_a_credential_store_is_refused() { + let scratch = Scratch::new("inside"); + let ssh = scratch.dir("home/.ssh"); + let s = spec("", &ssh, &[]); + let err = compile_policy_with(&s, vec![std::fs::canonicalize(&ssh).unwrap()]) + .unwrap_err() + .to_string(); + assert!(err.contains("credential path"), "{err}"); + assert!(err.contains("sandbox = \"none\""), "{err}"); + } + + /// Nested writable roots collapse to the outer one — one bind, no + /// duplicate mount of the same subtree. + #[test] + fn nested_writable_roots_collapse() { + let scratch = Scratch::new("nested"); + let outer = scratch.dir("outer"); + let inner = scratch.dir("outer/inner"); + let extra = vec![inner]; + let s = spec("", &outer, &extra); + let policy = compile_policy_with(&s, Vec::new()).unwrap(); + assert_eq!( + policy.writable, + vec![std::fs::canonicalize(&outer).unwrap()] + ); + } + + /// A missing granted root (deleted workspace) is skipped, not fatal. + #[test] + fn a_missing_granted_root_is_skipped() { + let scratch = Scratch::new("missing"); + let work = scratch.dir("work"); + let gone = scratch.path().join("gone"); + let extra = vec![gone]; + let s = spec("", &work, &extra); + let policy = compile_policy_with(&s, Vec::new()).unwrap(); + assert_eq!(policy.writable.len(), 1); + } + + #[test] + fn credential_paths_are_absolute_and_seeded() { + for path in credential_paths() { + assert!(path.is_absolute(), "{}", path.display()); + } + // The set is code, not config: widening it is a code change. + let names: Vec = credential_paths() + .iter() + .map(|p| { + p.file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned() + }) + .collect(); + for want in [".ssh", ".aws", ".gnupg"] { + assert!( + names.iter().any(|n| n == want), + "{want} missing from {names:?}" + ); + } + } + + /// `auto` may fall back; an explicit request may not. This is the rule the + /// whole module exists to make reviewable, so it is asserted directly. + #[test] + fn auto_falls_back_but_an_explicit_request_never_does() { + let work = Scratch::new("decide"); + let cwd = work.dir("work"); + let auto = SandboxSpec { + backend: "claude", + support: SandboxSupport::Spawn, + request: SandboxRequest::Auto, + network: NetworkPolicy::Allow, + cwd: &cwd, + extra_writable: &[], + }; + // Whatever this host can do, auto answers without an error. + let decision = decide(&auto).unwrap(); + assert!(decision.is_confined() == decision.is_confined()); + + let explicit = SandboxSpec { + request: SandboxRequest::Seatbelt, + ..auto + }; + match decide(&explicit) { + // On macOS the seatbelt request is refused because this release + // has no driver; elsewhere it is refused as the wrong platform. + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("not implemented") + || msg.contains("not supported on this platform"), + "{msg}" + ); + } + // A host that can run seatbelt (a later release) confines. + Ok(d) => assert!(d.is_confined()), + } + } + + #[test] + fn explicit_none_never_touches_the_host() { + let work = Scratch::new("none"); + let cwd = work.dir("work"); + let s = spec("claude", &cwd, &[]); + assert_eq!( + decide(&s).unwrap(), + SandboxDecision::Unconfined(Unconfined::ExplicitNone) + ); + } +} diff --git a/src/session.rs b/src/session.rs index 9e6f94f..1b5cfef 100644 --- a/src/session.rs +++ b/src/session.rs @@ -504,7 +504,7 @@ impl SessionManager { cfg: &crate::config::Config, checkpoint: Option, ) -> Self { - let resolved = crate::backend::registry::resolve_backends(&cfg.backends); + let resolved = crate::backend::registry::resolve_from_config(cfg); let mut clients = HashMap::new(); for r in resolved { if !r.detected { @@ -560,7 +560,7 @@ impl SessionManager { /// their existing backend objects; only new creates/resumes see the /// refreshed clients. pub fn refresh(&self, cfg: &crate::config::Config) { - let resolved = crate::backend::registry::resolve_backends(&cfg.backends); + let resolved = crate::backend::registry::resolve_from_config(cfg); let mut clients = HashMap::new(); for r in resolved { if !r.detected { diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 320002a..1a4f8f6 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -26,6 +26,11 @@ pub fn mock_config(auth_token: Option<&str>) -> Config { tls_key: None, backends: Default::default(), default_backend: Some("mock".to_string()), + // Sandboxing off in tests: the in-process mock backend spawns no + // child, and the explicit `none` keeps every test's launch line + // independent of whether the CI host has bwrap installed. + sandbox: damon_core::sandbox::SandboxRequest::None, + sandbox_network: damon_core::sandbox::NetworkPolicy::Backend, relay: None, permission_timeout_secs: None, session_retention_days: None, diff --git a/tests/rpc.rs b/tests/rpc.rs index a59483e..58160ca 100644 --- a/tests/rpc.rs +++ b/tests/rpc.rs @@ -97,6 +97,43 @@ async fn read_reply(ws: &mut Ws, id: u64) -> Value { } } +/// The `sandbox` param is validated at the door: a misspelled mode is a +/// `-32602`, not a session that silently runs unconfined under a name the +/// user believes is isolation. A valid value is accepted (the in-process +/// mock backend spawns nothing, so the policy itself is not exercised +/// here — the bwrap tests in `sandbox_bwrap.rs` and the policy unit tests +/// are). +#[tokio::test] +async fn session_create_validates_the_sandbox_param() { + let (_state, _store, addr) = serve(test_config(None)).await; + let (mut ws, _) = ws_connect(&format!("ws://{addr}/ws")).await; + + rpc_send( + &mut ws, + json!({"id":1,"method":"session.create", + "params":{"cwd":"/tmp","sandbox":"bubblewrap"}}), + ) + .await; + let bad = read_reply(&mut ws, 1).await; + assert_eq!(bad["error"]["code"], -32602, "{bad}"); + let msg = bad["error"]["message"].as_str().unwrap_or_default(); + assert!(msg.contains("auto, bwrap, seatbelt, docker, none"), "{msg}"); + + for (id, mode) in [(2, "none"), (3, "auto")] { + rpc_send( + &mut ws, + json!({"id":id,"method":"session.create", + "params":{"cwd":"/tmp","sandbox":mode}}), + ) + .await; + let ok = read_reply(&mut ws, id).await; + assert!( + ok["result"]["sessionId"].is_string(), + "sandbox={mode} must create: {ok}" + ); + } +} + /// A turn parked on a hung backend unwinds on turn.cancel — the /// turn.start request resolves with stopReason "canceled", the busy /// flag clears, and session.delete then removes the row. A hung diff --git a/tests/sandbox_bwrap.rs b/tests/sandbox_bwrap.rs new file mode 100644 index 0000000..cf0d722 --- /dev/null +++ b/tests/sandbox_bwrap.rs @@ -0,0 +1,305 @@ +//! bwrap driver, end to end: the "fake backend" is a plain shell command, so +//! what is exercised is the compiled sandbox itself — the mount layout, the +//! deny overlays, and the namespace flags — not an agent CLI. +//! +//! Every test here guards itself: a host without bubblewrap, or with +//! unprivileged user namespaces disabled (Debian's +//! `kernel.unprivileged_userns_clone=0`, Ubuntu 24.04's AppArmor policy), +//! cannot run any of it, and the test says why and returns instead of +//! failing. CI installs bubblewrap on the Linux leg so the guards normally +//! pass there; the compiler unit tests in `src/sandbox/` run everywhere and +//! are what pins the policy shape. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Duration; + +use damon_core::sandbox::{ + self, NetworkPolicy, SandboxCommand, SandboxDecision, SandboxKind, SandboxPolicy, +}; + +/// A scratch tree under the system temp dir that cleans itself up. +struct Scratch(PathBuf); + +impl Scratch { + fn new(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("damon-sandbox-it-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn path(&self) -> &Path { + &self.0 + } + + fn dir(&self, rel: &str) -> PathBuf { + let p = self.0.join(rel); + std::fs::create_dir_all(&p).unwrap(); + std::fs::canonicalize(p).unwrap() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// True when this host can run the driver at all; prints the reason when it +/// cannot, so a skipped test is visible in the log rather than silent. +fn bwrap_usable() -> bool { + match sandbox::driver_for(SandboxKind::Bwrap) { + Some(driver) => { + let status = driver.status(); + if !status.usable { + eprintln!("skipping: {}", status.detail); + } + status.usable + } + None => { + eprintln!("skipping: no bwrap driver in this build"); + false + } + } +} + +fn policy( + work: &Path, + writable: Vec, + denied: Vec, + net: NetworkPolicy, +) -> SandboxPolicy { + SandboxPolicy { + backend: "fake".to_string(), + cwd: work.to_path_buf(), + writable, + denied, + denied_files: Vec::new(), + network: net, + } +} + +/// Compile `sh -c