Repository navigation
fix(gateguard): check isDestructiveFindExec on each command segment to close compound-command bypass - #2292
Conversation
`isDestructiveBash` called `isDestructiveFindExec` only on the raw full
command string. When the raw string starts with a non-find command (e.g.
`echo x && find . -exec rm {} \;`), `isDestructiveFindExec` checks
tokens[0] and returns false — then the per-segment loop never calls it
again, letting the destructive `find -exec rm` segment through silently.
Fix: call `isDestructiveFindExec(segment)` inside the per-segment loop so
compound commands (`&&`, `;`, `|`) cannot be used to prepend a harmless
command and bypass the find-exec destructive check.
Adds three regression tests covering `&&`, `;`, and `|` bypass patterns.
📝 WalkthroughSummary by CodeRabbit
Walkthrough
Changesfind -exec destructive bypass fix
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration. 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 |
|
| Filename | Overview |
|---|---|
| scripts/hooks/gateguard-fact-force.js | Refactors the isDestructiveFindExec check in isDestructiveBash to iterate over raw body segments rather than calling it once on the full raw command, closing the compound-command bypass. |
| tests/hooks/gateguard-fact-force.test.js | Adds four regression tests covering the compound-command bypass via &&, ;, |
Reviews (2): Last reviewed commit: "fix(gateguard): use raw body segments fo..." | Re-trigger Greptile
…ose quoted-binary gap
The previous per-segment call passed quote-stripped output from
splitCommandSegments to isDestructiveFindExec, so a quoted exec binary
like find . -exec 'rm' {} \; would arrive as find . -exec {} \; and
the check would silently miss it.
Switch to splitting collectExecutableBodies output on [;|&]+ without
quote-stripping first, so the find-exec binary name is always intact
when isDestructiveFindExec inspects it. This also covers || and
background & separators that the original tests did not exercise.
Adds a regression test for the || OR-chain bypass pattern.
Addresses Greptile review comments on PR affaan-m#2292.
|
Thanks for the review @greptile-apps! Both P2 concerns addressed in the latest commit (a9a45c7): P1 — quoted exec binary false-negative: Confirmed valid. `splitCommandSegments` calls `stripQuotedStrings` internally before splitting, so passing its output to `isDestructiveFindExec` would erase quoted binaries like `'rm'`. Fixed by switching to raw body segments — `collectExecutableBodies` output split on `[;|&]+` without quote-stripping, so the exec binary name is always intact when checked. P2 — `||` separator not tested: Also fixed. The `[;|&]+` split pattern already handled it in the implementation; added a regression test for `false || find . -exec rm {} ;`. All 133 tests pass. |
|
The P2 ( However, P1 is still incomplete. The switch to raw body segments correctly preserves quoted binary names in the string, but Concrete trace: The fix belongs inside const baseCmd = commandBasename(execTokens[0].replace(/^(['"])(.*)\1$/, '$2'));That one-liner handles both assert(isDestructiveBash("find . -exec 'rm' {} \\;"), "quoted exec binary should be blocked");
assert(isDestructiveBash('find . -exec "rm" {} \\;'), "double-quoted exec binary should be blocked");Everything else in the commit looks solid — the Tip: You can customize Greptile's behavior for this repo with |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 `@scripts/hooks/gateguard-fact-force.js`:
- Line 557: The isDestructiveFindExec function on line 557 fails to handle Bash
commands with assignment prefixes like FOO=bar find . -exec rm {} \; because it
checks if the first token is find without skipping leading assignment words.
Update the isDestructiveFindExec function to skip any leading tokens that
contain assignment syntax (tokens with =) before checking if the actual command
basename is find, then search for the -exec flag after that command token to
properly identify destructive find commands regardless of prefix assignments.
- Around line 556-557: The split pattern in the body.split() call on line 556 is
missing newline characters as command separators, allowing destructive commands
separated by newlines to bypass security checks. Update the regex pattern in the
split() method to include newline characters alongside the existing semicolon,
pipe, and ampersand separators so that commands separated by newlines like echo
ok\nfind . -exec rm are properly split into separate segments before being
passed to isDestructiveFindExec. Consider implementing a quote-aware splitting
approach to avoid treating newlines or other separators that appear within
quoted strings as actual command boundaries.
In `@tests/hooks/gateguard-fact-force.test.js`:
- Around line 1631-1634: Add two additional regression test cases following the
same pattern as the OR-chain bypass test at line 1631. Create a new test for the
newline bypass pattern using expectDestructiveDeny with the command string 'echo
ok\nfind . -exec rm {} \;' and a descriptive message like 'Newline bypass: find
-exec rm', and create another test for the assignment-prefix bypass pattern
using expectDestructiveDeny with the command string 'echo ok && FOO=bar find .
-exec rm {} \;' and a descriptive message like 'Assignment-prefix bypass: find
-exec rm'. Both tests should follow the same structure as the existing test with
the conditional increment/decrement of passed/failed counters.
🪄 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: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 9ea93702-16a7-4066-88f0-35a5cd776548
📒 Files selected for processing (2)
scripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.js
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Greptile Review
🧰 Additional context used
📓 Path-based instructions (19)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}
📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}
📄 CodeRabbit inference engine (.cursor/rules/common-security.md)
No hardcoded secrets (API keys, passwords, tokens) - validate before any commit
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}
📄 CodeRabbit inference engine (.cursor/rules/common-security.md)
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}
📄 CodeRabbit inference engine (.cursor/rules/common-security.md)
Use parameterized queries to prevent SQL injection
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}
📄 CodeRabbit inference engine (.cursor/rules/common-security.md)
Implement XSS prevention by sanitizing HTML output
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}
📄 CodeRabbit inference engine (.cursor/rules/common-security.md)
NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)
**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead
**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn aboutconsole.logstatements in edited files
Check all modified files forconsole.logstatements before session ends
**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter:interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects
**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are metUse Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{test,spec}.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test
Files:
tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,json,env*}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Do not hardcode secrets, API keys, passwords, or tokens
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{jsx,tsx,js,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
HTML output must be sanitized where applicable
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,env*}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Required environment variables must be validated at startup
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,go,rs,kt,cpp,c,fs}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.{js,ts,jsx,tsx,py,java,go,rs,kt,cpp,c,fs}: Write tests before implementation using TDD workflow: write failing test (RED), implement minimal code (GREEN), then refactor (IMPROVE)
Keep functions small (<50 lines) and files focused (<800 lines, typical 200-400 lines)
Avoid deep nesting (>4 levels)
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,go,rs,kt}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.{js,ts,jsx,tsx,py,java,go,rs,kt}: Never mutate existing objects; always create new objects with changes applied (Immutability requirement)
Handle errors at every level; provide user-friendly messages in UI code and detailed context in server-side logs
Ensure error messages don't leak sensitive data
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
**/*.{jsx,tsx,html,js,ts}
📄 CodeRabbit inference engine (AGENTS.md)
Sanitize HTML output to prevent XSS vulnerabilities
Files:
tests/hooks/gateguard-fact-force.test.jsscripts/hooks/gateguard-fact-force.js
{package.json,*.config.js,scripts/**/*.js}
📄 CodeRabbit inference engine (CLAUDE.md)
Package manager detection should support npm, pnpm, yarn, and bun, with configuration via CLAUDE_PACKAGE_MANAGER environment variable or project config.
Files:
scripts/hooks/gateguard-fact-force.js
scripts/**/*.js
📄 CodeRabbit inference engine (CLAUDE.md)
Ensure cross-platform support for Windows, macOS, and Linux via Node.js scripts in the scripts/ directory.
Files:
scripts/hooks/gateguard-fact-force.js
{scripts,bin}/**
⚙️ CodeRabbit configuration file
{scripts,bin}/**: Focus on command injection, unsafe subprocess usage, path traversal, SSRF, secret exposure, and missing tests for new CLI behavior.
Files:
scripts/hooks/gateguard-fact-force.js
| for (const rawSeg of body.split(/[;|&]+/).map(s => s.trim()).filter(Boolean)) { | ||
| if (isDestructiveFindExec(rawSeg)) return true; |
There was a problem hiding this comment.
Split raw segments on newlines too.
Line 556 misses Bash newline separators, so echo ok\nfind . -exec rm {} \; stays one segment. isDestructiveFindExec then sees echo as the first token and the destructive find -exec rm bypasses the gate.
Suggested fix direction
- for (const rawSeg of body.split(/[;|&]+/).map(s => s.trim()).filter(Boolean)) {
+ for (const rawSeg of body.split(/[;|&\n]+/).map(s => s.trim()).filter(Boolean)) {
if (isDestructiveFindExec(rawSeg)) return true;
}Prefer a raw, quote-aware splitter if you want to avoid promoting quoted literals while still treating unquoted ;, |, &, and newlines as separators.
🤖 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 556 - 557, The split
pattern in the body.split() call on line 556 is missing newline characters as
command separators, allowing destructive commands separated by newlines to
bypass security checks. Update the regex pattern in the split() method to
include newline characters alongside the existing semicolon, pipe, and ampersand
separators so that commands separated by newlines like echo ok\nfind . -exec rm
are properly split into separate segments before being passed to
isDestructiveFindExec. Consider implementing a quote-aware splitting approach to
avoid treating newlines or other separators that appear within quoted strings as
actual command boundaries.
| const bodies = collectExecutableBodies(raw); | ||
| for (const body of bodies) { | ||
| for (const rawSeg of body.split(/[;|&]+/).map(s => s.trim()).filter(Boolean)) { | ||
| if (isDestructiveFindExec(rawSeg)) return true; |
There was a problem hiding this comment.
Handle assignment-prefixed find commands.
Line 557 still relies on isDestructiveFindExec requiring the first token to be find. A valid Bash segment like FOO=bar find . -exec rm {} \; executes find, but the check sees FOO=bar first and returns false.
Suggested fix direction
- if (isDestructiveFindExec(rawSeg)) return true;
+ if (isDestructiveFindExec(rawSeg)) return true;Update isDestructiveFindExec to skip leading Bash assignment words before checking the command basename, and search -exec after that command token.
🤖 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` at line 557, The isDestructiveFindExec
function on line 557 fails to handle Bash commands with assignment prefixes like
FOO=bar find . -exec rm {} \; because it checks if the first token is find
without skipping leading assignment words. Update the isDestructiveFindExec
function to skip any leading tokens that contain assignment syntax (tokens with
=) before checking if the actual command basename is find, then search for the
-exec flag after that command token to properly identify destructive find
commands regardless of prefix assignments.
| if (test('denies find -exec rm {} \\; after || (OR-chain bypass)', () => { | ||
| expectDestructiveDeny('false || find . -exec rm {} \\;', | ||
| 'OR-chain bypass: find -exec rm'); | ||
| })) passed++; else failed++; |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add regressions for newline and assignment-prefix bypasses.
Line 1631 adds || coverage, but the new scanner still needs tests for echo ok\nfind . -exec rm {} \; and echo ok && FOO=bar find . -exec rm {} \;; both are valid Bash forms for the same destructive find -exec path.
🤖 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 1631 - 1634, Add two
additional regression test cases following the same pattern as the OR-chain
bypass test at line 1631. Create a new test for the newline bypass pattern using
expectDestructiveDeny with the command string 'echo ok\nfind . -exec rm {} \;'
and a descriptive message like 'Newline bypass: find -exec rm', and create
another test for the assignment-prefix bypass pattern using
expectDestructiveDeny with the command string 'echo ok && FOO=bar find . -exec
rm {} \;' and a descriptive message like 'Assignment-prefix bypass: find -exec
rm'. Both tests should follow the same structure as the existing test with the
conditional increment/decrement of passed/failed counters.
Summary
isDestructiveBashcalledisDestructiveFindExeconly on the raw full command string, not on individual segments after splitting on&&,;,|echo x && find . -exec rm {} \;bypassed the gateguard entirely because the first token wasecho, notfindif (isDestructiveFindExec(segment)) return true;inside the per-segment loop&&,;, and|compound-command bypass patternsCloses #2291
Test plan
node tests/hooks/gateguard-fact-force.test.js→ 132 passed, 0 failedecho x && find . -exec rm {} \;is now blockedtrue; find . -name "*.log" -exec rm -rf {} \;is now blockedecho start | find . -exec rm {} \;is now blockedfind . -exec rm {} \;(direct, no prefix) still blocked as before