Repository navigation
fix(sandbox): review follow-ups from #60 — launch failure, resume confinement, param honesty - #61
Conversation
…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>
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. |
| 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())); |
There was a problem hiding this comment.
🔍 주기적 드라이버 검사가 비동기 워커를 점유함
캐시가 만료되면 백엔드 실행이 Tokio 워커에서 드라이버 프로세스를 동기적으로 기다린다. 완료할 때까지 캐시 잠금도 유지하므로, 재검사를 블로킹 전용 작업으로 분리할지 검토할 만하다.
Was this helpful? React with 👍 or 👎 to provide feedback.
| Ok(_) => dirs.push(path), | ||
| Err(_) => {} |
- 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>
| let env: HashMap<String, String> = resolved.env.iter().cloned().collect(); | ||
| let transport = resolved.spawn_ndjson(&args, &env, &config).await?; |
There was a problem hiding this comment.
🟡 별도 설정 디렉터리의 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의 세션 목록 구현에 실제 실행과 같은 설정 루트를 전달하세요. 백엔드 환경의 오버라이드, 상속 환경, 기본 경로의 우선순위를 실행과 검색에서 일치시키고, 커스텀 설정 루트에만 세션 파일이 있는 경우를 테스트하세요.
Was this helpful? React with 👍 or 👎 to provide feedback.
| 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"); |
There was a problem hiding this comment.
🔍 병렬 실행에서 불안정한 세션 재개 테스트
모의 백엔드 기록은 모든 테스트가 공유합니다. 재개 응답을 기다리는 동안 다른 테스트가 기록을 추가하면 마지막 항목이 다른 세션의 설정일 수 있습니다. 모의 클라이언트 인스턴스마다 기록을 분리하세요.
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>
| assert!( | ||
| cmd.program == "bwrap" || cmd.program.ends_with("/bwrap"), | ||
| "the launcher is the sandbox: {}", | ||
| cmd.program | ||
| ); |
There was a problem hiding this comment.
🔍 백엔드 PATH를 덮어쓰는 세션 시작 테스트가 없음
이 테스트는 bwrap이라는 이름도 허용하고 백엔드 환경을 적용하지 않습니다. 백엔드 PATH에 bubblewrap이 없어도 세션 실행이 성공하는지 회귀 테스트로 확인할 필요가 있습니다.
Was this helpful? React with 👍 or 👎 to provide feedback.
| crate::backend::registry::which("bwrap") | ||
| .map(|p| p.to_string_lossy().into_owned()) | ||
| .unwrap_or_else(|| "bwrap".to_string()) |
There was a problem hiding this comment.
🟥 작업공간의 파일이 샌드박스 런처로 실행됨
데몬의 PATH에서 찾은 상대 경로는 세션 실행 시 작업공간 기준으로 해석됩니다. 이 경우 신뢰할 수 없는 저장소의 파일이 검사를 통과한 bubblewrap 대신 샌드박스 밖에서 실행될 수 있습니다.
Was this helpful? React with 👍 or 👎 to provide feedback.
Follow-up to #60 (merged into
mainas 2f52012), which landed the first cut of #33 while the review fixes for it were still being written. This branch is those fixes, rebased ontomain— each one is a case where the merged policy could break a session or be quieter than it claims.What it fixes
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 atbwrap: Can't mkdir parents for …, whiledamond doctorand 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/tmptmpfs, so a host that cannot set the recipe up fails atdoctorrather than at the first turn./, which the policy refuses as a writable root — underautothe model/mode picker would have come back with only "auto". Those probes answermodel/listand start no turn, so they are explicitly unconfined, the same rule the discovery probe already follows.[backends.X].envstate overrides were invisible to the policy.backend_state_dirsread the daemon's environment, but the child is launched with the backend's — soCODEX_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.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 benone. The mode now rides the session row (sessions.sandbox, ALTER migration + the in-memory schema) and is re-applied on every reattach. Asandboxthat is present but not a string answers-32602instead of being dropped by the optional-field rule, which would have handed a client that asked to be confined an unconfined session.[backends.X].env— those spawns passed an empty env map, so aCLAUDE_CONFIG_DIRoverride 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 aPATHin that env block cannot leave the launcher, or the binary the probe validated, unresolved.SandboxUnsupported, so the wire answersnot_supportedrather 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: nullstays equivalent to omitting the param;docs/protocol-v2.mdanddocs/protocol-v2.ko.mdgain thesession.createparam; 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, andsession.createpersists the mode and the reattach path hands it back — an explicitnonesession 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) andmcp_probe(needsnode).Still open, worth a decision
tests/sandbox_bwrap.rsskips on every leg — the Linux leg exercises the compiler but never the sandbox. The one-line change (test job + coverage job):workflowspermission.sandboxyet (optional, so behavior is unchanged).Refs #33, #60