Skip to content

feat(security): exec_capture caps + timeout primitive (v0.2.0 subprocess hardening) - #17

Merged
thehoff merged 8 commits into
developfrom
feat/sec-exec-capture-limits
May 18, 2026
Merged

thehoff merged 8 commits into
developfrom
feat/sec-exec-capture-limits

Conversation

@thehoff

@thehoff thehoff commented May 18, 2026

Copy link
Copy Markdown
Owner

Summary

Generalises the v0.1.6 tirith-gate hardening pattern (b4c93c3) to the central exec_capture primitive in src/core/stream.rs. First v0.2.0 ROADMAP item: subprocess timeouts everywhere.

Three Codex review rounds; final state addresses all blockers.

What lands

Commit What
6916ee2 docs(security): subprocess-timeout audit across all production sites — docs/security/AUDIT-subprocess-timeouts.md enumerates every prod subprocess call site by latency-policy class
bdc39a7 fix(security): exec_capture stdout/stderr cap + optional wall-clock timeout (F-01/F-02/F-04) — new CaptureLimits, exec_capture_with_limits, exec_capture_short
51d6fcf fix(security): bound git rev-parse fallback in PreToolUse hook (F-02) — hooks/permissions.rs uses exec_capture_short(_, 10s) for the git rev-parse --show-toplevel fallback
ff4408e docs(roadmap): reconcile v0.1.6/v0.1.7 — v0.1.6 actually shipped both items v0.1.7 was listed for
361da5d docs(security): expand subprocess audit with Codex re-grep findings — Codex round-1 found 4 sites the original audit missed (F-06 to F-09)
a0c2585 fix(security): exec_capture truncation contract + Codex-requested edge tests — Codex round-2 #3 + #6
0788beb fix(security): fail-loud truncation warning in exec_capture wrappers (Codex round-2 blocker)
4009c0e fix(security): caller-side truncation guards (Codex round-3 blocker) — summary.rs, prisma_cmd.rs (3 sites), pnpm_cmd.rs (3 sites)

Threat model

exec_capture is the central choke point — 18 modules go through it. v0.1.6 fixed the tirith gate's specific instance; this generalises:

  • stdout/stderr caps (default 64 MiB) — runaway children get SIGPIPE rather than OOMing the host
  • Optional wall-clock timeout — for hook-path callers that must not freeze the agent
  • Truncation contract — CaptureResult.truncated_{stdout,stderr} flags so parse-heavy callers can bail rather than parse a capped prefix
  • Fail-loud wrapper warnings — [ctxc] warning: ... — capture truncated emitted from the convenience wrappers
  • Per-caller guards — summary.rs, prisma_cmd.rs, pnpm_cmd.rs now fall back to raw passthrough on truncation rather than parse wrong counts

Test plan

  • cargo build — clean
  • cargo test — 2003 pass / 6 ignored / 0 fail
  • Codex review: round-1 + round-2 + round-3, all blockers addressed
  • Tests cover: short-deadline timeout, normal-path no-op, stdout cap, stderr cap, exact-EOF boundary, 1ms deadline race, 0-byte cap, stderr-only flood completion, kill-on-exited-child, drain_with_cap unit tests, truncation flag set/clear, warn_if_capped no-op path

🤖 Generated with Claude Code

thehoff and others added 8 commits May 18, 2026 15:26
Maps every Command::new() call site by latency-policy class:
hook-blocking (aggressive timeout), user-driven filter (cap only),
internal short-lived (soft deadline). Documents F-01/F-02/F-04 plus
two accepted limitations (F-03 covered transitively by F-01 cap;
F-05 `--shell` passthrough out of scope by design).

First v0.2.0 ROADMAP item. Code change lands in follow-up commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…imeout (F-01/F-02/F-04)

Adds CaptureLimits, exec_capture_with_limits, and exec_capture_short
in src/core/stream.rs. Spawns + drains stdout/stderr concurrently in
threads (avoids the pipe-buffer deadlock the tirith hardening avoided
via Stdio::null on stderr — exec_capture must keep stderr because
filters depend on it).

Defaults: 64 MiB cap per stream, no wall-clock timeout. Matches the
ceiling used by the tirith gate (`b4c93c3`). Existing exec_capture
keeps its signature and delegates to the limited variant with
defaults — no caller change required for the 18 modules that go
through it.

exec_capture_short is the hook-path convenience: caller supplies the
deadline, timeout returns Err so callers can fall back the same way
tirith_gate::check does.

6 new unit tests cover: short-deadline timeout, normal-path no-op,
stdout cap, stderr cap (independent), default-path unchanged, and
CaptureLimits::default values. Suite: 1842 → 1848 passing.

See docs/security/AUDIT-subprocess-timeouts.md for the policy rationale.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
find_project_root falls back to `git rev-parse --show-toplevel` when
the directory walk for .claude/ misses. That fallback runs in
Claude Code's PreToolUse path — a stalled git (dead NFS, hung FUSE,
unhealthy network mount) would freeze the agent until CC's own
timeout fires.

Switches the call to exec_capture_short with a 10s budget. Timeout
→ Err → existing `.ok()?` short-circuit treats it as "no project
root", same as today's "git failed" path.

Closes F-02 from AUDIT-subprocess-timeouts.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rogress

v0.1.6 actually shipped both items that were originally listed under
v0.1.7 (global-filter trust H-3 via 52b475e+97fe98e, tirith subprocess
timeout F-01 via b4c93c3). Mark v0.1.6 shipped, v0.1.7 unscoped, and
the v0.2.0 Global TOML filter trust item closed.

