diff options
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 10 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 41 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 10 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/ensure_agent_sdk.py | 10 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/extensibility.py | 27 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/hooks.json | 50 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 154 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/session_state.py | 72 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 3 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_portable_output.py | 181 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_prompt_untracked_snapshot.py | 169 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_repo_resolution.py | 41 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_state_file.py | 197 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_user_config_dir.py | 98 |
14 files changed, 941 insertions, 122 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index c51dcb4a..18e5cddc 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -68,6 +68,14 @@ Claude Code does not pass your sign-in to plugins in a session started with `CLA | `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) | +### Hook output for other hosts + +```bash +SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 # default: detected +``` + +The hooks' JSON output carries two fields that only Claude Code reads (`metrics` and `rewakeSummary`), and the SessionStart hook prints a separate `{"async": ...}` line first. A host that validates hook output against a closed schema rejects them. In portable mode they are left out, so every hook prints one JSON object with only the standard fields (`decision`, `reason`, `systemMessage`, `hookSpecificOutput`), and the SessionStart hook runs to completion before the host continues. It turns on by itself when the host passes `PLUGIN_ROOT` and does not identify itself as Claude Code; set the variable to `1` or `0` to force it either way. + ### Higher-recall mode ```bash @@ -80,7 +88,7 @@ Runs two parallel review calls and unions the findings. Catches a few percentage Drop a `claude-security-guidance.md` in any of: -- `~/.claude/claude-security-guidance.md` — user-wide rules +- `~/.claude/claude-security-guidance.md` — user-wide rules (when `CLAUDE_CONFIG_DIR` is set, the same file in that directory is read too) - `<project>/.claude/claude-security-guidance.md` — project rules, intended to be committed - `<project>/.claude/claude-security-guidance.local.md` — local overrides, intended to be `.gitignore`'d diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 44b205f0..f05a0094 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -94,6 +94,47 @@ PROVENANCE_BANNER = ( ) +# Output that only Claude Code reads: the `metrics` and `rewakeSummary` fields, +# and the separate `{"async": ...}` line an async hook prints first. Other hosts +# that run this plugin's hooks can validate hook output against a closed schema +# and reject the whole output over a field or a second line they do not know, +# which shows up as a hook error. +_CLAUDE_CODE_OUTPUT_FIELDS = ("metrics", "rewakeSummary") + + +def _detect_portable_output(): + forced = os.environ.get("SECURITY_GUIDANCE_PORTABLE_OUTPUT", "").strip().lower() + if forced in ("1", "true", "yes", "on"): + return True + if forced in ("0", "false", "no", "off"): + return False + if os.environ.get("CLAUDECODE") or os.environ.get("CLAUDE_CODE_ENTRYPOINT"): + return False + return bool(os.environ.get("PLUGIN_ROOT")) + + +# Decided once, from the environment the host started the hook with: code the +# hook runs in-process later can set these variables itself. +_PORTABLE_OUTPUT = _detect_portable_output() + + +def portable_output(): + """True when stdout should carry only the standard hook output fields. + + SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 or =0 forces it on or off. Otherwise it + is on only when the host passes PLUGIN_ROOT and does not identify itself as + Claude Code, so Claude Code and direct invocations are unchanged.""" + return _PORTABLE_OUTPUT + + +def write_hook_output(out): + """Print one hook output line. In portable mode the Claude Code only + fields are left out; what remains (possibly `{}`) is still valid output.""" + if portable_output(): + out = {k: v for k, v in out.items() if k not in _CLAUDE_CODE_OUTPUT_FIELDS} + print(json.dumps(out), flush=True) + + def _read_plugin_version_int(): """Encode plugin.json version "M.m.p" as M*10000 + m*100 + p so it fits the bool|number metrics constraint. Returns 0 if unreadable.""" diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 74870c15..7725cdd9 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -104,17 +104,22 @@ def consume_stop_state(session_id, clear=True): "fire_count_expired": expired and state.get("stop_hook_fire_count", 0) > 0, "previous_findings": [] if findings_expired else list(state.get("previous_findings", [])), "reviewed_diff_hash": state.get("reviewed_diff_hash"), + # State lost or overwritten since the last Stop (session_state). + "state_resets": state.get("state_resets", 0), + "state_overwrites": state.get("state_overwrites", 0), } if clear: state["touched_paths"] = [] state.pop("reviewed_diff_hash", None) + state.pop("state_resets", None) + state.pop("state_overwrites", None) return snap return with_locked_state(session_id, _snap) or { "touched_paths": [], "baseline_sha": None, "head_at_capture": None, "untracked_at_baseline": {}, "fire_count": 0, "fire_count_expired": False, "previous_findings": [], - "reviewed_diff_hash": None, + "reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0, } @@ -199,7 +204,8 @@ def capture_git_baseline(cwd): NOTE: `git stash create` 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. + 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 diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index f5d016db..f49e857d 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -27,7 +27,7 @@ from pathlib import Path # → ~/.claude/security. See _base.state_dir for resolution precedence. Re-aliased # here to match the existing local name (state_dir was already a local var in # main() and _maybe_emit_user_notice). -from _base import state_dir as _resolve_state_dir +from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output # Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry. NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python @@ -765,7 +765,11 @@ if __name__ == "__main__": # SessionStart runs before the user's first prompt; doing this in the # background means the first commit-review of the session usually finds # the venv ready. - print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True) + # + # Not printed in portable mode: a host that reads stdout as one JSON + # document rejects a second line, and runs this hook to completion anyway. + if not portable_output(): + print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True) t0 = time.perf_counter() try: outcome, err_phase, err_kind = main() @@ -859,4 +863,4 @@ if __name__ == "__main__": "additionalContext": notice, } response["systemMessage"] = notice - print(json.dumps(response), flush=True) + write_hook_output(response) diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index a9c7f8fe..cb3e0a8d 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -12,11 +12,13 @@ Two extensibility points, both additive only: Discovery, in precedence order (matching CLAUDE.md / settings.json): - ``~/.claude/<name>`` (user) + - ``$CLAUDE_CONFIG_DIR/<name>`` (user, when set to another directory) - ``<cwd>/.claude/<name>`` (project, committed) - ``<cwd>/.claude/<name>.local.<ext>`` (project local, gitignored) Managed delivery via ``managed-settings.json`` is not yet supported. -Org admins can still push files to ``~/.claude/`` via MDM/GPO. +Org admins can still push files to ``~/.claude/`` (or the directory +``CLAUDE_CONFIG_DIR`` names) via MDM/GPO. Trust model: - The ``.md`` is repo-controlled and goes into the USER prompt (not system), @@ -89,11 +91,32 @@ def user_patterns() -> List[Dict[str, Any]]: # ── claude-security-guidance.md ─────────────────────────────────────────────────────── +def _user_config_dirs() -> List[str]: + """User-level config directories. ``~/.claude`` always, so a file placed + there keeps loading; then ``CLAUDE_CONFIG_DIR`` when it names another + directory. Empty is treated as not set, as in ``_base.state_dir``.""" + dirs = [os.path.expanduser(os.path.join("~", ".claude"))] + configured = (os.environ.get("CLAUDE_CONFIG_DIR") or "").strip() + if configured: + configured = os.path.expanduser(configured) + if _same_dir(configured, dirs[0]): + return dirs + dirs.append(configured) + return dirs + + +def _same_dir(a: str, b: str) -> bool: + try: + return os.path.samefile(a, b) + except OSError: + return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b)) + + def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str]]: """Existing config file paths, lowest precedence first (so concat reads in precedence order user → project → project-local). Truncation is done on the concatenated string, so lowest-precedence content is dropped last.""" - paths = [("User", os.path.expanduser(os.path.join("~", ".claude", basename)))] + paths = [("User", os.path.join(d, basename)) for d in _user_config_dirs()] if cwd: paths.append(("Project", os.path.join(cwd, ".claude", basename))) # claude-security-guidance.local.md / security-patterns.local.yaml diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json index a4723026..eef54730 100644 --- a/plugins/security-guidance/hooks/hooks.json +++ b/plugins/security-guidance/hooks/hooks.json @@ -37,58 +37,26 @@ { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git commit:*)", + "if": "Bash(git*commit*)", "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" }, { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git -C * commit *)", + "if": "Bash(git*push*)", "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" }, { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git push:*)", + "if": "Bash(gt *)", "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git -C * push*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt create:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt modify:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt submit:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" } ], "matcher": "Bash" diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 116059a7..639e9c64 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -86,6 +86,7 @@ from _base import ( # noqa: E402,F401 _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, state_dir as _resolve_state_dir, + write_hook_output as _write_hook_output, ) import extensibility # noqa: E402 from patterns import ( # noqa: E402,F401 @@ -296,7 +297,7 @@ def emit_metrics( out["reason"] = additional_context if system_message: out["systemMessage"] = system_message - print(json.dumps(out), flush=True) + _write_hook_output(out) def _llm_review_off(): @@ -600,29 +601,38 @@ def handle_user_prompt_submit(input_data): sys.exit(0) session_id = input_data.get("session_id", "default") - # stash-create 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(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - # Always capture the untracked snapshot. `git stash create` returns - # empty 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 something tracked is dirtied. - untracked_now = _f_ut.result() or {} + # 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 + # filter) is captured. + snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW + + def _capture(repo_cwd): + if not snapshot_untracked: + return capture_git_baseline(repo_cwd), None + # stash-create 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(capture_git_baseline, repo_cwd) + _f_ut = _ex.submit(_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 + # 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 + # something tracked is dirtied. + return _f_sha.result(), _f_ut.result() or {} + + sha, untracked_now = _capture(cwd) if not sha and not _git_toplevel(cwd): hint = load_repo_hint(session_id) if hint: debug_log(f"UPS: cwd is not a git repo; using repo hint {hint!r}") cwd = hint - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - untracked_now = _f_ut.result() or {} + sha, untracked_now = _capture(cwd) head = _git_rev_parse_head(cwd) # If the previous turn's Stop hook never ran (user interrupt, follow-up @@ -641,14 +651,24 @@ def handle_user_prompt_submit(input_data): # we still need to capture a baseline. if state.get("touched_paths") and state.get("baseline_sha"): preserved["value"] = True + # A baseline captured while the Stop review was off has no + # snapshot beside it. Without one the next Stop would take every + # untracked file in the tree as written this turn. + if untracked_now is not None and "untracked_at_baseline" not in state: + state["untracked_at_baseline"] = untracked_now return if sha: state["baseline_sha"] = sha state["head_at_capture"] = head # untracked_at_baseline is independent of whether the stash produced - # a SHA — write it unconditionally so compute_v2_review_set's - # preexisting-untracked exclusion works in untracked-only trees. - state["untracked_at_baseline"] = untracked_now + # 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 + # baseline. + if untracked_now is None: + state.pop("untracked_at_baseline", None) + else: + state["untracked_at_baseline"] = untracked_now with_locked_state(session_id, _save) if preserved["value"]: @@ -743,26 +763,33 @@ _COMMIT_DIFFSTAT_PATTERNS = [ # or trailing hook output isn't picked up and fed to `git show`. _COMMIT_SHA_RE = re.compile(r'^\[[^\]]*?\b([0-9a-f]{7,40})\]', re.MULTILINE) -# Regex matching `git commit` commands. Mirrors Claude Code's own commit -# detection — it does NOT tolerate `git -c k=v commit` global options, which -# keeps this hook aligned with CC's commit attribution on what counts as a -# commit. +# Regex matching `git commit` commands, global options included (see below). # # Also matches `gt create` and `gt modify` — Graphite's stacked-PR wrapper # around git. `gt create` produces a new commit (mapped to git commit # semantics); `gt modify` amends the current commit (mapped to git commit -# --amend, also flagged by _GIT_AMEND_RE below). The hooks.json matcher -# widening for `gt create:*` / `gt modify:*` / `gt submit:*` ships in the -# same change set — without that widening this regex change is dead code -# because the hook subprocess never spawns for gt invocations. See #2048. +# --amend, also flagged by _GIT_AMEND_RE below). hooks.json has a +# `Bash(gt *)` entry so the hook subprocess spawns for gt invocations. +# +# Global options allowed between `git` and the subcommand, shared by +# _GIT_COMMIT_RE and _GIT_PUSH_RE: `-C <path>`, `-c key=val`, `--opt=val`, +# the long options that take a separate value, and flags that take none +# (`--no-pager`, `-p`). A value may be quoted in part (`-c user.name="A B"`). +_GIT_OPT_VALUE = r'''(?:[^\s"']|"[^"]*"|'[^']*')+''' +_GIT_VALUE_OPTS = r'git-dir|work-tree|namespace|config-env|attr-source' +_GIT_GLOBAL_OPTS = ( + r'(?:\s+-[Cc]\s+' + _GIT_OPT_VALUE + + r'|\s+--[^\s=]+=' + _GIT_OPT_VALUE + + r'|\s+--(?:' + _GIT_VALUE_OPTS + r')\s+' + _GIT_OPT_VALUE + # `--help` / `--version` run no subcommand. + + r'|\s+(?:--(?!(?:' + _GIT_VALUE_OPTS + r'|help|version)\s)[^\s=]+|-[pP])(?=\s))*' +) _GIT_COMMIT_RE = re.compile( - # `git -C <path>` and `git -c key=val` global options are allowed between - # `git` and `commit` (mirrors the long-standing tolerance in - # _GIT_PUSH_RE). Without this, `git -C /repo commit` is silently dropped - # by the handler — see #2089's secondary finding. The gt branch has no - # global-option layer to worry about. - r'\bgit(?:\s+-[Cc]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+' - r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+commit\b' + # Without the global-option tolerance, `git -C /repo commit` is silently + # dropped by the handler — see #2089's secondary finding. The gt branch + # has no global-option layer to worry about. + # `(?!-)`: not the plumbing commands `git commit-graph` / `git commit-tree`. + r'\bgit' + _GIT_GLOBAL_OPTS + r'\s+commit\b(?!-)' r'|\bgt\s+(?:create|modify)\b' ) # Match either the `--amend` flag (with the leading whitespace boundary @@ -787,11 +814,9 @@ COMMIT_REVIEW_RATE_WINDOW_S = int( # ─── push-sweep ───────────────────────────────────────────────────────────── # # Mirrors Claude Code's own push-command matching — tolerates `git -C <p>` / -# `git -c k=v` global options. The hooks.json `Bash(git push:*)` matcher -# (subcommand prefix) doesn't, but those forms are rare in practice -# and the python only ever runs after CC's matcher fired, so this regex is a -# defensive re-gate, not a widening — `git -C path push` won't reach python -# unless chained with a plain `git push` in the same compound command. +# `git -c k=v` global options, as the hooks.json `Bash(git*push*)` matcher +# does. That matcher also lets through e.g. `git stash push`; this regex is +# what decides whether the command is a push. # # `gh pr create` is intentionally NOT a separate hooks.json matcher: gh runs # `git push` as a child process, which CC's matcher doesn't observe (it sees @@ -799,14 +824,13 @@ COMMIT_REVIEW_RATE_WINDOW_S = int( # entry would buy minimal extra coverage (sessions that push only via gh) at # the cost of an extra python spawn on every `... && gh pr create` compound # (the common case). Those sessions are caught on their next standalone `git push`. -# Matches `git push` (with optional `-c k=v` / `-C path` global options -# CC's hooks.json matcher doesn't tolerate) OR `gt submit` — Graphite's +# Matches `git push` (with optional `-c k=v` / `-C path` global options) +# OR `gt submit` — Graphite's # stacked-PR push command. gt submit forwards to `git push` internally, # but the bash hook fires on Claude's top-level command so we need to # recognize gt submit at the matcher level. See #2048. _GIT_PUSH_RE = re.compile( - r'(?:\bgit(?:\s+-[cC]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+' - r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+push\b|\bgt\s+submit\b)' + r'(?:\bgit' + _GIT_GLOBAL_OPTS + r'\s+push\b|\bgt\s+submit\b)' ) # `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on @@ -827,8 +851,9 @@ PUSH_SWEEP_REPORT_CAP = int(os.environ.get("SG_PUSH_SWEEP_REPORT_CAP", "3")) def _claim_bash_hook_once(input_data): """De-dupe across hooks.json `if` matchers firing for the same Bash call. - `git commit -m x && git push` matches both `Bash(git commit:*)` and - `Bash(git push:*)` `if` configs → CC spawns this script twice with the + `git commit -m x && git push` matches both `Bash(git*commit*)` and + `Bash(git*push*)` `if` configs, and a command CC cannot parse runs every + `if` config → CC spawns this script more than once with the SAME `tool_use_id`. The first spawn atomically creates a sentinel under `.git/`; subsequent spawns see it and exit early. Avoids redundant LLM calls (and the redundant asyncRewake) on compound commands. @@ -1232,9 +1257,10 @@ def handle_commit_review_posttooluse(input_data): command = tool_input.get("command", "") if not isinstance(command, str) or not _GIT_COMMIT_RE.search(command): - # Defensive only — hooks.json's `"if": "Bash(git commit:*)"` is the - # real gate so CC never spawns python3 for ls/grep/etc. This catches - # cases where CC's command matching fails open and spawns the hook anyway. + # hooks.json's `"if": "Bash(git*commit*)"` only keeps CC from + # spawning python3 for ls/grep/etc. It lets through other git commands + # with "commit" in them (`git merge --no-commit`), and CC runs the hook + # anyway when it cannot parse the command; this regex decides. sys.exit(0) debug_log(f"Commit review: detected git commit in command") @@ -1786,9 +1812,8 @@ def handle_push_sweep_posttooluse(input_data): ) interrupted = tool_response.get("interrupted", False) - # Re-gate: hooks.json `if` matched, but confirm with the broader regex - # (defensive — `git -C`/`-c` forms won't reach here via the hooks.json - # prefix matcher alone, but a compound with a plain `git push` would). + # Re-gate: hooks.json `if` matched (or CC could not parse the command + # and ran every entry), so confirm with the regex. if not _GIT_PUSH_RE.search(command): sys.exit(0) @@ -2160,6 +2185,13 @@ def handle_stop_hook(input_data): head_at_capture = snap["head_at_capture"] untracked_at_baseline = snap.get("untracked_at_baseline") or {} previous_findings = snap["previous_findings"] + # Only when it happened: state lost to an unreadable file, and saves that + # overwrote another hook's (possible only without locking). SubagentStop + # does not clear them, so it does not report them either. + if not is_subagent: + for _k in ("state_resets", "state_overwrites"): + if isinstance(snap.get(_k), int) and snap[_k] > 0: + _TAIL_METRICS[_k] = snap[_k] # Sweep pattern-warning outcomes (pure local work; stop_hook_active is # already guaranteed False here so no double-count guard needed). @@ -2547,11 +2579,15 @@ def main(): # Handle PostToolUse[Bash] — commit review or push sweep (asyncRewake). # - # hooks.json has two `if` configs under the Bash matcher (`git commit:*` - # and `git push:*`). CC evaluates each `if` independently and spawns this + # hooks.json has three `if` configs under the Bash matcher (`git*commit*`, + # `git*push*` and `gt *`), kept to one per kind because CC runs EVERY + # entry when it cannot parse the command (loops, some substitutions): one + # entry per spelling meant one python per entry on those calls. CC + # evaluates each `if` independently and spawns this # script ONCE PER MATCH — so `git commit -m x && git push` spawns python # twice with the same command string and the same tool_use_id. The python - # cannot tell which `if` fired it. + # cannot tell which `if` fired it, which is also why the three entries + # share one rewakeMessage. # # Routing therefore MUST check commit FIRST so that compound commit+push # commands continue to hit commit-review (the pre-existing behaviour) on @@ -2574,7 +2610,7 @@ def main(): # 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. - print(json.dumps({"metrics": {"bash_hook_dedup": True}}), flush=True) + _write_hook_output({"metrics": {"bash_hook_dedup": True}}) sys.exit(0) if _GIT_COMMIT_RE.search(cmd): handle_commit_review_posttooluse(input_data) @@ -2659,7 +2695,7 @@ def main(): if notice: output["systemMessage"] = notice if output: - print(json.dumps(output)) + _write_hook_output(output) sys.exit(0) diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py index 8dbadfd2..c8045532 100644 --- a/plugins/security-guidance/hooks/session_state.py +++ b/plugins/security-guidance/hooks/session_state.py @@ -17,6 +17,7 @@ except ImportError: import json import os import re +import tempfile from datetime import datetime from _base import debug_log, state_dir as _state_dir @@ -47,7 +48,7 @@ def get_lock_file(session_id): def cleanup_old_state_files(): - """Remove state files and lock files older than 30 days.""" + """Remove state files, lock files and leftover temporary files older than 30 days.""" try: state_dir = _state_dir() if not os.path.exists(state_dir): @@ -58,7 +59,7 @@ def cleanup_old_state_files(): for filename in os.listdir(state_dir): if filename.startswith("security_warnings_state_") and ( - filename.endswith(".json") or filename.endswith(".lock") + filename.endswith((".json", ".lock", ".tmp")) ): file_path = os.path.join(state_dir, filename) try: @@ -96,25 +97,79 @@ def load_state(session_id): if isinstance(data, dict): data.setdefault("shown_warnings", []) return data - except (json.JSONDecodeError, IOError, KeyError, TypeError): + except FileNotFoundError: + return {"shown_warnings": []} + except (ValueError, IOError, KeyError, TypeError): + # ValueError: not JSON, or bytes that do not decode. pass - return {"shown_warnings": []} + # The file is there but cannot be used, so everything the session had + # recorded is gone. Leave a mark for the Stop hook to report: a flag, not + # a count, since an earlier mark is lost with the rest. + debug_log(f"State file {state_file} is unreadable, starting from an empty state") + return {"shown_warnings": [], "state_resets": 1} + + +# Windows still writes the state file in place: a rename there is refused +# while another process has the file open and can make a concurrent open fail, +# and hooks run without a state lock on Windows (see with_locked_state). +_RENAME_INTO_PLACE = os.name != "nt" + + +def _write_then_rename(state_file, state): + """Write `state` to a temporary file and rename it over `state_file`. + Returns False, with nothing changed, when this directory does not allow + it; any other failure raises OSError and leaves the state file as it was.""" + tmp = None + try: + fd, tmp = tempfile.mkstemp( + dir=os.path.dirname(state_file), + prefix=os.path.basename(state_file) + ".", suffix=".tmp") + with os.fdopen(fd, "w") as f: + json.dump(state, f) + os.replace(tmp, state_file) + return True + except BaseException as e: + if tmp: + try: + os.unlink(tmp) + except OSError: + pass + if isinstance(e, PermissionError): + return False + raise def save_state(session_id, state): - """Save the full state dict to file.""" + """Save the full state dict to file. + + The new contents go to a temporary file that is then renamed over the + state file, so a hook killed part-way through a save (a timeout, an + interrupt) leaves the previous state. Written in place it left a truncated + file, which load_state reads as an empty state: the turn baseline, touched + paths and shown warnings were lost. + """ state_file = get_state_file(session_id) try: state_dir = os.path.dirname(state_file) if state_dir: os.makedirs(state_dir, exist_ok=True) + if _RENAME_INTO_PLACE and _write_then_rename(state_file, state): + return with open(state_file, "w") as f: json.dump(state, f) except (IOError, OSError) as e: debug_log(f"Failed to save state file {state_file}: {e}") +def _raw_state(state_file): + try: + with open(state_file, "rb") as f: + return f.read() + except OSError: + return None + + def with_locked_state(session_id, callback): """ Execute callback with exclusive access to the state file. @@ -132,8 +187,15 @@ def with_locked_state(session_id, callback): if fcntl is None: # No file locking available (Windows) — run without locking + state_file = get_state_file(session_id) + before = _raw_state(state_file) state = load_state(session_id) result = callback(state) + if _raw_state(state_file) != before: + # Another hook changed the state after it was read here, and this + # save is about to drop that change. Count how often it happens; + # the Stop hook reports the count. + state["state_overwrites"] = state.get("state_overwrites", 0) + 1 save_state(session_id, state) return result diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 11af0273..998401c2 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -128,7 +128,8 @@ def hook_env(tmp_path, stub_api): "CLAUDE_PROJECT_DIR", "HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", - "CLAUDE_CODE_USE_FOUNDRY")} + "CLAUDE_CODE_USE_FOUNDRY", + "PLUGIN_ROOT", "SECURITY_GUIDANCE_PORTABLE_OUTPUT")} env.update(GIT_ENV) env.update({ "SECURITY_WARNINGS_STATE_DIR": str(state), diff --git a/plugins/security-guidance/tests/test_portable_output.py b/plugins/security-guidance/tests/test_portable_output.py new file mode 100644 index 00000000..cad2052c --- /dev/null +++ b/plugins/security-guidance/tests/test_portable_output.py @@ -0,0 +1,181 @@ +import json +import os +import subprocess +import sys + +import pytest + +from conftest import ( + HOOKS_DIR, STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, ups_payload, +) + +# What a host with a closed hook output schema accepts. +STOP_FIELDS = {"continue", "decision", "reason", "stopReason", "suppressOutput", "systemMessage"} +POST_TOOL_USE_FIELDS = STOP_FIELDS | {"hookSpecificOutput"} +HOST_MARKERS = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT", + "SECURITY_GUIDANCE_PORTABLE_OUTPUT") + + +def _env(hook_env, **extra): + env = {k: v for k, v in hook_env.items() if k not in HOST_MARKERS} + env.update(extra) + return env + + +def _objects(stdout): + lines = [l for l in stdout.splitlines() if l.strip()] + return [json.loads(l) for l in lines] + + +def _review_with_finding(workspace, env, stub_api): + ws, repo = workspace + stub_api.vulns = [STUB_VULN] + run_hook(ups_payload(repo), env) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + return run_hook(stop_payload(repo), env) + + +class TestOtherHost: + def test_stop_skip_path_prints_only_standard_fields(self, workspace, hook_env): + ws, repo = workspace + rc, so, se = run_hook(stop_payload(repo), _env(hook_env, PLUGIN_ROOT=str(ws))) + assert rc == 0 + assert _objects(so) == [{}] + + def test_stop_finding_keeps_the_block_and_the_guidance(self, workspace, hook_env, stub_api): + rc, so, se = _review_with_finding(workspace, _env(hook_env, PLUGIN_ROOT="/p"), stub_api) + (out,) = _objects(so) + assert set(out) <= STOP_FIELDS, out + assert out["decision"] == "block" + assert "command_injection" in out["reason"] + assert "command_injection" in se + + def test_pattern_warning_keeps_the_guidance(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, PLUGIN_ROOT="/p") + (repo / "app.py").write_text(VULN_PY) + rc, so, se = run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + assert rc == 0 + (out,) = _objects(so) + assert set(out) <= POST_TOOL_USE_FIELDS, out + assert out["hookSpecificOutput"]["additionalContext"] + + def test_kill_switch_path(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, PLUGIN_ROOT="/p", SECURITY_GUIDANCE_DISABLE="1") + rc, so, se = run_hook(stop_payload(repo), env) + assert rc == 0 + assert all(set(o) <= STOP_FIELDS for o in _objects(so)) + + + def test_mode_is_not_changed_by_the_hook_process_itself(self, hook_env): + code = ("import os, _base\n" + "os.environ['CLAUDE_CODE_ENTRYPOINT'] = 'sdk-py'\n" + "_base.write_hook_output({'metrics': {'x': 1}, 'reason': 'r'})\n") + r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, + cwd=HOOKS_DIR, env=_env(hook_env, PLUGIN_ROOT="/p"), timeout=60) + assert _objects(r.stdout) == [{"reason": "r"}], r.stderr + + +class TestClaudeCodeUnchanged: + @pytest.mark.parametrize("extra", [ + {}, + {"PLUGIN_ROOT": "/p", "CLAUDECODE": "1"}, + {"PLUGIN_ROOT": "/p", "CLAUDE_CODE_ENTRYPOINT": "cli"}, + {"PLUGIN_ROOT": "/p", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "0"}, + ]) + def test_metrics_and_summary_are_still_sent(self, workspace, hook_env, stub_api, extra): + rc, so, se = _review_with_finding(workspace, _env(hook_env, **extra), stub_api) + (out,) = _objects(so) + assert out["metrics"]["vulns_found"] == 1 + assert out["rewakeSummary"] + assert out["decision"] == "block" + + def test_forced_on_under_claude_code(self, workspace, hook_env): + ws, repo = workspace + env = _env(hook_env, CLAUDECODE="1", SECURITY_GUIDANCE_PORTABLE_OUTPUT="1") + rc, so, se = run_hook(stop_payload(repo), env) + assert metrics_of(so) is None and _objects(so) == [{}] + + +# SessionStart runs ensure_agent_sdk.py. The wrapper picks the branch without +# installing anything: whether the SDK looks importable, and whether the +# interpreter looks older than the SDK supports. +SESSION_START_FIELDS = STOP_FIELDS | {"hookSpecificOutput"} +_BOOTSTRAP = """ +import importlib.util, os, runpy, sys +script, sdk, old_py = sys.argv[1:4] +sys.path.insert(0, os.path.dirname(script)) +real = importlib.util.find_spec +def find_spec(name, *a, **k): + if name == "claude_agent_sdk": + return object() if sdk == "present" else None + return real(name, *a, **k) +importlib.util.find_spec = find_spec +class V(tuple): + major, minor = property(lambda s: s[0]), property(lambda s: s[1]) +sys.version_info = V(((3, 9, 6) if old_py == "old" else (3, 12, 0)) + ("final", 0)) +sys.argv = [script] +runpy.run_path(script, run_name="__main__") +""" + + +def _session_start(tmp_path, branch, **extra): + state = tmp_path / "state" + state.mkdir(exist_ok=True) + sdk, old_py = "absent", "new" + if branch == "noop": + sdk = "present" + elif branch == "concurrent_build": + (state / "agent-sdk-venv.building").touch() + elif branch == "failure": + (tmp_path / "file").write_text("") + state = tmp_path / "file" / "state" + elif branch == "notice": + old_py = "old" + env = {k: v for k, v in os.environ.items() if k not in HOST_MARKERS} + env.update(SECURITY_WARNINGS_STATE_DIR=str(state), HOME=str(tmp_path), + PYTHONDONTWRITEBYTECODE="1", **extra) + r = subprocess.run( + [sys.executable, "-c", _BOOTSTRAP, str(HOOKS_DIR / "ensure_agent_sdk.py"), sdk, old_py], + input="{}", capture_output=True, text=True, env=env, timeout=60, + ) + return r.returncode, r.stdout, r.stderr + + +SESSION_START_BRANCHES = ["noop", "concurrent_build", "failure", "notice"] + + +class TestSessionStartOtherHost: + @pytest.mark.parametrize("branch", SESSION_START_BRANCHES) + def test_one_document_with_only_standard_fields(self, tmp_path, branch): + rc, so, se = _session_start(tmp_path, branch, PLUGIN_ROOT="/p") + assert rc == 0 and se == "" + out = json.loads(so) # the whole stream is one JSON document + assert set(out) <= SESSION_START_FIELDS, out + assert (out != {}) == (branch == "notice") + + def test_notice_is_kept(self, tmp_path): + rc, so, se = _session_start(tmp_path, "notice", PLUGIN_ROOT="/p") + out = json.loads(so) + assert "Python" in out["systemMessage"] + assert out["hookSpecificOutput"] == { + "hookEventName": "SessionStart", "additionalContext": out["systemMessage"]} + + +class TestSessionStartClaudeCodeUnchanged: + @pytest.mark.parametrize("branch,outcome", [ + ("noop", 0), ("concurrent_build", 5), ("failure", 3), ("notice", 6)]) + @pytest.mark.parametrize("extra", [ + {}, + {"PLUGIN_ROOT": "/p", "CLAUDECODE": "1"}, + {"PLUGIN_ROOT": "/p", "SECURITY_GUIDANCE_PORTABLE_OUTPUT": "0"}, + ]) + def test_async_line_then_metrics(self, tmp_path, branch, outcome, extra): + rc, so, se = _session_start(tmp_path, branch, **extra) + assert rc == 0 + first, second = _objects(so) + assert first == {"async": True, "asyncTimeout": 180000} + assert second["metrics"]["sdk_bootstrap"] == outcome + assert ("systemMessage" in second) == (branch == "notice") diff --git a/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py b/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py new file mode 100644 index 00000000..be0fc1ee --- /dev/null +++ b/plugins/security-guidance/tests/test_prompt_untracked_snapshot.py @@ -0,0 +1,169 @@ +import json +import os +import shutil + +import pytest + +from conftest import ( + VULN_PY, edit_payload, make_repo, metrics_of, run_hook, stop_payload, ups_payload, +) + +OFF_SWITCHES = [ + pytest.param({"ENABLE_STOP_REVIEW": "0"}, id="stop-review-off"), + pytest.param({"ENABLE_CODE_SECURITY_REVIEW": "0"}, id="all-reviews-off"), +] +OLD = "import os\nos.system(cmd)\n" + + +@pytest.fixture +def on(hook_env, tmp_path): + """hook_env with the Stop review on, and a `git` first on PATH that + records each call before running it.""" + shim = tmp_path / "bin" + shim.mkdir() + log = tmp_path / "git.log" + log.write_text("") + (shim / "git").write_text( + f'#!/bin/sh\nprintf \'%s\\n\' "$*" >> "{log}"\nexec "{shutil.which("git")}" "$@"\n') + (shim / "git").chmod(0o755) + env = {k: v for k, v in hook_env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} + env.update(HOME=str(tmp_path), PATH=f"{shim}{os.pathsep}{hook_env['PATH']}", + GIT_CALLS=str(log)) + return env + + +def _listed_untracked(env): + with open(env["GIT_CALLS"]) as f: + return any("ls-files --others" in line for line in f) + + +def _state(env, session_id="s1"): + path = os.path.join(env["SECURITY_WARNINGS_STATE_DIR"], + f"security_warnings_state_{session_id}.json") + with open(path) as f: + return json.load(f) + + +def _repo(tmp_path): + repo = make_repo(tmp_path / "repo", {"app.py": OLD}) + (repo / "notes.txt").write_text("scratch\n") + return repo + + +def _write_payload(cwd, file_path, content, session_id="s1"): + return { + "session_id": session_id, + "hook_event_name": "PostToolUse", + "tool_name": "Write", + "tool_input": {"file_path": str(file_path), "content": content}, + "tool_response": {}, + "cwd": str(cwd), + } + + +def _reviewed(stub_api): + n = len(stub_api.calls) + del stub_api.calls[:] + return n > 0 + + +pytestmark = pytest.mark.skipif(os.name == "nt", reason="the git recorder is a sh script") + + +class TestPrompt: + def test_review_on_takes_the_snapshot(self, tmp_path, on): + repo = _repo(tmp_path) + rc, _, _ = run_hook(ups_payload(repo), on) + assert rc == 0 + assert _listed_untracked(on) + assert list(_state(on)["untracked_at_baseline"]) == ["notes.txt"] + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_off_does_not_list_the_worktree(self, tmp_path, on, off): + repo = _repo(tmp_path) + rc, _, _ = run_hook(ups_payload(repo), {**on, **off}) + assert rc == 0 + assert not _listed_untracked(on) + assert "untracked_at_baseline" not in _state(on) + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_off_write_filter_still_knows_what_was_there(self, tmp_path, on, off): + """The stash baseline is still captured: a full-file Write that keeps + a risky call from before the prompt is not reported as new.""" + repo = _repo(tmp_path) + env = {**on, **off, "CLAUDE_PROJECT_DIR": str(repo)} + (repo / "app.py").write_text(OLD + "# edited before the prompt\n") + run_hook(ups_payload(repo), env) + + _rc, out, _ = run_hook(_write_payload(repo, repo / "app.py", OLD + "print('x')\n"), env) + assert "additionalContext" not in out + _rc, out, _ = run_hook(_write_payload( + repo, repo / "app.py", OLD + "import pickle\npickle.loads(data)\n"), env) + assert "pickle" in out and "os.system" not in out + + def test_review_off_uses_the_repo_hint_without_listing(self, tmp_path, on): + repo = _repo(tmp_path) + outside = tmp_path / "not-a-repo" + outside.mkdir() + (repo / "app.py").write_text(VULN_PY) + # The hint a commit review that resolved the repo leaves behind. + with open(os.path.join(on["SECURITY_WARNINGS_STATE_DIR"], + "security_warnings_state_s1.json"), "w") as f: + json.dump({"shown_warnings": [], "repo_root_hint": str(repo)}, f) + rc, _, _ = run_hook(ups_payload(outside), {**on, "ENABLE_STOP_REVIEW": "0"}) + assert rc == 0 + assert not _listed_untracked(on) + assert _state(on).get("baseline_sha") + + def test_review_off_drops_the_snapshot_of_an_older_baseline(self, tmp_path, on): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), on) + assert "untracked_at_baseline" in _state(on) + run_hook(ups_payload(repo), {**on, "ENABLE_STOP_REVIEW": "0"}) + assert "untracked_at_baseline" not in _state(on) + + +class TestTurn: + def test_review_on_reviews_only_new_untracked_files(self, tmp_path, on, stub_api): + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), on) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["skip_reason"] == 9 # empty review set + assert not _reviewed(stub_api) + + run_hook(ups_payload(repo), on) + (repo / "new_vuln.py").write_text(VULN_PY) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["files_reviewed"] == 1 + assert _reviewed(stub_api) + + @pytest.mark.parametrize("off", OFF_SWITCHES) + def test_review_switched_back_on_at_the_next_prompt(self, tmp_path, on, stub_api, off): + """Old untracked files are not reviewed as this turn's work.""" + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), {**on, **off}) + run_hook(stop_payload(repo), {**on, **off}) + + run_hook(ups_payload(repo), on) + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["skip_reason"] == 9 + assert not _reviewed(stub_api) + + def test_review_switched_back_on_after_an_interrupted_turn(self, tmp_path, on, stub_api): + """The interrupted turn's baseline is kept, so its edit is reviewed, + and the old untracked file beside it is not.""" + off = {**on, "ENABLE_STOP_REVIEW": "0"} + repo = _repo(tmp_path) + (repo / "old_vuln.py").write_text(VULN_PY) + run_hook(ups_payload(repo), off) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py"), off) # no Stop: interrupted + baseline = _state(on)["baseline_sha"] + + run_hook(ups_payload(repo), on) + assert _state(on)["baseline_sha"] == baseline + _rc, out, _ = run_hook(stop_payload(repo), on) + assert metrics_of(out)["files_reviewed"] == 1 + assert _reviewed(stub_api) diff --git a/plugins/security-guidance/tests/test_repo_resolution.py b/plugins/security-guidance/tests/test_repo_resolution.py index 8bcf24b9..30c94a7c 100644 --- a/plugins/security-guidance/tests/test_repo_resolution.py +++ b/plugins/security-guidance/tests/test_repo_resolution.py @@ -191,6 +191,10 @@ class TestRegexes: "git -c core.editor=true -C sub commit --amend", "git --git-dir=x/.git --work-tree=x commit -m x", "git --git-dir x/.git commit -m x", + "git --no-pager commit -m x", + "git -p --no-optional-locks -c user.name=x --bare commit -m x", + 'git -c user.name="First Last" -c user.email=a@b.c commit -S -m x', + "git --git-dir='a b/.git' --namespace ns commit -m x", "cd sub && git commit -m x", "gt create -m x", ]) @@ -199,16 +203,29 @@ class TestRegexes: @pytest.mark.parametrize("cmd", [ "git push", "git -C sub push origin main", 'git -C "a b" push', - "git --work-tree x push -u origin HEAD", "gt submit", + "git --work-tree x push -u origin HEAD", "git --no-pager push", + 'git -c http.extraHeader="X-A: b" push', "git --config-env http.extraheader=TOK push", "gt submit", ]) def test_push_re(self, cmd): assert hook._GIT_PUSH_RE.search(cmd) - @pytest.mark.parametrize("cmd", ["git status", "git log --oneline", "echo commit"]) + @pytest.mark.parametrize("cmd", ["git status", "git log --oneline", "echo commit", + "git commit-graph write --reachable", "git commit-tree HEAD^{tree}", + "git log --grep commit", "git stash push", + "git log --oneline commit", "git --no-pager log --grep commit", + "git merge --no-commit topic", "git --git-dir commit status", + "git --namespace commit log", "git --help commit", + 'git -c user.name="commit status']) def test_commit_re_negative(self, cmd): assert not hook._GIT_COMMIT_RE.search(cmd) - @pytest.mark.parametrize("unit", ['-c "a"', "-c 'a'", "--no-a=b", "--a=b=c=d", "--git-dir x"]) + @pytest.mark.parametrize("cmd", ["git stash push", "git log --grep push", "git commit-graph write", + "git --no-pager stash push", "git --no-pager log push"]) + def test_push_re_negative(self, cmd): + assert not hook._GIT_PUSH_RE.search(cmd) + + @pytest.mark.parametrize("unit", ['-c "a"', "-c 'a'", "--no-a=b", "--a=b=c=d", "--git-dir x", + "--no-pager", "-p", '-c a="b c"', "--namespace x"]) @pytest.mark.parametrize("regex,verb", [("_GIT_COMMIT_RE", "commit"), ("_GIT_PUSH_RE", "push")]) def test_global_option_prefix_is_linear(self, regex, verb, unit): cre = getattr(hook, regex) @@ -228,11 +245,19 @@ class TestHooksJson: assert stop["command"].endswith('security_reminder_hook.py"') assert stop["asyncRewake"] is True bash = [g for g in cfg["hooks"]["PostToolUse"] if g.get("matcher") == "Bash"][0] - ifs = {h.get("if") for h in bash["hooks"]} - assert {"Bash(git commit:*)", "Bash(git push:*)", "Bash(git -C * commit *)", - "Bash(git -C * push*)", "Bash(gt create:*)", "Bash(gt modify:*)", - "Bash(gt submit:*)"} <= ifs - + # One entry per kind, not per spelling: when Claude Code cannot parse + # a command it runs every entry, so each extra entry is one more process. + assert [h.get("if") for h in bash["hooks"]] == [ + "Bash(git*commit*)", "Bash(git*push*)", "Bash(gt *)"] + assert all(h["asyncRewake"] is True and h["rewakeMessage"] for h in bash["hooks"]) + + @pytest.mark.parametrize("cmd", ["git stash push", "git commit-graph write --reachable", + "git log --grep commit", "gt log"]) + def test_other_commands_the_if_patterns_let_through_do_nothing(self, workspace, hook_env, stub_api, cmd): + ws, repo = workspace + commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, cmd, ""), hook_env) + assert rc == 0 and so.strip() == "" and not stub_api.calls def _read_state(env): diff --git a/plugins/security-guidance/tests/test_state_file.py b/plugins/security-guidance/tests/test_state_file.py new file mode 100644 index 00000000..0d3a56b0 --- /dev/null +++ b/plugins/security-guidance/tests/test_state_file.py @@ -0,0 +1,197 @@ +import json +import os +import signal +import subprocess +import sys +import time + +import pytest + +from conftest import HOOKS_DIR, make_repo, metrics_of, run_hook, stop_payload, ups_payload + +import session_state as ss + + +@pytest.fixture +def state_dir(tmp_path, monkeypatch): + d = tmp_path / "state" + d.mkdir() + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d)) + monkeypatch.delenv("CLAUDE_CODE_REMOTE_SESSION_ID", raising=False) + # Keep the legacy lock-file sweep and the debug log out of the real home. + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setattr(ss, "debug_log", lambda _msg: None) + return d + + +def _seed(session_id="s1"): + ss.with_locked_state(session_id, lambda st: st.update( + baseline_sha="a" * 40, touched_paths=["x.py"], + untracked_at_baseline={f"dir/file_{i:05d}.py": i for i in range(1500)})) + + +def _on_disk(state_dir, session_id="s1"): + return json.loads((state_dir / f"security_warnings_state_{session_id}.json").read_text()) + + +def _leftovers(state_dir): + return sorted(p.name for p in state_dir.iterdir() if p.name.endswith(".tmp")) + + +_MARK_ONE = ( + "import sys; sys.path.insert(0, sys.argv[1]); import session_state as s; " + "s.with_locked_state('s1', lambda st: st['shown_warnings'].append(sys.argv[2]))" +) + +# A save that dies half-way through writing, as a hook killed on timeout does. +_KILLED_MID_SAVE = """ +import json, os, signal, sys +sys.path.insert(0, sys.argv[1]) +import session_state as s +def dump(obj, f, **kw): + data = json.dumps(obj) + f.write(data[:len(data) // 2]); f.flush() + os.kill(os.getpid(), signal.SIGKILL) +s.json.dump = dump +s.with_locked_state('s1', lambda st: st['touched_paths'].append('y.py')) +""" + + +@pytest.mark.skipif(os.name == "nt", reason="rename into place is not used on Windows") +class TestSaveIsAtomic: + def test_a_save_killed_part_way_keeps_the_previous_state(self, state_dir): + _seed() + r = subprocess.run([sys.executable, "-c", _KILLED_MID_SAVE, str(HOOKS_DIR)], + env=dict(os.environ)) + assert r.returncode == -signal.SIGKILL + state = ss.load_state("s1") + assert state["baseline_sha"] == "a" * 40 + assert state["touched_paths"] == ["x.py"] + assert len(state["untracked_at_baseline"]) == 1500 + assert "state_resets" not in state + + def test_no_temporary_file_is_left_behind(self, state_dir): + _seed() + ss.with_locked_state("s1", lambda st: st["touched_paths"].append("y.py")) + assert _on_disk(state_dir)["touched_paths"] == ["x.py", "y.py"] + assert _leftovers(state_dir) == [] + + def test_state_that_cannot_be_written_leaves_the_file_alone(self, state_dir): + _seed() + with pytest.raises(TypeError): + ss.save_state("s1", {"shown_warnings": [], "bad": object()}) + assert _on_disk(state_dir)["baseline_sha"] == "a" * 40 + assert _leftovers(state_dir) == [] + + def test_writes_in_place_where_the_directory_refuses_a_rename(self, state_dir, monkeypatch): + _seed() + + def refuse(_src, _dst): + raise PermissionError("rename refused") + monkeypatch.setattr(ss.os, "replace", refuse) + ss.with_locked_state("s1", lambda st: st["touched_paths"].append("y.py")) + assert _on_disk(state_dir)["touched_paths"] == ["x.py", "y.py"] + assert _leftovers(state_dir) == [] + + def test_a_full_disk_leaves_the_previous_state(self, state_dir, monkeypatch): + _seed() + + def full(_obj, f, **_kw): + f.write('{"shown_warn') + raise OSError(28, "No space left on device") + monkeypatch.setattr(ss.json, "dump", full) + ss.save_state("s1", {"shown_warnings": []}) + assert _on_disk(state_dir)["baseline_sha"] == "a" * 40 + assert _leftovers(state_dir) == [] + + def test_in_place_where_rename_is_not_used(self, state_dir, monkeypatch): + monkeypatch.setattr(ss, "_RENAME_INTO_PLACE", False) + monkeypatch.setattr(ss.os, "replace", lambda *_a: pytest.fail("renamed")) + _seed() + assert _on_disk(state_dir)["touched_paths"] == ["x.py"] + + +@pytest.mark.skipif(ss.fcntl is None, reason="needs file locking") +def test_concurrent_writers_all_land(state_dir): + """Eight hooks marking one warning each at the same moment keep all eight.""" + for _round in range(5): + (state_dir / "security_warnings_state_s1.json").unlink(missing_ok=True) + procs = [subprocess.Popen([sys.executable, "-c", _MARK_ONE, str(HOOKS_DIR), f"k{i}"], + env=dict(os.environ)) for i in range(8)] + assert [p.wait() for p in procs] == [0] * 8 + assert sorted(_on_disk(state_dir)["shown_warnings"]) == [f"k{i}" for i in range(8)] + assert _leftovers(state_dir) == [] + + +class TestStateLossIsCounted: + def test_missing_file_is_a_fresh_state(self, state_dir): + assert ss.load_state("s1") == {"shown_warnings": []} + + @pytest.mark.parametrize("content", [ + b"", b'{"baseline_sha": "abc", "touched_pa', b"42", b'{"baseline_sha": "\xff\xfe"}']) + def test_unreadable_file_is_counted(self, state_dir, content): + (state_dir / "security_warnings_state_s1.json").write_bytes(content) + assert ss.load_state("s1") == {"shown_warnings": [], "state_resets": 1} + + def test_overwriting_another_hooks_save_is_counted_without_locking( + self, state_dir, monkeypatch): + monkeypatch.setattr(ss, "fcntl", None) + _seed() + assert "state_overwrites" not in _on_disk(state_dir) + + def slow_hook(state): + # Another hook saves while this one is between its read and write. + time.sleep(0.01) + ss.save_state("s1", {**state, "touched_paths": ["x.py", "other.py"]}) + state["shown_warnings"].append("k") + ss.with_locked_state("s1", slow_hook) + after = _on_disk(state_dir) + assert after["state_overwrites"] == 1 + assert after["touched_paths"] == ["x.py"] # the other hook's save was lost + + def test_a_concurrent_save_of_the_same_state_is_not_counted(self, state_dir, monkeypatch): + monkeypatch.setattr(ss, "fcntl", None) + _seed() + + def reader(state): + ss.save_state("s1", dict(state)) # another hook that only read + return state["baseline_sha"] + assert ss.with_locked_state("s1", reader) == "a" * 40 + assert "state_overwrites" not in _on_disk(state_dir) + + def test_stop_reports_the_counts_once(self, tmp_path, hook_env): + repo = make_repo(tmp_path / "repo") + hook_env = {k: v for k, v in hook_env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} + state_file = os.path.join(hook_env["SECURITY_WARNINGS_STATE_DIR"], + "security_warnings_state_s1.json") + run_hook(ups_payload(repo), hook_env) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert "state_resets" not in m and "state_overwrites" not in m + + with open(state_file, "w") as f: + f.write('{"baseline_sha": "abc", "touched_pa') + run_hook(ups_payload(repo), hook_env) + with open(state_file) as f: + state = json.load(f) + state["state_overwrites"] = 3 + with open(state_file, "w") as f: + json.dump(state, f) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert (m["state_resets"], m["state_overwrites"]) == (1, 3) + + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert "state_resets" not in m and "state_overwrites" not in m + + +def test_cleanup_removes_old_temporary_files(state_dir): + old = state_dir / "security_warnings_state_s1.json.a1b2c3.tmp" + new = state_dir / "security_warnings_state_s2.json.a1b2c3.tmp" + old.write_text("{}") + new.write_text("{}") + long_ago = time.time() - 31 * 24 * 60 * 60 + os.utime(old, (long_ago, long_ago)) + ss.cleanup_old_state_files() + assert not old.exists() and new.exists() diff --git a/plugins/security-guidance/tests/test_user_config_dir.py b/plugins/security-guidance/tests/test_user_config_dir.py new file mode 100644 index 00000000..7c8a1245 --- /dev/null +++ b/plugins/security-guidance/tests/test_user_config_dir.py @@ -0,0 +1,98 @@ +"""User-level claude-security-guidance.md and security-patterns files are +found in the directory CLAUDE_CONFIG_DIR names, as well as in ~/.claude.""" +import json +import os + +import pytest + +import extensibility + +MARKER = "MARKER_POLICY_LINE" +PATTERNS = {"patterns": [{"rule_name": "marker_rule", "substrings": ["x"], "reminder": "r"}]} + + +@pytest.fixture +def home(tmp_path, monkeypatch): + h = tmp_path / "home" + h.mkdir() + monkeypatch.setenv("HOME", str(h)) + monkeypatch.setenv("USERPROFILE", str(h)) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + return h + + +def write_user_files(d, marker=MARKER, rule="marker_rule"): + d.mkdir(parents=True, exist_ok=True) + (d / "claude-security-guidance.md").write_text(f"- {marker}\n") + patterns = {"patterns": [dict(PATTERNS["patterns"][0], rule_name=rule)]} + (d / "security-patterns.json").write_text(json.dumps(patterns)) + + +def load(): + extensibility.load_for_session(None) + return extensibility.guidance_block(), [r["ruleName"] for r in extensibility.user_patterns()] + + +def test_files_in_configured_dir_are_loaded(home, monkeypatch): + cfg = home / ".claude-work" + write_user_files(cfg) + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg)) + guidance, rules = load() + assert MARKER in guidance + assert rules == ["user:marker_rule"] + + +def test_default_dir_still_loaded_when_config_dir_is_set(home, monkeypatch): + write_user_files(home / ".claude") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home / ".claude-work")) + guidance, rules = load() + assert MARKER in guidance + assert rules == ["user:marker_rule"] + + +def test_both_dirs_loaded_default_first(home, monkeypatch): + write_user_files(home / ".claude", marker="FROM_DEFAULT", rule="default_rule") + cfg = home / ".claude-work" + write_user_files(cfg, marker="FROM_CONFIGURED", rule="configured_rule") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg)) + guidance, rules = load() + assert guidance.index("FROM_DEFAULT") < guidance.index("FROM_CONFIGURED") + assert rules == ["user:default_rule", "user:configured_rule"] + + +@pytest.mark.parametrize("spelling", ["{home}/.claude", "{home}/.claude/", "~/.claude", "{home}/link"]) +def test_config_dir_naming_the_default_dir_is_read_once(home, monkeypatch, spelling): + write_user_files(home / ".claude") + os.symlink(home / ".claude", home / "link") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", spelling.format(home=home)) + guidance, rules = load() + assert guidance.count(MARKER) == 1 + assert rules == ["user:marker_rule"] + + +@pytest.mark.parametrize("value", ["", " "]) +def test_empty_config_dir_is_not_set(home, monkeypatch, value): + write_user_files(home / ".claude") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", value) + assert extensibility._user_config_dirs() == [str(home / ".claude")] + guidance, rules = load() + assert guidance.count(MARKER) == 1 + + +def test_tilde_in_config_dir_is_expanded(home, monkeypatch): + write_user_files(home / ".claude-work") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", "~/.claude-work") + guidance, _ = load() + assert MARKER in guidance + + +def test_project_files_unchanged(home, monkeypatch, tmp_path): + cfg = home / ".claude-work" + write_user_files(cfg, marker="FROM_USER") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(cfg)) + proj = tmp_path / "proj" + write_user_files(proj / ".claude", marker="FROM_PROJECT", rule="project_rule") + extensibility.load_for_session(str(proj)) + guidance = extensibility.guidance_block() + assert guidance.index("FROM_USER") < guidance.index("FROM_PROJECT") + assert [r["ruleName"] for r in extensibility.user_patterns()] == ["user:marker_rule", "user:project_rule"] |
