Repository navigation
security(agent): encode advisory command arguments as bash argv tokens (#2347) - #2435
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
Sorry @EffortlessSteven, you have reached your weekly rate limit of 500000 diff characters.
Please try again later or upgrade to continue using Sourcery
|
Warning Review limit reached
Next review available in: 22 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
WalkthroughThe shared ChangesAdvisory command shell quoting
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Code Review
This pull request updates the ripr advisory command string generation to encode arguments as single-quoted bash tokens instead of double-quoted ones, preventing unintended shell expansions and correctly handling special characters. The feedback highlights two valid issues: first, reusing shell_arg for formatting Rust code examples in fixtures results in invalid Rust syntax (single quotes for string literals); second, the temporary directories created during round-trip tests can leak if the tests return early, which can be resolved using an RAII guard.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Decision
- Needs reviewer attention before upstream: findings remain.
Confirmed findings
- shell_arg is now reused to format Rust string-literal examples in fixtures (assertion_shape.example, evidence-quality-benchmark sample.source). After switching to single-quote encoding, fixtures now contain
authenticate('')and'ok'which are invalid Rust (single quotes are char literals). Stop reusing shell_arg for Rust code generation; introduce a dedicated Rust string quoter. shell_argis now reused to format Rust source examples, but Rust char literals are single-quoted single chars.'tmp root'and'gap 1'and the assertion target'ripr agent start --root tmp\ root --packet gap\ 1'are not valid Rust and the blessed corpus will mislead any downstream tool that treats the sample as compilable Rust. Either introduce a separaterust_argquoting helper or revert these fixture strings to double-quoted form. Mirrors gemini-code-assist[bot] comment on loop_commands.rs:228.- assertion_shape.example now contains authenticate('') which is invalid Rust (empty char literal). Either add a Rust string escaper distinct from shell_arg, or post-process the example field to keep double quotes. Documented as a sibling-helper gap.
- Mechanical single-quote flip rewrites embedded judge narrative. The text was originally
match='Invalid key: "invalid key"'; it is nowmatch='Invalid key: 'invalid key''. The new form parses as two adjacent strings (Invalid key: invalid key) if pasted, and the recorded review text no longer matches the original pytest.raises call. Confirm each affected reason string was human-checked, not bulk-substituted. - shell_arg_round_trips_through_real_bash leaks temp dir on early-return: if any iteration returns Err OR if bash lookup is None the round_trip_dir is never removed_dir_all'd. Each cargo test run accumulates stale ripr-shell-arg--argv/redirect dirs. Wrap dir in a Drop guard (RAII) or move cleanup into a single end-of-test block before each Err return path. Comment-raised by gemini-code-assist on the same line.
- Both new bash tests (shell_arg_round_trips_through_real_bash and redirect_shaped_gap_id_cannot_open_a_second_redirect) leak their tempdir on every early-return path. Wrap dir in a TempDirGuard (Drop calls remove_dir_all) so cleanup runs on scope exit; also covers panics inside the for loop.
Confirmed findings
- No native/unsafe code path touched; unsafe-review sensor reports 0 new_gaps/0 worsened. Allocation-failure analysis not raised by this diff (format! on owned String, no Box::from(slice), no Vec::from). Defer if raised later.
- fixtures/python-judged-pr-panel/scaled-judged.json and ts_repair_packet_complete free-text prose fields had quote characters inside JSON strings rewritten to single quotes (e.g.
'invalid key'insidematch=...). JSON parser-tolerant but a human reading the prose may notice the cosmetic change; goldens should be re-blessed with a recorded reason. - TEMP_DIR cleanup is only invoked on the happy path of shell_arg_round_trips_through_real_bash and redirect_shaped_gap_id_cannot_open_a_second_redirect. If
bash_for_round_tripreturns Some and then a per-value iteration Errs, the early return path beforeremove_dir_allleaks per-PID temp dirs in /tmp. RAII guard recommended by gemini-code-assist still unaddressed.
Verification questions
- Confirm tests spawn bash via Command::new with owned PathBuf and ad-hoc temp dir; round_trip_dir/redirect-clobber tests only remove_dir_all on Ok path — early Err leaks the temp dir. No UB, but the leak is a gemini review-comment observation, not a lifetime issue.
- Confirm gemini review-comment #2: round-trip and redirect tests leak tempdir on early return (bash_for_round_trip returns None → Ok early; or a hostile-value check returns Err early). The remove_dir_all is at the end of Ok(()) and before early return Errs.
Verification questions
[review body truncated; see review artifacts]
[review body truncated; see review artifacts]
#2347) `ripr` publishes advisory command strings for a human or an agent to copy into a shell. Every argument was wrapped in double quotes, which does not make a value inert: bash still expands `$VAR`, `$(cmd)`, and `` `cmd` `` inside double quotes. The encoder also left a bare `\` unquoted, and emitted the empty string as nothing at all, so an empty argument silently vanished from the command line. The concrete harm: these commands already end in `> out.json`, so a gap id shaped like `gap:pr:1 > /path/file` supplied a second redirect. Copying the command truncated a file the operator never named and changed the id the command actually received. Replace the encoder with a total single-quote form: unambiguous values pass through unquoted, everything else is `'...'` with an embedded `'` rendered as `'\''`. Single quotes are the only bash quoting form with no interior interpretation, so one rule covers `$`, backtick, `!`, `\`, newline, and redirect characters. Note that escaping `!` inside double quotes would have made things worse, not better: `\!` is literally backslash-bang in a non-interactive shell. Route the two remaining hand-quoted call sites -- the TypeScript and Perl repair-packet receipt commands -- through the same encoder instead of interpolating into `--verify-cmd "{}"`. Proof is a real shell, not an assumed shape: 19 hostile values (empty, spaces, backslashes, both quote kinds, `$VAR`, `$(cmd)`, backticks, `!`, newlines, redirect-shaped ids, `;`, `|`, `&&`, glob, tilde, leading dash) are encoded, executed by bash, and compared byte for byte, plus a test that a redirect-shaped gap id cannot truncate an unintended file. Two details that string assertions would have missed: `bash.exe` on Windows is often WSL bash, which cannot open a host path, so the probe confirms the candidate can actually run a script; and passing the script with `-c` routes it through argv joining and MSYS re-parsing, so it is written to a file instead. The scratch directory is owned by an RAII guard so it is removed on every early return and on panic. Ordinary commands are unchanged -- values made only of unambiguous characters are still emitted unquoted. Only fixtures whose command strings are actually produced by the encoder move. Fixtures carrying Rust or Python source examples, recorded judge narrative, or a receipt command passed through verbatim from an input ledger (`receipt_command_source: gap_ledger.receipt_command`) keep their original quoting.
9441ac7 to
b4e31ec
Compare
Both review findings were correct; fixed in
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/ripr/src/agent/loop_commands.rs`:
- Around line 461-469: Update the round-trip validation around the bash
invocation to expose and validate the argument count separately from stdout
contents. Make the test script print the received argv count, parse that count
from the command output, and require exactly one argument before comparing the
newline-normalized received value with value; preserve the existing diagnostic
context in errors.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 922ac6ad-eeb6-4dd8-92b4-95313def79cb
📒 Files selected for processing (18)
CHANGELOG.mdcrates/ripr/src/agent/loop_commands.rscrates/ripr/src/app/agent_status.rscrates/ripr/src/lsp/tests.rscrates/ripr/src/output/first_pr.rscrates/ripr/src/output/perl_gap_record_projection.rscrates/ripr/src/output/receipt_write.rscrates/ripr/src/output/typescript_packet_projection.rsfixtures/boundary_gap/expected/llm-work-loop/path-with-spaces/review-summary.jsonfixtures/evidence-promotion-honesty-corpus/corpus.jsonfixtures/first_successful_pr/boundary-gap/expected/start-here.jsonfixtures/first_successful_pr/boundary-gap/expected/start-here.mdfixtures/first_successful_pr/output-contract-gap/expected/start-here.jsonfixtures/first_successful_pr/output-contract-gap/expected/start-here.mdfixtures/ts_repair_packet_complete/expected/CHANGELOG.mdfixtures/ts_repair_packet_complete/expected/check.jsonfixtures/ts_repair_packet_complete/expected/human-full.txtpolicy/process_allowlist.txt
🔗 Linked repositories identified
CodeRabbit considers these linked repositories for cross-repo context during reviews:
EffortlessMetrics/ripr(auto-detected)EffortlessMetrics/em-ci(auto-detected)EffortlessMetrics/perl-lsp(auto-detected)EffortlessMetrics/unsafe-review(auto-detected)EffortlessMetrics/ub-review(auto-detected)
The round-trip oracle compared only the bytes bash received, and the comment claimed that proved "exactly one argument". It did not: a value split across two argv entries prints the same stdout as a single entry containing a newline, so the `line one\nline two` case could not be distinguished from a split. Bind the encoded token with `set --` and print `$#` before the value, so the argument count is checked separately from the bytes. Verified against a deliberately unquoted encoder: the empty value now reports 0 arguments, which the byte comparison alone could never surface.
The round-trip oracle was weaker than its comment claimed — fixed in
|
Replaces #2386. Built clean on current
main(4ca7ad13) — no patch script, no transformation workflow, no proof carried over from the superseded encoder.Problem
riprpublishes advisory command strings for a human or an agent to copy into a shell. Every argument was wrapped in double quotes, which does not make a value inert — bash still expands$VAR,$(cmd), and`cmd`inside double quotes.The concrete harm: these commands already end in
> out.json, so a gap id shaped likegap:pr:1 > /path/filesupplies a second redirect. Copying the command truncates a file the operator never named, and changes the id the command actually receives.Why not the #2386 encoder
That draft added
$,`, and!escapes to the double-quoted form. I did not carry it forward, because it has three defects that all look correct as string assertions:\was in the pass-through safe seta\bemitted unquoted; bash consumes the backslashvalue.chars().all(..)on""\!inside double quotesChange
A total single-quote encoder. Unambiguous values pass through unquoted; everything else is
'...'with an embedded'rendered as'\''.Single quotes are the only bash quoting form with no interior interpretation at all, so one rule covers
$, backtick,!,\, newline, and redirect characters. The empty string becomes''rather than disappearing.Two remaining hand-quoted call sites — the TypeScript and Perl repair-packet receipt commands, which interpolated into
--verify-cmd "{}"— now route through the same encoder.Proof
A real shell, not an assumed shape. 19 hostile values are encoded, executed by bash, and compared byte for byte:
empty, spaces, backslashes, backslash-separated paths, both quote kinds, adjacent quotes,
$VAR,$(cmd), backticks,!, newlines, redirect-shaped ids,;,|, glob,&&, tilde, leading dash.Plus a test that a redirect-shaped gap id cannot truncate an unintended file — it seeds a victim file, runs the encoded command, and asserts both that the file is untouched and that the id arrived intact.
I verified the proof can fail. Restoring the old double-quote encoder makes the round-trip test fail on
$HOMEexpanding to a real home directory. Without that check the test could have passed vacuously.Two host details it surfaced, both of which would have made the suite lie:
bash.exeonPATHunder Windows is frequently WSL bash. It runs fine but cannot open a drive-letter host path, so a naivebash -c "exit 0"probe would have made every case fail for a reason unrelated to the encoder. The probe now confirms the candidate can actually execute a script from the real directory, and prefers Git Bash resolved fromProgramFilesrather than a hard-coded path.-croutes it through Rust argv joining and then MSYS re-parsing, which rewrote the quoting before bash saw it. The script is written to a file so it reaches bash byte for byte — which is also how these advisory strings are really used.Gates
Local, on this tree:
cargo fmt --checkcargo clippy --workspace --all-targets -- -D warningscargo test -p ripr --lib— 3778 passed, 0 failedcargo xtask precommitcargo xtask goldens checkcargo xtask fixturescargo xtask check-fixture-contractscargo xtask check-process-policycargo xtask check-allow-attributescargo xtask check-generated,check-output-contractspolicy/process_allowlist.txtgains one entry naming the owner and reason for the test-only bash spawns.fixtures/ts_repair_packet_completeis re-blessed with a recorded reason.Review map
crates/ripr/src/agent/loop_commands.rscrates/ripr/src/output/typescript_packet_projection.rsshell_argcrates/ripr/src/output/perl_gap_record_projection.rspolicy/process_allowlist.txtScope
Ordinary commands are unchanged — values made only of unambiguous characters are still emitted unquoted. The published shape changes only where a value genuinely needs quoting.
One pre-existing failure is visible on Windows only and is not touched here:
diff_json_reports_changed_surface_before_full_repo_contextassertssrc/lib.rsand getssrc\lib.rs. It reproduces identically onmainwithout this change. It is the class #2393 tracks — Linux-only continuous CI cannot see it.Closes #2347.