Repository navigation
feat(sandbox): declarative isolation policy with a Linux bwrap driver (Refs #33) - #60
Conversation
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: 정인권 <developjik@gmail.com>
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
| match std::fs::symlink_metadata(&path) { | ||
| Ok(meta) if meta.file_type().is_file() => files.push(path), | ||
| _ => dirs.push(path), |
There was a problem hiding this comment.
🔴 자격 증명 경로가 없으면 샌드박스 시작 실패
홈 디렉터리에 .aws 같은 자격 증명 경로가 없어도 샌드박스는 그곳에 마운트를 시도합니다. bwrap은 읽기 전용 홈에 마운트 지점을 만들 수 없어 에이전트를 실행하지 못합니다.
Learn more
credential_paths는 호스트에 없는 경로도 반환합니다. compile_args는 호스트 루트를 읽기 전용으로 마운트한 뒤 각 디렉터리의 마운트 지점에 --tmpfs를 적용합니다. bubblewrap은 마운트 지점이 없으면 먼저 디렉터리를 만들기 때문에 부모가 읽기 전용이면 종료합니다. probe는 자격 증명 마운트를 생략하므로 이 실패를 발견하지 못합니다.
Example: 작업 디렉터리가 /home/me/project이고 /home/me/.aws가 없는 계정에서는 가용성 검사가 통과해도 실제 에이전트 실행이 실패합니다.
Recommended fix: 실제로 존재하는 저장소와 아직 없는 경로를 구분하세요. 없는 경로를 가려야 한다면 호스트를 변경하지 않는 전용 오버레이를 사용하세요. 실제 정책 컴파일을 거쳐 일부 자격 증명 경로가 없는 홈에서 에이전트가 실행되는지 검증하세요.
Was this helpful? React with 👍 or 👎 to provide feedback.
| let env: HashMap<String, String> = 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?; |
There was a problem hiding this comment.
🔴 샌드박스가 Codex·OMP·Pi 모델 조회를 차단
모델 조회는 작업 디렉터리를 전달하지 않아 Codex·OMP·Pi가 /에서 조회용 세션을 시작합니다. 샌드박스가 /를 거부하므로 모델 및 모드 선택기에 자동 옵션만 남습니다.
Learn more
Codex 모델 조회와 OMP·Pi 모델 조회는 작업 디렉터리가 없으면 /를 선택합니다. 두 경로 모두 새 샌드박스 실행 함수로 연결됩니다. compile_policy_with는 호스트 루트 전체가 쓰기 가능해지는 것을 막기 위해 /를 거부합니다. 이 때문에 백엔드에 모델 목록을 요청하기도 전에 조회가 끝납니다.
Example: bwrap을 사용하는 데몬에서 웹 UI의 에이전트를 Codex로 바꾸면 catalog.models가 실패하고 모델 및 모드 메뉴에는 자동 옵션만 남습니다.
Recommended fix: 두 모델 조회 경로에서 실제로 존재하는 별도 임시 작업 디렉터리를 기본값으로 사용하고 조회가 끝나면 정리하세요. / 거부 규칙은 유지하고, 작업 디렉터리를 보내지 않는 모델 조회를 테스트하세요.
Was this helpful? React with 👍 or 👎 to provide feedback.
| let mut writable: Vec<PathBuf> = 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); |
There was a problem hiding this comment.
🔴 샌드박스에서 워크트리 변경을 스테이징할 수 없음
워크트리 생성으로 만든 체크아웃의 Git 인덱스는 원본 저장소에 남습니다. 별도 권한이 없으면 샌드박스가 그 인덱스를 읽기 전용으로 두므로 에이전트의 git add와 git commit이 실패합니다.
Learn more
워크트리 기본 경로는 원본 저장소의 형제 디렉터리입니다. 웹 UI는 생성된 워크트리 프로젝트로 바로 세션을 열고, session.create는 그 프로젝트의 루트를 작업 디렉터리로 사용합니다. 연결 워크트리의 .git은 원본 저장소 아래의 워크트리 메타데이터를 가리킵니다. 별도 경로 권한이 없으면 bwrap 마운트는 체크아웃만 쓰기 가능하게 하고, Git의 인덱스 잠금 파일은 여전히 읽기 전용 경로에 놓입니다.
Example: /code/demo-worktrees/pr-9의 파일을 수정하는 데는 성공하지만 /code/demo/.git/worktrees/pr-9/index.lock을 만들 수 없어 스테이징은 실패합니다.
Recommended fix: 워크트리 세션이 Git 쓰기를 지원하려면 전용 Git 메타데이터를 격리하거나, 필요한 외부 경로에 한해 명시적으로 쓰기 권한을 받으세요. 원본 저장소 전체를 자동으로 쓰기 가능하게 만들지 말고, Damon이 생성한 워크트리에서 실제 Git 작업을 테스트하세요.
Was this helpful? React with 👍 or 👎 to provide feedback.
| ) -> anyhow::Result<Arc<crate::backend::transport::NdjsonTransport>> { | ||
| let decision = self.sandbox_decision(session)?; | ||
| crate::backend::transport::NdjsonTransport::spawn( | ||
| &self.command, | ||
| args, | ||
| env, |
There was a problem hiding this comment.
🔴 백엔드 환경 설정으로 지정한 상태 디렉터리에 기록 불가
[backends.codex.env]의 CODEX_HOME은 Codex 프로세스에 전달되지만 샌드박스 정책에는 전달되지 않습니다. 작업 디렉터리나 별도 허용 경로 밖에 있는 상태 디렉터리는 읽기 전용으로 남아 Codex가 세션 기록을 저장하지 못합니다.
Learn more
backend_state_dirs는 데몬 프로세스의 환경만 읽습니다. 그러나 NdjsonTransport::spawn은 백엔드 환경을 자식에 적용하므로, Codex가 세션 기록에 쓰는 CODEX_HOME이 정책에서 허용한 경로와 다를 수 있습니다. 같은 구조는 OMP와 Pi의 상태 경로 환경 변수에도 적용됩니다.
Example: 데몬 환경에는 CODEX_HOME이 없고 [backends.codex.env]에서 /home/me/codex-state를 지정하면, 작업 디렉터리나 별도 허용 경로가 그곳을 포함하지 않는 한 정책은 ~/.codex만 쓰기 가능하게 합니다.
Recommended fix: 상태 경로는 자식 프로세스의 실제 환경과 같은 우선순위로 계산하세요. 백엔드 환경의 값이 상속된 환경보다 우선하도록 하고, 동일한 값을 기준으로 마운트와 프로세스 실행을 구성하세요.
Was this helpful? React with 👍 or 👎 to provide feedback.
| 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. |
There was a problem hiding this comment.
🔍 Linux CI가 실제 bwrap 실행을 검증하지 않음
변경 기록과 달리 Linux 의존성 설치 단계는 bubblewrap을 설치하지 않습니다. 테스트 가드는 드라이버가 없거나 네임스페이스를 만들 수 없으면 테스트를 건너뜁니다.
Was this helpful? React with 👍 or 👎 to provide feedback.
| (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) | ||
| ), |
There was a problem hiding this comment.
🔍 미지원 샌드박스가 RPC 내부 오류로 분류됨
서버 모드 백엔드가 격리를 지원하지 않을 때 일반 오류를 반환합니다. RPC 오류 변환은 이를 NOT_SUPPORTED가 아닌 내부 오류로 처리합니다.
Was this helpful? React with 👍 or 👎 to provide feedback.
| 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()); | ||
| } |
| 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()))?, | ||
| ), | ||
| }, |
There was a problem hiding this comment.
🟥 세션 재개 시 명시적으로 요청한 격리가 풀림
세션별 bwrap 설정은 저장되지 않아 세션 재연결 때 백엔드 기본값으로 돌아갑니다. 기본값이 none이면 같은 세션의 다음 에이전트 명령이 격리 없이 실행됩니다.
Was this helpful? React with 👍 or 👎 to provide feedback.
| Field::str_opt("projectId"), | ||
| Field::str_opt("persona"), | ||
| Field::array_opt("allowedTools"), | ||
| Field::str_opt("sandbox"), |
There was a problem hiding this comment.
🟨 잘못된 샌드박스 요청이 오류 없이 무시됨
요청 파서는 문자열이 아닌 sandbox 값을 버립니다. 설정의 기본값이 none이면 클라이언트는 오류 대신 격리되지 않은 세션을 받습니다.
Was this helpful? React with 👍 or 👎 to provide feedback.
| fn status(&self) -> DriverStatus { | ||
| static STATUS: OnceLock<DriverStatus> = OnceLock::new(); | ||
| STATUS.get_or_init(probe).clone() |
The climb used a fixed number of `..`, which reaches / from a /tmp scratch dir but not from macOS's /var/folders/... (CI caught it). Count the components instead, so the path leaves any temp root. Signed-off-by: 정인권 <developjik@gmail.com>
| let mut climb = cwd.clone(); | ||
| for _ in 0..cwd.components().count() + 2 { | ||
| climb.push(".."); | ||
| } |
The golden argv and the host-root/traversal cases name POSIX paths, which are not absolute on Windows and cannot resolve to a root there (CI caught it). bwrap is Linux-only, so those assertions are unix-only; the decision rules they sit beside still run everywhere. Signed-off-by: 정인권 <developjik@gmail.com>
There was a problem hiding this comment.
🔍 Windows에서 쓰기 경로 검증을 확인하지 않는 bwrap 테스트
Windows에서는 경로 거부 테스트 둘 다 /home/u/project를 절대 경로로 인정하지 않는 첫 검사에서 통과합니다. 테스트 이름과 달리 쓰기 경로를 검사하는 분기에는 도달하지 않습니다.
Was this helpful? React with 👍 or 👎 to provide feedback.
fix(sandbox): review follow-ups from #60 — launch failure, resume confinement, param honesty
Refs #33 — the first cut. Merging this does not close the issue: seatbelt and docker drivers are still open.
The agent runs arbitrary shell commands, so without isolation a hallucinated flag, an injected instruction, or an unlucky
rmreaches straight into the host:~/.ssh, cloud credentials, registry tokens, the network. This PR adds the policy, the seam, and the Linux driver; the other two drivers have a place to land.What is in this cut
One declaration, three scopes.
sandbox = "auto" | "bwrap" | "seatbelt" | "docker" | "none"reads at the top level (the default for every backend), per backend ([backends.X] sandbox), and per session (session.create's newsandboxparam — added to the request struct,FIELDSand therpc_methods()catalog, so the drift test holds it in place).sandbox::decideis the only place the rules live (src/sandbox/mod.rs):noneautoautodamond doctorautoopencode,mimo)unsupported— notnonebwrap/seatbelt/dockerbwrap/seatbelt/dockerunprivileged_userns_clone=0/ wrong platform / driver not implementedbwrap/seatbelt/dockersandbox = "none"or a spawn-mode backendThe serve case is the one worth arguing about:
opencode/mimoattach to a long-livedserveprocess and sessions are directories inside it, so there is no spawn point. Recording that asnonewould read as "isolation considered and declined" when it was never possible — hence a distinctUnsupportedstate, and a hard failure when a driver is asked for anyway (OpencodeClient::create_session/resume_sessionrun the decision purely for that refusal).The bwrap driver (
src/sandbox/bwrap.rs) — pure compiler, golden-tested:~/.claude+~/.claude.json,$CODEX_HOME/~/.codex,~/.omp,~/.pi,~/.qwen,~/.factory,~/.zcode; env overrides win, mirroringskills_hub::targets). A missing state dir is created so a first login inside the sandbox can persist.~/.ssh,~/.aws,~/.gnupg,~/.netrc,~/.git-credentials,~/.npmrc,~/.pypirc,~/.docker,~/.kube,~/.password-store,~/.config/gh,~/.config/gcloud, and Damon's own~/.config/damon/~/.damon(auth token + discovery).SSH_AUTH_SOCKis scrubbed: the agent socket stays connectable through a read-only bind, so a mount cannot hide it and the CLIs never need it.Planner promises, each with a test: every path absolute (
..-relative is rejected, not resolved against the daemon's cwd); every path symlink-resolved, so a link inside the worktree binds its target and a link to/cannot become writable;/is refused as a workdir; a workdir inside a credential store is refused by name; nested writable roots collapse; a missing granted root is skipped rather than failing the session.Wiring:
NdjsonTransport::spawntakes the resolved decision (it never falls back on its own), and every spawn-mode backend launches throughResolvedBackend::spawn_ndjson, so the policy is applied in one call site per backend. Serve-mode spawns are excluded by construction.damond doctorprints the platform driver's status and one line per detected backend —bwrap: network allow; writable …,unsupported — …, or the failure.Tests
src/sandbox/: 20+ unit tests — golden argv, deny-after-bind ordering,/dev/nullfor file credentials, network share flag, relative/../symlink escapes, credential precedence, opt-out and fallback rules, serve-mode refusal, config parsing at all three scopes, catalog support flags.tests/sandbox_bwrap.rs: the four end-to-end cases from the acceptance criteria (write outside the workdir, read-only root, credential path denied as dir and file, network denied/allowed against a listener in the test process) plus one transport-wiring test (a fakeshbackend reports, through the NDJSON pipe, that it ran inside the sandbox). Each guards itself: no usable bwrap → print why and return.tests/rpc.rs:session.createwith a misspelled sandbox is-32602; valid values create.Local:
cargo fmt --check,cargo clippy --all-targets -- -D warnings,cargo test(298 lib + all integration suites) pass on this branch (two environment-only failures are pre-existing here:shutdown_kills_the_process_treeleaves a zombie the container's PID 1 never reaps, andmcp_probe's fixture needsnode). The bwrap integration tests skipped locally — this box has no bubblewrap andkernel.unprivileged_userns_clone=0— so their first real run is CI.One thing this PR cannot do itself
CI needs
bubblewrapon the Linux leg for those tests to run rather than skip:- name: Install Linux deps if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y libdbus-1-dev pkg-config + run: sudo apt-get update && sudo apt-get install -y libdbus-1-dev pkg-config bubblewrap(also in the
coveragejob). The push credential for this branch has noworkflowspermission, so the change is not in the branch — worth applying here or in a follow-up, since otherwise the Linux leg only exercises the compiler, not the sandbox.Known gaps (named so they are decisions, not surprises)
127.0.0.1:9470gets host-privilegedfile.*/session.*/worktree.*work done for it, which is strictly more than its mount view allows. Closing it needs either a per-connection credential the sandbox cannot read or a policy that denies the daemon port while allowing the model API (the--unshare-netside is wired and tested, the allow-list is not). Its own decision.<repo>/.git/worktrees/<branch>, or<repo>/.gitfor a subdir cwd), sogit add/commitfail withRead-only file systemwhilestatus/diffwork. Granting it means giving the agent write access to git hooks and refs of the parent repo — worth deciding on purpose, not by default.client.rs,npm/client.mjs,python/client.py) do not passsandboxyet; the param is optional, so they keep today's behavior. Adding it to their create helpers + tests is mechanical but touches three published contracts.SSH_AUTH_SOCKare described below.Deliberately out of scope (follow-ups on #33)
autoon macOS reportsseatbelt: not implementedthrough doctor.sandbox_network = "backend"), which for every agent CLI is allow — its model API call is why it runs at all. Blocking the agent's shell tools while leaving its API calls open needs a proxy in front of the agent;--unshare-netis wired and tested, so that knob is ready.SSH_AUTH_SOCK(AWS_*,GITHUB_TOKEN, …) — a deny list that could break a user's owngh/awsworkflow inside the agent, so it wants its own decision.--seccomp),--disable-userns, and binding a--tmpfsscratch for/tmpworkdirs (today the host's read-only/tmpis kept so a bind source is never shadowed).