summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-11 00:12:42 +0000
committerClaude <noreply@anthropic.com>2026-11-11 00:12:42 +0000
commitdd8045d9111fd00eb6af95f556d49e71c2e64afe (patch)
tree5e26561430626b6bb6298994c24e046888f22531
parentf699b405631107dd0658f74178381f8500d43408 (diff)
parent97a623ab987f54e967e903aba9d57c94e4e9d026 (diff)
Merge branch 'mhegazy/sg-powershell-commit-hooks' into mhegazy/sg2020batchmhegazy/sg2020batch
Co-authored-by: mhegazy <mhegazy@anthropic.com>
-rw-r--r--plugins/security-guidance/hooks/diffstate.py4
-rw-r--r--plugins/security-guidance/hooks/hooks.json21
-rw-r--r--plugins/security-guidance/hooks/reporesolve.py25
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py13
-rw-r--r--plugins/security-guidance/tests/test_repo_resolution.py67
5 files changed, 123 insertions, 7 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 6df7a5c6..255fdcce 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -726,8 +726,8 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0):
# ─── commits of a turn, count only ──────────────────────────────────────────
#
-# A commit review starts from a hook on the Bash tool. A commit made another
-# way (the PowerShell tool, a script, the user's own terminal) starts none.
+# A commit review starts from a hook on the Bash or PowerShell tool. A commit
+# made another way (a script, the user's own terminal) starts none.
# The Stop row says how many commits a turn made and how many of them no
# commit hook saw. Nothing reads these to decide whether a review runs.
#
diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json
index eef54730..138dae00 100644
--- a/plugins/security-guidance/hooks/hooks.json
+++ b/plugins/security-guidance/hooks/hooks.json
@@ -60,6 +60,27 @@
}
],
"matcher": "Bash"
+ },
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"",
+ "if": "PowerShell(git*commit*)",
+ "asyncRewake": true,
+ "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:",
+ "rewakeSummary": "Security review found issues"
+ },
+ {
+ "type": "command",
+ "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"",
+ "if": "PowerShell(git*push*)",
+ "asyncRewake": true,
+ "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:",
+ "rewakeSummary": "Security review found issues"
+ }
+ ],
+ "matcher": "PowerShell"
}
],
"Stop": [
diff --git a/plugins/security-guidance/hooks/reporesolve.py b/plugins/security-guidance/hooks/reporesolve.py
index 7611cfaf..c00a752c 100644
--- a/plugins/security-guidance/hooks/reporesolve.py
+++ b/plugins/security-guidance/hooks/reporesolve.py
@@ -26,10 +26,13 @@ SCAN_MAX_DEPTH = int(os.environ.get("SG_REPO_SCAN_MAX_DEPTH", "3"))
SCAN_MAX_REPOS = int(os.environ.get("SG_REPO_SCAN_MAX_REPOS", "64"))
SCAN_BUDGET_S = float(os.environ.get("SG_REPO_SCAN_BUDGET_S", "4"))
-_SEPARATORS = frozenset(";&|()\n")
+_SEPARATORS = frozenset(";&|(){}\n")
_SHA_RE = re.compile(r"^[0-9a-f]{7,40}$")
_ENV_ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
_PREFIX_WORDS = frozenset(("env", "time", "exec", "command", "nohup"))
+_CHANGE_DIR_WORDS = frozenset(("cd", "pushd", "set-location", "push-location"))
+_PUSH_DIR_WORDS = frozenset(("pushd", "push-location"))
+_POP_DIR_WORDS = frozenset(("popd", "pop-location"))
def _abs(base, p):
@@ -47,6 +50,10 @@ def _is_sep(tok):
def _tokenize(command):
+ # shlex reads a line end as a space, but it ends a statement, unless a
+ # backslash or a PowerShell backtick continues the line.
+ command = re.sub(r"[\\`]\r?\n", " ", command)
+ command = re.sub(r"\r?\n", " ; ", command)
if os.sep == "\\":
command = command.replace("\\", "\\\\")
try:
@@ -66,6 +73,7 @@ def dirs_from_command(command, cwd, subcommands=None):
tokens = _tokenize(command)
out = []
cur = cwd or ""
+ pushed = []
i = 0
n = len(tokens)
at_start = True
@@ -78,7 +86,18 @@ def dirs_from_command(command, cwd, subcommands=None):
if at_start and (_ENV_ASSIGN_RE.match(t) or t in _PREFIX_WORDS):
i += 1
continue
- if at_start and t in ("cd", "pushd"):
+ if at_start and t.lower() in _POP_DIR_WORDS:
+ if pushed:
+ cur = pushed.pop()
+ i += 1
+ at_start = False
+ continue
+ if at_start and t.lower() in _CHANGE_DIR_WORDS:
+ if t.lower() in _PUSH_DIR_WORDS:
+ pushed.append(cur)
+ # PowerShell names the folder with an optional -Path.
+ if i + 2 < n and tokens[i + 1].lower() in ("-path", "-literalpath"):
+ i += 1
if i + 1 < n and not _is_sep(tokens[i + 1]) and tokens[i + 1] not in ("-",) \
and not tokens[i + 1].startswith("-"):
nxt = _abs(cur, tokens[i + 1])
@@ -90,6 +109,8 @@ def dirs_from_command(command, cwd, subcommands=None):
at_start = False
continue
prog = os.path.basename(t) if t else t
+ if prog.lower() in ("git", "git.exe", "git.cmd"):
+ prog = "git"
if at_start and prog in ("git", "gt"):
j = i + 1
cdir = cur
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index e0c25754..d0c82f6c 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -1106,12 +1106,15 @@ _GIT_GLOBAL_OPTS = (
# `--help` / `--version` run no subcommand.
+ r'|\s+(?:--(?!(?:' + _GIT_VALUE_OPTS + r'|help|version)\s)[^\s=]+|-[pP])(?=\s))*'
)
+# PowerShell runs programs by any case and with their extension, and a quoted
+# full path ends in a quote.
+_GIT_PROGRAM = r"""(?i:git(?:\.(?:exe|cmd))?)["']?"""
_GIT_COMMIT_RE = re.compile(
# Without the global-option tolerance, `git -C /repo commit` is silently
# dropped by the handler — see #2089's secondary finding. The gt branch
# has no global-option layer to worry about.
# `(?!-)`: not the plumbing commands `git commit-graph` / `git commit-tree`.
- r'\bgit' + _GIT_GLOBAL_OPTS + r'\s+commit\b(?!-)'
+ r'\b' + _GIT_PROGRAM + _GIT_GLOBAL_OPTS + r'\s+commit\b(?!-)'
r'|\bgt\s+(?:create|modify)\b'
)
# Match either the `--amend` flag (with the leading whitespace boundary
@@ -1152,7 +1155,7 @@ COMMIT_REVIEW_RATE_WINDOW_S = int(
# but the bash hook fires on Claude's top-level command so we need to
# recognize gt submit at the matcher level. See #2048.
_GIT_PUSH_RE = re.compile(
- r'(?:\bgit' + _GIT_GLOBAL_OPTS + r'\s+push\b|\bgt\s+submit\b)'
+ r'(?:\b' + _GIT_PROGRAM + _GIT_GLOBAL_OPTS + r'\s+push\b|\bgt\s+submit\b)'
)
# `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on
@@ -3311,6 +3314,9 @@ def main():
tool_input = input_data.get("tool_input", {})
hook_event_name = input_data.get("hook_event_name", "")
debug_log(f"Processing: hook_event={hook_event_name}, tool={tool_name}")
+ if tool_name == "PowerShell":
+ # Same fields and same git commands as Bash: commit review and push sweep.
+ tool_name = "Bash"
# Load project-specific security guidance and custom patterns once
# per invocation. Failures are non-fatal (debug-logged) so a malformed
@@ -3367,7 +3373,8 @@ def main():
# it, and say whether a plain text check could have told so before
# Python. Both values carry the sample weight, so they sum to
# estimates of all such starts.
- if _unmatched_bash_sampled(input_data) and not portable_output():
+ if (input_data.get("tool_name") == "Bash" and _unmatched_bash_sampled(input_data)
+ and not portable_output()):
skip = 0 if _shell_precheck_passes(raw_input) else _UNMATCHED_BASH_SAMPLE
emit_metrics({"bash_no_match": _UNMATCHED_BASH_SAMPLE, "precheck_skip": skip})
return
diff --git a/plugins/security-guidance/tests/test_repo_resolution.py b/plugins/security-guidance/tests/test_repo_resolution.py
index 05ac597c..937ba5f9 100644
--- a/plugins/security-guidance/tests/test_repo_resolution.py
+++ b/plugins/security-guidance/tests/test_repo_resolution.py
@@ -642,3 +642,70 @@ class TestStop:
m = metrics_of(so)
assert m["skip_reason"] == 9 and m["repo_resolution"] == rr.RES_NONE
assert not stub_api.calls
+
+
+class TestPowerShellTool:
+ def _payload(self, ws, command, out):
+ return {**bash_payload(ws, command, out), "tool_name": "PowerShell"}
+
+ def test_commit_is_reviewed(self, workspace, hook_env, stub_api):
+ ws, repo = workspace
+ sha, out = commit_file(repo, "app.py", VULN_PY)
+ rc, so, se = run_hook(self._payload(ws, "git commit -m change", out), hook_env)
+ m = metrics_of(so)
+ assert m.get("skip_reason") is None and m["files_reviewed"] == 1, m
+
+ def test_git_exe_commit_is_reviewed(self, workspace, hook_env, stub_api):
+ ws, repo = workspace
+ sha, out = commit_file(repo, "app.py", VULN_PY)
+ rc, so, se = run_hook(self._payload(repo, "git.exe commit -m change", out), hook_env)
+ assert metrics_of(so)["files_reviewed"] == 1
+
+ def test_other_command_starts_no_review(self, workspace, hook_env, stub_api):
+ ws, repo = workspace
+ rc, so, se = run_hook(self._payload(repo, "Get-ChildItem | Select-Object Name", ""), hook_env)
+ assert rc == 0 and not so.strip()
+
+ @pytest.mark.parametrize("command", [
+ "Set-Location {d}; git commit -m x",
+ "set-location -Path {d}; git commit -m x",
+ "Push-Location -LiteralPath {d}; git.exe commit -m x",
+ "cd {d}; git.exe commit -m x",
+ "Push-Location {d}\ngit commit -m x\nPop-Location",
+ "Set-Location {d}; if ($?) {{ git commit -m x }}",
+ "Git.EXE -C {d} commit -m x",
+ ])
+ def test_folder_from_the_command(self, tmp_path, command):
+ target = tmp_path / "work"
+ got = rr.dirs_from_command(command.format(d=target), str(tmp_path), {("git", "commit")})
+ assert got == [str(target)]
+
+ def test_push_location_ends_at_pop_location(self, tmp_path):
+ command = f"Push-Location {tmp_path / 'other'}; git status; Pop-Location; git commit -m x"
+ assert rr.dirs_from_command(command, str(tmp_path), {("git", "commit")}) == [str(tmp_path)]
+
+ @pytest.mark.parametrize("command", [
+ "git.exe push", "GIT push origin main", "& 'C:\\Git\\cmd\\git.exe' push",
+ ])
+ def test_push_spellings(self, command):
+ assert hook._GIT_PUSH_RE.search(command)
+
+ @pytest.mark.parametrize("command", [
+ "Git commit -m x", "git.cmd commit -m x", '& "C:\\Program Files\\Git\\cmd\\git.exe" commit -m x',
+ ])
+ def test_commit_spellings(self, command):
+ assert hook._GIT_COMMIT_RE.search(command)
+
+ def test_git_commit_tree_is_still_left_alone(self):
+ assert not hook._GIT_COMMIT_RE.search("git.exe commit-tree abc")
+
+ def test_bash_line_continuation_stays_one_statement(self, tmp_path):
+ got = rr.dirs_from_command("git \\\n commit -m x", str(tmp_path), {("git", "commit")})
+ assert got == [str(tmp_path)]
+
+ def test_hook_entries(self):
+ with open(os.path.join(HOOKS_DIR, "hooks.json")) as f:
+ groups = json.load(f)["hooks"]["PostToolUse"]
+ group = next(g for g in groups if g["matcher"] == "PowerShell")
+ assert [h["if"] for h in group["hooks"]] == ["PowerShell(git*commit*)", "PowerShell(git*push*)"]
+ assert all(h["asyncRewake"] for h in group["hooks"])