summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-18 00:11:54 +0000
committerClaude <noreply@anthropic.com>2026-11-18 00:11:54 +0000
commitbdbd27da1d3b535eabfdf7dc5bf2e308858d7d3a (patch)
treeda496d193340865569478b7d1ed9d3d10ce081d7 /plugins
parenta5576bbfa2a13729122803fc8e3adf370f99d37a (diff)
parent1331242ea877583fc40794a535514bd9591cf20c (diff)
Merge remote-tracking branch 'origin/main' into mhegazy/sg-commit-diff-memory
Co-authored-by: mhegazy <mhegazy@anthropic.com> # Conflicts: # plugins/security-guidance/hooks/security_reminder_hook.py
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md1
-rw-r--r--plugins/security-guidance/hooks/diffstate.py91
-rw-r--r--plugins/security-guidance/hooks/extensibility.py123
-rw-r--r--plugins/security-guidance/hooks/gitutil.py203
-rw-r--r--plugins/security-guidance/hooks/hooks.json3
-rw-r--r--plugins/security-guidance/hooks/llm.py131
-rw-r--r--plugins/security-guidance/hooks/patterns.py30
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py407
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh57
-rw-r--r--plugins/security-guidance/tests/conftest.py9
-rw-r--r--plugins/security-guidance/tests/test_chained_commit_push.py405
-rw-r--r--plugins/security-guidance/tests/test_custom_rule_brace_globs.py187
-rw-r--r--plugins/security-guidance/tests/test_custom_rule_stats.py3
-rw-r--r--plugins/security-guidance/tests/test_launcher_redirector.py215
-rw-r--r--plugins/security-guidance/tests/test_line_continuation.py81
-rw-r--r--plugins/security-guidance/tests/test_pattern_false_positives.py96
-rw-r--r--plugins/security-guidance/tests/test_renamed_into_review.py466
-rw-r--r--plugins/security-guidance/tests/test_review_result_keys.py132
-rw-r--r--plugins/security-guidance/tests/test_reviewer_tools.py32
-rw-r--r--plugins/security-guidance/tests/test_tls_macos_ca_file.py193
-rw-r--r--plugins/security-guidance/tests/test_tls_store_unreadable_cert.py2
-rw-r--r--plugins/security-guidance/tests/test_unmatched_bash_metric.py6
22 files changed, 2705 insertions, 168 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index 46049569..8f7a1be6 100644
--- a/plugins/security-guidance/README.md
+++ b/plugins/security-guidance/README.md
@@ -72,6 +72,7 @@ On the default API host, a claude.ai token (`sk-ant-oat`) that arrives as `ANTHR
| `ENABLE_CODE_SECURITY_REVIEW=0` | on | Disable all LLM reviews (Stop hook + commit/push) |
| `ENABLE_STOP_REVIEW=0` | on | Disable only the Stop-hook diff review, keeping commit/push reviews. Useful for multi-agent / shared-worktree setups where another agent can move HEAD between a worker's turns |
| `ENABLE_COMMIT_REVIEW=0` | on | Disable layer 3 (agentic commit review) |
+| `MAX_COMMIT_REVIEWS_PER_HOUR=<n>` | `20` | The most commit reviews, and separately the most push reviews, that one session runs in a rolling hour. A commit or push past the limit still goes through, without a review and without a message; a later push can still review the commit. Must be a whole number; `0` runs none. It counts reviews, not tokens or cost, and does not limit the Stop-hook diff review |
| `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` | unset | Keep the reviewer's own Claude Code runs as session transcripts (see [Privacy and data handling](#privacy-and-data-handling)) |
### Hook output for other hosts
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index cd3205e6..a94363f4 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -1228,6 +1228,83 @@ def _mark_inflight(repo_root, shas):
pass
+_holds = {}
+
+
+def hold_until_exit(path):
+ """Lock the file at `path` until this process ends or calls
+ `release_hold`, so that others can see it `is_held`. Best-effort; never
+ raises."""
+ import time as _time
+ try:
+ fd = _open_own_file(path, os.O_RDWR)
+ except (OSError, TypeError):
+ return
+ try:
+ for _ in range(10): # another process may be looking at this moment
+ if _flock_nb(fd, exclusive=True):
+ _holds[path] = fd # left open: the lock goes when the process does
+ return
+ _time.sleep(0.01)
+ except OSError:
+ pass
+ os.close(fd)
+
+
+def release_hold(path):
+ """Give up the lock `hold_until_exit` took. Never raises."""
+ fd = _holds.pop(path, None)
+ if fd is not None:
+ _drop_marker(path, fd, unlink=False)
+
+
+def is_held(path):
+ """Whether a live process holds the file at `path`; None when that cannot
+ be told (no such file, or no locks here)."""
+ try:
+ fd = _open_own_file(path, os.O_RDONLY)
+ except (OSError, TypeError):
+ return None
+ try:
+ # Shared, so two processes looking at once do not look like a holder
+ # to each other.
+ return not _flock_nb(fd, exclusive=False)
+ except OSError:
+ return None
+ finally:
+ os.close(fd)
+
+
+def becomes_held(path, max_wait_s, poll_s=0.1):
+ """Whether a live process holds the file at `path` or does so soon."""
+ import time as _time
+ end = _time.monotonic() + max_wait_s
+ while not is_held(path):
+ if _time.monotonic() >= end:
+ return False
+ _time.sleep(poll_s)
+ return True
+
+
+def wait_for_holder(path, max_wait_s, poll_s=0.5):
+ """Wait for the process holding the file at `path` to end. Returns
+ (ended, waited_s); `ended` is False when it still runs after `max_wait_s`,
+ or when that cannot be told."""
+ import time as _time
+ start = _time.monotonic()
+ waited, looks_free = False, 0
+ while True:
+ held = is_held(path)
+ # Free twice in a row: a holder creates the file a moment before it
+ # locks it.
+ looks_free = 0 if held else looks_free + 1
+ spent = _time.monotonic() - start
+ if held is None or looks_free == 2 or (held and spent >= max_wait_s):
+ return looks_free == 2 and held is False, spent if waited else 0.0
+ waited = waited or held
+ _time.sleep(poll_s)
+
+
def _load_inflight_shas(repo_root, shas, _gd=None):
"""Which of `shas` another live review in this clone holds right now."""
out = set()
@@ -1238,18 +1315,8 @@ def _load_inflight_shas(repo_root, shas, _gd=None):
p = os.path.join(gd, _INFLIGHT_PREFIX + sha)
if not _is_full_sha(sha) or p in _inflight_held:
continue
- try:
- fd = _open_own_file(p, os.O_RDONLY)
- except OSError:
- continue
- try:
- # Shared, so two reviews asking at once do not look like a
- # holder to each other.
- if not _flock_nb(fd, exclusive=False):
- out.add(sha)
- except OSError:
- pass
- os.close(fd)
+ if is_held(p):
+ out.add(sha)
return out
diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py
index 7f434371..6dd8d470 100644
--- a/plugins/security-guidance/hooks/extensibility.py
+++ b/plugins/security-guidance/hooks/extensibility.py
@@ -83,10 +83,13 @@ def load_for_session(cwd: Optional[str]) -> None:
a malformed config file produces a debug_log entry, never a crash.
"""
global _guidance_block, _user_patterns, _refused_regexes, _match_roots
+ global _brace_forms_left
_refused_regexes = 0
env_project = os.environ.get("CLAUDE_PROJECT_DIR") or None
_match_roots = tuple(_project_dirs(cwd)[:1]) or ((env_project,) if env_project else ())
_rels_cache.clear()
+ _forms_cache.clear()
+ _brace_forms_left = _BRACE_BUDGET
try:
_guidance_block = _wrap_guidance(_load_guidance(cwd))
except Exception as e:
@@ -420,6 +423,9 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]:
if not isinstance(paths, list) or not isinstance(exclude, list):
debug_log(f"extensibility: skipping {name}: paths/exclude_paths must be lists")
return None
+ for glob in (*paths, *exclude):
+ if isinstance(glob, str):
+ _glob_forms(glob, name) # now, so the log can name the rule
rule["_globs"] = (tuple(paths), tuple(exclude)) # read by edit_stats
# Capture as defaults so the lambda doesn't share state across rules.
rule["path_filter"] = (
@@ -431,7 +437,8 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]:
def _rule_covers(path: str, include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool:
"""Whether a rule's globs let it apply to `path`, as check_patterns hands it
over (POSIX absolute paths without their leading `/`). Globs are read against
- the full path and the path inside the project, and `**/` can match no folder."""
+ the full path and the path inside the project, `**/` can match no folder, and
+ `{a,b}` is either."""
full = path if os.path.isabs(path) else "/" + path
rels = _rels_cache.get(full)
if rels is None:
@@ -444,7 +451,7 @@ def _rule_covers(path: str, include: Tuple[str, ...], exclude: Tuple[str, ...])
def _glob_match(path: str, include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool:
"""The reading of globs before _rule_covers, kept for edit_stats: full path
- or file name only, and `**/` needs a folder."""
+ or file name only, `**/` needs a folder, and braces are literal."""
norm = path.replace(os.sep, "/")
base = os.path.basename(norm)
def _hit(globs: Tuple[str, ...]) -> bool:
@@ -496,7 +503,7 @@ def _has_redos_structure(regex: str) -> bool:
_SHAPE_PLAIN_PATHS = 1 # a `paths` glob with a folder and no leading `*`
_SHAPE_PLAIN_EXCLUDE = 2 # the same in `exclude_paths`
_SHAPE_MID_STARS = 4 # `/**/` inside a glob
-_SHAPE_BRACES = 8 # `{a,b}`, which fnmatch takes literally
+_SHAPE_BRACES = 8 # `{`, as in `{a,b}`
_SHAPE_LEADING = 16 # starts with `/` or `./`
_SHAPE_REGEX_REFUSED = 32 # a rule dropped by the slow-regex check
_SHAPE_REGEX_COUNTED = 64 # a loaded regex repeats a repeated group by count
@@ -533,20 +540,112 @@ def _zero_depth_forms(glob: str) -> Tuple[str, ...]:
return tuple(forms)
+# Globs that braces may stand for: in one glob, and in all the rules loaded,
+# counted with their `**/` forms. Real rules list a few file types and folders;
+# this bounds what a project's file can cost. A glob beyond either is read as it
+# is written. User files load first, so a project's cannot use up their share.
+_MAX_BRACE_FORMS = 256
+_MAX_BRACE_GLOB_LEN = 1000
+_BRACE_BUDGET = 4096
+_brace_forms_left = _BRACE_BUDGET
+# glob -> its _glob_forms.
+_forms_cache: Dict[str, Tuple[Tuple[str, str, bool], ...]] = {}
+
+
+def _brace_group(glob: str) -> Optional[Tuple[int, Tuple[int, ...], int]]:
+ """The first `{...}` with a comma of its own: where it opens, its commas,
+ where it closes. Braces inside `[...]` are members of that set."""
+ stack: List[Tuple[int, List[int]]] = []
+ found = None
+ i, last_set_end = 0, glob.rfind("]")
+ while i < len(glob):
+ c = glob[i]
+ if c == "[" and i < last_set_end:
+ # As fnmatch reads a set: `]` right after `[` or `[!` is a member.
+ start = i + 2 if glob.startswith("!", i + 1) else i + 1
+ end = glob.find("]", start + 1)
+ if end > 0:
+ i = end
+ elif c == "{":
+ stack.append((i, []))
+ elif c == "," and stack:
+ stack[-1][1].append(i)
+ elif c == "}" and stack:
+ opened, commas = stack.pop()
+ if commas and (found is None or opened < found[0]):
+ found = (opened, tuple(commas), i)
+ i += 1
+ return found
+
+
+def _brace_forms(glob: str) -> Optional[Tuple[str, ...]]:
+ """`glob`, and the globs its braces stand for: `*.{ts,tsx}` is also `*.ts`
+ and `*.tsx`. None when there are too many. Braces with no comma are literal."""
+ todo, done = [glob], []
+ while todo:
+ form = todo.pop()
+ group = _brace_group(form)
+ if group is None:
+ done.append(form)
+ continue
+ opened, commas, closed = group
+ if len(todo) + len(done) + len(commas) + 1 > _MAX_BRACE_FORMS:
+ return None
+ edges = (opened,) + commas + (closed,)
+ rest = form[closed + 1:]
+ for a, b in zip(edges, edges[1:]):
+ option = form[a + 1:b].strip()
+ # `{src,}/**` would leave `/**`, which takes in every file.
+ if option or opened or not rest.startswith("/"):
+ todo.append(form[:opened] + option + rest)
+ # The glob as written stays, for a name that has braces in it.
+ return tuple(dict.fromkeys([glob] + [f for f in done if f]))
+
+
+def _glob_forms(glob: str, rule_name: str = "") -> Tuple[Tuple[str, str, bool], ...]:
+ """The globs `glob` stands for, each as (glob, its literal end, whether it
+ has a folder in it), in the filesystem's case."""
+ global _brace_forms_left
+ if glob in _forms_cache:
+ return _forms_cache[glob]
+ braces = (glob,)
+ if "{" in glob and "," in glob:
+ fits = _brace_forms_left > 0 and len(glob) <= _MAX_BRACE_GLOB_LEN
+ braces = (_brace_forms(glob) if fits else None) or ()
+ forms = tuple((b, f) for b in braces for f in _zero_depth_forms(b))
+ if not braces or (len(braces) > 1 and len(forms) > _brace_forms_left):
+ debug_log(f"extensibility: {rule_name}: too many combinations in braces, "
+ f"read as written: {glob!r:.80}")
+ # Finding out that it does not fit has a cost too.
+ _brace_forms_left -= _MAX_BRACE_FORMS
+ forms = tuple((glob, f) for f in _zero_depth_forms(glob))
+ elif len(braces) > 1:
+ _brace_forms_left -= len(forms)
+ out = []
+ for b, f in forms:
+ # A glob with no folder in it is about the file name: `*` crosses `/`,
+ # so against the path inside the project `test*` would take in a tree.
+ folder = "/" in b.replace("\\", "/")
+ f = os.path.normcase(f)
+ out.append((f, f[max(f.rfind(c) for c in "*?[]") + 1:], folder))
+ _forms_cache[glob] = tuple(out)
+ return _forms_cache[glob]
+
+
def _wider_glob_match(path: str, rels: Tuple[str, ...],
include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool:
"""_glob_match, with globs also read against the path inside the project
- (`rels`), and `**/` able to match no folder."""
- norm = path.replace(os.sep, "/")
- names = [norm, norm.lstrip("/"), os.path.basename(norm)]
- inside = [n for rel in rels for n in (rel, "/" + rel, "./" + rel)]
+ (`rels`), `**/` able to match no folder, and braces as alternatives."""
+ full = path.replace(os.sep, "/")
+ names = [os.path.normcase(n) for n in (full, full.lstrip("/"), os.path.basename(full))]
+ inside = names + [os.path.normcase(n) for rel in rels for n in (rel, "/" + rel, "./" + rel)]
def _hit(globs: Tuple[str, ...]) -> bool:
- # A glob with no folder in it is about the file name: `*` crosses `/`,
- # so against the path inside the project `test*` would take in a tree.
- return any(fnmatch.fnmatch(n, f) for g in globs
- for f in _zero_depth_forms(g)
- for n in (names + inside if "/" in g.replace("\\", "/") else names))
+ # The literal end first: compiling a glob is the slow part, and most of
+ # the options in braces end differently.
+ return any(n.endswith(tail) and fnmatch.fnmatchcase(n, form) for g in globs
+ for form, tail, folder in _glob_forms(g)
+ for n in (inside if folder else names))
if include and not _hit(include):
return False
if exclude and _hit(exclude):
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index fa658b02..9f519dc3 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -685,6 +685,16 @@ def _env_with_private_objects(env, cwd, objects_dir):
return out
+def _literal_paths_env(env):
+ """`env` with every path a git command is given taken as a file name, not
+ a pattern: a file named `:(glob)**` stands only for itself. git refuses
+ that together with a glob or icase setting from the user's environment."""
+ env = {k: v for k, v in env.items()
+ if k not in ("GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS")}
+ env["GIT_LITERAL_PATHSPECS"] = "1"
+ return env
+
+
def _add_new_files(cwd, paths, env, tmp_index):
"""`git add --intent-to-add` the untracked `paths` to the index copy `env`
names, so the diff shows them. The add has to store the empty blob, so a
@@ -697,12 +707,8 @@ def _add_new_files(cwd, paths, env, tmp_index):
reader threads that decode stderr — git error messages can reference
non-ASCII filenames and crash on cp1252. See #2099. Drop text=True so bytes
stay raw."""
- # The paths are file names, not patterns, for this git add only: an
- # untracked file named `:(glob)**` must add only itself. git refuses that
- # together with a glob or icase setting from the user's environment.
- env = {k: v for k, v in env.items()
- if k not in ("GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS")}
- env["GIT_LITERAL_PATHSPECS"] = "1"
+ # For this git add only.
+ env = _literal_paths_env(env)
def add(add_env):
results = _run_git_on_review_paths(
@@ -1345,6 +1351,25 @@ def _note_rename(old_path, new_path):
_secret_rename_origins[new_path] = old_path
+def _name_status_pairs(stdout):
+ """(old path or None, path) for each entry of `git diff --name-status -z`
+ output. Fields are `status\\0path\\0`, or `R<score>\\0old\\0new\\0` for a
+ rename or copy, which is listed by its new name."""
+ fields = (stdout or b"").decode("utf-8", errors="replace").split("\0")
+ i = 0
+ while i + 1 < len(fields):
+ if not fields[i]:
+ # `git log` can put an empty field between two commits.
+ i += 1
+ continue
+ old = None
+ if fields[i][:1] in ("R", "C") and i + 2 < len(fields):
+ old = fields[i + 1]
+ i += 1
+ yield old, fields[i + 1]
+ i += 2
+
+
def _git_name_only(cwd, base, include_untracked=False):
"""Return the set of repo-root-relative paths that differ from `base`,
or None if git failed (unresolvable ref, not a repo, timeout). Callers
@@ -1372,18 +1397,11 @@ def _git_name_only(cwd, base, include_untracked=False):
stderr_str = (result.stderr or b"").decode("utf-8", errors="replace")
debug_log(f"_git_name_only({base!r}) rc={result.returncode}: {stderr_str[:200]}")
return None
- stdout = (result.stdout or b"").decode("utf-8", errors="replace")
- # Fields are `status\0path\0`, or `R<score>\0old\0new\0` for a rename
- # or copy, which is listed by its new name only.
- fields = stdout.split("\0")
names = set()
- i = 0
- while i + 1 < len(fields):
- if fields[i][:1] in ("R", "C") and i + 2 < len(fields):
- _note_rename(fields[i + 1], fields[i + 2])
- i += 1
- names.add(fields[i + 1])
- i += 2
+ for old, new in _name_status_pairs(result.stdout):
+ if old:
+ _note_rename(old, new)
+ names.add(new)
return names
try:
@@ -2209,6 +2227,11 @@ def _parse_diff_header(header):
`"a/we\\"ird.py" "b/we\\"ird.py"`. Either side can be quoted on its own.
"""
old = new = None
+ # The same name on both sides, as in every section but a rename or a copy.
+ # A name that contains ` b/` can only be told apart this way.
+ same = header[2:(len(header) - 1) // 2]
+ if same and header == f"a/{same} b/{same}":
+ return same, same
if header.startswith('"'):
first = _read_quoted_path(header, 0)
if not first:
@@ -2246,11 +2269,32 @@ def _section_is_reviewable(file_path, old_path):
return _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path)
+def _rename_of(lines):
+ """(old path, new path) of a section git shows as a rename or a copy, or
+ None. Read from its `rename from` / `rename to` lines, where each path
+ stands alone; the header line is ambiguous when a name contains ` b/`."""
+ old = None
+ for line in lines:
+ if line.startswith('@@'):
+ break
+ m = re.match(r'(?:rename|copy) (from|to) (.+)', line)
+ if not m:
+ continue
+ path = m.group(2)
+ if path.startswith('"'):
+ quoted = _read_quoted_path(path, 0)
+ path = quoted[0] if quoted else path
+ if m.group(1) == 'to':
+ return (old, path) if old else None
+ old = path
+ return None
+
+
def _iter_diff_sections(diff_output):
"""Yield (new_path, old_path, lines after the header line) per file section."""
for section in _DIFF_SECTION_RE.split(diff_output)[1:]:
lines = section.split('\n')
- paths = _parse_diff_header(lines[0])
+ paths = _rename_of(lines[1:]) or _parse_diff_header(lines[0])
if paths:
yield paths[1] or paths[0], paths[0], lines[1:]
else:
@@ -2301,6 +2345,129 @@ def parse_diff_into_files(diff_output):
return files
+# Names whose content the commit and push reviews never read although it can
+# be code: text and documents. Not every name they leave out: a key, an
+# archive or a vendored file under a new name is still what it was.
+_TEXT_EXTENSIONS = frozenset(('.txt', '.text', '.md', '.markdown', '.rst'))
+_DATA_EXTENSIONS = frozenset((
+ '.json', '.yaml', '.yml', '.toml', '.properties', '.tfvars', '.ipynb',
+))
+_CODE_EXTENSIONS = SOURCE_CODE_EXTENSIONS - _DATA_EXTENSIONS
+
+
+# Text that holds secrets by its name or its folder's (`api_keys.txt`,
+# `keys/prod.md`, `.ssh/notes.txt`). It stays unread when it becomes code; so
+# does a document that only has such a word in its name (`hotkeys.md`).
+_SECRET_TEXT_RE = re.compile(
+ r"(?:secrets?|credentials?|creds?|passwords?|passwd|keys?|tokens?|vault"
+ r"|/\.(?:ssh|aws|gnupg|kube))/"
+ r"|(?:secret|credential|passw|passphrase|api.?key|recovery.?code|service.?account)[^/]*$"
+ r"|(?:keys?|tokens?|creds?|pass|pwd|env|logins|pem|ed25519|netrc|npmrc)"
+ r"(?![a-z])[^/]*$")
+
+
+def _is_secret_stem(file_path):
+ """`credentials.txt`, `id_rsa.md`: a secret's name with an extension."""
+ stem = os.path.splitext(os.path.basename(file_path))[0].lower()
+ return (_is_secret_shaped(stem) or stem in _SECRET_NAMED_STEMS
+ or stem.startswith('password'))
+
+
+def _is_secret_text(file_path):
+ """Whether a name says the file holds secrets, if it is not a code name."""
+ path = "/" + file_path.replace("\\", "/").lower()
+ return (_is_secret_shaped(file_path)
+ or os.path.splitext(path)[1] not in _CODE_EXTENSIONS
+ and os.path.basename(path) not in SOURCE_CODE_BASENAMES
+ and (_is_secret_stem(path) or bool(_SECRET_TEXT_RE.search(path))))
+
+
+def _is_text_turned_code(old_path, new_path):
+ ext = os.path.splitext(new_path)[1].lower()
+ return (os.path.splitext(old_path)[1].lower() in _TEXT_EXTENSIONS
+ and not _is_secret_text(old_path) and not _is_secret_stem(new_path)
+ and (ext in _CODE_EXTENSIONS
+ or os.path.basename(new_path).lower() in SOURCE_CODE_BASENAMES)
+ and _section_is_reviewable(new_path, old_path)
+ and not _is_reviewable_source(old_path))
+
+
+def renamed_into_review(diff_output):
+ """The new names of the files a diff renames or copies from a text name
+ the review leaves out (`notes.txt`) to a code name it reviews. git shows
+ only what changed across a rename, and nothing at all when the content did
+ not, so what nobody reviewed as text would never be read as code.
+
+ Empty when the diff also removes or renames a secret-shaped file: git
+ picks which old name a new file came from, and between two alike it can be
+ the other one.
+ """
+ if "\nrename to " not in diff_output and "\ncopy to " not in diff_output:
+ return []
+ names = []
+ for file_path, old_path, lines in _iter_diff_sections(diff_output):
+ renamed = _rename_of(lines)
+ if (renamed or lines[:1] and lines[0].startswith("deleted file mode")) \
+ and _is_secret_shaped(old_path):
+ return []
+ if renamed and _is_text_turned_code(old_path, file_path):
+ names.append(file_path)
+ return names
+
+
+# How many commits back came_from_secret looks.
+_SECRET_ORIGIN_COMMITS = 50
+
+
+def came_from_secret(repo_root, rev, paths, timeout):
+ """Those of `paths` at `rev` that one of the last commits renamed from a
+ secret's name, whatever they were called in between. None on error."""
+ try:
+ result = subprocess.run(
+ [*GIT_CMD, "-c", "log.diffMerges=separate", "log", "-m",
+ "-n", str(_SECRET_ORIGIN_COMMITS), "--format=", "--name-status", "-z",
+ "--no-ext-diff", rev, "--"],
+ cwd=repo_root, capture_output=True, timeout=timeout,
+ # A partial clone would download old files to compare them.
+ env={**os.environ, "GIT_NO_LAZY_FETCH": "1"})
+ except (subprocess.TimeoutExpired, OSError) as e:
+ debug_log(f"came_from_secret: {e}")
+ return None
+ if result.returncode != 0:
+ return None
+ # Newest commit first: every name each path has had so far.
+ had = {path: {path} for path in paths}
+ for old, new in _name_status_pairs(result.stdout):
+ for names in had.values():
+ if old and new in names:
+ names.add(old)
+ return {path for path, names in had.items() if any(map(_is_secret_text, names))}
+
+
+def git_diff_unpaired(repo_root, revs, paths, timeout):
+ """{path: hunks} for those of `paths` the commit or range `revs` names
+ (`show` or `diff` arguments) changed, each shown whole instead of against
+ the name it was renamed from. Empty hunks for a file git shows none for (a
+ binary one). None on error."""
+ try:
+ result = _run_diff_bounded(
+ [*GIT_CMD, revs[0], "-p", "--no-renames", "--no-color", "--no-ext-diff",
+ "--no-textconv", *revs[1:], "--", *paths],
+ timeout, cwd=repo_root, env=_literal_paths_env(os.environ))
+ except (subprocess.TimeoutExpired, OSError) as e:
+ debug_log(f"git_diff_unpaired: {e}")
+ return None
+ if result.returncode != 0:
+ debug_log(f"git_diff_unpaired: rc={result.returncode}: "
+ f"{result.stderr[:200].decode('utf-8', errors='replace')}")
+ return None
+ text = result.stdout.decode("utf-8", errors="replace")
+ # A path that used to be a directory also matches the files under it.
+ shown = {name: "" for name, _, _ in _iter_diff_sections(text)}
+ shown.update(parse_diff_into_files(text))
+ return {name: hunks for name, hunks in shown.items() if name in paths}
+
+
def filter_preexisting_from_diff(diff_files, cwd, baseline_sha):
"""
Filter out pre-existing content from diff files.
diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json
index 138dae00..d066726c 100644
--- a/plugins/security-guidance/hooks/hooks.json
+++ b/plugins/security-guidance/hooks/hooks.json
@@ -27,7 +27,8 @@
"hooks": [
{
"type": "command",
- "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\""
+ "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"",
+ "timeout": 60
}
],
"matcher": "Edit|Write|MultiEdit|NotebookEdit"
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 793da3c3..7b5e02fd 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -265,12 +265,21 @@ def _anthropic_base_url() -> str:
# the ones that fail; _urlopen does the same on the releases that do not.
_STORE_TLS_UNSET = object()
-_store_tls_context = _STORE_TLS_UNSET # None once Python's default context is known to build
+# The context the API calls use; None once Python's default one is known to do.
+_store_tls_context = _STORE_TLS_UNSET
_store_tls_lock = threading.Lock()
# Store entries left out of that context; emit_metrics reports it.
_store_certs_skipped = 0
+def _as_http_client_would(context):
+ """Sets what http.client sets on the context it makes itself."""
+ context.set_alpn_protocols(["http/1.1"])
+ if context.post_handshake_auth is not None:
+ context.post_handshake_auth = True
+ return context
+
+
def _context_without_unreadable_store_certs():
"""(context, skipped): Python's default TLS context built from the
Windows store entries OpenSSL can parse, and how many it could not.
@@ -307,31 +316,82 @@ def _context_without_unreadable_store_certs():
if context is None:
return None, skipped
context.set_default_verify_paths()
- # What http.client sets on the context it would have made.
- context.set_alpn_protocols(["http/1.1"])
- if context.post_handshake_auth is not None:
- context.post_handshake_auth = True
- return context, skipped
+ return _as_http_client_would(context), skipped
+
+
+# ── macOS Python with no certificates ────────────────────────────────────
+# A Python from the python.org installer has no CA certificates until its
+# "Install Certificates" command is run, and every HTTPS call from it fails
+# to verify. macOS ships a CA file, the one Apple's /usr/bin/python3 uses;
+# with it the calls verify as they do there.
+
+_ON_MACOS = sys.platform == "darwin"
+_MACOS_CA_FILE = "/etc/ssl/cert.pem"
+
+
+def _context_with_os_ca_file():
+ """Python's default TLS context plus the CA file macOS ships, or None.
+ Only where the default one has no certificate at all, so a Python that
+ can verify anything keeps exactly what it trusts. SSL_CERT_FILE and
+ SSL_CERT_DIR are the user's own choice of what to trust and win, also
+ when they point at nothing."""
+ if not _ON_MACOS or ssl is None:
+ return None
+ if "SSL_CERT_FILE" in os.environ or "SSL_CERT_DIR" in os.environ:
+ return None
+ if not _anthropic_base_url().lower().startswith("https:"):
+ return None
+ paths = ssl.get_default_verify_paths()
+ if paths.cafile or not os.path.isfile(_MACOS_CA_FILE):
+ return None
+ # The factory urllib uses, so a site that replaced it keeps its choice.
+ context = ssl._create_default_https_context()
+ if context.verify_mode != ssl.CERT_REQUIRED or context.cert_store_stats()["x509"]:
+ return None
+ # A CA directory is read during the handshake and is not in those counts.
+ # OpenSSL reads only hashed names (1a2b3c4d.0) from it; Homebrew keeps a
+ # placeholder file there.
+ with contextlib.suppress(OSError):
+ if paths.capath and any(re.fullmatch(r"[0-9a-f]{8}\.\d+", name)
+ for name in os.listdir(paths.capath)):
+ return None
+ context.load_verify_locations(cafile=_MACOS_CA_FILE)
+ return _as_http_client_would(context)
+
+
+def _own_tls_context():
+ """The context for API calls where Python's default one fails every call
+ (see above), else None."""
+ global _store_certs_skipped
+ try:
+ context, skipped = _context_without_unreadable_store_certs()
+ except Exception as e:
+ debug_log(f"TLS: certificate store check failed: {type(e).__name__}")
+ context, skipped = None, 0
+ if context is not None:
+ debug_log(f"TLS: the Windows certificate store has {skipped} certificate(s) "
+ "OpenSSL cannot read; using the store without them")
+ _store_certs_skipped = skipped
+ return context
+ try:
+ context = _context_with_os_ca_file()
+ except Exception as e:
+ debug_log(f"TLS: check for a Python without CA certificates failed: {type(e).__name__}")
+ return None
+ if context is not None:
+ debug_log(f"TLS: this Python has no CA certificates; using {_MACOS_CA_FILE}")
+ return context
def _urlopen(request, timeout):
"""urllib.request.urlopen for the plugin's API calls. Uses Python's
- default TLS context unless that cannot be built because of the Windows
- certificate store (see above); checked once per process."""
- global _store_tls_context, _store_certs_skipped
+ default TLS context unless that one fails every call (see
+ _own_tls_context); checked once per process."""
+ global _store_tls_context
if _store_tls_context is _STORE_TLS_UNSET:
with _store_tls_lock:
if _store_tls_context is _STORE_TLS_UNSET:
- try:
- context, skipped = _context_without_unreadable_store_certs()
- except Exception as e:
- debug_log(f"TLS: certificate store check failed: {type(e).__name__}")
- context, skipped = None, 0
- if context is not None:
- debug_log(f"TLS: the Windows certificate store has {skipped} certificate(s) "
- "OpenSSL cannot read; using the store without them")
- _store_certs_skipped = skipped
- _store_tls_context = context
+ _store_tls_context = _own_tls_context()
if _store_tls_context is None:
return urllib.request.urlopen(request, timeout=timeout)
return urllib.request.urlopen(request, timeout=timeout, context=_store_tls_context)
@@ -1937,6 +1997,35 @@ def _agentic_commit_review_enabled() -> bool:
# precedents and an adversarial refute taxonomy to drop low-signal findings.
_AGENTIC_INVESTIGATE_SYSTEM = review_api.AGENTIC_INVESTIGATE_SYSTEM
+
+# The investigate stages return their findings through the StructuredOutput
+# tool and nothing reads what they write beside it. Told so here, not in
+# review_api: a caller of that module may take its answer from the text.
+_REVIEWER_OUTPUT_RULE = (
+ "\n\nOUTPUT: only the `findings` you return are read, not text you write. "
+ "Write no prose before, between or after tool calls, and no verdicts "
+ "for files you clear: think them through instead. Ask for the files "
+ "and searches you can already name in one message, within the budget "
+ "above. `explanation` must still name the source, the sink and the path "
+ "between them. When you are done, return the findings at once."
+)
+
+
+def _investigate_system() -> str:
+ """The investigate stages' system prompt. Text between tool calls is where
+ a model reasons when thinking is off or the user picked the model, so the
+ output rule is left out there."""
+ thinking_off = (os.environ.get("MAX_THINKING_TOKENS", "").strip() == "0"
+ or any(os.environ.get(v, "").strip().lower() in ("1", "true", "yes", "on")
+ for v in ("CLAUDE_CODE_DISABLE_THINKING",
+ "CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING")))
+ picked = any(os.environ.get(v, "").strip()
+ for v in ("SG_AGENTIC_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL"))
+ if thinking_off or picked:
+ return _AGENTIC_INVESTIGATE_SYSTEM
+ return _AGENTIC_INVESTIGATE_SYSTEM + _REVIEWER_OUTPUT_RULE
+
+
_FINDINGS_SCHEMA = review_api.FINDINGS_SCHEMA
_SURVIVED_SCHEMA = review_api.SURVIVED_SCHEMA
@@ -2468,7 +2557,7 @@ def _agentic_review(
t0 = _t.time()
try:
inv, inv_turns, inv_subtype = _run(
- _AGENTIC_INVESTIGATE_SYSTEM, user_prompt, schema=_FINDINGS_SCHEMA
+ _investigate_system(), user_prompt, schema=_FINDINGS_SCHEMA
)
if os.environ.get("SG_AGENTIC_DEBUG_DIR"):
_dd = os.environ["SG_AGENTIC_DEBUG_DIR"]
@@ -2534,7 +2623,7 @@ def _agentic_review(
)
try:
inv2, _, _ = _run(
- _AGENTIC_INVESTIGATE_SYSTEM, iter2_prompt, schema=_FINDINGS_SCHEMA
+ _investigate_system(), iter2_prompt, schema=_FINDINGS_SCHEMA
)
if inv2:
seen = {(c.get("filePath"), c.get("category")) for c in candidates}
diff --git a/plugins/security-guidance/hooks/patterns.py b/plugins/security-guidance/hooks/patterns.py
index 46224164..689f9c77 100644
--- a/plugins/security-guidance/hooks/patterns.py
+++ b/plugins/security-guidance/hooks/patterns.py
@@ -48,6 +48,22 @@ def _call_args():
_CALL_ARGS = _call_args()
+
+def _page_function_call():
+ """Regex for Playwright's and Puppeteer's `$eval('selector', function`, read
+ from its "eval(". It runs the function, so nothing is evaluated from a string.
+
+ Both have to be written out in the call: a string with nothing put into it,
+ then a function. AngularJS `scope.$eval(expr)` and any other `$eval(` do not
+ match. Every repeat is bounded.
+ """
+ selector = r"\x22[^\x22\\\n]{0,300}\x22|\x27[^\x27\\\n]{0,300}\x27|`[^`$\\]{0,300}`"
+ arrow = r"(?:[\w$]{1,60}|\([^()]{0,200}\))\s{0,20}(?::[^=\n]{0,60})?=>"
+ return rf"eval\(\s{{0,200}}(?:{selector})\s{{0,20}},\s{{0,200}}(?:async\b\s{{0,20}})?(?:function\b|{arrow})"
+
+
+_PAGE_FUNCTION_CALL = _page_function_call()
+
# Security patterns configuration
SECURITY_PATTERNS = [
{
@@ -119,15 +135,18 @@ Only use exec() if you absolutely need shell features and the input is guarantee
# JS-only construct: gate to JS/TS files so docs/.md and other prose
# mentioning "new Function" don't trip the warning.
"path_filter": lambda p: p.endswith(_JS_EXTS),
- "substrings": ["new Function"],
+ # The whole word: `new FunctionRegistry()` is another class. The two names
+ # code gives to Function itself still count.
+ "regex": r"new Function(?:Constructor|Ctor)?(?![\w$])",
"reminder": "\u26a0\ufe0f Security Warning: Using new Function() with string interpolation is a CODE INJECTION vulnerability. If any variable is concatenated or interpolated into the function body string, an attacker controlling that variable can execute arbitrary code. Use safe alternatives: for property access use obj[key] or array.reduce((o, k) => o[k], root); for computation use a safe expression parser. NEVER interpolate untrusted strings into new Function() bodies.",
},
{
"ruleName": "eval_injection",
# Lookbehind excludes `.` so method calls like PyTorch model.eval(),
- # redis.eval(), spec.eval() don't match. Skip doc/prose files.
+ # redis.eval(), spec.eval() don't match. Playwright's page.$eval('selector',
+ # function) is left out too. Skip doc/prose files.
"path_filter": lambda p: not p.endswith(_DOC_EXTS),
- "regex": r"(?<![a-zA-Z0-9_\.])eval\(",
+ "regex": rf"(?<![a-zA-Z0-9_\.])(?!(?<=\$){_PAGE_FUNCTION_CALL})eval\(",
"reminder": "⚠️ Security Warning: eval() executes arbitrary code and is a major security risk. Use JSON.parse() for data, ast.literal_eval() for Python literals, or a safe expression parser. If this is safe or is explicitly needed, briefly document that in a comment before continuing.",
},
{
@@ -150,7 +169,8 @@ Only use exec() if you absolutely need shell features and the input is guarantee
# docs/example HTML, playground/self-contained skills that hardcode
# innerHTML strings with zero user input (#410).
"path_filter": lambda p: p.endswith(_JS_EXTS),
- "substrings": [".innerHTML =", ".innerHTML="],
+ # An assignment, not a `==` or `===` comparison.
+ "regex": r"\.innerHTML ?=(?!=)",
"reminder": "⚠️ Security Warning: Setting innerHTML with untrusted content can lead to XSS vulnerabilities. Use textContent for plain text or safe DOM methods for HTML content. If you need HTML support, consider using an HTML sanitizer library such as DOMPurify.",
},
{
@@ -253,7 +273,7 @@ Additionally, validate user inputs:
"ruleName": "outerHTML_xss",
# Browser DOM API: only meaningful in JS/TS source.
"path_filter": lambda p: p.endswith(_JS_EXTS),
- "substrings": [".outerHTML =", ".outerHTML="],
+ "regex": r"\.outerHTML ?=(?!=)",
"reminder": "⚠️ Security Warning: Use textContent or sanitize with DOMPurify. outerHTML assignment is an XSS sink equivalent to innerHTML.",
},
{
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index b6274442..d31307de 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -117,7 +117,8 @@ from gitutil import ( # noqa: E402,F401
_LOW_PRIORITY_SUFFIXES, _LOW_PRIORITY_PATH_TOKENS,
_prioritize_diff_files, _is_reviewable_source,
extract_file_paths_from_diff, parse_diff_into_files,
- filter_preexisting_from_diff,
+ filter_preexisting_from_diff, renamed_into_review,
+ came_from_secret, git_diff_unpaired,
)
from diffstate import ( # noqa: E402,F401
STOP_LOOP_STATE_TTL_SEC, PREVIOUS_FINDINGS_TTL_SEC,
@@ -260,10 +261,19 @@ _TAIL_METRICS: Dict[str, Any] = {}
# Of those, the ones that go after the others whenever they were set: a row
# over CC's key cap loses them before any older review key. Only the launcher
# keys below come later; those are also on every smaller row of the session.
-_LAST_METRIC_KEYS = ("diff_seen", "cr_pack")
+_LAST_METRIC_KEYS = ("diff_seen", "cr_pack", "renamed_in")
# CC keeps this many keys of a row.
_METRIC_KEY_CAP = 20
+# A review row's result, kind and time. emit_metrics puts them right after its
+# own keys (pv, launcher, usage, net_err), so the key cap cuts descriptive keys
+# before any of these. Keep it short: a failed row can carry 12 keys ahead of
+# them, and commit_review / push_sweep tell the rows apart under the old cap
+# of 10.
+_LEAD_METRIC_KEYS = ("review_failed", "api_error", "vulns_found",
+ "commit_review", "push_sweep", "review_ms",
+ "files_reviewed", "agentic", "deduped",
+ "critical_count", "high_count")
# How long a Stop row waits for its commit count.
_TURN_COMMITS_WAIT_S = 2.0
# Set by the Stop hook: queues the commit count for the row being emitted.
@@ -374,7 +384,8 @@ def emit_metrics(
the same reason but stale: once `rate_count` was added to every
commit-review emit, the with-vulns dict hit 10 keys, `pv` was skipped, and
findings metrics landed without a plugin version attached, breaking
- per-version breakdowns.
+ per-version breakdowns. `_LEAD_METRIC_KEYS` come next on a review row,
+ wherever the caller put them.
`rewake_summary` (asyncRewake only): per-run override of the static
rewakeSummary in hooks.json, shown to the user in the terminal as the
@@ -431,8 +442,15 @@ def emit_metrics(
net_err = _net_error_metric()
if net_err:
head["net_err"] = net_err
- if head:
- metrics = {**head, **metrics}
+ # Skip rows are left as they are: theirs is the skip reason.
+ lead = {} if metrics.get("skipped") else {
+ k: metrics[k] for k in _LEAD_METRIC_KEYS if k in metrics}
+ metrics = {**head, **lead, **metrics}
+ if not metrics.get("skipped"):
+ # Always true on a row that is not a skip, so cut before the rest.
+ for k in ("commit_review_on", "push_sweep_on"):
+ if k in metrics:
+ metrics[k] = metrics.pop(k)
# Diagnostic keys go last, so they are the first dropped when a row is
# over CC's key cap and never displace an existing key.
tail = {}
@@ -1097,14 +1115,17 @@ _COMMIT_SHA_RE = re.compile(r'^\[[^\]]*?\b([0-9a-f]{7,40})\]', re.MULTILINE)
# _GIT_COMMIT_RE and _GIT_PUSH_RE: `-C <path>`, `-c key=val`, `--opt=val`,
# the long options that take a separate value, and flags that take none
# (`--no-pager`, `-p`). A value may be quoted in part (`-c user.name="A B"`).
-_GIT_OPT_VALUE = r'''(?:[^\s"']|"[^"]*"|'[^']*')+'''
+# Between the words: whitespace, or a line continued with a backslash (Bash) or
+# a backtick (PowerShell).
+_WORD_GAP = r'(?:\s|[\\`]\r?\n)+'
+_GIT_OPT_VALUE = r'''(?:(?![\\`]\r?\n)[^\s"']|"[^"]*"|'[^']*')+'''
_GIT_VALUE_OPTS = r'git-dir|work-tree|namespace|config-env|attr-source'
_GIT_GLOBAL_OPTS = (
- r'(?:\s+-[Cc]\s+' + _GIT_OPT_VALUE
- + r'|\s+--[^\s=]+=' + _GIT_OPT_VALUE
- + r'|\s+--(?:' + _GIT_VALUE_OPTS + r')\s+' + _GIT_OPT_VALUE
+ r'(?:' + _WORD_GAP + r'-[Cc]' + _WORD_GAP + _GIT_OPT_VALUE
+ + r'|' + _WORD_GAP + r'--[^\s=]+=' + _GIT_OPT_VALUE
+ + r'|' + _WORD_GAP + r'--(?:' + _GIT_VALUE_OPTS + r')' + _WORD_GAP + _GIT_OPT_VALUE
# `--help` / `--version` run no subcommand.
- + r'|\s+(?:--(?!(?:' + _GIT_VALUE_OPTS + r'|help|version)\s)[^\s=]+|-[pP])(?=\s))*'
+ + r'|' + _WORD_GAP + r'(?:--(?!(?:' + _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.
@@ -1114,15 +1135,15 @@ _GIT_COMMIT_RE = re.compile(
# 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'\b' + _GIT_PROGRAM + _GIT_GLOBAL_OPTS + r'\s+commit\b(?!-)'
- r'|\bgt\s+(?:create|modify)\b'
+ r'\b' + _GIT_PROGRAM + _GIT_GLOBAL_OPTS + _WORD_GAP + r'commit\b(?!-)'
+ r'|\bgt' + _WORD_GAP + r'(?:create|modify)\b'
)
# Match either the `--amend` flag (with the leading whitespace boundary
# preserved from the original) OR `gt modify` which is semantically an
# amend. The handler treats matches as "find the pre-amend SHA via reflog
# and diff against THAT, not against the post-amend HEAD's parent" — same
# code path for both git --amend and gt modify.
-_GIT_AMEND_RE = re.compile(r'(?:\s--amend\b|\bgt\s+modify\b)')
+_GIT_AMEND_RE = re.compile(r'(?:\s--amend\b|\bgt' + _WORD_GAP + r'modify\b)')
# Rolling-window cap on LLM commit-review calls. See atomic_check_rate_limit
# docstring for the rationale that motivated the switch from a lifetime cap.
@@ -1155,7 +1176,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'(?:\b' + _GIT_PROGRAM + _GIT_GLOBAL_OPTS + r'\s+push\b|\bgt\s+submit\b)'
+ r'(?:\b' + _GIT_PROGRAM + _GIT_GLOBAL_OPTS + _WORD_GAP + r'push\b|\bgt' + _WORD_GAP + r'submit\b)'
)
# `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on
@@ -1221,6 +1242,35 @@ def _unmatched_bash_sampled(input_data):
return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0
+_bash_hook_git_dir = {}
+
+
+def _bash_hook_sentinel(input_data, route="once"):
+ """The file one spawn of this Bash call's hook creates to claim `route`,
+ or None when there is nothing to tell the spawns apart by."""
+ tuid = input_data.get("tool_use_id")
+ cwd = input_data.get("cwd")
+ if not tuid or not cwd:
+ return None
+ command = (input_data.get("tool_input") or {}).get("command", "") or ""
+ call = (tuid, cwd, command)
+ if call not in _bash_hook_git_dir:
+ _bash_hook_git_dir[call] = _git_dir(
+ _git_toplevel(cwd)
+ or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS)
+ or cwd
+ )
+ gd = _bash_hook_git_dir[call]
+ if not gd:
+ return None
+ # 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]
+ # A second route ("push") lets the other spawn of a commit-and-push run
+ # its own review, once.
+ return os.path.join(gd, f"sg-hook-once-{safe}" + ("" if route == "once" else f"-{route}"))
+
+
def _claim_bash_hook_once(input_data, route="once"):
"""De-dupe across hooks.json `if` matchers firing for the same Bash call.
@@ -1236,20 +1286,12 @@ def _claim_bash_hook_once(input_data, route="once"):
Sentinel is per-clone (`.git/sg-hook-once-<tool_use_id>`), not /tmp,
so concurrent CC sessions in *different* repos don't collide. Stale
- sentinels (>5min) are GC'd opportunistically.
+ sentinels (older than a hook can run) are GC'd opportunistically.
"""
- tuid = input_data.get("tool_use_id")
- cwd = input_data.get("cwd")
- if not tuid or not cwd:
- return True
- command = (input_data.get("tool_input") or {}).get("command", "") or ""
- gd = _git_dir(
- _git_toplevel(cwd)
- or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS)
- or cwd
- )
- if not gd:
+ sentinel = _bash_hook_sentinel(input_data, route)
+ if not sentinel:
return True
+ gd = os.path.dirname(sentinel)
# GC: best-effort sweep of stale sentinels so they don't accumulate.
import time as _time
now = _time.time()
@@ -1258,21 +1300,20 @@ def _claim_bash_hook_once(input_data, route="once"):
if name.startswith("sg-hook-once-"):
p = os.path.join(gd, name)
try:
- if now - os.path.getmtime(p) > 300:
+ if now - os.path.getmtime(p) > 900:
os.unlink(p)
except OSError:
pass
except OSError:
pass
- # 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]
- # 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)
+ command = (input_data.get("tool_input") or {}).get("command", "") or ""
+ if (route == "once" and _GIT_COMMIT_RE.search(command)
+ and _GIT_PUSH_RE.search(command)):
+ # The push spawn of this command waits for this one to end.
+ diffstate.hold_until_exit(sentinel)
return True
except FileExistsError:
return False
@@ -1366,6 +1407,78 @@ def _merge_resolved_diff_files(repo_root, merges):
resolved[path] = resolved[path] + "\n" + hunks if path in resolved else hunks
return resolved
+
+# Files renamed into review that one review takes, by priority, how much of
+# the prompt they get, and the time for the git calls behind it.
+MAX_RENAMED_IN = 10
+RENAMED_IN_BYTES = DIFF_TOTAL_BYTES // 4
+RENAMED_IN_TIMEOUT_S = 15
+
+
+def _with_renamed_in(repo_root, diff_files, renamed, cap):
+ """`diff_files` plus, whole, files renamed into review (see
+ renamed_into_review). `renamed` is (name, git arguments that show it, the
+ commit they end at) per file. Returns (files, whether git failed to show
+ some of them).
+
+ No file reviewed without them is dropped or cut because of them: a new
+ entry goes behind the others in a place they leave free, and a file
+ already there for an edit becomes the whole of it plus the lines the edit
+ removed. The rest is reviewed as before.
+ """
+ origin = {}
+ for name, revs, rev in renamed:
+ origin.setdefault(name, (revs, rev))
+ if not origin or len(diff_files) > cap:
+ return diff_files, False
+ there = dict(diff_files)
+ room = cap - len(diff_files)
+ by_revs = {}
+ for name, _ in _prioritize_diff_files([(n, "") for n in origin], MAX_RENAMED_IN)[0]:
+ if there.get(name, "").startswith("@@@"):
+ continue # a merge's own hunks, in another format
+ if name not in there:
+ if room <= 0:
+ continue
+ room -= 1
+ by_revs.setdefault(origin[name], []).append(name)
+
+ deadline = time.monotonic() + RENAMED_IN_TIMEOUT_S
+
+ def left():
+ return max(deadline - time.monotonic(), 0.1)
+
+ whole, failed = {}, False
+ for (revs, rev), names in by_revs.items():
+ secret = came_from_secret(repo_root, rev, names, left())
+ names = [n for n in names if secret is not None and n not in secret]
+ shown = git_diff_unpaired(repo_root, revs, names, left()) if names else {}
+ failed = failed or secret is None or shown is None or len(shown) < len(names)
+ whole.update((name, hunks) for name, hunks in (shown or {}).items() if hunks)
+
+ def size(hunks):
+ # With room for the marker a cut file ends in.
+ return min(len(hunks), DIFF_PER_FILE_BYTES) + 100
+
+ budget = min(RENAMED_IN_BYTES,
+ DIFF_TOTAL_BYTES - sum(size(hunks) for _, hunks in diff_files))
+ taken = {}
+ for name, hunks in whole.items():
+ if name in there:
+ removed = [ln for ln in there[name].split("\n") if ln.startswith(("@@", "-"))]
+ hunks = "\n".join([hunks, *removed])
+ if len(hunks) > DIFF_PER_FILE_BYTES:
+ continue
+ if size(hunks) <= budget:
+ budget -= size(hunks)
+ taken[name] = hunks
+ if taken:
+ debug_log(f"{len(taken)} file(s) renamed from a text name")
+ _TAIL_METRICS["renamed_in"] = len(taken)
+ files = [(name, taken.pop(name, hunks)) for name, hunks in diff_files]
+ return files + list(taken.items()), failed
+
+
def _push_section(bash_output):
"""Return the slice of `bash_output` that contains the push's range lines.
@@ -1488,6 +1601,9 @@ _RACE_MAX_WAIT_S = 480
# Claude Code kills the hook. The inner CLI exits with the hook. The same limit
# holds for a commit or push review's single-shot review outside a race.
_RACE_END_S = 570
+# Seconds after which a failed commit review stops waiting for the push review
+# of its own command, which may run to the limit above on a later clock.
+_HOOK_LAST_WAIT_S = 580
# api_error for a race that hit that deadline with no verdict.
_RACE_TIMED_OUT = -2
@@ -1718,12 +1834,37 @@ def _left_out_files_notice(session_id, repo_root, untracked, diff_output):
f"in {DEBUG_LOG_FILE}.")
-def _exit_review_failed(kind, session_id, metrics, status, pushed="no"):
+def _push_review_takes_over(input_data):
+ """True when the push spawn of this commit-and-push call waits to review
+ what this commit review has no verdict on."""
+ command = input_data["tool_input"]["command"]
+ sentinel = _bash_hook_sentinel(input_data, "push")
+ return bool(
+ PUSH_SWEEP_ENABLED and sentinel and _GIT_PUSH_RE.search(command)
+ # It may still be on its way to the wait when a review fails at once.
+ and diffstate.becomes_held(sentinel, 3))
+
+
+def _push_review_settled_it(input_data):
+ """Let the push review that waits for this commit review go on, and wait
+ for its end. False when it ended without a verdict and told nobody (a cap,
+ no network, killed): that is for the commit review to report."""
+ debug_log("Commit review: got no verdict; waiting for the push review of the same command")
+ diffstate._release_inflight()
+ diffstate.release_hold(_bash_hook_sentinel(input_data))
+ diffstate.wait_for_holder(_bash_hook_sentinel(input_data, "push"),
+ max(0.0, _HOOK_LAST_WAIT_S - _hook_spent_s()))
+ return os.path.exists(_bash_hook_sentinel(input_data, "settled"))
+
+
+def _exit_review_failed(kind, session_id, metrics, status, pushed="no", told=None):
"""End a commit ("Commit") or push ("Push") review that got no verdict.
Never reports the code as clean. Tells Claude once per session for each
kind of review and failure; repeats are only logged. `pushed` ("yes",
- "maybe" or "no"): whether the commit's own command also pushed it. Exits.
+ "maybe" or "no"): whether the commit's own command also pushed it;
+ "taken_over" when that command's push review dealt with it. `told` is
+ called when Claude is told. Exits.
"""
failure, reason, cause = _review_failure_reason(status)
debug_log(f"{kind} review: got no verdict ({reason}); not marked reviewed")
@@ -1733,7 +1874,7 @@ def _exit_review_failed(kind, session_id, metrics, status, pushed="no"):
# A commit its own command pushed gets its own notice: no later push
# re-checks it.
told_key = f"review_failed:{kind}:{failure}" + (":pushed" if pushed == "yes" else "")
- if not atomic_check_and_mark_warning(session_id, told_key):
+ if pushed == "taken_over" or not atomic_check_and_mark_warning(session_id, told_key):
emit_metrics(metrics)
sys.exit(0)
subject = "this push" if kind == "Push" else "this commit"
@@ -1760,8 +1901,41 @@ def _exit_review_failed(kind, session_id, metrics, status, pushed="no"):
emit_metrics(metrics,
rewake_summary=(f"{kind} security review did not complete: {reason}. "
f"Log: {DEBUG_LOG_FILE}"))
+ if told:
+ told()
sys.exit(2)
+def _commit_in_output(bash_output):
+ """The commit that a successful `git commit` printed, or None."""
+ # Require BOTH a line-anchored `[branch sha]` AND a git-only diffstat
+ # signal before treating the tool call as a successful commit. The old
+ # `any()` check false-positived on (a) pre-commit/husky/lint-staged hooks
+ # emitting labels like `[pre-commit abc1234]`, and on (b) chained
+ # `git commit || git log --stat` where `N files changed` appears in output
+ # even though the commit itself failed.
+ #
+ # Take only the LAST match: pre-commit/husky hooks can print bracketed
+ # labels like `[pre-commit abc1234]` that precede the real `[branch sha]`
+ # line; chained commands like `git commit && git commit` produce multiple
+ # real SHAs and we want the most recent. The real commit line is always
+ # last in git's own output — the earlier matches are either decoys or
+ # superseded commits.
+ all_shas = _COMMIT_SHA_RE.findall(bash_output)
+ if all_shas and any(p.search(bash_output) for p in _COMMIT_DIFFSTAT_PATTERNS):
+ return all_shas[-1]
+ return None
+
+
+def _commit_review_candidates(bash_output, repo_root):
+ """(shas, stale): the commits the commit review of a Bash call that was
+ not interrupted takes, newest first, before it leaves out those already
+ reviewed or under review: the one its output names, else the fresh ones in
+ the reflog, with the count of entries too old. Both the commit review and
+ the push review of the same call choose by this."""
+ named = _commit_in_output(bash_output)
+ return ([named], 0) if named else _git_reflog_recent_commits(repo_root)
+
+
def handle_commit_review_posttooluse(input_data):
"""PostToolUse handler for Bash — reviews git commits for security issues.
@@ -1798,19 +1972,10 @@ def handle_commit_review_posttooluse(input_data):
bash_output = stdout + "\n" + stderr
interrupted = bool(tool_response.get("interrupted"))
- # Require BOTH a line-anchored `[branch sha]` AND a git-only diffstat
- # signal before treating the tool call as a successful commit. The old
- # `any()` check false-positived on (a) pre-commit/husky/lint-staged hooks
- # emitting labels like `[pre-commit abc1234]`, and on (b) chained
- # `git commit || git log --stat` where `N files changed` appears in output
- # even though the commit itself failed.
all_shas = _COMMIT_SHA_RE.findall(bash_output)
diffstate.note_seen_commits(session_id, all_shas)
- commit_succeeded = (
- not interrupted
- and bool(all_shas)
- and any(p.search(bash_output) for p in _COMMIT_DIFFSTAT_PATTERNS)
- )
+ named = None if interrupted else _commit_in_output(bash_output)
+ commit_succeeded = bool(named)
# commit_review_on emitted on every path so telemetry can filter on
# commit_review and group by commit_review_on.
@@ -1851,7 +2016,7 @@ def handle_commit_review_posttooluse(input_data):
repo_res = RES_HINT
_base["repo_resolution"] = repo_res
_root = repo_root
- _fresh, _stale = _git_reflog_recent_commits(_root)
+ _fresh, _stale = _commit_review_candidates(bash_output, _root)
diffstate.note_seen_commits(session_id, _fresh)
if _fresh:
# Commits an earlier call's review is still working on are that
@@ -1909,8 +2074,8 @@ def handle_commit_review_posttooluse(input_data):
emit_metrics({"skipped": True, "skip_reason": 25, **_base})
sys.exit(0)
- if not repo_root and all_shas and not _reflog_shas:
- repo_root = repo_containing_commit(all_shas[-1], scan_roots(cwd))
+ if not repo_root and named:
+ repo_root = repo_containing_commit(named, scan_roots(cwd))
if repo_root:
repo_res = RES_SHA_SCAN
if not repo_root:
@@ -1936,13 +2101,6 @@ def handle_commit_review_posttooluse(input_data):
# fallback above is the narrow exception: it only fires when output gave
# us nothing AND the cwd repo's own reflog confirms a `commit:` just
# happened there, which rules out the cross-repo case.
- #
- # Take only the LAST match: pre-commit/husky hooks can print bracketed
- # labels like `[pre-commit abc1234]` that precede the real `[branch sha]`
- # line; chained commands like `git commit && git commit` produce multiple
- # real SHAs and we want the most recent. The real commit line is always
- # last in git's own output — the earlier matches are either decoys or
- # superseded commits.
if _reflog_shas:
# Output-based detection already failed above; the reflog SHAs are the
# authoritative ones. Don't re-parse bash_output here — any bracketed
@@ -1953,7 +2111,7 @@ def handle_commit_review_posttooluse(input_data):
# all are reviewed.
shas = _reflog_shas
else:
- shas = [all_shas[-1]] if all_shas else []
+ shas = [named] if named else []
if not shas:
debug_log("Commit review: no SHA in commit output")
emit_metrics({"skipped": True, "skip_reason": 33, **_base})
@@ -2020,6 +2178,7 @@ def handle_commit_review_posttooluse(input_data):
# can contain non-UTF8 source (latin-1, cp1252) and text=True would raise
# UnicodeDecodeError outside the except clause.
diff_files = []
+ renamed = []
resolved = 0
max_files = 10 * MAX_DIFF_FILES
for sha in shas:
@@ -2048,8 +2207,18 @@ def handle_commit_review_posttooluse(input_data):
debug_log(f"Commit review: {_cmd} {sha} rc={result.returncode}")
continue
resolved += 1
- diff_files.extend(parse_diff_into_files(
- result.stdout.decode("utf-8", errors="replace")))
+ diff_text = result.stdout.decode("utf-8", errors="replace")
+ diff_files.extend(parse_diff_into_files(diff_text))
+ names = renamed_into_review(diff_text)
+ if names:
+ revs, rev = ("show", "--format=", sha), sha
+ if pre_amend_sha:
+ revs = ("diff", pre_amend_sha, sha)
+ elif sha != shas[0] and _is_ancestor(repo_root, sha, shas[0]):
+ # A later commit of the same call can have changed the file
+ # again: show it as the last one left it.
+ revs, rev = ("diff", f"{sha}^", shas[0]), shas[0]
+ renamed += [(name, revs, rev) for name in names]
# Dedup by path. The widened reflog scan can return >1 SHA (e.g.
# `git commit && git commit --amend` within 120s); a path that appears in
@@ -2069,6 +2238,8 @@ def handle_commit_review_posttooluse(input_data):
"shas_found": len(shas), **_diff_read_metrics()})
sys.exit(0)
+ diff_files, _ = _with_renamed_in(repo_root, diff_files, renamed, MAX_DIFF_FILES)
+
# Empty amend delta = message-only amend (or whitespace-only that the
# diff already collapses). No code to review; skip cleanly. skip_reason=35.
# Gated on resolved > 0 so subprocess failures (caught with `continue`
@@ -2076,8 +2247,20 @@ def handle_commit_review_posttooluse(input_data):
# skip_reason=28 correctly.
if pre_amend_sha and not diff_files:
debug_log("Commit review: --amend produced empty delta (message-only?), skipping")
+ # Same content under a new sha: as reviewed as the original is. With
+ # its review still running, see that end first. A push review of the
+ # new sha waits for this process meanwhile: wait less than it does, so
+ # that it can still review what has no verdict by then.
+ _new = _full_shas(repo_root, shas)
+ _mark_inflight(repo_root, _new)
+ reviewed, _waited = _reviewed_after_inflight(
+ repo_root, [pre_amend_sha], max(0.0, INFLIGHT_WAIT_S * 0.9 - _hook_spent_s()))
+ if pre_amend_sha in reviewed:
+ _append_reviewed_shas(repo_root, _new)
emit_metrics({"skipped": True, "skip_reason": 35, **_base,
- "files_reviewed": 0, **_diff_read_metrics()})
+ "files_reviewed": 0,
+ **({"inflight_wait_s": max(1, int(round(_waited)))} if _waited else {}),
+ **_diff_read_metrics()})
sys.exit(0)
debug_log(f"Commit review: {resolved}/{len(shas)} sha(s) resolved, "
@@ -2174,7 +2357,7 @@ def handle_commit_review_posttooluse(input_data):
# severity filter; `survived_after_sev` is the count the user actually
# sees. Include `survived_after_sev` ONLY when the filter actually
# dropped candidates — otherwise it's redundant with `survived` and eats
- # into CC's metric-key cap, pushing files_reviewed/review_ms out of the
+ # into CC's metric-key cap, pushing critical_count/high_count out of the
# emitted metrics.
#
# CC accepts only booleans and finite numbers as metric values.
@@ -2217,7 +2400,9 @@ def handle_commit_review_posttooluse(input_data):
**_base, **_agentic_m,
"files_reviewed": len(diff_files), "review_ms": review_ms,
}, api_status, pushed=(
- "yes" if _push_in_output(bash_output)
+ "taken_over" if _push_review_takes_over(input_data)
+ and _push_review_settled_it(input_data)
+ else "yes" if _push_in_output(bash_output)
else "maybe" if _GIT_PUSH_RE.search(command) or _MAY_PUSH_VIA_GH_RE.search(command)
else "no"))
@@ -2323,12 +2508,17 @@ def _pushed_beyond_commit_review(repo_root, push_range, bash_output):
"""
covered = []
if COMMIT_REVIEW_ENABLED:
- named = _COMMIT_SHA_RE.findall(bash_output)
- covered = named[-1:] or _git_reflog_recent_commits(repo_root)[0]
+ covered = _commit_review_candidates(bash_output, repo_root)[0]
rest = [s for s in push_range if not any(s.startswith(c) for c in covered)]
+ return _without_review(repo_root, rest)
+
+
+def _without_review(repo_root, shas):
+ """True when one of `shas` is neither reviewed nor under review."""
+ # In that order: a review that ends in between then counts as reviewed.
+ held = _load_inflight_shas(repo_root, shas)
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)
+ return any(s not in reviewed and s not in held for s in shas)
def handle_push_sweep_posttooluse(input_data):
@@ -2499,7 +2689,9 @@ def handle_push_sweep_posttooluse(input_data):
emit_metrics({"skipped": True, "skip_reason": 41, **_base})
sys.exit(0)
- push_range = _git_rev_list_range(repo_root, prev_upstream, "HEAD")
+ # The tip that was pushed, checked above. HEAD itself may move meanwhile.
+ tip = head or "HEAD"
+ push_range = _git_rev_list_range(repo_root, prev_upstream, tip)
if not push_range:
emit_metrics({"skipped": True, "skip_reason": 42, **_base, "pushed": 0})
sys.exit(0)
@@ -2509,24 +2701,55 @@ def handle_push_sweep_posttooluse(input_data):
"pushed": len(push_range)})
sys.exit(0)
+ def _note_settled():
+ # Tells the commit spawn of this call that it has nothing to report.
+ if (_GIT_COMMIT_RE.search(command) and any(
+ s.startswith(c) for s in push_range
+ for c in _commit_review_candidates(bash_output, repo_root)[0])):
+ _claim_bash_hook_once(input_data, "settled")
+
+ _spawn_wait, _take_over = 0.0, False
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)
+ # All of it is the other spawn's to review. Once pushed, no later push
+ # covers it, so see that review end and take over what got no verdict.
+ # One that outlasts the wait, or cannot be watched, is left to it.
+ reviewed = _load_reviewed_shas(repo_root)
+ if any(s not in reviewed for s in push_range):
+ diffstate.hold_until_exit(_bash_hook_sentinel(input_data, "push"))
+ _ended, _spawn_wait = diffstate.wait_for_holder(
+ _bash_hook_sentinel(input_data), INFLIGHT_WAIT_S)
+ _take_over = _ended and _without_review(repo_root, push_range)
+ if _ended and not _take_over:
+ reviewed = _load_reviewed_shas(repo_root)
+ if all(s in reviewed for s in push_range):
+ _note_settled()
+ # A commit the hourly cap kept out stays out.
+ _skip = (47 if not _take_over
+ else 23 if atomic_check_rate_limit(
+ session_id, "CommitReview", 0, COMMIT_REVIEW_RATE_WINDOW_S
+ )[1] >= MAX_COMMIT_REVIEWS_PER_HOUR
+ else 24 if not ensure_anthropic_reachable() else 0)
+ if _skip:
+ emit_metrics({"skipped": True, "skip_reason": _skip, **_base,
+ "pushed": len(push_range),
+ **({"inflight_wait_s": max(1, int(round(_spawn_wait)))}
+ if _spawn_wait else {})})
+ 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.
reviewed, _waited = _reviewed_after_inflight(
- repo_root, push_range, INFLIGHT_WAIT_S)
+ repo_root, push_range, max(0.0, INFLIGHT_WAIT_S - _spawn_wait))
+ _waited += _spawn_wait
_wait_m = {}
if _waited:
_wait_m = {"inflight_wait_s": max(1, int(round(_waited)))}
debug_log(f"Push sweep: waited {_waited:.0f}s for a running commit review")
base, tail = _compute_push_sweep_base(prev_upstream, push_range, reviewed)
prefix_advanced = len(push_range) - len(tail)
- _parents = _git_range_parents(repo_root, prev_upstream, "HEAD") if base else {}
+ _parents = _git_range_parents(repo_root, prev_upstream, tip) if base else {}
_settled = []
if any(len(p) > 1 for p in _parents.values()):
base, _settled = _push_sweep_base_with_merges(
@@ -2541,12 +2764,15 @@ def handle_push_sweep_posttooluse(input_data):
prefix_advanced = 0
if base is None:
debug_log("Push sweep: every pushed commit already reviewed")
+ _note_settled()
emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0,
"prefix_advanced": prefix_advanced, **_wait_m})
sys.exit(0)
- if _waited and head and _git_rev_parse_head(repo_root) != head:
- # Same guard as above: the diff and the reviewer's file reads are
- # both taken at HEAD, and HEAD left the pushed tip during the wait.
+ _head_moved = bool(_waited and head and _git_rev_parse_head(repo_root) != head)
+ if _head_moved and not _take_over:
+ # Same guard as above: the agentic reviewer reads files at HEAD, and
+ # HEAD left the pushed tip during the wait. A take-over goes on without
+ # that reviewer, on the diff of the pushed tip.
debug_log("Push sweep: HEAD moved while waiting, skipping")
emit_metrics({"skipped": True, "skip_reason": 44, **_base, **_wait_m})
sys.exit(0)
@@ -2555,7 +2781,7 @@ def handle_push_sweep_posttooluse(input_data):
f"{prefix_advanced} base={base[:12]} tail={len(tail)}")
max_files = 10 * MAX_PUSH_SWEEP_FILES
- diff_text = _git_diff_range(repo_root, base, "HEAD",
+ diff_text = _git_diff_range(repo_root, base, tip,
keeper=_review_diff_keeper(max_files))
if diff_text is None:
# Diff failed (non-zero exit / 30s timeout / git missing). Do NOT
@@ -2573,13 +2799,23 @@ def handle_push_sweep_posttooluse(input_data):
diff_files = parse_diff_into_files(diff_text)
for _path, _hunks in diff_files:
_resolved[_path] = _resolved[_path] + "\n" + _hunks if _path in _resolved else _hunks
- diff_files = list(_resolved.items())
+ diff_files, _unread = _with_renamed_in(
+ repo_root, list(_resolved.items()),
+ [(name, ("diff", base, head or "HEAD"), head or "HEAD")
+ for name in renamed_into_review(diff_text)],
+ MAX_PUSH_SWEEP_FILES)
+ if not diff_files and _unread:
+ # As for a failed diff above: there was something to review.
+ emit_metrics({**_base, "pushed": len(push_range),
+ "unreviewed": len(tail), "skip_reason": 45})
+ sys.exit(0)
if not diff_files:
emit_metrics({**_base, "pushed": len(push_range),
"unreviewed": len(tail), "skip_reason": 30,
**_diff_read_metrics()})
# Still mark tail reviewed — there's nothing to review.
_append_reviewed_shas(repo_root, tail, vulns_found=0)
+ _note_settled()
sys.exit(0)
# Same prioritize-don't-bail logic as commit-review (see comment there).
# push-sweep ranges are net diffs over many commits so they hit the cap
@@ -2600,6 +2836,8 @@ def handle_push_sweep_posttooluse(input_data):
if _dropped:
_base = {**_base, "diff_files_dropped": _dropped}
+ if _take_over:
+ _base["commit_no_verdict"] = True
_allowed, _rate_n = atomic_check_rate_limit(
session_id, "PushSweep",
MAX_COMMIT_REVIEWS_PER_HOUR, COMMIT_REVIEW_RATE_WINDOW_S)
@@ -2610,7 +2848,7 @@ def handle_push_sweep_posttooluse(input_data):
_mark_inflight(repo_root, tail)
_diff_token, _seen_m = _diff_review_started(
- repo_root, _cap_files_for_prompt(diff_files))
+ repo_root, _cap_files_for_prompt(diff_files), tip=tip)
_TAIL_METRICS.update(_seen_m)
import time as _time
@@ -2624,7 +2862,7 @@ def handle_push_sweep_posttooluse(input_data):
review_start = _time.time()
rel_touched = [fp for fp, _ in diff_files]
- if _agentic_commit_review_enabled():
+ if _agentic_commit_review_enabled() and not _head_moved:
concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race(
repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s(),
)
@@ -2649,10 +2887,11 @@ def handle_push_sweep_posttooluse(input_data):
_exit_review_failed("Push", session_id, {
**_base, **_wait_m, "pushed": len(push_range), "unreviewed": len(tail),
"files_reviewed": len(diff_files), "review_ms": review_ms,
- }, api_status)
+ }, api_status, told=_note_settled)
# The tail is now covered by this net-diff review.
_append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or []))
+ _note_settled()
_diff_review_done(_diff_token)
new_vulns, n_deduped = _dedup_against_state(
@@ -3231,7 +3470,7 @@ def handle_stop_hook(input_data):
record_reviewed_diff(session_id, diff_hash)
wake = _left_out_wake()
# CC keeps the first 20 metric keys (10 in older versions), in insertion
- # order, after the pv and usage keys emit_metrics puts first. The previous
+ # order, after the keys emit_metrics puts first. The previous
# **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced
# off this most-common path, so the diff-strategy diagnostics never reached
# telemetry. Drop sweep here (it's PostToolUse-warning state, orthogonal to
@@ -3381,8 +3620,8 @@ def main():
#
# 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.
+ # commit-review will not see or gave no verdict on: 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)):
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index f2d5bd8a..74927965 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -3,14 +3,13 @@
#
# On Windows + Git Bash, `python3` typically resolves to the Microsoft Store
# stub at C:\Users\<user>\AppData\Local\Microsoft\WindowsApps\python3, which
-# exits 49 silently in non-TTY subprocess context (a known Microsoft Store
-# stub behavior). This shim
-# probes each candidate with `-c ""` and skips any that fails, so the Store
-# stub falls through to the real python.org install (`python` in Git Bash) or
+# is not a Python; it is told by its link and not started (sg_is_redirector).
+# This shim probes each other candidate with `-c ""` and skips any that fails,
+# so the search reaches the real python.org install (`python` in Git Bash) or
# the `py -3` launcher.
#
# Order:
-# 1. python3 — canonical on macOS/Linux; the Store stub fails the probe.
+# 1. python3 — canonical on macOS/Linux; the Store stub is skipped.
# 2. python — python.org installs on Windows; some Linux distros (RHEL 7
# EOL'd 2024-06) point this at Python 2, but `-c ""` succeeds
# on Python 2 too — guard with a version check.
@@ -117,11 +116,50 @@ note_unreadable() {
return 0
}
+# Where packaged aliases exist (and bash has what telling them apart needs).
+sg_windows=""
+case "${OSTYPE:-}" in
+ msys*|cygwin*) [ "${BASH_VERSINFO[0]:-0}" -lt 4 ] || sg_windows=1 ;;
+esac
+
# True iff the command's executable is on PATH ($1 of a possibly multi-word
# command like `py -3`). A builtin lookup: `$(probe ...)` costs a process even
-# when the interpreter does not exist, so missing names are skipped first.
+# when the interpreter does not exist, so missing names are skipped first. On
+# Windows a python or python3 that is only App Installer's alias counts as
+# missing; that check takes one process, in place of starting the alias.
+sg_skipped=""
on_path() {
- command -v "$1" >/dev/null 2>&1
+ case "$sg_windows:$1" in
+ 1:python|1:python3)
+ hash "$1" 2>/dev/null || return 1
+ if sg_is_redirector "${BASH_CMDS[$1]:-}"; then
+ sg_skipped="${sg_skipped:+$sg_skipped, }$1"
+ return 1
+ fi ;;
+ *) command -v "$1" >/dev/null 2>&1 ;;
+ esac
+}
+
+# True iff $1 is the path of App Installer's python or python3, which Windows
+# puts under ...\Microsoft\WindowsApps when no packaged Python is installed.
+# It is not a Python, it points the user to the Store, so nothing is lost by
+# telling it by where its link leads instead of starting it. Starting it is a
+# packaged app activation on every hook, and waits for Windows' package
+# services: normally a fraction of a second, but until they answer again when
+# they are stuck, in every session on the machine at once. See #3870, #6348.
+# Git Bash shows these aliases as symbolic links; where the link cannot be
+# read, the name is probed like any other. Aliases of a packaged Python are
+# interpreters and are probed too.
+sg_is_redirector() {
+ local to
+ [ -n "$sg_windows" ] && sg_is_alias_path "$1" || return 1
+ # Full path: another readlink on PATH may not know these links.
+ to=$(/usr/bin/readlink -- "$1" 2>/dev/null </dev/null) || return 1
+ # Not lowercased: the result would depend on the locale.
+ case "$to" in
+ *[/\\]Microsoft.DesktopAppInstaller_*) return 0 ;;
+ esac
+ return 1
}
# How long the probes took, for the launcher_probe_max_ms / launcher_probe_ms
@@ -404,7 +442,7 @@ for name in "python3" "python"; do
first=1
while IFS= read -r c; do
if [ -n "$first" ]; then first=""; continue; fi
- [ -n "$c" ] && sg_candidates+=("$c")
+ [ -n "$c" ] && ! sg_is_redirector "$c" && sg_candidates+=("$c")
done <<EOF
$(type -ap "$name" 2>/dev/null)
EOF
@@ -452,6 +490,9 @@ if [ -n "$sg_unreadable" ]; then
fi
echo "security-guidance: no working Python 3 interpreter found." >&2
echo " tried: python3.13 to python3.10, python3, python, py -3, python3.14 to python3.19" >&2
+if [ -n "$sg_skipped" ]; then
+ echo " not started: $sg_skipped (App Installer's alias, which is not a Python)" >&2
+fi
echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2
echo " on macOS, install Python 3.10+ via Homebrew (\`brew install python\`)" >&2
exit 1
diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py
index b0df08de..3987e1de 100644
--- a/plugins/security-guidance/tests/conftest.py
+++ b/plugins/security-guidance/tests/conftest.py
@@ -96,7 +96,11 @@ class _Stub(http.server.BaseHTTPRequestHandler):
self.server.calls.append(self.path)
if self.server.delay:
time.sleep(self.server.delay)
- if self.server.status == 200:
+ status = self.server.status
+ reviews = [c for c in self.server.calls if c.endswith("/v1/messages")]
+ if self.path.endswith("/v1/messages") and len(reviews) <= getattr(self.server, "fail_first", 0):
+ status = 400
+ if status == 200:
vulns = list(self.server.vulns)
body = json.dumps({
"id": "msg_stub", "type": "message", "role": "assistant",
@@ -107,7 +111,7 @@ class _Stub(http.server.BaseHTTPRequestHandler):
}).encode()
else:
body = b'{"type":"error","error":{"type":"invalid_request_error","message":"stub"}}'
- self.send_response(self.server.status)
+ self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
@@ -126,6 +130,7 @@ def stub_api():
srv.bodies = []
srv.status = 200
srv.delay = 0
+ srv.fail_first = 0 # the first N review requests are answered with 400
srv.vulns = []
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
diff --git a/plugins/security-guidance/tests/test_chained_commit_push.py b/plugins/security-guidance/tests/test_chained_commit_push.py
index 8518ed5f..9b105362 100644
--- a/plugins/security-guidance/tests/test_chained_commit_push.py
+++ b/plugins/security-guidance/tests/test_chained_commit_push.py
@@ -4,15 +4,23 @@ 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 contextlib
+import errno
+import json
import os
import subprocess
+import sys
+import time
import pytest
-from conftest import GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook
+from conftest import (
+ GIT_ENV, HOOK_SCRIPT, bash_payload, commit_file, git, make_repo, metrics_of, run_hook,
+)
+import diffstate
import security_reminder_hook as hook
-from diffstate import _append_reviewed_shas
+from diffstate import _append_reviewed_shas, _load_reviewed_shas
CMD = "git add -A && git commit -m new && git push"
@@ -110,3 +118,396 @@ def test_plain_commit_second_start_is_deduped(repo, env):
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
+
+
+# The push spawn waits for the commit spawn, and takes over what it gave no
+# verdict on.
+
+@contextlib.contextmanager
+def _spawn(payload, env):
+ p = subprocess.Popen([sys.executable, str(HOOK_SCRIPT)], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env)
+ try:
+ p.stdin.write(json.dumps(payload))
+ p.stdin.close()
+ p.stdin = None
+ yield p
+ finally:
+ if p.poll() is None:
+ p.kill()
+ p.communicate()
+
+
+def _until(cond, what, timeout=30):
+ end = time.time() + timeout
+ while not cond():
+ assert time.time() < end, f"timed out waiting for {what}"
+ time.sleep(0.05)
+
+
+def _both_spawns(repo, env, out, err, meanwhile=lambda commit: None, command=CMD):
+ """The two spawns of one call, the commit spawn first. Returns the commit
+ spawn's (exit code, metrics, stderr), then the push spawn's."""
+ payload = bash_payload(str(repo), command, stdout=out, stderr=err, tool_use_id="t1")
+ with _spawn(payload, env) as commit:
+ _until(lambda: (repo / ".git" / "sg-hook-once-t1").exists(), "the commit spawn's claim")
+ with _spawn(payload, env) as push:
+ _until(lambda: (repo / ".git" / "sg-hook-once-t1-push").exists(),
+ "the push spawn's claim")
+ meanwhile(commit)
+ ends = []
+ for p in (commit, push):
+ so, se = p.communicate(timeout=90)
+ ends.append((p.returncode, metrics_of(so), se))
+ return ends
+
+
+def _reviews(stub_api):
+ return len([c for c in stub_api.calls if c.endswith("/v1/messages")])
+
+
+def _head(repo):
+ return git(repo, "rev-parse", "HEAD").strip()
+
+
+def test_one_review_while_the_push_spawn_waits(repo, hook_env, stub_api):
+ out, err = _commit_and_push(repo)
+ stub_api.delay = 4
+ commit, push = _both_spawns(repo, hook_env, out, err)
+ assert commit[1]["commit_review"] is True and "skip_reason" not in commit[1]
+ assert push[1]["skip_reason"] == 47 and push[1]["inflight_wait_s"] >= 1
+ assert "commit_no_verdict" not in push[1]
+ assert _reviews(stub_api) == 1
+
+
+def test_failed_commit_review_is_taken_over(repo, hook_env, stub_api):
+ out, err = _commit_and_push(repo)
+ stub_api.fail_first, stub_api.delay = 2, 1 # the review and its retry
+ commit, push = _both_spawns(repo, hook_env, out, err)
+ # The push review reports, so the commit review does not.
+ assert commit[0] == 0 and commit[1]["review_failed"] is True and not commit[2]
+ assert push[1]["commit_no_verdict"] is True and push[1]["unreviewed"] == 1
+ assert "skip_reason" not in push[1] and _reviews(stub_api) == 3
+ assert _head(repo) in _load_reviewed_shas(str(repo))
+
+
+def test_killed_commit_review_is_taken_over(repo, hook_env, stub_api):
+ out, err = _commit_and_push(repo)
+ stub_api.delay = 6
+
+ def kill(commit):
+ _until(lambda: _reviews(stub_api) == 1, "the commit review's request")
+ commit.kill()
+
+ _, push = _both_spawns(repo, hook_env, out, err, kill)
+ assert push[1]["commit_no_verdict"] is True and push[1]["unreviewed"] == 1
+ assert _head(repo) in _load_reviewed_shas(str(repo))
+
+
+def test_take_over_keeps_to_the_commit_review_cap(repo, hook_env, stub_api):
+ hook_env["MAX_COMMIT_REVIEWS_PER_HOUR"] = "1"
+ _, first = commit_file(repo, "first.py", "print('first')\n", "first")
+ run_hook(bash_payload(str(repo), "git commit -m first", first), hook_env)
+ out, err = _commit_and_push(repo)
+ commit, push = _both_spawns(repo, hook_env, out, err)
+ assert commit[1]["skip_reason"] == 23
+ assert push[1]["skip_reason"] == 23
+ assert _reviews(stub_api) == 1
+
+
+def test_commit_without_reviewable_files_sends_nothing(repo, hook_env, stub_api):
+ out, err = _commit_and_push(repo, "notes.png")
+ commit, push = _both_spawns(repo, hook_env, out, err)
+ assert commit[1]["skip_reason"] == 30 and push[1]["skip_reason"] == 30
+ assert _reviews(stub_api) == 0
+
+
+def test_message_only_amend_is_not_reviewed_again(repo, hook_env, stub_api):
+ _, made = commit_file(repo, "a.py", "print('a')\n", "a")
+ run_hook(bash_payload(str(repo), "git commit -m a", made), hook_env)
+ out, err = _run(repo, "commit", "--amend", "-m", "better")
+ pout, perr = _run(repo, "push")
+ commit, push = _both_spawns(repo, hook_env, out + pout, err + perr,
+ command="git commit --amend -m better && git push")
+ assert commit[1]["skip_reason"] == 35 and push[1]["skip_reason"] == 47
+ assert _reviews(stub_api) == 1
+
+
+def test_nothing_is_held_where_files_cannot_be_locked(repo, monkeypatch):
+ def no_locks(fd, exclusive):
+ raise OSError(errno.ENOLCK, "no locks here")
+
+ path = str(repo / ".git" / "sg-hook-once-t1")
+ open(path, "w").close()
+ monkeypatch.setattr(diffstate, "_flock_nb", no_locks)
+ for p in (path, path + "-missing", None):
+ diffstate.hold_until_exit(p)
+ assert diffstate.is_held(p) is None
+ assert diffstate.wait_for_holder(p, 5) == (False, 0.0)
+ assert diffstate.becomes_held(p, 0) is False
+
+
+def test_wait_for_holder_stops_at_the_limit(tmp_path):
+ path = tmp_path / "held"
+ path.write_text("")
+ script = ("import sys, time\nsys.path.insert(0, sys.argv[2])\nimport diffstate\n"
+ "diffstate.hold_until_exit(sys.argv[1])\n"
+ "print('held', flush=True)\ntime.sleep(60)\n")
+ p = subprocess.Popen([sys.executable, "-c", script, str(path), os.path.dirname(diffstate.__file__)],
+ stdout=subprocess.PIPE, text=True)
+ try:
+ assert p.stdout.readline().strip() == "held"
+ ended, waited = diffstate.wait_for_holder(str(path), 1)
+ assert ended is False and waited >= 1
+ assert diffstate.is_held(str(path)) is True
+ p.kill()
+ p.wait()
+ assert diffstate.wait_for_holder(str(path), 20) == (True, 0.0)
+ finally:
+ p.kill()
+ p.communicate()
+
+
+def test_both_reviews_pick_the_same_commits(repo):
+ """The output names a commit but has no diffstat: both go by the reflog."""
+ (repo / "quiet.py").write_text("print('quiet')\n")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "-m", "quiet")
+ out, err = _run(repo, "commit", "--allow-empty", "-m", "marker")
+ pout, perr = _run(repo, "push")
+ output = out + pout + err + perr
+ assert hook._COMMIT_SHA_RE.findall(output) and not hook._commit_in_output(output)
+ both = git(repo, "rev-list", "@{u}@{1}..HEAD").split()
+ assert hook._commit_review_candidates(output, str(repo))[0][:2] == both
+ assert not _beyond(repo, output)
+
+
+def test_quiet_commit_then_empty_commit_runs_one_review(repo, hook_env, stub_api):
+ (repo / "quiet.py").write_text("print('quiet')\n")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "-m", "quiet")
+ out, err = _run(repo, "commit", "--allow-empty", "-m", "marker")
+ pout, perr = _run(repo, "push")
+ stub_api.delay = 2
+ commit, push = _both_spawns(
+ repo, hook_env, out + pout, err + perr,
+ command="git commit -q -m quiet && git commit --allow-empty -m marker && git push")
+ assert commit[1]["sha_via_reflog"] is True and push[1]["skip_reason"] == 47
+ assert _reviews(stub_api) == 1
+
+
+def test_slow_commit_review_is_left_alone(repo, hook_env, stub_api):
+ """It outlasts the wait: skipped as before, not reviewed twice."""
+ out, err = _commit_and_push(repo)
+ stub_api.delay = 4
+ commit, push = _both_spawns(repo, {**hook_env, "SG_INFLIGHT_WAIT_S": "1"}, out, err)
+ assert "skip_reason" not in commit[1] and push[1]["skip_reason"] == 47
+ assert "commit_no_verdict" not in push[1]
+ assert _reviews(stub_api) == 1
+
+
+def test_take_over_after_head_moved(repo, hook_env, stub_api):
+ """Another commit landed meanwhile: still reviewed, as it was pushed."""
+ out, err = _commit_and_push(repo)
+ pushed = _head(repo)
+ stub_api.fail_first, stub_api.delay = 2, 2
+
+ def move_head(commit):
+ _until(lambda: diffstate.is_held(str(repo / ".git" / "sg-hook-once-t1-push")),
+ "the push spawn's wait")
+ commit_file(repo, "later.py", "print('later')\n", "later")
+
+ _, push = _both_spawns(repo, hook_env, out, err, move_head)
+ assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1]
+ assert "new.py" in stub_api.bodies[-1] and "later.py" not in stub_api.bodies[-1]
+ assert _load_reviewed_shas(str(repo)) == {pushed}
+
+
+def test_no_promise_of_a_push_review_that_ended(repo, hook_env, stub_api):
+ """Two branches pushed: that push review skips, and nothing takes over."""
+ git(repo, "branch", "side")
+ git(repo, "push", "-q", "origin", "side")
+ git(repo, "checkout", "-q", "side")
+ commit_file(repo, "side.py", "print('side')\n", "side")
+ git(repo, "checkout", "-q", "main")
+ (repo / "new.py").write_text("print('new')\n")
+ git(repo, "add", "-A")
+ out, err = _run(repo, "commit", "-m", "new")
+ pout, perr = _run(repo, "push", "--all", "origin")
+ stub_api.fail_first, stub_api.delay = 2, 2
+ commit, push = _both_spawns(repo, hook_env, out + pout, err + perr,
+ command="git commit -m new && git push --all origin")
+ assert push[1]["skip_reason"] == 44 and commit[1]["review_failed"] is True
+ assert "a later push will not re-check it" in commit[2]
+
+
+def test_message_only_amend_while_the_original_is_under_review(repo, hook_env, stub_api):
+ _, made = commit_file(repo, "a.py", "print('a')\n", "a")
+ stub_api.delay = 5
+ with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env):
+ _until(lambda: _reviews(stub_api) == 1, "the original's review")
+ out, err = _run(repo, "commit", "--amend", "-m", "better")
+ pout, perr = _run(repo, "push")
+ commit, push = _both_spawns(repo, hook_env, out + pout, err + perr,
+ command="git commit --amend -m better && git push")
+ assert commit[1]["skip_reason"] == 35 and push[1]["skip_reason"] == 47
+ assert _reviews(stub_api) == 1
+
+
+def test_failed_review_at_the_cap_still_reports(repo, hook_env, stub_api):
+ """The cap leaves the push review no turn, so the commit review reports."""
+ out, err = _commit_and_push(repo)
+ stub_api.fail_first, stub_api.delay = 2, 1
+ commit, push = _both_spawns(repo, {**hook_env, "MAX_COMMIT_REVIEWS_PER_HOUR": "1"}, out, err)
+ assert commit[0] == 2 and "a later push will not re-check it" in commit[2]
+ assert push[1]["skip_reason"] == 23
+
+
+def test_both_reviews_fail(repo, hook_env, stub_api):
+ out, err = _commit_and_push(repo)
+ stub_api.status = 400
+ commit, push = _both_spawns(repo, hook_env, out, err)
+ assert commit[0] == 0 and commit[1]["review_failed"] is True
+ assert push[0] == 2 and "a later push will not re-check them" in push[2]
+
+
+def test_older_commit_under_another_review_is_left_to_it(repo, hook_env, stub_api):
+ _, made = commit_file(repo, "older.py", "print('older')\n", "older")
+ stub_api.delay = 4
+ with _spawn(bash_payload(str(repo), "git commit -m older", made), hook_env) as older:
+ _until(lambda: _reviews(stub_api) == 1, "the older commit's review")
+ out, err = _commit_and_push(repo)
+ commit, push = _both_spawns(repo, hook_env, out, err)
+ older.communicate(timeout=60)
+ assert push[1]["skip_reason"] == 47
+ assert _reviews(stub_api) == 2
+
+
+@pytest.mark.parametrize("chained", [False, True])
+def test_message_only_amend_of_a_commit_whose_review_fails(repo, hook_env, stub_api, chained):
+ """The amended commit is not recorded on the word of a review that then
+ gives no verdict: the push review covers it."""
+ _, made = commit_file(repo, "a.py", "print('a')\n", "a")
+ stub_api.delay, stub_api.fail_first = 5, 2
+ amend = "git commit --amend -m better"
+ with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env) as orig:
+ _until(lambda: _reviews(stub_api) == 1, "the original's review")
+ out, err = _run(repo, "commit", "--amend", "-m", "better")
+ if chained:
+ pout, perr = _run(repo, "push")
+ _, (_, push, _) = _both_spawns(repo, hook_env, out + pout, err + perr,
+ command=amend + " && git push")
+ else:
+ run_hook(bash_payload(str(repo), amend, out, stderr=err, tool_use_id="t2"), hook_env)
+ pout, perr = _run(repo, "push")
+ push = metrics_of(run_hook(bash_payload(
+ str(repo), "git push", pout, stderr=perr, tool_use_id="t3"), hook_env)[1])
+ orig.communicate(timeout=60)
+ assert "skip_reason" not in push and push["unreviewed"] == 1
+ assert _reviews(stub_api) == 3 # the review, its retry, the push review
+ assert _head(repo) in _load_reviewed_shas(str(repo))
+
+
+def _push_only(repo, env, tool_use_id, name):
+ commit_file(repo, name, "print('outside')\n", name)
+ out, err = _run(repo, "push")
+ return run_hook(bash_payload(str(repo), "git push", out, stderr=err,
+ tool_use_id=tool_use_id), env)
+
+
+def test_failure_is_told_when_the_push_review_is_at_its_cap(repo, hook_env, stub_api):
+ hook_env["MAX_COMMIT_REVIEWS_PER_HOUR"] = "2"
+ for n in ("p1", "p2"):
+ assert "skip_reason" not in metrics_of(_push_only(repo, hook_env, n, n + ".py")[1])
+ out, err = _commit_and_push(repo)
+ stub_api.status, stub_api.delay = 400, 1
+ commit, push = _both_spawns(repo, hook_env, out, err)
+ assert push[1]["skip_reason"] == 23 and not push[2]
+ assert commit[0] == 2 and "a later push will not re-check it" in commit[2]
+
+
+def test_failure_is_told_when_the_push_review_told_of_one_before(repo, hook_env, stub_api):
+ stub_api.status = 400
+ assert "did not complete" in _push_only(repo, hook_env, "p1", "p1.py")[2]
+ out, err = _commit_and_push(repo)
+ commit, push = _both_spawns(repo, hook_env, out, err)
+ assert push[0] == 0 and push[1]["review_failed"] is True
+ assert commit[0] == 2 and "a later push will not re-check it" in commit[2]
+
+
+def test_failure_is_told_when_the_push_review_is_killed(repo, hook_env, stub_api):
+ out, err = _commit_and_push(repo)
+ payload = bash_payload(str(repo), CMD, stdout=out, stderr=err, tool_use_id="t1")
+ stub_api.fail_first, stub_api.delay = 2, 4
+ with _spawn(payload, hook_env) as commit:
+ _until(lambda: (repo / ".git" / "sg-hook-once-t1").exists(), "the commit spawn's claim")
+ with _spawn(payload, hook_env) as push:
+ _until(lambda: _reviews(stub_api) == 3, "the push review's request")
+ push.kill()
+ _, told = commit.communicate(timeout=60)
+ assert commit.returncode == 2 and "a later push will not re-check it" in told
+
+
+def test_other_commits_of_the_command_do_not_bring_a_failure_notice(repo, hook_env, stub_api):
+ """Only what was pushed is for the push review: the commit that was then
+ amended is not, and the review of the rest succeeded."""
+ (repo / "new.py").write_text("print('new')\n")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "-m", "wip")
+ git(repo, "commit", "-q", "--amend", "-m", "done")
+ out, err = _run(repo, "push")
+ stub_api.fail_first, stub_api.delay = 2, 1
+ commit, push = _both_spawns(
+ repo, hook_env, out, err,
+ command="git commit -q -m wip && git commit -q --amend -m done && git push")
+ assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1]
+ assert commit[0] == 0 and not commit[2]
+
+
+def test_separate_push_waits_for_a_message_only_amend(repo, hook_env, stub_api):
+ _, made = commit_file(repo, "a.py", "print('a')\n", "a")
+ stub_api.delay = 6
+ amend = "git commit --amend -m better"
+ with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env):
+ _until(lambda: _reviews(stub_api) == 1, "the original's review")
+ out, err = _run(repo, "commit", "--amend", "-m", "better")
+ with _spawn(bash_payload(str(repo), amend, out, stderr=err, tool_use_id="t2"), hook_env) as p:
+ marker = repo / ".git" / ("sg-inflight-" + _head(repo))
+ _until(lambda: diffstate.is_held(str(marker)), "the amend's claim")
+ pout, perr = _run(repo, "push")
+ push = metrics_of(run_hook(bash_payload(
+ str(repo), "git push", pout, stderr=perr, tool_use_id="t3"), hook_env)[1])
+ p.communicate(timeout=60)
+ assert push["unreviewed"] == 0 and push["inflight_wait_s"] >= 1
+ assert _reviews(stub_api) == 1
+
+
+def test_amend_waits_less_than_its_push_review(repo, hook_env, stub_api):
+ """The original outlasts both waits: the push review still gets its turn."""
+ _, made = commit_file(repo, "a.py", "print('a')\n", "a")
+ stub_api.delay = 25
+ env = {**hook_env, "SG_INFLIGHT_WAIT_S": "15"}
+ with _spawn(bash_payload(str(repo), "git commit -m a", made), hook_env):
+ _until(lambda: _reviews(stub_api) == 1, "the original's review")
+ out, err = _run(repo, "commit", "--amend", "-m", "better")
+ pout, perr = _run(repo, "push")
+ commit, push = _both_spawns(repo, env, out + pout, err + perr,
+ command="git commit --amend -m better && git push")
+ assert commit[1]["skip_reason"] == 35 and commit[1]["inflight_wait_s"] >= 1
+ assert push[1]["commit_no_verdict"] is True and "skip_reason" not in push[1]
+
+
+def test_failure_of_a_commit_elsewhere_is_told(repo, hook_env, stub_api, tmp_path):
+ """The push is of another repository, whose commits are all reviewed."""
+ _, made = commit_file(repo, "a.py", "print('a')\n", "a")
+ run_hook(bash_payload(str(repo), "git commit -m a", made), hook_env)
+ lib = make_repo(tmp_path / "lib")
+ (lib / "x.py").write_text("print('x')\n")
+ git(lib, "add", "-A")
+ out, err = _run(lib, "commit", "-m", "x")
+ pout, perr = _run(repo, "push")
+ stub_api.status, stub_api.delay = 400, 1
+ commit, _ = _both_spawns(
+ repo, hook_env, out + pout, err + perr,
+ command=f"git -C {lib} commit -m x && git push")
+ assert commit[0] == 2 and "did not complete" in commit[2]
diff --git a/plugins/security-guidance/tests/test_custom_rule_brace_globs.py b/plugins/security-guidance/tests/test_custom_rule_brace_globs.py
new file mode 100644
index 00000000..6cef5689
--- /dev/null
+++ b/plugins/security-guidance/tests/test_custom_rule_brace_globs.py
@@ -0,0 +1,187 @@
+"""`{a,b}` in a custom rule's glob means either."""
+import fnmatch
+import itertools
+import time
+
+import pytest
+
+import extensibility
+
+from test_custom_rule_path_globs import _hits, _module_state, _rule # noqa: F401
+
+CASES = [
+ # glob, file inside the project, applies
+ ("*.{ts,tsx}", "src/a.ts", True),
+ ("*.{ts,tsx}", "src/lib/a.tsx", True),
+ ("*.{ts,tsx}", "src/a.js", False),
+ ("*.{ts,tsx}", "src/a.ts.bak", False),
+ ("**/*.{ts,tsx}", "config.ts", True),
+ ("**/*.{ts,tsx}", "src/lib/a.tsx", True),
+ ("**/*.{ts,tsx}", "src/a.py", False),
+ ("{src,lib}/**", "src/x/a.py", True),
+ ("{src,lib}/**", "lib/a.py", True),
+ ("{src,lib}/**", "other/a.py", False),
+ ("src/{a,b}/**/*.{ts,js}", "src/b/a.js", True),
+ ("src/{a,b}/**/*.{ts,js}", "src/c/a.js", False),
+ ("./{src,lib}/*.ts", "lib/a.ts", True),
+ ("*.{ts,{m,c}ts}", "a.mts", True),
+ ("*.{ts,{m,c}ts}", "a.xts", False),
+ ("*.{test,spec}.ts", "src/a.spec.ts", True),
+ ("*.{ts, tsx}", "a.tsx", True),
+ # An empty option before `/` does not turn the glob into "every file".
+ ("{src,}/**", "src/a.ts", True),
+ ("{src,}/**", "lib/a.ts", False),
+ ("{,src}/*.ts", "lib/a.ts", False),
+ ("{{,x},src}{,y}/**", "lib/a.ts", False),
+ # More combinations than anyone counts.
+ ("{src,lib,app,packages}/**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts,vue}", "app/x/a.vue", True),
+ ("config{,.local}.ts", "config.ts", True),
+ ("config{,.local}.ts", "config.local.ts", True),
+ # A set keeps its braces, and one option is not a choice.
+ ("[{,}].ts", "{.ts", True),
+ ("[{,}].ts", "ts", False),
+ ("a{b}.ts", "a{b}.ts", True),
+ ("a{b}.ts", "ab.ts", False),
+ ("*.{ts,tsx", "a.ts", False),
+ # An option with no folder in it is about the file name.
+ ("{test*,src/**}", "tests/x/a.py", False),
+ ("{test*,src/**}", "x/test_a.py", True),
+ ("{test*,src/**}", "src/a.py", True),
+]
+
+
+@pytest.fixture(autouse=True)
+def _fresh_forms(monkeypatch):
+ monkeypatch.setattr(extensibility, "_forms_cache", {})
+ monkeypatch.setattr(extensibility, "_brace_forms_left", extensibility._BRACE_BUDGET)
+
+
+@pytest.mark.parametrize("glob,rel,applies", CASES)
+def test_braces_in_paths(glob, rel, applies, tmp_path, monkeypatch):
+ project = _rule(tmp_path, monkeypatch, include=[glob])
+ assert bool(_hits(project, rel)) is applies
+
+
+@pytest.mark.parametrize("glob,rel,applies", CASES)
+def test_braces_in_exclude_paths(glob, rel, applies, tmp_path, monkeypatch):
+ project = _rule(tmp_path, monkeypatch, exclude=[glob])
+ assert bool(_hits(project, rel)) is not applies
+
+
+def test_an_exclude_silences_only_its_own_rule(tmp_path, monkeypatch):
+ project = _rule(tmp_path, monkeypatch, exclude=["*.{js,ts}"])
+ extensibility.load_for_session(str(project))
+ import security_reminder_hook as hook
+ hits = [r for r, _ in hook.check_patterns(str(project / "a.js"), "NEEDLE(eval(x))\n")]
+ assert "eval_injection" in hits and "user:r" not in hits
+
+
+@pytest.mark.parametrize("glob", ["{a,b}.ts", "*.{ts,tsx}", "x{,y}", "{a,{b,c}}"])
+def test_a_name_with_the_braces_in_it_still_matches(glob):
+ name = glob.replace("*", "z")
+ assert extensibility._wider_glob_match("/p/" + name, (), (glob,), ())
+
+
+@pytest.mark.parametrize("glob,forms", [
+ ("*.ts", {"*.ts"}),
+ ("{a,b}", {"{a,b}", "a", "b"}),
+ ("{{a,b}}", {"{{a,b}}", "{a}", "{b}"}),
+ ("{a,b}{c,d}", {"{a,b}{c,d}", "ac", "ad", "bc", "bd"}),
+ ("{a,}", {"{a,}", "a"}),
+ ("{a,}/b", {"{a,}/b", "a/b"}),
+ ("{/a,/b}/c", {"{/a,/b}/c", "/a/c", "/b/c"}),
+ ("x/{a,}/b", {"x/{a,}/b", "x/a/b", "x//b"}),
+ ("{,}", {"{,}"}),
+ ("a}{b,c}", {"a}{b,c}", "a}b", "a}c"}),
+ ("{x{a,b}", {"{x{a,b}", "{xa", "{xb"}),
+ ("[{a,b]{c,d}", {"[{a,b]{c,d}", "[{a,b]c", "[{a,b]d"}),
+ ("[!]{]{c,d}", {"[!]{]{c,d}", "[!]{]c", "[!]{]d"}),
+ ("[{a,b}", {"[{a,b}", "[a", "[b"}),
+ ("", {""}),
+])
+def test_forms(glob, forms):
+ assert set(extensibility._brace_forms(glob)) == forms
+
+
+def test_up_to_the_cap_is_expanded_and_over_it_is_not():
+ cap = extensibility._MAX_BRACE_FORMS
+ at = "{" + ",".join(map(str, range(cap))) + "}"
+ assert len(extensibility._brace_forms(at)) == cap + 1
+ assert extensibility._brace_forms(at[:-1] + ",x}") is None
+
+
+def _over_cap():
+ return "src/*.{" + ",".join(f"e{i}" for i in range(extensibility._MAX_BRACE_FORMS)) + ",ts}"
+
+
+def test_an_over_cap_glob_is_read_as_written_and_the_log_names_the_rule(tmp_path, monkeypatch):
+ log = []
+ monkeypatch.setattr(extensibility, "debug_log", log.append)
+ project = _rule(tmp_path, monkeypatch, include=[_over_cap(), "lib/*.{ts,js}"])
+ assert not _hits(project, "src/a.ts")
+ assert _hits(project, "lib/a.ts")
+ assert [m for m in log if "too many combinations" in m and " r:" in m]
+
+
+def test_the_budget_is_shared_by_all_rules_and_starts_again_each_load(tmp_path, monkeypatch):
+ monkeypatch.setattr(extensibility, "_BRACE_BUDGET", 5)
+ project = _rule(tmp_path, monkeypatch, include=["a.{ts,js}", "b.{ts,js}"])
+ for _ in range(2):
+ assert _hits(project, "a.ts")
+ assert not _hits(project, "b.ts")
+
+
+def test_plain_globs_need_no_budget(tmp_path, monkeypatch):
+ monkeypatch.setattr(extensibility, "_BRACE_BUDGET", 0)
+ project = _rule(tmp_path, monkeypatch, include=["src/**/*.ts", "a{b}.py"])
+ assert _hits(project, "src/a.ts") and _hits(project, "a{b}.py")
+
+
+@pytest.mark.parametrize("glob", [
+ "{a,b}" * 200,
+ "{" * 20000 + "a,b" + "}" * 20000,
+ "{a," * 20000,
+ "[" * 20000 + "{a,b}",
+ "[{" * 10000 + "]" + "{a,b}" * 20,
+ "{" + "a," * 50000 + "}",
+])
+def test_a_hostile_glob_is_quick(glob):
+ started = time.perf_counter()
+ extensibility._brace_forms(glob)
+ assert time.perf_counter() - started < 5
+
+
+@pytest.mark.parametrize("glob", [
+ "**/r/**/x/**/y/**/z{a,b}{c,d}{e,f}{g,h}{i,j}/**",
+ "*{*a,*b}*{*c,*d}*{*e,*f}*{*g,*h}*",
+])
+def test_a_project_full_of_hostile_rules_is_bounded(glob):
+ """Whole matching cost, no literal end to help, 500 different globs."""
+ globs = tuple(f"{i}{glob}" for i in range(500))
+ plain = tuple(g.replace("{", "(").replace("}", ")") for g in globs)
+ started = time.perf_counter()
+ sizes = [len(extensibility._glob_forms(g)) - len(extensibility._glob_forms(p))
+ for g, p in zip(globs, plain)]
+ assert 0 < sum(sizes) <= extensibility._BRACE_BUDGET
+ assert not extensibility._wider_glob_match("/p/src/lib/a.ts", ("src/lib/a.ts",), globs, ())
+ assert time.perf_counter() - started < 20
+
+
+def test_many_globs_that_do_not_fit_are_given_up_on_quickly():
+ started = time.perf_counter()
+ for i in range(5000):
+ extensibility._glob_forms(f"{i}" + "{a,b}" * 190)
+ assert time.perf_counter() - started < 10
+
+
+def _matches(name, glob):
+ """One glob against one file name, through the plugin's matcher."""
+ return any(name.endswith(tail) and fnmatch.fnmatchcase(name, form)
+ for form, tail, _ in extensibility._glob_forms(glob) if form == glob)
+
+
+def test_the_quick_check_agrees_with_fnmatch():
+ globs = ["".join(g) for n in range(5) for g in itertools.product("a*?[]!", repeat=n)]
+ for glob in globs:
+ for name in ("", "a", "aa", "ab", "a-b", "a]", "]", "[a", "!", "a!"):
+ assert _matches(name, glob) == fnmatch.fnmatchcase(name, glob), (name, glob)
diff --git a/plugins/security-guidance/tests/test_custom_rule_stats.py b/plugins/security-guidance/tests/test_custom_rule_stats.py
index 41bf9141..f0d0f86e 100644
--- a/plugins/security-guidance/tests/test_custom_rule_stats.py
+++ b/plugins/security-guidance/tests/test_custom_rule_stats.py
@@ -43,7 +43,8 @@ def test_the_wider_reading_never_loses_an_include(glob, tmp_path):
("/src/**", "src/a.ts", False, True),
("*.ts", "src/lib/deep/t.ts", True, True),
("src/**", "other/a.ts", False, False),
- ("*.{ts,js}", "config.ts", False, False),
+ ("*.{ts,js}", "config.ts", False, True),
+ ("*.{ts,js}", "config.py", False, False),
])
def test_readings(glob, f, now, wider, tmp_path):
path = str(tmp_path.joinpath(*f.split("/")))
diff --git a/plugins/security-guidance/tests/test_launcher_redirector.py b/plugins/security-guidance/tests/test_launcher_redirector.py
new file mode 100644
index 00000000..26800a72
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_redirector.py
@@ -0,0 +1,215 @@
+"""sg-python.sh does not start the python/python3 that App Installer provides.
+
+On Windows without a packaged Python, `python3` under ...\\Microsoft\\WindowsApps
+is a link to AppInstallerPythonRedirector.exe, which is not a Python. Starting
+it on every hook makes the hook wait for Windows' package services, and hang
+while they do not answer. See #3870, #6348.
+
+Aliases are shell scripts behind a symbolic link, so these tests need a POSIX
+shell; the launcher's Windows branch is switched on with OSTYPE.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR
+
+SHIM = HOOKS_DIR / "sg-python.sh"
+BASH = shutil.which("bash") or "/bin/bash"
+REAL = os.path.realpath(sys.executable)
+try:
+ BASH_MAJOR = int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True,
+ text=True, timeout=30).stdout.strip() or 0)
+except (OSError, ValueError, subprocess.SubprocessError):
+ BASH_MAJOR = 0
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+needs_bash4 = pytest.mark.skipif(BASH_MAJOR < 4, reason="the Windows branch needs bash 4")
+
+HOOK = "import os, sys\nprint('name=' + os.environ.get('SG_NAME', ''))\nprint('stdin=' + sys.stdin.read())\n"
+
+
+class Box:
+ def __init__(self, root):
+ self.apps = root / "AppData" / "Local" / "Microsoft" / "WindowsApps"
+ self.pkg = root / "Program Files" / "WindowsApps" / "Microsoft.DesktopAppInstaller_1.29.379.0_x64__8wekyb3d8bbwe"
+ self.bin = root / "bin"
+ self.late = root / "late"
+ self.log = root / "log"
+ for d in (self.apps, self.pkg, self.bin, self.late):
+ d.mkdir(parents=True)
+ self.log.write_text("")
+ self.script = root / "hook.py"
+ self.script.write_text(HOOK)
+ # Names the launcher tries that this machine may really have.
+ for name in ("python3.13", "python3.12", "python3.11", "python3.10", "python3.14", "py"):
+ self.broken(self.bin / name)
+
+ def write(self, path, text):
+ path.write_text(text)
+ path.chmod(0o755)
+
+ def broken(self, path):
+ self.write(path, f"#!{BASH}\nexit 49\n")
+
+ def python(self, path):
+ self.write(path, f"#!{BASH}\necho {path.name} >> '{self.log}'\nSG_NAME={path.name} exec '{REAL}' \"$@\"\n")
+
+ def alias(self, name, target="AppInstallerPythonRedirector.exe", hangs=False):
+ """An entry under WindowsApps that leads to `target`, and logs its starts."""
+ exe = self.pkg / target
+ body = "sleep 300" if hangs else "exit 49"
+ self.write(exe, f"#!{BASH}\necho redirector >> '{self.log}'\n{body}\n")
+ (self.apps / name).symlink_to(exe)
+
+ def path(self, *first):
+ return os.pathsep.join([*(str(p) for p in first), str(self.bin), "/usr/bin", "/bin"])
+
+ def run(self, path, ostype="msys", timeout=60):
+ env = {"PATH": path, "HOME": os.environ.get("HOME", "/"), "OSTYPE": ostype,
+ "SECURITY_WARNINGS_STATE_DIR": str(self.log.parent / "state")}
+ return subprocess.run([BASH, str(SHIM), str(self.script)], input="payload", capture_output=True,
+ text=True, timeout=timeout, env=env)
+
+ @property
+ def starts(self):
+ return self.log.read_text().split()
+
+
+def _tools(box):
+ """A PATH entry with readlink and no Python of the machine's own."""
+ d = box.log.parent / "tools"
+ d.mkdir(exist_ok=True)
+ for name in ("readlink", "sleep"):
+ if not (d / name).exists():
+ (d / name).symlink_to(shutil.which(name))
+ return str(d)
+
+
+@pytest.fixture
+def box(tmp_path):
+ return Box(tmp_path)
+
+
+@needs_bash4
+def test_redirector_is_not_started(box):
+ box.alias("python3")
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.apps))
+ assert r.returncode == 0, r.stderr
+ assert r.stdout.splitlines() == ["name=python", "stdin=payload"]
+ assert "redirector" not in box.starts
+
+
+@needs_bash4
+def test_redirector_that_never_answers_does_not_hold_the_hook(box):
+ box.alias("python3", hangs=True)
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.apps), timeout=30)
+ assert r.returncode == 0 and "name=python" in r.stdout
+
+
+@needs_bash4
+def test_both_names_lead_to_the_redirector(box):
+ # python and python3 both first on PATH as redirectors, a real python
+ # further down: found by its full path, as before.
+ box.alias("python3")
+ box.alias("python")
+ box.python(box.late / "python")
+ r = box.run(os.pathsep.join([str(box.apps), str(box.late), str(box.bin), "/nowhere"])
+ + os.pathsep + _tools(box))
+ assert r.returncode == 0, r.stderr
+ assert "name=python" in r.stdout
+ assert "redirector" not in box.starts
+
+
+@needs_bash4
+def test_only_redirectors_is_reported_as_no_python(box):
+ box.alias("python3")
+ box.alias("python")
+ r = box.run(os.pathsep.join([str(box.apps), str(box.bin), _tools(box)]))
+ assert r.returncode == 1
+ assert "no working Python 3 interpreter found" in r.stderr
+ assert "not started: python3, python (App Installer's alias" in r.stderr
+ assert box.starts == []
+
+
+@needs_bash4
+@pytest.mark.parametrize("ostype", ["msys", "cygwin"])
+def test_redirector_behind_a_broken_python_is_not_started(box, ostype):
+ # Pass 4 collects every further python3 on PATH by its full path.
+ box.alias("python3")
+ box.broken(box.bin / "python3")
+ box.broken(box.bin / "python")
+ r = box.run(os.pathsep.join([str(box.bin), str(box.apps), _tools(box)]), ostype=ostype)
+ assert r.returncode == 1
+ assert box.starts == []
+
+
+@needs_bash4
+def test_link_outside_windowsapps_is_not_looked_at(box):
+ # Only aliases are told by their link; any other python3 is asked.
+ box.alias("python3")
+ (box.apps / "python3").rename(box.late / "python3")
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.late))
+ assert r.returncode == 0 and "name=python" in r.stdout
+ assert "redirector" in box.starts
+
+
+@needs_bash4
+def test_readlink_on_path_is_not_relied_on(box):
+ box.alias("python3")
+ box.python(box.bin / "python")
+ box.broken(box.bin / "readlink")
+ r = box.run(box.path(box.apps))
+ assert r.returncode == 0 and "redirector" not in box.starts
+
+
+
+@needs_bash4
+def test_packaged_python_alias_is_still_used(box):
+ # An alias of a packaged Python leads to that Python, not to the redirector.
+ pkg = box.pkg.parent / "PythonSoftwareFoundation.Python.3.12_3.12.2800.0_x64__qbz5n2kfra8p0"
+ pkg.mkdir()
+ box.python(pkg / "python3.12.exe")
+ (box.apps / "python3").symlink_to(pkg / "python3.12.exe")
+ box.broken(box.bin / "python")
+ r = box.run(box.path(box.apps))
+ assert r.returncode == 0, r.stderr
+ assert "stdin=payload" in r.stdout
+ assert "python3.12.exe" in box.starts
+
+
+@needs_bash4
+def test_unreadable_link_is_probed_as_before(box):
+ # Not a link at all (or readlink missing): the name is started and fails.
+ box.write(box.apps / "python3", f"#!{BASH}\necho redirector >> '{box.log}'\nexit 49\n")
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.apps))
+ assert r.returncode == 0 and "name=python" in r.stdout
+ assert "redirector" in box.starts
+
+
+def test_other_systems_do_not_look_at_links(box):
+ box.alias("python3")
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.apps), ostype="linux-gnu")
+ assert r.returncode == 0 and "name=python" in r.stdout
+ assert "redirector" in box.starts
+
+
+def test_edit_hook_has_a_time_limit():
+ """The edit hook holds the tool call; without a limit of its own a stuck
+ one holds it for the host's 600 s default. See #6348."""
+ groups = json.loads((HOOKS_DIR / "hooks.json").read_text())["hooks"]["PostToolUse"]
+ (edit,) = [g for g in groups if "Edit" in g["matcher"]]
+ assert [h.get("timeout") for h in edit["hooks"]] == [60]
+ # The background reviews keep the host's limit: they run past a minute.
+ for g in groups:
+ if g is not edit:
+ assert all("timeout" not in h for h in g["hooks"])
diff --git a/plugins/security-guidance/tests/test_line_continuation.py b/plugins/security-guidance/tests/test_line_continuation.py
new file mode 100644
index 00000000..794fa789
--- /dev/null
+++ b/plugins/security-guidance/tests/test_line_continuation.py
@@ -0,0 +1,81 @@
+"""A git command continued on the next line is still a commit or a push."""
+import time
+
+import pytest
+
+from conftest import bash_payload, commit_file, git, make_repo, metrics_of, run_hook
+
+import security_reminder_hook as hook
+from diffstate import _load_reviewed_shas
+
+
+@pytest.mark.parametrize("command", [
+ "git \\\n commit -m x",
+ "git \\\r\n commit -m x",
+ "git `\r\n commit -m x",
+ "git -C \\\n . commit",
+ "git \\\n -c user.name='A B' \\\n --no-pager \\\n commit -m x",
+ "git --git-dir \\\n .git commit",
+ "gt \\\n create x",
+ "# kept in C:\\temp\\\ngit commit -m x",
+ "git commit \\\n -m x",
+])
+def test_is_a_commit(command):
+ assert hook._GIT_COMMIT_RE.search(command)
+
+
+@pytest.mark.parametrize("command", [
+ "git \\\n push origin main", "git -C x `\n push", "gt \\\n submit", "echo a\\\ngit push",
+])
+def test_is_a_push(command):
+ assert hook._GIT_PUSH_RE.search(command)
+
+
+@pytest.mark.parametrize("command", [
+ "git log \\\n commit", "git \\ commit", "git \\\n --help commit", "git \\\n commit-graph write",
+ "git log `date`\ncommit", "legit\\\ncommit",
+])
+def test_is_neither(command):
+ assert not hook._GIT_COMMIT_RE.search(command)
+ assert not hook._GIT_PUSH_RE.search(command)
+
+
+def test_continued_gt_modify_is_an_amend():
+ assert hook._GIT_AMEND_RE.search("gt \\\n modify -m x")
+
+
+def test_long_command_is_matched_quickly():
+ for part in (" \\\n", " -c \\\n", " -c a=b \\\n", " --x \\\n", "\\\n", " `\n-p"):
+ start = time.monotonic()
+ hook._GIT_COMMIT_RE.search("git" + part * 3000 + " x")
+ assert time.monotonic() - start < 2
+
+
+@pytest.mark.parametrize("tool, command", [
+ ("Bash", "git \\\n commit -m change"),
+ ("Bash", "git -c core.abbrev=12 \\\n commit -m change"),
+ ("PowerShell", "git `\n commit -m change"),
+ ("Bash", "cd .. && git -C \\\n repo \\\n commit -m change"),
+])
+def test_continued_commit_is_reviewed(tmp_path, hook_env, stub_api, tool, command):
+ repo = make_repo(tmp_path / "repo")
+ sha, out = commit_file(repo, "a.py", "print('a')\n")
+ payload = {**bash_payload(str(repo), command, out), "tool_name": tool}
+ _, so, _ = run_hook(payload, hook_env)
+ assert metrics_of(so).get("commit_review") is True
+ assert sha in _load_reviewed_shas(str(repo))
+
+
+def test_continued_push_is_reviewed(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo")
+ remote = tmp_path / "remote.git"
+ git(tmp_path, "init", "-q", "--bare", str(remote))
+ git(repo, "remote", "add", "origin", str(remote))
+ git(repo, "push", "-q", "-u", "origin", "main")
+ base = git(repo, "rev-parse", "HEAD").strip()
+ sha, _ = commit_file(repo, "a.py", "print('a')\n")
+ git(repo, "push", "-q", "origin", "main")
+ out = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n"
+ _, so, _ = run_hook(bash_payload(str(repo), "git \\\n push origin main", out), hook_env)
+ assert metrics_of(so).get("push_sweep") is True
+ assert sha in _load_reviewed_shas(str(repo))
diff --git a/plugins/security-guidance/tests/test_pattern_false_positives.py b/plugins/security-guidance/tests/test_pattern_false_positives.py
new file mode 100644
index 00000000..5a816bac
--- /dev/null
+++ b/plugins/security-guidance/tests/test_pattern_false_positives.py
@@ -0,0 +1,96 @@
+"""Ordinary code that the edit warnings used to fire on, next to the real uses
+that still have to."""
+import time
+
+import pytest
+
+import security_reminder_hook as hook
+
+EVAL, FUNCTION, INNER, OUTER = (
+ "eval_injection", "new_function_injection", "innerHTML_xss", "outerHTML_xss")
+
+
+def fired(path, content):
+ return [rule for rule, _ in hook.check_patterns(path, content)]
+
+
+QUIET = [
+ ("t.js", "await page.$$eval('.btn', ns => ns.length)\n"),
+ ("t.js", "await page.$eval('#id', e => e.tagName)\n"),
+ ("t.ts", "await page.$eval('a', (el: HTMLLinkElement) => el.href)\n"),
+ ("t.ts", "await page.$eval('a', (el): string => el.href)\n"),
+ ("t.js", "await page.$eval(\n '.row',\n async function (el) { return el.id }\n)\n"),
+ ("t.js", "await frame.$$eval(`.row a`, (els, min) => els.length > min, 3)\n"),
+ ("t.js", "await handle.$eval('[a=\"b\"]', async ({ href }) => href)\n"),
+ ("t.js", "const r = new FunctionRegistry()\n"),
+ ("t.tsx", "const c = new FunctionComponent()\n"),
+ ("t.js", "return new Function_(a)\n"),
+ ("t.js", "if (el.innerHTML === expected) { pass() }\n"),
+ ("t.js", "if (el.innerHTML == expected) { pass() }\n"),
+ ("t.js", "if (el.innerHTML=== expected) { pass() }\n"),
+ ("t.js", "expect(el.outerHTML === golden).toBe(true)\n"),
+]
+
+CAUGHT = [
+ (EVAL, "c.js", "const v = eval(userInput)\n"),
+ (EVAL, "c.py", "v = eval(user_input)\n"),
+ # AngularJS evaluates an expression string, on whatever the scope is called.
+ (EVAL, "c.js", "$scope.$eval(attrs.expr)\n"),
+ (EVAL, "c.js", "scope.$eval(userInput)\n"),
+ (EVAL, "c.js", "this.$eval(expr)\n"),
+ (EVAL, "c.js", "element.scope().$eval(expr)\n"),
+ (EVAL, "c.js", "scope.$parent.$eval(expr, { $event: ev })\n"),
+ (EVAL, "c.js", "scope.$eval(expr, locals)\n"),
+ (EVAL, "c.js", "const $eval = eval; $eval(code)\n"),
+ # A page function given as a string, or by name.
+ (EVAL, "c.js", "await page.$eval('a', 'e => ' + body)\n"),
+ (EVAL, "c.js", "await page.$eval('a', readHref)\n"),
+ # An expression or selector that is not a constant.
+ (EVAL, "c.js", "scope.$eval(expr, () => x)\n"),
+ (EVAL, "c.js", "$eval(code, x => 1)\n"),
+ (EVAL, "c.js", "scope.$eval('cb(' + x + ')', cb => 1)\n"),
+ (EVAL, "c.js", "scope.$eval(`cb(${x})`, cb => 1)\n"),
+ # An eval inside or after the page function call.
+ (EVAL, "c.js", "await page.$eval('a', el => eval(el.dataset.code))\n"),
+ (EVAL, "c.js", "await page.$eval(eval(sel), el => el.id)\n"),
+ (EVAL, "c.js", "await page.$eval('a', el => el.id)\nscope.$eval(expr)\n"),
+ (EVAL, "c.js", "await page.$eval('a', el => el.id)\neval(code)\n"),
+ # The shape only excuses `$eval(`.
+ (EVAL, "c.js", "eval('a', el => el.id)\n"),
+ (FUNCTION, "c.js", "const f = new Function('a', body)\n"),
+ (FUNCTION, "c.js", "const f = new Function ('a', body)\n"),
+ (FUNCTION, "c.ts", "const f = new Function<any>(body)\n"),
+ (FUNCTION, "c.js", "const f = new Function`return 1`\n"),
+ (FUNCTION, "c.js", "Reflect.apply(new Function, null, [])\n"),
+ (FUNCTION, "c.js", "new Function"),
+ (FUNCTION, "c.js", "new FunctionConstructor(body)\n"),
+ (FUNCTION, "c.js", "new FunctionRegistry(); new Function(body)\n"),
+ (INNER, "c.js", "el.innerHTML = html\n"),
+ (INNER, "c.js", "el.innerHTML=html\n"),
+ (INNER, "c.js", "el.innerHTML =\n html\n"),
+ (INNER, "c.js", "el.innerHTML ="),
+ (INNER, "c.js", "if (el.innerHTML === a) el.innerHTML = b\n"),
+ (OUTER, "c.js", "el.outerHTML = html\n"),
+ (OUTER, "c.js", "el.outerHTML=html\n"),
+ (OUTER, "c.js", "if (el.outerHTML !== a && el.outerHTML === c) el.outerHTML = b\n"),
+]
+
+
+@pytest.mark.parametrize("path,content", QUIET)
+def test_ordinary_code_gets_no_warning(path, content):
+ assert fired(path, content) == []
+
+
+@pytest.mark.parametrize("rule,path,content", CAUGHT)
+def test_real_use_still_warns_once(rule, path, content):
+ assert fired(path, content).count(rule) == 1
+
+
+@pytest.mark.parametrize("path,unit", [
+ ("t.js", "$eval("), ("t.js", "$eval('"), ("t.js", "$eval(`"), ("t.js", "$eval('a',("),
+ ("t.js", "$eval('a' "), ("t.js", "$eval('a',(b): "), ("t.js", ".innerHTML "),
+])
+def test_repeated_openings_stay_quick(path, unit):
+ start = time.monotonic()
+ hook.check_patterns(path, unit * (200_000 // len(unit)))
+ assert time.monotonic() - start < 5
diff --git a/plugins/security-guidance/tests/test_renamed_into_review.py b/plugins/security-guidance/tests/test_renamed_into_review.py
new file mode 100644
index 00000000..109f5efc
--- /dev/null
+++ b/plugins/security-guidance/tests/test_renamed_into_review.py
@@ -0,0 +1,466 @@
+"""A file renamed from a name the commit and push reviews leave out to one
+they read is reviewed whole; every other rename is reviewed as before."""
+import json
+import os
+import sys
+
+import pytest
+
+from conftest import (
+ GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook,
+)
+
+import gitutil
+import security_reminder_hook as hook
+from diffstate import _load_reviewed_shas
+
+BODY = "import os\n" + "".join(f"value_{i} = {i}\n" for i in range(30)) + "os.system(input())\n"
+MARK = "os.system(input())"
+SECRET = "".join(f"KEY_{i}=SECRET_VALUE_{i}\n" for i in range(30))
+
+
+@pytest.fixture(autouse=True)
+def git_env(monkeypatch):
+ for k, v in GIT_ENV.items():
+ monkeypatch.setenv(k, v)
+
+
+def _sent(stub_api):
+ return "\n".join(json.dumps(b) for b, c in zip(stub_api.bodies, stub_api.calls)
+ if c.endswith("/v1/messages"))
+
+
+def _move(repo, old, new):
+ (repo / new).parent.mkdir(parents=True, exist_ok=True)
+ git(repo, "mv", old, new)
+
+
+def _commit(repo, env, command="git commit -m change", args=("-m", "change")):
+ git(repo, "add", "-A")
+ out = git(repo, "commit", *args)
+ return metrics_of(run_hook(bash_payload(repo, command, stdout=out), env)[1])
+
+
+def _push_repo(tmp_path, files):
+ repo = make_repo(tmp_path / "repo", files)
+ remote = tmp_path / "remote.git"
+ git(tmp_path, "init", "-q", "--bare", str(remote))
+ git(repo, "remote", "add", "origin", str(remote))
+ git(repo, "push", "-q", "-u", "origin", "main")
+ return repo, remote
+
+
+def _push(repo, remote, env):
+ old = git(repo, "rev-parse", "--short", "@{u}").strip()
+ git(repo, "push", "-q")
+ new = git(repo, "rev-parse", "--short", "HEAD").strip()
+ out = f"To {remote}\n {old}..{new} main -> main\n"
+ return metrics_of(run_hook(bash_payload(repo, "git push", out), env)[1])
+
+
+@pytest.mark.parametrize("old,new", [
+ ("notes.txt", "payload.py"),
+ ("docs/setup.md", "bin/setup.sh"),
+ ("docs/image.txt", "Dockerfile"),
+ ("notes.txt", "a b/pay load.py"),
+ ("notes.txt", "café.py"),
+])
+def test_commit_review_reads_the_renamed_file(tmp_path, hook_env, stub_api, old, new):
+ repo = make_repo(tmp_path / "repo", {old: BODY, "app.py": "x = 1\n"})
+ _move(repo, old, new)
+ m = _commit(repo, hook_env)
+ assert m.get("skip_reason") is None and m["files_reviewed"] == 1, m
+ assert m["renamed_in"] == 1
+ assert MARK in _sent(stub_api)
+
+
+def test_push_review_reads_the_renamed_file(tmp_path, hook_env, stub_api):
+ repo, remote = _push_repo(tmp_path, {"notes.txt": BODY})
+ _move(repo, "notes.txt", "payload.py")
+ git(repo, "commit", "-qm", "rename")
+ m = _push(repo, remote, hook_env)
+ assert m.get("skip_reason") is None and m["files_reviewed"] == 1, m
+ assert MARK in _sent(stub_api)
+
+
+def test_edit_in_the_rename_shows_the_whole_file_once(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY})
+ _move(repo, "notes.txt", "payload.py")
+ text = (repo / "payload.py").read_text().replace("value_29 = 29", "value_29 = EDITED")
+ (repo / "payload.py").write_text(text)
+ m = _commit(repo, hook_env)
+ assert m["renamed_in"] == 1 and m["files_reviewed"] == 1, m
+ # Added, not context: the reviewer is told to leave context lines alone.
+ assert "+" + MARK in _sent(stub_api) and "+value_29 = EDITED" in _sent(stub_api)
+ assert "\\n " + MARK not in _sent(stub_api)
+ # What the edit removed is still there to see.
+ assert "-value_29 = 29" in _sent(stub_api)
+
+
+def test_edit_hunk_stays_where_the_whole_file_does_not_fit(tmp_path, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, "app.py": "x = 1\n"})
+ _move(repo, "notes.txt", "payload.py")
+ git(repo, "commit", "-qm", "c")
+ renamed = [("payload.py", ("show", "--format=", "HEAD"), "HEAD")]
+ edits = [("payload.py", "@@ -1 +1 @@\n-x\n+y"), ("app.py", "@@ -1 +1 @@\n-x\n+y")]
+ files, failed = hook._with_renamed_in(str(repo), edits, renamed, 30)
+ assert [n for n, _ in files] == ["payload.py", "app.py"] and not failed
+ assert MARK in files[0][1] and files[1] == edits[1]
+ for name, limit in (("DIFF_TOTAL_BYTES", 300), ("DIFF_PER_FILE_BYTES", 300)):
+ with monkeypatch.context() as m:
+ m.setattr(hook, name, limit)
+ assert hook._with_renamed_in(str(repo), edits, renamed, 30)[0] == edits
+ monkeypatch.setattr(hook, "RENAMED_IN_BYTES", 300)
+ for before in (edits, edits[1:]):
+ assert hook._with_renamed_in(str(repo), before, renamed, 30)[0] == before
+
+
+def test_merge_hunks_are_left_alone(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY})
+ _move(repo, "notes.txt", "payload.py")
+ git(repo, "commit", "-qm", "c")
+ files = [("payload.py", "@@@ -1,1 -1,1 +1,1 @@@\n- x\n -y\n++z")]
+ renamed = [("payload.py", ("show", "--format=", "HEAD"), "HEAD")]
+ assert hook._with_renamed_in(str(repo), files, renamed, 30) == (files, False)
+
+
+def test_rename_added_by_an_amend(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, "app.py": "x = 1\n"})
+ commit_file(repo, "app.py", "x = 2\n")
+ _move(repo, "notes.txt", "payload.py")
+ m = _commit(repo, hook_env, "git commit --amend --no-edit", ("--amend", "--no-edit"))
+ assert m.get("amend_delta_review") is True and m["files_reviewed"] == 1, m
+ assert MARK in _sent(stub_api)
+
+
+@pytest.mark.parametrize("old,new", [
+ ("a.py", "pkg/b.py"), ("a.py", "notes.txt"), ("notes.txt", "other.txt"),
+ ("a.py", "vendor/a.py"), ("vendor/a.py", "a.py"), ("server.pem", "server"),
+ ("prod.env", "prod.sh"), (".htpasswd", "htpasswd"), ("dump.csv", "dump.sql"),
+ ("credentials.txt", "credentials.sh"), ("notes.txt", "credentials.sh"), ("deploy_rsa.txt", "deploy.sh"),
+ ("passwords.md", "list.py"), ("notes.txt", "notes"), ("data.txt", "data.json"), ("notes.txt", "vendor/a.py"),
+])
+def test_other_renames_are_not_sent(tmp_path, hook_env, stub_api, old, new):
+ repo = make_repo(tmp_path / "repo", {old: BODY, "app.py": "x = 1\n"})
+ _move(repo, old, new)
+ m = _commit(repo, hook_env)
+ assert m["skip_reason"] == 30 and "renamed_in" not in m
+ assert _sent(stub_api) == ""
+
+
+@pytest.mark.parametrize("name", """
+ api_keys.txt tokens.txt apiKeysProd.md KEYS.md AWSkeys.txt GCPkey.md DBpass.txt stripekey.txt
+ API_TOKEN.rst github-token-old.txt db_password.txt db_passwd.md my.creds.txt db-cred.txt
+ root_pwd.txt site_logins.txt prod.env.txt env.production.txt server.pem.txt id_ed25519.md
+ passphrase.md github-recovery-codes.txt gcp-service-account.txt service_account.md pgpass.txt
+ npmrc.txt netrc.txt my-secret.txt app_credential.md
+ secrets/prod.txt Credentials/prod.md prod-creds/a.txt api-keys/s.txt tokens/a/b.md .secrets/a.txt
+ vault/a.txt passwd/a.txt .ssh/prod.txt a/.aws/prod.txt a/.gnupg/n.md .kube/n.txt a/Passwords/b.txt
+ api_keys passwords secrets.yaml .env .env.py server.pem server.key deploy_rsa
+""".split())
+def test_name_of_a_secret(name):
+ assert gitutil._is_secret_text(name)
+
+
+@pytest.mark.parametrize("name", """
+ notes.txt compassion.md environment.md keyboard.rst login.md tokenizer.md jwt.md author.md
+ aws/setup.md ssh/setup.md password-manager/notes.txt secret-service/notes.txt keyboards/a.txt
+ tokenizer/notes.txt
+""".split())
+def test_name_of_ordinary_text(name):
+ assert not gitutil._is_secret_text(name)
+ assert gitutil._is_text_turned_code(name, "config.py")
+
+
+@pytest.mark.parametrize("name", [
+ "tokens.py", "api_keys.py", "token_store.js", "vendor/tokens.go", "secrets/load.py",
+ "vault/Dockerfile", "secrets/Makefile"])
+def test_code_is_not_a_list_of_secrets(name):
+ assert not gitutil._is_secret_text(name)
+
+
+@pytest.mark.parametrize("old,new", [
+ ("api_keys.txt", "api_keys.py"), ("tokens.txt", "config.py"), ("keys/prod.md", "config.sh")])
+def test_list_of_secrets_is_not_sent(tmp_path, hook_env, stub_api, old, new):
+ repo = make_repo(tmp_path / "repo", {old: SECRET, "app.py": "x = 1\n"})
+ _move(repo, old, new)
+ m = _commit(repo, hook_env)
+ assert m["skip_reason"] == 30 and "renamed_in" not in m, m
+ assert _sent(stub_api) == ""
+
+
+@pytest.mark.parametrize("old", ["api_keys.txt", "passwords", "secrets.yaml", "server.pem"])
+def test_list_of_secrets_renamed_in_two_steps_is_not_sent(tmp_path, hook_env, stub_api, old):
+ repo = make_repo(tmp_path / "repo", {old: SECRET})
+ _move(repo, old, "settings.txt")
+ git(repo, "commit", "-qm", "one")
+ _move(repo, "settings.txt", "settings.py")
+ assert _commit(repo, hook_env)["skip_reason"] == 30
+ assert _sent(stub_api) == ""
+
+
+def test_other_renames_of_the_commit_are_still_read(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {
+ "api_keys.txt": SECRET, "docs/hotkeys.md": "press a\n" * 9, "notes.txt": BODY})
+ _move(repo, "api_keys.txt", "settings.py")
+ _move(repo, "docs/hotkeys.md", "hotkeys.py")
+ _move(repo, "notes.txt", "payload.py")
+ assert _commit(repo, hook_env)["renamed_in"] == 1
+ assert MARK in _sent(stub_api) and "SECRET_VALUE" not in _sent(stub_api)
+
+
+def test_list_of_secrets_is_not_listed():
+ assert not gitutil._is_text_turned_code("api_keys.txt", "config.py")
+
+
+def test_code_with_a_secret_word_in_its_name_is_not_a_secret_origin(
+ tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"token_store.py": BODY, "app.py": "x = 1\n"})
+ _move(repo, "token_store.py", "notes.txt")
+ git(repo, "commit", "-qm", "one")
+ _move(repo, "notes.txt", "payload.py")
+ assert _commit(repo, hook_env)["renamed_in"] == 1
+ assert MARK in _sent(stub_api)
+
+
+def test_rename_away_from_a_secret_shaped_name_stays_out(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"deploy_rsa": SECRET})
+ _move(repo, "deploy_rsa", "settings.py")
+ assert _commit(repo, hook_env)["skip_reason"] == 30
+ assert _sent(stub_api) == ""
+
+
+@pytest.mark.parametrize("secret_goes", ["deleted", "renamed"])
+def test_not_sent_whole_when_a_secret_shaped_file_goes_too(
+ tmp_path, hook_env, stub_api, secret_goes):
+ # Same content under both names: git may pair either with the new file.
+ repo = make_repo(tmp_path / "repo", {
+ ".env": SECRET, "notes.txt": SECRET, "app.py": "x = 1\n"})
+ _move(repo, "notes.txt", "settings.py")
+ if secret_goes == "deleted":
+ git(repo, "rm", "-q", ".env")
+ else:
+ _move(repo, ".env", "old_env.txt")
+ (repo / "app.py").write_text("x = input()\n")
+ m = _commit(repo, hook_env)
+ assert m["files_reviewed"] == 1 and "renamed_in" not in m, m
+ assert "SECRET_VALUE" not in _sent(stub_api)
+
+
+@pytest.mark.parametrize("amend", [False, True])
+def test_secret_shaped_file_renamed_in_two_steps_stays_out(tmp_path, hook_env, stub_api, amend):
+ repo = make_repo(tmp_path / "repo", {".env": SECRET})
+ _move(repo, ".env", "settings.txt")
+ git(repo, "commit", "-qm", "one")
+ _move(repo, "settings.txt", "settings.py")
+ extra = ["--amend", "--no-edit"] if amend else ["-m", "two"]
+ m = _commit(repo, hook_env, "git commit " + " ".join(extra), extra)
+ assert "SECRET_VALUE" not in _sent(stub_api) and "renamed_in" not in m, m
+ assert m["skip_reason"] == (35 if amend and m.get("amend_delta_review") else 30), m
+
+
+def test_secret_shaped_file_renamed_after_edits_stays_out(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"deploy_rsa": SECRET})
+ _move(repo, "deploy_rsa", "a.txt")
+ with open(repo / "a.txt", "a") as f:
+ f.write("MORE=1\n")
+ git(repo, "commit", "-qam", "one")
+ commit_file(repo, "other.py", "x = 1\n")
+ _move(repo, "a.txt", "settings.py")
+ m = _commit(repo, hook_env)
+ assert "SECRET_VALUE" not in _sent(stub_api), m
+
+
+@pytest.mark.parametrize("how", [
+ "added lately", "in a merge", "in a merge, combined diffs", "on a side branch"])
+def test_secret_shaped_origin_is_followed(tmp_path, hook_env, stub_api, how):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ if how.endswith("combined diffs"):
+ git(repo, "config", "log.diffMerges", "combined")
+ if how == "on a side branch":
+ commit_file(repo, "app.py", "x = 2\n")
+ git(repo, "switch", "-qc", "side", "HEAD~1")
+ commit_file(repo, ".env", SECRET)
+ if how.startswith("in a merge"):
+ git(repo, "switch", "-qc", "side")
+ commit_file(repo, "side.py", "y = 1\n")
+ git(repo, "switch", "-q", "main")
+ git(repo, "merge", "-q", "--no-ff", "--no-commit", "side")
+ _move(repo, ".env", "settings.txt")
+ git(repo, "commit", "-qm", "one")
+ if how == "on a side branch":
+ git(repo, "switch", "-q", "main")
+ git(repo, "merge", "-q", "--no-ff", "--no-edit", "side")
+ for i in range(5):
+ commit_file(repo, f"m{i}.py", "z = 1\n")
+ _move(repo, "settings.txt", "settings.py")
+ m = _commit(repo, hook_env)
+ assert m["skip_reason"] == 30 and "SECRET_VALUE" not in _sent(stub_api), m
+
+
+def test_unknown_origin_stays_out(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY})
+ _move(repo, "notes.txt", "payload.py")
+ git(repo, "commit", "-qm", "c")
+ show = ("show", "--format=", "HEAD")
+ assert hook._with_renamed_in(str(repo), [], [("payload.py", show, "nope")], 30) == ([], True)
+ assert hook._with_renamed_in(str(repo), [], [("payload.py", show, "HEAD")], 30)[0]
+ assert gitutil.came_from_secret(str(repo), "HEAD", ["payload.py"], 10) == set()
+ assert gitutil.came_from_secret(str(repo), "nope", ["payload.py"], 10) is None
+
+
+def _two_quiet_commits(repo, env, second):
+ _move(repo, "notes.txt", "payload.py")
+ git(repo, "commit", "-qm", "one")
+ second()
+ git(repo, "add", "-A")
+ git(repo, "commit", "-qm", "two")
+ command = "git commit -qm one && git commit -qam two"
+ return metrics_of(run_hook(bash_payload(repo, command), env)[1])
+
+
+def test_file_is_shown_as_the_last_of_the_commits_left_it(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY})
+ m = _two_quiet_commits(repo, hook_env, lambda: (repo / "payload.py").write_text(
+ BODY.replace(MARK, "print('fixed')")))
+ assert m["reflog_shas_n"] > 1 and m["files_reviewed"] == 1 and m["renamed_in"] == 1, m
+ assert "+value_5 = 5" in _sent(stub_api) and "+print('fixed')" in _sent(stub_api)
+ assert "+" + MARK not in _sent(stub_api)
+
+
+def _many(n):
+ return {f"d/m{i:03}.txt": f"import os\nvalue = {i}\nkey_{i} = 'k{i}'\nname_{i} = {i}\n"
+ for i in range(n)}
+
+
+@pytest.mark.parametrize("edits,renames,renamed_in", [
+ (28, 20, 2), (30, 5, None), (3, 12, hook.MAX_RENAMED_IN), (0, 40, hook.MAX_RENAMED_IN)])
+def test_renamed_files_take_only_free_places(
+ tmp_path, hook_env, stub_api, edits, renames, renamed_in):
+ edited = {f"e{i:02}.py": "x = 1\n" for i in range(edits)}
+ repo = make_repo(tmp_path / "repo", {**edited, **_many(renames)})
+ for name in edited:
+ (repo / name).write_text("x = 2\n")
+ for name in _many(renames):
+ _move(repo, name, name[:-4] + ".py")
+ m = _commit(repo, hook_env)
+ assert m["files_reviewed"] == edits + (renamed_in or 0), m
+ assert m.get("renamed_in") == renamed_in and "diff_files_dropped" not in m
+ assert all(n in _sent(stub_api) for n in edited)
+
+
+def test_renames_do_not_count_towards_the_skip_for_huge_diffs(tmp_path, monkeypatch):
+ many = [(f"e{i}.py", "@@ -1 +1 @@\n-x\n+y") for i in range(31)]
+ monkeypatch.setattr(hook, "git_diff_unpaired", None)
+ assert hook._with_renamed_in("/r", many, [("n.py", ("show", "x"), "x")], 30) == (many, False)
+
+
+def test_a_directory_replaced_by_the_file_adds_one_file(tmp_path, hook_env, stub_api):
+ under = {f"makefile/auth_handler{i:02}.py": f"import os\nx = {i}\n" for i in range(20)}
+ edits = {f"e{i:02}.py": "x = 1\n" for i in range(9)}
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, **under, **edits})
+ git(repo, "rm", "-rq", "makefile")
+ _move(repo, "notes.txt", "makefile")
+ for name in edits:
+ (repo / name).write_text("x = 2\n")
+ m = _commit(repo, hook_env)
+ assert m["renamed_in"] == 1 and m["files_reviewed"] == 30, m
+ assert "diff_files_dropped" not in m
+
+
+def test_push_with_an_unreadable_file_leaves_the_commits_unrecorded(tmp_path, hook_env, stub_api):
+ repo, remote = _push_repo(tmp_path, {"notes.txt": BODY})
+ blob = git(repo, "rev-parse", "HEAD:notes.txt").strip()
+ _move(repo, "notes.txt", "payload.py")
+ git(repo, "commit", "-qm", "rename")
+ git(repo, "push", "-q")
+ # git shows a rename of unchanged content without reading that content.
+ obj = repo / ".git" / "objects" / blob[:2] / blob[2:]
+ os.chmod(obj, 0o644)
+ obj.unlink()
+ out = f"To {remote}\n {git(repo, 'rev-parse', '--short', 'HEAD~1').strip()}.."\
+ f"{git(repo, 'rev-parse', '--short', 'HEAD').strip()} main -> main\n"
+ m = metrics_of(run_hook(bash_payload(repo, "git push", out), hook_env)[1])
+ assert m["skip_reason"] == 45, m
+ assert not _load_reviewed_shas(str(repo))
+ assert _sent(stub_api) == ""
+
+
+@pytest.mark.skipif(sys.platform in ("win32", "darwin"), reason="file names are Unicode there")
+def test_push_of_a_name_that_is_not_utf8_is_not_recorded(tmp_path, hook_env, stub_api):
+ repo, remote = _push_repo(tmp_path, {"notes.txt": BODY})
+ os.rename(repo / "notes.txt", os.fsencode(repo) + b"/caf\xe9.py")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-qm", "rename")
+ assert _push(repo, remote, hook_env)["skip_reason"] == 45
+ assert not _load_reviewed_shas(str(repo))
+
+
+@pytest.mark.parametrize("name", ["GIT_ICASE_PATHSPECS", "GIT_GLOB_PATHSPECS",
+ "GIT_NOGLOB_PATHSPECS", "GIT_LITERAL_PATHSPECS"])
+def test_pathspec_setting_in_the_environment(tmp_path, hook_env, stub_api, name):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY})
+ _move(repo, "notes.txt", "payload.py")
+ m = _commit(repo, {**hook_env, name: "1"})
+ assert m.get("renamed_in") == 1, m
+
+
+def test_new_name_is_a_file_name_not_a_pattern(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, "a.py": "x = 1\n"})
+ _move(repo, "notes.txt", "[ab].py")
+ (repo / "a.py").write_text("x = 2\n")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-qm", "c")
+ files = gitutil.git_diff_unpaired(
+ str(repo), ("show", "--format=", "HEAD"), ["[ab].py"], 10)
+ assert list(files) == ["[ab].py"]
+
+
+def test_names_in_a_rename_with_an_edit_come_from_the_rename_lines():
+ hunk = ["--- a/x", "+++ b/y", "@@ -1 +1 @@", "-a", "+b"]
+ text = (_section("a/cfg b/.env b/cfg b/app.py", "rename from cfg b/.env",
+ "rename to cfg b/app.py", *hunk)
+ + _section("a/a b/x.py b/a b/y.py", "rename from a b/x.py", "rename to a b/y.py", *hunk))
+ assert [n for n, _ in gitutil.parse_diff_into_files(text)] == ["a b/y.py"]
+ assert gitutil.extract_file_paths_from_diff(text) == ["a b/y.py"]
+
+
+def test_name_with_the_header_separator_in_it(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"notes.txt": BODY, "cfg b/app.py": "x = 1\n"})
+ _move(repo, "notes.txt", "pkg b/tool.py")
+ (repo / "cfg b/app.py").write_text("x = input()\n")
+ m = _commit(repo, hook_env)
+ assert m["files_reviewed"] == 2 and m["renamed_in"] == 1, m
+ assert "pkg b/tool.py" in _sent(stub_api) and "cfg b/app.py" in _sent(stub_api)
+ assert "tool.py b/pkg" not in _sent(stub_api) and "app.py b/cfg" not in _sent(stub_api)
+
+
+def _section(header, *lines):
+ return "\n".join([f"diff --git {header}", *lines]) + "\n"
+
+
+@pytest.mark.parametrize("header,old,new,expect", [
+ ("a/n.txt b/n.py", "n.txt", "n.py", ["n.py"]),
+ ('"a/we\\"ird.txt" "b/we\\"ird.py"', '"we\\"ird.txt"', '"we\\"ird.py"', ['we"ird.py']),
+ ("a/x b/y.txt b/x b/y.py", "x b/y.txt", "x b/y.py", ["x b/y.py"]),
+ ("a/x.py b/y.py b/x.py b/z.py", "x.py b/y.py", "x.py b/z.py", []),
+ ("a/.env b/n.py", ".env", "n.py", []),
+ ("a/n.txt b/deploy_rsa", "n.txt", "deploy_rsa", []),
+])
+@pytest.mark.parametrize("verb", ["rename", "copy"])
+def test_names_come_from_the_rename_lines(verb, header, old, new, expect):
+ text = _section(header, "similarity index 100%", f"{verb} from {old}", f"{verb} to {new}")
+ assert gitutil.renamed_into_review(text) == expect
+
+
+def test_lines_of_content_are_not_rename_lines():
+ text = _section("a/a.py b/a.py", "--- a/a.py", "+++ b/a.py", "@@ -1 +1,3 @@",
+ " rename from n.txt", "rename from n.txt", "rename to n.py")
+ assert gitutil.renamed_into_review(text) == []
+
+
+@pytest.mark.parametrize("gone", [".env", "cfg b/.env", "deploy_rsa"])
+def test_nothing_is_listed_when_a_secret_shaped_file_goes_too(gone):
+ text = (_section(f"a/{gone} b/{gone}", "deleted file mode 100644", "@@ -1 +0,0 @@", "-x")
+ + _section("a/n.txt b/n.py", "similarity index 100%", "rename from n.txt", "rename to n.py"))
+ assert gitutil.renamed_into_review(text) == []
diff --git a/plugins/security-guidance/tests/test_review_result_keys.py b/plugins/security-guidance/tests/test_review_result_keys.py
new file mode 100644
index 00000000..f6711f05
--- /dev/null
+++ b/plugins/security-guidance/tests/test_review_result_keys.py
@@ -0,0 +1,132 @@
+"""Review rows keep their result, kind and time when they have more keys than
+Claude Code keeps (the first 20)."""
+import json
+
+import pytest
+
+import security_reminder_hook as hook
+
+_USAGE = {"tok_in": 1, "tok_out": 1, "tok_cache_r": 0, "tok_cache_w": 0,
+ "cost_usd": 0.1, "api_calls": 3}
+_HTTP_ERR = {"http_err_last": 429, "http_err_count": 2}
+# The keys the commit and push handlers pass, in their order.
+_REFLOG = {"sha_via_reflog": True, "reflog_shas_n": 1}
+_COMMIT_BASE = {"commit_review": True, "commit_review_on": True, "cwd_is_repo": False,
+ "repo_resolution": 2, **_REFLOG, "diff_files_dropped": 3, "rate_count": 1}
+_PUSH_BASE = {"push_sweep": True, "push_sweep_on": True, "cwd_is_repo": False,
+ "repo_resolution": 2, "diff_files_dropped": 3, "rate_count": 1}
+# A commit made with `git commit -q`, the common shape of a row with findings.
+_QUIET_COMMIT = {"vulns_found": 1, "commit_review": True, "commit_review_on": True,
+ **_REFLOG, "rate_count": 1, "agentic": True, "candidates": 1, "survived": 1,
+ "race_winner": 1, "critical_count": 0, "high_count": 1,
+ "files_reviewed": 4, "review_ms": 9500}
+_COMMIT_FINDINGS = {"vulns_found": 2, **_COMMIT_BASE, "agentic": True, "candidates": 3,
+ "survived": 3, "survived_after_sev": 2, "race_winner": 1,
+ "critical_count": 1, "high_count": 1,
+ "files_reviewed": 4, "review_ms": 9500, "deduped": 1}
+_COMMIT_CLEAN = {"vulns_found": 0, **_COMMIT_BASE, "agentic": True, "candidates": 3,
+ "survived": 0, "race_winner": 1, "files_reviewed": 4, "review_ms": 9500}
+_COMMIT_KNOWN = {"vulns_found": 0, **_COMMIT_BASE, "agentic": True, "candidates": 3,
+ "survived": 3, "race_winner": 1, "deduped": 3,
+ "files_reviewed": 4, "review_ms": 9500}
+_PUSH = {**_PUSH_BASE, "pushed": 2, "unreviewed": 1, "prefix_advanced": 1, "vulns_found": 2,
+ "files_reviewed": 4, "review_ms": 9500, "deduped": 1, "inflight_wait_s": 4}
+_COMMIT_FAILED = {**_COMMIT_BASE, "agentic": False, "agentic_fallback": 2,
+ "race_winner": 1, "files_reviewed": 4, "review_ms": 9500}
+_PUSH_FAILED = {**_PUSH_BASE, "inflight_wait_s": 4, "pushed": 2, "unreviewed": 1,
+ "files_reviewed": 4, "review_ms": 9500}
+
+
+@pytest.fixture(autouse=True)
+def _clean(monkeypatch):
+ monkeypatch.setattr(hook, "_PV", 20000)
+ monkeypatch.setattr(hook, "_TAIL_METRICS", {"diff_seen": 0, "child_stderr": 2})
+ monkeypatch.setattr(hook, "_REVIEWER_EFFORT_METRICS", {"rv_effort": 5})
+ monkeypatch.setattr(hook, "_LAUNCHER_METRICS", {})
+ monkeypatch.setattr(hook, "_LAUNCHER_DIRECT", {})
+ monkeypatch.setattr(hook, "_log_usage", lambda usage: None)
+ monkeypatch.setattr(hook, "_usage_metrics", lambda: dict(_USAGE))
+ monkeypatch.setattr(hook, "_precheck_miss", False)
+ monkeypatch.setattr(hook, "_net_error_metric", lambda: 0)
+ monkeypatch.setattr(hook.llm, "gateway_cfg", lambda: 3)
+ monkeypatch.delenv("SG_LAUNCHER_FALLBACK", raising=False)
+
+
+def _row(capsys):
+ return json.loads(capsys.readouterr().out)["metrics"]
+
+
+def _kept(row, cap=hook._METRIC_KEY_CAP):
+ """The part of a row Claude Code forwards."""
+ return dict(list(row.items())[:cap])
+
+
+_ROWS = {"quiet-commit": _QUIET_COMMIT, "commit-findings": _COMMIT_FINDINGS,
+ "commit-clean": _COMMIT_CLEAN, "commit-known": _COMMIT_KNOWN, "push": _PUSH}
+
+
+@pytest.mark.parametrize("http_err", [{}, _HTTP_ERR], ids=["", "http-errors"])
+@pytest.mark.parametrize("name", _ROWS)
+def test_result_and_time_are_kept(capsys, monkeypatch, name, http_err):
+ metrics = _ROWS[name]
+ monkeypatch.setattr(hook, "_usage_metrics", lambda: {**_USAGE, **http_err})
+ hook.emit_metrics(metrics)
+ row = _row(capsys)
+ assert len(row) > hook._METRIC_KEY_CAP
+ kept = _kept(row)
+ must = ("vulns_found", "review_ms", "files_reviewed", "commit_review",
+ "push_sweep", "agentic", "deduped", "critical_count", "high_count")
+ assert {k: kept.get(k) for k in must} == {k: metrics.get(k) for k in must}
+ assert {"pv", *_USAGE, *http_err} <= set(kept)
+
+
+def test_quiet_commit_loses_one_descriptive_key(capsys):
+ hook.emit_metrics(_QUIET_COMMIT)
+ row = _row(capsys)
+ assert set(_QUIET_COMMIT) - set(_kept(row)) == {"commit_review_on"}
+
+
+@pytest.mark.parametrize("kind, metrics, split", [
+ ("Commit", _COMMIT_FAILED, "commit_review"), ("Push", _PUSH_FAILED, "push_sweep")])
+def test_failed_review_keeps_result_and_time(capsys, monkeypatch, kind, metrics, split):
+ """With every key that can come ahead of them."""
+ monkeypatch.setattr(hook, "_usage_metrics", lambda: {**_USAGE, **_HTTP_ERR})
+ monkeypatch.setattr(hook, "_net_error_metric", lambda: 2001)
+ monkeypatch.setattr(hook, "_precheck_miss", True)
+ monkeypatch.setenv("SG_LAUNCHER_FALLBACK", "1")
+ monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda *a: False)
+ with pytest.raises(SystemExit):
+ hook._exit_review_failed(kind, "s1", metrics, 429)
+ kept = _kept(_row(capsys))
+ assert kept["review_failed"] is True and kept[split] is True
+ assert (kept["api_error"], kept["vulns_found"]) == (429, 0)
+ assert (kept["review_ms"], kept["files_reviewed"]) == (9500, 4)
+ assert kept["net_err"] == 2001 and kept.get("agentic") == metrics.get("agentic")
+
+
+@pytest.mark.parametrize("metrics, split", [
+ (_QUIET_COMMIT, "commit_review"), (_PUSH, "push_sweep")])
+def test_kind_and_time_fit_the_old_cap_of_ten(capsys, metrics, split):
+ hook.emit_metrics(metrics)
+ kept = _kept(_row(capsys), 10)
+ assert {"vulns_found", split, "review_ms"} <= set(kept)
+
+
+def test_only_the_order_changes(capsys):
+ hook.emit_metrics(_COMMIT_FINDINGS)
+ row = _row(capsys)
+ added = {"pv", *_USAGE, "gateway_cfg", "diff_seen", "child_stderr", "rv_effort"}
+ assert {k: v for k, v in row.items() if k not in added} == _COMMIT_FINDINGS
+ rest = [k for k in _COMMIT_FINDINGS
+ if k not in hook._LEAD_METRIC_KEYS and k != "commit_review_on"]
+ assert [k for k in row if k in rest] == rest
+
+
+@pytest.mark.parametrize("metrics", [
+ {"skipped": True, "skip_reason": 21, "commit_review": True, "commit_review_on": True},
+ {"skipped": True, "skip_reason": 35, "diff_strategy_v2": True, "deduped": 2, "review_ms": 900},
+])
+def test_skip_rows_are_unchanged(capsys, monkeypatch, metrics):
+ monkeypatch.setattr(hook, "_usage_metrics", dict)
+ hook.emit_metrics(metrics)
+ assert list(_row(capsys))[:1 + len(metrics)] == ["pv", *metrics]
diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py
index 555ef0ad..f5f75cfd 100644
--- a/plugins/security-guidance/tests/test_reviewer_tools.py
+++ b/plugins/security-guidance/tests/test_reviewer_tools.py
@@ -90,6 +90,10 @@ def sdk(monkeypatch, tmp_path):
for var in ("CONTEXT_DIR", "DEBUG_DIR", "MODEL", "ITER2", "FILTER", "NO_ADJUDICATE",
"DIFF_INTERSECT", "EXCLUDE_MEDIUM", "MAX_TURNS"):
monkeypatch.delenv("SG_AGENTIC_" + var, raising=False)
+ for var in ("MAX_THINKING_TOKENS", "CLAUDE_CODE_DISABLE_THINKING",
+ "CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING", "ANTHROPIC_DEFAULT_OPUS_MODEL"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setattr(llm, "_listed_models", lambda: {})
return spawned
@@ -104,6 +108,34 @@ def test_every_agentic_stage_gets_only_the_read_tools(sdk, tmp_path):
assert "permission_mode" not in opts
+def _systems(sdk, tmp_path):
+ llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"])
+ return [opts["system_prompt"] for opts in sdk]
+
+
+@pytest.mark.parametrize("opus", [None, "", " "])
+def test_investigate_stages_are_told_their_text_is_not_read(sdk, tmp_path, monkeypatch, opus):
+ if opus is not None:
+ monkeypatch.setenv("ANTHROPIC_DEFAULT_OPUS_MODEL", opus)
+ investigate, second, refute = _systems(sdk, tmp_path)
+ for system in (investigate, second):
+ assert system == llm._AGENTIC_INVESTIGATE_SYSTEM + llm._REVIEWER_OUTPUT_RULE
+ assert llm._REVIEWER_OUTPUT_RULE not in refute
+ # review_api's prompt, which other harnesses use as it is, keeps its text.
+ assert "OUTPUT:" not in llm._AGENTIC_INVESTIGATE_SYSTEM
+ assert "Aim for at least one candidate" in llm._AGENTIC_INVESTIGATE_SYSTEM
+
+
+@pytest.mark.parametrize("name,value", [
+ ("MAX_THINKING_TOKENS", "0"), ("CLAUDE_CODE_DISABLE_THINKING", "1"),
+ ("CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING", "true"), ("SG_AGENTIC_MODEL", "some-model"),
+ ("ANTHROPIC_DEFAULT_OPUS_MODEL", "some-model")])
+def test_output_rule_is_left_out_where_text_is_the_reasoning(sdk, tmp_path, monkeypatch, name, value):
+ monkeypatch.setenv(name, value)
+ investigate, second, _ = _systems(sdk, tmp_path)
+ assert investigate == second == llm._AGENTIC_INVESTIGATE_SYSTEM
+
+
def test_single_turn_sdk_review_gets_no_tools(sdk):
schema = {"type": "object", "properties": {}}
assert llm._call_claude_via_sdk("review this", schema) is not None
diff --git a/plugins/security-guidance/tests/test_tls_macos_ca_file.py b/plugins/security-guidance/tests/test_tls_macos_ca_file.py
new file mode 100644
index 00000000..f2e73798
--- /dev/null
+++ b/plugins/security-guidance/tests/test_tls_macos_ca_file.py
@@ -0,0 +1,193 @@
+"""A macOS Python without any CA certificate uses the CA file macOS ships.
+
+A python.org Python has none until its "Install Certificates" command is run.
+The machine and that Python are stood in for here, so the cases run on every
+platform.
+"""
+import http.client
+import ssl
+import types
+import urllib.error
+
+import pytest
+
+# The certificates, the HTTPS endpoint and the review call of the store tests.
+from test_tls_store_unreadable_cert import ( # noqa: F401
+ UNRELATED_CA_PEM, _head, _review, https_api, pki, store, urlopen_calls)
+
+import llm
+
+_real_create_default_context = ssl.create_default_context
+
+
+def _no_certificates(*args, **kwargs):
+ """What create_default_context gives on a Python with no CA file."""
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
+ default = _real_create_default_context(cadata=UNRELATED_CA_PEM)
+ context.verify_flags, context.options = default.verify_flags, default.options
+ return context
+
+
+@pytest.fixture
+def mac(store, monkeypatch, tmp_path):
+ """A Mac whose Python has no certificates and whose OS CA file holds one."""
+ os_file = tmp_path / "cert.pem"
+ os_file.write_text(UNRELATED_CA_PEM)
+ paths = types.SimpleNamespace(cafile=None, capath=None)
+ monkeypatch.delattr(ssl, "enum_certificates", raising=False) # Windows only
+ monkeypatch.setattr(llm, "_ON_MACOS", True)
+ monkeypatch.setattr(llm, "_MACOS_CA_FILE", str(os_file))
+ monkeypatch.setattr(ssl, "get_default_verify_paths", lambda: paths)
+ monkeypatch.setattr(ssl, "_create_default_https_context", _no_certificates)
+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)
+ return types.SimpleNamespace(paths=paths, os_file=os_file, tmp=tmp_path)
+
+
+def _names(context):
+ return {dict(x[0] for x in c["subject"])["commonName"] for c in context.get_ca_certs()}
+
+
+def _context():
+ return llm._context_with_os_ca_file()
+
+
+class TestContext:
+ def test_holds_the_os_file_and_nothing_else(self, mac):
+ assert _names(_context()) == {"sg test unrelated CA"}
+
+ def test_verifies_as_any_default_context(self, mac):
+ context = _context()
+ assert context.verify_mode == ssl.CERT_REQUIRED
+ assert context.check_hostname is True
+ default = _real_create_default_context(cadata=UNRELATED_CA_PEM)
+ assert context.verify_flags == default.verify_flags
+ assert context.options == default.options
+ assert context.minimum_version == default.minimum_version
+
+ def test_is_set_up_as_http_client_does(self, mac, monkeypatch):
+ offered = []
+ monkeypatch.setattr(ssl.SSLContext, "set_alpn_protocols",
+ lambda self, protocols: offered.append(protocols))
+ ours = _context()
+ theirs = http.client.HTTPSConnection("localhost")._context
+ assert offered == [["http/1.1"], ["http/1.1"]]
+ assert ours.post_handshake_auth == theirs.post_handshake_auth
+
+ def test_a_python_with_a_ca_file_is_left_alone(self, mac):
+ mac.paths.cafile = str(mac.tmp / "own.pem")
+ assert _context() is None
+
+ def test_a_python_with_a_ca_directory_is_left_alone(self, mac):
+ certs = mac.tmp / "certs"
+ certs.mkdir()
+ (certs / "1a2b3c4d.0").write_text(UNRELATED_CA_PEM)
+ mac.paths.capath = str(certs)
+ assert _context() is None
+
+ @pytest.mark.parametrize("contents", [[], [".keepme"], ["notes.txt"]])
+ def test_a_directory_without_certificates_counts_as_none(self, mac, contents):
+ certs = mac.tmp / "certs"
+ certs.mkdir()
+ for name in contents: # Homebrew keeps a .keepme there
+ (certs / name).write_text("")
+ mac.paths.capath = str(certs)
+ assert _context() is not None
+
+ def test_a_directory_that_cannot_be_listed_counts_as_none(self, mac, monkeypatch):
+ def listdir(path):
+ raise PermissionError(path)
+ mac.paths.capath = str(mac.tmp)
+ monkeypatch.setattr(llm.os, "listdir", listdir)
+ assert _context() is not None
+
+ def test_certificates_found_another_way_are_left_alone(self, mac, monkeypatch):
+ """A default context can hold some though the paths name no file."""
+ monkeypatch.setattr(ssl, "_create_default_https_context",
+ lambda: _real_create_default_context(cadata=UNRELATED_CA_PEM))
+ assert _context() is None
+
+ def test_a_site_that_replaced_the_default_is_left_alone(self, mac, monkeypatch):
+ monkeypatch.setattr(ssl, "_create_default_https_context",
+ ssl._create_unverified_context)
+ assert _context() is None
+
+ @pytest.mark.parametrize("value", ["/nonexistent", ""])
+ @pytest.mark.parametrize("var", ["SSL_CERT_FILE", "SSL_CERT_DIR"])
+ def test_the_users_own_choice_wins(self, mac, monkeypatch, var, value):
+ monkeypatch.setenv(var, value)
+ assert _context() is None
+
+ def test_a_plain_http_endpoint_needs_none(self, mac, monkeypatch):
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://127.0.0.1:4000")
+ assert _context() is None
+
+ def test_other_platforms_are_untouched(self, mac, monkeypatch):
+ monkeypatch.setattr(llm, "_ON_MACOS", False)
+ assert _context() is None
+
+ def test_no_os_file_means_no_change(self, mac):
+ mac.os_file.unlink()
+ assert _context() is None
+
+
+class TestCalls:
+ def test_the_context_is_built_once(self, mac, urlopen_calls, monkeypatch):
+ real, builds = llm._context_with_os_ca_file, []
+ monkeypatch.setattr(llm, "_context_with_os_ca_file",
+ lambda: builds.append(1) or real())
+ llm._urlopen(_head(), 5)
+ llm._urlopen(_head(), 5)
+ assert len(builds) == 1
+ first, second = [c["context"] for c in urlopen_calls]
+ assert first is second
+ assert _names(first) == {"sg test unrelated CA"}
+
+ @pytest.mark.parametrize("problem", ["not a certificate", PermissionError])
+ def test_an_os_file_that_cannot_be_used_changes_nothing(
+ self, mac, urlopen_calls, monkeypatch, problem):
+ if isinstance(problem, str):
+ mac.os_file.write_text(problem)
+ else:
+ def refuse(self, **kwargs):
+ raise problem("denied")
+ monkeypatch.setattr(ssl.SSLContext, "load_verify_locations", refuse)
+ monkeypatch.setattr(ssl, "_create_default_https_context",
+ lambda: ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT))
+ llm._urlopen(_head(), 5)
+ assert urlopen_calls == [{"timeout": 5}]
+
+
+class TestHandshake:
+ """Real TLS against a local endpoint that only the OS file can vouch for."""
+
+ @staticmethod
+ def _os_file_trusts(mac, pki):
+ mac.os_file.write_text(ssl.DER_cert_to_PEM_cert(pki["trusted"]["ca"]))
+
+ @staticmethod
+ def _refused(srv):
+ with pytest.raises(urllib.error.URLError) as raised:
+ llm._urlopen(_head(), 5)
+ assert isinstance(raised.value.reason, ssl.SSLCertVerificationError)
+ _review()
+ assert llm.last_review_failed()
+ assert srv.calls == []
+
+ def test_a_review_runs(self, mac, pki, https_api):
+ srv = https_api("trusted")
+ self._os_file_trusts(mac, pki)
+ _review()
+ assert not llm.last_review_failed()
+ assert len(srv.calls) == 1
+
+ def test_without_the_os_file_the_review_fails(self, mac, https_api):
+ srv = https_api("trusted")
+ mac.os_file.unlink()
+ self._refused(srv)
+
+ @pytest.mark.parametrize("server", ["untrusted", "other-host"])
+ def test_a_certificate_it_does_not_cover_is_still_refused(
+ self, mac, pki, https_api, server):
+ srv = https_api(server)
+ self._os_file_trusts(mac, pki)
+ self._refused(srv)
diff --git a/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py b/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py
index c76aa8aa..89452630 100644
--- a/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py
+++ b/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py
@@ -85,6 +85,8 @@ def store(monkeypatch):
# The store is checked once per process.
monkeypatch.setattr(llm, "_store_tls_context", llm._STORE_TLS_UNSET)
monkeypatch.setattr(llm, "_store_certs_skipped", 0)
+ # Not this machine's: a Mac whose Python has no certificates.
+ monkeypatch.setattr(llm, "_ON_MACOS", False)
for var in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy",
"ALL_PROXY", "all_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR"):
monkeypatch.delenv(var, raising=False)
diff --git a/plugins/security-guidance/tests/test_unmatched_bash_metric.py b/plugins/security-guidance/tests/test_unmatched_bash_metric.py
index 8933bbd1..9c49f6c4 100644
--- a/plugins/security-guidance/tests/test_unmatched_bash_metric.py
+++ b/plugins/security-guidance/tests/test_unmatched_bash_metric.py
@@ -66,8 +66,10 @@ def test_one_call_in_ten_is_sampled():
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)")
+ assert hook._GIT_COMMIT_RE.pattern.endswith(
+ rf"{hook._WORD_GAP}commit\b(?!-)|\bgt{hook._WORD_GAP}(?:create|modify)\b")
+ assert hook._GIT_PUSH_RE.pattern.endswith(
+ rf"{hook._WORD_GAP}push\b|\bgt{hook._WORD_GAP}submit\b)")
def _commands():