summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/diffstate.py
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-27 20:03:52 +0000
committerClaude <noreply@anthropic.com>2026-10-27 20:03:52 +0000
commit3654d346b45836e43e013b849be19233ff0efbc3 (patch)
tree080cdfdff1e1f3df67ca9517251bbe8052890724 /plugins/security-guidance/hooks/diffstate.py
parent45bb3d5c14f7c20c9bdc9a30e798cf0d77467e2e (diff)
parentf8c5e7a1dcb71b10cb74586224b5401f3de5db28 (diff)
Merge remote-tracking branch 'origin/main' into mhegazy/sg-secret-rename-pairingmhegazy/sg-secret-rename-pairing
# Conflicts: # plugins/security-guidance/hooks/diffstate.py
Diffstat (limited to 'plugins/security-guidance/hooks/diffstate.py')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py296
1 files changed, 268 insertions, 28 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index fc42f8c1..5f65ac7f 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -6,17 +6,18 @@ there so callers keep resolving bare names through the hook module's
globals — tests that ``monkeypatch.setattr(hook, "<fn>", …)`` continue
to work without retargeting.
"""
+import hashlib
import os
import subprocess
import sys
import time
-from _base import debug_log, _PV
+from _base import debug_log, portable_output, _PV
from gitutil import (
GIT_CMD,
_git_dir, _git_toplevel, _git_status_porcelain,
_git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index,
- _secret_rename_origins,
+ _secret_rename_origins, index_entry_count,
)
from session_state import with_locked_state
from extensibility import _same_dir
@@ -323,6 +324,8 @@ def get_baseline_file_content(session_id, file_path, cwd):
# from uncommitted work that was already there. Stored with baseline_sha.
# Telemetry only.
last_baseline_fail = 0
+# Entries in the index the last capture copied, None if unknown. Telemetry only.
+last_index_entries = None
def capture_git_baseline(cwd):
@@ -351,8 +354,9 @@ def capture_git_baseline(cwd):
# with `Ávila_report.txt` triggers a quotePath/locale warning) would
# trip the stderr reader thread on Windows cp1252. Decode both streams
# leniently for symmetry with _list_untracked. See #2056.
- global last_baseline_fail
+ global last_baseline_fail, last_index_entries
last_baseline_fail = 0
+ last_index_entries = None
try:
# Check if HEAD exists (i.e., repo has at least one commit)
head_check = subprocess.run(
@@ -370,6 +374,7 @@ def capture_git_baseline(cwd):
# env is None when no usable index copy could be made: fall
# back to HEAD.
if env is not None:
+ last_index_entries = index_entry_count(env["GIT_INDEX_FILE"])
result = subprocess.run(
[*GIT_CMD, "stash", "create"],
cwd=cwd, capture_output=True, timeout=15, env=env
@@ -504,6 +509,164 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0):
pass
+# ─── repeated-diff count ────────────────────────────────────────────────────
+#
+# Count only. A change that comes back under a new commit (undo and re-commit,
+# rebase before the first push) is unknown to the reviewed-shas record and is
+# reviewed again. These helpers say how often that happens, by remembering a
+# hash of each reviewed hunk next to the reviewed-shas file. Nothing here
+# decides whether a review runs, and nothing here waits on another process
+# for more than a moment.
+
+_SEEN_DIFFS_BASENAME = "sg-reviewed-diffs"
+_SEEN_DIFFS_TTL_S = 7 * 24 * 3600
+# Past this size the record is cut back to its newest half.
+_SEEN_DIFFS_TRIM_BYTES = 1024 * 1024
+_SEEN_DIFFS_MAX_KEYS = 500
+_SEEN_DIFFS_LOCK_TRIES = 10
+
+# `diff_seen` values, weakest first. A review reports the weakest of its
+# hunks: 3 means every hunk already had a finished review in this clone.
+DIFF_SEEN_ERROR = -1 # the record could not be read or written
+DIFF_SEEN_NO = 0 # some hunk was never reviewed
+DIFF_SEEN_UNFINISHED = 1 # a review of it started and has no verdict (yet)
+DIFF_SEEN_OTHER_TREE = 2 # finished, on different repo contents
+DIFF_SEEN_SAME_TREE = 3 # finished, on the same tree
+
+
+def _hunk_keys(diff_files):
+ """One hash per hunk: the path plus the hunk's lines, context included.
+
+ The `@@` line is left out, so a hunk keeps its key when a rebase only
+ moves it; the same edit next to different code gets a different key.
+ """
+ keys = {}
+ for path, content in diff_files:
+ hunks, cur = [], []
+ for ln in content.split("\n"):
+ if ln.startswith("@@"):
+ hunks.append(cur)
+ cur = []
+ else:
+ cur.append(ln)
+ hunks.append(cur)
+ for body in hunks:
+ # A file's last hunk ends with the diff's trailing blank line.
+ while body and not body[-1]:
+ body.pop()
+ if not body:
+ continue
+ h = hashlib.sha256(path.encode("utf-8", "replace"))
+ h.update(b"\0")
+ h.update("\n".join(body).encode("utf-8", "replace"))
+ keys[h.hexdigest()[:16]] = None
+ keys = list(keys)
+ if len(keys) > _SEEN_DIFFS_MAX_KEYS:
+ # Keep the record small: the hunks past the cap share one key, so
+ # they only match the same set of hunks again.
+ rest = hashlib.sha256(" ".join(keys[_SEEN_DIFFS_MAX_KEYS - 1:]).encode("ascii"))
+ keys = keys[:_SEEN_DIFFS_MAX_KEYS - 1] + [rest.hexdigest()[:16]]
+ return keys
+
+
+def _seen_lock(fd):
+ """True: locked. False: another process kept it. None: no flock here."""
+ for _ in range(_SEEN_DIFFS_LOCK_TRIES):
+ try:
+ if _flock_nb(fd, exclusive=True):
+ return True
+ except (ImportError, OSError):
+ return None
+ time.sleep(0.05)
+ return False
+
+
+def _append_diff_row(f, locked, token, done):
+ """Append one record for the review to `f`, the record opened "a+b"."""
+ _, keys, tree = token
+ row = f"{int(time.time())}\t{tree}\t{int(done)}\t{' '.join(keys)}\n".encode("ascii")
+ size = f.seek(0, os.SEEK_END)
+ if size:
+ f.seek(size - 1)
+ if f.read(1) != b"\n":
+ row = b"\n" + row # a torn last record must not swallow this one
+ # Cutting the record back rewrites it: not while another process holds
+ # the lock. Without flock at all, bounded beats exact.
+ if locked is not False and size + len(row) > _SEEN_DIFFS_TRIM_BYTES:
+ f.seek(0)
+ keep, room = [], _SEEN_DIFFS_TRIM_BYTES // 2
+ for ln in reversed(f.read().splitlines(keepends=True)):
+ room -= len(ln)
+ if room < 0:
+ break
+ keep.append(ln)
+ f.seek(0)
+ f.truncate()
+ row = b"".join(reversed(keep)) + row
+ f.write(row)
+ f.flush()
+
+
+def _diff_review_started(repo_root, diff_files, tip="HEAD"):
+ """Note that a review of `diff_files`, a diff ending at `tip`, is starting.
+
+ Returns (token, metrics). `metrics` is {"diff_seen": <DIFF_SEEN_* code>}:
+ whether this clone already reviewed every hunk of this diff. `token` goes
+ to `_diff_review_done` once the review has a verdict. Never raises.
+ """
+ if portable_output() or not diff_files:
+ # No metrics leave the hook in portable mode, so nothing to count.
+ return None, {}
+ try:
+ gd = _git_dir(repo_root)
+ keys = _hunk_keys(diff_files)
+ if not gd or not keys:
+ raise ValueError("no git dir" if not gd else "no hunks")
+ token = (os.path.join(gd, _SEEN_DIFFS_BASENAME), keys,
+ "".join(_full_shas(repo_root, [tip + "^{tree}"])[:1]))
+ tree = token[2]
+ now = time.time()
+ best = dict.fromkeys(keys, DIFF_SEEN_NO)
+ # Read and note under one lock, so two reviews of one diff that start
+ # together cannot both miss each other.
+ with open(token[0], "a+b") as f:
+ locked = _seen_lock(f.fileno())
+ if locked is False:
+ raise OSError("record is locked")
+ f.seek(0)
+ for ln in f.read().decode("ascii", "replace").splitlines():
+ row = ln.split("\t")
+ if len(row) != 4 or not row[0].isdigit() or len(row[0]) > 12:
+ continue
+ if now - int(row[0]) > _SEEN_DIFFS_TTL_S:
+ continue
+ if row[2] != "1":
+ seen = DIFF_SEEN_UNFINISHED
+ elif tree and row[1] == tree:
+ seen = DIFF_SEEN_SAME_TREE
+ else:
+ seen = DIFF_SEEN_OTHER_TREE
+ for k in row[3].split(" "):
+ if best.get(k, seen) < seen:
+ best[k] = seen
+ _append_diff_row(f, locked, token, done=False)
+ return token, {"diff_seen": min(best.values())}
+ except Exception as e:
+ debug_log(f"Repeated-diff count: not counted ({type(e).__name__}: {e})")
+ return None, {"diff_seen": DIFF_SEEN_ERROR}
+
+
+def _diff_review_done(token):
+ """Note that the review `token` came from got a verdict. Never raises."""
+ if not token:
+ return
+ try:
+ with open(token[0], "a+b") as f:
+ _append_diff_row(f, _seen_lock(f.fileno()), token, done=True)
+ except Exception as e:
+ debug_log(f"Repeated-diff count: verdict not noted ({type(e).__name__}: {e})")
+
+
# ─── in-flight review markers ───────────────────────────────────────────────
#
# A commit or push review records its shas only once it has a verdict, which
@@ -512,14 +675,19 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0):
# through a second full review. So a review first takes an exclusive flock on
# `sg-inflight-<sha>`, next to the reviewed-shas file, and holds it until its
# process ends; other reviews leave a locked commit to it. The kernel drops
-# the lock however the holder dies, so a killed review blocks nobody. Without
-# flock (native Windows Python, some network filesystems) there are no
+# the lock however the holder dies, so a killed review blocks nobody. Native
+# Windows Python has no flock; there the same lock is taken with LockFileEx.
+# Where files cannot be locked (some network filesystems) there are no
# markers and nothing changes.
_INFLIGHT_PREFIX = "sg-inflight-"
# A marker file nobody holds (a killed review's) is removed once this old.
_INFLIGHT_GC_AGE_S = 3600
_inflight_held = {}
+# Windows refuses to delete a file that is open, so a marker is closed first
+# there. Elsewhere it is deleted while still locked, so nobody can lock a
+# file that is about to go.
+_UNLINK_BEFORE_CLOSE = os.name != "nt"
def _full_shas(repo_root, shas):
@@ -538,11 +706,60 @@ def _full_shas(repo_root, shas):
return out
+_win_lock_file_ex = None
+
+
+def _win_lock_nb(fd, exclusive):
+ """`_flock_nb` for native Windows Python, with LockFileEx.
+
+ Shared and exclusive as with flock, never waits, and Windows drops the
+ lock when the handle is closed or the holder's process ends. Windows
+ locks stop other processes reading the locked bytes, so the byte locked
+ is one far past the end of the (empty) marker: copying a repository while
+ a review runs still reads the marker.
+ """
+ global _win_lock_file_ex
+ import errno
+ try:
+ import ctypes
+ import msvcrt
+ if _win_lock_file_ex is None:
+ from ctypes import wintypes
+
+ class _Overlapped(ctypes.Structure):
+ _fields_ = [("Internal", ctypes.c_void_p), ("InternalHigh", ctypes.c_void_p),
+ ("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD),
+ ("hEvent", wintypes.HANDLE)]
+
+ fn = ctypes.WinDLL("kernel32", use_last_error=True).LockFileEx
+ fn.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD,
+ wintypes.DWORD, ctypes.POINTER(_Overlapped)]
+ fn.restype = wintypes.BOOL
+ _win_lock_file_ex = (fn, _Overlapped)
+ except (ImportError, AttributeError, OSError) as e:
+ raise OSError(errno.ENOLCK, f"no file locking in this Python ({e})")
+ fn, _Overlapped = _win_lock_file_ex
+ fail_immediately, exclusive_lock = 0x1, 0x2
+ where = _Overlapped(Offset=0, OffsetHigh=0x7FFFFFFF)
+ if fn(msvcrt.get_osfhandle(fd), fail_immediately | (exclusive_lock if exclusive else 0),
+ 0, 1, 0, ctypes.byref(where)):
+ return True
+ err = ctypes.get_last_error()
+ if err == 33: # ERROR_LOCK_VIOLATION: another handle holds it
+ return False
+ raise OSError(errno.ENOLCK, f"LockFileEx failed (WinError {err})")
+
+
def _flock_nb(fd, exclusive):
"""True when the lock was taken, False when another process holds it.
Raises OSError when the file cannot be locked at all."""
import errno
- import fcntl
+ if os.name == "nt":
+ return _win_lock_nb(fd, exclusive)
+ try:
+ import fcntl
+ except ImportError as e:
+ raise OSError(errno.ENOLCK, f"no file locking in this Python ({e})")
try:
fcntl.flock(fd, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB)
return True
@@ -552,16 +769,36 @@ def _flock_nb(fd, exclusive):
raise
-def _release_inflight():
- for p, fd in list(_inflight_held.items()):
+def _again_if_refused(op, *args):
+ """`op(*args)`, tried a few times where another process having the file
+ open for a moment refuses it (Windows). Raises the last OSError."""
+ import time as _time
+ tries = 1 if _UNLINK_BEFORE_CLOSE else 3
+ for attempt in range(tries):
try:
- os.unlink(p)
- except OSError:
- pass
+ return op(*args)
+ except PermissionError:
+ if attempt == tries - 1:
+ raise
+ _time.sleep(0.01)
+
+
+def _drop_marker(p, fd, unlink=True):
+ """Close a marker this process has open and, with `unlink`, delete it, in
+ the order this platform needs. Never raises. A delete that stays refused
+ leaves an unlocked file, which is swept once old."""
+ steps = [(_again_if_refused, os.unlink, p)] if unlink else []
+ steps.insert(len(steps) if _UNLINK_BEFORE_CLOSE else 0, (os.close, fd))
+ for step, *args in steps:
try:
- os.close(fd)
+ step(*args)
except OSError:
pass
+
+
+def _release_inflight():
+ for p, fd in list(_inflight_held.items()):
+ _drop_marker(p, fd)
_inflight_held.clear()
@@ -580,11 +817,10 @@ def _sweep_inflight(gd):
except OSError:
continue
try:
- if _flock_nb(fd, exclusive=True):
- os.unlink(p)
+ unheld = _flock_nb(fd, exclusive=True)
except OSError:
- pass
- os.close(fd)
+ unheld = False
+ _drop_marker(p, fd, unlink=unheld)
def _mark_inflight(repo_root, shas):
@@ -592,7 +828,6 @@ def _mark_inflight(repo_root, shas):
run, until the process ends. Best-effort; never raises. A commit another
live review holds stays with that review."""
try:
- import fcntl # noqa: F401
gd = _git_dir(repo_root)
if not gd:
return
@@ -601,17 +836,26 @@ def _mark_inflight(repo_root, shas):
p = os.path.join(gd, _INFLIGHT_PREFIX + sha)
if not _is_full_sha(sha) or p in _inflight_held:
continue
- fd = os.open(p, os.O_RDWR | os.O_CREAT, 0o600)
try:
- # The inode check: a holder unlinks its marker when it ends,
- # and a lock on that unlinked file would claim nothing.
- held = (_flock_nb(fd, exclusive=True)
- and os.fstat(fd).st_ino == os.stat(p).st_ino)
+ fd = _again_if_refused(os.open, p, os.O_RDWR | os.O_CREAT, 0o600)
+ except OSError:
+ # One marker that cannot be opened does not cost the others
+ # their claim.
+ continue
+ try:
+ held = _flock_nb(fd, exclusive=True)
except OSError:
# Cannot lock here at all: leave no file that reads as held.
- os.close(fd)
- os.unlink(p)
+ _drop_marker(p, fd)
return
+ if held and _UNLINK_BEFORE_CLOSE:
+ # The inode check: a holder unlinks its marker when it ends,
+ # and a lock on that unlinked file would claim nothing. Not
+ # where an open file cannot be unlinked in the first place.
+ try:
+ held = os.fstat(fd).st_ino == os.stat(p).st_ino
+ except OSError:
+ held = False
if not held:
os.close(fd)
continue
@@ -627,10 +871,6 @@ def _mark_inflight(repo_root, shas):
def _load_inflight_shas(repo_root, shas, _gd=None):
"""Which of `shas` another live review in this clone holds right now."""
out = set()
- try:
- import fcntl # noqa: F401
- except ImportError:
- return out
gd = _gd or _git_dir(repo_root)
if not gd:
return out