diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-20 17:19:54 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-20 17:19:54 +0000 |
| commit | 0f6be178f21e3966272328322e6291b2f47c4727 (patch) | |
| tree | 355d693a59ba39f5fdde016e3541edf2b011b5f9 | |
| parent | 6d375ed2062b0c34e8a18885439cd992ad2d834a (diff) | |
| parent | e68e375d22866ba36c1eb0b4cc46db96c65f6a4e (diff) | |
Merge main into mhegazy/sg-stop-diff-memorymhegazy/sg-stop-diff-memory
Conflict in get_git_diff: main added IGNORE_SUBMODULES to the diff command on the line where this branch resets its read counters. Both are kept.
| -rw-r--r-- | .claude-plugin/marketplace.json | 2 | ||||
| -rw-r--r-- | plugins/security-guidance/README.md | 14 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 32 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 153 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/sg-python.sh | 21 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_launcher_newer_python.py | 55 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_nested_repos.py | 162 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_no_credentials_notice.py | 175 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_notebook_edit_patterns.py | 193 |
9 files changed, 771 insertions, 36 deletions
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 09ec1f3a..9e79ada1 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -479,7 +479,7 @@ "url": "https://github.com/aws/agent-toolkit-for-aws.git", "path": "plugins/aws-startup-advisor", "ref": "main", - "sha": "613dc216a1cf0836b81a28d7f3a81f2b72034394" + "sha": "b310d1c46b4ced6423a737542c92a3a22cfe9e96" }, "homepage": "https://github.com/aws/agent-toolkit-for-aws" }, diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index b8a67ed4..f4806fca 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -20,7 +20,7 @@ Marketplace ships enabled by default in Claude Code — no setup beyond having t - Claude Code CLI ≥ v2.1.144 - Python 3.8+ on `PATH` (`python3`, `python`, or `py -3` — the plugin picks the first that works) -- A working API path (subscription, API key, or 3P provider config) +- Credentials for the LLM reviews: your Claude Code sign-in, an API key, or 3P provider config (see [Credentials](#credentials)) ## Configuration @@ -48,6 +48,16 @@ SECURITY_REVIEW_MODEL=claude-opus-5-5 `SECURITY_REVIEW_MODEL` controls the LLM diff review. `SG_AGENTIC_MODEL` (same syntax) controls the agentic commit reviewer. +### Credentials + +The pattern warnings need no credentials. The LLM reviews (the diff review on Stop and the commit/push reviewer) use the first of these that applies: + +- **A cloud provider (Bedrock, Vertex, Foundry)** — if Claude Code is configured for one, reviews run through your installed Claude Code with that provider config. +- **`ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in the environment** — used as is, against `ANTHROPIC_BASE_URL` if you set one. +- **Signed in to Claude Code (`/login`)** — Claude Code passes your sign-in to the plugin's hooks, and reviews use that account. + +Claude Code does not pass your sign-in to plugins in a session started with `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, or `DO_NOT_TRACK` set. If no credentials reach the plugin, for that or any other reason, the LLM reviews are skipped and only the pattern warnings run. The plugin tells you so when Claude edits a file in a git repo, at most once a week. Set `ENABLE_CODE_SECURITY_REVIEW=0` if that is what you want; it also hides the notice. + ### Enabling/disabling layers | Variable | Default | What it does | @@ -131,7 +141,7 @@ 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`. -**Review never finds anything** — verify your API path works. 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. +**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. **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/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 0e7fcf95..92662593 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -51,11 +51,27 @@ GIT_CMD = [ "-c", "diff.noprefix=false", "-c", "diff.srcPrefix=a/", "-c", "diff.dstPrefix=b/", + # A directory with its own `.git` inside the work tree (a submodule, a + # vendored checkout, an unpacked archive) is another repository with its + # own config. To report it as modified, or to show its changes inline + # (diff.submodule=diff), git starts a second git inside it, which reads + # that config and runs the commands it names. The hook stays out of it: + # such a directory is left out of the review set, and a commit that moves + # one shows as the two commit ids. + "-c", "diff.ignoreSubmodules=all", + "-c", "diff.submodule=short", ] +# diff.ignoreSubmodules is a default that the repository's own settings for +# one submodule (.gitmodules, submodule.<name>.ignore) override. The option +# cannot be overridden. Pass it to every `git status` and work-tree `git diff`. +IGNORE_SUBMODULES = "--ignore-submodules=all" + SAFE_GIT_CONFIG = ( ("core.fsmonitor", "false"), ("core.hooksPath", "/dev/null"), + ("diff.ignoreSubmodules", "all"), + ("diff.submodule", "short"), ) # The hook's git runs in the background beside the session's own git. Without @@ -451,8 +467,11 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths): # `git status` and here would silently drop ALL untracked files # from the diff. --ignore-missing only works with --dry-run, so # filter to surviving paths (lexists so dangling symlinks count). + # A nested repository (`dir/`) would be added as a submodule + # entry; see diff.ignoreSubmodules in GIT_CMD. surviving = [p for p in untracked_paths - if os.path.lexists(os.path.join(cwd, p))] + if not p.endswith("/") + and os.path.lexists(os.path.join(cwd, p))] add_args = ["--"] + surviving if surviving else None else: add_args = None @@ -676,7 +695,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", "--name-only", "-z", base], + [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base], cwd=cwd, capture_output=True, timeout=30, env=env, ) @@ -717,7 +736,7 @@ def _git_status_porcelain(cwd): try: # core.quotePath=false comes from GIT_CMD globally (see definition). r = subprocess.run( - [*GIT_CMD, "status", "--porcelain=v1", "-uall", "-z"], + [*GIT_CMD, "status", IGNORE_SUBMODULES, "--porcelain=v1", "-uall", "-z"], cwd=cwd, capture_output=True, timeout=30, ) if r.returncode != 0: @@ -735,7 +754,10 @@ def _git_status_porcelain(cwd): continue xy, path = e[:2], e[3:] if xy == "??": - untracked.add(path) + # With -uall only a nested repository is listed as `dir/`. + # It is not a file to review; see diff.ignoreSubmodules. + if not path.endswith("/"): + untracked.add(path) else: tracked.add(path) # Rename/copy entries are XY old\0new\0 — second NUL field is @@ -1055,7 +1077,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa return "" # core.quotePath=false comes from GIT_CMD globally (see definition). - cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec + cmd = [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec _diff_read.update(bytes=0, cut_files=0, cut_bytes=0) try: if untracked_paths is not None and not untracked_paths: diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 9ff43529..112f0bf3 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -49,7 +49,9 @@ Other: - SECURITY_REVIEW_MODEL: Model for LLM review (default: the newest Opus) - ANTHROPIC_API_KEY: Required for LLM-based reviews - ANTHROPIC_AUTH_TOKEN: Alternative to API key — OAuth access token sent as Bearer auth. - Claude Code passes this automatically for OAuth-authenticated users. + Claude Code passes this to the plugin's hooks for signed-in users, unless + telemetry or nonessential traffic is turned off. With neither, the LLM + reviews are skipped and the user is told once (see README, Credentials). """ try: @@ -314,6 +316,72 @@ def emit_metrics( out["systemMessage"] = system_message _write_hook_output(out) + +def _llm_review_off(): + """Why no LLM review can run: (log text, extra metrics), or None.""" + if not ENABLE_CODE_SECURITY_REVIEW: + return "LLM review disabled", {} + if not HAS_API_CREDENTIALS: + return "no API credentials", {"no_creds": True} + return None + + +# Claude Code hands a signed-in user's credentials to this plugin's hooks, +# but not in a session started with one of these set. +_NO_CREDENTIALS_NOTICE_INTERVAL_SEC = 7 * 24 * 3600 + + +def _credential_withholding_env_vars(): + names = [v for v in ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", + "DISABLE_TELEMETRY") if os.environ.get(v)] + if os.environ.get("DO_NOT_TRACK", "").strip().lower() in ( + "1", "true", "yes", "on"): + names.append("DO_NOT_TRACK") + return names + + +def _no_credentials_notice(file_path): + """Text telling the user the LLM reviews are not running, or None. + + Without credentials every Stop, commit and push review is skipped, and + nothing else tells the user. Returned for an edit inside a git repo (the + reviews only look at those), at most once a week per install: the marker + file in the state dir holds the time of the last notice. A marker that + can't be written means no notice rather than one on every edit. The + caller is the Edit/Write hook because the review hooks run in the + background, where Claude Code does not show a systemMessage. + """ + import time as _time + try: + marker = os.path.join(_resolve_state_dir(), ".no_credentials_notice") + try: + age = _time.time() - os.path.getmtime(marker) + if 0 <= age < _NO_CREDENTIALS_NOTICE_INTERVAL_SEC: + return None + except OSError: + pass + if not _git_toplevel(os.path.dirname(os.path.abspath(file_path))): + return None + os.makedirs(os.path.dirname(marker), exist_ok=True) + with open(marker, "w"): + pass + except OSError: + return None + withheld_by = _credential_withholding_env_vars() + if withheld_by: + why = ("Claude Code does not pass your sign-in to plugins while " + + " or ".join(withheld_by) + " is set") + else: + why = "No Anthropic credentials were passed to the plugin's hooks" + rest = (", so only the pattern warnings on edits are active" + if ENABLE_PATTERN_RULES else "") + return ( + "security-guidance: the AI security review of your changes is not " + f"running. {why}{rest}. See \"Credentials\" in the plugin README. " + "Set ENABLE_CODE_SECURITY_REVIEW=0 to turn the review off and hide " + "this notice, which is shown at most once a week." + ) + # ===================================================================== # State management # ===================================================================== @@ -472,11 +540,30 @@ def sweep_pending_warnings(session_id): # Pattern matching # ===================================================================== +def _notebook_cell_sources(content): + """Cell sources of a saved notebook, or None when content is not one (a + single cell's source, say).""" + if not isinstance(content, str) or not content.lstrip("\ufeff \t\r\n").startswith("{"): + return None + try: + sources = [cell.get("source", "") for cell in json.loads(content.lstrip("\ufeff"))["cells"]] + return "\n".join(src if isinstance(src, str) else "".join(src) for src in sources) + except Exception: + return None + def check_patterns(file_path, content): """Check if file path or content matches any security patterns. Returns ALL matches.""" normalized_path = file_path.lstrip("/") matches = [] + # A saved notebook is JSON: its string escapes hide code from the rules + # ("\nos.system(" has no word boundary) and its outputs can run to + # megabytes. Check the cells as written instead. + if normalized_path.endswith(".ipynb"): + cell_sources = _notebook_cell_sources(content) + if cell_sources is not None: + content = cell_sources + for pattern in list(SECURITY_PATTERNS) + extensibility.user_patterns(): # path_filter is a gate: when present, the rule only applies to # matching paths. Distinct from path_check, which is itself a @@ -515,7 +602,7 @@ def check_patterns(file_path, content): return matches -def extract_content_from_input(tool_name, tool_input): +def extract_content_from_input(tool_name, tool_input, tool_response=None): """Extract content to check from tool input based on tool type.""" if tool_name == "Write": return tool_input.get("content", "") @@ -526,6 +613,15 @@ def extract_content_from_input(tool_name, tool_input): if edits: return " ".join(edit.get("new_string", "") for edit in edits) return "" + elif tool_name == "NotebookEdit": + # A deleted cell adds no code. A failed edit comes back as an error + # in the response, with the notebook unchanged. + if tool_input.get("edit_mode") == "delete": + return "" + if isinstance(tool_response, dict) and tool_response.get("error"): + return "" + new_source = tool_input.get("new_source", "") + return new_source if isinstance(new_source, str) else "" return "" # ===================================================================== @@ -1330,9 +1426,10 @@ def handle_commit_review_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 32, **_base}) sys.exit(0) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - debug_log("Commit review: LLM review disabled or no API credentials") - emit_metrics({"skipped": True, "skip_reason": 22, **_base}) + off = _llm_review_off() + if off: + debug_log(f"Commit review: {off[0]}") + emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base}) sys.exit(0) if not ensure_anthropic_reachable(): @@ -1798,8 +1895,9 @@ def handle_push_sweep_posttooluse(input_data): if interrupted: emit_metrics({"skipped": True, "skip_reason": 21, **_base}) sys.exit(0) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - emit_metrics({"skipped": True, "skip_reason": 22, **_base}) + off = _llm_review_off() + if off: + emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base}) sys.exit(0) if not cwd: emit_metrics({"skipped": True, "skip_reason": 25, **_base}) @@ -2228,9 +2326,10 @@ def handle_stop_hook(input_data): debug_log(f"Stop hook: already fired {fire_count} times (max {MAX_STOP_HOOK_FIRINGS}), skipping") _skip(2) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - debug_log("Stop hook: LLM review disabled or no API credentials") - _skip(3) + off = _llm_review_off() + if off: + debug_log(f"Stop hook: {off[0]}") + _skip(3, **off[1]) # Stop-hook-only kill switch — placed after consume_stop_state so # touched_paths is still cleared each turn (a disabled Stop hook that @@ -2634,7 +2733,8 @@ def main(): record_touched_path(session_id, file_path) - content = extract_content_from_input(tool_name, tool_input) + content = extract_content_from_input( + tool_name, tool_input, input_data.get("tool_response")) all_guidance = [] raw_pattern_matches = [] @@ -2674,30 +2774,31 @@ def main(): # rule_id: RuleId of the first raw match (values stay small/enumerable in telemetry) # rule_mask: bitmask of ALL raw matches — POPCOUNT gives raw hit count, # (mask >> N) & 1 tests for a specific rule + output = {} if raw_pattern_matches: raw_names = [r for r, _ in raw_pattern_matches] - output = {"metrics": { + output["metrics"] = { "pattern_hits": len(all_guidance), # User-defined patterns (rule_name="user:*") have no static # RuleId; emit -1 so the metrics pipeline can distinguish. "rule_id": int(_RULE_NAME_TO_ID.get(raw_names[0], -1)), "rule_mask": rule_names_to_mask(raw_names), **({"pv": _PV} if _PV else {}), - }} - if all_guidance: - output["hookSpecificOutput"] = { - "hookEventName": "PostToolUse", - "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), - } + } + if all_guidance: + output["hookSpecificOutput"] = { + "hookEventName": "PostToolUse", + "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), + } + # The LLM reviews are on but can't run: say so. + if (ENABLE_CODE_SECURITY_REVIEW and not HAS_API_CREDENTIALS + and (ENABLE_STOP_REVIEW or COMMIT_REVIEW_ENABLED + or PUSH_SWEEP_ENABLED)): + notice = _no_credentials_notice(file_path) + if notice: + output["systemMessage"] = notice + if output: _write_hook_output(output) - elif all_guidance: - # Defensive: pattern rules disabled but guidance somehow set (shouldn't happen) - print(json.dumps({ - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), - } - })) sys.exit(0) diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh index f1b9d68c..a02c7d6c 100755 --- a/plugins/security-guidance/hooks/sg-python.sh +++ b/plugins/security-guidance/hooks/sg-python.sh @@ -135,7 +135,8 @@ is_sdk_compatible() { # Pass 1 — try minor-versioned binaries in descending order. These are only # present if the user explicitly installed them (Homebrew / python.org / pyenv), # so picking one here always upgrades over the system `python3`. Highest -# available wins; the user doesn't have to PATH-prefer it. +# of these wins; the user doesn't have to PATH-prefer it. Releases newer +# than this list are pass 2b. for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do on_path "$cmd" || continue v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } @@ -165,6 +166,22 @@ for cmd in "python3" "python" "py -3"; do esac done +# Pass 2b — minor versions newer than the pass 1 list, so a machine whose +# only SDK-compatible Python is a recent release (system `python3` 3.9 next to +# Homebrew's python3.14) is not left on pass 3. Tried only when nothing +# above is compatible: an interpreter that already works is never traded for +# a newer one, which may not have the SDK or wheels for its dependencies yet. +# Oldest first for the same reason. Missing names cost no process (on_path). +# See #4907, #5024. +for cmd in "python3.14" "python3.15" "python3.16" "python3.17" "python3.18" "python3.19"; do + on_path "$cmd" || continue + v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + v=${v%$'\r'} + if is_sdk_compatible "$v"; then + exec "$cmd" "$@" + fi +done + # Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks # (PostToolUse regex on Edit/Write) only need 3.6+ and are useful on their # own; the SDK-dependent paths will detect the version mismatch and degrade @@ -237,7 +254,7 @@ if [ -n "$sg_unreadable" ]; then exit 1 fi echo "security-guidance: no working Python 3 interpreter found." >&2 -echo " tried: python3.13, python3.12, python3.11, python3.10, python3, python, py -3" >&2 +echo " tried: python3.13 to python3.10, python3, python, py -3, python3.14 to python3.19" >&2 echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2 echo " on macOS, install Python 3.10+ via Homebrew (\`brew install python\`)" >&2 exit 1 diff --git a/plugins/security-guidance/tests/test_launcher_newer_python.py b/plugins/security-guidance/tests/test_launcher_newer_python.py new file mode 100644 index 00000000..fc152b73 --- /dev/null +++ b/plugins/security-guidance/tests/test_launcher_newer_python.py @@ -0,0 +1,55 @@ +"""sg-python.sh finds Python releases newer than its versioned list. + +The versioned names it prefers stop at python3.13. A machine whose `python3` +is below 3.10 (stock macOS: 3.9) and whose only newer interpreter is +python3.14 used to end up on 3.9, which cannot load the agent SDK, so the +commit reviewer was off without a word. See #4907, #5024. + +Interpreters are emulated with shell scripts, so these tests need a POSIX +shell. +""" +import sys + +import pytest + +from test_launcher_process_count import PYTHON, _add, _run, _starts, box # noqa: F401 + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers") + + +def test_newer_release_beats_a_python3_below_3_10(box): + _add(box, "python3", PYTHON, version="3.9") + _add(box, "python3.14", PYTHON, version="3.14") + r = _run(box, "hook.py") + assert "ran:python3.14" in r.stdout, r.stdout + r.stderr + assert _starts(box) == ["python3 probe", "python3.14 probe", "python3.14 hook.py"] + + +def test_newer_release_is_found_when_it_is_the_only_python(box): + _add(box, "python3.15", PYTHON, version="3.15") + r = _run(box, "hook.py") + assert "ran:python3.15" in r.stdout, r.stdout + r.stderr + assert _starts(box) == ["python3.15 probe", "python3.15 hook.py"] + + +@pytest.mark.parametrize("working", ["python3.12", "python3", "python"]) +def test_an_interpreter_that_already_works_is_kept(box, working): + _add(box, working, PYTHON, version="3.12") + _add(box, "python3.14", PYTHON, version="3.14") + r = _run(box, "hook.py") + assert f"ran:{working}" in r.stdout, r.stdout + r.stderr + assert "python3.14 probe" not in _starts(box) + + +def test_oldest_of_the_newer_releases_is_tried_first(box): + _add(box, "python3.16", PYTHON, version="3.16") + _add(box, "python3.14", PYTHON, version="3.14") + r = _run(box, "hook.py") + assert "ran:python3.14" in r.stdout, r.stdout + r.stderr + + +def test_no_python_at_all_still_starts_nothing(box): + r = _run(box, "hook.py") + assert r.returncode == 1 + assert "python3.14" in r.stderr + assert _starts(box) == [] diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py new file mode 100644 index 00000000..cb010018 --- /dev/null +++ b/plugins/security-guidance/tests/test_nested_repos.py @@ -0,0 +1,162 @@ +import os +import subprocess +import tempfile + +import pytest + +from conftest import ( + GIT_ENV, STUB_VULN, VULN_PY, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, +) + +import gitutil + + +def _add_nested_repo(parent, rel, marker): + """A directory with its own `.git` whose config names a filter command, + the way an unpacked archive or a vendored checkout can. The command leaves + a line in `marker` each time git runs it.""" + nested = make_repo(parent / rel, { + "lib.py": "print('one')\n", + ".gitattributes": "* filter=probe\n", + }) + git(nested, "config", "filter.probe.clean", + f"sh -c 'echo ran >> \"{marker.as_posix()}\"; cat'") + # Same size, so git has to read the file to tell whether it changed. + (nested / "lib.py").write_text("print('two')\n") + old = os.stat(nested / ".git" / "index").st_mtime - 3600 + os.utime(nested / ".git" / "index", (old, old)) + return nested + + +@pytest.fixture +def outer(tmp_path): + return make_repo(tmp_path / "outer", {"app.py": "print('hi')\n"}) + + +@pytest.fixture +def marker(tmp_path): + return tmp_path / "filter-ran" + + +def _turn(repo, hook_env, stub_api, during): + stub_api.vulns = [STUB_VULN] + assert run_hook(ups_payload(repo), hook_env)[0] == 0 + during() + return run_hook(stop_payload(repo), hook_env) + + +def test_untracked_nested_repo_filter_not_run(outer, marker, hook_env, stub_api): + def during(): + _add_nested_repo(outer, "vendor/pkg", marker) + (outer / "app.py").write_text(VULN_PY) + + rc, out, err = _turn(outer, hook_env, stub_api, during) + + assert not marker.exists(), marker.read_text() + # The turn's own edit is still reviewed. + assert stub_api.calls, (rc, out, err) + assert "app.py" in out + err + + +def test_untracked_nested_repo_alone_is_not_reviewed(outer, marker, hook_env, stub_api): + rc, out, err = _turn( + outer, hook_env, stub_api, + lambda: _add_nested_repo(outer, "vendor/pkg", marker)) + + assert not marker.exists(), marker.read_text() + assert not stub_api.calls + assert (metrics_of(out) or {}).get("skipped") is True + + +@pytest.fixture +def git_env(tmp_path, monkeypatch): + """For calling gitutil in this process: a temp dir of our own, and the + environment restored afterwards.""" + d = tmp_path / "tmproot" + d.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(d)) + saved = dict(os.environ) + os.environ.update(GIT_ENV) + yield + os.environ.clear() + os.environ.update(saved) + + +def _record_nested_repo(outer, marker, gitmodules=None): + nested = _add_nested_repo(outer, "vendor/pkg", marker) + if gitmodules: + (outer / ".gitmodules").write_text(gitmodules) + git(outer, "add", "-A") + git(outer, "commit", "-q", "-m", "add vendor/pkg") + if marker.exists(): + marker.unlink() + return nested + + +def test_untracked_nested_repo_is_not_a_changed_file(outer, marker, git_env): + _add_nested_repo(outer, "vendor/pkg", marker) + (outer / "new.py").write_text("x = 1\n") + + tracked, untracked = gitutil._git_status_porcelain(str(outer)) + + assert (tracked, untracked) == (set(), {"new.py"}) + + +def test_intent_to_add_skips_nested_repos(outer, marker, git_env): + _add_nested_repo(outer, "vendor/pkg", marker) + (outer / "new.py").write_text("x = 1\n") + + with gitutil._temp_index(str(outer), ["new.py", "vendor/pkg/"]) as env: + assert env is not None + listed = subprocess.run( + ["git", "ls-files", "-s"], cwd=outer, capture_output=True, + text=True, env=env, + ).stdout + + assert "new.py" in listed + assert "160000" not in listed + assert not marker.exists() + + +# A repository can ask for one submodule to be checked whatever the default. +GITMODULES_IGNORE_NONE = ( + '[submodule "pkg"]\n\tpath = vendor/pkg\n\turl = ./vendor/pkg\n\tignore = none\n' +) + + +@pytest.mark.parametrize("gitmodules", [None, GITMODULES_IGNORE_NONE]) +def test_status_and_diff_leave_out_recorded_nested_repo(outer, marker, git_env, gitmodules): + nested = _record_nested_repo(outer, marker, gitmodules) + (nested / "lib.py").write_text("print('abc')\n") + (outer / "app.py").write_text(VULN_PY) + + tracked, untracked = gitutil._git_status_porcelain(str(outer)) + diff = gitutil.get_git_diff(str(outer), "HEAD", untracked_paths=[]) + names = gitutil._git_name_only(str(outer), "HEAD") + + assert tracked == {"app.py"} + assert names == {"app.py"} + assert "app.py" in diff and "vendor/pkg" not in diff + assert not marker.exists() + + +def test_commit_range_diff_does_not_enter_nested_repo(outer, marker, git_env, tmp_path): + nested = _record_nested_repo(outer, marker, GITMODULES_IGNORE_NONE) + ext_marker = tmp_path / "ext-diff-ran" + git(nested, "config", "diff.external", + f"sh -c 'echo ran >> \"{ext_marker.as_posix()}\"'") + base = git(outer, "rev-parse", "HEAD").strip() + git(nested, "commit", "-q", "-am", "two") + git(outer, "commit", "-q", "-am", "move vendor/pkg") + for m in (marker, ext_marker): + if m.exists(): + m.unlink() + # The user's own setting asks for a submodule's changes inline. + os.environ.update({"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "diff.submodule", + "GIT_CONFIG_VALUE_0": "diff"}) + + out = gitutil._git_diff_range(str(outer), base, "HEAD") + + assert not ext_marker.exists() and not marker.exists() + assert "lib.py" not in (out or "") diff --git a/plugins/security-guidance/tests/test_no_credentials_notice.py b/plugins/security-guidance/tests/test_no_credentials_notice.py new file mode 100644 index 00000000..1995397e --- /dev/null +++ b/plugins/security-guidance/tests/test_no_credentials_notice.py @@ -0,0 +1,175 @@ +"""Without credentials the LLM reviews are skipped; the user is told.""" +import json +import os +import time + +import pytest + +from conftest import ( + bash_payload, commit_file, edit_payload, git, metrics_of, run_hook, + stop_payload, ups_payload, VULN_PY, +) + +# Anything in the developer's shell that changes whether a review would run. +_AMBIENT = ( + "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_TELEMETRY", "DO_NOT_TRACK", + "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", + "CLAUDE_CODE_USE_MANTLE", "CLAUDE_CODE_USE_ANTHROPIC_AWS", + "SECURITY_GUIDANCE_DISABLE", "ENABLE_SECURITY_REMINDER", + "ENABLE_CODE_SECURITY_REVIEW", "ENABLE_STOP_REVIEW", "ENABLE_COMMIT_REVIEW", + "ENABLE_PATTERN_RULES", +) + + +def _env(hook_env, creds=False, **extra): + env = {k: v for k, v in hook_env.items() if k not in _AMBIENT} + if creds: + env["ANTHROPIC_API_KEY"] = "test-key" + env.update(extra) + return env + + +def _edit_output(repo, env, name="app.py", content=VULN_PY, session_id="s1"): + (repo / name).write_text(content) + rc, out, _ = run_hook( + edit_payload(repo, repo / name, new_string=content, session_id=session_id), env) + assert rc == 0 + lines = [l for l in out.splitlines() if l.startswith("{")] + assert len(lines) <= 1 + return json.loads(lines[0]) if lines else {} + + +def _notice(repo, env, **kw): + return _edit_output(repo, env, **kw).get("systemMessage") + + +def _marker(env): + return os.path.join(env["SECURITY_WARNINGS_STATE_DIR"], ".no_credentials_notice") + + +def test_edit_without_credentials_tells_the_user_once(workspace, hook_env): + _, repo = workspace + env = _env(hook_env) + notice = _notice(repo, env) + assert "is not running" in notice + assert "No Anthropic credentials were passed" in notice + assert "only the pattern warnings on edits are active" in notice + assert "ENABLE_CODE_SECURITY_REVIEW=0" in notice + assert _notice(repo, env) is None + assert _notice(repo, env, session_id="s2") is None + + +def test_notice_comes_back_after_a_week(workspace, hook_env): + _, repo = workspace + env = _env(hook_env) + assert _notice(repo, env) + six_days, eight_days = time.time() - 6 * 86400, time.time() - 8 * 86400 + os.utime(_marker(env), (six_days, six_days)) + assert _notice(repo, env) is None + os.utime(_marker(env), (eight_days, eight_days)) + assert _notice(repo, env) + assert _notice(repo, env) is None + + +def test_notice_names_every_setting_that_withholds_credentials(workspace, hook_env): + _, repo = workspace + notice = _notice(repo, _env(hook_env, DISABLE_TELEMETRY="1", DO_NOT_TRACK="true")) + assert "while DISABLE_TELEMETRY or DO_NOT_TRACK is set" in notice + + +@pytest.mark.parametrize("var", ["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DO_NOT_TRACK"]) +def test_notice_names_the_setting(workspace, hook_env, var): + _, repo = workspace + assert f"while {var} is set" in _notice(repo, _env(hook_env, **{var: "1"})) + + +def test_do_not_track_off_is_not_blamed(workspace, hook_env): + _, repo = workspace + notice = _notice(repo, _env(hook_env, DO_NOT_TRACK="0")) + assert "DO_NOT_TRACK" not in notice and "No Anthropic credentials" in notice + + +def test_notice_does_not_promise_pattern_warnings_that_are_off(workspace, hook_env): + _, repo = workspace + notice = _notice(repo, _env(hook_env, ENABLE_PATTERN_RULES="0")) + assert "is not running" in notice and "pattern warnings" not in notice + + +def test_notice_rides_along_with_a_pattern_warning(workspace, hook_env): + _, repo = workspace + risky = "import os\nos.system('ls ' + name)\n" + with_creds = _edit_output( + repo, _env(hook_env, creds=True), name="a.py", content=risky) + assert with_creds["metrics"]["pattern_hits"] == 1 + assert "systemMessage" not in with_creds + out = _edit_output(repo, _env(hook_env), name="b.py", content=risky) + assert "is not running" in out["systemMessage"] + assert out["metrics"] == with_creds["metrics"] + assert (out["hookSpecificOutput"]["additionalContext"] + == with_creds["hookSpecificOutput"]["additionalContext"]) + + +def test_no_notice_with_credentials(workspace, hook_env): + _, repo = workspace + assert _notice(repo, _env(hook_env, creds=True)) is None + assert _notice(repo, _env(hook_env, ANTHROPIC_AUTH_TOKEN="t")) is None + assert _notice(repo, _env(hook_env, CLAUDE_CODE_USE_BEDROCK="1")) is None + assert not os.path.exists(_marker(hook_env)) + + +def test_no_notice_when_the_reviews_are_turned_off(workspace, hook_env): + _, repo = workspace + assert _notice(repo, _env(hook_env, ENABLE_CODE_SECURITY_REVIEW="0")) is None + assert _notice(repo, _env(hook_env, SECURITY_GUIDANCE_DISABLE="1")) is None + assert _notice(repo, _env( + hook_env, ENABLE_STOP_REVIEW="0", SECURITY_GUIDANCE_COMMIT_REVIEW="off", + SG_PUSH_SWEEP="off")) is None + assert not os.path.exists(_marker(hook_env)) + assert _notice(repo, _env(hook_env, ENABLE_STOP_REVIEW="0")) + + +def test_no_notice_outside_a_git_repo(workspace, hook_env, tmp_path): + _, repo = workspace + plain = tmp_path / "plain" + plain.mkdir() + env = _env(hook_env) + assert _notice(plain, env, name="notes.py") is None + assert not os.path.exists(_marker(env)) + assert _notice(repo, env) + + +def test_no_notice_when_the_state_dir_is_unwritable(workspace, hook_env, tmp_path): + _, repo = workspace + blocker = tmp_path / "not-a-dir" + blocker.write_text("") + env = _env(hook_env, SECURITY_WARNINGS_STATE_DIR=str(blocker / "state")) + assert _notice(repo, env) is None + assert _notice(repo, env) is None + + +def test_skipped_reviews_report_the_missing_credentials(workspace, hook_env, stub_api): + _, repo = workspace + env = _env(hook_env) + run_hook(ups_payload(repo), env) + _edit_output(repo, env) + rc, out, _ = run_hook(stop_payload(repo), env) + m = metrics_of(out) + assert rc == 0 and m["skip_reason"] == 3 and m["no_creds"] is True + + _, commit_out = commit_file(repo, "app.py", VULN_PY + "# again\n") + rc, out, _ = run_hook( + bash_payload(repo, "git commit -m change", stdout=commit_out), env) + m = metrics_of(out) + assert rc == 0 and m["skip_reason"] == 22 and m["no_creds"] is True + + rc, out, _ = run_hook(bash_payload(repo, "git push origin main"), env) + m = metrics_of(out) + assert rc == 0 and m["push_sweep"] and m["skip_reason"] == 22 and m["no_creds"] is True + assert stub_api.calls == [] + + off = _env(hook_env, ENABLE_CODE_SECURITY_REVIEW="0") + for payload in (stop_payload(repo, session_id="s3"), + bash_payload(repo, "git push origin main", session_id="s3")): + rc, out, _ = run_hook(payload, off) + assert "no_creds" not in metrics_of(out) diff --git a/plugins/security-guidance/tests/test_notebook_edit_patterns.py b/plugins/security-guidance/tests/test_notebook_edit_patterns.py new file mode 100644 index 00000000..df4d37a9 --- /dev/null +++ b/plugins/security-guidance/tests/test_notebook_edit_patterns.py @@ -0,0 +1,193 @@ +"""NotebookEdit cell sources go through the same pattern checks as file edits.""" +import json +import subprocess +import sys + +import pytest + +import extensibility +import security_reminder_hook as hook + +from conftest import HOOKS_DIR, metrics_of, run_hook + +CELL = ( + "import pickle, os\n" + "data = pickle.loads(open('model.pkl', 'rb').read())\n" + "os.system(f'convert {user_input}')\n" +) +CELL_RULES = ["os_system_injection", "pickle_deserialization"] + + +@pytest.fixture +def env(hook_env, tmp_path): + # Keep the developer's own security-patterns files out of the counts. + home = tmp_path / "home" + home.mkdir() + hook_env.update(HOME=str(home), USERPROFILE=str(home)) + hook_env.pop("CLAUDE_CONFIG_DIR", None) + return hook_env + + +def notebook_payload(cwd, notebook, new_source=CELL, tool_response=None, **tool_input): + return { + "session_id": "s1", + "hook_event_name": "PostToolUse", + "tool_name": "NotebookEdit", + "tool_input": {"notebook_path": str(notebook), "new_source": new_source, **tool_input}, + "tool_response": tool_response if tool_response is not None else {}, + "cwd": str(cwd), + } + + +def warning_of(stdout): + for line in stdout.splitlines(): + if line.strip().startswith("{"): + out = json.loads(line).get("hookSpecificOutput") + if out: + return out["additionalContext"] + return "" + + +@pytest.mark.parametrize("tool_input", [ + {"cell_id": "c1"}, + {"cell_id": "c1", "edit_mode": "replace", "cell_type": "code"}, + {"cell_id": "c1", "edit_mode": "insert", "cell_type": "code"}, + {"edit_mode": "insert", "cell_type": "code"}, + {"cell_id": "c1", "cell_type": "markdown"}, +]) +def test_cell_source_is_checked(tmp_path, env, tool_input): + rc, out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", **tool_input), env) + assert rc == 0 + warning = warning_of(out) + assert "pickle" in warning + assert "os.system" in warning + assert metrics_of(out)["pattern_hits"] == 2 + + +def test_same_cell_matches_a_python_file_edit(tmp_path, env): + _, nb_out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", cell_id="c1"), env) + py = notebook_payload(tmp_path, tmp_path / "analysis.py") + py.update(tool_name="Edit", tool_input={ + "file_path": str(tmp_path / "analysis.py"), "old_string": "", "new_string": CELL}) + _, py_out, _ = run_hook(py, env) + assert metrics_of(nb_out)["rule_mask"] == metrics_of(py_out)["rule_mask"] + + +@pytest.mark.parametrize("tool_input, tool_response", [ + ({"cell_id": "c1", "edit_mode": "delete"}, {}), + ({"cell_id": "c1", "edit_mode": "delete", "cell_type": "code"}, {"error": ""}), + ({"cell_id": "c1"}, {"error": "File has been modified since read"}), + ({"cell_id": "c1"}, {"new_source": CELL, "error": "Edit rejected"}), +]) +def test_deleted_cell_and_failed_edit_are_not_checked(tmp_path, env, tool_input, tool_response): + rc, out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", + tool_response=tool_response, **tool_input), env) + assert rc == 0 + assert metrics_of(out) is None + assert warning_of(out) == "" + + +def test_successful_edit_with_an_empty_error_is_checked(tmp_path, env): + # What Claude Code sends for an edit that worked. + _, out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", cell_id="c1", + tool_response={"error": "", "cell_type": "code", "old_source": CELL}), + env) + assert metrics_of(out)["pattern_hits"] == 2 + + +@pytest.mark.parametrize("tool_input, tool_response", [ + ({"cell_id": "c1", "new_source": None}, {}), + ({"cell_id": "c1", "new_source": ["import pickle"]}, {}), + ({"cell_id": None}, {}), + ({"cell_id": "c1"}, "Updated cell c1"), + ({"cell_id": "c1"}, None), +]) +def test_unexpected_shapes_do_not_break_the_hook(tmp_path, env, tool_input, tool_response): + payload = notebook_payload(tmp_path, tmp_path / "analysis.ipynb", **tool_input) + payload["tool_response"] = tool_response + rc, _, err = run_hook(payload, env) + assert rc == 0 + assert "Traceback" not in err + + +def test_clean_cell_is_quiet(tmp_path, env): + rc, out, _ = run_hook( + notebook_payload(tmp_path, tmp_path / "analysis.ipynb", + new_source="import json\ndata = json.load(open('m.json'))\n", + cell_id="c1"), env) + assert rc == 0 + assert metrics_of(out) is None + + +def saved_notebook(code, bom=""): + # NotebookEdit saves a cell's source as one string; Jupyter saves a list of lines. + return bom + json.dumps({ + "cells": [ + {"cell_type": "markdown", "id": "m", "metadata": {}, "source": "# Notes\n"}, + {"cell_type": "code", "id": "c", "metadata": {}, "source": code, "outputs": []}, + ], + "metadata": {}, "nbformat": 4, "nbformat_minor": 5, + }, indent=1) + + +@pytest.fixture +def rules(monkeypatch): + monkeypatch.setattr(extensibility, "_user_patterns", []) + return lambda path, content: sorted(r for r, _ in hook.check_patterns(str(path), content)) + + +@pytest.mark.parametrize("bom", ["", ""]) +def test_saved_notebook_is_checked_by_its_cells_as_written(rules, bom): + saved = saved_notebook(CELL, bom) + assert "\\nos.system(" in saved + assert rules("analysis.ipynb", saved) == CELL_RULES + assert rules("analysis.ipynb", saved_notebook(CELL.splitlines(True), bom)) == CELL_RULES + assert rules("analysis.ipynb", saved_notebook("x = 1\n", bom)) == [] + + +def test_saved_notebook_outputs_are_not_checked(rules): + saved = json.loads(saved_notebook("x = 1\n")) + saved["cells"][1]["outputs"] = [{"output_type": "stream", "name": "stdout", "text": [CELL]}] + assert rules("analysis.ipynb", json.dumps(saved)) == [] + saved["cells"][0]["source"] = CELL.splitlines(True) + assert rules("analysis.ipynb", json.dumps(saved)) == CELL_RULES + + +@pytest.mark.parametrize("content", [ + "{not json", "{}", '{"cells": 5}', '{"cells": [5]}', '{"cells": [{"source": 5}]}', "[]", +]) +def test_content_that_is_not_a_saved_notebook_is_checked_as_is(rules, content): + assert rules("analysis.ipynb", content) == [] + assert rules("analysis.ipynb", content + "\nimport os\nos.system(cmd)\n") == ["os_system_injection"] + + +def test_other_files_are_not_read_as_notebooks(rules): + assert rules("analysis.py", saved_notebook("import os\nos.system(cmd)\n")) == [] + + +SWEEP = ( + "import sys, json; sys.path.insert(0, sys.argv[1]);" + "import security_reminder_hook as h;" + "print(json.dumps(h.sweep_pending_warnings('s1')[:2]))" +) + + +def sweep(env): + r = subprocess.run([sys.executable, "-c", SWEEP, str(HOOKS_DIR)], + capture_output=True, text=True, env=env) + return json.loads(r.stdout.strip().splitlines()[-1]) + + +def test_notebook_warning_is_tallied_from_the_saved_cells(tmp_path, env): + nb = tmp_path / "analysis.ipynb" + nb.write_text(saved_notebook(CELL)) + run_hook(notebook_payload(tmp_path, nb, cell_id="c"), env) + assert sweep(env) == [0, 2] + + run_hook(notebook_payload(tmp_path, nb, cell_id="c"), env) + nb.write_text(saved_notebook("x = 1\n")) + assert sweep(env) == [2, 0] |