Subprocess-timeouts-everywhere updated to point at the new audit doc
and reflect that the central exec_capture primitive now has the
hardening — remaining work is per-caller routing decisions only.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Original cut grepped only Command::new and trusted the v0.1.6 overnight
summary on what was already hardened. Codex review of the first commit
re-grepped over .output() / .status() / .spawn() on helper-returned
Command values and found:

- F-06 (HIGH): src/analytics/security_cmd.rs::{fetch_audit_stats,
  fetch_doctor_status} are NOT actually hardened. No run_tirith_capture
  helper, no wait_timeout import — bare Command::new(bin).output().
  v0.1.6 overnight summary doc claimed the hardening landed; the code
  shows otherwise. Same failure mode the project memory rule
  "verify-code-not-subjects" covers. Fix lands in its own branch.

- F-07 (LOW): aws_cmd, go_cmd, git commit bypass exec_capture's cap
  via direct cmd.output(). User-driven (class B) so no wall-clock
  deadline appropriate; stdout cap would still apply if routed
  through the new primitive. git commit needs stdin(Stdio::inherit())
  for $EDITOR which exec_capture nulls — solve per-caller.

- F-08 (LOW): main.rs:1301 TOML-match filter dispatch — same shape.

- F-09 (info): main.rs:2711 rtk web curl — not capped at spawn layer
  but curl's --max-time 30 / --max-filesize 64M bound the work
  in-process (v0.1.6 web hardening). Acceptable as is.

Updated TL;DR and Method to reflect the expanded surface. The
"Recommended changes" section still describes what THIS branch ships;
F-06/F-07/F-08 are tracked for follow-up branches.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…e tests

Addresses Codex round-2 review findings on the exec_capture hardening
branch:

Truncation contract (Codex finding #3):
- Add truncated_stdout / truncated_stderr bools to CaptureResult.
  Silent truncation was a real API ambiguity — callers parsing JSON
  on a capped prefix would treat parse failures as real errors.
- New drain_with_cap helper reads at most `max` bytes then peeks one
  byte to detect whether the stream had more pending. Detection is
  exact: a stream that ends precisely at the cap reports
  truncated=false (no false positives at exact-EOF boundary).
- exec_capture_with_limits propagates both flags through.

Edge cases (Codex finding #6):
- truncated flag set/clear at boundary (3 tests including exact-EOF
  no-false-positive)
- very-short deadline race (1ms) — either Ok or Err is acceptable,
  no panic/hang/orphan
- cap-of-0 pathological config — child still runs, output empty,
  flag set if child wrote anything
- stderr-only flood completes without stdout-drain deadlock
  (validates the threaded-drain design holds when one stream is dead)
- kill-on-already-exited-child does not surface as error (back-to-back
  short calls confirm no leftover state from unused timeout-error path)
- drain_with_cap helper unit tests for the truncation peek logic

Suite: 1848 → 1856 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…(Codex round-2 blocker)

Codex round 2 flagged a real semantic gap: the truncated_stdout /
truncated_stderr flags from CaptureResult exist but no production
caller checks them. summary.rs, curl_cmd.rs, prisma_cmd.rs, git.rs,
pnpm_cmd.rs all print or parse capped output without knowing it was
truncated — silent data corruption.

Adds a fail-loud `[ctxc] warning: ... — capture truncated` to stderr
from inside the exec_capture / exec_capture_short wrappers. The
warning mirrors the existing RAW_CAP messages in run_streaming
(stream.rs:333/342) for consistency.

Sophisticated callers that want silence — because they're going to
inspect the flags programmatically — should call
exec_capture_with_limits directly, which stays quiet.

Net effect: all 18 modules using exec_capture get the safety net for
free, no caller migration needed. The truncated_stdout/_stderr flags
remain authoritative for callers that want to act on them.

Suite: 1856 → 1857 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codex round-3 review of the exec_capture work identified that the
wrapper-level fail-loud warning (commit 4be2f3b) was necessary but
not sufficient for parse-heavy callers. PARSE consumers operate on
the truncated prefix and silently report wrong counts / structures,
even after seeing the stderr warning.

Three sites identified by Codex round-3:

1. src/cmds/system/summary.rs — synthesises a heuristic summary from
   raw output. A capped prefix would mislead `summarize_tests` /
   `summarize_build` line counts. Now prepends an explicit
   `[!] OUTPUT TRUNCATED — ...` marker line so the summary cannot be
   read as authoritative.

2. src/cmds/js/prisma_cmd.rs (3 call sites — run_generate, run_migrate,
   run_db_push) — each calls `exec_capture` then text-parses the
   output for migration counts, table changes, etc. Added a
   `passthrough_if_truncated` helper that emits the raw prefix with a
   stderr warning and skips the parser when either flag is set.

3. src/cmds/js/pnpm_cmd.rs (3 call sites — run_list, run_outdated,
   run_install) — same pattern. JSON / tabular parsers would
   produce wrong dependency counts on truncated input. Same helper
   (file-local — kept the two near-identical 17-line copies to avoid
   exporting a public API that bleeds the truncation contract into
   every caller's signature; revisit if a 4th caller appears).

Net result: at the 64 MiB default cap, all 6 parser callers now
fall back to raw passthrough rather than emitting confidently-wrong
filter output. The wrapper warning in core/stream.rs still fires so
the user sees the truncation message even when the caller path
catches it.

cargo test: 2003 pass / 6 ignored / 0 fail.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thehoff
thehoff merged commit ffff68d into develop May 18, 2026
4 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