Repository navigation
fix(discover): count sudo RTK_DISABLED=1 commands as bypass in analytics - #3808
Conversation
KuSh
left a comment
There was a problem hiding this comment.
Thanks — the bug is real and the direction is right, but the new sudo prefix regex makes a flag-arity assumption that reintroduces the same false negative it's meant to fix, so requesting changes.
Three correctness items inline, plus a cargo fmt failure.
Design note: rather than a second regex sitting next to ENV_PREFIX, consider teaching ENV_PREFIX (registry.rs:69) itself to tolerate sudo flags — it already alternates on sudo\s+. Doing it there fixes both orderings in one place and fixes classify_command, which today returns Unsupported { base_command: "-E docker" } for sudo -E docker ps. So flagged-sudo commands are currently missing from the supported/rewrite side of rtk discover, not just from the bypass counter.
Scope note: please keep the arg parsing here deliberately shallow — no sudo option table, no flag/value arity map. #3681 is landing a shared CLI-arg tokenizer for exactly that job, and duplicating a mini-parser here will only have to be torn out. This fix just needs to stop swallowing tokens it can't identify.
|
Fixed the sudo parsing issues from the review, including flags with values and RTK_DISABLED before sudo. Added regression coverage for both command detection and analytics tuples. Formatting and clippy pass, the full Linux unit suite passes with 2,930 tests, and the focused regressions pass. The only Linux integration failure locally is the existing unwritable-directory test because this WSL run is root, so chmod does not make the directory unwritable. |
KuSh
left a comment
There was a problem hiding this comment.
Round 2 on b7a642c. The four threads from the first round are fixed and resolved — the flag-arity guess is gone, both orderings work, the returned tuple is no longer mangled, and the full gate is green on my machine (cargo fmt --all -- --check, cargo clippy --all-targets, cargo test --all). Thanks for reusing lexer::tokenize rather than growing a second regex, and for keeping the sudo option table out of it.
The new heuristic overshoots in the other direction, though. It never misses a bypass relative to strip_disabled_prefix — the returned prefix always spans the RTK_DISABLED= token, and it falls back to the old helper otherwise — but it now invents bypasses that aren't there. Three inline, each verified by running strip_disabled_prefix_for_analytics / cmd_has_rtk_disabled_prefix on this head:
| input | reported as | reality |
|---|---|---|
RTK_DISABLED=1 ssh host docker ps |
docker bypass, suggests rtk docker ps |
runs on a remote host, RTK can't apply |
sudo -E docker run -e RTK_DISABLED=1 img npm run build |
npm bypass |
container env var, npm runs inside the container |
sudo -E ls && docker run -e RTK_DISABLED=1 img git status |
git bypass |
detection crossed a && |
The third one is the one with teeth: src/discover/mod.rs:101 is protected because it calls split_command_chain first, but src/analytics/gain.rs:674 passes the whole unsplit line to cmd_has_rtk_disabled_prefix, so this inflates the rtk gain "used RTK_DISABLED=1 unnecessarily" percentage that gates the >10% warning.
On scope / #3681: the loop is now doing the two things a real arg tokenizer does — deciding whether a token is a flag's value or a command word, and where the argument list ends. That's exactly #3681's job, and I'd rather not have a second implementation of it here. But #3681 is still a draft with changes requested, so I don't think this should sit and wait on it. My suggestion is to make this round deliberately narrower rather than smarter:
- bail out entirely if any token before
disabled_indexis notTokenKind::Arg; - drop the
saw_sudo && saw_sudo_flagcatch-all — accept onlysudo,env,KEY=VALUEand-flagsin the prefix, and give up on anything else; - stop at the first command-word candidate after the prefix instead of scanning forward until something classifies as
Supported.
That fixes the bug you set out to fix, keeps every false positive above out, and leaves a small enough surface that swapping in #3681's tokenizer later is a rewrite of ten lines rather than an untangling. Happy to be argued out of it if you see a case the narrow version misses.
Address rtk-ai#3808 review: only accept sudo/env/KEY=VALUE/-flag wrappers, never search past non-Arg tokens for RTK_DISABLED=, and stop at the first command word instead of scanning into wrapper arguments. Fixes false positives from docker -e, && chains, ssh/xargs/watch, and value-taking sudo flags like -u root.
b7a642c to
f274d9e
Compare
|
Round-2 review items should now be addressed on the latest head (narrow prefix: only |
KuSh
left a comment
There was a problem hiding this comment.
Round 3 of 3 — CHANGES REQUESTED
Claim: rtk discover / rtk gain should count sudo RTK_DISABLED=1 <cmd> as an RTK bypass (#3756).
Scope: accept if narrowed to "peel the wrapper so the bypass can be detected, but ask the coverage counterfactual about the command the user actually typed — so a wrapped bypass is counted only when hooks.transparent_prefixes really makes that wrapper rewritable, and gain's ungated predicate stays syntactic". (Rounds 1-2 predate this template; verdict stated now, frozen from here.)
Ran: rtk discover --all --format json and rtk gain end-to-end through the real ClaudeProvider on synthetic Claude sessions (CLAUDE_CONFIG_DIR, hook registered in settings.json), two binaries built from c75f1590 (develop) and f274d9eb with separate CARGO_TARGET_DIRs (md5 c25843e1… vs 006742ca… — differ). 28-case curated matrix + 264-case generated sweep (17 wrappers × 8 commands × both orderings), each case in its own session file, each scored against the oracle rtk rewrite "<line minus the RTK_DISABLED= token>"; 9 extra edge cases on both consumers. Invariants: every branch of the new decision (wrapper-run, non-Arg break, no-match fallback, supported/unsupported command word), both orderings, under the hook (rtk rewrite on all 264 — 0 differences ref↔head, the rewrite path is untouched), both consumers (discover and gain), and the config axis (default vs transparent_prefixes = ["sudo", "sudo -E"]). Savings floor: N/A — this is a meta-command report, there is no producer output being compressed.
Matrix: never executed on this PR before — running now (rounds 1-2 probed the helper in unit tests only, which is why CI has been green through a 70-case false-positive regression).
CI @f274d9eb: all green, 11/11 including all three OS runners. Local gate green on the head and on the head merged onto c75f1590 (076b536e): fmt / clippy / test --all all exit 0.
Blocks merge (1, new — it is what the matrix found)
-
src/discover/mod.rs:381— the counterfactual is asked about a command the user never typed (1 call site; the helper itself is fine). The peel handswould_be_covered_without_bypassthe stripped remainder, so the gate answers fordocker pswhen the line wassudo docker ps.rewrite_commandrefuses sudo by design (#146,test_rewrite_sudo_passthrough), so for every sudo form the real counterfactual is false — droppingRTK_DISABLED=1recovers nothing.Evidence, default config, 264 generated lines scored against
rtk rewrite:false positives missed develop 0 72 this PR 70 72 PR + the fix in finding 2 0 72 On the 28-case matrix
rtk discovergoes 7 → 14 andrtk gain39% → 57%, and not one of the 7 new lines is a real bypass:sudo RTK_DISABLED=1 docker ps counted → docker ps | rtk rewrite "sudo docker ps" → (nothing) sudo -E RTK_DISABLED=1 docker ps counted → docker ps | rtk rewrite "sudo -E docker ps" → (nothing) RTK_DISABLED=1 sudo docker ps counted → docker ps | rtk rewrite "sudo docker ps" → (nothing) RTK_DISABLED=1 sudo -E docker ps counted → docker ps | rtk rewrite "sudo -E docker ps" → (nothing) sudo FOO=1 RTK_DISABLED=1 cargo test counted → cargo test | rtk rewrite "sudo FOO=1 cargo test" → (nothing) env -i RTK_DISABLED=1 docker ps counted → docker ps | rtk rewrite "env -i docker ps" → (nothing) sudo -E RTK_DISABLED=1 -H docker ps counted → docker ps | rtk rewrite "sudo -E -H docker ps" → (nothing)What the user is shown:
RTK_DISABLED BYPASS -- 14 commands ran without filtering These commands used RTK_DISABLED=1 unnecessarily: docker ps (10x), cargo test (2x), git log (1x), make CC=gcc (1x) -> Remove RTK_DISABLED=1 to recover token savingsTwo problems compound: the savings don't exist, and
truncate_command(actual_cmd)has erased thesudo, so the example is a command that was never run. develop reported these honestly inTOP UNHANDLEDassudo …. The hook's own #508 warning agrees with develop:rtk rewrite "sudo RTK_DISABLED=1 docker ps"prints nothing, whilertk rewrite "RTK_DISABLED=1 docker ps"prints[rtk] RTK_DISABLED=1 detected …— so analytics would now count bypasses the runtime doesn't consider bypasses.This is the exact failure class
would_be_covered_without_bypasswas introduced to prevent (its own doc comment, #3206 review).The same mechanism, not sudo-specific — all new, all with an empty
rtk rewrite:foo=bar RTK_DISABLED=1 git status develop 0 → PR 1 (ENV_PREFIX requires [A-Z_][A-Z0-9_]*=) RTK_DISABLED=1 x=y=z git status develop 0 → PR 1 -x RTK_DISABLED=1 git status develop 0 → PR 1 RTK_DISABLED=1 -- git status develop 0 → PR 1Worth stressing: the fix is not to tighten the allowlist further. With the counterfactual asked correctly, every line above goes back to 0 with the allowlist exactly as you wrote it — the gate already knows what the hook would do, including the user's
transparent_prefixes.
Optional — will not hold merge
-
One verified way to fix 1 (inline on
registry.rs:665, full diff there). Indiscover/mod.rs, hand the gate the line with only theRTK_DISABLED=assignments dropped fromenv_prefix— wrapper intact. Inregistry.rs, putcmd_has_rtk_disabled_prefixback onstrip_disabled_prefix: its only caller isgain's >10% warning, which has no coverage gate, so a wrapper-aware peel there can only inflate the number (measured: themod.rshunk alone leavesgainat 57%). Any fix that asks the gate about the typed line is equally fine; this one is here so you can compare.discover (default) discover ( transparent_prefixes = ["sudo","sudo -E"])gaindevelop 7 7 — misses the real bypasses 39% this PR 14 ✗ 14 ✗ 57% ✗ PR + this diff 7 ✓ 12 ✓ 39% ✓ The right-hand column is the PR's goal, reached: for a user who declared
sudotransparent the bypass really is recoverable, and only then is it counted. fmt / clippy /test --allall exit 0 with it applied. -
The new guards are unpinned, which is why CI stayed green through all 70. Mutating the pre-match
breakon a non-Argtoken tocontinueleaves the whole registry suite green; so does dropping the post-matchbreak,|| value.contains('='), and|| value == "env". The test commented "do not look past&&" passes for an unrelated reason —lsis a non-wrapper command word, so the function early-returns before the loop ever reaches the&&.sudo -v && RTK_DISABLED=1 docker ps(a common idiom) is the shape that actually exercises it. And the whole 14 → 7 behaviour change in finding 2 breaks no existingdiscovertest. -
sudo -u rootis asymmetric, and it is my doing.sudo -u root RTK_DISABLED=1 docker ps→ not detected; the mirrorRTK_DISABLED=1 sudo -u root docker ps→gaincounts it whilediscoverdrops it, so the warning's "runrtk discoverfor details" points at a report that doesn't contain it. Measured identical on develop, this PR and the patch — pre-existing, not yours. Round 1 had this case working; my round-2 wording ("accept onlysudo/env/KEY=VALUE/-flags") is what removed it. Keeping it out is the right trade for now, and it is noted in the rewritten #3756, not something you owe.
Filed as follow-ups
- #3756 corrected — that one was on me. I wrote it, and its premise was wrong: it read #2810's removal of
sudofromENV_PREFIXas an "analytics blind spot", but #2810 also means the hook no longer rewritessudo …, so there is nothing to count unless the user declared the wrapper transparent. It also asked for the peel "at the two consumer sites", which is the half that inflatesgain. You implemented what it asked for, including its test list, faithfully. The issue now describes thetransparent_prefixescounterfactual and the tests that go with it. - #4278:
RTK_DISABLED=after a wrapper the hook does rewrite through is never counted —nice docker ps→nice rtk docker ps, andrtk rewrite "nice RTK_DISABLED=1 docker ps"prints the #508 warning itself, yet analytics counts it on neither develop nor this PR (72 of 264 in the sweep). That is the genuine under-count in this family. - #4277:
gain's bypass warning has no coverage gate at all, so it over-counts on develop too (RTK_DISABLED=1 xargs -n1 git showis counted;rtk rewrite "xargs -n1 git show"is empty). Pre-existing; finding 2 only stops this PR widening it.
Checked and correct — no need to re-verify
- The rewrite path is untouched:
rtk rewritebyte-identical across all 264 cases, develop ↔ head.strip_disabled_prefixitself unchanged, and the new test pinningstrip_disabled_prefix("sudo RTK_DISABLED=1 docker ps") == ("", …)is exactly the right guard. - All three round-2 blockers are genuinely fixed, by mechanism: the forward scan no longer latches onto an argument (
ssh/xargs/watch/./deploy.shall fall back), thesaw_sudo && saw_sudo_flagcatch-all is gone (sudo -E docker run -e RTK_DISABLED=1 …→ not detected), and the scan stops at the first non-Argtoken (sudo -E ls && docker run -e RTK_DISABLED=1 …→ not detected). Verified end-to-end, not just in the unit tests. - Reusing
discover::lexer::tokenizeis the right call..claude/rules/rust-patterns.mdrule 6 points atcore::arg_tokenizer, but that takes an already-split argv slice with a per-tooltakes_valuegrammar; a raw transcript command line islexer.rs's job. Citing rule 6 here would be wrong. (It is the tool for the-u rootsub-problem in finding 4, if that ever comes back.) cargo fmt --all --check,cargo clippy --all-targets,cargo test --all: green on the head and on the head merged onto current develop.
Hypotheses built and dropped
- The token allowlist needs tightening for
-x/foo=bar/--. Dropped: with the counterfactual asked correctly all of them return 0 with the allowlist untouched. The looseness is only reachable because the gate was being asked the wrong question. contains_unattestable_constructmight already refuse sudo. Dropped by reading and by execution: it covers substitutions and file redirects only, and the 7 sudo lines sail through the gate.rtk gainmight be shielded likediscoveris. Dropped:gaincallscmd_has_rtk_disabled_prefixon whole unsplit lines with no gate, measured 39% → 57%.
Your questions
- "Value-taking sudo flags like
-u rootare also out of scope with this shallow parse, which matches the review guidance." → Agreed, and it was my guidance. Confirmed out of scope; it is finding 4 above, not something you owe. One correction: the mirrorRTK_DISABLED=1 sudo -u root …isn't symmetric with it, but that is pre-existing on develop, so still not yours.
Next
Fix finding 1 — the diff in finding 2 is one verified way, your own take is just as welcome — and this merges: CI is already green and everything else in the PR is verified correct. The follow-ups are filed and are not yours.
Keep wrappers (sudo/env/transparent_prefixes) when asking whether the hook would have rewritten the line without RTK_DISABLED=. Peel only the RTK_DISABLED= assignments for that gate; leave gain on the syntactic strip_disabled_prefix so it does not inflate without a coverage check. Addresses KuSh round-3 CHANGES_REQUESTED on rtk-ai#3808.
|
Addressed round-3 finding 1 on 71d74f4 (same approach as the optional diff in the review): the coverage counterfactual keeps the wrapper the user typed, and |
A segment carrying `RTK_DISABLED=` whose peeled command rtk supports is now judged in one place, `judge_disabled_segment`, against one line: the segment with its `RTK_DISABLED=` word removed and every other word kept, wrapper included. It is a bypass when the hook would have rewritten that line. Otherwise that same line goes through the normal classification, like the command typed without the assignment. Before, the bypass check asked about the line with its wrapper while the fall-through asked hook coverage about the peeled command, so `sudo RTK_DISABLED=1 docker ps` was reported as hook coverage of `docker ps` although the hook never rewrites `sudo`. Words are split as the rest of discover splits them (lexer tokens coalesced into shell words), so a quoted or expanded value is removed whole. The peel's tests now also cover an assignment after `sudo`, `env` after `sudo`, and an operator after wrapper-only words, and its comments no longer say `gain` uses it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
KuSh
left a comment
There was a problem hiding this comment.
Round 4 (landing) — APPROVED
Claim: rtk discover counts an RTK_DISABLED= placed behind a sudo / env / assignment wrapper as a bypass when the hook would really have rewritten the command the user typed.
Scope: accept if narrowed to "peel the wrapper to detect the bypass, ask the coverage gate about the line the user typed" (round 3, frozen) — met.
Ran: rtk discover --format json and rtk gain end-to-end through the real ClaudeProvider on synthetic Claude sessions with the hook registered, on develop 083a9c5d, 71d74f4b merged onto develop, and the fixup merged onto develop (distinct binaries, md5-checked). 264-line generated sweep (17 wrappers × 8 commands × both orderings) under two configs — default, and hooks.transparent_prefixes = ["sudo", "sudo -E"] — each line scored against rtk rewrite of the line without its RTK_DISABLED= word; a 15-line matrix of every outcome a line can get (bypass, hook coverage, supported miss, unsupported) per config; the 28-line set and 9 edge lines from round 3; rtk rewrite byte-identical develop ↔ PR on all 264 lines in both configs. 12 mutations of the new code, each failing a named test. Savings floor: N/A (meta command).
Matrix: executed round 3, rerun on this head and on the fixup.
CI @71d74f4b: 11/11 green. @2d37b2de4: 11/11 green.
Blocks merge
-
→ fixed insrc/discover/mod.rs:381— the bypass counterfactual was asked about a command the user never typed71d74f4b: 0 false positives on 264 lines in either config (round 3: 70),discover7 / 12 on the 28-line set (default /sudotransparent; develop 7 / 7),gain39% as on develop. -
New this round, closed by the fixup — and mine. The same mistake at the sibling call site: when the gate says "not a bypass", the fall-through handed
hook_coveragethe peeled command, so a no-op bypass was reported as hook coverage of a command that never ran through rtk. Round 3 named only one call site, and the diff I posted there fixed only that one.default config develop 71d74f4bfixup same line without RTK_DISABLED=sudo RTK_DISABLED=1 docker psunhandled hook coverage unhandled unhandled env -i RTK_DISABLED=1 git statusunhandled hook coverage unhandled unhandled RTK_DISABLED=1 sudo docker psnot reported hook coverage unhandled unhandled RTK_DISABLED='1 2' docker psbypass hook coverage bypass — With
sudodeclared transparent, the sudo lines are bypasses on71d74f4band on the fixup alike.
Fixup 2d37b2de4 — pushed, code-reviewed
- A segment carrying
RTK_DISABLED=whose peeled command rtk supports is judged once, byjudge_disabled_segment, against one line: the segment with itsRTK_DISABLED=word removed and every other word kept. A bypass when the hook would rewrite that line; otherwise that same line is classified like any other command — which is what the table above checks against the line typed without the assignment. - The word is removed as a whole shell word (lexer tokens coalesced, as elsewhere in discover), so
RTK_DISABLED='1 2'andRTK_DISABLED=$CIgo whole andFOO='a b'stays verbatim. - Tests:
test_disabled_segment_is_judged_as_typed_without_the_bypasstakes its inputs from the peel and fails if the gate or the fall-through gets the peeled command, if the assignment is kept, or if the wrapper is dropped;test_without_rtk_disabled_keeps_every_other_wordpins the word removal. The peel's tests now coversudo FOO=1 RTK_DISABLED=1 …,sudo env RTK_DISABLED=1 …andsudo -v && RTK_DISABLED=1 …, so each of its four guards fails a test when mutated (round-3 optional 3); three passed the suite before, and one silently dropped 7 real bypasses withsudotransparent. - Comments no longer say
gaingoes through the peel.
Filed as follow-ups
- #4278 —
RTK_DISABLED=after a wrapper the hook rewrites through (nice,timeout,command) is never counted: 72 / 264, same as develop. - #4277 —
gain's bypass warning has no coverage gate (pre-existing). - #3756 — rewritten around the
transparent_prefixescounterfactual; this PR implements it. - #4412 — with
sudotransparent,RTK_DISABLED=$CInext tosudois not detected: the peel splits the word at$. A missed count, as on develop.
Checked and correct — no need to re-verify
- Rewrite path untouched:
rtk rewriteidentical develop ↔ PR, 264 lines × 2 configs. gainunchanged from develop:cmd_has_rtk_disabled_prefixstays onstrip_disabled_prefix, pinned bytest_cmd_has_rtk_disabled_prefix.cargo fmt --check,clippy --all-targets,test --allgreen on71d74f4bmerged onto develop083a9c5d(4094 tests) and on the fixup merged onto it (4095).
Next
Nothing — approving on 2d37b2de4. Thanks for the quick turnaround on round 3.
Rounds: landing. Threads: 0 open, 3 resolved this round (finding 1 fixed by 71d74f4b, the round-3 diff applied in 71d74f4b, the unpinned guards closed by the fixup).
Resolve conflicts with rtk-ai#3808, which reworked discover's RTK_DISABLED= handling (wrapper-aware `strip_disabled_prefix_for_analytics` and `judge_disabled_segment`). Keep develop's per-segment logic as the one gate and route `line_has_counted_bypass` (gain's count) through it, replacing this branch's own `classify_bypass`. Drop `cmd_has_rtk_disabled_prefix` again: gain was its only caller. Its rtk-ai#3808 regression cases move to `line_has_counted_bypass` tests.
Summary
Adds an analytics-only prefix stripper (\strip_disabled_prefix_for_analytics) that skips a leading \sudo\ (and optional sudo flags like -E) before delegating to the shared \strip_disabled_prefix. This ensures that commands such as \sudo RTK_DISABLED=1 docker ps\ are counted as RTK bypasses in
tk discover\ and
tk gain\ without modifying the shared \strip_disabled_prefix\ used by rewrite routines.
Closes #3756
Validation