summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--plugins/security-guidance/hooks/hooks.json17
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py62
-rw-r--r--plugins/security-guidance/tests/test_powershell_metric.py155
3 files changed, 234 insertions, 0 deletions
diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json
index eef54730..6065fdad 100644
--- a/plugins/security-guidance/hooks/hooks.json
+++ b/plugins/security-guidance/hooks/hooks.json
@@ -60,6 +60,23 @@
}
],
"matcher": "Bash"
+ },
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\" commit",
+ "if": "PowerShell(git*commit*)",
+ "asyncRewake": true
+ },
+ {
+ "type": "command",
+ "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\" push",
+ "if": "PowerShell(git*push*)",
+ "asyncRewake": true
+ }
+ ],
+ "matcher": "PowerShell"
}
],
"Stop": [
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index c6b7badb..7381d3fc 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -1101,6 +1101,60 @@ def _unmatched_bash_sampled(input_data):
return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0
+# `git` in any letter case, `git.exe` and a quoted path to it, which PowerShell
+# all runs as git: wider than _GIT_COMMIT_RE / _GIT_PUSH_RE on purpose. Only the
+# calls the hooks.json `if` patterns let through are seen, so `gt` and a path
+# such as `& 'C:\...\git.exe' push` mostly are not.
+_PS_GIT_RE = re.compile(
+ r"""\b(?i:git(?:\.exe["']?)?)""" + _GIT_GLOBAL_OPTS + r'\s+(commit\b(?!-)|push\b)'
+)
+# skip_reason codes of the rows below.
+_SKIP_PS = {"commit": 50, "push": 51}
+
+
+def _powershell_row(input_data, entry):
+ """Metrics for one PowerShell tool call, or None for no row.
+
+ Measurement only: commits and pushes made through the PowerShell tool are
+ not reviewed, and this says how many there are. Numbers and flags only;
+ nothing of the command or its output is kept.
+
+ `entry` is the hooks.json entry that started this process ("commit" or
+ "push"); each reports its own kind, so a call that does both gives one row
+ of each, marked `ps_both`.
+ """
+ tool_input = input_data.get("tool_input")
+ command = tool_input.get("command") if isinstance(tool_input, dict) else None
+ if not isinstance(command, str) or entry not in _SKIP_PS:
+ return None
+ found = {}
+ for m in _PS_GIT_RE.finditer(command):
+ found.setdefault(m.group(1), m.group(0))
+ if not found:
+ # Started only because Claude Code could not parse the command, or it
+ # is another git command with one of the words in it. Per start, as
+ # for Bash: one call can start both entries.
+ if _unmatched_bash_sampled(input_data):
+ return {"ps_no_match": _UNMATCHED_BASH_SAMPLE}
+ return None
+ if entry not in found:
+ return None
+ known = _GIT_COMMIT_RE if entry == "commit" else _GIT_PUSH_RE
+ resp = input_data.get("tool_response")
+ resp = resp if isinstance(resp, dict) else {}
+ op = resp.get("gitOperation")
+ return {
+ "skip_reason": _SKIP_PS[entry],
+ # Whether the Bash patterns would recognise this spelling.
+ "ps_known": bool(known.search(found[entry])),
+ # Whether Claude Code itself saw the commit or push happen.
+ "ps_op": isinstance(op, dict) and entry in op,
+ "ps_both": len(found) == 2,
+ "ps_on": ENABLE_CODE_SECURITY_REVIEW and (
+ COMMIT_REVIEW_ENABLED if entry == "commit" else PUSH_SWEEP_ENABLED),
+ }
+
+
def _claim_bash_hook_once(input_data):
"""De-dupe across hooks.json `if` matchers firing for the same Bash call.
@@ -2970,6 +3024,14 @@ def main():
hook_event_name = input_data.get("hook_event_name", "")
debug_log(f"Processing: hook_event={hook_event_name}, tool={tool_name}")
+ # PostToolUse[PowerShell]: count commits and pushes, review nothing.
+ if tool_name == "PowerShell":
+ if hook_event_name == "PostToolUse" and not portable_output():
+ row = _powershell_row(input_data, sys.argv[1] if len(sys.argv) > 1 else "")
+ if row:
+ emit_metrics(row)
+ return
+
# Load project-specific security guidance and custom patterns once
# per invocation. Failures are non-fatal (debug-logged) so a malformed
# config never prevents the built-in checks from running.
diff --git a/plugins/security-guidance/tests/test_powershell_metric.py b/plugins/security-guidance/tests/test_powershell_metric.py
new file mode 100644
index 00000000..2e4bfd49
--- /dev/null
+++ b/plugins/security-guidance/tests/test_powershell_metric.py
@@ -0,0 +1,155 @@
+"""Commits and pushes made through the PowerShell tool are counted; nothing is reviewed."""
+import json
+import os
+import subprocess
+import sys
+import time
+
+import pytest
+
+from conftest import (
+ HOOK_SCRIPT, HOOKS_DIR, STUB_VULN, VULN_PY, bash_payload, commit_file, metrics_of,
+)
+
+import security_reminder_hook as hook
+
+COMMIT_OUT = "[main 1a2b3c4] change\n 1 file changed, 1 insertion(+)\n"
+
+
+def _payload(cwd, command, stdout="", tool_use_id="toolu_x", **response):
+ p = bash_payload(cwd, command, stdout, tool_use_id=tool_use_id)
+ p["tool_name"] = "PowerShell"
+ p["tool_response"].update(response)
+ return p
+
+
+def _run(payload, env, *args):
+ r = subprocess.run([sys.executable, str(HOOK_SCRIPT), *args], input=json.dumps(payload),
+ capture_output=True, text=True, env=env, timeout=120)
+ return r.returncode, r.stdout, r.stderr
+
+
+def _sampled_id(sampled):
+ for n in range(1000):
+ tid = f"toolu_{n}"
+ if hook._unmatched_bash_sampled({"tool_use_id": tid}) is sampled:
+ return tid
+
+
+def test_commit_is_counted_and_not_reviewed(workspace, hook_env, stub_api):
+ ws, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ _, out = commit_file(repo, "app.py", VULN_PY)
+ before = sorted(os.listdir(os.path.join(repo, ".git")))
+ rc, so, se = _run(_payload(repo, "git commit -m change", out), hook_env, "commit")
+ m = metrics_of(so)
+ assert rc == 0 and se == "" and not stub_api.calls
+ assert m["skip_reason"] == 50 and m["pv"]
+ assert m["ps_known"] is True and m["ps_op"] is False and m["ps_on"] is True
+ # No claim file, no reviewed sha: the next push from Bash still sees the commit.
+ assert sorted(os.listdir(os.path.join(repo, ".git"))) == before
+ # Keys that mark a Bash commit review stay off this row.
+ assert not {"skipped", "commit_review", "push_sweep"} & set(m)
+
+
+def test_the_row_holds_only_numbers_and_flags(workspace, hook_env):
+ rc, so, _ = _run(_payload("/w", "git commit -m 'secret words'", COMMIT_OUT), hook_env, "commit")
+ out = json.loads(so)
+ assert list(out) == ["metrics"]
+ assert all(isinstance(v, (bool, int, float)) for v in out["metrics"].values())
+ assert "secret" not in so and "1a2b3c4" not in so
+
+
+@pytest.mark.parametrize("command,kinds,known", [
+ ("git commit -m x", {"commit"}, True),
+ ("git -C sub commit -m x", {"commit"}, True),
+ ("git push origin main", {"push"}, True),
+ ("git add -A; git commit -m x; git push", {"commit", "push"}, True),
+ ("git commit --amend --no-edit", {"commit"}, True),
+ ("git.exe commit -m x", {"commit"}, False),
+ ("git.exe commit -m 'git commit fix'", {"commit"}, False),
+ ("GIT commit -m x", {"commit"}, False),
+ ("& 'C:\\Program Files\\Git\\cmd\\git.exe' push", {"push"}, False),
+ ('& "C:\\Program Files\\Git\\cmd\\git.exe" -C sub commit -m x', {"commit"}, False),
+ ("if ($?) { git commit -m x }", {"commit"}, True),
+ ("git commit -m @'\nline\n'@", {"commit"}, True),
+])
+def test_spellings(command, kinds, known):
+ for entry in ("commit", "push"):
+ row = hook._powershell_row(_payload("/w", command), entry)
+ if entry in kinds:
+ assert row["skip_reason"] == {"commit": 50, "push": 51}[entry]
+ assert row["ps_known"] is known and row["ps_both"] is (len(kinds) == 2)
+ else:
+ assert row is None
+
+
+@pytest.mark.parametrize("command", [
+ "git status", "git commit-graph write", "git stash push", "Get-ChildItem | Select-Object Name",
+ "digit commit", "git log --grep push-it", "Get-Content commit.txt", "git --help commit",
+ 'Write-Host "Git Commit failed"', # subcommands are lower case
+])
+def test_other_commands_are_not_counted_as_commits(command):
+ for entry in ("commit", "push"):
+ p = _payload("/w", command, tool_use_id=_sampled_id(False))
+ assert hook._powershell_row(p, entry) is None
+ p = _payload("/w", command, tool_use_id=_sampled_id(True))
+ assert hook._powershell_row(p, entry) == {"ps_no_match": hook._UNMATCHED_BASH_SAMPLE}
+
+
+@pytest.mark.parametrize("op,entry,seen", [
+ ({"commit": {"sha": "1a2b3c4", "kind": "committed"}}, "commit", True),
+ ({"commit": {"sha": "1a2b3c4", "kind": "committed"}}, "push", False),
+ ({"push": {"branch": "main"}}, "push", True),
+ (None, "commit", False), ("commit", "commit", False),
+])
+def test_whether_claude_code_saw_it_happen(op, entry, seen):
+ p = _payload("/w", "git commit -m x; git push", gitOperation=op)
+ assert hook._powershell_row(p, entry)["ps_op"] is seen
+
+
+def test_reviews_turned_off_are_marked(hook_env):
+ for var, kind in (("ENABLE_COMMIT_REVIEW", "commit"), ("ENABLE_CODE_SECURITY_REVIEW", "commit"),
+ ("ENABLE_CODE_SECURITY_REVIEW", "push")):
+ _, so, _ = _run(_payload("/w", f"git {kind}"), {**hook_env, var: "0"}, kind)
+ assert metrics_of(so)["ps_on"] is False, var
+
+
+@pytest.mark.parametrize("change", [
+ {"tool_input": None}, {"tool_input": {}}, {"tool_input": "git commit"}, {"tool_input": ["a"]}, {"tool_input": {"command": ["git", "commit"]}},
+ {"tool_input": {"command": "git commit"}, "tool_response": "text"},
+ {"tool_input": {"command": "git commit"}, "tool_response": None},
+])
+def test_odd_payloads_never_fail(hook_env, change):
+ p = {**_payload("/w", "x", tool_use_id=_sampled_id(False)), **change}
+ for args in (["commit"], ["push"], []):
+ rc, _, se = _run(p, hook_env, *args)
+ assert rc == 0 and se == ""
+
+
+def test_other_hosts_and_other_events_get_no_row(hook_env):
+ markers = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "SECURITY_GUIDANCE_PORTABLE_OUTPUT")
+ env = {k: v for k, v in hook_env.items() if k not in markers}
+ env["PLUGIN_ROOT"] = "/p"
+ assert _run(_payload("/w", "git commit -m x"), env, "commit") == (0, "", "")
+ p = {**_payload("/w", "git commit -m x"), "hook_event_name": "PreToolUse"}
+ assert _run(p, hook_env, "commit") == (0, "", "")
+
+
+def test_the_pattern_is_linear():
+ t0 = time.perf_counter()
+ assert not hook._PS_GIT_RE.search("git " + '-c "git" ' * 3000)
+ assert time.perf_counter() - t0 < 0.5
+ for unit in ('-c "a"', "--no-a=b", "--git-dir x", "--no-pager", '-c a="b c"'):
+ t0 = time.perf_counter()
+ assert not hook._PS_GIT_RE.search("git " + " ".join([unit] * 40) + " commitfoo")
+ assert time.perf_counter() - t0 < 0.05
+
+
+def test_hooks_json_entries():
+ post = json.loads((HOOKS_DIR / "hooks.json").read_text())["hooks"]["PostToolUse"]
+ group = [g for g in post if g.get("matcher") == "PowerShell"][0]["hooks"]
+ assert [(h["if"], h["command"].rsplit(" ", 1)[1]) for h in group] == [
+ ("PowerShell(git*commit*)", "commit"), ("PowerShell(git*push*)", "push")]
+ # In the background, so the tool call never waits for a count.
+ assert all(h["asyncRewake"] is True for h in group)