summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-10 19:15:59 +0000
committerClaude <noreply@anthropic.com>2026-11-10 19:32:30 +0000
commita8a2c783f7537cdd59cb8a47072c8f2d89d258ff (patch)
treef9341eaa0bfbafa78d670ae591787bfe5bb7b3b0 /plugins
parentdceb15d50832e6adf380bedc26dde03d251324b9 (diff)
security-guidance: review what a commit-and-push command sends out beyond its own commitmhegazy/sg-chained-push-review
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py54
-rw-r--r--plugins/security-guidance/tests/test_chained_commit_push.py112
-rw-r--r--plugins/security-guidance/tests/test_repo_resolution.py5
3 files changed, 157 insertions, 14 deletions
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index b02dcab7..538079cc 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -1209,7 +1209,7 @@ def _unmatched_bash_sampled(input_data):
return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0
-def _claim_bash_hook_once(input_data):
+def _claim_bash_hook_once(input_data, route="once"):
"""De-dupe across hooks.json `if` matchers firing for the same Bash call.
`git commit -m x && git push` matches both `Bash(git*commit*)` and
@@ -1255,7 +1255,9 @@ def _claim_bash_hook_once(input_data):
# Sanitize tuid into a filesystem-safe basename — defensive, the value is
# CC-generated (toolu_<b64ish>), but it ends up in a path.
safe = re.sub(r"[^A-Za-z0-9_-]", "_", tuid)[:80]
- sentinel = os.path.join(gd, f"sg-hook-once-{safe}")
+ # A second route ("push") lets the other spawn of a commit-and-push run
+ # its own review, once.
+ sentinel = os.path.join(gd, f"sg-hook-once-{safe}" + ("" if route == "once" else f"-{route}"))
try:
fd = os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
os.close(fd)
@@ -2260,6 +2262,21 @@ def handle_commit_review_posttooluse(input_data):
# uses as the "force fix" signal that triggers the rewakeMessage flow.
sys.exit(2)
+def _pushed_beyond_commit_review(repo_root, push_range, bash_output):
+ """True when a command that both commits and pushes sent out a commit no
+ review covers. The other spawn's commit review takes the commit the
+ output names last, or the reflog's fresh ones when the output hides them.
+ """
+ covered = []
+ if COMMIT_REVIEW_ENABLED:
+ named = _COMMIT_SHA_RE.findall(bash_output)
+ covered = named[-1:] or _git_reflog_recent_commits(repo_root)[0]
+ rest = [s for s in push_range if not any(s.startswith(c) for c in covered)]
+ reviewed = _load_reviewed_shas(repo_root)
+ held = _load_inflight_shas(repo_root, rest)
+ return any(s not in reviewed and s not in held for s in rest)
+
+
def handle_push_sweep_posttooluse(input_data):
"""Review the just-pushed range as one diff, advancing the base past the
contiguous prefix of already-per-commit-reviewed shas.
@@ -2437,6 +2454,12 @@ def handle_push_sweep_posttooluse(input_data):
"pushed": len(push_range)})
sys.exit(0)
+ if _GIT_COMMIT_RE.search(command) and not _pushed_beyond_commit_review(
+ repo_root, push_range, bash_output):
+ emit_metrics({"skipped": True, "skip_reason": 47, **_base,
+ "pushed": len(push_range)})
+ sys.exit(0)
+
# A commit review that is still running on these commits records them
# once it has a verdict. Wait for it instead of reviewing the same diff a
# second time; if it ends without one, they are reviewed here.
@@ -3260,17 +3283,16 @@ def main():
#
# Routing therefore MUST check commit FIRST so that compound commit+push
# commands continue to hit commit-review (the pre-existing behaviour) on
- # the commit-matcher invocation. The push-matcher invocation of the SAME
- # compound command is deduped by `_claim_bash_hook_once` below: the second
- # spawn loses the tool_use_id sentinel race and exits early with
- # `bash_hook_dedup`, so commit-review runs exactly once. The alternative —
+ # the commit-matcher invocation. The second spawn of the SAME compound
+ # command loses the tool_use_id sentinel race in `_claim_bash_hook_once`
+ # below, so commit-review runs exactly once. The alternative —
# checking push first — would silently DROP commit-review
# on `git commit && git push`, which is a regression.
#
- # The push-sweep does NOT run on the compound call. That's acceptable: the
- # just-made commit is recorded by commit-review, so the next standalone
- # push sees it as reviewed and the sweep base advances past it. Older
- # unreviewed commits in the range are caught on that next push.
+ # The push-matcher spawn then claims the "push" route and runs the push
+ # sweep, which reviews only when the command pushed a commit that
+ # commit-review will not see: once behind the upstream, no later push
+ # would cover it.
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)):
@@ -3287,7 +3309,13 @@ def main():
# Rides on whichever row this start emits; nothing is skipped.
global _precheck_miss
_precheck_miss = True
- if not _claim_bash_hook_once(input_data):
+ run_commit_review = bool(_GIT_COMMIT_RE.search(cmd))
+ if _claim_bash_hook_once(input_data):
+ pass
+ elif (run_commit_review and _GIT_PUSH_RE.search(cmd)
+ and _claim_bash_hook_once(input_data, "push")):
+ run_commit_review = False
+ else:
# 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.
@@ -3296,9 +3324,9 @@ def main():
dedup = {"pv": _PV, "precheck_miss": 1, **dedup}
_write_hook_output({"metrics": dedup})
sys.exit(0)
- if _GIT_COMMIT_RE.search(cmd):
+ if run_commit_review:
handle_commit_review_posttooluse(input_data)
- elif _GIT_PUSH_RE.search(cmd):
+ else:
handle_push_sweep_posttooluse(input_data)
return
diff --git a/plugins/security-guidance/tests/test_chained_commit_push.py b/plugins/security-guidance/tests/test_chained_commit_push.py
new file mode 100644
index 00000000..8518ed5f
--- /dev/null
+++ b/plugins/security-guidance/tests/test_chained_commit_push.py
@@ -0,0 +1,112 @@
+"""A command that both commits and pushes can send out other commits too.
+
+The commit review sees only the commit the command made, and no later push
+covers what is already behind the upstream, so the second start of the hook
+for such a command runs the push review when something else went out.
+"""
+import os
+import subprocess
+
+import pytest
+
+from conftest import GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook
+
+import security_reminder_hook as hook
+from diffstate import _append_reviewed_shas
+
+CMD = "git add -A && git commit -m new && git push"
+
+
+def _run(repo, *args):
+ r = subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True,
+ env={**os.environ, **GIT_ENV})
+ return r.stdout, r.stderr
+
+
+@pytest.fixture
+def repo(tmp_path):
+ r = make_repo(tmp_path / "repo")
+ subprocess.run(["git", "init", "-q", "--bare", str(tmp_path / "remote.git")], check=True)
+ git(r, "remote", "add", "origin", str(tmp_path / "remote.git"))
+ git(r, "push", "-q", "-u", "origin", "main")
+ return r
+
+
+def _commit_and_push(repo, name="new.py"):
+ (repo / name).write_text("print('new')\n")
+ git(repo, "add", "-A")
+ out, err = _run(repo, "commit", "-m", "new")
+ pout, perr = _run(repo, "push")
+ return out + pout, err + perr
+
+
+def _beyond(repo, output):
+ pushed = git(repo, "rev-list", "@{u}@{1}..HEAD").split()
+ return hook._pushed_beyond_commit_review(str(repo), pushed, output)
+
+
+def _three_starts(repo, env, command, out, err):
+ payload = bash_payload(str(repo), command, stdout=out, stderr=err, tool_use_id="t1")
+ return [metrics_of(run_hook(payload, env)[1]) for _ in range(3)]
+
+
+def test_older_unreviewed_commit_is_beyond_the_commit_review(repo):
+ commit_file(repo, "older.py", "print('older')\n", "older")
+ out, err = _commit_and_push(repo)
+ assert _beyond(repo, out + err)
+
+
+def test_only_the_new_commit_is_covered(repo):
+ out, err = _commit_and_push(repo)
+ assert not _beyond(repo, out + err)
+
+
+def test_older_commit_already_reviewed_is_covered(repo):
+ commit_file(repo, "older.py", "print('older')\n", "older")
+ _append_reviewed_shas(str(repo), [git(repo, "rev-parse", "HEAD").strip()])
+ out, err = _commit_and_push(repo)
+ assert not _beyond(repo, out + err)
+
+
+def test_earlier_commit_of_the_same_command_is_not_covered(repo):
+ (repo / "a.py").write_text("print('a')\n")
+ git(repo, "add", "-A")
+ out1, _ = _run(repo, "commit", "-m", "one")
+ out, err = _commit_and_push(repo)
+ assert _beyond(repo, out1 + out + err)
+
+
+def test_hidden_commit_line_uses_the_reflog(repo):
+ _, err = _commit_and_push(repo)
+ assert not _beyond(repo, err)
+
+
+def test_commit_review_switched_off_covers_nothing(repo, monkeypatch):
+ out, err = _commit_and_push(repo)
+ monkeypatch.setattr(hook, "COMMIT_REVIEW_ENABLED", False)
+ assert _beyond(repo, out + err)
+
+
+def test_second_start_runs_the_push_review_for_older_commits(repo, env):
+ commit_file(repo, "older.py", "print('older')\n", "older")
+ out, err = _commit_and_push(repo)
+ first, second, third = _three_starts(repo, env, CMD, out, err)
+ assert first.get("commit_review") is True
+ assert second.get("push_sweep") is True and second.get("skip_reason") != 47
+ assert third.get("bash_hook_dedup") is True
+
+
+def test_second_start_reviews_nothing_for_the_new_commit_alone(repo, env):
+ out, err = _commit_and_push(repo)
+ first, second, _ = _three_starts(repo, env, CMD, out, err)
+ assert first.get("commit_review") is True
+ assert second.get("skip_reason") == 47
+
+
+def test_plain_commit_second_start_is_deduped(repo, env):
+ (repo / "x.py").write_text("print(1)\n")
+ git(repo, "add", "-A")
+ out, err = _run(repo, "commit", "-m", "x")
+ first, second, _ = _three_starts(repo, env, "git commit -m x", out, err)
+ assert first.get("commit_review") is True
+ assert second.get("bash_hook_dedup") is True
diff --git a/plugins/security-guidance/tests/test_repo_resolution.py b/plugins/security-guidance/tests/test_repo_resolution.py
index bd1840f4..05ac597c 100644
--- a/plugins/security-guidance/tests/test_repo_resolution.py
+++ b/plugins/security-guidance/tests/test_repo_resolution.py
@@ -388,8 +388,11 @@ class TestCommitReview:
p = bash_payload(ws, "git -C sub commit -m change && git -C sub push", out, tool_use_id="toolu_1")
rc1, so1, _ = run_hook(p, hook_env)
rc2, so2, _ = run_hook(p, hook_env)
+ rc3, so3, _ = run_hook(p, hook_env)
assert metrics_of(so1).get("commit_review") is True
- assert metrics_of(so2) == {"bash_hook_dedup": True}
+ # A commit-and-push command gets one more start, for the push review.
+ assert metrics_of(so2).get("push_sweep") is True
+ assert metrics_of(so3) == {"bash_hook_dedup": True}
class TestPushSweep: