Skip to content

fix(sandbox): review follow-ups from #60 — launch failure, resume confinement, param honesty - #61

Merged
developjik merged 3 commits into
mainfrom
fix/sandbox-review-followups
Nov 28, 2026
Merged

developjik merged 3 commits into
mainfrom
fix/sandbox-review-followups

Conversation

@developjik

@developjik developjik commented Nov 28, 2026 •

Copy link
Copy Markdown
Owner

Follow-up to #60 (merged into main as 2f52012), which landed the first cut of #33 while the review fixes for it were still being written. This branch is those fixes, rebased onto main — each one is a case where the merged policy could break a session or be quieter than it claims.

What it fixes

  1. A credential path that does not exist failed the whole launch. credential_paths() returns paths whether or not they exist, and the compiler masked each with --tmpfs. bwrap has to create that mount point, and its parent is inside the read-only root — so on any home without ~/.aws (or ~/.gnupg, …) every session would have died at bwrap: Can't mkdir parents for …, while damond doctor and the probe still said "usable". Only existing paths are masked now: a path that is absent has nothing to leak, and the sandbox cannot create it either (its parent is read-only). The probe also mounts the recipe's /tmp tmpfs, so a host that cannot set the recipe up fails at doctor rather than at the first turn.
  2. The Codex/OMP catalog probe spawned with cwd /, which the policy refuses as a writable root — under auto the model/mode picker would have come back with only "auto". Those probes answer model/list and start no turn, so they are explicitly unconfined, the same rule the discovery probe already follows.
  3. [backends.X].env state overrides were invisible to the policy. backend_state_dirs read the daemon's environment, but the child is launched with the backend's — so CODEX_HOME = "/srv/codex" in config would have left the CLI confined out of its own state directory. The launch env now wins, both in the policy and in the process.
  4. An explicit per-session sandbox was lost on resume. session.create {sandbox: "bwrap"} was not persisted, so the next reattach (idle reap, session.resume, session.restart, daemon restart) fell back to the backend's default — which may be none. The mode now rides the session row (sessions.sandbox, ALTER migration + the in-memory schema) and is re-applied on every reattach. A sandbox that is present but not a string answers -32602 instead of being dropped by the optional-field rule, which would have handed a client that asked to be confined an unconfined session.
  5. Claude/Qwen never received [backends.X].env — those spawns passed an empty env map, so a CLAUDE_CONFIG_DIR override did nothing while the policy now bound the overridden directory. They get the resolved env like every other backend. The launcher (bwrap) is also resolved to an absolute path against the daemon's PATH, so a PATH in that env block cannot leave the launcher, or the binary the probe validated, unresolved.
  6. Smaller: every explicit refusal (wrong platform, not implemented, not usable, serve backend) is the typed SandboxUnsupported, so the wire answers not_supported rather than a generic internal error; the probe is cached for 30 s instead of forever (a driver installed or a sysctl flipped while the daemon runs must take effect) and its cap is 3 s so a hung bwrap cannot hold a worker; sandbox: null stays equivalent to omitting the param; docs/protocol-v2.md and docs/protocol-v2.ko.md gain the session.create param; the CHANGELOG no longer claims CI installs bubblewrap (it does not — see below).

Verification

cargo fmt --check, cargo clippy --all-targets -- -D warnings, cargo test (297 lib + all integration suites) pass on this branch. New tests cover each fix: a missing credential path is not mounted, a launch-env state override wins, the serve refusal stays typed, and session.create persists the mode and the reattach path hands it back — an explicit none session is closed, resumed, and the mock backend reports the stored mode in the config it was relaunched with.

Two failures are pre-existing in this container and unrelated: shutdown_kills_the_process_tree (a zombie the container's PID 1 never reaps) and mcp_probe (needs node).

Still open, worth a decision

  • CI does not install bubblewrap, so tests/sandbox_bwrap.rs skips on every leg — the Linux leg exercises the compiler but never the sandbox. The one-line change (test job + coverage job):
    -        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
    It is not in this branch: the credential that pushes here has no workflows permission.
  • The daemon's own API stays reachable from inside the sandbox (RPCs run in the daemon, outside it, and a loopback bind has no token). Closing it needs a per-connection credential the sandbox cannot read, or a deny-the-daemon-port allow-list.
  • git writes fail in a linked worktree or a repo subdirectory (the git dir is outside the workdir). Granting it means giving the agent git hooks and refs of the parent repo — a deliberate choice, not a default.
  • The Rust/npm/Python create helpers do not pass sandbox yet (optional, so behavior is unchanged).

Refs #33, #60

…esty

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: 정인권 <developjik@gmail.com>
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-28T16:36:26.708823Z
We couldn’t complete this review. Comment @codex review to try again.
9ad8f28 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@devin-ai-integration devin-ai-integration Bot left a comment •

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.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 7 potential issues.

Devin Review

Comment thread src/backend/registry.rs Resolved
Comment thread src/rpc.rs Resolved
Comment thread src/rpc/session.rs Resolved
Comment thread src/sandbox/bwrap.rs
Comment on lines +56 to +65
static CACHE: OnceLock<Mutex<Option<(Instant, DriverStatus)>>> = 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()));

