Skip to content

fix(gateguard): check isDestructiveFindExec on each command segment to close compound-command bypass - #2292

Merged
affaan-m merged 2 commits into
affaan-m:mainfrom
kapil971390:fix/find-exec-compound-command-bypass
Jun 18, 2026
Merged

affaan-m merged 2 commits into
affaan-m:mainfrom
kapil971390:fix/find-exec-compound-command-bypass

Conversation

@kapil971390

Copy link
Copy Markdown
Contributor

Summary

  • isDestructiveBash called isDestructiveFindExec only on the raw full command string, not on individual segments after splitting on &&, ;, |
  • Commands like echo x && find . -exec rm {} \; bypassed the gateguard entirely because the first token was echo, not find
  • Fix: add if (isDestructiveFindExec(segment)) return true; inside the per-segment loop
  • Adds 3 regression tests covering &&, ;, and | compound-command bypass patterns

Closes #2291

Test plan

  • node tests/hooks/gateguard-fact-force.test.js → 132 passed, 0 failed
  • echo x && find . -exec rm {} \; is now blocked
  • true; find . -name "*.log" -exec rm -rf {} \; is now blocked
  • echo start | find . -exec rm {} \; is now blocked
  • find . -exec rm {} \; (direct, no prefix) still blocked as before

`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.
@kapil971390
kapil971390 requested a review from affaan-m as a code owner June 18, 2026 19:03
@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Improved destructive command detection for find ... -exec ... workflows, adding an additional early check across segmented command bodies to better prevent dangerous -exec execution.
  • Tests

    • Expanded coverage to ensure find . -exec rm ... \; (including rm -rf) is still denied when preceded by &&, ;, |, and ||, preventing parsing boundary edge cases.

Walkthrough

isDestructiveBash now performs an early pass that collects all executable bodies, splits each into raw command segments, and checks isDestructiveFindExec on every raw segment before the existing destructive-check workflow resumes. Four regression tests verify that find -exec rm and find -exec rm -rf are blocked when preceded by &&, ;, |, or || operators.

Changes

find -exec destructive bypass fix

Layer / File(s) Summary
Early find -exec per-segment check
scripts/hooks/gateguard-fact-force.js
isDestructiveBash now builds bodies via collectExecutableBodies(raw), iterates through per-body raw segments (split on `;
Regression tests for compound command contexts
tests/hooks/gateguard-fact-force.test.js
Four new test cases verify find . -exec rm and find . -exec rm -rf with \; remain denied when preceded by &&, ;, |, or || operators.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • affaan-m/ECC#2267: Directly related — also modifies destructive find ... -exec ... detection in scripts/hooks/gateguard-fact-force.js with corresponding test additions.
  • affaan-m/ECC#2161: Both PRs modify isDestructiveBash logic for find -exec and destructive detection across split command segments.

Suggested reviewers

  • affaan-m

Poem

A find slipped past when not first in line,
With && and ; as its disguise so fine.
Now each raw segment faces the test,
No -exec rm escapes the gateguard's best. 🔒

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Title accurately describes the main fix: checking isDestructiveFindExec on each command segment to prevent compound-command bypass.
Description check ✅ Passed Description clearly explains the vulnerability, the fix mechanism, and provides concrete bypass examples with test coverage confirmation.
Linked Issues check ✅ Passed Code changes directly address issue #2291 by adding isDestructiveFindExec checks within the segment loop and using raw body segments to preserve quoted binary names, covering all bypass patterns (&&, ;, |, ||).
Out of Scope Changes check ✅ Passed Changes are limited to the gateguard security fix and corresponding test coverage; no unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

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.

❤️ Share

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

@greptile-apps

greptile-apps Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a security bypass in the gateguard Bash hook where isDestructiveFindExec was called only once on the full raw command, allowing compound commands like echo x && find . -exec rm {} \; to slip past because the first token was not find. The fix splits each raw executable body on [;|&]+ and calls isDestructiveFindExec on every resulting segment before quote-stripping, which also preserves quoted exec-binary detection that splitCommandSegments would otherwise break.

  • Core fix (scripts/hooks/gateguard-fact-force.js): isDestructiveBash now iterates over raw segments of every executable body and calls isDestructiveFindExec per segment; the bodies result from collectExecutableBodies is stored once and reused for the subsequent splitCommandSegments loop, avoiding a redundant call.
  • Regression tests (tests/hooks/gateguard-fact-force.test.js): Four new tests exercise &&, ;, |, and || compound-command bypass patterns, including the || OR-chain form raised in the previous review round.

Confidence Score: 5/5

The change is a targeted, well-reasoned security fix with no new logic paths that could introduce false negatives or regressions.

The splitting approach (raw body → /[;|&]+/) is internally consistent with splitCommandSegments and correctly handles \; terminators being split away — isDestructiveFindExec still detects destructive commands from the remaining tokens. The bodies variable is computed once and reused, avoiding duplicate collectExecutableBodies calls. The four new regression tests cover all compound-operator forms including ||. No existing tests are expected to break, and no new code paths are left untested.

No files require special attention.

Important Files Changed

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

Comment thread scripts/hooks/gateguard-fact-force.js Resolved
…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.
@kapil971390

Copy link
Copy Markdown
Contributor Author

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.

@greptile-apps

greptile-apps Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

The P2 (||) fix and its regression test look correct — [;|&]+ cleanly covers all separator forms.

However, P1 is still incomplete. The switch to raw body segments correctly preserves quoted binary names in the string, but isDestructiveFindExec → tokenize just whitespace-splits the segment and passes the result straight to commandBasename, which only strips paths and .exe — it doesn't strip quote characters. So find . -exec 'rm' {} \; produces execTokens[0] = "'rm'" (with single quotes), and commandBasename("'rm'") returns "'rm'", not "rm". The === 'rm' check fails and the command passes through undetected.

Concrete trace:

raw segment (after [;|&]+ split): "find . -exec 'rm' {} \"
tokenize → ['find', '.', '-exec', "'rm'", '{}', '\']
execTokens[0] = "'rm'"
commandBasename("'rm'") → "'rm'"
"'rm'" === 'rm' → false  ← still undetected

The fix belongs inside isDestructiveFindExec — strip outer quotes from the exec binary token before checking:

const baseCmd = commandBasename(execTokens[0].replace(/^(['"])(.*)\1$/, '$2'));

That one-liner handles both 'rm' and "rm" and is a no-op for unquoted tokens. You'd also want regression tests:

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 collectExecutableBodies + raw-segment approach is the right architecture; the quote-stripping just needs to happen one level deeper.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.

@coderabbitai coderabbitai 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between da0e5d5 and a9a45c7.

📒 Files selected for processing (2)
  • scripts/hooks/gateguard-fact-force.js
  • tests/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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 about console.log statements in edited files
Check all modified files for console.log statements 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 met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • tests/hooks/gateguard-fact-force.test.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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.js
  • scripts/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

Comment on lines +556 to +557
for (const rawSeg of body.split(/[;|&]+/).map(s => s.trim()).filter(Boolean)) {
if (isDestructiveFindExec(rawSeg)) return true;

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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;

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

Comment on lines +1631 to +1634
if (test('denies find -exec rm {} \\; after || (OR-chain bypass)', () => {
expectDestructiveDeny('false || find . -exec rm {} \\;',
'OR-chain bypass: find -exec rm');
})) passed++; else failed++;

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.

🛠️ 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.

@affaan-m
affaan-m merged commit 3cdc69a into affaan-m:main Jun 18, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Security: destructive find -exec bypasses gateguard via compound commands (&&, ;, |)

3 participants