From 9ad8f28a30f283c51e993386cd1d8729da1dae9f 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 01:25:07 +0900 Subject: [PATCH 1/3] =?UTF-8?q?fix(sandbox):=20address=20review=20findings?= =?UTF-8?q?=20=E2=80=94=20launch,=20resume,=20and=20param=20honesty?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of the first cut surfaced four ways the policy could break a session or be quietly weaker than it claims: - A credential path that does not exist was masked with a tmpfs. bwrap has to create that mount point, and its parent is inside the read-only root, so the whole launch failed on any home without `~/.aws` (and the probe did not catch it). Only existing paths are masked now — a path that is absent has nothing to leak, and the sandbox cannot create it either. The probe also mounts the recipe's `/tmp` tmpfs, so this class of setup failure shows up in `doctor` instead of at the first turn. - The Codex/OMP catalog probe spawns with cwd `/`, which a policy refuses as a writable root — the model picker would have come back empty under `auto`. Those probes run no turn, so they are explicitly unconfined (same rule as the discovery probe). - `[backends.X].env` state overrides (`CODEX_HOME = …`) were not seen by the state-directory resolution, which read the daemon's env: the CLI would have been confined out of its own state dir. The launch env now wins, in the policy and in the process. - `session.create`'s `sandbox` was not persisted, so a session created with an explicit `bwrap` came back unconfined on resume/restart. The mode rides the session row (`sessions.sandbox`) and is re-applied on every reattach. A present but non-string `sandbox` now answers `-32602` instead of being dropped by the optional-field rule. Also: an unsupported sandbox request is a typed error, so the wire answers `not_supported` rather than a generic internal error; the probe answer is cached for 30s instead of forever (a driver installed while the daemon runs must take effect); protocol docs gain the param. Refs #33 Signed-off-by: 정인권 --- CHANGELOG.md | 18 +++++-- docs/protocol-v2.ko.md | 2 +- docs/protocol-v2.md | 2 +- src/backend/codex.rs | 5 ++ src/backend/omp.rs | 3 ++ src/backend/registry.rs | 1 + src/rpc.rs | 16 +++++++ src/rpc/session.rs | 22 +++++++++ src/sandbox/bwrap.rs | 46 +++++++++++++++--- src/sandbox/mod.rs | 103 +++++++++++++++++++++++++++++++++------- src/store.rs | 41 +++++++++++++++- tests/rpc.rs | 14 +++++- 12 files changed, 243 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f93a52..8b893d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,11 @@ - `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. + param, stored with the session so resume re-applies it rather than + falling back to a possibly looser default). `auto` (default) means this + platform's driver when the host can run it; `none` is an explicit + opt-out. The param is strictly typed — a present non-string answers + `-32602` instead of being dropped. - 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 @@ -26,12 +29,19 @@ `--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). +- Only credential paths that exist are masked: bwrap would have to create + a mount point under the read-only root otherwise, which fails the whole + launch (a path that does not exist has nothing to leak, and the sandbox + cannot create it either). - 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. + a usable bwrap (no binary, or unprivileged user namespaces disabled). +- Known gaps, left for their own decisions: the sandboxed agent can still + reach the daemon's loopback API (RPCs run unconfined), and git writes in + a linked worktree or a repo subdirectory (the git dir lives outside the + workdir) are not granted. - 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 diff --git a/docs/protocol-v2.ko.md b/docs/protocol-v2.ko.md index e6f0c10..0d32d64 100644 --- a/docs/protocol-v2.ko.md +++ b/docs/protocol-v2.ko.md @@ -70,7 +70,7 @@ WebSocket(`GET /ws`) 또는 릴레이 터널 위의 JSON 메시지. 하나의 | `backend.update_plan` | `{backend}` | `{backend, action: "install"\|"update", kind, command[], manualCommand, canRun, blockers[], platform}` — `backend.update`가 실행할 정확한 argv와 복사-붙여넣기 대안; 부수 효과 없음 | | `backend.update` | `{backend, creationId?}` | `{creationId, ok: true, version?}` — 플랜을 실행(npm 글로벌 설치 또는 CLI 공식 인스톨러); 진행은 요청 연결로 `{"event":"backend.update_progress","creationId","data":{phase, line?, exitOk?}}` 스트리밍(줄당 캡); 검증된 채널이 없으면 `-32602`(플랜 blockers 참조), 실패/420s 타임아웃은 `-32000`(출력 꼬리가 메시지에 동승) | | `backend.update_cancel` | `{creationId}` | `{cancelled: bool}` — 해당 id의 실행 중 런이 없으면 false | -| `session.create` | `{backend?, cwd?, model?, mode?, mcpServers?, allowedTools?, projectId?, persona?}` — 프로젝트가 세션의 범위를 정한다: 루트가 cwd 기본값이 되고 기본값들이 미지정 파라미터를 채운다(명시 값 항상 우선); `persona`는 `bot.list`의 봇 id — SOUL/AGENTS 블록이 매 턴 앞에 실리며 세션 수명 동안 고정, resume 시 파일에서 재해석(모르는 id는 `-32602`); `allowedTools`는 실행 시 강제할 수 있는 백엔드용 세션별 도구 허용 목록(claude: `--allowedTools`) | `{sessionId, backend, persona?, replayed, cursor}` | +| `session.create` | `{backend?, cwd?, model?, mode?, mcpServers?, allowedTools?, projectId?, persona?, sandbox?}` — 프로젝트가 세션의 범위를 정한다: 루트가 cwd 기본값이 되고 기본값들이 미지정 파라미터를 채운다(명시 값 항상 우선); `persona`는 `bot.list`의 봇 id — SOUL/AGENTS 블록이 매 턴 앞에 실리며 세션 수명 동안 고정, resume 시 파일에서 재해석(모르는 id는 `-32602`); `allowedTools`는 실행 시 강제할 수 있는 백엔드용 세션별 도구 허용 목록(claude: `--allowedTools`); `sandbox`는 `auto`/`bwrap`/`seatbelt`/`docker`/`none` — 생략하면 그 백엔드에 설정된 샌드박스를 따르고, 명시한 값은 세션에 저장되어 resume 때 그대로 다시 적용되며, 이 백엔드나 호스트가 감당할 수 없는 값은 격리 없이 도는 대신 create를 실패시킨다(`-32602`) | `{sessionId, backend, persona?, replayed, cursor}` | | `session.resume` | `{sessionId}` — 또는 네이티브 세션 임포트는 `{handle:{provider,native_handle}, cwd?, title?}` | `{sessionId, backend, replayed, cursor}` | | `session.messages` | `{sessionId, limit?, offset?}` | `{messages: [{id, session_id, role, ts, data}]}` | | `session.export` | `{sessionId}` | `{session: {sessionId, createdAt, backend, title, tags, cwd}, messages: [{id, role, ts, data}], usage: {contextUsed, contextSize, costUsd, turns}}` | diff --git a/docs/protocol-v2.md b/docs/protocol-v2.md index 6805d99..e779e04 100644 --- a/docs/protocol-v2.md +++ b/docs/protocol-v2.md @@ -73,7 +73,7 @@ unchanged, so string-matching clients keep working. | `backend.update_plan` | `{backend}` | `{backend, action: "install"\|"update", kind, command[], manualCommand, canRun, blockers[], platform}` — the exact argv `backend.update` runs plus the copy-paste fallback; no side effects | | `backend.update` | `{backend, creationId?}` | `{creationId, ok: true, version?}` — runs the plan (npm global install or the CLI's official installer); progress streams to the requesting connection as `{"event":"backend.update_progress","creationId","data":{phase, line?, exitOk?}}` with per-line caps; `-32602` when the backend has no verified channel (see the plan's blockers), `-32000` on failure or the 420s timeout (output tail rides the message) | | `backend.update_cancel` | `{creationId}` | `{cancelled: bool}` — false when no live run holds the id | -| `session.create` | `{backend?, cwd?, model?, mode?, mcpServers?, allowedTools?, projectId?, persona?}` — the project scopes the session: its root becomes the cwd default and its defaults fill unset params (explicit always wins); `persona` names a bot from `bot.list` whose SOUL/AGENTS block rides in front of every turn, bound for the session's life and re-resolved from the files on resume (`-32602` unknown persona); `allowedTools` is a per-session tool allowlist for backends that enforce one at launch (claude: `--allowedTools`) | `{sessionId, backend, persona?, replayed, cursor}` | +| `session.create` | `{backend?, cwd?, model?, mode?, mcpServers?, allowedTools?, projectId?, persona?, sandbox?}` — the project scopes the session: its root becomes the cwd default and its defaults fill unset params (explicit always wins); `persona` names a bot from `bot.list` whose SOUL/AGENTS block rides in front of every turn, bound for the session's life and re-resolved from the files on resume (`-32602` unknown persona); `allowedTools` is a per-session tool allowlist for backends that enforce one at launch (claude: `--allowedTools`); `sandbox` is `auto` / `bwrap` / `seatbelt` / `docker` / `none` — unset inherits the backend's configured sandbox, an explicit value is stored with the session and re-applied on resume, and one this backend or host cannot honor fails the create (`-32602`) instead of running unconfined | `{sessionId, backend, persona?, replayed, cursor}` | | `session.resume` | `{sessionId}` — or `{handle:{provider,native_handle}, cwd?, title?}` to import a native session | `{sessionId, backend, replayed, cursor}` | | `session.messages` | `{sessionId, limit?, offset?}` | `{messages: [{id, session_id, role, ts, data}]}` | | `session.export` | `{sessionId}` | `{session: {sessionId, createdAt, backend, title, tags, cwd}, messages: [{id, role, ts, data}], usage: {contextUsed, contextSize, costUsd, turns}}` | diff --git a/src/backend/codex.rs b/src/backend/codex.rs index abf6cfe..00c5f71 100644 --- a/src/backend/codex.rs +++ b/src/backend/codex.rs @@ -82,6 +82,11 @@ impl AgentClient for CodexClient { &self.resolved, SessionConfig { cwd: cwd.unwrap_or_else(|| Path::new("/")).to_path_buf(), + // Catalog introspection: this probe answers `model/list` and + // never starts a turn, so it is not one of the spawns the + // sandbox policy exists to confine — and its cwd is `/`, + // which a policy refuses as a writable root. + sandbox: Some(crate::sandbox::SandboxRequest::None), ..Default::default() }, ) diff --git a/src/backend/omp.rs b/src/backend/omp.rs index 8512b20..cd2a225 100644 --- a/src/backend/omp.rs +++ b/src/backend/omp.rs @@ -154,6 +154,9 @@ impl AgentClient for OmpClient { self.profile, SessionConfig { cwd: cwd.unwrap_or_else(|| Path::new("/")).to_path_buf(), + // Catalog introspection only — see the same note in + // codex.rs: the probe lists models and starts no turn. + sandbox: Some(crate::sandbox::SandboxRequest::None), ..Default::default() }, ) diff --git a/src/backend/registry.rs b/src/backend/registry.rs index c16c2be..9df4dff 100644 --- a/src/backend/registry.rs +++ b/src/backend/registry.rs @@ -312,6 +312,7 @@ impl ResolvedBackend { network: self.sandbox_network, cwd: &session.cwd, extra_writable: &session.granted_roots, + launch_env: &self.env, }; crate::sandbox::decide(&spec) } diff --git a/src/rpc.rs b/src/rpc.rs index c0cf82b..5c15835 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -265,6 +265,14 @@ fn error_payload(e: &anyhow::Error) -> (i64, String, Option) { { return (error_code::ASK_NOT_FOUND, e.to_string(), None); } + // A backend or host that cannot honor a sandbox request is a + // not-supported surface, not a daemon bug. + if e.chain().any(|c| { + c.downcast_ref::() + .is_some() + }) { + return (error_code::NOT_SUPPORTED, e.to_string(), None); + } (error_code::INTERNAL_ERROR, e.to_string(), None) } @@ -2941,6 +2949,14 @@ async fn reattach(state: &Arc, conn: &Arc, id: &str) -> Result Result { let req = Create::parse(params)?; + // A `sandbox` that is present but not a string must fail here. The field + // table drops ill-typed *optional* fields — the wire-compatible rule for + // every other param — but dropping this one would answer a client that + // asked to be confined with a session it never asked for. + if let Some(raw) = params.get("sandbox") + && !raw.is_null() + && !raw.is_string() + { + return Err(RpcError::error( + error_code::INVALID_PARAMS, + "sandbox must be a string — auto|bwrap|seatbelt|docker|none", + )); + } let mut cfg = req.config()?; let mut backend = req.backend.clone(); // A project scopes the session: its root becomes the cwd default and @@ -528,6 +541,15 @@ pub(super) async fn create( .store .create_session(&ms.id, &cfg.cwd.to_string_lossy(), Some(&ms.provider)) .await?; + // An explicit per-session sandbox rides the row: resume/restart must + // re-apply the same confinement instead of falling back to the + // backend's default (which may be looser). + if let Some(mode) = cfg.sandbox { + let _ = state + .store + .set_session_sandbox(&ms.id, Some(&mode.to_string())) + .await; + } if let Some(pid) = &project { let _ = state.store.set_session_project(&ms.id, Some(pid)).await; } diff --git a/src/sandbox/bwrap.rs b/src/sandbox/bwrap.rs index b4b103e..ebd55fd 100644 --- a/src/sandbox/bwrap.rs +++ b/src/sandbox/bwrap.rs @@ -20,7 +20,7 @@ use std::path::Path; use std::process::{Command, Stdio}; -use std::sync::OnceLock; +use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; use anyhow::{Result, bail}; @@ -35,6 +35,10 @@ use super::{ /// `doctor` or the first session. const PROBE_TIMEOUT: Duration = Duration::from_secs(10); +/// How long a probe answer is trusted before the next `auto` resolution +/// re-checks (see `Bwrap::status`). +const STATUS_TTL: Duration = Duration::from_secs(30); + pub struct Bwrap; impl SandboxDriver for Bwrap { @@ -43,8 +47,23 @@ impl SandboxDriver for Bwrap { } fn status(&self) -> DriverStatus { - static STATUS: OnceLock = OnceLock::new(); - STATUS.get_or_init(probe).clone() + // Re-probed after a short while: `auto` reads this on every session + // start, and a driver installed (or a sysctl flipped) while the + // daemon runs must take effect without a restart — a forever-cached + // "not usable" would leave a resident daemon unconfined with no way + // to tell. The probe is one short-lived process, so the window keeps + // session starts cheap without pinning the answer. + static CACHE: OnceLock>> = OnceLock::new(); + let cache = CACHE.get_or_init(|| Mutex::new(None)); + let mut guard = cache.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((at, status)) = guard.as_ref() + && at.elapsed() < STATUS_TTL + { + return status.clone(); + } + let status = probe(); + *guard = Some((Instant::now(), status.clone())); + status } fn wrap( @@ -184,6 +203,10 @@ fn probe() -> DriverStatus { "/dev", "--proc", "/proc", + // The recipe's own scratch mount, so a host where /tmp cannot be + // masked fails here rather than at the first session. + "--tmpfs", + "/tmp", "--unshare-all", "--die-with-parent", "--new-session", @@ -475,6 +498,7 @@ mod tests { network: NetworkPolicy::Backend, cwd: Path::new("/tmp"), extra_writable: &[], + launch_env: &[], }; let decision = decide(&spec).unwrap(); assert!(matches!( @@ -486,9 +510,18 @@ mod tests { request: SandboxRequest::Bwrap, ..spec }; - let err = decide(&spec).unwrap_err().to_string(); - assert!(err.contains("opencode"), "{err}"); - assert!(err.contains("sandbox = \"none\""), "{err}"); + let err = decide(&spec).unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("opencode"), "{msg}"); + assert!(msg.contains("sandbox = \"none\""), "{msg}"); + // Typed, so the wire answers `not_supported` rather than a daemon + // bug (see rpc::error_payload). + assert!( + err.chain().any(|c| c + .downcast_ref::() + .is_some()), + "the refusal must stay typed: {msg}" + ); } /// An explicit opt-out is honored everywhere, serve mode included. @@ -501,6 +534,7 @@ mod tests { network: NetworkPolicy::Backend, cwd: Path::new("/tmp"), extra_writable: &[], + launch_env: &[], }; assert_eq!( decide(&spec).unwrap(), diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index 1e26837..1ae0763 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -351,6 +351,15 @@ impl SandboxDecision { } } +/// A sandbox request the backend or host cannot honor. +/// +/// Typed so the wire can answer `not_supported` instead of a generic +/// internal error: a client asking a serve-mode backend for `bwrap` is +/// making a request the backend does not support, not hitting a daemon bug. +#[derive(Debug, thiserror::Error)] +#[error("{0}")] +pub struct SandboxUnsupported(pub String); + /// One backend session's sandbox inputs, before resolution. pub struct SandboxSpec<'a> { /// Backend id (routing name). @@ -365,6 +374,10 @@ pub struct SandboxSpec<'a> { /// 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], + /// The environment the child will run with (`[backends.X].env`). + /// State-directory overrides are resolved against it, not the daemon's + /// own environment — they are frequently not the same. + pub launch_env: &'a [(String, String)], } /// Turn a spec into a decision. Errors are the "explicitly requested but @@ -384,13 +397,16 @@ pub fn decide(spec: &SandboxSpec<'_>) -> Result { // 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::Serve, requested) => { + return Err(SandboxUnsupported(format!( + "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) + )) + .into()); + } (SandboxSupport::Spawn, SandboxRequest::Auto) => match platform_default() { Some(kind) => kind, None => { @@ -495,16 +511,23 @@ fn compile_policy_with(spec: &SandboxSpec<'_>, denied: Vec) -> Result, 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), + Ok(_) => dirs.push(path), + Err(_) => {} } (files, dirs) }); @@ -519,7 +542,7 @@ fn compile_policy_with(spec: &SandboxSpec<'_>, denied: Vec) -> Result Vec { +pub fn backend_state_dirs(backend: &str, launch_env: &[(String, String)]) -> Vec { let home = home_dir(); + // The child's own environment wins over the daemon's: `[backends.X.env]` + // is what the CLI will actually see (`CODEX_HOME = "/srv/codex"` there + // must be the directory the policy binds, or the CLI cannot write its + // state). let env_dir = |var: &str| { - std::env::var_os(var) - .filter(|v| !v.is_empty()) - .map(PathBuf::from) + launch_env + .iter() + .find(|(k, _)| k == var) + .map(|(_, v)| PathBuf::from(v)) + .filter(|p| !p.as_os_str().is_empty()) + .or_else(|| { + 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 { @@ -769,6 +803,7 @@ mod tests { network: NetworkPolicy::Deny, cwd, extra_writable: extra, + launch_env: &[], } } @@ -926,6 +961,41 @@ mod tests { ); } + /// A credential path that does not exist is not mounted at all: bwrap + /// would have to mkdir the mount point under the read-only root, which + /// fails the whole launch. Nothing can leak from a path that is absent, + /// and the sandbox cannot create it either. + #[test] + fn a_missing_credential_path_is_not_mounted() { + let scratch = Scratch::new("noshadow"); + let work = scratch.dir("work"); + let absent = scratch.path().join("no-such-home/.aws"); + let s = spec("", &work, &[]); + let policy = compile_policy_with(&s, vec![absent.clone()]).unwrap(); + assert!(policy.denied.is_empty(), "{:?}", policy.denied); + assert!(policy.denied_files.is_empty()); + } + + /// The state directory follows the child's environment + /// (`[backends.X].env = { CODEX_HOME = … }`), not just the daemon's — + /// the CLI writes wherever that variable points, so the bind has to + /// match it or the CLI cannot save a session. (Only the override side + /// is asserted here: the process env itself is shared with other + /// tests, so the `~/.codex` fallback is not a stable expectation.) + #[test] + fn a_launch_env_state_override_is_honored() { + let env = vec![("CODEX_HOME".to_string(), "/srv/codex-home".to_string())]; + assert_eq!( + backend_state_dirs("codex", &env), + vec![PathBuf::from("/srv/codex-home")] + ); + let pio = vec![("PI_CODING_AGENT_DIR".to_string(), "/srv/pi".to_string())]; + assert_eq!( + backend_state_dirs("pi", &pio), + vec![PathBuf::from("/srv/pi")] + ); + } + /// A missing granted root (deleted workspace) is skipped, not fatal. #[test] fn a_missing_granted_root_is_skipped() { @@ -974,6 +1044,7 @@ mod tests { network: NetworkPolicy::Allow, cwd: &cwd, extra_writable: &[], + launch_env: &[], }; // Whatever this host can do, auto answers without an error. let decision = decide(&auto).unwrap(); diff --git a/src/store.rs b/src/store.rs index 5ae2051..339c543 100644 --- a/src/store.rs +++ b/src/store.rs @@ -688,6 +688,10 @@ impl Store { "ALTER TABLE sessions ADD COLUMN project_id TEXT", ), ("persona", "ALTER TABLE sessions ADD COLUMN persona TEXT"), + // The sandbox a session was created with, when it asked for + // one explicitly: resume has to apply the same confinement, + // not silently fall back to the backend's default. + ("sandbox", "ALTER TABLE sessions ADD COLUMN sandbox TEXT"), ] { if !cols.contains(col) && let Err(e) = c.execute_batch(ddl) @@ -1153,7 +1157,8 @@ impl Store { pinned INTEGER NOT NULL DEFAULT 0, archived INTEGER NOT NULL DEFAULT 0, project_id TEXT, - persona TEXT + persona TEXT, + sandbox TEXT ); CREATE TABLE messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -2631,6 +2636,40 @@ impl Store { .flatten()) } + /// Persist the sandbox mode a session was created with (None = the + /// session followed its backend's configured default). Resume re-applies + /// it: a session that asked to be confined must not come back looser + /// than it was. + pub async fn set_session_sandbox(&self, id: &str, mode: Option<&str>) -> anyhow::Result<()> { + let (sid, m) = (id.to_string(), mode.map(String::from)); + self.conn + .call(move |c| { + c.execute( + "UPDATE sessions SET sandbox = ?2 WHERE id = ?1", + rusqlite::params![sid, m], + )?; + Ok::<(), tokio_rusqlite::Error>(()) + }) + .await?; + Ok(()) + } + + /// The sandbox mode the session asked for at create (None = inherit the + /// backend's default). + pub async fn session_sandbox(&self, id: &str) -> anyhow::Result> { + let sid = id.to_string(); + Ok(self + .conn + .call(move |c| { + c.query_row("SELECT sandbox FROM sessions WHERE id = ?1", [sid], |r| { + r.get::<_, Option>(0) + }) + .optional() + }) + .await? + .flatten()) + } + /// The session's project scope (None = unbound) — the key that /// selects a session's effective granted roots. pub async fn session_project(&self, id: &str) -> anyhow::Result> { diff --git a/tests/rpc.rs b/tests/rpc.rs index 58160ca..cdaa67a 100644 --- a/tests/rpc.rs +++ b/tests/rpc.rs @@ -105,7 +105,7 @@ async fn read_reply(ws: &mut Ws, id: u64) -> Value { /// are). #[tokio::test] async fn session_create_validates_the_sandbox_param() { - let (_state, _store, addr) = serve(test_config(None)).await; + let (_state, store, addr) = serve(test_config(None)).await; let (mut ws, _) = ws_connect(&format!("ws://{addr}/ws")).await; rpc_send( @@ -119,6 +119,7 @@ async fn session_create_validates_the_sandbox_param() { let msg = bad["error"]["message"].as_str().unwrap_or_default(); assert!(msg.contains("auto, bwrap, seatbelt, docker, none"), "{msg}"); + let mut explicit: Option = None; for (id, mode) in [(2, "none"), (3, "auto")] { rpc_send( &mut ws, @@ -131,7 +132,18 @@ async fn session_create_validates_the_sandbox_param() { ok["result"]["sessionId"].is_string(), "sandbox={mode} must create: {ok}" ); + if mode == "none" { + explicit = ok["result"]["sessionId"].as_str().map(str::to_string); + } } + + // The explicit value rides the row: resume re-applies it instead of + // falling back to the backend's (possibly looser) default. + let id = explicit.expect("session id"); + assert_eq!( + store.session_sandbox(&id).await.unwrap().as_deref(), + Some("none") + ); } /// A turn parked on a hung backend unwinds on turn.cancel — the From 31decd8e2b4cd0e34115a1a4e4607427d2505544 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 01:56:25 +0900 Subject: [PATCH 2/3] =?UTF-8?q?fix(sandbox):=20second=20review=20pass=20?= =?UTF-8?q?=E2=80=94=20child=20env,=20refusal=20codes,=20probe=20cost?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Claude/Qwen were spawned with an empty env map, so `[backends.X].env` never reached them (a `CLAUDE_CONFIG_DIR` override silently did nothing) while the sandbox policy — which now reads the same env — bound the overridden directory. The transport gets the resolved env like every other backend, so the policy and the process agree. - Every explicit refusal (wrong platform, driver not implemented, driver unusable, serve backend) is the typed `SandboxUnsupported`, so the wire answers `not_supported` instead of an internal error. - The probe runs inline on a tokio worker; its cap drops to 3s so a hung bwrap cannot hold a worker for a session start. - `sandbox: null` stays equivalent to omitting the param (documented), and an imported native session is a new session, so the backend policy governs it. - The persistence test now proves the reattach path: close, resume through the mock log, and assert the stored mode reached the backend. - CHANGELOG records the late-created-credential gap next to the others. Signed-off-by: 정인권 --- CHANGELOG.md | 8 +++++--- src/backend/streamjson.rs | 15 ++++++++------- src/rpc/session.rs | 4 ++++ src/sandbox/bwrap.rs | 7 ++++--- src/sandbox/mod.rs | 23 ++++++++++++++--------- tests/common/mod.rs | 16 ++++++++++++++-- tests/rpc.rs | 34 ++++++++++++++++++++++++++++++++-- 7 files changed, 81 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b893d1..f413553 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,9 +39,11 @@ test in `tests/sandbox_bwrap.rs` — those skip themselves on hosts without a usable bwrap (no binary, or unprivileged user namespaces disabled). - Known gaps, left for their own decisions: the sandboxed agent can still - reach the daemon's loopback API (RPCs run unconfined), and git writes in - a linked worktree or a repo subdirectory (the git dir lives outside the - workdir) are not granted. + reach the daemon's loopback API (RPCs run unconfined); git writes in a + linked worktree or a repo subdirectory (the git dir lives outside the + workdir) are not granted; and a credential store created *while* a + session runs becomes readable to that session, because only paths that + existed at launch are masked (the next session masks it). - 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 diff --git a/src/backend/streamjson.rs b/src/backend/streamjson.rs index f87f6f6..2a11000 100644 --- a/src/backend/streamjson.rs +++ b/src/backend/streamjson.rs @@ -637,9 +637,12 @@ impl StreamJsonSession { let mut args = resolved.args.clone(); args.extend(dialect.launch_args(&config, resume)); - let transport = resolved - .spawn_ndjson(&args, &HashMap::new(), &config) - .await?; + // `[backends.X].env` reaches the child like every other backend's + // (it used to be dropped here, which silently disabled the override + // — and, worse for the sandbox, left the policy binding an + // `CLAUDE_CONFIG_DIR` the process never saw). + let env: HashMap = resolved.env.iter().cloned().collect(); + let transport = resolved.spawn_ndjson(&args, &env, &config).await?; let session = Arc::new(Self { transport: transport.clone(), @@ -962,10 +965,8 @@ impl AgentSession for OneShotSession { args.extend(self.dialect.launch_args(&config, resume.as_deref())); args.extend(self.dialect.prompt_args(&prompt)?); - let transport = self - .resolved - .spawn_ndjson(&args, &HashMap::new(), &config) - .await?; + let env: HashMap = self.resolved.env.iter().cloned().collect(); + let transport = self.resolved.spawn_ndjson(&args, &env, &config).await?; *self.active.lock().await = Some(transport.clone()); let turn_id = uuid::Uuid::new_v4().to_string(); diff --git a/src/rpc/session.rs b/src/rpc/session.rs index cc83de9..8cae358 100644 --- a/src/rpc/session.rs +++ b/src/rpc/session.rs @@ -469,6 +469,7 @@ pub(super) async fn create( // table drops ill-typed *optional* fields — the wire-compatible rule for // every other param — but dropping this one would answer a client that // asked to be confined with a session it never asked for. + // (`null` is the wire's "not set" and stays equivalent to omitting it.) if let Some(raw) = params.get("sandbox") && !raw.is_null() && !raw.is_string() @@ -628,6 +629,9 @@ pub(super) async fn resume( .map(std::path::PathBuf::from) .unwrap_or_else(|| std::path::PathBuf::from(".")); check_cwd_allowed(state, &cwd)?; + // An import is a NEW session: there is no stored per-session sandbox + // to re-apply, so the backend's configured policy governs it (and a + // serve-mode backend still refuses an explicit request there). let mut cfg = SessionConfig { cwd, ..Default::default() diff --git a/src/sandbox/bwrap.rs b/src/sandbox/bwrap.rs index ebd55fd..a871e1e 100644 --- a/src/sandbox/bwrap.rs +++ b/src/sandbox/bwrap.rs @@ -31,9 +31,10 @@ use super::{ }; /// 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); +/// A working bwrap answers in milliseconds. The probe runs inline on a +/// tokio worker (the decision is sync), so the cap is short: a hung bwrap +/// must not hold a worker for a session start. +const PROBE_TIMEOUT: Duration = Duration::from_secs(3); /// How long a probe answer is trusted before the next `auto` resolution /// re-checks (see `Bwrap::status`). diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index 1ae0763..9f64a63 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -351,6 +351,12 @@ impl SandboxDecision { } } +/// [`SandboxUnsupported`] as an `anyhow::Error`, so every refusal keeps the +/// same wire code (`not_supported`) instead of landing as an internal error. +fn unsupported(message: String) -> anyhow::Error { + SandboxUnsupported(message).into() +} + /// A sandbox request the backend or host cannot honor. /// /// Typed so the wire can answer `not_supported` instead of a generic @@ -398,14 +404,13 @@ pub fn decide(spec: &SandboxSpec<'_>) -> Result { // that cannot have it. Warning and continuing would silently run the // agent exactly as unprotected as before. (SandboxSupport::Serve, requested) => { - return Err(SandboxUnsupported(format!( + return Err(unsupported(format!( "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) - )) - .into()); + ))); } (SandboxSupport::Spawn, SandboxRequest::Auto) => match platform_default() { Some(kind) => kind, @@ -432,11 +437,11 @@ pub fn decide(spec: &SandboxSpec<'_>) -> Result { if fallback_ok { return Ok(SandboxDecision::Unconfined(Unconfined::AutoNoDriver(why))); } - bail!( + return Err(unsupported(format!( "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!( @@ -446,11 +451,11 @@ pub fn decide(spec: &SandboxSpec<'_>) -> Result { if fallback_ok { return Ok(SandboxDecision::Unconfined(Unconfined::AutoNoDriver(why))); } - bail!( + return Err(unsupported(format!( "sandbox = \"{}\" is not available: {why}. Use sandbox = \"auto\" or \"none\", or the \ bwrap driver on Linux.", spec.request - ); + ))); }; let status = driver.status(); @@ -459,11 +464,11 @@ pub fn decide(spec: &SandboxSpec<'_>) -> Result { if fallback_ok { return Ok(SandboxDecision::Unconfined(Unconfined::AutoNoDriver(why))); } - bail!( + return Err(unsupported(format!( "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)?; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 1a4f8f6..9f0873b 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -78,6 +78,16 @@ pub fn mock_client_with_listing( /// (prompt containing "perm"), optionally hangs (prompt containing /// "hang") until interrupted. `listing` backs /// list_importable/list_all_importable for the history-scanner tests. +/// Every `SessionConfig` a mock backend was handed, in order. Tests that +/// care what the daemon launched with (the sandbox a session resumes under, +/// for one) read the tail of this instead of reaching into the manager. +pub fn mock_config_log() -> Arc>> { + static LOG: std::sync::OnceLock>>> = + std::sync::OnceLock::new(); + LOG.get_or_init(|| Arc::new(parking_lot::Mutex::new(Vec::new()))) + .clone() +} + struct MockClient { listing: Arc>>, } @@ -109,7 +119,8 @@ impl AgentClient for MockClient { async fn fetch_catalog(&self, _cwd: Option<&std::path::Path>) -> Result { Ok(ProviderCatalog::default()) } - async fn create_session(&self, _config: SessionConfig) -> Result> { + async fn create_session(&self, config: SessionConfig) -> Result> { + mock_config_log().lock().push(config); Ok(Arc::new(MockSession::new())) } @@ -123,8 +134,9 @@ impl AgentClient for MockClient { async fn resume_session( &self, handle: &PersistenceHandle, - _config: SessionConfig, + config: SessionConfig, ) -> Result> { + mock_config_log().lock().push(config); let s = MockSession::new(); *s.handle.lock().await = Some(handle.clone()); Ok(Arc::new(s)) diff --git a/tests/rpc.rs b/tests/rpc.rs index cdaa67a..c660908 100644 --- a/tests/rpc.rs +++ b/tests/rpc.rs @@ -137,13 +137,43 @@ async fn session_create_validates_the_sandbox_param() { } } - // The explicit value rides the row: resume re-applies it instead of - // falling back to the backend's (possibly looser) default. + // The explicit value rides the row, and the reattach path hands it back + // to the backend — a session created with an explicit mode must not come + // back under the backend's (possibly looser) default. let id = explicit.expect("session id"); assert_eq!( store.session_sandbox(&id).await.unwrap().as_deref(), Some("none") ); + // Reattach needs a persisted native handle; the mock has none from a + // plain create, so give the row one and resume through it. + store + .set_agent_session(&id, "mock", "native-1") + .await + .unwrap(); + // Close the live one first: an already-live session answers resume by + // subscribing, no relaunch involved. + rpc_send( + &mut ws, + json!({"id":8,"method":"session.close","params":{"sessionId":id}}), + ) + .await; + let _ = read_reply(&mut ws, 8).await; + let log = common::mock_config_log(); + log.lock().clear(); + rpc_send( + &mut ws, + json!({"id":9,"method":"session.resume","params":{"sessionId":id}}), + ) + .await; + let restarted = read_reply(&mut ws, 9).await; + assert!(restarted["result"]["sessionId"].is_string(), "{restarted}"); + let relaunched = log.lock().last().cloned().expect("a relaunch config"); + assert_eq!( + relaunched.sandbox, + Some(damon_core::sandbox::SandboxRequest::None), + "resume must re-apply the stored sandbox" + ); } /// A turn parked on a hung backend unwinds on turn.cancel — the From b68286346a21d78eca545cc7a8dc8d66ee24e550 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 02:09:48 +0900 Subject: [PATCH 3/3] fix(sandbox): resolve the launcher on the daemon's PATH MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The launcher was exec'd by name, so a `[backends.X].env` PATH (a custom bin dir, a cleanup helper) could leave `bwrap` unresolvable and the session unable to start. It is resolved to an absolute path against the daemon's own PATH now — the same lookup the probe used, so the binary that was validated is the one that runs. Signed-off-by: 정인권 --- src/sandbox/bwrap.rs | 18 ++++++++++++++---- tests/sandbox_bwrap.rs | 6 +++++- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/sandbox/bwrap.rs b/src/sandbox/bwrap.rs index a871e1e..bccd605 100644 --- a/src/sandbox/bwrap.rs +++ b/src/sandbox/bwrap.rs @@ -80,10 +80,15 @@ impl SandboxDriver for Bwrap { } } -/// The launcher binary name. Resolved through PATH by the spawn, which is -/// also how the probe found it. +/// The launcher to exec: resolved to an absolute path against the daemon's +/// PATH, so the launch does not depend on the *child's* environment — a +/// `[backends.X].env` PATH (a custom bin dir, a cleanup helper) would +/// otherwise leave `bwrap` unresolvable and the session unable to start. +/// It also guarantees the binary the probe validated is the one used. fn launcher() -> String { - "bwrap".to_string() + crate::backend::registry::which("bwrap") + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|| "bwrap".to_string()) } /// Policy + command → the full `bwrap` argument list (everything after the @@ -484,7 +489,12 @@ mod tests { policy: Box::new(policy(NetworkPolicy::Allow)), }; let cmd = confined.confine("claude", &[]).unwrap(); - assert_eq!(cmd.program, "bwrap"); + // Absolute when bwrap is on the daemon's PATH, bare otherwise. + assert!( + cmd.program == "bwrap" || cmd.program.ends_with("/bwrap"), + "{}", + cmd.program + ); assert_eq!(cmd.args.last().unwrap(), "claude"); } diff --git a/tests/sandbox_bwrap.rs b/tests/sandbox_bwrap.rs index cf0d722..2ab602e 100644 --- a/tests/sandbox_bwrap.rs +++ b/tests/sandbox_bwrap.rs @@ -95,7 +95,11 @@ fn confined(policy: &SandboxPolicy, script: &str) -> SandboxCommand { fn run(policy: &SandboxPolicy, script: &str) -> std::process::Output { let cmd = confined(policy, script); - assert_eq!(cmd.program, "bwrap", "the launcher is the sandbox"); + assert!( + cmd.program == "bwrap" || cmd.program.ends_with("/bwrap"), + "the launcher is the sandbox: {}", + cmd.program + ); Command::new(&cmd.program) .args(&cmd.args) .output()