@devin-ai-integration devin-ai-integration Bot Nov 28, 2026 •

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.

🔍 주기적 드라이버 검사가 비동기 워커를 점유함

캐시가 만료되면 백엔드 실행이 Tokio 워커에서 드라이버 프로세스를 동기적으로 기다린다. 완료할 때까지 캐시 잠금도 유지하므로, 재검사를 블로킹 전용 작업으로 분리할지 검토할 만하다.

Devin Review


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

Comment thread tests/rpc.rs Resolved
Comment thread src/rpc.rs Resolved
Comment thread src/sandbox/mod.rs
Comment on lines +529 to +530
Ok(_) => dirs.push(path),
Err(_) => {}

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.

🟨 세션이 시작된 뒤 생성된 호스트 자격 증명 노출

시작 시 없던 자격 증명 경로에는 마스크가 설치되지 않는다. 사용자가 세션 실행 중 해당 위치에 자격 증명을 생성하면, 에이전트가 읽기 전용 호스트 마운트를 통해 읽을 수 있다.

Devin Review


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

- 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: 정인권 <developjik@gmail.com>

@devin-ai-integration devin-ai-integration Bot left a comment •

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.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 3 new potential issues.

Devin Review

Comment thread src/backend/streamjson.rs Resolved
Comment thread src/backend/streamjson.rs
Comment on lines +644 to +645
let env: HashMap<String, String> = resolved.env.iter().cloned().collect();
let transport = resolved.spawn_ndjson(&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.

🟡 별도 설정 디렉터리의 Claude 세션이 가져오기 목록에서 누락됨

백엔드에 CLAUDE_CONFIG_DIR을 지정하면 Claude는 그곳에 세션을 저장하지만 세션 검색은 여전히 ~/.claude/projects만 읽습니다. 해당 디렉터리의 세션은 가져오기와 재검색 결과에 나타나지 않습니다.

Learn more

세션을 시작하거나 재개할 때 Claude는 백엔드 환경에 지정된 CLAUDE_CONFIG_DIR을 사용합니다. 하지만 가져오기 RPC는 스트림 백엔드의 목록 조회를 거쳐 기본 경로만 읽는 Claude의 목록 구현을 호출합니다. 재검색도 기본 전체 목록 구현을 통해 같은 조회를 사용합니다. 따라서 검색은 실제로 사용 중인 세션 저장소를 읽지 않습니다.

Example: [backends.claude.env]의 CLAUDE_CONFIG_DIR을 /srv/claude-profile로 지정하고 같은 설정으로 생성한 세션을 session.import에서 조회합니다. 세션 파일은 /srv/claude-profile/projects 아래에 있지만 RPC는 ~/.claude/projects만 열어 해당 세션을 반환하지 않습니다.

Recommended fix: Claude의 세션 목록 구현에 실제 실행과 같은 설정 루트를 전달하세요. 백엔드 환경의 오버라이드, 상속 환경, 기본 경로의 우선순위를 실행과 검색에서 일치시키고, 커스텀 설정 루트에만 세션 파일이 있는 경우를 테스트하세요.

Devin Review


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

Comment thread tests/rpc.rs
Comment on lines +162 to +171
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");

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.

🔍 병렬 실행에서 불안정한 세션 재개 테스트

모의 백엔드 기록은 모든 테스트가 공유합니다. 재개 응답을 기다리는 동안 다른 테스트가 기록을 추가하면 마지막 항목이 다른 세션의 설정일 수 있습니다. 모의 클라이언트 인스턴스마다 기록을 분리하세요.

Devin Review


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

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: 정인권 <developjik@gmail.com>

@devin-ai-integration devin-ai-integration Bot left a comment

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.

Devin Review found 2 new potential issues.

Devin Review

Comment thread tests/sandbox_bwrap.rs
Comment on lines +98 to +102
assert!(
cmd.program == "bwrap" || cmd.program.ends_with("/bwrap"),
"the launcher is the sandbox: {}",
cmd.program
);

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.

🔍 백엔드 PATH를 덮어쓰는 세션 시작 테스트가 없음

이 테스트는 bwrap이라는 이름도 허용하고 백엔드 환경을 적용하지 않습니다. 백엔드 PATH에 bubblewrap이 없어도 세션 실행이 성공하는지 회귀 테스트로 확인할 필요가 있습니다.

Devin Review


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

Comment thread src/sandbox/bwrap.rs
Comment on lines +89 to +91
crate::backend::registry::which("bwrap")
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| "bwrap".to_string())

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.

🟥 작업공간의 파일이 샌드박스 런처로 실행됨

데몬의 PATH에서 찾은 상대 경로는 세션 실행 시 작업공간 기준으로 해석됩니다. 이 경우 신뢰할 수 없는 저장소의 파일이 검사를 통과한 bubblewrap 대신 샌드박스 밖에서 실행될 수 있습니다.

Devin Review


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

@developjik
developjik merged commit fb123cc into main Nov 28, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant