Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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) |
Expand Down
37 changes: 37 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Comment on lines +32 to +34

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Linux CI가 실제 bwrap 실행을 검증하지 않음

변경 기록과 달리 Linux 의존성 설치 단계는 bubblewrap을 설치하지 않습니다. 테스트 가드는 드라이버가 없거나 네임스페이스를 만들 수 없으면 테스트를 건너뜁니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

- 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
Expand Down
1 change: 1 addition & 0 deletions README.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 드라이버는 후속.

## 설치

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
33 changes: 33 additions & 0 deletions config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions examples/backend_probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 1 addition & 2 deletions src/backend/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,7 @@ pub struct CodexSession {
impl CodexSession {
async fn spawn(resolved: &ResolvedBackend, config: SessionConfig) -> Result<Arc<Self>> {
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?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 샌드박스가 Codex·OMP·Pi 모델 조회를 차단

모델 조회는 작업 디렉터리를 전달하지 않아 Codex·OMP·Pi가 /에서 조회용 세션을 시작합니다. 샌드박스가 /를 거부하므로 모델 및 모드 선택기에 자동 옵션만 남습니다.

Learn more

Codex 모델 조회와 OMP·Pi 모델 조회는 작업 디렉터리가 없으면 /를 선택합니다. 두 경로 모두 새 샌드박스 실행 함수로 연결됩니다. compile_policy_with는 호스트 루트 전체가 쓰기 가능해지는 것을 막기 위해 /를 거부합니다. 이 때문에 백엔드에 모델 목록을 요청하기도 전에 조회가 끝납니다.

Example: bwrap을 사용하는 데몬에서 웹 UI의 에이전트를 Codex로 바꾸면 catalog.models가 실패하고 모델 및 모드 메뉴에는 자동 옵션만 남습니다.

Recommended fix: 두 모델 조회 경로에서 실제로 존재하는 별도 임시 작업 디렉터리를 기본값으로 사용하고 조회가 끝나면 정리하세요. / 거부 규칙은 유지하고, 작업 디렉터리를 보내지 않는 모델 조회를 테스트하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


let (events, _) = broadcast::channel(512);
let session = Arc::new(Self {
Expand Down
5 changes: 4 additions & 1 deletion src/backend/droid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
}
}
}
5 changes: 4 additions & 1 deletion src/backend/omp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ impl OmpSession {
let env: HashMap<String, String> = 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 {
Expand Down Expand Up @@ -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);
Expand Down
13 changes: 13 additions & 0 deletions src/backend/opencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Arc<OpencodeServer>>,
http: reqwest::Client,
caps: Capabilities,
Expand All @@ -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))
Expand Down Expand Up @@ -221,6 +225,12 @@ impl AgentClient for OpencodeClient {
}

async fn create_session(&self, config: SessionConfig) -> Result<Arc<dyn AgentSession>> {
// 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
Expand Down Expand Up @@ -266,6 +276,9 @@ impl AgentClient for OpencodeClient {
handle: &PersistenceHandle,
config: SessionConfig,
) -> Result<Arc<dyn AgentSession>> {
// 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))
}
Expand Down
Loading
Loading