Skip to content

PTY child process inherits the daemon environment unsanitized - #1554

Merged
malibio merged 2 commits into
mainfrom
issue-1521-pty-env-allowlist
Jul 6, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-1521-pty-env-allowlist

Conversation

@malibio

@malibio malibio commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

Closes #1521

Spawned agent CLIs (claude, codex, gemini, pi, opencode) previously
inherited the daemon's full environment, exposing any secrets present
there to third-party binaries. CommandBuilder::env_clear() now wipes
the inherited environment before spawn; a fixed base allowlist (HOME,
PATH, TERM, SHELL, LANG, USER) plus each agent's declared auth env vars
are the only variables forwarded, and only when actually set.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a small, well-scoped fix for a real security gap: PTY-spawned agent CLIs previously inherited the daemon's entire environment (confirmed — portable-pty's CommandBuilder::new() defaults to get_base_env(), i.e. std::env::vars_os(), the full parent env). The change replaces that with env_clear() + an explicit allowlist (6 base vars + per-agent auth vars from a new AgentDefinition::auth_env_vars field), verified end-to-end against the portable-pty 0.8.1 source (no re-merge of parent env at spawn time; cwd/envs are independent fields with no ordering hazard; which::which binary resolution is correctly decoupled from the child's runtime env).

I independently re-ran cargo test -p nodespace-agent --lib (264 passed) and cargo clippy -p nodespace-agent --all-targets -- -D warnings -D clippy::unused-async (clean), matching the implementer's report. I also grepped for any other env-manipulation site in pty//acp/ — apply_env_allowlist is the only one, and all launch_for_test/spawn_in_pty callers across the workspace (packages/agent/src/pty/manager.rs, packages/daemon/tests/agent_session_grpc.rs) go through it. This is a net-positive, correctly-targeted fix. No blockers.

Requirements Check

  • PTY children receive an explicit environment allowlist, not the full inherited env — confirmed true end-to-end. apply_env_allowlist calls cmd.env_clear() (a full BTreeMap wipe per portable-pty source) then repopulates only BASE_ENV_ALLOWLIST + auth_env_vars from std::env::var, with missing vars silently skipped (not passed through empty). spawn_command builds the child strictly from self.envs, so nothing outside the allowlist reaches the child.
  • Code passes bun run quality:fix; tests pass — implementer reports full workspace test:all green (966+ Rust, 147 frontend files, one known-flaky unrelated perf test that passed on retry); I independently reproduced the narrower cargo test -p nodespace-agent --lib (264 passed) and clippy-clean results myself.

Findings

Critical Issues

None.

Suggested Improvements

  • packages/agent/src/pty/session.rs:64 (BASE_ENV_ALLOWLIST) — Consider adding TMPDIR. Node/Bun-based CLI tooling (claude, codex, opencode all plausibly ship Node/Bun-based binaries or subprocesses) sometimes uses TMPDIR for scratch files, and its absence means every agent silently falls back to the OS default temp dir rather than whatever the daemon's environment specifies. This isn't function-breaking (graceful degradation), so it's an improvement, not a blocker.
  • packages/agent/src/pty/session.rs:768-792 (unlisted_env_var_does_not_reach_pty_child) — std::env::set_var/remove_var mutate true process-global state, and remove_var runs only in the test body after assertions are queued, not in a Drop guard or finally-equivalent. If collect_output/await_exit ever panicked or timed out between set_var and remove_var, NODESPACE_TEST_SECRET_1521=should-not-leak would leak into the rest of that test binary's process env for any later test run in the same process. Low risk given the unique key name and that this is a #[cfg(test)]-only module in a single crate, but wrapping the var lifetime in a small RAII guard (struct EnvVarGuard that removes on Drop) would make this test panic-safe for free. Same applies to apply_env_allowlist_forwards_extra_vars_when_present at line 821-837.

Nitpicks

  • Nit: packages/agent/src/pty/session.rs:64 — USER and SHELL in BASE_ENV_ALLOWLIST are plausible but likely dead weight for these 5 CLIs, none of which are interactive shells themselves. Not worth blocking on — harmless to include, and erring toward "forward a few extra environment-identity vars" is a reasonable default for a security-sensitive allowlist where the failure mode of omission (broken CLI) is worse than the failure mode of inclusion (non-secret metadata).
  • Nit: packages/agent/src/pty/session.rs:206 (#[allow(clippy::too_many_arguments)]) — CLAUDE.md's "no lint suppression" rule is aimed at suppressing lints that flag real bugs or genuine code smells (unused vars, dead code, correctness lints). too_many_arguments on a fn that is pub(crate)-effectively-private (only called from launch() and in-file tests), already well-documented with a doc comment explaining why it exists (split out of launch for testability), and where the alternative (bundling 8 positional args into a SpawnParams struct for a single production call site) is speculative generality that YAGNI argues against — this reads as a defensible, narrow exception rather than a rule violation. If a second production call site or a 9th parameter shows up, that's the trigger to introduce the params struct; premature bundling now would be over-engineering for a private helper.
  • Nit: packages/agent/src/acp/registry.rs:37 — auth_env_vars values aren't derived from any documented spec (as the issue itself acknowledges is best-effort), so minor omissions (e.g. Codex might also read a CODEX_API_KEY-style var in some configs, unverified) are plausible but not worth chasing without a documented source of truth per CLI.

Answers to the specific review questions

  1. Base allowlist: Correct core set (HOME, PATH, TERM, LANG are all load-bearing for a functioning CLI in a PTY). USER/SHELL are nice-to-have, not clearly load-bearing, but harmless. TMPDIR is the one plausible gap worth adding (see Improvements above); NO_COLOR/FORCE_COLOR/COLORTERM/LC_ALL omissions are cosmetic-only and fine to skip.
  2. Auth env var catalog: Plausible and consistent with each CLI's publicly documented auth mechanism. The Pi/OpenCode "union of all four provider keys" approach is a reasonable simplification for multi-provider tools rather than trying to detect which provider is active.
  3. Test quality: The three regression tests are sound, not vacuous. unlisted_env_var_does_not_reach_pty_child genuinely exercises the production apply_env_allowlist call path via launch_for_test → real PTY spawn → real env dump — if env_clear() were reverted, the secret would appear in env output and the test would fail. The collect_output/await_exit helpers are pre-existing, already used by ~10 other tests, and wait on real signals (broadcast + watch channel) rather than racing sleeps, so no new flakiness introduced. unsafe { set_var/remove_var } is required syntax under this edition of Rust and is the only way to do this in a test; the cleanup-on-panic gap noted above is real but low-severity given process/key isolation.
  4. #[allow(clippy::too_many_arguments)]: Defensible narrow exception, not a violation of the project's no-suppression rule in spirit — see Nitpicks above for full reasoning.
  5. Security gap check: No casing/alt-name/wildcard bypass found — apply_env_allowlist only ever calls std::env::var(key) for the literal strings in BASE_ENV_ALLOWLIST and auth_env_vars; there's no prefix or pattern matching anywhere that could accidentally admit an unlisted var. For the overlap question: if a future agent's auth_env_vars included "PATH" by mistake, BASE_ENV_ALLOWLIST.iter().chain(extra_vars) would yield PATH twice, and cmd.env(key, value) (backed by a BTreeMap, confirmed via the vendored source) simply overwrites the existing entry with the same value — no panic, no duplicate entry, functionally a no-op. Safe by construction.
  6. Other observations: None beyond what's captured above. The diff is atomic (single concern: env sanitization), doesn't bundle unrelated changes, and the doc comments on BASE_ENV_ALLOWLIST, apply_env_allowlist, and AgentDefinition::auth_env_vars clearly explain the "why" (security boundary) rather than just the mechanics — good maintainability signal for a security-sensitive code path future editors need to understand quickly.

Recommendation

APPROVE. This closes a genuine, previously-confirmed security gap with a minimal, correct, well-tested change. No critical or blocking issues found. The two Suggested Improvements (TMPDIR addition, RAII guard for test env vars) are worth a fast follow-up but do not need to gate this merge — the core security property (secrets no longer reach PTY children) is fully achieved and independently verified at both the source-analysis level and by re-running the test suite.

@malibio

malibio commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Review recommendation: APPROVE. (Note: gh pr review --approve was rejected by GitHub — "Can not approve your own pull request" — since this session is authenticated as the PR author. Recording the approval decision here as a comment instead; a maintainer/different account should cast the formal approving review before merge.)

- Added TMPDIR to BASE_ENV_ALLOWLIST — some Node/Bun-based agent CLIs
  rely on it for scratch files; the daemon-side value is safe to forward
  and costs nothing to include.
- Replaced raw set_var/remove_var pairs in tests with an EnvVarGuard
  that removes the var on Drop, so a panic mid-test no longer leaks a
  fake env var into later tests in the same process.

Skipped (non-blocking, judged not worth the change): USER/SHELL in the
base allowlist being unused by the current 5 agent CLIs — harmless to
keep, and useful if a future agent CLI's shell-out behavior needs them.

Addresses reviewer recommendations from PR #1554 review.
@malibio

malibio commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback

Both non-blocking suggestions from the review were applied in 474913f:

  • ✅ Added TMPDIR to BASE_ENV_ALLOWLIST — some Node/Bun-based agent CLIs use it for scratch files; low cost to include.
  • ✅ Replaced raw set_var/remove_var pairs in the two tests that mutate process env with an EnvVarGuard (RAII, cleans up on Drop even on panic).

Skipped: none — both suggestions were small and cheap enough to just do.

cargo test -p nodespace-agent --lib (264 passed), quality:fix, and test:all (via pre-push hook) all pass.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: Both changes are minor, low-risk, mechanical (one const addition, one test-only refactor with no behavior change to production code). No new functionality, no architectural changes, no critical/important findings were in play — the original review already recommended APPROVE. Ready for merge pending maintainer approval (self-approval is blocked by GitHub for the PR author).

@malibio
malibio merged commit 920e5cf into main Jul 6, 2026
@malibio
malibio deleted the issue-1521-pty-env-allowlist branch July 6, 2026 20:51
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.

PTY child process inherits the daemon environment unsanitized

1 participant