Skip to content

security(agent): encode advisory command arguments as bash argv tokens (#2347) - #2435

Merged
EffortlessSteven merged 2 commits into
mainfrom
fix/agent-command-bash-argv-encoder-2347
Jul 25, 2026
Merged

EffortlessSteven merged 2 commits into
mainfrom
fix/agent-command-bash-argv-encoder-2347

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Replaces #2386. Built clean on current main (4ca7ad13) — no patch script, no transformation workflow, no proof carried over from the superseded encoder.

Problem

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 concrete harm: these commands already end in > out.json, so a gap id shaped like gap:pr:1 > /path/file supplies 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:

Defect Consequence
\ was in the pass-through safe set a\b emitted unquoted; bash consumes the backslash
value.chars().all(..) on "" vacuously true, so an empty argument emitted nothing and vanished from the command line
\! inside double quotes literally backslash-bang in a non-interactive shell — corrupts the value it claims to protect

Change

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 $HOME expanding 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.exe on PATH under Windows is frequently WSL bash. It runs fine but cannot open a drive-letter host path, so a naive bash -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 from ProgramFiles rather than a hard-coded path.
  • Passing the script via -c routes 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 --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo test -p ripr --lib — 3778 passed, 0 failed
  • cargo xtask precommit
  • cargo xtask goldens check
  • cargo xtask fixtures
  • cargo xtask check-fixture-contracts
  • cargo xtask check-process-policy
  • cargo xtask check-allow-attributes
  • cargo xtask check-generated, check-output-contracts

policy/process_allowlist.txt gains one entry naming the owner and reason for the test-only bash spawns. fixtures/ts_repair_packet_complete is re-blessed with a recorded reason.

Review map

Path What to look at
crates/ripr/src/agent/loop_commands.rs the encoder and its doc comment; the round-trip and redirect-clobber tests
crates/ripr/src/output/typescript_packet_projection.rs receipt command routed through shell_arg
crates/ripr/src/output/perl_gap_record_projection.rs same, Perl side
goldens + fixtures quote-shape only; no semantic movement
policy/process_allowlist.txt one added line

Scope

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_context asserts src/lib.rs and gets src\lib.rs. It reproduces identically on main without this change. It is the class #2393 tracks — Linux-only continuous CI cannot see it.

Closes #2347.

@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.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @EffortlessSteven, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@EffortlessSteven, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 22 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 27a73c93-be58-4b46-9334-32d0d36a819e

📥 Commits

Reviewing files that changed from the base of the PR and between b4e31ec and d6cc75f.

📒 Files selected for processing (1)
  • crates/ripr/src/agent/loop_commands.rs

Walkthrough

The shared shell_arg encoder now emits single-quoted Bash tokens, handles empty and embedded-quote values, and is used by receipt-command projections. Tests, fixtures, changelog entries, and command expectations were updated accordingly.

Changes

Advisory command shell quoting

Layer / File(s) Summary
Single-quote encoder and validation
crates/ripr/src/agent/loop_commands.rs, policy/process_allowlist.txt
shell_arg now encodes empty, hostile, and embedded-quote values with Bash single-quote rules, with direct and Bash round-trip tests plus redirect regression coverage.
Command construction integration
crates/ripr/src/output/perl_gap_record_projection.rs, crates/ripr/src/output/typescript_packet_projection.rs, crates/ripr/src/app/agent_status.rs, crates/ripr/src/lsp/tests.rs, crates/ripr/src/output/first_pr.rs, crates/ripr/src/output/receipt_write.rs
Receipt projections route command values through shell_arg, and generated command expectations use single quotes where quoting is required.
Golden outputs and release notes
CHANGELOG.md, fixtures/..., fixtures/ts_repair_packet_complete/expected/*
Expected advisory commands and release notes record the updated quoting format.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Poem

A rabbit hopped through Bash so bright,
And wrapped each token snug and tight.
No dollar leap, no backtick flight,
Empty strings now show their might.
Safe commands bloom in single-quote light!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: switching advisory command arguments to Bash argv token encoding for security.
Description check ✅ Passed It covers the core template content well, though several sections like source links, rollback, and traceability are omitted.
Linked Issues check ✅ Passed The PR implements the requested single-quote shell escaping, keeps the safe-path fast path, and adds bash byte-exact hostile-value tests.
Out of Scope Changes check ✅ Passed The changelog, fixtures, and policy update all support the quoting fix and test coverage; no unrelated code paths are introduced.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/agent-command-bash-argv-encoder-2347

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread crates/ripr/src/agent/loop_commands.rs Resolved
Comment thread crates/ripr/src/agent/loop_commands.rs Resolved
@codecov

codecov Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.52941% with 28 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/ripr/src/agent/loop_commands.rs 82.92% 28 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions github-actions 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.

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_arg is 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 separate rust_arg quoting 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 now match='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' inside match=...). 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_trip returns Some and then a per-value iteration Errs, the early return path before remove_dir_all leaks 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]

Comment thread crates/ripr/src/agent/loop_commands.rs Resolved
Comment thread crates/ripr/src/agent/loop_commands.rs Resolved
Comment thread crates/ripr/src/agent/loop_commands.rs Resolved
#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.
@EffortlessSteven
EffortlessSteven force-pushed the fix/agent-command-bash-argv-encoder-2347 branch from 9441ac7 to b4e31ec Compare July 25, 2026 07:50
@EffortlessSteven

Copy link
Copy Markdown
Member Author

Both review findings were correct; fixed in b4e31ec4

1. The fixture flip corrupted content that is not encoder output

This was a real defect and the reviewers caught it precisely. I updated the goldens with a line-level text substitution that matched any line containing ripr , which swept in content that has nothing to do with shell quoting:

  • fixtures/evidence-quality-benchmark/corpus.json — a Rust sample became agent_start_command('tmp root', 'gap 1'), which is invalid Rust; single quotes are char literals.
  • fixtures/boundary_gap/expected/evidence-record-contract/corpus.json — assertion_shape.example became authenticate(''), an empty char literal.
  • fixtures/python-judged-pr-panel/scaled-judged.json — human-authored judge narrative. match='Invalid key: "invalid key"' became match='Invalid key: 'invalid key'', which is not the pytest call that was actually reviewed.

All four files are reverted to their pre-PR contents.

One correction to the diagnosis. Several comments infer that shell_arg is now reused to format Rust string literals, and recommend introducing a separate rust_arg helper. That is not what happened — there is no such reuse. Every shell_arg call site builds a shell command (roots, base refs, paths, gap ids); none of them render Rust or Python source. Those fixture strings are static corpus data that my substitution corrupted directly. So no sibling helper is needed here, and no production path emits Rust code through the shell encoder. Worth being explicit, because "add a rust_arg helper" would have added a helper guarding an invariant nothing violates.

2. A fourth file was wrong for a different reason

fixtures/first_successful_pr/typescript-preview-gap/ also reverted, and the test told me why rather than my guessing: the packet reports

"receipt_command_source": "gap_ledger.receipt_command"

That command is passed through verbatim from the input ledger, not produced by the encoder. Re-quoting it would have misrepresented recorded input as generated output. Input and expected both keep their original double-quoted form.

The remaining fixture changes are only those whose command strings the encoder actually produces.

3. Temp directory leak

Correct, and it applied to both bash tests on every early return and on panic, not just the None path. RoundTripDir now owns the directory and removes it in Drop, so cleanup runs on scope exit.

Verification after the fix

  • cargo test -p ripr --lib — 3778 passed, 0 failed
  • cargo fmt --check, cargo clippy --workspace --all-targets -- -D warnings
  • cargo xtask precommit, fixtures, goldens check, check-fixture-contracts, check-generated

Two unrelated failures seen while verifying, neither caused by this PR

  • output::doctor::tests::doctor_test_tool_is_closed_before_its_executable_path_is_published failed once on CI with ExecutableFileBusy, then passed on rerun. Root-caused and filed as Flaky: doctor atomic-publish test lacks the bounded launch retry its sibling has (ExecutableFileBusy) #2441: that test launches once while its sibling carries a bounded retry for exactly this retryable_launch_failure case.
  • lsp::tests::framed_lsp_root_switch_repulls_scoped_to_new_root failed once locally under full parallelism and passes in isolation and on rerun.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 526ab40 and b4e31ec.

📒 Files selected for processing (18)
  • CHANGELOG.md
  • crates/ripr/src/agent/loop_commands.rs
  • crates/ripr/src/app/agent_status.rs
  • crates/ripr/src/lsp/tests.rs
  • crates/ripr/src/output/first_pr.rs
  • crates/ripr/src/output/perl_gap_record_projection.rs
  • crates/ripr/src/output/receipt_write.rs
  • crates/ripr/src/output/typescript_packet_projection.rs
  • fixtures/boundary_gap/expected/llm-work-loop/path-with-spaces/review-summary.json
  • fixtures/evidence-promotion-honesty-corpus/corpus.json
  • fixtures/first_successful_pr/boundary-gap/expected/start-here.json
  • fixtures/first_successful_pr/boundary-gap/expected/start-here.md
  • fixtures/first_successful_pr/output-contract-gap/expected/start-here.json
  • fixtures/first_successful_pr/output-contract-gap/expected/start-here.md
  • fixtures/ts_repair_packet_complete/expected/CHANGELOG.md
  • fixtures/ts_repair_packet_complete/expected/check.json
  • fixtures/ts_repair_packet_complete/expected/human-full.txt
  • policy/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)

Comment thread crates/ripr/src/agent/loop_commands.rs Resolved
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.
@EffortlessSteven

Copy link
Copy Markdown
Member Author

The round-trip oracle was weaker than its comment claimed — fixed in d6cc75fb

This is correct and worth stating plainly: the check compared only the bytes bash received, while the comment asserted it proved "exactly one argument". It did not. printf '%s\n' a b and a single argument "a\nb" produce identical stdout, so the line one\nline two case could not be distinguished from a token split. The comment was making a claim the oracle could not support.

Both bash tests now bind the encoded token with set -- and print $# before the value, so the argument count is checked separately from the bytes:

set -- <encoded>
printf '%s\n' "$#"
printf '%s' "$1"

printf '%s' for the value emits no trailing newline, so the byte comparison stays exact.

Verified the strengthened oracle can fail. Against a deliberately unquoted encoder it now reports:

Error: "empty: encoded value produced 0 arguments, expected exactly 1"

That is a failure mode the previous byte-only comparison could never surface — an empty argument vanishing from the command line produces no bytes either way.

Re-verified after the change: cargo fmt --check, cargo clippy --workspace --all-targets -- -D warnings, cargo test -p ripr --lib (3778 passed, 0 failed), cargo xtask precommit.

@EffortlessSteven
EffortlessSteven merged commit 236df22 into main Jul 25, 2026
22 of 24 checks passed
@EffortlessSteven
EffortlessSteven deleted the fix/agent-command-bash-argv-encoder-2347 branch July 25, 2026 08:27
This was referenced Jul 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

full-ci Run required, advisory, and release-like CI lanes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

security(agent): shell_arg escapes backslash and double-quote but not $, backtick, or ! — partial shell escaping

1 participant