Repository navigation
fix(hooks): close plain (...) and brace { ...; } bypass in gateguard destructive scan - #1912
Conversation
PR affaan-m#1905 (the maintainer batch that integrated affaan-m#1889) added `scripts/lib/shell-substitution.js` and exported `extractCommandSubstitutions` from it, but `gateguard-fact-force.js` still ships its own private copy of the same function — the original I extracted into the lib. With both files in `main`, the private copy in gateguard is now dead duplication. This commit removes the private definition and imports the lib version. No public behavior change in the regression suite: - gateguard's existing 72 tests pass unchanged - the existing destructive cases (rm -rf, git push --force, dd if=, drop table, $(...) and backtick subshells) still flag correctly - the existing allow cases (echo, ls) still pass One small semantic improvement comes free: the lib version maintains quote state inside the `$(...)` depth-counting loop (added in affaan-m#1889 round 1), whereas the private copy did not. In practice this is masked by `explodeSubshells` running as a second pass, so existing tests already exercise the destructive cases that quote-tracking would otherwise catch; the lib version is just the cleaner of the two implementations. The remaining destructive-bash blind spots — plain `(...)` and brace `{ ...; }` group bodies — are addressed in the next two commits.
Sibling extractor for `extractCommandSubstitutions` and
`extractSubshellGroups`, completing the set of grouping constructs
bash supports that can hide commands from naive segment splitters.
Recognition matches bash's actual reserved-word semantics, not just
literal `{`/`}` matching:
- `{` opens a group only when followed by whitespace AND preceded by
the line start, whitespace, or a shell operator (`;`, `|`, `&`, `(`).
So `{npm run dev}` is NOT a brace group (single token), and
`foo{` is not either (token continuation, not a reserved word).
- `}` closes the group only when preceded by `;` or whitespace.
So `${foo}` and `array}` inside the body are not closing braces.
- Single quotes and double quotes are literal for `{`/`}` (bash does
not recognize `{ ...; }` inside either kind of quoted string).
- `$(...)`, backticks, and plain `(...)` spans are skipped during
the scan so the sibling extractors can own those bodies.
No consumer yet; the next commit wires this into
`scripts/hooks/gateguard-fact-force.js` alongside
`extractSubshellGroups` to close the brace-group destructive bypass
(`{ rm -rf /tmp/x; }`).
Test fixtures verifying the recognition rules in the next-but-one
commit; lib-level unit coverage to follow as part of a separate
`tests/lib/shell-substitution.test.js` if reviewers prefer.
…e scan
Before this commit, `isDestructiveBash` only looked inside `$(...)`
and backtick command substitutions (via `extractCommandSubstitutions`).
Two other shell grouping constructs that execute their bodies were
not opened up:
(rm -rf /tmp/x) ← plain subshell — bypassed
((rm -rf /tmp/x)) ← nested subshell — bypassed
{ rm -rf /tmp/x; } ← brace group — bypassed
(git push --force origin main)
{ git push --force origin main; }
(echo y; (rm -rf /tmp/x)) ← nested subshell with destructive inside
Reproduced against `main` (commit 375d750):
$ cat > /tmp/probe.js <<... # load gateguard, call isDestructiveBash
$ node /tmp/probe.js
allowed | "(rm -rf /tmp/x)"
allowed | "((rm -rf /tmp/x))"
allowed | "{ rm -rf /tmp/x; }"
allowed | "(git push --force origin main)"
allowed | "{ git push --force origin main; }"
This affects every destructive classifier in this hook — the rm
detector, the git-force detector, and the SQL/dd regex — because
they all run downstream of the same `splitCommandSegments` pass and
that pass never saw the inner segments.
Fix: introduce `collectExecutableBodies(raw)`. A BFS that harvests
`raw` plus every body returned by `extractCommandSubstitutions`,
`extractSubshellGroups`, and the new `extractBraceGroups`,
recursively (cross-syntax: `(... $(...) ...)` and friends), bounded
by a `seen` set. Feed the resulting body list into the existing
`splitCommandSegments` flatMap, then run the existing per-segment
destructive classifiers unchanged. The classifiers themselves
require no edits — they just get more segments to look at.
After this commit, all six lines above return DESTRUCTIVE. The 72
existing gateguard regression tests still pass.
Regression tests for the newly closed bypass forms in the next
commit. The legitimate-allow cases that must NOT regress (literal
inside quotes, `(echo hello)`, `(npm test)`, etc.) are also covered
there explicitly to lock in the quote-awareness boundary.
13 new cases lock in the behavior added by the previous commit.
Each was verified to fail before the fix and pass after.
Newly blocked (exit destructive):
(rm -rf /tmp/junk)
((rm -rf /tmp/junk))
{ rm -rf /tmp/junk; }
(git push --force origin main)
{ git push --force origin main; }
(echo y; { rm -rf /tmp/junk; }) — cross-syntax () containing {}
$(echo y; (rm -rf /tmp/junk)) — cross-syntax $() containing ()
Negative coverage — explicitly asserted NOT to regress, since the
new group-body walker is the easiest place to leak false positives:
git commit -m '(rm -rf /tmp/junk)' — single-quoted literal
echo "(rm -rf /tmp/junk)" — double-quoted literal
echo "{ rm -rf /tmp/junk; }" — double-quoted brace literal
(echo hello) — non-destructive subshell
{ echo hello; } — non-destructive brace group
echo {rm -rf /tmp/junk} — no-space form, not a brace group
The no-space case is intentional: bash treats `{rm` as a single
token rather than as a `{` reserved word, so the body never runs
at runtime. Recognising it would be over-conservative.
Test suite count: 72 → 85 in gateguard-fact-force.test.js.
|
ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughThe PR expands destructive-command detection in the GateGuard hook by adding brace-group parsing to the shell-substitution library and changing the hook to breadth-first collect and scan executable bodies from command substitutions, subshells, and brace groups; tests are added to cover nested and edge-case brace/subshell scenarios. ChangesExpanded Shell Syntax Parsing for Destructive Command Detection
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
scripts/hooks/gateguard-fact-force.js (1)
319-344: 💤 Low valueMinor:
bodiesmay contain duplicates across BFS paths.The
seenset guards against reprocessing the same body, butbodies.push(body)runs unconditionally each time a body is extracted. If the same body string is produced by two different extraction paths (e.g., nested(...)containing a duplicate of an outer$(...)body), it is appended multiple times. This is purely wasted work in the downstreamflatMap(splitCommandSegments)— correctness is unaffected because the destructive checks are pure functions of the segment — but you could gate the push onseen.has(body)for a tighter loop.♻️ Optional dedup at push time
while (queue.length) { const current = queue.shift(); if (seen.has(current)) continue; seen.add(current); for (const body of extractCommandSubstitutions(current)) { + if (seen.has(body)) continue; bodies.push(body); queue.push(body); } for (const body of extractSubshellGroups(current)) { + if (seen.has(body)) continue; bodies.push(body); queue.push(body); } for (const body of extractBraceGroups(current)) { + if (seen.has(body)) continue; bodies.push(body); queue.push(body); } }🤖 Prompt for 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. In `@scripts/hooks/gateguard-fact-force.js` around lines 319 - 344, The function collectExecutableBodies currently pushes each extracted body into bodies and queue unconditionally, causing duplicates across different BFS paths; update the loops over extractCommandSubstitutions, extractSubshellGroups, and extractBraceGroups so that for each extracted body you first check seen.has(body) and only if false do you call bodies.push(body) and queue.push(body) (keeping seen logic unchanged) to avoid duplicate entries that downstream flatMap(splitCommandSegments) would reprocess.tests/hooks/gateguard-fact-force.test.js (1)
1285-1296: 💤 Low valueMinor:
((...))is arithmetic evaluation, not a nested subshell.The cohort comment and the test label ("nested
((...))subshell") describe((...))as a nested subshell, but in bash((expr))is the arithmetic-evaluation construct — at top level it would try to evaluaterm,-rf,/tmp/junkas arithmetic tokens and fail rather than executingrm. The current parser still depth-tracks it as nested parens and produces a destructive verdict, which is a fine conservative behavior, but the comment misleads future readers about why this case is gated. Consider rewording to "nested parens (e.g.((...))) treated conservatively" or similar so the safety-vs.-semantics distinction is documented.🤖 Prompt for 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. In `@tests/hooks/gateguard-fact-force.test.js` around lines 1285 - 1296, The comment and test label incorrectly describe the `((...))` construct as a nested subshell; update the cohort comment and the test description string used in the two test cases (the `'denies rm -rf inside nested ((...)) subshell'` test and the surrounding comment block) to correctly note that `((...))` is arithmetic evaluation and is being treated conservatively (e.g., "nested parens / arithmetic ((...)) treated conservatively" or "arithmetic ((...)) treated conservatively") so readers understand we're gatekeeping for safety rather than documenting actual subshell semantics.
🤖 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.
Nitpick comments:
In `@scripts/hooks/gateguard-fact-force.js`:
- Around line 319-344: The function collectExecutableBodies currently pushes
each extracted body into bodies and queue unconditionally, causing duplicates
across different BFS paths; update the loops over extractCommandSubstitutions,
extractSubshellGroups, and extractBraceGroups so that for each extracted body
you first check seen.has(body) and only if false do you call bodies.push(body)
and queue.push(body) (keeping seen logic unchanged) to avoid duplicate entries
that downstream flatMap(splitCommandSegments) would reprocess.
In `@tests/hooks/gateguard-fact-force.test.js`:
- Around line 1285-1296: The comment and test label incorrectly describe the
`((...))` construct as a nested subshell; update the cohort comment and the test
description string used in the two test cases (the `'denies rm -rf inside nested
((...)) subshell'` test and the surrounding comment block) to correctly note
that `((...))` is arithmetic evaluation and is being treated conservatively
(e.g., "nested parens / arithmetic ((...)) treated conservatively" or
"arithmetic ((...)) treated conservatively") so readers understand we're
gatekeeping for safety rather than documenting actual subshell semantics.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: f82adaef-e2f5-4b4f-919b-ecaf40e21b6a
📒 Files selected for processing (3)
scripts/hooks/gateguard-fact-force.jsscripts/lib/shell-substitution.jstests/hooks/gateguard-fact-force.test.js
Greptile SummaryThis PR closes two shell-grouping bypass surfaces in the
Confidence Score: 5/5Safe to merge — the change tightens the destructive-command gate without loosening any existing checks, and the round-1 review edge cases are now addressed in code and covered by dedicated tests. The BFS walker and extractBraceGroups are additive, security-tightening changes. Quote handling, span-skipping, and boundary detection all match bash semantics. The previous review concerns about premature } termination and missing nested-{ boundary checks have been addressed. The 85-test suite directly covers the bypass table and round-1 edge cases. No files require special attention. Important Files Changed
Reviews (2): Last reviewed commit: "test(hooks): coverage for brace-group sp..." | Re-trigger Greptile |
… scan
Greptile flagged two logic gaps in `extractBraceGroups`:
1. The body-accumulation loop did not skip `$(...)` / `(...)` /
backtick spans before counting `}` depth decrements. With the
existing strict `}` rule (closing only when preceded by `;` or
whitespace), the `$()` and `()` cases happen not to misfire in
practice — but the **backtick** case does:
{ echo `echo }`; rm -rf /tmp/x; }
The `}` inside the backtick body is preceded by a space, so
under the old code it satisfied the close rule and terminated
the brace group early. Body extracted: `" echo `echo "`.
In `gateguard-fact-force.js` this never manifested as a real
destructive bypass because `explodeSubshells` runs as a second
pass and unwraps backtick bodies into top-level segments anyway.
But the lib itself was buggy, and any future consumer without
that backup pass (e.g. `pre-bash-dev-server-block.js`) would
inherit the gap.
2. The nested `{` depth check did not apply the same "preceded by
a boundary" rule as the outer scan. Tokens like `foo{` in
`{ x foo{ ; rm -rf; }` would happen to be safe under the
existing whitespace-after-`{` rule, but the inconsistency was
real and worth fixing.
Fix: in the body-accumulation loop, walk past `$(...)`, `(...)`,
and backtick spans as opaque chunks (with their own quote-state
tracking, mirroring the outer scan), and require nested `{` to
satisfy the same `prevIsBoundary` rule.
After this commit:
IN: { echo `echo }`; rm -rf /tmp/x; }
→ body: " echo `echo }`; rm -rf /tmp/x; "
IN: { echo $(echo "}"); rm -rf /tmp/x; }
→ body: " echo $(echo \"}\"); rm -rf /tmp/x; "
The 85 existing gateguard regression tests still pass; lib-level
regression cases for the new spans are added in a follow-up commit.
CodeRabbit nitpick (low value but cheap): `seen` only guards against re-queueing the same body, not against re-pushing it into the flat `bodies` list. When the same body is reached via two different BFS paths (e.g. one extractor's internal recursion plus a cross-syntax sibling), it appeared in `bodies` twice and was fed through `splitCommandSegments` twice. Correctness was unaffected because the destructive classifiers are pure, but the duplicate work was real. Fix: hoist the `seen.has(body)` check ahead of `bodies.push` in each extractor loop, so a body is pushed at most once total. This is the cleanup I noted in the PR affaan-m#1889 round-1 reply re: BFS redundancy — best handled here, alongside the gateguard consolidation, because the two share the same BFS shape. No behavior change; 85 gateguard tests still pass.
5 new regression cases lock in the brace-group span-skip behaviour
added in the previous lib commit:
{ echo `echo }`; rm -rf /tmp/junk; } — backtick body with }
{ echo $(echo "}"); rm -rf /tmp/junk; } — $() body with }
{ (echo "}"); rm -rf /tmp/junk; } — () body with }
{ x=$(echo a}b); rm -rf /tmp/junk; } — $() body with }
{ echo foo{bar; rm -rf /tmp/junk; } — foo{ token, not nested {
Each was verified to fail (body extracted early, destructive
classifier never sees `rm -rf`) before the lib fix, and to pass
after.
Also addresses CodeRabbit's `((...))` label nitpick: bash's
`((expr))` is the arithmetic-evaluation construct, not a nested
subshell. The parser depth-tracks it conservatively (the inner
tokens are still scanned), but the cohort comment and test label
previously called it a "nested subshell" — misleading future
readers about why the case is gated. Updated the comment and the
test name to describe it as "arithmetic eval, treated
conservatively".
Test suite count: 85 → 90 in gateguard-fact-force.test.js.
|
ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR. |
Summary
scripts/hooks/gateguard-fact-force.jsopens up$(...)and backtick command substitutions before running its destructive classifiers, but two other shell grouping constructs that execute their bodies are not opened up: plain(...)subshells and{ ...; }brace groups. This PR closes both.Bypass surface (reproduced on
mainat 375d750)rm -rf /tmp/x(rm -rf /tmp/x)((rm -rf /tmp/x)){ rm -rf /tmp/x; }(git push --force origin main){ git push --force origin main; }(echo y; { rm -rf /tmp/x; })$(echo y; (rm -rf /tmp/x))Affects every destructive classifier —
isDestructiveRm,isDestructiveGit, theDESTRUCTIVE_SQL_DDregex — because they all run downstream of the samesplitCommandSegmentspass and that pass was never given the inner segments.Fix
A small BFS (
collectExecutableBodies) walks the raw command and harvests every body returned by the three sibling extractors inscripts/lib/shell-substitution.js:extractCommandSubstitutions($(...), backticks) — existingextractSubshellGroups(plain(...)) — added in PR fix(hooks): close subshell bypass in pre-bash-dev-server-block #1889 / fix: integrate recent hook and docs PRs #1905extractBraceGroups({ ...; }) — new in this PRThe harvested bodies are fed into the existing
splitCommandSegmentsflatMap; the per-segment classifiers themselves require no edits.extractBraceGroupsrecognises bash's actual reserved-word semantics ({must be followed by whitespace and preceded by line start / whitespace /;/|/&/(;}must be preceded by;or whitespace) so{npm run dev}does not trigger (single token, no executable body at runtime), andecho "{ rm -rf; }"stays allowed (bash does not honour brace groups inside double quotes).Commit layout
Split into four reviewable commits:
refactor(hooks): import extractCommandSubstitutions from shared libDrops gateguard's private 99-line duplicate of the function now that PR fix: integrate recent hook and docs PRs #1905 landed
scripts/lib/shell-substitution.jsonmain. The 72 existing gateguard tests pass unchanged.feat(lib): add extractBraceGroups for { ...; } shell groupsSibling to
extractSubshellGroups. No consumer yet.fix(hooks): cover plain (...) and brace { ...; } bodies in destructive scanWires both new extractors plus
extractCommandSubstitutionsthrough a BFS walker. This is the behaviour change.test(hooks): regression coverage for subshell + brace destructive bypass13 new cases — 7 newly-blocked, 6 explicitly-allowed (literals in quotes, non-destructive groups, the no-space brace edge case).
Tests
node tests/hooks/gateguard-fact-force.test.js— 85/85 (was 72/72)yarn lintcleanyarn testgreen locallyProvenance
Direct follow-up to PR #1889 (closed; integrated via #1905). In that PR I noted: "consolidating both call sites onto this shared lib is a follow-up worth doing once this PR lands". This is that follow-up. The
extractCommandSubstitutionsduplication is gone; gateguard now benefits from the same quote-state tracking the PR #1889 round-1 review added to the lib.Test plan
Summary by cubic
Closes a bypass in the gateguard destructive scan by inspecting bodies inside plain subshells
( ... )and brace groups{ ...; }, and fixes brace-group parsing so nested spans can’t hide destructive commands. This blocks hiddenrm -rf,git push --force, and similar commands nested in these groups.Bug Fixes
collectExecutableBodies) and feed them intosplitCommandSegments, covering(...),((...)), and{ ...; }across nesting.extractBraceGroupsto skip$(...), backticks, and(...)spans and to enforce the nested-{boundary rule, preventing early-close cases like{ echo \echo }`; ... }`.Refactors
extractCommandSubstitutions; addextractBraceGroupsand wire it withextractSubshellGroups.Written for commit 873fbad. Summary will update on new commits.
Summary by CodeRabbit