summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-04 19:22:04 +0000
committerClaude <noreply@anthropic.com>2026-11-04 19:22:04 +0000
commit18b39784432502087fefa2afe459ed23b56e9dd9 (patch)
tree3d4e98dd5cd2c7b94b9053506215c06ab84b8faf /plugins
parentfa4eb54397ee2faccb6940512a19c017cb1337f3 (diff)
security-guidance: count Bash hook starts that match no commit or push
Measurement only. One Bash call in ten that starts the hook without a commit or push reports bash_no_match, and precheck_skip when a plain text check on the hook input could have told so before Python started. precheck_miss marks a reviewed command that such a check would have dropped. Nothing is skipped and no review changes.
Diffstat (limited to 'plugins')
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py62
-rw-r--r--plugins/security-guidance/tests/test_unmatched_bash_metric.py138
2 files changed, 199 insertions, 1 deletions
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 3efe344e..c6b7badb 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -324,6 +324,10 @@ def emit_metrics(
# names on PATH were launcher aliases that cannot read the plugin files.
if os.environ.get("SG_LAUNCHER_FALLBACK") == "1":
head["launcher_fallback"] = 1
+ if _precheck_miss:
+ # Up front: this is the key that says a text check would have lost a
+ # review, so it must not be the one cut by the key cap.
+ head["precheck_miss"] = 1
usage = _usage_metrics()
head.update(usage)
# Why the last call got no HTTP response (api_error -1 says only that it
@@ -1056,6 +1060,47 @@ try:
except ValueError:
INFLIGHT_WAIT_S = 240
+# Word pairs a shell `case` pattern (`*git*commit*|*git*push*|...`) would look
+# for in the raw hook input: wider than _GIT_COMMIT_RE / _GIT_PUSH_RE, so a
+# command those match always contains one of these pairs in this order.
+_SHELL_PRECHECK_PAIRS = (
+ ("git", "commit"), ("git", "push"),
+ ("gt", "create"), ("gt", "modify"), ("gt", "submit"),
+)
+# One in this many unmatched Bash calls reports, to keep the row count down.
+_UNMATCHED_BASH_SAMPLE = 10
+# Set when a command that is reviewed would not have passed the text check.
+_precheck_miss = False
+
+
+def _shell_precheck_passes(raw):
+ """True when `raw` holds one of _SHELL_PRECHECK_PAIRS, first word first.
+
+ Measurement only. Tells how many hook starts that match no commit or push
+ a text check in the launcher could avoid (`precheck_skip`), and whether
+ that check would ever drop a command that is reviewed (`precheck_miss`).
+ """
+ for first, second in _SHELL_PRECHECK_PAIRS:
+ at = raw.find(first)
+ if at != -1 and raw.find(second, at + len(first)) != -1:
+ return True
+ return False
+
+
+def _unmatched_bash_sampled(input_data):
+ """Pick the same one call in _UNMATCHED_BASH_SAMPLE in every start of it.
+
+ One Bash call can start this hook once per hooks.json entry, so the choice
+ is made from the call's id: all its starts report or none do. A call with
+ no id is not reported.
+ """
+ tool_use_id = input_data.get("tool_use_id")
+ if not isinstance(tool_use_id, str) or not tool_use_id:
+ return False
+ digest = hashlib.sha256(tool_use_id.encode("utf-8", "replace")).digest()
+ return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0
+
+
def _claim_bash_hook_once(input_data):
"""De-dupe across hooks.json `if` matchers firing for the same Bash call.
@@ -2977,12 +3022,27 @@ def main():
if tool_name == "Bash" and hook_event_name == "PostToolUse":
cmd = (input_data.get("tool_input") or {}).get("command", "") or ""
if not (_GIT_COMMIT_RE.search(cmd) or _GIT_PUSH_RE.search(cmd)):
+ # Measurement only: this start matched no commit or push. Count
+ # 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():
+ skip = 0 if _shell_precheck_passes(raw_input) else _UNMATCHED_BASH_SAMPLE
+ emit_metrics({"bash_no_match": _UNMATCHED_BASH_SAMPLE, "precheck_skip": skip})
return
+ if not _shell_precheck_passes(raw_input):
+ # The text check would have dropped a command that is reviewed.
+ # Rides on whichever row this start emits; nothing is skipped.
+ global _precheck_miss
+ _precheck_miss = True
if not _claim_bash_hook_once(input_data):
# Another spawn for this same tool_use_id already claimed the
# work (compound matched multiple `if` configs). Emit a single
# metric so telemetry can count how often the de-dupe kicks in.
- _write_hook_output({"metrics": {"bash_hook_dedup": True}})
+ dedup = {"bash_hook_dedup": True}
+ if _precheck_miss and not portable_output():
+ dedup = {"pv": _PV, "precheck_miss": 1, **dedup}
+ _write_hook_output({"metrics": dedup})
sys.exit(0)
if _GIT_COMMIT_RE.search(cmd):
handle_commit_review_posttooluse(input_data)
diff --git a/plugins/security-guidance/tests/test_unmatched_bash_metric.py b/plugins/security-guidance/tests/test_unmatched_bash_metric.py
new file mode 100644
index 00000000..c6aec681
--- /dev/null
+++ b/plugins/security-guidance/tests/test_unmatched_bash_metric.py
@@ -0,0 +1,138 @@
+"""Bash hook starts that match no commit or push are counted; nothing changes."""
+import itertools
+import json
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOK_SCRIPT, STUB_VULN, VULN_PY, bash_payload, commit_file, metrics_of, run_hook
+
+import security_reminder_hook as hook
+
+WEIGHT = hook._UNMATCHED_BASH_SAMPLE
+SHELL_PATTERN = "|".join(f"*{a}*{b}*" for a, b in hook._SHELL_PRECHECK_PAIRS)
+
+
+def _call_id(sampled):
+ for n in itertools.count():
+ tool_use_id = f"toolu_{n}"
+ if hook._unmatched_bash_sampled({"tool_use_id": tool_use_id}) is sampled:
+ return tool_use_id
+
+
+def _raw(command, stdout="ok"):
+ return json.dumps(bash_payload("/w", command, stdout=stdout))
+
+
+def test_unmatched_call_reports_what_a_text_check_would_do(workspace, hook_env):
+ ws, _ = workspace
+ loop = bash_payload("/w", "for f in a b; do echo $f; done", tool_use_id=_call_id(True))
+ rc, so, se = run_hook(loop, hook_env)
+ m = metrics_of(so)
+ assert rc == 0 and se == ""
+ assert m["bash_no_match"] == WEIGHT and m["precheck_skip"] == WEIGHT and m["pv"]
+
+ # Text mentions pass a text check and still match nothing.
+ for command, stdout in (("git log --grep commit", ""), ("ls", "run git push next")):
+ p = bash_payload("/w", command, stdout, tool_use_id=_call_id(True))
+ rc, so, se = run_hook(p, hook_env)
+ m = metrics_of(so)
+ assert rc == 0 and m["bash_no_match"] == WEIGHT and m["precheck_skip"] == 0
+
+
+def test_unsampled_call_stays_silent(workspace, hook_env):
+ loop = "for f in a b; do echo $f; done"
+ assert run_hook(bash_payload("/w", loop, tool_use_id=_call_id(False)), hook_env) == (0, "", "")
+ assert run_hook(bash_payload("/w", loop), hook_env) == (0, "", "") # no call id
+
+
+def test_other_hosts_get_no_row(workspace, 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"
+ p = bash_payload("/w", "for f in a b; do echo $f; done", tool_use_id=_call_id(True))
+ assert run_hook(p, env) == (0, "", "")
+
+
+def test_one_call_in_ten_is_sampled():
+ picked = sum(hook._unmatched_bash_sampled({"tool_use_id": f"toolu_{n}"}) for n in range(20000))
+ assert 20000 / WEIGHT * 0.85 < picked < 20000 / WEIGHT * 1.15
+ assert not hook._unmatched_bash_sampled({}) and not hook._unmatched_bash_sampled({"tool_use_id": 7})
+
+
+def test_pairs_cover_every_verb_in_the_regexes():
+ # A verb added to either regex has to be added to _SHELL_PRECHECK_PAIRS
+ # and to _commands() below.
+ assert hook._GIT_COMMIT_RE.pattern.endswith(r"\s+commit\b(?!-)|\bgt\s+(?:create|modify)\b")
+ assert hook._GIT_PUSH_RE.pattern.endswith(r"\s+push\b|\bgt\s+submit\b)")
+
+
+def _commands():
+ """Commands the commit and push regexes match, in the spellings they allow."""
+ opts = ["", " -C sub", " -c user.name=x", " -c 'a.b=c d'", " --git-dir=.git", " --no-pager",
+ " -P", " --namespace=n", " --work-tree .", " -C a -c b=c --no-pager"]
+ seps = [" ", "\t", " ", "\n"]
+ heads = ["", "cd x && ", "FOO=1 ", "(", "for i in 1; do ", "echo \"$(", "/usr/bin/", "x=`"]
+ for head, opt, sep, verb in itertools.product(heads, opts, seps, ["commit", "push"]):
+ yield f"{head}git{opt}{sep}{verb} -m 'é \"q\" \\ done'"
+ for head, sep, verb in itertools.product(heads, seps, ["create", "modify", "submit"]):
+ yield f"{head}gt{sep}{verb} --all"
+
+
+def test_text_check_never_drops_a_reviewed_command():
+ matched = [c for c in _commands() if hook._GIT_COMMIT_RE.search(c) or hook._GIT_PUSH_RE.search(c)]
+ assert len(matched) > 600
+ for command in matched:
+ for ensure_ascii in (True, False):
+ raw = json.dumps(bash_payload("/w", command), ensure_ascii=ensure_ascii)
+ assert hook._shell_precheck_passes(raw), command
+
+
+CASES = [
+ ("ls -la | head", False),
+ ("echo commit the git way", False), # wrong order
+ ("grep -c gt app.py", False),
+ ("git status && echo 'ready to commit'", True),
+ ("gt log; echo submit", True),
+ ("git\tpush", True),
+ ("digit; echo pushed", True),
+]
+
+
+def test_text_check_on_known_strings():
+ for command, passes in CASES:
+ assert hook._shell_precheck_passes(_raw(command)) is passes, command
+
+
+@pytest.mark.skipif(not shutil.which("bash"), reason="needs bash")
+def test_text_check_agrees_with_the_shell_pattern():
+ script = f'input=$(cat); case "$input" in {SHELL_PATTERN}) echo pass ;; *) echo skip ;; esac'
+ for command, _ in CASES:
+ raw = _raw(command)
+ r = subprocess.run(["bash", "-c", script], input=raw.encode(), capture_output=True, timeout=30)
+ assert (r.stdout.strip() == b"pass") is hook._shell_precheck_passes(raw), command
+
+
+def test_reviewed_command_a_text_check_would_drop_is_flagged(workspace, hook_env, stub_api):
+ ws, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ _, out = commit_file(repo, "app.py", VULN_PY)
+ raw = json.dumps(bash_payload(repo, "git commit -m change", out))
+ # Same command, with one letter written as a JSON escape.
+ raw = raw.replace('"git commit -m change"', '"git \\u0063ommit -m change"')
+ assert json.loads(raw)["tool_input"]["command"] == "git commit -m change"
+ if hook._shell_precheck_passes(raw):
+ pytest.skip("the temporary path itself passes the text check")
+ r = subprocess.run([sys.executable, str(HOOK_SCRIPT)], input=raw, capture_output=True,
+ text=True, env=hook_env, timeout=120)
+ m = metrics_of(r.stdout)
+ assert m["precheck_miss"] == 1 and m.get("commit_review") is True
+ assert list(m).index("precheck_miss") < 3 # ahead of the row's own keys
+
+ # The ordinary spelling carries no flag.
+ _, out = commit_file(repo, "b.py", VULN_PY)
+ rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), hook_env)
+ m = metrics_of(so)
+ assert m.get("commit_review") is True and "precheck_miss" not in m