diff options
| author | Claude <noreply@anthropic.com> | 2026-11-05 22:32:49 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-05 22:32:49 +0000 |
| commit | de917f463b5dbdd924d6299e96d1b9e489339488 (patch) | |
| tree | 494357518efe808e65ff987921d5a6584323e849 /plugins | |
| parent | 6ba0afbdce92bdafd4b3c7323ba57328455257f4 (diff) | |
| parent | d189be9fc7a63d53d4e2af59accdd70e933e41e9 (diff) | |
Merge main into mhegazy/sg-interp-reparse-telemetrymhegazy/sg-interp-reparse-telemetry
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
20 files changed, 2179 insertions, 249 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index bae789b4..e0c4a888 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -68,6 +68,7 @@ Claude Code does not pass your sign-in to plugins in a session started with `CLA | `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) | +| `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 @@ -116,12 +117,14 @@ The plugin sends data to a model endpoint to perform its reviews. Specifically, Where that data goes depends on your Claude Code configuration: - **Default (Anthropic API / subscription):** sent to `api.anthropic.com` and handled under Anthropic's [Commercial Terms](https://www.anthropic.com/legal/commercial-terms) and [Privacy Policy](https://www.anthropic.com/legal/privacy). -- **LLM gateway** (`ANTHROPIC_BASE_URL` set): sent to your gateway URL instead, with the headers in `ANTHROPIC_CUSTOM_HEADERS` (except `anthropic-beta`). The gateway operator's terms apply. +- **LLM gateway** (`ANTHROPIC_BASE_URL` set to a URL): sent to your gateway URL instead, with the headers in `ANTHROPIC_CUSTOM_HEADERS` (except `anthropic-beta`). The gateway operator's terms apply. - **Claude apps gateway, signed in with `/login`:** your installed Claude Code sends the reviews to the gateway, using its own stored sign-in. The plugin never reads the sign-in. The gateway operator's terms apply. - **3rd-party providers** (Bedrock / Vertex / Foundry / Mantle): sent to your configured provider endpoint. The provider's data-handling terms apply (e.g., AWS / GCP / Azure). The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata, finding categories, the Agent SDK's own warnings and errors, and up to 20 lines of stderr from each Claude Code run the plugin starts for a review (20 in all for each agentic commit review, which starts several runs) — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded. +The agentic commit reviewer, and every review on a 3rd-party provider, runs an inner Claude Code through the Agent SDK. The plugin starts it with `--no-session-persistence`, so these runs are not saved as session transcripts under `~/.claude/projects/`. Set `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` to keep them, for example to debug a review; a saved transcript contains the full review prompt, including diff hunks, and is removed by Claude Code's normal session cleanup (`cleanupPeriodDays`). A Claude Code older than 2.0.63 does not have the flag; the review then runs without it and is saved as before. + ### Review usage and cost The LLM reviews use your API path, so they cost tokens (or subscription usage) on top of your own session. The default reviewer is the newest Opus model. On the Anthropic API path the diff review on Stop calls the API directly, so it does not appear in Claude Code's own cost figures or transcripts. After each review the plugin writes one line to its debug log: @@ -145,6 +148,8 @@ This is a best-effort assistive tool, not a guarantee. Treat findings as suggest **Plugin doesn't seem to fire** — check that `~/.claude/claude-security-guidance.md` (or hook activity) shows in debug logs. Run Claude Code with `--debug-file /tmp/claude/debug.txt` and grep for `security_reminder_hook`. The plugin also writes its own log to `~/.claude/security/log.txt`. +**Looking into one commit review** — set `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` before the run; the reviewer's prompt, tool calls and answer are then kept as session transcripts under `~/.claude/projects/`. + **Review never finds anything** — verify your API path works, and that credentials reach the plugin (see [Credentials](#credentials)): `~/.claude/security/log.txt` says `no API credentials` when they don't. When a commit or push review gets no usable answer from the model, Claude is told once per session for each kind of review and failure (for example "Commit security review did not complete: …"), and the reason is logged. If a commit whose review failed is pushed later from Claude Code, the push review checks it. On 3P providers, if you set `SECURITY_REVIEW_MODEL`, check it is a provider-specific id your account can invoke. On LLM gateways, check the gateway's logs for `POST /v1/messages` traffic from the plugin. In a session signed in to a Claude apps gateway with `/login`, reviews run only when `claude auth status` shows the gateway and that you are logged in. They run through the Claude Code at `~/.local/bin/claude`, where the native installer puts it on macOS and Linux. On Windows, or for any other install, set `SG_AGENTIC_CLI_PATH` to its full path. **Too many false positives** — set `SECURITY_REVIEW_MODEL` to a cheaper model (`claude-sonnet-5-5`) and re-evaluate; if precision is the priority, stay on the default. diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 9ba40385..34655335 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -13,11 +13,12 @@ import sys import time from _base import debug_log, portable_output, _PV +import gitutil from gitutil import ( GIT_CMD, _git_dir, _git_toplevel, _git_status_porcelain, _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, - index_entry_count, + _secret_rename_origins, index_entry_count, ) from session_state import with_locked_state from extensibility import _same_dir @@ -319,7 +320,7 @@ def get_baseline_file_content(session_id, file_path, cwd): # How the last capture_git_baseline call got its SHA: 0 a real snapshot, -# 1 `stash create` failed and HEAD was returned, 2 no index copy and HEAD was +# 1 the snapshot failed and HEAD was returned, 2 no index copy and HEAD was # returned. With 1 or 2 the next Stop review cannot tell the turn's changes # from uncommitted work that was already there. Stored with baseline_sha. # Telemetry only. @@ -328,29 +329,110 @@ last_baseline_fail = 0 last_index_entries = None +# Who the snapshot commit is made by. Set on every commit-tree call, so the +# user's own name never appears on a commit they did not make and a repo with +# no identity configured still works. The commit object does land in +# `.git/objects`, but nothing refers to it, like the one `git stash create` +# used to make here: it is prunable from the moment it is written. +_SNAPSHOT_IDENT = { + "GIT_AUTHOR_NAME": "security-guidance", "GIT_AUTHOR_EMAIL": "security-guidance@localhost", + "GIT_COMMITTER_NAME": "security-guidance", "GIT_COMMITTER_EMAIL": "security-guidance@localhost", +} + +# The whole snapshot, not one command: `stash create` was capped at 15 s and a +# per-command cap would let a slow filesystem hold the prompt for far longer. +_SNAPSHOT_BUDGET_S = 15 + + +def _snapshot_commit(cwd, env, head_tree): + """A commit of every tracked change, on the index copy `env` names. + + Returns its SHA, "" when nothing tracked has changed (so the caller uses + HEAD, `head_tree` being HEAD's tree), or None when git refused or the + time budget ran out. + + No `--missing-ok`: git counts a partial clone's promisor blobs as + present, so write-tree neither fetches nor fails on one, and the + existence check it would turn off is worth keeping. + """ + deadline = time.monotonic() + _SNAPSHOT_BUDGET_S + + def run(args, extra=None): + left = deadline - time.monotonic() + if left <= 0: + raise subprocess.TimeoutExpired(args, _SNAPSHOT_BUDGET_S) + return subprocess.run( + [*GIT_CMD, *args], cwd=cwd, capture_output=True, timeout=left, + env={**env, **(extra or {})}, + ) + + # No pathspec: `add -u` has staged the whole work tree, whatever directory + # of it `cwd` is, since git 2.0. `-- :/` would say the same but fails + # outright under a user's GIT_LITERAL_PATHSPECS. + add = run(["add", "-u"]) + if add.returncode != 0: + debug_log(f"Snapshot: add -u failed: {_stderr_of(add)}") + return None + tree = run(["write-tree"]) + sha = (tree.stdout or b"").decode("utf-8", errors="replace").strip() + if tree.returncode != 0 or not sha: + debug_log(f"Snapshot: write-tree failed: {_stderr_of(tree)}") + return None + if sha == head_tree: + return "" + if gitutil.last_dropped_gitlinks: + # A nested repository's entry is gone from the index copy, so the + # tree cannot equal HEAD's even on a clean work tree. Ask whether + # anything but those entries differs, rather than writing a commit + # object on every prompt in a repo with submodules. + same = run(["diff-tree", "--quiet", "--ignore-submodules=all", head_tree, sha]) + if same.returncode == 0: + return "" + commit = run(["-c", "commit.gpgsign=false", "commit-tree", sha, "-p", "HEAD", + "-m", "security-guidance turn baseline"], _SNAPSHOT_IDENT) + out = (commit.stdout or b"").decode("utf-8", errors="replace").strip() + if commit.returncode != 0 or not out: + debug_log(f"Snapshot: commit-tree failed: {_stderr_of(commit)}") + return None + return out + + +def _stderr_of(result): + return (result.stderr or b"").decode("utf-8", errors="replace").strip()[:200] + + def capture_git_baseline(cwd): """ Capture a git ref representing the current working tree state. - Uses `git stash create` which creates a commit object for the current state - (HEAD + uncommitted changes) without modifying the stash list or working tree. + Builds a commit object for the current state (HEAD + uncommitted changes) + without touching the stash list or the working tree: `add -u` stages every + tracked change into a throwaway index copy, `write-tree` turns that into a + tree, and `commit-tree` hangs it off HEAD. Falls back to HEAD if the working tree is clean. Returns the SHA string, or None if not in a git repo or if the repo has no commits. - `stash create` runs on a throwaway copy of the index (GIT_INDEX_FILE), so - its `index.lock` and `index.stash.<pid>` files land next to the copy, not - in `.git`: it cannot collide with a concurrent git command, and a timeout - kill cannot leave a lock that blocks the user's next one. - GIT_OPTIONAL_LOCKS does not cover stash. Copying the real index without a - lock is safe: git replaces it by atomic rename. - - NOTE: `git stash create` does NOT capture untracked files. UPS pairs this + This was `git stash create`, which does the same thing in one command but + checks the work tree on a single thread, while `add -u` uses git's index + preload (one thread per 500 entries, up to 20). On a filesystem where each + file status is slow — a WSL repository on a Windows drive, a network mount + — that is the whole cost of the prompt: see #6854, where `stash create` + took 4 s on 1,424 files and never finished on 10,000. + + The commands run on a throwaway copy of the index (GIT_INDEX_FILE), so + their `index.lock` lands next to the copy, not in `.git`: they cannot + collide with a concurrent git command, and a timeout kill cannot leave a + lock that blocks the user's next one. GIT_OPTIONAL_LOCKS does not cover + these. Copying the real index without a lock is safe: git replaces it by + atomic rename. + + NOTE: the snapshot does NOT capture untracked files. UPS pairs this SHA with a `_list_untracked()` snapshot stored as `untracked_at_baseline`, and `compute_v2_review_set` subtracts that set so pre-existing untracked files are not reviewed as Claude-authored. UPS takes no snapshot while the Stop review, its only reader, is switched off. """ # stdout is a SHA so text=True is safe on stdout, but a non-ASCII - # filename in `git stash create`'s STDERR warning (e.g. a worktree + # filename in git's STDERR warning (e.g. a worktree # with `Ávila_report.txt` triggers a quotePath/locale warning) would # trip the stderr reader thread on Windows cp1252. Decode both streams # leniently for symmetry with _list_untracked. See #2056. @@ -358,15 +440,19 @@ def capture_git_baseline(cwd): last_baseline_fail = 0 last_index_entries = None try: - # Check if HEAD exists (i.e., repo has at least one commit) + # HEAD's commit and its tree in one call: the commit is the answer + # for a clean tree, the tree is what the snapshot is compared with. + # A failure here means the repo has no commits — skip the review + # rather than create commits in the user's repo. head_check = subprocess.run( - [*GIT_CMD, "rev-parse", "HEAD"], + [*GIT_CMD, "rev-parse", "HEAD", "HEAD^{tree}"], cwd=cwd, capture_output=True, timeout=5 ) - if head_check.returncode != 0: - # No commits yet — skip review rather than creating commits in the user's repo + head_out = (head_check.stdout or b"").decode("utf-8", errors="replace").split() + if head_check.returncode != 0 or len(head_out) != 2: debug_log("No commits in repo, skipping baseline capture") return None + head_sha, head_tree = head_out sha = "" # untracked_paths=[]: a plain copy of the index, no `add -N` pass. @@ -375,25 +461,14 @@ def capture_git_baseline(cwd): # back to HEAD. if env is not None: last_index_entries = index_entry_count(env["GIT_INDEX_FILE"]) - result = subprocess.run( - [*GIT_CMD, "stash", "create"], - cwd=cwd, capture_output=True, timeout=15, env=env - ) - sha = (result.stdout or b"").decode("utf-8", errors="replace").strip() - if not sha and result.returncode != 0: + sha = _snapshot_commit(cwd, env, head_tree) + if sha is None: last_baseline_fail = 1 + sha = "" else: last_baseline_fail = 2 - if sha: - return sha - - # Working tree is clean — stash create returns empty. Use HEAD. - result = subprocess.run( - [*GIT_CMD, "rev-parse", "HEAD"], - cwd=cwd, capture_output=True, timeout=5 - ) - sha = (result.stdout or b"").decode("utf-8", errors="replace").strip() - return sha if sha else None + # No snapshot: nothing tracked has changed, or it could not be taken. + return sha or head_sha except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: debug_log(f"Failed to capture git baseline: {e}") return None @@ -997,12 +1072,12 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel review_set = (files dirty vs current HEAD, plus files committed this turn when HEAD advanced linearly) ∩ (files whose content differs from the - pre-turn stash baseline). The first term is immune to checkout/pull + pre-turn baseline). The first term is immune to checkout/pull ballooning; the second filters out the user's untouched pre-turn WIP. Falls back to dirty_now alone when no baseline is available. untracked_at_baseline: {repo-root-relative path: mtime_ns} captured at - UPS. `git stash create` doesn't include untracked files, so without this + UPS. The baseline snapshot doesn't include untracked files, so without this snapshot a pre-existing untracked file looks "new since baseline" forever. A file is excluded only if it was untracked at baseline AND its mtime is unchanged — an in-place edit during the turn is still reviewed. @@ -1073,11 +1148,11 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel dirty_now |= _git_name_only(repo, f"{head_at_capture}..HEAD") or set() diff_base = head_at_capture - # changed_since: tracked files vs the stash baseline (no `add -N` — the - # stash never contained untracked files anyway), then union with + # changed_since: tracked files vs the turn baseline (no `add -N` — the + # baseline never contained untracked files anyway), then union with # currently-untracked. The previous `include_untracked=True` arm cost a # full `git add -N .` (slow in large repos) per call to surface - # untracked files in the diff output — but `git diff <stash>` already + # untracked files in the diff output — but `git diff <baseline>` already # lists them as "only in worktree" without that, and we have the explicit # set from status regardless. if baseline_sha: @@ -1087,9 +1162,13 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel else: changed_since = None # changed_since is None on missing baseline OR on git error (e.g. the - # dangling stash SHA was pruned). Either way, don't intersect with ∅ — + # dangling baseline SHA was pruned). Either way, don't intersect with ∅ — # that would silently zero the review set. Fall back to dirty_now. review_set = (dirty_now & changed_since) if changed_since is not None else dirty_now + # Kept beside its new name so that the content diff pairs the two. + secret_origins = { + old for new, old in _secret_rename_origins.items() if new in review_set} + review_set = review_set | secret_origins review_paths = [os.path.join(repo, p) for p in sorted(review_set)] untracked_in_review = sorted(new_untracked & review_set) @@ -1101,4 +1180,6 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel # Only emit when nonzero to stay under the 10-key telemetry cap. if preexisting_unchanged: metrics["preexisting_untracked_excluded"] = len(preexisting_unchanged) + if secret_origins: + metrics["secret_renamed"] = len(secret_origins) return review_paths, diff_base, repo, untracked_in_review, metrics diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 75d08298..c80d0600 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -331,12 +331,17 @@ _path_list_too_long = set() # A failed `git add --intent-to-add` during this hook run, for the Stop hook's # metrics: kind * 100000 + the paths the add was given. One number because a -# review row is near CC's key cap. A failed add leaves the new files out of the -# diff, so a turn that only added files looks like a turn with no changes; a -# timeout loses the whole diff. kind: 1 git could not write the empty blob to -# the object store, 2 any other git error, 3 timeout. A git that speaks another -# language counts as 2. -_add_failed = {"code": 0} +# review row is near CC's key cap. kind: 1 git could not write the empty blob +# to the object store and the retry failed too, 2 any other git error, 3 +# timeout, 4 the retry with a private object directory worked. A git that +# speaks another language reports a failed retry as 2. With 1 to 3 the new +# files are not in the diff, so a turn that only added files looks like a turn +# with no changes. `left_out` says so for the last get_git_diff alone: the code +# stays set through a fallback diff that worked. +_add_failed = {"code": 0, "left_out": False} + +# Next to an index copy: where a retried `git add -N` stores the empty blob. +_OBJECTS_DIR_SUFFIX = ".objects" def _too_many_args(e): @@ -434,8 +439,9 @@ def _owner_is_gone(name): def _sweep_stale_indexes(dirpath, uid): - """Delete index copies in `dirpath` that a killed run left behind. Only - regular files owned by `uid` (None: no ownership check) are touched. + """Delete index copies in `dirpath` that a killed run left behind, and + their private object directories. Only regular files and directories owned + by `uid` (None: no ownership check) are touched. A copy goes as soon as the hook that made it is gone: a killed hook can leave one per run, and index-sized files fill a disk long before the age @@ -458,12 +464,16 @@ def _sweep_stale_indexes(dirpath, uid): p = os.path.join(dirpath, name) try: st = os.lstat(p) - if not stat.S_ISREG(st.st_mode): + is_dir = stat.S_ISDIR(st.st_mode) and name.endswith(_OBJECTS_DIR_SUFFIX) + if not (is_dir or stat.S_ISREG(st.st_mode)): continue if uid is not None and st.st_uid != uid: continue if max(st.st_mtime, st.st_ctime) < cutoff or _owner_is_gone(name): - os.unlink(p) + if is_dir: + _remove_objects_dir(p) + else: + os.unlink(p) if time.monotonic() > deadline: return except OSError: @@ -567,6 +577,24 @@ def _copy_slot(tmpdir, index_bytes=0): os.close(held) +def _remove_objects_dir(path): + """Remove a private object directory. git writes objects read-only, which + stops Windows from deleting them.""" + import shutil + import stat + + def writable_then_retry(func, p, _exc): + # Not a link: chmod would follow it to whatever it points at. + if func in (os.unlink, os.rmdir) and not os.path.islink(p): + os.chmod(p, stat.S_IWRITE) + func(p) + + try: + shutil.rmtree(path, onerror=writable_then_retry) + except OSError: + pass + + def _remove_copy(tmp_index): """Remove an index copy and the files git wrote next to it.""" import glob @@ -575,6 +603,7 @@ def _remove_copy(tmp_index): os.unlink(p) except OSError: pass + _remove_objects_dir(tmp_index + _OBJECTS_DIR_SUFFIX) def remove_copies_on_termination(): @@ -633,6 +662,75 @@ def _hook_tmpdir(): def _note_add_failure(kind, paths): _add_failed["code"] = kind * 100000 + min(len(paths), 99999) + _add_failed["left_out"] = kind != 4 + + +def _env_with_private_objects(env, cwd, objects_dir): + """`env` for a git that writes objects to `objects_dir` and still reads + the repository's own, wherever git says they are (a linked worktree shares + them). A path holding the list separator is left out, since git would + split it; the add then fails only if it has to read an object.""" + out = {**env, "GIT_OBJECT_DIRECTORY": objects_dir} + try: + r = subprocess.run([*GIT_CMD, "rev-parse", "--git-path", "objects"], + cwd=cwd, capture_output=True, timeout=5, env=env) + except (subprocess.TimeoutExpired, OSError): + return out + own = os.path.join(cwd, os.fsdecode(r.stdout).strip()) + if r.returncode == 0 and os.pathsep not in own: + out["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = os.pathsep.join( + p for p in (own, env.get("GIT_ALTERNATE_OBJECT_DIRECTORIES")) if p) + return out + + +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 + user who cannot write the object store gets a second try that stores it in + a private directory next to the copy. Nothing needs that blob afterwards: + `git diff` reads these files from the work tree. `git stash create` would + fail on such an index, and only runs on a copy with nothing added. + + No stdout used here (only returncode matters), but text=True still spawns + 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" + + def add(add_env): + results = _run_git_on_review_paths( + ["add", "--intent-to-add"], paths, timeout=10, cwd=cwd, env=add_env) + return next((r for r in results if r.returncode != 0), None) + + try: + failed = add(env) + except subprocess.TimeoutExpired: + # No retry: git is slow here, not refused. The diff goes on for the + # tracked files, so a timeout on every turn cannot stop their reviews. + _note_add_failure(3, paths) + return + if not failed: + return + debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") + # Whatever happens to the retry, the diff goes on for the tracked files. + try: + objects_dir = tmp_index + _OBJECTS_DIR_SUFFIX + os.mkdir(objects_dir, 0o700) + retry_failed = add(_env_with_private_objects(env, cwd, objects_dir)) + if retry_failed: + debug_log(f"git add -N retry failed: {retry_failed.stderr[:200].decode('utf-8', errors='replace')}") + except (subprocess.TimeoutExpired, OSError) as e: + debug_log(f"git add -N retry failed: {e}") + retry_failed = True + if retry_failed: + _note_add_failure(1 if b"empty blob" in failed.stderr else 2, paths) + else: + _note_add_failure(4, paths) @contextlib.contextmanager @@ -721,24 +819,7 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths): else: add_args = None if add_args: - # No stdout used here (only returncode matters), but text=True - # still spawns 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. - try: - results = _run_git_on_review_paths( - ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd, - # The paths are file names, not patterns, for this git add - # only: an untracked file named `:(glob)**` must add only - # itself. - env={**env, "GIT_LITERAL_PATHSPECS": "1"}) - except subprocess.TimeoutExpired: - _note_add_failure(3, add_args) - raise - failed = next((r for r in results if r.returncode != 0), None) - if failed: - _note_add_failure(1 if b"empty blob" in failed.stderr else 2, add_args) - debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") + _add_new_files(cwd, add_args, env, tmp_index) # A whole-tree add puts a nested repository back. if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index): yield None @@ -830,6 +911,11 @@ def _gitlink_paths(top, env): return found +# True when the last _drop_gitlinks call removed at least one gitlink, so the +# index copy and HEAD can no longer have the same tree even on a clean tree. +last_dropped_gitlinks = False + + def _drop_gitlinks(top, env, tmp_index): """Remove the gitlink (mode 160000) entry of every nested repository from the index copy that `env` names, never from the real index, before @@ -841,6 +927,8 @@ def _drop_gitlinks(top, env, tmp_index): `git stash create` fails on the empty directory. `top` is the work tree's top directory. Returns True on success, False on any failure; the copy must not be used then.""" + global last_dropped_gitlinks + last_dropped_gitlinks = False try: if not _may_have_gitlinks(tmp_index): return True @@ -865,6 +953,7 @@ def _drop_gitlinks(top, env, tmp_index): return False # Keep the mtime the copy came with; see _copied_index. os.utime(tmp_index, ns=(mtime_ns, mtime_ns)) + last_dropped_gitlinks = True debug_log(f"gitlink entries (nested repositories) removed from the " f"index copy: {len(nested)}; their contents are not reviewed") return True @@ -1094,6 +1183,18 @@ def _git_reflog_recent_commits(repo_root, max_age_s=120, max_n=5): return fresh, stale +# New name -> secret-shaped old name, for the renames and copies git reported +# during this hook run. The Stop review limits its diff to a list of paths: +# with only the new name in it, git shows the secret's content as a new file, +# and the diff parsers cannot tell it came from a name they leave out. +_secret_rename_origins = {} + + +def _note_rename(old_path, new_path): + if _is_secret_shaped(old_path): + _secret_rename_origins[new_path] = old_path + + 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 @@ -1113,7 +1214,7 @@ def _git_name_only(cwd, base, include_untracked=False): def _run(env): # core.quotePath=false comes from GIT_CMD globally (see definition). result = subprocess.run( - [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base], + [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-status", "-z", base], cwd=cwd, capture_output=True, timeout=30, env=env, ) @@ -1122,7 +1223,18 @@ def _git_name_only(cwd, base, include_untracked=False): 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") - return {p for p in stdout.split("\0") if p} + # 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 + return names try: # The diff only reads the index (diff.autoRefreshIndex is off in @@ -1183,6 +1295,8 @@ def _git_status_porcelain(cwd): # 2-char-status entry. if "R" in xy or "C" in xy: i += 1 + if i < len(entries): + _note_rename(entries[i], path) i += 1 return tracked, untracked except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: @@ -1489,6 +1603,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa MAX_FILE_DIFF_BYTES is cut down to its added lines. """ _path_list_too_long.clear() + _add_failed["left_out"] = False pathspec = _diff_pathspec(cwd, paths) if paths and not pathspec: # Caller restricted to specific paths but none are inside this repo diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index aa201235..c0a878f4 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -17,6 +17,7 @@ Two reassignable globals here are read by handlers in ``_last_review_truncated_bytes``. Handlers reference them as ``llm.X`` (not via ``from``-import) so they observe reassignment. """ +import contextlib import hashlib import json import logging @@ -195,10 +196,13 @@ def _anthropic_base_url() -> str: Honors ANTHROPIC_BASE_URL (the convention the Anthropic SDK and CC itself use) so customers behind an LLM gateway (LiteLLM, Bifrost, self-hosted Anthropic-compatible proxy) can route the plugin's reviews through their - gateway. Defaults to https://api.anthropic.com. Always returns a string - with no trailing slash so callers can safely append /v1/messages etc. + gateway. Defaults to https://api.anthropic.com, also when the variable is + set but blank, which is how the SDK and CC read it. Always returns a + string with no trailing slash so callers can safely append /v1/messages + etc. """ - return os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com").rstrip("/") + base = os.environ.get("ANTHROPIC_BASE_URL", "").strip() + return (base or "https://api.anthropic.com").rstrip("/") # ── Windows certificate store with an entry OpenSSL cannot read ────────── @@ -282,6 +286,10 @@ def _urlopen(request, timeout): return urllib.request.urlopen(request, timeout=timeout, context=_store_tls_context) +def _is_remote_session() -> bool: + return os.environ.get("CLAUDE_CODE_REMOTE", "").lower() in ("1", "true", "yes", "on") + + def _probe_anthropic(timeout: float = 5.0) -> bool: req = urllib.request.Request(_anthropic_base_url() + "/", method="HEAD") try: @@ -420,7 +428,7 @@ def ensure_anthropic_reachable() -> bool: global _anthropic_reachable if _anthropic_reachable is not None: return _anthropic_reachable - if os.environ.get("CLAUDE_CODE_REMOTE", "").lower() not in ("1", "true", "yes", "on"): + if not _is_remote_session(): _anthropic_reachable = True return True if _probe_anthropic(): @@ -1050,7 +1058,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, system_prompt=CLAUDE_CODE_SYSTEM_PROMPT, cli_path=cli_path, allowed_tools=[], - extra_args=_only_tools_args(), + extra_args={**_only_tools_args(), **_reviewer_session_args()}, setting_sources=[], max_turns=2, model=chosen_model, @@ -1077,9 +1085,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, _record_usage(getattr(msg, "usage", None) or {}, chosen_model, cost_usd=getattr(msg, "total_cost_usd", None)) elif getattr(msg, "subtype", None) == "api_retry": - data = getattr(msg, "data", None) - status = data.get("error_status") if isinstance(data, dict) else None - _retried_after.add(str(status) if isinstance(status, int) else "no response") + status = _api_retry_status(msg) + _retried_after.add(str(status) if status is not None else "no response") return structured # 60s ceiling: a single review request on a healthy 3P endpoint completes @@ -1840,6 +1847,32 @@ def _send_sdk_logs_to_debug_log() -> None: sdk_logger.propagate = False +# Claude Code older than 2.0.63 exits at startup with "unknown option" when +# given --no-session-persistence. The flag is sent until an inner CLI +# refuses it. +_SESSION_FLAG = "no-session-persistence" +_send_session_flag = True + + +def _reviewer_session_args() -> Dict[str, Optional[str]]: + """Extra CLI flags for the SDK-spawned inner `claude`. + + Review runs are one-shot and never resumed, so by default the inner CLI + is told not to save them as session transcripts (they hold the full + review prompt, including diff hunks). SECURITY_GUIDANCE_PERSIST_SESSIONS=1 + keeps the transcripts, e.g. to debug a review. + """ + keep = os.environ.get("SECURITY_GUIDANCE_PERSIST_SESSIONS", "").strip().lower() + if not _send_session_flag or keep in ("1", "on", "true", "yes"): + return {} + return {_SESSION_FLAG: None} + + +def _names_session_flag(stderr_line: Any) -> bool: + text = str(stderr_line) + return _SESSION_FLAG in text and "unknown option" in text.lower() + + # The agentic reviewer reads a diff it must not trust, so it gets # file-reading tools and nothing else. _REVIEWER_TOOLS = ("Read", "Grep", "Glob") @@ -1874,22 +1907,57 @@ def _names_strict_mcp_flag(stderr_line: Any) -> bool: return "--strict-mcp-config" in str(stderr_line) +def _refused_flags(stderr_lines: List[Any]) -> List[str]: + """Which of the flags this plugin can leave out the lines refuse.""" + refused = [] + if any(_names_strict_mcp_flag(l) for l in stderr_lines): + refused.append("--strict-mcp-config") + if any(_names_session_flag(l) for l in stderr_lines): + refused.append("--" + _SESSION_FLAG) + return refused + + def _run_inner_cli(start: Callable[[], Any], stderr_lines: List[str]) -> Any: """start() runs one inner CLI to its result; stderr_lines receives what that CLI writes to stderr. A start the CLI refused over - --strict-mcp-config is made once more without the flag, and the flag is - left out for the rest of this process.""" - global _send_strict_mcp - del stderr_lines[:] - try: - return start() - except Exception: - if not any(_names_strict_mcp_flag(l) for l in stderr_lines): - raise - _send_strict_mcp = False - debug_log("inner CLI refused --strict-mcp-config; starting it again without the flag") + --strict-mcp-config or --no-session-persistence is made again without + that flag, and the flag is left out for the rest of this process. A CLI + names one flag per start, so one that refuses both is started three + times.""" + global _send_strict_mcp, _send_session_flag + left_out: List[str] = [] + while True: del stderr_lines[:] - return start() + try: + return start() + except Exception: + refused = [f for f in _refused_flags(stderr_lines) if f not in left_out] + if not refused: + raise + if "--strict-mcp-config" in refused: + _send_strict_mcp = False + if "--" + _SESSION_FLAG in refused: + _send_session_flag = False + left_out += refused + debug_log(f"inner CLI refused {' and '.join(refused)}; " + "starting it again without") + + +class _ReviewerAuthFailed(Exception): + """The agentic reviewer's credentials were refused; retrying cannot help.""" + + +# Retry notices in a row, each after a 401, at which the review stops. One is +# normal: the CLI renews a stored login after a 401 and tries again. Not used +# in a remote session, where the CLI waits out a short sign-in outage on purpose. +_AGENTIC_MAX_401_RETRIES = 3 + + +def _api_retry_status(msg: Any) -> Optional[int]: + """The HTTP status of the CLI's api_retry notice, if it gives one.""" + data = getattr(msg, "data", None) + status = data.get("error_status") if isinstance(data, dict) else None + return status if isinstance(status, int) else None def _agentic_spawn_env() -> Dict[str, str]: @@ -2079,15 +2147,15 @@ def _agentic_review( # Without a callback the inner CLI writes to this hook's stderr, which # Claude Code shows Claude as the review notice. Log it instead. child_stderr_lines = [0] - # Lines of the current start that name --strict-mcp-config (_run_inner_cli). + # Lines of the current start that refuse a flag (_run_inner_cli). flag_refusals: List[str] = [] def _child_stderr_metric() -> Dict[str, int]: return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {} def _on_child_stderr(line: str) -> None: - if _names_strict_mcp_flag(line): - # Not counted: where the flag is refused, every review gets this + if _refused_flags([line]): + # Not counted: where a flag is refused, every review gets this # line once, from the start that is then made again. flag_refusals.append(str(line)) debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}") @@ -2113,7 +2181,8 @@ def _agentic_review( # Pre-approved, and the only tools the reviewer has: no # permission mode can then let it write, run or fetch anything. allowed_tools=list(_REVIEWER_TOOLS), - extra_args=_only_tools_args(_REVIEWER_TOOLS), + extra_args={**_only_tools_args(_REVIEWER_TOOLS), + **_reviewer_session_args()}, setting_sources=[], max_turns=turns if turns is not None else max_turns, model=model, @@ -2172,39 +2241,54 @@ def _agentic_review( # Blocks are matched by shape so older SDK builds need no extra import. file_tool_ids = set() - async for msg in query(prompt=_once(), options=opts): - if isinstance(msg, AssistantMessage): - n += 1 - for b in getattr(msg, "content", None) or []: - if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS - and getattr(b, "id", None)): - file_tool_ids.add(b.id) - ctx["rv_tool_calls"] += 1 - elif isinstance(msg, ResultMessage): - subtype = msg.subtype - if msg.structured_output is not None: - structured = msg.structured_output - # SDK ResultMessage carries aggregate usage + cache-aware - # cost across the whole multi-turn run; prefer its cost over - # the price-table estimate. getattr guards older SDK builds. - _record_usage(getattr(msg, "usage", None) or {}, model, - cost_usd=getattr(msg, "total_cost_usd", None)) - for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): - value = getattr(msg, attr, None) - # Counting must never fail the review: anything that - # is not a positive finite number adds nothing. - if (isinstance(value, (int, float)) and not isinstance(value, bool) - and 0 < value < float("inf")): - ctx[key] += int(value) - else: - # Tool results come back as user messages. - content = getattr(msg, "content", None) - if isinstance(content, list): - ctx["rv_tool_err"] += sum( - 1 for b in content - if getattr(b, "is_error", None) is True - and getattr(b, "tool_use_id", None) in file_tool_ids - ) + auth_retries = 0 + # Closed on the way out, also on a raise, so the CLI stops with the review. + async with contextlib.aclosing(query(prompt=_once(), options=opts)) as messages: + async for msg in messages: + if isinstance(msg, AssistantMessage): + # Old CLIs answer each refused request by asking the model + # again, hundreds of times; the message is the same on all. + if getattr(msg, "error", None) == "authentication_failed": + raise _ReviewerAuthFailed("authentication_failed") + auth_retries = 0 + n += 1 + for b in getattr(msg, "content", None) or []: + if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS + and getattr(b, "id", None)): + file_tool_ids.add(b.id) + ctx["rv_tool_calls"] += 1 + elif isinstance(msg, ResultMessage): + subtype = msg.subtype + if msg.structured_output is not None: + structured = msg.structured_output + # SDK ResultMessage carries aggregate usage + cache-aware + # cost across the whole multi-turn run; prefer its cost over + # the price-table estimate. getattr guards older SDK builds. + _record_usage(getattr(msg, "usage", None) or {}, model, + cost_usd=getattr(msg, "total_cost_usd", None)) + for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): + value = getattr(msg, attr, None) + # Counting must never fail the review: anything that + # is not a positive finite number adds nothing. + if (isinstance(value, (int, float)) and not isinstance(value, bool) + and 0 < value < float("inf")): + ctx[key] += int(value) + elif getattr(msg, "subtype", None) == "api_retry": + # A gateway's 401 without the API's x-should-retry: false + # keeps the CLI retrying for about three minutes. + auth_retries = auth_retries + 1 if _api_retry_status(msg) == 401 else 0 + if (auth_retries >= _AGENTIC_MAX_401_RETRIES + and not _is_remote_session()): + raise _ReviewerAuthFailed(f"{auth_retries} retries after HTTP 401") + else: + # Tool results come back as user messages. + content = getattr(msg, "content", None) + if isinstance(content, list): + ctx["rv_tool_err"] += sum( + 1 for b in content + if getattr(b, "is_error", None) is True + and getattr(b, "tool_use_id", None) in file_tool_ids + ) return structured, n, subtype def _run(system: str, prompt: str, *, schema: Dict[str, Any] diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 8723710d..7c84357f 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -23,7 +23,7 @@ The plugin has two layers: ## How the git baseline works -On each UserPromptSubmit, the plugin runs `git stash create` to get a SHA representing +On each UserPromptSubmit, the plugin takes a snapshot commit to get a SHA representing the current working tree state (HEAD + any uncommitted changes). This SHA is saved to the session state file. When the Stop hook fires, it runs `git diff <baseline_sha>` to get only the changes made since that snapshot. After analysis, the baseline is updated @@ -68,6 +68,7 @@ import re import subprocess import sys import threading +import time import urllib.request from datetime import datetime from enum import IntEnum @@ -219,6 +220,9 @@ CONTINUATION_SUFFIX = ( "response." ) +# New files named in the notice for a failed `git add -N`. +_LEFT_OUT_NAMES_SHOWN = 5 + # Extra keys emit_metrics appends to every row this invocation emits. _TAIL_METRICS: Dict[str, Any] = {} # Of those, the ones that go after the others whenever they were set: a row @@ -326,6 +330,10 @@ def emit_metrics( # names on PATH were launcher aliases that cannot read the plugin files. if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": head["launcher_fallback"] = 1 + if _precheck_miss: + # Up front: this is the key that says a text check would have lost a + # review, so it must not be the one cut by the key cap. + head["precheck_miss"] = 1 usage = _usage_metrics() head.update(usage) # Why the last call got no HTTP response (api_error -1 says only that it @@ -764,7 +772,7 @@ def handle_user_prompt_submit(input_data): # The untracked snapshot has one reader: the Stop-hook diff review, which # skips before reading it when either of these switches is off (see # handle_stop_hook). Listing the worktree on every prompt then buys - # nothing, so only the stash baseline (still read by the Write pattern + # nothing, so only the turn baseline (still read by the Write pattern # filter) is captured. snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW spent = {"baseline": 0.0, "untracked": 0.0} @@ -779,15 +787,15 @@ def handle_user_prompt_submit(input_data): def _capture(repo_cwd): if not snapshot_untracked: return _timed("baseline", capture_git_baseline, repo_cwd), None - # stash-create and ls-files both walk the worktree (~2-5s each in a + # the baseline snapshot and ls-files both walk the worktree (~2-5s each in a # very large repo). Run them concurrently so UPS latency stays # ≈ max(both). import concurrent.futures as _cf with _cf.ThreadPoolExecutor(max_workers=2) as _ex: _f_sha = _ex.submit(_timed, "baseline", capture_git_baseline, repo_cwd) _f_ut = _ex.submit(_timed, "untracked", _list_untracked, repo_cwd) - # Taken whether or not the stash produced a SHA. `git stash - # create` returns empty when there are no TRACKED changes, but + # Taken whether or not the snapshot produced a SHA. The baseline + # falls back to HEAD when there are no TRACKED changes, but # pre-existing untracked files still need to be excluded from the # next Stop's review_set — otherwise an untracked-only working # tree gets every untracked file reviewed on every turn until @@ -855,7 +863,7 @@ def handle_user_prompt_submit(input_data): # When the turn began: what a Stop review in another checkout has # to go on. state["prompt_at"] = captured_at - # untracked_at_baseline is independent of whether the stash produced + # untracked_at_baseline is independent of whether the snapshot produced # a SHA, so compute_v2_review_set's preexisting-untracked exclusion # works in untracked-only trees. None means no snapshot was taken # (Stop review off): drop the previous one, which belongs to an older @@ -1060,6 +1068,47 @@ try: except ValueError: INFLIGHT_WAIT_S = 240 +# Word pairs a shell `case` pattern (`*git*commit*|*git*push*|...`) would look +# for in the raw hook input: wider than _GIT_COMMIT_RE / _GIT_PUSH_RE, so a +# command those match always contains one of these pairs in this order. +_SHELL_PRECHECK_PAIRS = ( + ("git", "commit"), ("git", "push"), + ("gt", "create"), ("gt", "modify"), ("gt", "submit"), +) +# One in this many unmatched Bash calls reports, to keep the row count down. +_UNMATCHED_BASH_SAMPLE = 10 +# Set when a command that is reviewed would not have passed the text check. +_precheck_miss = False + + +def _shell_precheck_passes(raw): + """True when `raw` holds one of _SHELL_PRECHECK_PAIRS, first word first. + + Measurement only. Tells how many hook starts that match no commit or push + a text check in the launcher could avoid (`precheck_skip`), and whether + that check would ever drop a command that is reviewed (`precheck_miss`). + """ + for first, second in _SHELL_PRECHECK_PAIRS: + at = raw.find(first) + if at != -1 and raw.find(second, at + len(first)) != -1: + return True + return False + + +def _unmatched_bash_sampled(input_data): + """Pick the same one call in _UNMATCHED_BASH_SAMPLE in every start of it. + + One Bash call can start this hook once per hooks.json entry, so the choice + is made from the call's id: all its starts report or none do. A call with + no id is not reported. + """ + tool_use_id = input_data.get("tool_use_id") + if not isinstance(tool_use_id, str) or not tool_use_id: + return False + digest = hashlib.sha256(tool_use_id.encode("utf-8", "replace")).digest() + return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0 + + def _claim_bash_hook_once(input_data): """De-dupe across hooks.json `if` matchers firing for the same Bash call. @@ -1270,18 +1319,68 @@ def is_commit_review_enabled(): COMMIT_REVIEW_ENABLED = is_commit_review_enabled() -# Seconds from the start of a commit or push review's race after which -# neither side waits for the other any longer; well inside Claude Code's -# 10-minute hook timeout. +_HOOK_STARTED = time.monotonic() + +# Seconds into the hook after which neither side of a commit or push review's +# race waits for the other any longer; well inside Claude Code's 10-minute hook +# timeout. _RACE_MAX_WAIT_S = 480 +# Seconds after which the review ends even if a side is still waiting on a +# request that does not answer, with time left to tell the session before +# 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 # api_error for a race that hit that deadline with no verdict. _RACE_TIMED_OUT = -2 +def _hook_spent_s() -> float: + return time.monotonic() - _HOOK_STARTED + +def _single_shot_review( + diff_files: List[Tuple[str, str]], + previous_findings: List[Dict[str, Any]], +) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: + """A single-shot review as (guidance, vulns, metrics); failures are in the + metrics, not raised.""" + try: + g, v = analyze_code_security( + diff_files, is_diff=True, previous_findings=previous_findings + ) + # Read on this thread: the outcome is per thread. + failed = llm.last_review_failed() + return g, v, {"agentic": False, "review_failed": failed, + "api_error": llm.last_review_status() if failed else None} + except Exception as e: + debug_log(f"single-shot review crashed: {type(e).__name__}: {e}") + return None, [], {"agentic": False, "review_failed": True, "api_error": None} + +def _single_shot_review_in_time( + diff_files: List[Tuple[str, str]], + previous_findings: List[Dict[str, Any]], +) -> Tuple[Optional[str], List[Dict[str, Any]], bool, Optional[int]]: + """A single-shot review outside a race, as (guidance, vulns, failed, status). + + It ends at _RACE_END_S into the hook, whatever is pending. + """ + done: List[Any] = [] + worker = threading.Thread( + target=lambda: done.append(_single_shot_review(diff_files, previous_findings)), + daemon=True, + ) + worker.start() + worker.join(timeout=max(0.0, _RACE_END_S - _hook_spent_s())) + if not done: + debug_log("single-shot review: nothing returned in time") + return None, [], True, _RACE_TIMED_OUT + g, v, m = done[0] + return g, v, m["review_failed"], m["api_error"] + def _agentic_review_with_race( repo_root: str, diff_files: List[Tuple[str, str]], rel_touched: List[str], previous_findings: List[Dict[str, Any]], + spent_s: float = 0.0, ) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: """Race the agentic reviewer against a delayed single-shot fallback. @@ -1293,10 +1392,13 @@ def _agentic_review_with_race( verdict) is returned so the caller never starts another review. If agentic finishes before the delay, the fallback never runs. + `spent_s`, the time the hook has already run, comes off the delay and both + limits: the hook's time limit does not restart with the race. + Metrics added: race_winner : 1 = agentic won, 2 = fallback won (CC accepts only bool/finite-number metric values — strings would discard the dict) - race_delay_s : the configured delay + race_delay_s : the delay used race_started : 1 if the fallback was actually launched, else 0 Only the commit-review and push-sweep handlers call this — external @@ -1310,13 +1412,16 @@ def _agentic_review_with_race( if os.environ.get("SG_AGENTIC_NO_RACE") == "1": return agentic_review(repo_root, diff_files, rel_touched) - delay_s = int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) + delay_s = max(0, int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) - int(spent_s)) + if spent_s >= 1: + debug_log(f"Review race: {spent_s:.0f}s already spent, fallback starts after {delay_s}s") q: "_queue.Queue[Tuple[str, Any]]" = _queue.Queue(maxsize=1) fallback_started = _th.Event() fallback_done = _th.Event() agentic_done = _th.Event() fallback_result: Dict[str, Any] = {} - deadline = _t.monotonic() + _RACE_MAX_WAIT_S + deadline = _t.monotonic() + max(0.0, _RACE_MAX_WAIT_S - spent_s) + timed_out = (None, [], {"agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) def _agentic() -> None: try: @@ -1334,33 +1439,26 @@ def _agentic_review_with_race( if agentic_done.is_set(): return # agentic finished within the delay — never start fallback fallback_started.set() - result = (None, [], {"agentic": False, "review_failed": True, "api_error": None}) + result = _single_shot_review(diff_files, previous_findings) + fallback_result["r"] = result + fallback_done.set() + if result[2]["review_failed"]: + # A failed fallback does not win: the agentic review's inner + # CLI may still get a verdict where direct calls cannot. + agentic_done.wait(timeout=max(0.0, deadline - _t.monotonic())) try: - g, v = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings - ) - # Read on this thread: the outcome is per thread. - failed = llm.last_review_failed() - result = (g, v, {"agentic": False, "review_failed": failed, - "api_error": llm.last_review_status() if failed else None}) - except Exception: # pragma: no cover + q.put_nowait(("fallback", result)) + except _queue.Full: pass - finally: - fallback_result["r"] = result - fallback_done.set() - if result[2]["review_failed"]: - # A failed fallback does not win: the agentic review's inner - # CLI may still get a verdict where direct calls cannot. - agentic_done.wait(timeout=max(0.0, deadline - _t.monotonic())) - try: - q.put_nowait(("fallback", result)) - except _queue.Full: - pass _th.Thread(target=_agentic, daemon=True).start() _th.Thread(target=_fallback, daemon=True).start() - winner, (g, v, m) = q.get() + try: + winner, (g, v, m) = q.get(timeout=max(0.0, _RACE_END_S - spent_s)) + except _queue.Empty: + debug_log("review race: nothing returned in time") + winner, (g, v, m) = "fallback", timed_out # What the agentic run saw of its directory, and how much work it did, # is kept when the fallback's result replaces it below. reviewer_context = ( @@ -1373,8 +1471,7 @@ def _agentic_review_with_race( if fallback_done.wait(timeout=max(0.0, deadline - _t.monotonic())): winner, (g, v, m) = "fallback", fallback_result["r"] else: - winner, (g, v, m) = "fallback", (None, [], { - "agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) + winner, (g, v, m) = "fallback", timed_out m = {**m, **reviewer_context} # a copy: don't mutate the callee's metrics dict m["race_winner"] = 1 if winner == "agentic" else 2 m["race_delay_s"] = delay_s @@ -1389,7 +1486,7 @@ def _review_failure_reason(status): _RACE_TIMED_OUT. """ gateway = (", or an LLM gateway may need its key in ANTHROPIC_CUSTOM_HEADERS" - if os.environ.get("ANTHROPIC_BASE_URL") else "") + if os.environ.get("ANTHROPIC_BASE_URL", "").strip() else "") if status == _RACE_TIMED_OUT: return ("timeout", "the review did not finish in time", "") if llm._is_3p_provider(): @@ -1420,6 +1517,44 @@ def _review_failure_reason(status): return ("reply", "the model's reply could not be read", "") +def _left_out_files_notice(session_id, repo_root, untracked, diff_output): + """(one line for the terminal, text for Claude) naming the source files a + failed `git add -N` kept out of this Stop review, or None. + + Each set of files gets one notice a session: the wake ends in another Stop + that fails the same way, and a notice there would wake Claude for ever. So + no notice unless the mark is saved. Paths are JSON quoted in ASCII: a file + name can hold a line break. + """ + in_diff = set(extract_file_paths_from_diff(diff_output or "")) + + def has_content(p): + try: + return os.path.getsize(os.path.join(repo_root, p)) > 0 + except OSError: + return False + + names = sorted(p for p in untracked or () + if p not in in_diff and _is_reviewable_source(p) and has_content(p)) + if not names: + return None + key = "new_files_left_out:" + hashlib.sha256( + "\0".join(names).encode("utf-8", "replace")).hexdigest()[:16] + if not atomic_check_and_mark_warning(session_id, key): + return None + if key not in load_state(session_id).get("shown_warnings", ()): + return None + _TAIL_METRICS["add_fail_told"] = len(names) + shown = ", ".join(json.dumps(p) for p in names[:_LEFT_OUT_NAMES_SHOWN]) + if len(names) > _LEFT_OUT_NAMES_SHOWN: + shown += f" and {len(names) - _LEFT_OUT_NAMES_SHOWN} more" + return (f"Security review left out new files: {shown}. Log: {DEBUG_LOG_FILE}", + f"The security review did not see these new files, so it did not " + f"review them: {shown}. git could not add them to the review's " + f"diff. Tell the user this in one sentence, and that details are " + f"in {DEBUG_LOG_FILE}.") + + def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): """End a commit ("Commit") or push ("Push") review that got no verdict. @@ -1849,7 +1984,7 @@ def handle_commit_review_posttooluse(input_data): if _agentic_commit_review_enabled(): rel_touched = [fp for fp, _ in diff_files] concrete_guidance, vulns, _am = _agentic_review_with_race( - repo_root, diff_files, rel_touched, previous_findings + repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s() ) agentic_metrics.update(_am) if _am.get("child_stderr"): @@ -1863,17 +1998,13 @@ def handle_commit_review_posttooluse(input_data): # Fall back to single-shot only on agentic FAILURE (SDK/investigate # crash). If agentic completed and returned 0 findings, trust that. if agentic_metrics.get("agentic_fallback"): - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() else: - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() review_ms = int((_time.time() - review_start) * 1000) # `survived` is the raw self-refute count BEFORE the high/critical-only @@ -2290,7 +2421,7 @@ def handle_push_sweep_posttooluse(input_data): rel_touched = [fp for fp, _ in diff_files] if _agentic_commit_review_enabled(): concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race( - repo_root, diff_files, rel_touched, previous_findings + repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s(), ) if agentic_metrics.get("child_stderr"): _TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"] @@ -2298,24 +2429,20 @@ def handle_push_sweep_posttooluse(input_data): review_failed = bool(agentic_metrics.get("review_failed")) api_status = agentic_metrics.get("api_error") if agentic_metrics.get("agentic_fallback"): - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() else: - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() agentic_metrics = {} review_ms = int((_time.time() - review_start) * 1000) if review_failed: # Not marked reviewed. A later push does not re-check these commits: # its range starts from the new upstream. _exit_review_failed("Push", session_id, { - **_base, "pushed": len(push_range), "unreviewed": len(tail), + **_base, **_wait_m, "pushed": len(push_range), "unreviewed": len(tail), "files_reviewed": len(diff_files), "review_ms": review_ms, }, api_status) @@ -2489,10 +2616,29 @@ def handle_stop_hook(input_data): _TAIL_METRICS["warn_fired_mask"] = warn_fired_mask v2_metrics = {} + left_out = False + restore_paths = touched_paths + + def _left_out_notice(): + # Asked for as the row goes out: the mark must not outlive a hook + # killed during the review. + if not left_out: + return None + return _left_out_files_notice(session_id, repo_root, untracked, diff_output) + + def _left_out_wake(): + """emit_metrics arguments that wake Claude to say new files were left out.""" + notice = _left_out_notice() + if not notice: + return {} + return {"rewake_summary": notice[0], "hook_event_name": hook_event_name, + "additional_context": (PROVENANCE_BANNER + "\n\n" + notice[1] + + CONTINUATION_SUFFIX + "\n")} def _skip(reason, restore=False, **extra): if restore: - restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) + restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline) + wake = _left_out_wake() # CC truncates metrics to 10 keys by # insertion order. v2_metrics (3) must precede sweep (3) so the v2 # diagnostics survive when extra adds touched_paths_count + ip_* keys. @@ -2504,8 +2650,8 @@ def handle_stop_hook(input_data): if gitutil._unparsed_diff_headers else {}), **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), - }) - sys.exit(0) + }, **wake) + sys.exit(2 if wake else 0) # Limit stop hook firings per asyncRewake loop to prevent infinite loops. # fire_count auto-expires after STOP_LOOP_STATE_TTL_SEC so a stale count @@ -2619,13 +2765,13 @@ def handle_stop_hook(input_data): f"{MAX_REVIEW_SET_PATHS} paths), skipping") _skip(8) # Run from repo_root so the toplevel-relative review_paths resolve. - # Diff CONTENT against the turn-start stash (baseline_sha) so the LLM + # Diff CONTENT against the turn-start snapshot (baseline_sha) so the LLM # sees only this-turn edits — diffing against HEAD includes the user's # pre-turn uncommitted WIP, which inflates review_ms and can re-flag # the same pre-existing pattern every turn. The file LIST still comes # from git state (compute_v2_review_set), so Bash/subagent edits are # caught either way. Fall back to diff_base (HEAD/head_at_capture) - # when the stash is missing or pruned. + # when the baseline commit is missing or pruned. content_base = baseline_sha or diff_base diff_output = get_git_diff(repo_root, content_base, full_context=False, paths=review_paths, untracked_paths=untracked) @@ -2648,6 +2794,15 @@ def handle_stop_hook(input_data): if not baseline_sha: baseline_sha = "HEAD" + # New files a failed `git add -N` hid: when nothing gets reviewed they are + # put back, listed as touched so the next prompt keeps this baseline even + # if an edit tool never wrote them. A review of the tracked files goes on + # without them, rather than repeating that review every turn. + left_out = gitutil._add_failed["left_out"] + if left_out: + restore_paths = list(touched_paths) + [ + os.path.join(repo_root, p) for p in untracked or ()] + if not diff_output or not diff_output.strip(): if "gave_up" in gitutil._path_list_too_long: debug_log("Stop hook: changed paths do not fit the git commands, skipping") @@ -2656,7 +2811,7 @@ def handle_stop_hook(input_data): debug_log("Stop hook: no source code files among the changed paths") _skip(7) debug_log("Stop hook: no changes since baseline") - _skip(6) + _skip(6, restore=left_out) diff_hash = hashlib.sha256(diff_output.encode("utf-8", "replace")).hexdigest() if snap.get("reviewed_diff_hash") == diff_hash: @@ -2667,7 +2822,7 @@ def handle_stop_hook(input_data): diff_files = parse_diff_into_files(diff_output) if not diff_files: debug_log("Stop hook: no source code files in diff") - _skip(7) + _skip(7, restore=left_out) # Mirror commit-review: hard-bail only on pathological diffs (>300 files, # usually a bad baseline), otherwise prioritize by security-risk path @@ -2791,6 +2946,7 @@ def handle_stop_hook(input_data): # untracked_baseline_n is the signal for whether the UPS-time # untracked-snapshot capture actually ran. sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"} + left_out_notice = _left_out_notice() # Guidance goes to stderr plus top-level decision/reason (see # emit_metrics). exit(2) preserved as the asyncRewake "force fix" # signal — that's the documented mechanism. @@ -2812,8 +2968,9 @@ def handle_stop_hook(input_data): **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), }, rewake_summary=_format_vulns_summary(vulns), - additional_context=(PROVENANCE_BANNER + "\n\n" - + concrete_guidance + CONTINUATION_SUFFIX + "\n"), + additional_context=(PROVENANCE_BANNER + "\n\n" + concrete_guidance + + ("\n\n" + left_out_notice[1] if left_out_notice else "") + + CONTINUATION_SUFFIX + "\n"), hook_event_name=hook_event_name) sys.exit(2) @@ -2821,11 +2978,12 @@ def handle_stop_hook(input_data): if stop_review_failed: debug_log(f"Stop hook: review got no verdict " f"({_review_failure_reason(llm.last_review_status())[1]})") - restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) + restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline) else: debug_log("Stop hook: no security issues found") if is_subagent: 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 # **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced @@ -2847,8 +3005,8 @@ def handle_stop_hook(input_data): if gitutil._unparsed_diff_headers else {}), **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), - }) - sys.exit(0) + }, **wake) + sys.exit(2 if wake else 0) _SDK_BOOTSTRAP_THROTTLE = os.path.join(_resolve_state_dir(), ".sdk_bootstrap_spawned") @@ -2981,12 +3139,27 @@ def main(): if tool_name == "Bash" and hook_event_name == "PostToolUse": cmd = (input_data.get("tool_input") or {}).get("command", "") or "" if not (_GIT_COMMIT_RE.search(cmd) or _GIT_PUSH_RE.search(cmd)): + # Measurement only: this start matched no commit or push. Count + # it, and say whether a plain text check could have told so before + # Python. Both values carry the sample weight, so they sum to + # estimates of all such starts. + if _unmatched_bash_sampled(input_data) and not portable_output(): + skip = 0 if _shell_precheck_passes(raw_input) else _UNMATCHED_BASH_SAMPLE + emit_metrics({"bash_no_match": _UNMATCHED_BASH_SAMPLE, "precheck_skip": skip}) return + if not _shell_precheck_passes(raw_input): + # The text check would have dropped a command that is reviewed. + # Rides on whichever row this start emits; nothing is skipped. + global _precheck_miss + _precheck_miss = True if not _claim_bash_hook_once(input_data): # Another spawn for this same tool_use_id already claimed the # work (compound matched multiple `if` configs). Emit a single # metric so telemetry can count how often the de-dupe kicks in. - _write_hook_output({"metrics": {"bash_hook_dedup": True}}) + dedup = {"bash_hook_dedup": True} + if _precheck_miss and not portable_output(): + dedup = {"pv": _PV, "precheck_miss": 1, **dedup} + _write_hook_output({"metrics": dedup}) sys.exit(0) if _GIT_COMMIT_RE.search(cmd): handle_commit_review_posttooluse(input_data) diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 464f4695..b0df08de 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -89,8 +89,10 @@ def workspace(tmp_path): class _Stub(http.server.BaseHTTPRequestHandler): def do_POST(self): n = int(self.headers.get("Content-Length") or 0) - if n: - self.rfile.read(n) + body = self.rfile.read(n).decode("utf-8", "replace") if n else "" + # Only the stub_api fixture keeps the request bodies. + if hasattr(self.server, "bodies"): + self.server.bodies.append(body) self.server.calls.append(self.path) if self.server.delay: time.sleep(self.server.delay) @@ -121,6 +123,7 @@ class _Stub(http.server.BaseHTTPRequestHandler): def stub_api(): srv = http.server.HTTPServer(("127.0.0.1", 0), _Stub) srv.calls = [] + srv.bodies = [] srv.status = 200 srv.delay = 0 srv.vulns = [] diff --git a/plugins/security-guidance/tests/test_add_failure_metric.py b/plugins/security-guidance/tests/test_add_failure_metric.py index 3a86a8ac..228b68b7 100644 --- a/plugins/security-guidance/tests/test_add_failure_metric.py +++ b/plugins/security-guidance/tests/test_add_failure_metric.py @@ -1,6 +1,11 @@ -"""A failed `git add --intent-to-add` leaves new files out of the Stop review's -diff. The review goes on as before; the Stop row says that it happened.""" +"""`git add --intent-to-add` puts new files in the Stop review's diff. A user +who cannot write the object store gets a retry with a private object directory; +a failure that stays leaves the new files for a later review, unless the turn's +tracked files were reviewed, and tells Claude which files were left out. The +Stop row says what happened.""" +import json import os +import shutil import subprocess import tempfile from types import SimpleNamespace @@ -8,11 +13,12 @@ from types import SimpleNamespace import pytest from conftest import ( - GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload, - ups_payload, + GIT_ENV, STUB_VULN, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, write_cli, ) import gitutil +import security_reminder_hook as hook def _cannot_write_read_only_dirs(): @@ -43,15 +49,16 @@ class TestObjectStoreNotWritable: def test_turn_that_only_adds_a_file(self, tmp_path, hook_env, stub_api, read_only_objects): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) read_only_objects(repo) + before = sorted(p for p in (repo / ".git" / "objects").rglob("*")) run_hook(ups_payload(repo), hook_env) (repo / "handlers.py").write_text(VULN_PY) m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) - assert m["skip_reason"] == 6, m - assert m["review_set_count"] == 1 - assert m["add_fail"] == 100001 - assert not stub_api.calls + assert m["files_reviewed"] == 1, m + assert m["add_fail"] == 400001 + assert stub_api.calls + assert sorted(p for p in (repo / ".git" / "objects").rglob("*")) == before - def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api, read_only_objects): + def test_tracked_edit_and_new_files(self, tmp_path, hook_env, stub_api, read_only_objects): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) read_only_objects(repo) run_hook(ups_payload(repo), hook_env) @@ -60,21 +67,247 @@ class TestObjectStoreNotWritable: (repo / "b.py").write_text("print('b')\n") m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) assert not m.get("skipped"), m - assert m["files_reviewed"] == 1 - assert m["add_fail"] == 100002 + assert m["files_reviewed"] == 3 + assert m["add_fail"] == 400002 + def test_linked_worktree_and_packed_repo(self, tmp_path, hook_env, stub_api, read_only_objects): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + git(repo, "repack", "-adq") + wt = tmp_path / "wt" + git(repo, "worktree", "add", "-q", "-b", "side", str(wt)) + read_only_objects(repo) + run_hook(ups_payload(wt), hook_env) + (wt / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(wt), hook_env)[1]) + assert m["files_reviewed"] == 1, m + assert m["add_fail"] == 400001 -class TestStopRow: - def test_other_git_error(self, tmp_path, hook_env, stub_api): - # git refuses --literal-pathspecs together with a user's icase setting. + def test_private_directory_is_gone_afterwards(self, tmp_path, monkeypatch, read_only_objects): + d = tmp_path / "tmproot" + d.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(d)) + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + read_only_objects(repo) + (repo / "new.py").write_text("print('new')\n") + out = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + gitutil._add_failed["code"] = 0 + assert "new.py" in out + assert not [p for p in d.rglob("*") if gitutil._TEMP_INDEX_PREFIX in p.name] + + +class TestPathspecSettings: + @pytest.mark.parametrize("name", ["GIT_ICASE_PATHSPECS", "GIT_GLOB_PATHSPECS"]) + def test_new_file_is_reviewed(self, tmp_path, hook_env, stub_api, name): + # git refuses --literal-pathspecs together with these two. repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) - env = {**hook_env, "GIT_ICASE_PATHSPECS": "1"} + env = {**hook_env, name: "1"} run_hook(ups_payload(repo), env) (repo / "handlers.py").write_text(VULN_PY) m = metrics_of(run_hook(stop_payload(repo), env)[1]) + assert m["files_reviewed"] == 1, m + assert "add_fail" not in m + + +@pytest.mark.skipif(os.name == "nt", reason="the stand-in git is a shell script") +def _env_refusing_add(tmp_path, hook_env, unless_set=None): + """`hook_env` with a git that fails `add -N`, unless `unless_set` is in its + environment.""" + d = tmp_path / "shim" + d.mkdir() + write_cli(d, "git", ( + "import os, subprocess, sys\n" + f"if '--intent-to-add' in sys.argv and not os.environ.get({unless_set!r}):\n" + " sys.stderr.write('fatal: refused\\n')\n" + " sys.exit(128)\n" + f"sys.exit(subprocess.call([{shutil.which('git')!r}, *sys.argv[1:]]))\n")) + return {**hook_env, "PATH": f"{d}{os.pathsep}{hook_env['PATH']}"} + + +class TestAddThatKeepsFailing: + def test_new_file_is_reviewed_once_git_works(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + bad = _env_refusing_add(tmp_path, hook_env) + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + run_hook(edit_payload(repo, str(repo / "handlers.py")), bad) + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) assert m["skip_reason"] == 6, m assert m["add_fail"] == 200001 + assert not stub_api.calls + + run_hook(ups_payload(repo), hook_env) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["files_reviewed"] == 1, m + assert stub_api.calls + + def test_file_no_edit_tool_wrote(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + bad = _env_refusing_add(tmp_path, hook_env) + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) + assert m["skip_reason"] == 6, m + + run_hook(ups_payload(repo), hook_env) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["files_reviewed"] == 1, m + + def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + bad = _env_refusing_add(tmp_path, hook_env) + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + (repo / "a.py").write_text("print('a')\n") + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) + assert m["files_reviewed"] == 1, m + assert m["add_fail"] == 200001 + + +class TestNoticeForLeftOutFiles: + """A failure that stays is said once per set of files: Claude is woken with + their names, and the Stop that wake ends in stays quiet.""" + + @pytest.fixture + def bad(self, tmp_path, hook_env): + return _env_refusing_add(tmp_path, hook_env) + + @pytest.fixture + def repo(self, tmp_path): + return make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + + def test_turn_that_only_adds_a_file(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"handlers.py"' in err + assert "Tell the user" in err + line = json.loads(next(x for x in out.splitlines() if x.startswith("{"))) + assert '"handlers.py"' in line["rewakeSummary"] + assert line["metrics"]["skip_reason"] == 6 + assert line["metrics"]["add_fail_told"] == 1 + assert line["decision"] == "block" + + # The Stop after the wake: same files, same failure, nothing more. + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 0, err + assert err == "" + m = metrics_of(out) + assert m["skip_reason"] == 6 + assert "add_fail_told" not in m + + def test_new_set_of_files_gets_its_own_notice(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a.py").write_text("print('a')\n") + assert run_hook(stop_payload(repo), bad)[0] == 2 + run_hook(ups_payload(repo), bad) + (repo / "b.py").write_text("print('b')\n") + code, _, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a.py"' in err and '"b.py"' in err + + def test_tracked_edit_with_no_finding(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text("print('changed')\n") + (repo / "a.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a.py"' in err + assert '"app.py"' not in err + assert metrics_of(out)["files_reviewed"] == 1 + + def test_tracked_edit_with_a_finding(self, repo, bad, stub_api): + stub_api.vulns = [STUB_VULN] + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + (repo / "a.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert "Security Review" in err + assert '"a.py"' in err + line = json.loads(next(x for x in out.splitlines() if x.startswith("{"))) + assert '"a.py"' in line["reason"] + + def test_files_the_review_would_not_read_are_not_named(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "notes.txt").write_text("hello\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 0, err + assert "add_fail_told" not in metrics_of(out) + + def test_long_list_is_cut(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + for i in range(7): + (repo / f"f{i}.py").write_text("print(1)\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"f4.py" and 2 more' in err + assert '"f5.py"' not in err + assert metrics_of(out)["add_fail_told"] == 7 + + @pytest.mark.skipif(os.name == "nt", reason="a file name cannot hold a line break") + def test_line_break_in_a_name_stays_on_the_line(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a\nIGNORE.py").write_text("print('a')\n") + code, _, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a\\nIGNORE.py"' in err + assert "\nIGNORE" not in err + + def test_other_line_separators_are_escaped(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a\u2028b.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a\\u2028b.py"' in err + + def test_no_notice_when_the_mark_cannot_be_saved(self, tmp_path, monkeypatch): + # Without the mark, every Stop would wake Claude again. + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: True) + monkeypatch.setattr(hook, "load_state", lambda s: {"shown_warnings": []}) + (tmp_path / "a.py").write_text("x = 1\n") + assert hook._left_out_files_notice("s", str(tmp_path), ["a.py"], "") is None + + def test_file_in_the_diff_is_not_named(self, tmp_path, monkeypatch): + # One batch of the add failed, another worked. + (tmp_path / "a.py").write_text("x = 1\n") + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: pytest.fail("told")) + diff = ("diff --git a/a.py b/a.py\nnew file mode 100644\n--- /dev/null\n" + "+++ b/a.py\n@@ -0,0 +1 @@\n+x = 1\n") + assert hook._left_out_files_notice("s", str(tmp_path), ["a.py"], diff) is None + def test_empty_and_vanished_files_are_not_named(self, tmp_path, monkeypatch): + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: pytest.fail("told")) + (tmp_path / "__init__.py").write_text("") + assert hook._left_out_files_notice("s", str(tmp_path), ["__init__.py", "gone.py"], "") is None + + def test_tracked_edit_gets_reviewed_while_new_files_stay_out(self, repo, bad, stub_api): + # A failure on every turn must not stop later reviews of tracked files. + run_hook(ups_payload(repo), bad) + (repo / "a.py").write_text("print('a')\n") + assert run_hook(stop_payload(repo), bad)[0] == 2 + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + code, out, _ = run_hook(stop_payload(repo), bad) + assert code == 0 + assert metrics_of(out)["files_reviewed"] == 1 + assert stub_api.calls + + def test_retry_that_works_says_nothing(self, repo, tmp_path, hook_env, stub_api): + env = _env_refusing_add(tmp_path, hook_env, unless_set="GIT_OBJECT_DIRECTORY") + run_hook(ups_payload(repo), env) + (repo / "handlers.py").write_text(VULN_PY) + code, out, err = run_hook(stop_payload(repo), env) + assert code == 0, err + m = metrics_of(out) + assert m["add_fail"] == 400001 + assert "add_fail_told" not in m + + +class TestStopRow: def test_add_that_works_reports_nothing(self, tmp_path, hook_env, stub_api): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) run_hook(ups_payload(repo), hook_env) @@ -122,13 +355,26 @@ class TestGetGitDiff: untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 200001 - def test_timeout_counts_and_still_gives_no_diff(self, repo, monkeypatch): + def test_timeout_counts_and_keeps_the_tracked_diff(self, repo, monkeypatch): self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10)) - assert gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], - untracked_paths=["new.py"]) is None - assert gitutil._add_failed["code"] == 300001 + (repo / "app.py").write_text("print('edited')\n") + out = gitutil.get_git_diff(str(repo), "HEAD", + paths=[str(repo / "new.py"), str(repo / "app.py")], + untracked_paths=["new.py"]) + assert "app.py" in out + assert "new.py" not in out + assert gitutil._add_failed == {"code": 300001, "left_out": True} - def test_object_store_refusal(self, repo, monkeypatch): + def test_a_fallback_diff_that_works_clears_left_out(self, repo, monkeypatch): + self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10)) + gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + monkeypatch.undo() + assert "new.py" in gitutil.get_git_diff( + str(repo), "HEAD", paths=[str(repo / "new.py")], untracked_paths=["new.py"]) + assert gitutil._add_failed == {"code": 300001, "left_out": False} + + def test_object_store_refusal_on_both_tries(self, repo, monkeypatch): self._adds_fail_with(monkeypatch, [SimpleNamespace( returncode=128, stderr=b"fatal: cannot create an empty blob in the object database")]) @@ -136,8 +382,92 @@ class TestGetGitDiff: untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 100001 + def test_retry_reads_the_repositorys_objects_and_writes_elsewhere(self, repo, monkeypatch): + seen = [] + real = gitutil._run_git_on_review_paths + + def run(args, paths, timeout, **kwargs): + if args[0] != "add": + return real(args, paths, timeout, **kwargs) + seen.append(kwargs["env"]) + return real(args, paths, timeout, **kwargs) if len(seen) > 1 else [ + SimpleNamespace(returncode=128, stderr=b"nope")] + + monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run) + out = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + assert "new.py" in out + assert "GIT_OBJECT_DIRECTORY" not in seen[0] + assert seen[1]["GIT_OBJECT_DIRECTORY"].endswith(".objects") + assert os.path.samefile(seen[1]["GIT_ALTERNATE_OBJECT_DIRECTORIES"], + repo / ".git" / "objects") + assert gitutil._add_failed["code"] == 400001 + + def test_retry_timeout_keeps_the_tracked_diff(self, repo, monkeypatch): + (repo / "app.py").write_text("print('changed')\n") + real = gitutil._run_git_on_review_paths + adds = [] + + def run(args, paths, timeout, **kwargs): + if args[0] != "add": + return real(args, paths, timeout, **kwargs) + adds.append(args) + if len(adds) > 1: + raise subprocess.TimeoutExpired("git", 10) + return [SimpleNamespace(returncode=128, stderr=b"fatal: nope")] + + monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run) + out = gitutil.get_git_diff(str(repo), "HEAD", untracked_paths=["new.py"]) + assert "app.py" in out + assert gitutil._add_failed["code"] == 200001 + def test_a_later_add_that_works_keeps_the_failure(self, repo, monkeypatch): gitutil._add_failed["code"] = 300001 gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 300001 + + +class TestLeftovers: + def _private_dir(self, parent, name): + d = parent / name + (d / "e6").mkdir(parents=True) + blob = d / "e6" / "9de29" + blob.write_bytes(b"x") + blob.chmod(0o444) + return d + + def test_removed_with_its_copy(self, tmp_path): + copy = tmp_path / "security_hook_idx_pid1_abcdefgh" + copy.write_bytes(b"i") + self._private_dir(tmp_path, copy.name + ".objects") + gitutil._remove_copy(str(copy)) + assert not list(tmp_path.iterdir()) + + @pytest.mark.skipif(os.name == "nt", reason="no pid check on Windows") + def test_killed_hooks_directory_is_swept(self, tmp_path): + p = subprocess.Popen(["git", "--version"], stdout=subprocess.DEVNULL) + p.wait() + self._private_dir(tmp_path, f"security_hook_idx_pid{p.pid}_abcdefgh.objects") + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert not list(tmp_path.iterdir()) + + def test_live_hooks_directory_stays(self, tmp_path): + self._private_dir(tmp_path, f"security_hook_idx_pid{os.getpid()}_abcdefgh.objects") + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert list(tmp_path.iterdir()) + + def test_other_directories_stay(self, tmp_path): + (tmp_path / "security_hook_idx_pid1_abcdefgh.other").mkdir() + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert list(tmp_path.iterdir()) + + @pytest.mark.skipif(os.name == "nt", reason="needs symlinks") + def test_link_at_the_private_directory_is_not_followed(self, tmp_path): + victim = tmp_path / "victim" + victim.mkdir() + (victim / "keep").write_text("x") + copy = tmp_path / "security_hook_idx_pid1_abcdefgh" + (tmp_path / (copy.name + ".objects")).symlink_to(victim) + gitutil._remove_copy(str(copy)) + assert (victim / "keep").exists() diff --git a/plugins/security-guidance/tests/test_agentic_auth_stop.py b/plugins/security-guidance/tests/test_agentic_auth_stop.py new file mode 100644 index 00000000..a2108cfc --- /dev/null +++ b/plugins/security-guidance/tests/test_agentic_auth_stop.py @@ -0,0 +1,148 @@ +"""The agentic reviewer stops as soon as its credentials are refused, instead +of waiting for the inner CLI to give up, and leaves every other run alone.""" +import os +import subprocess +import sys +import types + +import pytest + +import llm +from conftest import write_cli + + +class _Assistant: + def __init__(self, error=None): + self.content, self.error = [], error + + +class _System: + subtype = "api_retry" + + def __init__(self, status): + self.data = {"error_status": status} + + +@pytest.fixture +def sdk(monkeypatch, tmp_path): + """Replays `script.messages`, then a clean result, and counts what the + review read of them.""" + script = types.SimpleNamespace(messages=[], read=0) + + class ClaudeAgentOptions: + def __init__(self, **kwargs): + self.kwargs = kwargs + + class ResultMessage: + subtype, usage, total_cost_usd = "success", {}, 0.0 + structured_output = {"findings": []} + + async def query(prompt, options): + for m in script.messages: + script.read += 1 + yield m + yield ResultMessage() + + mod = types.ModuleType("claude_agent_sdk") + mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query + mod.AssistantMessage = _Assistant + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + monkeypatch.delenv("CLAUDE_CODE_REMOTE", raising=False) + return script + + +def _review(repo): + return llm.agentic_review(str(repo), [("a.py", "+x = 1\n")], ["a.py"])[2] + + +class TestStopsOnRefusedCredentials: + def test_first_auth_failure_ends_the_review(self, sdk, tmp_path): + sdk.messages = [_Assistant(error="authentication_failed") for _ in range(50)] + m = _review(tmp_path) + assert sdk.read == 1 + assert m["agentic_fallback"] == "investigate:_ReviewerAuthFailed" + + def test_repeated_401_retries_end_the_review(self, sdk, tmp_path): + sdk.messages = [_System(401) for _ in range(10)] + m = _review(tmp_path) + assert sdk.read == llm._AGENTIC_MAX_401_RETRIES + assert m["agentic_fallback"] == "investigate:_ReviewerAuthFailed" + + +class TestLeavesOtherRunsAlone: + def test_a_remote_session_rides_out_401_retries(self, sdk, tmp_path, monkeypatch): + monkeypatch.setenv("CLAUDE_CODE_REMOTE", "true") + sdk.messages = [_System(401) for _ in range(10)] + assert "agentic_fallback" not in _review(tmp_path) + + def test_a_login_renewed_after_one_401_goes_on(self, sdk, tmp_path): + sdk.messages = [_System(401), _Assistant()] + assert "agentic_fallback" not in _review(tmp_path) + + def test_401s_that_are_not_in_a_row_do_not_add_up(self, sdk, tmp_path): + sdk.messages = [_System(401), _System(401), _Assistant()] * 3 + assert "agentic_fallback" not in _review(tmp_path) + + def test_other_retries_do_not_count(self, sdk, tmp_path): + sdk.messages = [_System(s) for s in (529, 429, None, 500, 529, 529)] + assert "agentic_fallback" not in _review(tmp_path) + + def test_other_assistant_errors_do_not_stop_it(self, sdk, tmp_path): + sdk.messages = [_Assistant(error="rate_limit"), _Assistant(error="server_error")] + assert "agentic_fallback" not in _review(tmp_path) + + def test_a_message_without_the_field_is_read_as_before(self, sdk, tmp_path): + class Old: + content = [] + sys.modules["claude_agent_sdk"].AssistantMessage = Old + sdk.messages = [Old()] + assert "agentic_fallback" not in _review(tmp_path) + + +_REFUSED_CLI = """ +import json, os, sys, time +open(os.environ["SG_TEST_PID_FILE"], "w").write(str(os.getpid())) +def send(m): + sys.stdout.write(json.dumps(m) + chr(10)); sys.stdout.flush() +for line in sys.stdin: + m = json.loads(line) + if m.get("type") == "control_request": + send({"type": "control_response", "response": {"subtype": "success", + "request_id": m["request_id"], "response": {}}}) + elif m.get("type") == "user": + for _ in range(500): + send({"type": "assistant", "error": "authentication_failed", "message": { + "role": "assistant", "model": "m", "content": [{"type": "text", "text": "401"}]}}) + time.sleep(0.02) + time.sleep(60) +""" + +_DRIVER = """ +import json, llm, os, sys, time +start = time.time() +metrics = llm.agentic_review(sys.argv[1], [("a.py", "+x = 1")], ["a.py"])[2] +pid = int(open(os.environ["SG_TEST_PID_FILE"]).read()) +try: + os.kill(pid, 0); alive = True +except OSError: + alive = False +print(json.dumps({"fallback": metrics.get("agentic_fallback"), "alive": alive}), flush=True) +os._exit(0) +""" + + +def test_real_sdk_closes_the_cli_quietly(tmp_path): + """Stops the real SDK's child, and prints no traceback for the hook's + stderr, which reaches the session.""" + pytest.importorskip("claude_agent_sdk") + env = {**os.environ, "SG_TEST_PID_FILE": str(tmp_path / "pid"), + "SG_AGENTIC_CLI_PATH": str(write_cli(tmp_path, "claude", _REFUSED_CLI)), + "SECURITY_WARNINGS_STATE_DIR": str(tmp_path / "state"), + "PYTHONPATH": str(os.path.dirname(llm.__file__))} + r = subprocess.run([sys.executable, "-c", _DRIVER, str(tmp_path)], env=env, + capture_output=True, text=True, timeout=60) + assert "Traceback" not in r.stderr, r.stderr + assert '"fallback": "investigate:_ReviewerAuthFailed"' in r.stdout, (r.stdout, r.stderr) + assert '"alive": false' in r.stdout, r.stdout diff --git a/plugins/security-guidance/tests/test_base_url.py b/plugins/security-guidance/tests/test_base_url.py new file mode 100644 index 00000000..26317549 --- /dev/null +++ b/plugins/security-guidance/tests/test_base_url.py @@ -0,0 +1,87 @@ +"""A blank ANTHROPIC_BASE_URL means the default endpoint, as it does for the +Anthropic SDK and Claude Code, for every call the plugin makes.""" +import io +import json + +import pytest + +import llm +import security_reminder_hook as hook + +DEFAULT = "https://api.anthropic.com" +BLANK = ["", " ", "\t\n"] + + +@pytest.mark.parametrize("value", BLANK) +def test_blank_is_the_default_endpoint(monkeypatch, value): + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + assert llm._anthropic_base_url() == DEFAULT + + +@pytest.mark.parametrize("value, expected", [ + ("https://gw.example.com/", "https://gw.example.com"), + (" https://gw.example.com/base/ \n", "https://gw.example.com/base"), +]) +def test_a_real_value_is_kept(monkeypatch, value, expected): + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + assert llm._anthropic_base_url() == expected + + +def test_a_stray_slash_is_not_taken_for_blank(monkeypatch): + # A broken gateway setting must not quietly send code to the default host. + monkeypatch.setenv("ANTHROPIC_BASE_URL", "/") + assert llm._anthropic_base_url() == "" + + +def test_unset_is_the_default_endpoint(monkeypatch): + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + assert llm._anthropic_base_url() == DEFAULT + + +class _Reply(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +@pytest.mark.parametrize("value", BLANK) +def test_requests_go_to_the_default_endpoint(monkeypatch, value): + urls = [] + + def urlopen(request, timeout): + urls.append(request.full_url) + return _Reply(json.dumps({ + "data": [{"id": "claude-opus-4-8"}], + "content": [{"type": "text", "text": "{}"}], + "usage": {}, + }).encode()) + + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + monkeypatch.setattr(llm, "ANTHROPIC_API_KEY", "key") + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + monkeypatch.setattr(llm, "_urlopen", urlopen) + assert llm._probe_anthropic() + llm._fetch_newest_opus() + llm._call_claude("prompt", {"type": "object"}, thinking_budget=0, model="claude-x") + assert urls == [f"{DEFAULT}/", f"{DEFAULT}/v1/models?limit=100", f"{DEFAULT}/v1/messages"] + + +@pytest.mark.parametrize("value", BLANK) +def test_blank_is_not_reported_as_a_gateway(monkeypatch, value): + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + assert llm.gateway_cfg() == 0 + + +@pytest.mark.parametrize("value", BLANK) +def test_blank_gets_no_gateway_hint(monkeypatch, value): + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + assert "ANTHROPIC_CUSTOM_HEADERS" not in hook._review_failure_reason(401)[2] diff --git a/plugins/security-guidance/tests/test_baseline_snapshot.py b/plugins/security-guidance/tests/test_baseline_snapshot.py new file mode 100644 index 00000000..eaa0e5c2 --- /dev/null +++ b/plugins/security-guidance/tests/test_baseline_snapshot.py @@ -0,0 +1,257 @@ +"""The turn baseline is a commit of the tracked changes (#6854), where it used +to be `git stash create`. These pin the states where the two could differ.""" +import os +import subprocess + +import pytest + +import diffstate +import gitutil +from conftest import GIT_ENV, git, make_repo + + +@pytest.fixture(autouse=True) +def safe_env(monkeypatch): + for k, v in gitutil.git_config_env(gitutil.SAFE_GIT_CONFIG).items(): + monkeypatch.setenv(k, v) + + +def _tree(repo, sha): + return git(repo, "rev-parse", f"{sha}^{{tree}}").strip() + + +def _plain_stash_tree(repo): + """What `git stash create` would have produced, on the real index.""" + out = subprocess.run(["git", "stash", "create"], cwd=repo, capture_output=True, + text=True, env={**os.environ, **GIT_ENV}) + sha = out.stdout.strip() + return _tree(repo, sha) if sha else _tree(repo, "HEAD") + + +def _capture(repo): + sha = diffstate.capture_git_baseline(str(repo)) + return sha, diffstate.last_baseline_fail + + +def _repo(tmp_path, name="r"): + return make_repo(tmp_path / name, {"a.txt": "a\n", "b.txt": "b\n", "d/c.txt": "c\n"}) + + +def test_unstaged_and_staged_changes_are_in_the_snapshot(tmp_path): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("staged\n") + git(repo, "add", "a.txt") + (repo / "a.txt").write_text("staged\nunstaged\n") + (repo / "b.txt").write_text("also dirty\n") + sha, fail = _capture(repo) + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == "staged\nunstaged\n" + assert git(repo, "show", f"{sha}:b.txt") == "also dirty\n" + assert git(repo, "rev-parse", f"{sha}^").strip() == git(repo, "rev-parse", "HEAD").strip() + + +@pytest.mark.parametrize("state", [ + "unstaged", "staged", "staged-plus-unstaged", "worktree-delete", "staged-delete", + "staged-rename", "staged-new", "mode-change", "symlink", "untracked-only", "stale-stat", +]) +def test_same_tree_as_stash_create(tmp_path, state): + repo = _repo(tmp_path, state) + if state == "unstaged": + (repo / "a.txt").write_text("x\n") + elif state == "staged": + (repo / "a.txt").write_text("x\n"); git(repo, "add", "a.txt") + elif state == "staged-plus-unstaged": + (repo / "a.txt").write_text("x\n"); git(repo, "add", "a.txt") + (repo / "a.txt").write_text("y\n") + elif state == "worktree-delete": + (repo / "a.txt").unlink() + elif state == "staged-delete": + git(repo, "rm", "-q", "a.txt") + elif state == "staged-rename": + git(repo, "mv", "a.txt", "z.txt") + elif state == "staged-new": + (repo / "n.txt").write_text("n\n"); git(repo, "add", "n.txt") + elif state == "mode-change": + os.chmod(repo / "a.txt", 0o755) + elif state == "symlink": + (repo / "a.txt").unlink(); os.symlink("b.txt", repo / "a.txt") + elif state == "untracked-only": + (repo / "u.txt").write_text("u\n") + elif state == "stale-stat": + t = os.stat(repo / "a.txt").st_mtime + 2 + os.utime(repo / "a.txt", (t, t)) + # Capture FIRST: `git stash create` refreshes the real index, which would + # cancel the stale stat entry the last state is about. + sha, fail = _capture(repo) + assert fail == 0 + assert _tree(repo, sha) == _plain_stash_tree(repo) + + +def test_clean_tree_is_head(tmp_path): + repo = _repo(tmp_path) + assert _capture(repo) == (git(repo, "rev-parse", "HEAD").strip(), 0) + + +def test_conflicted_merge_snapshots_the_conflicted_files(tmp_path): + """`stash create` refused here and the whole conflicted file was then + reviewed as the turn's work. `add -u` resolves the conflict in the index + COPY, so the baseline holds what the work tree had, markers and all, and + the user's own index keeps its unmerged entries.""" + repo = _repo(tmp_path) + git(repo, "checkout", "-q", "-b", "other") + (repo / "a.txt").write_text("theirs\n"); git(repo, "commit", "-qam", "theirs") + git(repo, "checkout", "-q", "main") + (repo / "a.txt").write_text("ours\n"); git(repo, "commit", "-qam", "ours") + subprocess.run(["git", "merge", "other"], cwd=repo, capture_output=True, + env={**os.environ, **GIT_ENV}) + assert "UU" in git(repo, "status", "--porcelain") + conflicted = (repo / "a.txt").read_text() + sha, fail = _capture(repo) + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == conflicted + assert "UU" in git(repo, "status", "--porcelain") + assert git(repo, "ls-files", "-u") + + +def test_intent_to_add_file_is_snapshotted_with_its_content(tmp_path): + """`git add -N` marks a file to be committed without staging content. + `stash create` refused on such an index and the baseline fell back to + HEAD, so the file's pre-existing content was reviewed as the turn's work. + The snapshot holds that content, so only what the turn changes is.""" + repo = _repo(tmp_path) + (repo / "n.txt").write_text("secret = 1\n") + git(repo, "add", "-N", "n.txt") + sha, fail = _capture(repo) + assert fail == 0 + assert sha != git(repo, "rev-parse", "HEAD").strip() + assert git(repo, "show", f"{sha}:n.txt") == "secret = 1\n" + # The path is still named in the review set, as it was before, but its + # content is in the baseline now, so the reviewer is sent nothing for it + # where `stash create` failing sent the whole file. + + +def test_subdirectory_cwd_snapshots_the_whole_tree(tmp_path): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("top changed\n") + (repo / "d" / "c.txt").write_text("below changed\n") + sha, fail = _capture(repo / "d") + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == "top changed\n" + assert git(repo, "show", f"{sha}:d/c.txt") == "below changed\n" + + +def test_nested_repository_stays_out_of_the_snapshot(tmp_path): + """A directory with its own .git is another repository: #6837 keeps its + gitlink out of the index copy, so it must stay out of the tree too.""" + repo = _repo(tmp_path) + nested = repo / "vendor" + make_repo(nested, {"x.txt": "x\n"}) + git(repo, "add", "vendor") + git(repo, "commit", "-qm", "add nested") + (nested / "x.txt").write_text("changed inside\n") + (repo / "a.txt").write_text("changed outside\n") + sha, fail = _capture(repo) + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == "changed outside\n" + assert "vendor" not in git(repo, "ls-tree", "--name-only", sha) + + +def test_clean_tree_with_a_nested_repository_is_head(tmp_path): + """The index copy has no gitlink, so its tree can never equal HEAD's. + Without a second look that would mint a commit object on every prompt in + a repo with submodules, and the baseline would be a prunable dangling + commit instead of HEAD.""" + repo = _repo(tmp_path) + make_repo(repo / "vendor", {"x.txt": "x\n"}) + git(repo, "add", "vendor") + git(repo, "commit", "-qm", "add nested") + head = git(repo, "rev-parse", "HEAD").strip() + assert _capture(repo) == (head, 0) + + # A change inside the nested repository is still not this repo's work. + (repo / "vendor" / "x.txt").write_text("changed inside\n") + assert _capture(repo) == (head, 0) + + # A real change outside it still gets a snapshot. + (repo / "a.txt").write_text("changed outside\n") + sha, fail = _capture(repo) + assert fail == 0 and sha != head + assert git(repo, "show", f"{sha}:a.txt") == "changed outside\n" + + +def test_snapshot_leaves_the_real_index_and_worktree_alone(tmp_path): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("dirty\n") + before_index = (repo / ".git" / "index").read_bytes() + before_status = git(repo, "status", "--porcelain") + before_stash = git(repo, "stash", "list") + _capture(repo) + assert (repo / ".git" / "index").read_bytes() == before_index + assert git(repo, "status", "--porcelain") == before_status + assert git(repo, "stash", "list") == before_stash + assert [p for p in os.listdir(repo / ".git") if p.startswith("index.")] == [] + + +def test_snapshot_commit_is_unreferenced(tmp_path): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("dirty\n") + sha, _ = _capture(repo) + assert sha not in git(repo, "log", "--all", "--format=%H") + assert git(repo, "rev-parse", "HEAD").strip() != sha + + +def test_partial_clone_snapshots_without_fetching(tmp_path): + """A blobless clone has no blob for an unchanged file. git counts a + promisor object as present, so write-tree neither fetches nor fails; + this pins that, since the snapshot must never make a network call.""" + origin = _repo(tmp_path, "origin") + git(origin, "config", "uploadpack.allowFilter", "true") + for i in range(3): + (origin / f"big{i}.txt").write_text(f"content {i}\n") + git(origin, "add", "-A") + git(origin, "commit", "-qm", "more") + clone = tmp_path / "clone" + subprocess.run(["git", "clone", "-q", "--filter=blob:none", "--no-local", + str(origin), str(clone)], check=True, capture_output=True, + env={**os.environ, **GIT_ENV}) + # Nothing can be fetched from here on: a snapshot that tried would fail. + git(clone, "config", "remote.origin.url", "/nonexistent-origin") + (clone / "a.txt").write_text("dirty\n") + sha, fail = _capture(clone) + assert fail == 0 and sha + assert git(clone, "show", f"{sha}:a.txt") == "dirty\n" + + +def test_literal_pathspecs_in_the_environment(tmp_path, monkeypatch): + """A user who exports GIT_LITERAL_PATHSPECS gets it in the hook's + environment, and a magic pathspec would then fail outright and drop the + baseline to HEAD on every prompt of the session.""" + repo = _repo(tmp_path) + monkeypatch.setenv("GIT_LITERAL_PATHSPECS", "1") + (repo / "a.txt").write_text("dirty\n") + sha, fail = _capture(repo) + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == "dirty\n" + + +def test_no_identity_configured_still_snapshots(tmp_path, monkeypatch): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("dirty\n") + for var in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", + "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "EMAIL"): + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("GIT_CONFIG_SYSTEM", os.devnull) + sha, fail = _capture(repo) + assert fail == 0 and sha + assert "security-guidance" in git(repo, "show", "-s", "--format=%an", sha) + + +def test_signing_configured_does_not_sign_the_snapshot(tmp_path): + repo = _repo(tmp_path) + git(repo, "config", "commit.gpgsign", "true") + git(repo, "config", "gpg.program", "/nonexistent-gpg") + (repo / "a.txt").write_text("dirty\n") + sha, fail = _capture(repo) + assert fail == 0 and sha + assert git(repo, "show", "-s", "--format=%G?", sha).strip() in ("N", "") diff --git a/plugins/security-guidance/tests/test_git_index_locks.py b/plugins/security-guidance/tests/test_git_index_locks.py index 17a877ff..6faaddd3 100644 --- a/plugins/security-guidance/tests/test_git_index_locks.py +++ b/plugins/security-guidance/tests/test_git_index_locks.py @@ -65,12 +65,13 @@ def _make_stat_stale(path): os.utime(path, (t, t)) -def _is_stash_create(args): - return list(args[-2:]) == ["stash", "create"] +def _is_snapshot_add(args): + """The `git add -u` that stages the turn baseline's tracked changes.""" + return list(args[-2:]) == ["add", "-u"] class TestBaselineCapture: - def test_stash_create_gets_a_throwaway_index(self, tmp_path, tmproot, monkeypatch): + def test_snapshot_gets_a_throwaway_index(self, tmp_path, tmproot, monkeypatch): repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) (repo / "app.py").write_text("x = 2\n") before = _index_sig(repo / ".git") @@ -78,7 +79,7 @@ class TestBaselineCapture: real_run = subprocess.run def spy(args, **kw): - if _is_stash_create(args): + if _is_snapshot_add(args): seen.append(kw["env"]["GIT_INDEX_FILE"]) return real_run(args, **kw) @@ -90,13 +91,13 @@ class TestBaselineCapture: assert _index_litter(repo / ".git") == [] assert _leftovers(tmproot) == [] - def test_killed_stash_create_leaves_nothing(self, tmp_path, tmproot, monkeypatch): + def test_killed_snapshot_leaves_nothing(self, tmp_path, tmproot, monkeypatch): repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) (repo / "app.py").write_text("x = 2\n") real_run = subprocess.run def killed(args, **kw): - if _is_stash_create(args): + if _is_snapshot_add(args): idx = kw["env"]["GIT_INDEX_FILE"] for suffix in (".lock", ".stash.4242", ".stash.4242.lock"): with open(idx + suffix, "wb") as f: @@ -211,7 +212,7 @@ class TestReadOnlyGitLeavesTheRealIndexAlone: assert _leftovers(tmproot) == [] def test_diffs_need_no_index_copy(self, tmp_path, tmproot, monkeypatch): - """Every copy is index-sized, so only `add -N` and stash get one.""" + """Every copy is index-sized, so only `add -N` and the snapshot get one.""" repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n", "b.py": "b = 1\n"}) first = git(repo, "rev-parse", "HEAD").strip() commit_file(repo, "app.py", "x = 2\n") @@ -293,10 +294,10 @@ class TestWholeHook: assert m.get("skip_reason") is None and m["files_reviewed"] == 2, m calls = read_log() - assert {"stash", "status", "diff", "add"} <= {sub[0] for _, _, sub in calls} + assert {"write-tree", "status", "diff", "add"} <= {sub[0] for _, _, sub in calls} assert [c for c in calls if c[0] != "0"] == [] for _, index_file, sub in calls: - if sub[0] in ("stash", "add"): + if sub[0] in ("write-tree", "commit-tree", "add"): assert index_file.startswith(str(tmproot)), sub assert _index_sig(repo / ".git") == before assert _index_litter(repo / ".git") == [] diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py index 4c339a5f..fa998501 100644 --- a/plugins/security-guidance/tests/test_inflight_reviews.py +++ b/plugins/security-guidance/tests/test_inflight_reviews.py @@ -4,6 +4,7 @@ import json import os import subprocess import sys +import threading import time import pytest @@ -152,6 +153,63 @@ def test_push_stops_waiting_after_the_limit(tmp_path, hook_env, stub_api): assert len(_reviews(stub_api)) == 1 +def test_a_push_that_waited_ends_within_the_hook_limit(tmp_path, monkeypatch): + """The wait for a commit review and the race share one limit; a race that + restarts it runs the hook past Claude Code's timeout, with no notice.""" + import security_reminder_hook as hook + + repo, remote = _repo_with_remote(tmp_path) + _, sha, _, _ = _commit_and_push(repo, remote) + monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 1.0) + monkeypatch.setattr(hook, "_RACE_END_S", 1.5) + monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0") + release = threading.Event() + monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20)) + monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(20)) + + started = time.monotonic() + try: + with _held_by_another_review(repo, sha): + _, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 1.0, poll_s=0.05) + _, _, m = hook._agentic_review_with_race( + str(repo), [], [], [], spent_s=waited) + finally: + release.set() + assert 1.0 <= waited < 1.5 + assert 1.5 <= time.monotonic() - started < 2.4 + assert m["review_failed"] is True and m["api_error"] == hook._RACE_TIMED_OUT + + +def test_the_push_handler_counts_its_wait(tmp_path, agentic_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + _, sha, _, push_out = _commit_and_push(repo, remote) + log = tmp_path / "race.log" + env = {**agentic_env, "SG_INFLIGHT_WAIT_S": "2", "SG_AGENTIC_RACE_DELAY_S": "60", + "SECURITY_GUIDANCE_DEBUG_LOG": str(log)} + with _held_by_another_review(repo, sha): + _, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), env) + assert metrics_of(so)["inflight_wait_s"] >= 2 + assert "already spent, fallback starts after 5" in log.read_text() + + +def test_the_fallback_starts_sooner_after_a_wait(tmp_path, monkeypatch): + import security_reminder_hook as hook + + monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "180") + release = threading.Event() + monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20)) + monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: ("guidance", [])) + monkeypatch.setattr(hook.llm, "last_review_failed", lambda: False) + try: + g, _, m = hook._agentic_review_with_race(str(tmp_path), [], [], [], spent_s=240.0) + finally: + release.set() + assert g == "guidance" + assert (m["race_winner"], m["race_delay_s"], m["race_started"]) == (2, 0, 1) + + def test_push_does_not_wait_when_an_earlier_commit_needs_review_anyway(tmp_path, hook_env, stub_api): repo, remote = _repo_with_remote(tmp_path) base = git(repo, "rev-parse", "HEAD").strip() @@ -376,3 +434,61 @@ def test_windows_lock_is_off_where_the_call_is_missing(monkeypatch): monkeypatch.setattr(diffstate, "_win_lock_file_ex", None) with pytest.raises(OSError): diffstate._win_lock_nb(7, exclusive=True) + + +_SHORT_LIMIT = ( + "import sys\n" + "sys.path.insert(0, sys.argv[1])\n" + "import security_reminder_hook as hook\n" + "hook._RACE_END_S = float(sys.argv[2])\n" + "hook.main()\n" +) + + +def _run_with_limit(payload, env, limit_s): + started = time.monotonic() + r = subprocess.run( + [sys.executable, "-c", _SHORT_LIMIT, _HOOKS_DIR, str(limit_s)], + input=json.dumps(payload), capture_output=True, text=True, env=env, timeout=30) + return time.monotonic() - started, r + + +def test_single_shot_after_a_fast_agentic_failure_ends_in_time( + tmp_path, hook_env, failing_inner_cli, stub_api): + """The agentic run fails before the fallback starts, and the single-shot + review that follows hangs: the session still hears before the hook limit.""" + pytest.importorskip("claude_agent_sdk") + repo, _ = _repo_with_remote(tmp_path) + _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + stub_api.delay = 6 + env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli, + "SG_AGENTIC_RACE_DELAY_S": "60"} + took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4) + assert 4 <= took < 10, r.stderr + assert r.returncode == 2 and "did not finish in time" in r.stderr + assert metrics_of(r.stdout)["agentic_fallback"] == 2 + + +def test_single_shot_after_a_push_wait_ends_in_time( + tmp_path, hook_env, failing_inner_cli, stub_api): + pytest.importorskip("claude_agent_sdk") + repo, remote = _repo_with_remote(tmp_path) + _, sha, _, push_out = _commit_and_push(repo, remote) + stub_api.delay = 10 + env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli, + "SG_INFLIGHT_WAIT_S": "4", "SG_AGENTIC_RACE_DELAY_S": "60"} + with _held_by_another_review(repo, sha): + took, r = _run_with_limit(bash_payload(repo, "git push origin main", push_out), env, 8) + assert 8 <= took < 11.5, r.stderr # 12 s if the wait did not count + assert r.returncode == 2 and "did not finish in time" in r.stderr + assert metrics_of(r.stdout)["inflight_wait_s"] >= 4 + + +def test_single_shot_with_the_agentic_review_off_ends_in_time(tmp_path, hook_env, stub_api): + repo, _ = _repo_with_remote(tmp_path) + _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + stub_api.delay = 6 + env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "0"} + took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4) + assert 4 <= took < 10, r.stderr + assert r.returncode == 2 and "did not finish in time" in r.stderr diff --git a/plugins/security-guidance/tests/test_review_outcomes.py b/plugins/security-guidance/tests/test_review_outcomes.py index 887ff9c0..806e9bdd 100644 --- a/plugins/security-guidance/tests/test_review_outcomes.py +++ b/plugins/security-guidance/tests/test_review_outcomes.py @@ -1,5 +1,6 @@ """A review that got no verdict is never reported as clean.""" import json +import threading import time import pytest @@ -188,6 +189,25 @@ class TestFailedReviewIsNotClean: run.calls = calls return run + def test_review_ends_when_neither_side_returns(self, race, monkeypatch): + """A request that never answers holds both sides; the deadline holds anyway.""" + monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 0.1) + monkeypatch.setattr(hook, "_RACE_END_S", 0.2) + release = threading.Event() + monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(5)) + + def stuck_agentic(*a, **k): + release.wait(5) + started = time.monotonic() + try: + guidance, vulns, m = race(stuck_agentic) + finally: + release.set() + assert time.monotonic() - started < 2 + assert (guidance, vulns) == (None, []) + assert m["review_failed"] is True + assert m["api_error"] == hook._RACE_TIMED_OUT + def test_failed_fallback_waits_for_agentic(self, race): """Direct calls can fail where the agentic reviewer's CLI works (it may hold a credential the direct calls lack); its verdict must count.""" diff --git a/plugins/security-guidance/tests/test_review_session_persistence.py b/plugins/security-guidance/tests/test_review_session_persistence.py new file mode 100644 index 00000000..0643bea1 --- /dev/null +++ b/plugins/security-guidance/tests/test_review_session_persistence.py @@ -0,0 +1,134 @@ +"""Review runs through the Agent SDK are not saved as Claude Code session +transcripts unless SECURITY_GUIDANCE_PERSIST_SESSIONS is set.""" +import subprocess +import sys + +import pytest + +from conftest import ( + HOOKS_DIR, STUB_VULN, VULN_PY, bash_payload, commit_file, run_hook, + write_cli, +) + +import llm + +FLAG = "--no-session-persistence" +SINGLE_TURN = ( + "import sys; sys.path.insert(0, sys.argv[1]); import llm, review_api; " + "llm._call_claude_via_sdk('review', review_api.FINDINGS_SCHEMA)" +) + + +def _stub_cli(tmp_path, reject_flag=False): + """An inner CLI that records each launch's arguments on one line and + exits 1. With reject_flag it first refuses the flag the way a Claude Code + older than the flag does.""" + log = tmp_path / "inner-cli-launches" + reject = ( + f"if {FLAG!r} in sys.argv:\n" + f" sys.stderr.write(\"error: unknown option '{FLAG}'\\n\")\n" + " sys.exit(1)\n" + ) if reject_flag else "" + cli = write_cli(tmp_path, "claude", ( + "import sys\n" + # utf-8: the reviewer's prompt has characters cp1252 cannot write. + f"with open({str(log)!r}, 'a', encoding='utf-8') as f:\n" + " f.write(' '.join(sys.argv[1:]) + '\\n')\n" + f"{reject}" + "sys.exit(1)\n")) + return str(cli), log + + +def _reviews(log): + """Argument lines of the review launches (the SDK also probes `-v`).""" + return [l for l in log.read_text(encoding="utf-8").splitlines() + if "--input-format" in l] + + +@pytest.fixture +def sdk_env(env): + pytest.importorskip("claude_agent_sdk") + e = {**env, "SG_AGENTIC_COMMIT_REVIEW": "1"} + e.pop("SECURITY_GUIDANCE_PERSIST_SESSIONS", None) + return e + + +def _commit(repo, env): + _, out = commit_file(repo, "app.py", VULN_PY) + return run_hook(bash_payload(repo, "git commit -m change", out), env) + + +def _single_turn(env): + subprocess.run([sys.executable, "-c", SINGLE_TURN, str(HOOKS_DIR)], + env=env, capture_output=True, text=True, timeout=120) + + +class TestSessionArgs: + @pytest.mark.parametrize("value", [None, "", "0", "off"]) + def test_not_saved_by_default(self, monkeypatch, value): + monkeypatch.setattr(llm, "_send_session_flag", True) + if value is None: + monkeypatch.delenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", raising=False) + else: + monkeypatch.setenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", value) + assert llm._reviewer_session_args() == {"no-session-persistence": None} + + @pytest.mark.parametrize("value", ["1", " on ", "TRUE", "yes"]) + def test_opt_in_keeps_sessions(self, monkeypatch, value): + monkeypatch.setattr(llm, "_send_session_flag", True) + monkeypatch.setenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", value) + assert llm._reviewer_session_args() == {} + + def test_only_a_rejection_of_this_flag_counts(self): + assert llm._refused_flags(["error: unknown option '--other'"]) == [] + assert llm._refused_flags([f"error: unknown option '{FLAG}'"]) == [FLAG] + + def test_left_out_once_refused(self, monkeypatch): + monkeypatch.setattr(llm, "_send_session_flag", False) + monkeypatch.delenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", raising=False) + assert llm._reviewer_session_args() == {} + + +class TestInnerCliArguments: + def test_commit_reviewer_gets_the_flag(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert reviews and all(FLAG in r for r in reviews) + + def test_commit_reviewer_opt_in_drops_the_flag(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli, + "SECURITY_GUIDANCE_PERSIST_SESSIONS": "1"}) + reviews = _reviews(log) + assert reviews and not any(FLAG in r for r in reviews) + + def test_single_turn_review_gets_the_flag(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert reviews and all(FLAG in r for r in reviews) + + def test_single_turn_review_opt_in_drops_the_flag(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli, + "SECURITY_GUIDANCE_PERSIST_SESSIONS": "1"}) + reviews = _reviews(log) + assert reviews and not any(FLAG in r for r in reviews) + + +class TestInnerCliOlderThanTheFlag: + def test_commit_reviewer_runs_again_without_it(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path, reject_flag=True) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert [FLAG in r for r in reviews] == [True, False] + + def test_single_turn_review_runs_again_without_it(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path, reject_flag=True) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert [FLAG in r for r in reviews] == [True, False] diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py index 3b9521ff..555ef0ad 100644 --- a/plugins/security-guidance/tests/test_reviewer_tools.py +++ b/plugins/security-guidance/tests/test_reviewer_tools.py @@ -14,11 +14,14 @@ NO_TOOLS = {"tools": "", "strict-mcp-config": None} # Once an inner CLI has refused --strict-mcp-config. READ_ONLY_NO_MCP = {"tools": "Read,Grep,Glob", "disallowedTools": "mcp__*"} NO_TOOLS_NO_MCP = {"tools": "", "disallowedTools": "mcp__*"} +# Every review start also asks for its session not to be saved. +NOT_SAVED = {"no-session-persistence": None} @pytest.fixture(autouse=True) def strict_mcp_flag_sent(monkeypatch): monkeypatch.setattr(llm, "_send_strict_mcp", True) + monkeypatch.setattr(llm, "_send_session_flag", True) def test_tool_flags(): @@ -82,6 +85,7 @@ def sdk(monkeypatch, tmp_path): mod.AssistantMessage = type("AssistantMessage", (), {}) monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + monkeypatch.delenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", raising=False) monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) for var in ("CONTEXT_DIR", "DEBUG_DIR", "MODEL", "ITER2", "FILTER", "NO_ADJUDICATE", "DIFF_INTERSECT", "EXCLUDE_MEDIUM", "MAX_TURNS"): @@ -95,7 +99,7 @@ def test_every_agentic_stage_gets_only_the_read_tools(sdk, tmp_path): # investigate, second investigate pass, refute assert len(sdk) == 3 for opts in sdk: - assert opts["extra_args"] == READ_ONLY + assert opts["extra_args"] == {**READ_ONLY, **NOT_SAVED} assert opts["allowed_tools"] == ["Read", "Grep", "Glob"] assert "permission_mode" not in opts @@ -104,7 +108,8 @@ 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 assert len(sdk) == 1 - assert sdk[0]["extra_args"] == NO_TOOLS and sdk[0]["allowed_tools"] == [] + assert sdk[0]["extra_args"] == {**NO_TOOLS, **NOT_SAVED} + assert sdk[0]["allowed_tools"] == [] # What Claude Code prints, before exiting 1, on a machine whose administrator @@ -137,9 +142,9 @@ def test_agentic_review_runs_where_the_strict_mcp_flag_is_refused(managed_mcp, t # The refused start's line is not what child_stderr is there to count. assert "agentic_fallback" not in metrics and "child_stderr" not in metrics refused, ran = managed_mcp - assert [o["extra_args"] for o in refused] == [READ_ONLY] + assert [o["extra_args"] for o in refused] == [{**READ_ONLY, **NOT_SAVED}] # investigate, second investigate pass, refute - assert [o["extra_args"] for o in ran] == [READ_ONLY_NO_MCP] * 3 + assert [o["extra_args"] for o in ran] == [{**READ_ONLY_NO_MCP, **NOT_SAVED}] * 3 for opts in ran: assert opts["allowed_tools"] == ["Read", "Grep", "Glob"] @@ -148,11 +153,11 @@ def test_single_turn_sdk_review_runs_where_the_strict_mcp_flag_is_refused(manage schema = {"type": "object", "properties": {}} assert llm._call_claude_via_sdk("review this", schema) is not None refused, ran = managed_mcp - assert [o["extra_args"] for o in refused] == [NO_TOOLS] - assert [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] + assert [o["extra_args"] for o in refused] == [{**NO_TOOLS, **NOT_SAVED}] + assert [o["extra_args"] for o in ran] == [{**NO_TOOLS_NO_MCP, **NOT_SAVED}] # The refusal is remembered for the rest of the hook process. assert llm._call_claude_via_sdk("review this", schema) is not None - assert len(refused) == 1 and ran[-1]["extra_args"] == NO_TOOLS_NO_MCP + assert len(refused) == 1 and ran[-1]["extra_args"] == {**NO_TOOLS_NO_MCP, **NOT_SAVED} def test_other_start_failures_are_not_retried(sdk, monkeypatch, tmp_path): @@ -167,7 +172,7 @@ def test_other_start_failures_are_not_retried(sdk, monkeypatch, tmp_path): assert guidance is None and vulns == [] assert metrics["agentic_fallback"] == "investigate:RuntimeError" assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is None - assert [o["extra_args"] for o in sdk] == [READ_ONLY, NO_TOOLS] + assert [o["extra_args"] for o in sdk] == [{**READ_ONLY, **NOT_SAVED}, {**NO_TOOLS, **NOT_SAVED}] def test_reviews_started_together_are_each_started_again(managed_mcp): @@ -192,7 +197,7 @@ def test_reviews_started_together_are_each_started_again(managed_mcp): for t in threads: t.join(20) assert len(results) == 2 and None not in results - assert len(refused) == 2 and [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] * 2 + assert len(refused) == 2 and [o["extra_args"] for o in ran] == [{**NO_TOOLS_NO_MCP, **NOT_SAVED}] * 2 def test_review_rows_say_when_the_flag_was_left_out(managed_mcp, capsys): @@ -205,3 +210,63 @@ def test_review_rows_say_when_the_flag_was_left_out(managed_mcp, capsys): assert "strict_mcp_off" not in row() assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is not None assert row()["strict_mcp_off"] == 1 + + +# What a Claude Code older than --no-session-persistence prints, before exiting 1. +UNKNOWN = "error: unknown option '--no-session-persistence'" + + +@pytest.fixture +def old_cli(sdk, monkeypatch): + """The stand-in SDK's inner CLI now refuses --no-session-persistence + and, once that is gone, --strict-mcp-config: one flag per start, as + Claude Code does. Gives the options of the refused starts and of the + ones that ran.""" + answer = sys.modules["claude_agent_sdk"].query + refused = [] + + async def query(prompt, options): + args = options.kwargs["extra_args"] + line = (UNKNOWN if "no-session-persistence" in args + else REFUSAL if "strict-mcp-config" in args else None) + if line: + refused.append(options.kwargs) + options.kwargs["stderr"](line) + raise RuntimeError("Command failed with exit code 1") + async for msg in answer(prompt, options): + yield msg + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + return refused, sdk + + +def test_agentic_review_runs_where_both_flags_are_refused(old_cli, tmp_path): + _, vulns, metrics = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert len(vulns) == 1 + assert "agentic_fallback" not in metrics and "child_stderr" not in metrics + refused, ran = old_cli + assert [o["extra_args"] for o in refused] == [{**READ_ONLY, **NOT_SAVED}, READ_ONLY] + assert [o["extra_args"] for o in ran] == [READ_ONLY_NO_MCP] * 3 + + +def test_single_turn_sdk_review_runs_where_both_flags_are_refused(old_cli): + schema = {"type": "object", "properties": {}} + assert llm._call_claude_via_sdk("review this", schema) is not None + refused, ran = old_cli + assert [o["extra_args"] for o in refused] == [{**NO_TOOLS, **NOT_SAVED}, NO_TOOLS] + assert [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] + # Both refusals are remembered for the rest of the hook process. + assert llm._call_claude_via_sdk("review this", schema) is not None + assert len(refused) == 2 and ran[-1]["extra_args"] == NO_TOOLS_NO_MCP + + +def test_a_flag_refused_again_after_it_was_left_out_is_not_retried(sdk, monkeypatch): + async def query(prompt, options): + sdk.append(options.kwargs) + options.kwargs["stderr"](UNKNOWN) + raise RuntimeError("Command failed with exit code 1") + yield + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is None + assert [o["extra_args"] for o in sdk] == [{**NO_TOOLS, **NOT_SAVED}, NO_TOOLS] diff --git a/plugins/security-guidance/tests/test_secret_renames.py b/plugins/security-guidance/tests/test_secret_renames.py new file mode 100644 index 00000000..7d4e38fb --- /dev/null +++ b/plugins/security-guidance/tests/test_secret_renames.py @@ -0,0 +1,149 @@ +"""A tracked file renamed away from a secret-shaped name stays out of the +Stop review, however the rename reached git.""" +import errno +import os +import subprocess + +import pytest + +from conftest import ( + GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, +) + +import diffstate +import gitutil + +SECRET_BODY = "".join(f"KEY_{i}=SECRET_VALUE_{i}\n" for i in range(30)) +EDIT = "import os\nos.system(input())\n" + + +def _repo(tmp_path): + return make_repo(tmp_path / "repo", {"deploy_rsa": SECRET_BODY, "app.py": "x = 1\n"}) + + +def _sent(stub_api): + return "".join(stub_api.bodies) + + +def _rename(repo, how): + if how == "moved": + os.rename(repo / "deploy_rsa", repo / "settings.py") + return + git(repo, "mv", "deploy_rsa", "settings.py") + if how == "committed": + git(repo, "commit", "-qm", "rename") + elif how == "amended": + git(repo, "commit", "-q", "--amend", "-m", "init, renamed") + # Edited after the commit, so the file is still part of the turn. + with open(repo / "settings.py", "a") as f: + f.write("KEY_NEW=SECRET_VALUE_NEW\n") + + +@pytest.mark.parametrize("how", ["moved", "staged", "committed", "amended"]) +def test_stop_review_leaves_the_renamed_file_out(tmp_path, hook_env, stub_api, how): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), hook_env) + _rename(repo, how) + (repo / "app.py").write_text(EDIT) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert m.get("skip_reason") is None, m + assert m.get("files_reviewed") == 1 + # A plain mv is not a rename to git: the old name is listed as deleted. + assert m.get("secret_renamed") == (None if how == "moved" else 1) + assert "os.system" in _sent(stub_api) + assert "SECRET_VALUE" not in _sent(stub_api) + + +def test_stop_review_with_nothing_but_the_rename_sends_nothing(tmp_path, hook_env, stub_api): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), hook_env) + git(repo, "mv", "deploy_rsa", "settings.py") + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + assert metrics_of(stdout).get("skip_reason") == 7 + assert stub_api.bodies == [] + + +def test_commit_review_leaves_the_renamed_file_out(tmp_path, hook_env, stub_api): + repo = _repo(tmp_path) + git(repo, "mv", "deploy_rsa", "settings.py") + _sha, out = commit_file(repo, "app.py", EDIT) + run_hook(bash_payload(repo, "git commit -m change", stdout=out), hook_env) + assert "os.system" in _sent(stub_api) + assert "SECRET_VALUE" not in _sent(stub_api) + + +@pytest.fixture +def git_env(monkeypatch): + """The suite's git settings for calls made in this process.""" + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + monkeypatch.setattr(gitutil, "_secret_rename_origins", {}) + monkeypatch.setattr(diffstate, "_secret_rename_origins", gitutil._secret_rename_origins) + + +def test_listings_are_unchanged_and_note_the_secret_origin(tmp_path, git_env): + repo = make_repo(tmp_path / "repo", { + "deploy_rsa": SECRET_BODY, "old name.py": SECRET_BODY + "x = 1\n", + "gone.py": "x = 1\n", "edit.py": "x = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + git(repo, "mv", "old name.py", "new name.py") + git(repo, "rm", "-q", "gone.py") + (repo / "edit.py").write_text("x = 2\n") + names = {"settings.py", "new name.py", "gone.py", "edit.py"} + assert gitutil._git_name_only(str(repo), "HEAD") == names + assert gitutil._secret_rename_origins == {"settings.py": "deploy_rsa"} + gitutil._secret_rename_origins.clear() + assert gitutil._git_status_porcelain(str(repo)) == (names, set()) + assert gitutil._secret_rename_origins == {"settings.py": "deploy_rsa"} + + +def test_review_set_gains_only_the_origin_of_a_reviewed_file(tmp_path, git_env): + repo = make_repo(tmp_path / "repo", { + "deploy_rsa": SECRET_BODY, "old.py": SECRET_BODY + "x = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + git(repo, "mv", "old.py", "new.py") + paths, _base, root, _untracked, metrics = diffstate.compute_v2_review_set(str(repo), None, None, {}) + assert sorted(os.path.relpath(p, root) for p in paths) == ["deploy_rsa", "new.py", "settings.py"] + assert metrics["dirty_now_count"] == 2 and metrics["review_set_count"] == 3 + assert metrics["secret_renamed"] == 1 + + +def test_origin_still_pairs_beside_a_nested_repo_and_a_split_path_list( + tmp_path, git_env, monkeypatch): + repo = make_repo(tmp_path / "repo", {"deploy_rsa": SECRET_BODY, "app.py": "x = 1\n"}) + make_repo(repo / "nested", {"inner.py": "y = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + (repo / "app.py").write_text(EDIT) + (repo / "a_much_longer_module_name.py").write_text("y = 1\n") + (repo / "another_quite_long_module_name.py").write_text("y = 2\n") + for i in range(20): + (repo / f"note{i:02d}.txt").write_text("x\n") + paths, base, root, untracked, metrics = diffstate.compute_v2_review_set(str(repo), None, None, {}) + names = [os.path.relpath(p, root) for p in paths] + assert "deploy_rsa" in names and "settings.py" in names + assert not any(n.startswith("nested") for n in names) + assert metrics["secret_renamed"] == 1 + + # The OS refuses the one command that holds every path, so the paths go + # out in several: the old name has to be in the one with the new name. + real_popen = subprocess.Popen + limit = sum(len(a) + 1 for a in gitutil.GIT_CMD) + 220 + diffs = [] + + def popen(cmd, *args, **kwargs): + if sum(len(a) + 1 for a in cmd) > limit: + raise OSError(errno.E2BIG, "Argument list too long") + if "diff" in cmd: + diffs.append(cmd) + return real_popen(cmd, *args, **kwargs) + + monkeypatch.setattr(subprocess, "Popen", popen) + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 80) + diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert len(diffs) > 1 and all("deploy_rsa" in c for c in diffs) + reviewed = gitutil.parse_diff_into_files(diff) + assert sorted(f for f, _ in reviewed) == [ + "a_much_longer_module_name.py", "another_quite_long_module_name.py", "app.py"] + assert "SECRET_VALUE" not in "".join(d for _, d in reviewed) diff --git a/plugins/security-guidance/tests/test_slow_prompt_metrics.py b/plugins/security-guidance/tests/test_slow_prompt_metrics.py index fa947507..827b4642 100644 --- a/plugins/security-guidance/tests/test_slow_prompt_metrics.py +++ b/plugins/security-guidance/tests/test_slow_prompt_metrics.py @@ -10,7 +10,7 @@ import gitutil from conftest import git, make_repo, metrics_of, run_hook, ups_payload SLOW = 1.2 -STASH = '*"stash create"*' +SNAPSHOT = '*"add -u"*' MOUNTS = ( "25 30 8:32 / / rw,relatime - ext4 /dev/sdc rw\n" "60 25 0:50 / /mnt/c rw,noatime - 9p C:\\134 rw,aname=drivers\n" @@ -42,7 +42,7 @@ def _slow(hook_env, tmp_path, match): def test_slow_capture_reports_where_the_time_went(repo, hook_env, tmp_path): - rc, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH)) + rc, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, SNAPSHOT)) m = metrics_of(out) assert rc == 0 assert m["ups_ms"] >= SLOW * 1000 @@ -60,7 +60,7 @@ def test_slow_untracked_listing_is_told_apart(repo, hook_env, tmp_path): def test_slow_prompt_with_stop_review_off_lists_nothing(repo, hook_env, tmp_path): - env = {**_slow(hook_env, tmp_path, STASH), "ENABLE_STOP_REVIEW": "0"} + env = {**_slow(hook_env, tmp_path, SNAPSHOT), "ENABLE_STOP_REVIEW": "0"} m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) assert m["ups_baseline_ms"] >= SLOW * 1000 assert m["ups_untracked_ms"] == 0 @@ -90,7 +90,7 @@ def test_failed_snapshot_is_flagged(repo, hook_env, tmp_path): shim = tmp_path / "bin" shim.mkdir() (shim / "git").write_text( - f'#!/bin/sh\ncase "$*" in {STASH}) sleep {SLOW}; exit 1;; esac\n' + f'#!/bin/sh\ncase "$*" in *"write-tree"*) sleep {SLOW}; exit 1;; esac\n' f'exec "{shutil.which("git")}" "$@"\n') (shim / "git").chmod(0o755) env = {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"} @@ -110,14 +110,14 @@ def test_slow_launcher_is_reported_on_a_fast_prompt(repo, hook_env): def test_other_hosts_get_no_output(repo, hook_env, tmp_path): - env = {k: v for k, v in _slow(hook_env, tmp_path, STASH).items() + env = {k: v for k, v in _slow(hook_env, tmp_path, SNAPSHOT).items() if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT")} env["SECURITY_GUIDANCE_PORTABLE_OUTPUT"] = "1" assert run_hook(ups_payload(str(repo)), env)[1].strip() == "" def test_row_holds_no_path_and_valid_keys(repo, hook_env, tmp_path): - _, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH)) + _, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, SNAPSHOT)) assert str(repo) not in out and str(tmp_path) not in out metrics = json.loads(out)["metrics"] assert all(re.fullmatch(r"[a-z][a-z0-9_]{0,39}", k) for k in metrics) @@ -128,7 +128,7 @@ def test_slow_capture_saves_the_same_baseline(repo, hook_env, tmp_path): (repo / "app.py").write_text("print('changed')\n") (repo / "new.txt").write_text("untracked\n") states = [] - for name, env in (("fast", hook_env), ("slow", _slow(hook_env, tmp_path, STASH))): + for name, env in (("fast", hook_env), ("slow", _slow(hook_env, tmp_path, SNAPSHOT))): d = tmp_path / name d.mkdir() env = {k: v for k, v in env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} diff --git a/plugins/security-guidance/tests/test_stop_scope_metrics.py b/plugins/security-guidance/tests/test_stop_scope_metrics.py index c65103b6..7ae6dc64 100644 --- a/plugins/security-guidance/tests/test_stop_scope_metrics.py +++ b/plugins/security-guidance/tests/test_stop_scope_metrics.py @@ -29,13 +29,13 @@ def _turn(repo, env, edits=(), during=None): return _stop(repo, env) -def _no_stash_env(tmp_path, hook_env): - """An env whose `git stash` fails, like a snapshot that could not be taken.""" +def _no_write_tree_env(tmp_path, hook_env): + """An env whose `git write-tree` fails, like a snapshot that could not be taken.""" bindir = tmp_path / "bin" bindir.mkdir() shim = bindir / "git" shim.write_text( - '#!/bin/sh\nfor a in "$@"; do [ "$a" = stash ] && exit 1; done\n' + '#!/bin/sh\nfor a in "$@"; do [ "$a" = write-tree ] && exit 1; done\n' f'exec "{shutil.which("git")}" "$@"\n') shim.chmod(0o755) return {**hook_env, "PATH": f"{bindir}{os.pathsep}{hook_env['PATH']}"} @@ -127,7 +127,7 @@ class TestSnapshot: def test_failed_snapshot_is_counted(self, hook_env, workspace, tmp_path): ws, repo = workspace (repo / "app.py").write_text(VULN_PY) # uncommitted work from before the turn - m = _turn(repo, _no_stash_env(tmp_path, hook_env), edits=[ws / "notes.md"]) + m = _turn(repo, _no_write_tree_env(tmp_path, hook_env), edits=[ws / "notes.md"]) assert m["files_reviewed"] == 1 and m["review_scope"] == 130001 # The next prompt takes a real snapshot and the flag is gone. m = _turn(repo, hook_env, edits=[repo / "app.py"], @@ -138,7 +138,7 @@ class TestSnapshot: def test_flag_follows_the_snapshot_taken_after_a_finding(self, hook_env, stub_api, workspace, tmp_path): _, repo = workspace - broken = _no_stash_env(tmp_path, hook_env) + broken = _no_write_tree_env(tmp_path, hook_env) stub_api.vulns = [STUB_VULN] # Good snapshot at the prompt; the one taken after the finding fails. run_hook(ups_payload(repo), hook_env) diff --git a/plugins/security-guidance/tests/test_temp_index_cleanup.py b/plugins/security-guidance/tests/test_temp_index_cleanup.py index 4ac19ea5..9b103a71 100644 --- a/plugins/security-guidance/tests/test_temp_index_cleanup.py +++ b/plugins/security-guidance/tests/test_temp_index_cleanup.py @@ -220,7 +220,7 @@ class TestOwnerGone: @pytest.mark.skipif(os.name == "nt", reason="uses signals and a /bin/sh git shim") class TestHookProcessKilled: def _start_slow_hook(self, tmp_path, hook_env, repo): - """Start a UserPromptSubmit hook whose `git stash create` hangs, and + """Start a UserPromptSubmit hook whose snapshot `git add -u` hangs, and return once its index copy exists.""" import shutil import subprocess @@ -233,7 +233,7 @@ class TestHookProcessKilled: shim = bindir / "git" shim.write_text( "#!/bin/sh\n" - 'case "$*" in *"stash create"*) [ -n "$SLOW_GIT" ] && exec sleep 60;; esac\n' + 'case "$*" in *"add -u"*) [ -n "$SLOW_GIT" ] && exec sleep 60;; esac\n' f'exec "{real_git}" "$@"\n' ) shim.chmod(0o755) diff --git a/plugins/security-guidance/tests/test_unmatched_bash_metric.py b/plugins/security-guidance/tests/test_unmatched_bash_metric.py new file mode 100644 index 00000000..8933bbd1 --- /dev/null +++ b/plugins/security-guidance/tests/test_unmatched_bash_metric.py @@ -0,0 +1,162 @@ +"""Bash hook starts that match no commit or push are counted; nothing changes.""" +import itertools +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from conftest import HOOK_SCRIPT, STUB_VULN, VULN_PY, bash_payload, commit_file, metrics_of, run_hook + +import security_reminder_hook as hook + +WEIGHT = hook._UNMATCHED_BASH_SAMPLE +SHELL_PATTERN = "|".join(f"*{a}*{b}*" for a, b in hook._SHELL_PRECHECK_PAIRS) + + +def _call_id(sampled): + for n in itertools.count(): + tool_use_id = f"toolu_{n}" + if hook._unmatched_bash_sampled({"tool_use_id": tool_use_id}) is sampled: + return tool_use_id + + +def _raw(command, stdout="ok"): + return json.dumps(bash_payload("/w", command, stdout=stdout)) + + +def test_unmatched_call_reports_what_a_text_check_would_do(workspace, hook_env): + ws, _ = workspace + loop = bash_payload("/w", "for f in a b; do echo $f; done", tool_use_id=_call_id(True)) + rc, so, se = run_hook(loop, hook_env) + m = metrics_of(so) + assert rc == 0 and se == "" + assert m["bash_no_match"] == WEIGHT and m["precheck_skip"] == WEIGHT and m["pv"] + + # Text mentions pass a text check and still match nothing. + for command, stdout in (("git log --grep commit", ""), ("ls", "run git push next")): + p = bash_payload("/w", command, stdout, tool_use_id=_call_id(True)) + rc, so, se = run_hook(p, hook_env) + m = metrics_of(so) + assert rc == 0 and m["bash_no_match"] == WEIGHT and m["precheck_skip"] == 0 + + +def test_unsampled_call_stays_silent(workspace, hook_env): + loop = "for f in a b; do echo $f; done" + assert run_hook(bash_payload("/w", loop, tool_use_id=_call_id(False)), hook_env) == (0, "", "") + assert run_hook(bash_payload("/w", loop), hook_env) == (0, "", "") # no call id + + +def test_other_hosts_get_no_row(workspace, hook_env): + markers = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "SECURITY_GUIDANCE_PORTABLE_OUTPUT") + env = {k: v for k, v in hook_env.items() if k not in markers} + env["PLUGIN_ROOT"] = "/p" + p = bash_payload("/w", "for f in a b; do echo $f; done", tool_use_id=_call_id(True)) + assert run_hook(p, env) == (0, "", "") + + +def test_one_call_in_ten_is_sampled(): + picked = sum(hook._unmatched_bash_sampled({"tool_use_id": f"toolu_{n}"}) for n in range(20000)) + assert 20000 / WEIGHT * 0.85 < picked < 20000 / WEIGHT * 1.15 + assert not hook._unmatched_bash_sampled({}) and not hook._unmatched_bash_sampled({"tool_use_id": 7}) + + +def test_pairs_cover_every_verb_in_the_regexes(): + # A verb added to either regex has to be added to _SHELL_PRECHECK_PAIRS + # and to _commands() below. + assert hook._GIT_COMMIT_RE.pattern.endswith(r"\s+commit\b(?!-)|\bgt\s+(?:create|modify)\b") + assert hook._GIT_PUSH_RE.pattern.endswith(r"\s+push\b|\bgt\s+submit\b)") + + +def _commands(): + """Commands the commit and push regexes match, in the spellings they allow.""" + opts = ["", " -C sub", " -c user.name=x", " -c 'a.b=c d'", " --git-dir=.git", " --no-pager", + " -P", " --namespace=n", " --work-tree .", " -C a -c b=c --no-pager"] + seps = [" ", "\t", " ", "\n"] + heads = ["", "cd x && ", "FOO=1 ", "(", "for i in 1; do ", "echo \"$(", "/usr/bin/", "x=`"] + for head, opt, sep, verb in itertools.product(heads, opts, seps, ["commit", "push"]): + yield f"{head}git{opt}{sep}{verb} -m 'é \"q\" \\ done'" + for head, sep, verb in itertools.product(heads, seps, ["create", "modify", "submit"]): + yield f"{head}gt{sep}{verb} --all" + + +def test_text_check_never_drops_a_reviewed_command(): + matched = [c for c in _commands() if hook._GIT_COMMIT_RE.search(c) or hook._GIT_PUSH_RE.search(c)] + assert len(matched) > 600 + for command in matched: + for ensure_ascii in (True, False): + raw = json.dumps(bash_payload("/w", command), ensure_ascii=ensure_ascii) + assert hook._shell_precheck_passes(raw), command + + +CASES = [ + ("ls -la | head", False), + ("echo commit the git way", False), # wrong order + ("grep -c gt app.py", False), + ("git status && echo 'ready to commit'", True), + ("gt log; echo submit", True), + ("git\tpush", True), + ("digit; echo pushed", True), +] + + +def test_text_check_on_known_strings(): + for command, passes in CASES: + assert hook._shell_precheck_passes(_raw(command)) is passes, command + + +def _working_bash(): + """A bash that runs a script. On Windows that is the one shipped with + git: the `bash` on PATH there can be the WSL launcher, which is not one.""" + found = [] + git = shutil.which("git") + if sys.platform == "win32" and git: + root = Path(git).resolve().parent.parent + found += [root / "bin" / "bash.exe", root / "usr" / "bin" / "bash.exe"] + if shutil.which("bash"): + found.append(Path(shutil.which("bash"))) + for bash in found: + try: + r = subprocess.run([str(bash), "-c", "echo ok"], capture_output=True, timeout=30) + except (OSError, subprocess.SubprocessError): + continue + if r.returncode == 0 and r.stdout.strip() == b"ok": + return str(bash) + return None + + +def test_text_check_agrees_with_the_shell_pattern(): + bash = _working_bash() + if not bash: + pytest.skip("needs a working bash") + script = f'input=$(cat); case "$input" in {SHELL_PATTERN}) echo pass ;; *) echo skip ;; esac' + for command, _ in CASES: + raw = _raw(command) + r = subprocess.run([bash, "-c", script], input=raw.encode(), capture_output=True, timeout=30) + assert r.stdout.strip() in (b"pass", b"skip"), r.stderr + assert (r.stdout.strip() == b"pass") is hook._shell_precheck_passes(raw), command + + +def test_reviewed_command_a_text_check_would_drop_is_flagged(workspace, hook_env, stub_api): + ws, repo = workspace + stub_api.vulns = [STUB_VULN] + _, out = commit_file(repo, "app.py", VULN_PY) + raw = json.dumps(bash_payload(repo, "git commit -m change", out)) + # Same command, with one letter written as a JSON escape. + raw = raw.replace('"git commit -m change"', '"git \\u0063ommit -m change"') + assert json.loads(raw)["tool_input"]["command"] == "git commit -m change" + if hook._shell_precheck_passes(raw): + pytest.skip("the temporary path itself passes the text check") + r = subprocess.run([sys.executable, str(HOOK_SCRIPT)], input=raw, capture_output=True, + text=True, env=hook_env, timeout=120) + m = metrics_of(r.stdout) + assert m["precheck_miss"] == 1 and m.get("commit_review") is True + assert list(m).index("precheck_miss") < 3 # ahead of the row's own keys + + # The ordinary spelling carries no flag. + _, out = commit_file(repo, "b.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), hook_env) + m = metrics_of(so) + assert m.get("commit_review") is True and "precheck_miss" not in m |
