Repository navigation
fix(hooks): close the PowerShell destructive-command gate bypass - #2721
noliverbked wants to merge 5 commits into
Conversation
CLAUDE_CODE_USE_POWERSHELL_TOOL=1 makes PowerShell a second arbitrary-command shell, but every destructive-command gate was scoped to Bash alone. Identical destructive intent through the two tools produced opposite outcomes: the Bash recursive-delete form was denied, while the PowerShell equivalent passed through with exit 0 and no gate at all. The gate failed at two independent levels, so widening either alone was insufficient: - gateguard-fact-force.js: TOOL_MAP had no `powershell` key, and `if (toolName === 'Bash')` was the only branch reaching isDestructiveBash(). Unrecognised tool names fell through to the bare allow at the end of run(). - governance-capture.js: SECURITY_RELEVANT_TOOLS held only 'Bash', and a second Bash-only branch guarded APPROVAL_COMMANDS, so a bypassing command was also invisible to the audit trail. PowerShell delete verbs share no syntax with POSIX rm, so a dedicated isDestructivePowerShell() is required rather than reuse: the PowerShell recursive-delete form reaches isDestructiveRm() as tokens whose -Force fails its case-sensitive /f/ test. PowerShell also accepts any unambiguous parameter prefix, so -Recurse, -Rec and -r must all match. Detection reuses the file's existing quote-aware segmenter (quoteAwareSegments) rather than a naive split, which is what closes the quoted-separator evasion class described in GHSA-4v57-ph3x-gf55; the same choice resolves the `&` call operator and quoted command words for free. Covered in addition: pipelines that carry -Recurse on an upstream enumerator, backtick obfuscation, nested powershell/pwsh/cmd reinvocation including base64 -EncodedCommand, .NET [System.IO.Directory]::Delete, and splatted (opaque) parameters. -Force is gated even without -Recurse. This deliberately departs from the rm -f analogy: PowerShell's Remove-Item -Force on a directory removes the tree, and a static string cannot distinguish a file target from a directory target. isDestructiveBash() still runs for PowerShell input so the shell-agnostic phrases (force push, hard reset, DROP TABLE, dd) stay covered. The PowerShell detector runs only for the PowerShell tool, so Bash gating behaviour is unchanged - verified by differential testing of both versions across 15 representative Bash commands, 0 differences. The routine first-command gate intentionally shares ROUTINE_BASH_SESSION_KEY across both tools, so an operator sees one fact-forcing prompt per session rather than two; its message is now tool-neutral. Tests: 164 passed / 0 failed in gateguard-fact-force (20 new PowerShell cases, 144 pre-existing unaffected), 30/0 governance-capture, 13/0 posttooluse-dispatcher.
|
ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughPowerShell now uses destructive-command detection, governance approval checks, elevated-privilege checks, and dedicated hook routing. Detection covers aliases, nested shells, encoded commands, pipelines, parameter variants, and alternate deletion APIs. Tests cover denial, allowed commands, governance events, and shared session gating. ChangesPowerShell security enforcement
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant PowerShell
participant GateguardFactForce
participant GovernanceCapture
participant PostToolDispatcher
PowerShell->>GateguardFactForce: submit command
GateguardFactForce->>GateguardFactForce: inspect destructive syntax
GateguardFactForce-->>PowerShell: allow or deny command
PowerShell->>PostToolDispatcher: emit tool event
PostToolDispatcher->>GovernanceCapture: dispatch PowerShell event
GovernanceCapture->>GovernanceCapture: analyze approval and elevation patterns
GovernanceCapture-->>PowerShell: record governance result
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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.
Actionable comments posted: 4
🤖 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`:
- Around line 759-765: Update the destructive PowerShell detection logic near
the token loop in the relevant function to gate non-parameter target tokens
containing wildcards such as “*”, while preserving existing handling for
-Recurse, -Force, and splats. Add or update coverage for Remove-Item with a
wildcard target and no destructive parameter, ensuring it is classified as gated
and single-file -Force behavior remains unchanged.
- Around line 770-771: Update isDestructivePowerShell so reaching the recursion
limit at depth greater than 4 returns true instead of false, ensuring deeply
nested or unanalyzable PowerShell commands are treated as destructive candidates
while preserving existing behavior below the limit.
In `@scripts/hooks/governance-capture.js`:
- Around line 49-51: Add the PowerShell alias rm to the command alternatives in
the governance-capture regex, alongside Remove-Item and the existing aliases.
Ensure rm -Recurse is matched by the PowerShell-specific pattern while
preserving the current POSIX rm handling and other alias behavior.
In `@tests/hooks/gateguard-fact-force.test.js`:
- Around line 2484-2493: Update expectPsAllow in
tests/hooks/gateguard-fact-force.test.js#L2484-L2493 to assert that parseOutput
returns output before checking hookSpecificOutput, and add the pass-through
tool_name assertion in the else branch matching expectAllow. Also update the
shared-routine-gate test at tests/hooks/gateguard-fact-force.test.js#L2668-L2684
to assert output exists before its conditional check.
🪄 Autofix
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 Plus
Run ID: 92573461-e9e5-475b-b61b-378fb4abbcc3
📒 Files selected for processing (3)
scripts/hooks/gateguard-fact-force.jsscripts/hooks/governance-capture.jstests/hooks/gateguard-fact-force.test.js
📜 Review details
🧰 Additional context used
📓 Path-based instructions (17)
**/*.{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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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/governance-capture.jsscripts/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/governance-capture.jsscripts/hooks/gateguard-fact-force.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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,jsx,tsx,json,env*}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Do not hardcode secrets, API keys, passwords, or tokens
Files:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.js
**/*.{jsx,tsx,js,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
HTML output must be sanitized where applicable
Files:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,env*}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Required environment variables must be validated at startup
Files:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.js
**/*
📄 CodeRabbit inference engine (AGENTS.md)
**/*: Delegate complex features to a planner agent, architectural decisions to an architect agent, modified code to a code-reviewer agent, and security-sensitive work to a security-reviewer agent; use parallel agents for independent operations.
Never compromise security; validate all inputs and prevent hardcoded secrets, injection, XSS, CSRF, authentication or authorization failures, sensitive error leakage, and missing rate limits.
Never hardcode secrets; use environment variables or a secret manager, validate required secrets at startup, and rotate exposed secrets immediately.
Always create new objects and never mutate existing ones.
Plan complex features before implementation, identifying dependencies, risks, and phases.
Prefer many small, focused files; keep functions under 50 lines, files under 800 lines where practical, avoid nesting deeper than four levels, and use readable, well-named identifiers.
Handle errors at every level, provide user-friendly UI messages, log detailed server-side context, and never silently swallow errors.
Validate all user input at system boundaries using schema-based validation; fail fast with clear messages and never trust external data.
Required tests include unit tests, integration tests for APIs and database operations, and end-to-end tests for critical user flows.
Follow the mandatory TDD cycle: write a failing test, implement the minimum passing solution, then refactor and verify coverage.
Use a consistent API response envelope containing a success indicator, data payload, error message, and pagination metadata.
Encapsulate data access behind a repository interface with operations such asfindAll,findById,create,update, anddelete; business logic must depend on the abstraction rather than storage details.
Files:
scripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.jstests/hooks/gateguard-fact-force.test.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/governance-capture.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
🧠 Learnings (2)
📚 Learning: 2026-06-27T23:49:19.839Z
Learnt from: gaurav0107
Repo: affaan-m/ECC PR: 2373
File: tests/hooks/observe-signal-timeout.test.js:0-0
Timestamp: 2026-06-27T23:49:19.839Z
Learning: In tests under tests/hooks that require a Python runtime to run, the test should fail fast when Python isn’t available (or prerequisites aren’t met). Do not treat a missing Python runtime as test.skip, as an expected/allowed condition, or as a passing state; instead, explicitly fail (e.g., throw/return a rejected promise or use a test runner fail/expect that marks the test as failed) so reviewers can’t accidentally mask environment issues.
Applied to files:
tests/hooks/gateguard-fact-force.test.js
📚 Learning: 2026-07-14T03:26:12.530Z
Learnt from: thejesh23
Repo: affaan-m/ECC PR: 2517
File: tests/hooks/pre-bash-tmux-reminder.test.js:21-25
Timestamp: 2026-07-14T03:26:12.530Z
Learning: In this repository, do not flag `console.log` usage as a guideline violation in hook test files under `tests/hooks/*.test.js`. These tests intentionally use `console.log` for pass/fail output because the repo’s console-based runner (`tests/run-all.js`) is used and there is no Jest/Mocha dependency. Outside this specific hook-test path, follow the normal logging guidelines.
Applied to files:
tests/hooks/gateguard-fact-force.test.js
🔇 Additional comments (7)
scripts/hooks/gateguard-fact-force.js (6)
744-757: LGTM!
829-866: LGTM!
868-918: LGTM!
1323-1323: LGTM!Also applies to: 1391-1391
728-742: 🔒 Security & PrivacyNo change needed.
commandBasename()already removes a trailing.exeafter stripping the path, sopowershell.exe,pwsh.exe, andcmd.exeare normalized to the bare names used byPS_NESTED_SHELLSand the delete-verb checks.
1442-1454: 🔒 Security & PrivacyNo change needed.
PowerShell gating is reachable through the existing
BashPreToolUse hook registration.> Likely an incorrect or invalid review comment.scripts/hooks/governance-capture.js (1)
185-186: LGTM!Also applies to: 231-237
The PowerShell entries in APPROVAL_COMMANDS and the extended elevated-privilege check had no suite coverage; they were verified only by direct invocation. Adds 5 cases: recursive-delete detection including abbreviated parameter prefixes, Clear-Content/Format-Volume, a benign control, approval_requested parity with Bash, and elevated-privilege security_finding for RunAs/Set-Acl/takeown. All 6 assertions verified red-green against the pre-fix module (pre=none, post=flag); the benign control is 0 in both. Suite: 35 passed, 0 failed.
|
ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@tests/hooks/governance-capture.test.js`:
- Around line 362-367: Strengthen the assertions in the detectApprovalRequired
PowerShell test so the abbreviated -Rec input and the rd -Recurse input each
verify the expected PowerShell finding.pattern, rather than only checking that
findings exist. Keep the existing full-parameter coverage and ensure the
assertions specifically prove abbreviated-parameter support.
- Around line 379-397: Split the combined elevated-privilege loop in the
PowerShell governance tests into independently reported, descriptively named
test cases for Start-Process, Set-Acl, and takeown. Give each case explicit
Arrange, Act, and Assert steps while preserving the existing security_finding
event type and elevated_privilege_command reason checks.
🪄 Autofix
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 Plus
Run ID: 40417207-0d88-4fb2-84f6-d1f9b3e7254d
📒 Files selected for processing (1)
tests/hooks/governance-capture.test.js
📜 Review details
🧰 Additional context used
📓 Path-based instructions (14)
**/*.{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/governance-capture.test.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/governance-capture.test.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/governance-capture.test.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/governance-capture.test.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/governance-capture.test.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/governance-capture.test.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/governance-capture.test.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/governance-capture.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/governance-capture.test.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/governance-capture.test.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/governance-capture.test.js
**/*.{jsx,tsx,js,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
HTML output must be sanitized where applicable
Files:
tests/hooks/governance-capture.test.js
**/*.{js,ts,env*}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Required environment variables must be validated at startup
Files:
tests/hooks/governance-capture.test.js
**/*
📄 CodeRabbit inference engine (AGENTS.md)
**/*: Delegate complex features to a planner agent, architectural decisions to an architect agent, modified code to a code-reviewer agent, and security-sensitive work to a security-reviewer agent; use parallel agents for independent operations.
Never compromise security; validate all inputs and prevent hardcoded secrets, injection, XSS, CSRF, authentication or authorization failures, sensitive error leakage, and missing rate limits.
Never hardcode secrets; use environment variables or a secret manager, validate required secrets at startup, and rotate exposed secrets immediately.
Always create new objects and never mutate existing ones.
Plan complex features before implementation, identifying dependencies, risks, and phases.
Prefer many small, focused files; keep functions under 50 lines, files under 800 lines where practical, avoid nesting deeper than four levels, and use readable, well-named identifiers.
Handle errors at every level, provide user-friendly UI messages, log detailed server-side context, and never silently swallow errors.
Validate all user input at system boundaries using schema-based validation; fail fast with clear messages and never trust external data.
Required tests include unit tests, integration tests for APIs and database operations, and end-to-end tests for critical user flows.
Follow the mandatory TDD cycle: write a failing test, implement the minimum passing solution, then refactor and verify coverage.
Use a consistent API response envelope containing a success indicator, data payload, error message, and pagination metadata.
Encapsulate data access behind a repository interface with operations such asfindAll,findById,create,update, anddelete; business logic must depend on the abstraction rather than storage details.
Files:
tests/hooks/governance-capture.test.js
🧠 Learnings (2)
📚 Learning: 2026-06-27T23:49:19.839Z
Learnt from: gaurav0107
Repo: affaan-m/ECC PR: 2373
File: tests/hooks/observe-signal-timeout.test.js:0-0
Timestamp: 2026-06-27T23:49:19.839Z
Learning: In tests under tests/hooks that require a Python runtime to run, the test should fail fast when Python isn’t available (or prerequisites aren’t met). Do not treat a missing Python runtime as test.skip, as an expected/allowed condition, or as a passing state; instead, explicitly fail (e.g., throw/return a rejected promise or use a test runner fail/expect that marks the test as failed) so reviewers can’t accidentally mask environment issues.
Applied to files:
tests/hooks/governance-capture.test.js
📚 Learning: 2026-07-14T03:26:12.530Z
Learnt from: thejesh23
Repo: affaan-m/ECC PR: 2517
File: tests/hooks/pre-bash-tmux-reminder.test.js:21-25
Timestamp: 2026-07-14T03:26:12.530Z
Learning: In this repository, do not flag `console.log` usage as a guideline violation in hook test files under `tests/hooks/*.test.js`. These tests intentionally use `console.log` for pass/fail output because the repo’s console-based runner (`tests/run-all.js`) is used and there is no Jest/Mocha dependency. Outside this specific hook-test path, follow the normal logging guidelines.
Applied to files:
tests/hooks/governance-capture.test.js
| if (await test('detectApprovalRequired flags PowerShell recursive deletes', async () => { | ||
| assert.ok(detectApprovalRequired('Remove-Item -Recurse -Force C:/tmp/demo').length > 0); | ||
| // PowerShell accepts any unambiguous parameter prefix. | ||
| assert.ok(detectApprovalRequired('Remove-Item -Rec C:/tmp/demo').length > 0); | ||
| assert.ok(detectApprovalRequired('rd -Recurse C:/tmp/demo').length > 0); | ||
| })) passed += 1; else failed += 1; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert the PowerShell-specific finding for abbreviated parameters.
The length > 0 assertions do not prove that -Rec or rd -Recurse matched the intended PowerShell rule. A broader rule could satisfy these assertions while abbreviated-parameter detection is broken. Assert the expected finding.pattern, or add a boundary case that only the abbreviated PowerShell rule can match.
The PR objective explicitly requires abbreviated parameter support.
🤖 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/governance-capture.test.js` around lines 362 - 367, Strengthen
the assertions in the detectApprovalRequired PowerShell test so the abbreviated
-Rec input and the rd -Recurse input each verify the expected PowerShell
finding.pattern, rather than only checking that findings exist. Keep the
existing full-parameter coverage and ensure the assertions specifically prove
abbreviated-parameter support.
| if (await test('PowerShell tool raises approval_requested like Bash', async () => { | ||
| const events = analyzeForGovernanceEvents({ | ||
| tool_name: 'PowerShell', | ||
| tool_input: { command: 'Remove-Item -Recurse -Force C:/tmp/demo' }, | ||
| }); | ||
| assert.ok(events.map(e => e.eventType).includes('approval_requested')); | ||
| })) passed += 1; else failed += 1; | ||
|
|
||
| if (await test('PowerShell elevated-privilege commands raise a security_finding', async () => { | ||
| for (const command of ['Start-Process -Verb RunAs cmd', 'Set-Acl -Path C:/x -AclObject $a', 'takeown /f C:/x']) { | ||
| const events = analyzeForGovernanceEvents( | ||
| { tool_name: 'PowerShell', tool_input: { command } }, | ||
| { hookPhase: 'post' } | ||
| ); | ||
| const finding = events.find(e => e.eventType === 'security_finding'); | ||
| assert.ok(finding, `${command} should raise a security_finding`); | ||
| assert.strictEqual(finding.payload.reason, 'elevated_privilege_command'); | ||
| } | ||
| })) passed += 1; else failed += 1; |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Report each elevated-command case independently.
The loop tests Start-Process, Set-Acl, and takeown under one test. If one assertion fails, later commands are not evaluated as separate cases. Use separate test cases or a table-driven helper with explicit Arrange, Act, and Assert steps.
As per coding guidelines, tests must use an Arrange / Act / Assert structure with descriptive test names.
🤖 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/governance-capture.test.js` around lines 379 - 397, Split the
combined elevated-privilege loop in the PowerShell governance tests into
independently reported, descriptively named test cases for Start-Process,
Set-Acl, and takeown. Give each case explicit Arrange, Act, and Assert steps
while preserving the existing security_finding event type and
elevated_privilege_command reason checks.
Source: Coding guidelines
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
|
ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR. |
haelyra
left a comment
There was a problem hiding this comment.
Thank you for catching the PowerShell GateGuard gap. I completed the maintainer patch with a dedicated PowerShell route, fail-closed nested-command scanning, wildcard protection, rm alias handling, and direct configured-route coverage, then refreshed it on current main. The GateGuard, governance, dispatcher, and hook suites pass. Approving this exact head for hosted CI.
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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`:
- Around line 729-731: Extend the PowerShell destructive-command detection
around PS_DELETE_VERBS and isDestructivePowerShell to include Clear-Content,
Clear-Disk, and Format-Volume in a separate data-destruction verb set. Gate
these verbs independently of -Recurse and -Force, while preserving existing
Remove-Item, .NET delete, and cmd recursive-delete handling.
- Around line 760-766: Update the documentation comment for the destructive
PowerShell command detector near isDestructiveRm to accurately describe the
implemented behavior: any Remove-Item -Force prefix is gated, including
single-file and directory targets. Remove the claim that Remove-Item -Force
notes.txt remains ungated, while preserving the explanation that this behavior
intentionally differs from the rm -f comparison.
In `@tests/hooks/gateguard-fact-force.test.js`:
- Around line 2691-2712: Add a regression test near the existing Bash hook-ID
assertion that exercises the PowerShell routine-gate denial path through
runBashHook with a PowerShell command, then assert the emitted denial output
references POWERSHELL_HOOK_ID rather than BASH_HOOK_ID. Keep the test focused on
the observable disable ID selected by run() for PowerShell routine denials.
In `@tests/hooks/hooks.test.js`:
- Around line 2591-2610: Update the spawnSync environment in the test around the
route command to explicitly clear ECC_GATEGUARD and GATEGUARD_DISABLED and
remove the gateguard-fact-force entry from ECC_DISABLED_HOOKS, while preserving
the isolated GATEGUARD_STATE_DIR and other inherited environment values.
🪄 Autofix
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 Plus
Run ID: bf703639-8d35-49fc-b048-d588b2dfc1e1
📒 Files selected for processing (8)
hooks/hooks.jsonscripts/hooks/gateguard-fact-force.jsscripts/hooks/governance-capture.jsscripts/hooks/posttooluse-dispatcher.jstests/hooks/gateguard-fact-force.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jstests/hooks/posttooluse-dispatcher.test.js
📜 Review details
⏰ Context from checks skipped due to timeout. (13)
- GitHub Check: Test (ubuntu-latest, Node 22.x, bun)
- GitHub Check: Test (ubuntu-latest, Node 22.x, pnpm)
- GitHub Check: Test (ubuntu-latest, Node 22.x, npm)
- GitHub Check: Test (ubuntu-latest, Node 20.x, yarn)
- GitHub Check: Test (ubuntu-latest, Node 18.x, pnpm)
- GitHub Check: Test (ubuntu-latest, Node 20.x, pnpm)
- GitHub Check: Test (ubuntu-latest, Node 18.x, bun)
- GitHub Check: Test (ubuntu-latest, Node 20.x, npm)
- GitHub Check: Security Scan
- GitHub Check: Lint
- GitHub Check: Coverage
- GitHub Check: Validate Components
- GitHub Check: Greptile Review
🧰 Additional context used
📓 Path-based instructions (18)
**/*.{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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jshooks/hooks.jsontests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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/posttooluse-dispatcher.jsscripts/hooks/governance-capture.jsscripts/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/posttooluse-dispatcher.jsscripts/hooks/governance-capture.jsscripts/hooks/gateguard-fact-force.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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jshooks/hooks.jsontests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/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:
scripts/hooks/posttooluse-dispatcher.jstests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jsscripts/hooks/governance-capture.jstests/hooks/gateguard-fact-force.test.jsscripts/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/posttooluse-dispatcher.jsscripts/hooks/governance-capture.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/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jstests/hooks/gateguard-fact-force.test.js
tests/**
📄 CodeRabbit inference engine (AGENTS.md)
Maintain the project's test suite under the
tests/directory.
Files:
tests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jstests/hooks/gateguard-fact-force.test.js
hooks/**/*.json
📄 CodeRabbit inference engine (CLAUDE.md)
Hooks should be formatted as JSON with matcher conditions and hooks array.
Files:
hooks/hooks.json
🧠 Learnings (2)
📚 Learning: 2026-06-27T23:49:19.839Z
Learnt from: gaurav0107
Repo: affaan-m/ECC PR: 2373
File: tests/hooks/observe-signal-timeout.test.js:0-0
Timestamp: 2026-06-27T23:49:19.839Z
Learning: In tests under tests/hooks that require a Python runtime to run, the test should fail fast when Python isn’t available (or prerequisites aren’t met). Do not treat a missing Python runtime as test.skip, as an expected/allowed condition, or as a passing state; instead, explicitly fail (e.g., throw/return a rejected promise or use a test runner fail/expect that marks the test as failed) so reviewers can’t accidentally mask environment issues.
Applied to files:
tests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jstests/hooks/gateguard-fact-force.test.js
📚 Learning: 2026-07-14T03:26:12.530Z
Learnt from: thejesh23
Repo: affaan-m/ECC PR: 2517
File: tests/hooks/pre-bash-tmux-reminder.test.js:21-25
Timestamp: 2026-07-14T03:26:12.530Z
Learning: In this repository, do not flag `console.log` usage as a guideline violation in hook test files under `tests/hooks/*.test.js`. These tests intentionally use `console.log` for pass/fail output because the repo’s console-based runner (`tests/run-all.js`) is used and there is no Jest/Mocha dependency. Outside this specific hook-test path, follow the normal logging guidelines.
Applied to files:
tests/hooks/posttooluse-dispatcher.test.jstests/hooks/governance-capture.test.jstests/hooks/hooks.test.jstests/hooks/gateguard-fact-force.test.js
🪛 ast-grep (0.45.1)
tests/hooks/hooks.test.js
[warning] 2586-2586: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.readFileSync(hooksPath, 'utf8')
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').
(detect-non-literal-fs-filename)
🔇 Additional comments (19)
tests/hooks/gateguard-fact-force.test.js (3)
2516-2535: 📐 Maintainability & Code Quality | 💤 Low valueGrouped
expectPsDenycalls stop at the first failure.Lines 2518-2521 and 2528-2531 assert several independent commands in one test case. If
-Recfails,-ris never evaluated, and the alias sweep reports one failure instead of four. The same pattern repeats at Lines 2546-2549 and 2564-2567.The
labelargument keeps the failing case identifiable, so this is diagnosability, not correctness. Consider a table-driven loop that reports each command as its own case.As per coding guidelines, tests must "use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test".
Source: Coding guidelines
2459-2496: LGTM!
2592-2682: LGTM!tests/hooks/governance-capture.test.js (3)
362-368: 🎯 Functional Correctness | ⚡ Quick winThe assertions still do not prove which rule matched.
Lines 363-367 assert only
length > 0. A future broader entry inAPPROVAL_COMMANDSwould satisfy these assertions while the abbreviated-parameter rule atscripts/hooks/governance-capture.jsLine 51 is broken. Assert the expectedfinding.patterninstead.The PR objectives list abbreviated parameter support as an explicit requirement.
💚 Proposed fix
+ const PS_RECURSE_PATTERN_FRAGMENT = 'Remove-ItemProperty'; + if (await test('detectApprovalRequired flags PowerShell recursive deletes', async () => { - assert.ok(detectApprovalRequired('Remove-Item -Recurse -Force C:/tmp/demo').length > 0); - // PowerShell accepts any unambiguous parameter prefix. - assert.ok(detectApprovalRequired('Remove-Item -Rec C:/tmp/demo').length > 0); - assert.ok(detectApprovalRequired('rd -Recurse C:/tmp/demo').length > 0); - assert.ok(detectApprovalRequired('rm -Recurse C:/tmp/demo').length > 0); + // PowerShell accepts any unambiguous parameter prefix, so each spelling must + // match the dedicated PowerShell rule, not merely "some" rule. + for (const command of [ + 'Remove-Item -Recurse -Force C:/tmp/demo', + 'Remove-Item -Rec C:/tmp/demo', + 'rd -Recurse C:/tmp/demo', + 'rm -Recurse C:/tmp/demo', + ]) { + const findings = detectApprovalRequired(command); + assert.ok( + findings.some(f => f.pattern.includes(PS_RECURSE_PATTERN_FRAGMENT)), + `${command} should match the PowerShell delete rule, got: ${JSON.stringify(findings)}` + ); + } })) passed += 1; else failed += 1;
388-398: 📐 Maintainability & Code Quality | 💤 Low valueThe elevated-privilege cases still share one test.
Start-Process -Verb RunAs,Set-Acl, andtakeownrun in one loop. A failure on the first command stops the other two. Line 396 also omits an assertion message, so a wrongreasonwould not name the offending command.At minimum, add the command to the Line 396 message.
As per coding guidelines, tests must "use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test".
Source: Coding guidelines
370-386: LGTM!scripts/hooks/gateguard-fact-force.js (4)
44-44: LGTM!Also applies to: 718-758
838-875: LGTM!
877-928: LGTM!
1332-1332: LGTM!Also applies to: 1400-1400, 1451-1463, 1487-1488
scripts/hooks/governance-capture.js (3)
37-53: LGTM!
185-186: LGTM!
231-237: LGTM!hooks/hooks.json (2)
16-27: LGTM!
64-64: LGTM!scripts/hooks/posttooluse-dispatcher.js (1)
29-29: LGTM!tests/hooks/hooks.test.js (1)
2544-2563: LGTM!tests/hooks/posttooluse-dispatcher.test.js (2)
33-35: LGTM!
131-135: LGTM!
| const PS_DELETE_VERBS = new Set([ | ||
| 'remove-item', 'remove-itemproperty', 'ri', 'rm', 'rmdir', 'rd', 'del', 'erase', | ||
| ]); |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Clear-Content, Clear-Disk, and Format-Volume are gated by governance capture but not by the gate.
scripts/hooks/governance-capture.js Lines 52-53 add Clear-(?:Content|Disk) and Format-Volume to APPROVAL_COMMANDS. isDestructivePowerShell has no equivalent. PS_DELETE_VERBS at Lines 729-731 lists only Remove-Item and its aliases, and the regexes at Lines 740-743 cover only .NET delete and cmd recursive delete.
Result: Format-Volume -DriveLetter D emits an approval_requested event but passes the destructive gate once the session routine gate is satisfied. The audit record and the enforcement decision disagree — the same class of gap reported earlier for the rm alias, in the opposite direction.
Add a data-destruction verb set that is gated independently of -Recurse / -Force, since these cmdlets destroy content without either parameter.
🔒 Proposed fix: gate content-destroying cmdlets
const PS_DELETE_VERBS = new Set([
'remove-item', 'remove-itemproperty', 'ri', 'rm', 'rmdir', 'rd', 'del', 'erase',
]);
+
+// Cmdlets that destroy data without a delete verb and without -Recurse/-Force.
+// Gated on presence alone, matching the governance-capture approval patterns.
+const PS_DATA_DESTROYERS = new Set([
+ 'clear-content', 'clear-disk', 'format-volume',
+]); for (const tokens of quoteAwareSegments(raw)) {
if (tokens.length === 0) continue;
const verb = commandBasename(tokens[0]);
const rest = tokens.slice(1);
+
+ if (PS_DATA_DESTROYERS.has(verb)) return true;
if (PS_NESTED_SHELLS.has(verb)) {Also applies to: 784-798
🤖 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 729 - 731, Extend the
PowerShell destructive-command detection around PS_DELETE_VERBS and
isDestructivePowerShell to include Clear-Content, Clear-Disk, and Format-Volume
in a separate data-destruction verb set. Gate these verbs independently of
-Recurse and -Force, while preserving existing Remove-Item, .NET delete, and cmd
recursive-delete handling.
| /** | ||
| * Detect destructive PowerShell commands. | ||
| * | ||
| * Scoped deliberately to mirror `isDestructiveRm`, which gates `rm -rf` but not | ||
| * `rm -f`: the hazard class is *recursive or wildcarded* deletion, not any | ||
| * delete. A single-file `Remove-Item -Force notes.txt` stays ungated, exactly as | ||
| * its `rm -f notes.txt` equivalent does. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
The doc comment contradicts the implemented behavior.
Lines 765-766 state that Remove-Item -Force notes.txt stays ungated. Line 829 gates any -Force prefix, and Lines 827-828 explain why. The test at tests/hooks/gateguard-fact-force.test.js Line 2577 asserts denial for Remove-Item -Force C:/tmp/some-directory.
Correct the doc so a future reader does not treat the -Force gate as a bug.
📝 Proposed doc fix
- * Scoped deliberately to mirror `isDestructiveRm`, which gates `rm -rf` but not
- * `rm -f`: the hazard class is *recursive or wildcarded* deletion, not any
- * delete. A single-file `Remove-Item -Force notes.txt` stays ungated, exactly as
- * its `rm -f notes.txt` equivalent does.
+ * The hazard class is *recursive, forced, or wildcarded* deletion, not any
+ * delete. A plain `Remove-Item notes.txt` stays ungated. `-Force` is gated even
+ * without `-Recurse`, because `Remove-Item -Force <directory>` removes the tree
+ * and a static string cannot distinguish a file target from a directory target.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** | |
| * Detect destructive PowerShell commands. | |
| * | |
| * Scoped deliberately to mirror `isDestructiveRm`, which gates `rm -rf` but not | |
| * `rm -f`: the hazard class is *recursive or wildcarded* deletion, not any | |
| * delete. A single-file `Remove-Item -Force notes.txt` stays ungated, exactly as | |
| * its `rm -f notes.txt` equivalent does. | |
| /** | |
| * Detect destructive PowerShell commands. | |
| * | |
| * The hazard class is *recursive, forced, or wildcarded* deletion, not any | |
| * delete. A plain `Remove-Item notes.txt` stays ungated. `-Force` is gated even | |
| * without `-Recurse`, because `Remove-Item -Force <directory>` removes the tree | |
| * and a static string cannot distinguish a file target from a directory target. |
🤖 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 760 - 766, Update the
documentation comment for the destructive PowerShell command detector near
isDestructiveRm to accurately describe the implemented behavior: any Remove-Item
-Force prefix is gated, including single-file and directory targets. Remove the
claim that Remove-Item -Force notes.txt remains ungated, while preserving the
explanation that this behavior intentionally differs from the rm -f comparison.
| // Regression guard: the routine gate is shared, so PowerShell must not get a | ||
| // second first-command gate after Bash has already satisfied it. | ||
| if ( | ||
| test('shares the routine session gate with Bash', () => { | ||
| clearState(); | ||
| writeState({ checked: ['__bash_session__'], last_active: Date.now() }); | ||
| const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } }); | ||
| const output = parseOutput(result.stdout); | ||
| assert.ok(output, 'PowerShell should produce pass-through JSON'); | ||
| if (output.hookSpecificOutput) { | ||
| assert.notStrictEqual( | ||
| output.hookSpecificOutput.permissionDecision, | ||
| 'deny', | ||
| 'PowerShell should not re-trigger the routine gate Bash already satisfied' | ||
| ); | ||
| } else { | ||
| assert.strictEqual(output.tool_name, 'PowerShell'); | ||
| } | ||
| }) | ||
| ) | ||
| passed++; | ||
| else failed++; |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
No test asserts the PowerShell routine-gate hook ID.
run() at scripts/hooks/gateguard-fact-force.js Line 1487 selects POWERSHELL_HOOK_ID for PowerShell routine denials. That selection is the only observable effect of the new constant at Line 44, and no test covers it. The Bash equivalent is covered at Line 559 of this file.
A regression that reverts Line 1487 to BASH_HOOK_ID would print the wrong disable ID to the operator and pass the suite.
💚 Proposed test
+ if (
+ test('routine PowerShell denials name the PowerShell hook disable id', () => {
+ clearState();
+ const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } });
+ const output = parseOutput(result.stdout);
+ assert.ok(output, 'should produce JSON output');
+ const reason = output.hookSpecificOutput.permissionDecisionReason;
+ assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny');
+ assert.ok(reason.includes('pre:powershell:gateguard-fact-force'), 'should show the PowerShell hook ID');
+ assert.ok(!reason.includes('pre:bash:gateguard-fact-force'), 'should not show the Bash hook ID');
+ })
+ )
+ passed++;
+ else failed++;
+📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Regression guard: the routine gate is shared, so PowerShell must not get a | |
| // second first-command gate after Bash has already satisfied it. | |
| if ( | |
| test('shares the routine session gate with Bash', () => { | |
| clearState(); | |
| writeState({ checked: ['__bash_session__'], last_active: Date.now() }); | |
| const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } }); | |
| const output = parseOutput(result.stdout); | |
| assert.ok(output, 'PowerShell should produce pass-through JSON'); | |
| if (output.hookSpecificOutput) { | |
| assert.notStrictEqual( | |
| output.hookSpecificOutput.permissionDecision, | |
| 'deny', | |
| 'PowerShell should not re-trigger the routine gate Bash already satisfied' | |
| ); | |
| } else { | |
| assert.strictEqual(output.tool_name, 'PowerShell'); | |
| } | |
| }) | |
| ) | |
| passed++; | |
| else failed++; | |
| if ( | |
| test('routine PowerShell denials name the PowerShell hook disable id', () => { | |
| clearState(); | |
| const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } }); | |
| const output = parseOutput(result.stdout); | |
| assert.ok(output, 'should produce JSON output'); | |
| const reason = output.hookSpecificOutput.permissionDecisionReason; | |
| assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny'); | |
| assert.ok(reason.includes('pre:powershell:gateguard-fact-force'), 'should show the PowerShell hook ID'); | |
| assert.ok(!reason.includes('pre:bash:gateguard-fact-force'), 'should not show the Bash hook ID'); | |
| }) | |
| ) | |
| passed++; | |
| else failed++; | |
| // Regression guard: the routine gate is shared, so PowerShell must not get a | |
| // second first-command gate after Bash has already satisfied it. | |
| if ( | |
| test('shares the routine session gate with Bash', () => { | |
| clearState(); | |
| writeState({ checked: ['__bash_session__'], last_active: Date.now() }); | |
| const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } }); | |
| const output = parseOutput(result.stdout); | |
| assert.ok(output, 'PowerShell should produce pass-through JSON'); | |
| if (output.hookSpecificOutput) { | |
| assert.notStrictEqual( | |
| output.hookSpecificOutput.permissionDecision, | |
| 'deny', | |
| 'PowerShell should not re-trigger the routine gate Bash already satisfied' | |
| ); | |
| } else { | |
| assert.strictEqual(output.tool_name, 'PowerShell'); | |
| } | |
| }) | |
| ) | |
| passed++; | |
| else failed++; |
🤖 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 2691 - 2712, Add a
regression test near the existing Bash hook-ID assertion that exercises the
PowerShell routine-gate denial path through runBashHook with a PowerShell
command, then assert the emitted denial output references POWERSHELL_HOOK_ID
rather than BASH_HOOK_ID. Keep the test focused on the observable disable ID
selected by run() for PowerShell routine denials.
| try { | ||
| const result = spawnSync(route.hooks[0].command, { | ||
| shell: true, | ||
| cwd: repoRoot, | ||
| input: JSON.stringify({ | ||
| hook_event_name: 'PreToolUse', | ||
| tool_name: 'PowerShell', | ||
| tool_input: { command: 'Remove-Item C:/build/*' }, | ||
| session_id: 'configured-powershell-route' | ||
| }), | ||
| encoding: 'utf8', | ||
| env: { | ||
| ...process.env, | ||
| CLAUDE_PLUGIN_ROOT: repoRoot, | ||
| ECC_PLUGIN_ROOT: repoRoot, | ||
| ECC_PROFILE: 'standard', | ||
| GATEGUARD_STATE_DIR: stateDir | ||
| }, | ||
| timeout: 10000 | ||
| }); |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
The spawned route inherits GateGuard disable switches from the developer environment.
Line 2603 spreads process.env without clearing the gate opt-outs. ECC_GATEGUARD=off, GATEGUARD_DISABLED=1, or ECC_DISABLED_HOOKS=pre:powershell:gateguard-fact-force in the ambient environment makes the hook pass through, and the assertion at Line 2614 fails with a permissionDecision of undefined rather than a clear cause.
GATEGUARD_STATE_DIR is isolated correctly, so only the disable switches are unpinned.
💚 Proposed fix: pin the disable switches
env: {
...process.env,
CLAUDE_PLUGIN_ROOT: repoRoot,
ECC_PLUGIN_ROOT: repoRoot,
ECC_PROFILE: 'standard',
- GATEGUARD_STATE_DIR: stateDir
+ GATEGUARD_STATE_DIR: stateDir,
+ // Pin the opt-outs: an ambient disable switch would silently turn
+ // this route into a pass-through and fail the deny assertion below.
+ ECC_GATEGUARD: '',
+ GATEGUARD_DISABLED: '',
+ GATEGUARD_BASH_ROUTINE_DISABLED: '',
+ ECC_DISABLED_HOOKS: ''
},📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try { | |
| const result = spawnSync(route.hooks[0].command, { | |
| shell: true, | |
| cwd: repoRoot, | |
| input: JSON.stringify({ | |
| hook_event_name: 'PreToolUse', | |
| tool_name: 'PowerShell', | |
| tool_input: { command: 'Remove-Item C:/build/*' }, | |
| session_id: 'configured-powershell-route' | |
| }), | |
| encoding: 'utf8', | |
| env: { | |
| ...process.env, | |
| CLAUDE_PLUGIN_ROOT: repoRoot, | |
| ECC_PLUGIN_ROOT: repoRoot, | |
| ECC_PROFILE: 'standard', | |
| GATEGUARD_STATE_DIR: stateDir | |
| }, | |
| timeout: 10000 | |
| }); | |
| try { | |
| const result = spawnSync(route.hooks[0].command, { | |
| shell: true, | |
| cwd: repoRoot, | |
| input: JSON.stringify({ | |
| hook_event_name: 'PreToolUse', | |
| tool_name: 'PowerShell', | |
| tool_input: { command: 'Remove-Item C:/build/*' }, | |
| session_id: 'configured-powershell-route' | |
| }), | |
| encoding: 'utf8', | |
| env: { | |
| ...process.env, | |
| CLAUDE_PLUGIN_ROOT: repoRoot, | |
| ECC_PLUGIN_ROOT: repoRoot, | |
| ECC_PROFILE: 'standard', | |
| GATEGUARD_STATE_DIR: stateDir, | |
| // Pin the opt-outs: an ambient disable switch would silently turn | |
| // this route into a pass-through and fail the deny assertion below. | |
| ECC_GATEGUARD: '', | |
| GATEGUARD_DISABLED: '', | |
| GATEGUARD_BASH_ROUTINE_DISABLED: '', | |
| ECC_DISABLED_HOOKS: '' | |
| }, | |
| timeout: 10000 | |
| }); |
🤖 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/hooks.test.js` around lines 2591 - 2610, Update the spawnSync
environment in the test around the route command to explicitly clear
ECC_GATEGUARD and GATEGUARD_DISABLED and remove the gateguard-fact-force entry
from ECC_DISABLED_HOOKS, while preserving the isolated GATEGUARD_STATE_DIR and
other inherited environment values.
|
| for (const tokens of quoteAwareSegments(raw)) { | ||
| if (tokens.length === 0) continue; | ||
|
|
||
| const verb = commandBasename(tokens[0]); | ||
| const rest = tokens.slice(1); | ||
|
|
||
| if (PS_NESTED_SHELLS.has(verb)) { | ||
| if (isDestructiveNestedPsShell(rest, depth)) return true; | ||
| continue; | ||
| } | ||
|
|
||
| if (!PS_DELETE_VERBS.has(verb)) continue; | ||
|
|
||
| for (const token of rest) { | ||
| // Splatted parameters (`Remove-Item @params`) are opaque to static | ||
| // inspection, so a splatted delete is gated rather than assumed safe. | ||
| if (token.startsWith('@')) return true; | ||
| if (!token.startsWith('-')) { | ||
| // PowerShell expands wildcard targets before deletion. Even without | ||
| // -Recurse or -Force, one command can therefore remove an unbounded | ||
| // number of entries. | ||
| if (token.includes('*') || token.includes('?')) return true; | ||
| continue; | ||
| } | ||
| // -Force is gated as well as -Recurse: unlike `rm -f`, PowerShell's | ||
| // `Remove-Item -Force <directory>` removes the tree. | ||
| if (isPsParamPrefixOf(token, 'recurse') || isPsParamPrefixOf(token, 'force')) { | ||
| return true; |
There was a problem hiding this comment.
PowerShell subexpressions bypass the destructive-command gate
The PowerShell pre-tool hook denies Remove-Item -Recurse -Force C:/tmp/demo, but passes $(Remove-Item -Recurse -Force C:/tmp/demo) through on a fresh session. PowerShell evaluates the statement inside $(), so a destructive deletion can execute without the fact-forcing denial. Recursively inspect quote- and nesting-aware $() bodies with the same destructive-command classifier, and add a regression test for this form.
Rule Used: Treat CLI inputs, URLs, file paths, and subprocess... (source)
Artifacts
Node hook reproduction source comparing direct and PowerShell subexpression deletes
- This executed Node-only harness sends direct and `$()` PowerShell command strings to the configured hook with fresh state directories and sessions, showing the precise comparison setup.
Initial hook comparison: direct delete denied and subexpression delete passed through
- This captured first execution shows the direct destructive command denied while the `$()` form is returned unchanged by the Node hook, confirming the bypass.
Repeated hook comparison: direct delete denied and subexpression delete passed through
- This independently repeated execution with fresh state directories and sessions reproduces the same direct-deny versus subexpression-pass-through result, confirming it is deterministic.
Focused GateGuard regression suite passes without the missing PowerShell subexpression case
- This captured focused regression run completed with 166 passing tests and zero failures, showing existing coverage does not catch the reproduced PowerShell `$()` bypass.
| /DELETE\s+FROM\s+\w+\s*(?:;|$)/i, | ||
| // PowerShell Remove-Item and its aliases with -Recurse. PowerShell accepts any | ||
| // unambiguous parameter prefix, so -Recurse, -Rec and -r must all match. | ||
| /(?:^|[\s;|(])(?:Remove-Item|Remove-ItemProperty|ri|rm|rmdir|rd|del|erase)\b[^;|]*\s-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?\b/i, |
There was a problem hiding this comment.
Destructive PowerShell denials are missing approval audit events
GateGuard denies Remove-Item -Force C:/tmp/demo, Remove-Item C:/build/*, and [System.IO.Directory]::Delete('C:/tmp/demo',$true), but governance capture emits no approval_requested event for those same payloads. The current matcher recognizes only Remove-Item-family commands using -Recurse, leaving denied destructive attempts absent from the approval trail. Expand the approval classifier—or share GateGuard's classifier—so every destructive PowerShell form GateGuard denies is recorded.
Artifacts
Node validation source for GateGuard and governance audit behavior
- This executable Node harness sends identical safe JSON payloads to the real GateGuard and governance-capture entry points without executing PowerShell, proving the audit mismatch.
Recursive PowerShell delete control emits approval audit event
- This direct governance-capture control run shows that the supported Remove-Item -Recurse form emits a high-severity approval_requested event.
GateGuard denies three destructive PowerShell forms without audit events
- This executed harness output shows GateGuard denies all representative forms but governance capture emits no approval_requested event for force-only, wildcard, and .NET deletion.
haelyra
left a comment
There was a problem hiding this comment.
Thank you for taking on the PowerShell gap, and I am sorry this has waited so long. The direction is valuable and fits the ECC 2.2 security and evidence substrate, but I cannot merge the exact head while two reproduced gaps remain: a destructive command inside a PowerShell $() subexpression bypasses the pre-execution gate, and force-only, wildcard, plus .NET deletion forms can be denied without matching approval_requested evidence. Please add quote-aware recursive subexpression parsing, align the governance classifier with every PowerShell form the gate denies, and cover those cases through the configured hook entry points. If you do not have bandwidth for that revision, no problem; I queued ECC-039 so maintainers can finish it after ECC 2.2. Thank you again for pushing this safety surface forward.
|
Thank you for catching the PowerShell GateGuard gap. This was a real security hole: before your PR, a destructive PowerShell command had no dedicated pre-execution route at all. I am sorry it took us this long to close the loop on this thread. Your PR became the source for the maintainer fix in #2961 (merged September 7), which ported your route and detection inventory, then added quote-aware |
The hole
settings.jsoncan setCLAUDE_CODE_USE_POWERSHELL_TOOL=1, which makes PowerShell a second arbitrary-command shell alongside Bash. Every destructive-command gate in this repo is scoped toBashalone, so identical destructive intent through the two tools produced opposite outcomes.Reproduced through the real
run-with-flagsinvocation path, before the fix:Why widening the matcher alone is not enough
It fails at two independent levels:
gateguard-fact-force.js—TOOL_MAPhad nopowershellkey, andif (toolName === 'Bash')was the only branch reachingisDestructiveBash(). Unrecognised tool names fall through to the bare allow at the end ofrun().governance-capture.js—SECURITY_RELEVANT_TOOLSheld only'Bash', and a second Bash-only branch guardedAPPROVAL_COMMANDS. So a command that bypassed the gate was also invisible to the audit trail. The two failures compound.Approach
PowerShell delete verbs share no syntax with POSIX
rm, so reuse of the Bash tokenizer is not possible: the PowerShell recursive-delete form reachesisDestructiveRm()as tokens whose-Forcefails its case-sensitive/f/test. Hence a dedicatedisDestructivePowerShell().It does reuse this file's existing quote-aware segmenter (
quoteAwareSegments) rather than a naiveString.split. That is deliberate — the naive split reintroduces exactly the evasion class documented in GHSA-4v57-ph3x-gf55, and reusing the hardened splitter also resolves the&call operator and quoted command words with no extra code.Coverage beyond the base case:
"C:/evil;dir/*")& 'Remove-Item' ...(call operator)&is already a segment separatorGet-ChildItem -Recurse | Remove-Item-Recursestays visiblepowershell -Command/pwsh -c/cmd /csh -chandling-EncodedCommand <base64>cmd /c rd /s /q[System.IO.Directory]::Delete($p,$true)Remove-Item @params(splatting)Parameter matching uses prefixes, because PowerShell accepts any unambiguous abbreviation:
-Recurse,-Recand-rmust all match.One deliberate departure from the
rmanalogy-Forceis gated even without-Recurse. Unlikerm -f, PowerShell'sRemove-Item -Force <directory>removes the whole tree, and a static string cannot distinguish a file target from a directory target. A plainRemove-Item <path>with neither flag stays ungated.Bash behaviour is unchanged
The PowerShell detector runs only for the PowerShell tool.
isDestructiveBash()still runs for PowerShell input so shell-agnostic phrases (force push, hard reset,DROP TABLE,dd) stay covered. Verified by differential testing of the pre- and post-fix modules across 15 representative Bash commands: 0 differences.The routine first-command gate intentionally shares
ROUTINE_BASH_SESSION_KEYacross both tools, so an operator sees one fact-forcing prompt per session rather than two. Its message is now tool-neutral ("first shell command").Verification
The two-arm test that originally proved the bug — both now deny:
Note when reproducing: the destructive gate denies only on the first attempt per session per command-hash, so use a distinct
session_idper arm or the second run will look like a false "allow".Test suites:
governance-capture.js's new rules were additionally verified by direct invocation:Remove-Item -Recurse,-Rec,rd -Recurse,Clear-Content,Format-Volumeand force-push all raiseapproval_requested;Get-ChildItemdoes not; andStart-Process -Verb RunAsnow raisessecurity_finding: elevated_privilege_command, which was unreachable before becausePowerShellwas absent fromSECURITY_RELEVANT_TOOLS.Review
Reviewed by two independent reviewers (security and code-quality), both of which initially returned BLOCK on the first draft with live-verified bypasses. Every bypass they demonstrated — quoted-separator evasion, pipe-to-delete, call operator, bare
-Forceon a directory, nested shell,cmd /c, backtick obfuscation, splatting, .NET delete — is now a named regression test in this PR.Known residual risk (not addressed here)
Static command inspection has a ceiling, and PowerShell's unrestricted .NET access raises it. These remain undetected and are not claimed as covered:
Invoke-Expression/iexover a runtime-constructed string$r='-Recurse'; Remove-Item $r $p)IO.Directory/IO.Filedelete pattern matched hereThese are the same limits the Bash path has. The gate is a fact-forcing speed bump, not a sandbox, and it should not be described as one.
Suggested follow-up (not in this PR)
tests/hooks/governance-capture.test.jshas no PowerShell cases; the new rules there are verified by manual invocation (above) but not by the suite. Worth adding alongside.