diff options
| author | Claude <noreply@anthropic.com> | 2026-10-20 22:36:29 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-20 22:36:29 +0000 |
| commit | 6d4e17c8c4d45de2eba6dce119e56fff18ae43b1 (patch) | |
| tree | 701885afff4bfa63b7dbf1b7c8af7492e9aa90a0 /plugins/security-guidance/tests | |
| parent | d2919136660832d06d5260677b256033c7dbdbda (diff) | |
| parent | beecef224291d252a87f58c5e83df28d15fe3450 (diff) | |
Merge branch 'main' into mhegazy/sg-launcher-probe-timingmhegazy/sg-launcher-probe-timing
Diffstat (limited to 'plugins/security-guidance/tests')
15 files changed, 2473 insertions, 4 deletions
diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 998401c2..f1addb9b 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -1,10 +1,14 @@ import http.server +import io import json import os +import struct import subprocess import sys +import sysconfig import threading import time +import zipfile from pathlib import Path import pytest @@ -137,6 +141,9 @@ def hook_env(tmp_path, stub_api): "ANTHROPIC_BASE_URL": f"http://127.0.0.1:{stub_api.server_port}", "NO_PROXY": "*", "no_proxy": "*", "SG_AGENTIC_COMMIT_REVIEW": "0", + # Points the plugin at a claude that does not exist, so no hook test + # runs this machine's own claude. + "SG_AGENTIC_CLI_PATH": str(tmp_path / "no-claude"), "SECURITY_GUIDANCE_COMMIT_REVIEW": "on", "SG_PUSH_SWEEP": "on", "PYTHONDONTWRITEBYTECODE": "1", @@ -277,14 +284,47 @@ def env(hook_env, gateway): return e +def _windows_exe(script): + """`script` as the bytes of a Windows .exe: Windows starts neither a + `#!` file nor, without a shell, a .cmd with multi-line arguments. Built + the way pip builds a console script: its launcher stub, then the + interpreter to run, then a zip holding the script as __main__.py.""" + distlib = pytest.importorskip("pip._vendor.distlib") + stub = "t%s%s.exe" % ("64" if struct.calcsize("P") == 8 else "32", + "-arm" if sysconfig.get_platform() == "win-arm64" else "") + stub = os.path.join(os.path.dirname(distlib.__file__), stub) + if not os.path.isfile(stub): + pytest.skip(f"pip has no script launcher {os.path.basename(stub)}") + with open(stub, "rb") as f: + launcher = f.read() + python = f'"{sys.executable}"' if " " in sys.executable else sys.executable + archive = io.BytesIO() + with zipfile.ZipFile(archive, "w") as zf: + zf.writestr("__main__.py", script) + return launcher + f"#!{python}\n".encode("utf-8") + archive.getvalue() + + +def write_cli(tmp_path, name, script): + """A stand-in for `claude` in `tmp_path` that runs the Python `script`; + returns its path.""" + if os.name == "nt": + cli = tmp_path / f"{name}.exe" + cli.write_bytes(_windows_exe(script)) + else: + cli = tmp_path / name + cli.write_text(f"#!{sys.executable}\n{script}") + cli.chmod(0o755) + return cli + + @pytest.fixture def failing_inner_cli(tmp_path): """An inner CLI that prints a warning on stderr and exits 1; the review then falls back to a single-shot call.""" - cli = tmp_path / "claude" - cli.write_text("#!/bin/sh\necho 'claude.ai connectors are disabled' >&2\nexit 1\n") - cli.chmod(0o755) - return str(cli) + return str(write_cli(tmp_path, "claude", ( + "import sys\n" + "sys.stderr.write('claude.ai connectors are disabled\\n')\n" + "sys.exit(1)\n"))) @pytest.fixture diff --git a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py new file mode 100644 index 00000000..2325cd9b --- /dev/null +++ b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py @@ -0,0 +1,75 @@ +"""The SDK bootstrap's Python subprocesses must not import from the repository. + +`python -c` and `python -m` put the working directory first on the import +path, and hooks run in the user's repository, so every interpreter the +bootstrap starts runs from a directory the plugin owns. +""" +import ast +import os +import sys +from pathlib import Path + +import pytest + +import ensure_agent_sdk + +from conftest import HOOKS_DIR, make_repo + + +def _spawns(tree): + for node in ast.walk(tree): + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr in ("run", "Popen", "call", "check_call", "check_output") + and isinstance(node.func.value, ast.Name) and node.func.value.id == "subprocess"): + yield node + + +def test_every_spawn_sets_a_plugin_owned_cwd(): + tree = ast.parse((HOOKS_DIR / "ensure_agent_sdk.py").read_text()) + calls = list(_spawns(tree)) + assert len(calls) >= 6 + for call in calls: + cwd = [k for k in call.keywords if k.arg == "cwd"] + assert cwd, f"subprocess call on line {call.lineno} inherits the hook's working directory" + assert ast.unparse(cwd[0].value) == "_spawn_cwd()", call.lineno + + +def test_spawn_cwd_is_the_state_dir(tmp_path, monkeypatch): + state = tmp_path / "state" + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state)) + assert ensure_agent_sdk._spawn_cwd() == str(state) + assert state.is_dir() + + +def test_relative_state_dir_is_made_absolute(tmp_path, monkeypatch): + # Children run in the state dir, so a relative one would be resolved twice. + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", "rel") + assert ensure_agent_sdk._spawn_cwd() == str(tmp_path / "rel") + + +@pytest.mark.skipif(sys.platform == "win32", reason="symlinked interpreter") +@pytest.mark.skipif(sys.version_info < (3, 10), reason="bootstrap stops before the probe") +def test_health_check_ignores_module_in_repo(tmp_path, monkeypatch): + repo = tmp_path / "repo" + make_repo(repo) + marker = tmp_path / "imported-from-repo" + (repo / "claude_agent_sdk.py").write_text( + f"open({str(marker)!r}, 'w').write('x')\n") + + state = tmp_path / "state" + venv_bin = state / "agent-sdk-venv" / ("Scripts" if sys.platform == "win32" else "bin") + venv_bin.mkdir(parents=True) + venv_py = venv_bin / ("python.exe" if sys.platform == "win32" else "python") + os.symlink(sys.executable, venv_py) + + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state)) + monkeypatch.chdir(repo) + monkeypatch.setattr(ensure_agent_sdk, "_sdk_on_syspath", lambda: False) + # No rebuild if the probe fails: this test only covers the probe. + ensure_agent_sdk._write_cooldown(state) + + outcome, _, _ = ensure_agent_sdk.main() + + assert outcome in (ensure_agent_sdk.NOOP_VENV, ensure_agent_sdk.SKIP_COOLDOWN) + assert not marker.exists() diff --git a/plugins/security-guidance/tests/test_gateway_sign_in.py b/plugins/security-guidance/tests/test_gateway_sign_in.py new file mode 100644 index 00000000..7b6e9fc4 --- /dev/null +++ b/plugins/security-guidance/tests/test_gateway_sign_in.py @@ -0,0 +1,396 @@ +"""Reviews in a session signed in to a Claude apps gateway with /login, where +Claude Code gives hooks no credential.""" +import asyncio +import json +import os +import sys +import types + +import pytest + +from conftest import ( + VULN_PY, bash_payload, commit_file, edit_payload, git, metrics_of, run_hook, + stop_payload, ups_payload, write_cli, +) + +import _base +import llm + +SIGNED_IN = json.dumps({"loggedIn": True, "authMethod": "third_party", "apiProvider": "gateway"}) +NOT_SIGNED_IN = json.dumps({"loggedIn": False, "authMethod": "none", "apiProvider": "gateway"}) + + +def make_cli(tmp_path, auth_status, *, name="claude", hang=False, linger=False): + """A fake `claude` that logs each call to <name>.calls as its arguments, the + SECURITY_GUIDANCE_DISABLE it got and its working directory, prints + `auth_status` for `auth status --json`, and fails anything else. `hang` + waits 5 s before answering; `linger` leaves a process running that holds + stdout open after the CLI exits.""" + calls = tmp_path / f"{name}.calls" + script = f"""import os, subprocess, sys, time +with open({str(calls)!r}, "a", encoding="utf-8") as f: + f.write(" ".join(sys.argv[1:]) + " | SGD=" + os.environ.get("SECURITY_GUIDANCE_DISABLE", "") + + " | CWD=" + os.getcwd() + "\\n") +if sys.argv[1:3] != ["auth", "status"]: + sys.stderr.write("review refused\\n") + sys.exit(1) +if {hang!r}: + time.sleep(5) +sys.stdout.write({auth_status!r}) +sys.stdout.flush() +if {linger!r}: + subprocess.Popen([sys.executable, "-c", "import time; time.sleep(5)"]) +""" + return write_cli(tmp_path, name, script), calls + + +def calls_of(calls): + return calls.read_text(encoding="utf-8").splitlines() if calls.exists() else [] + + +def review_calls(calls): + return [c for c in calls_of(calls) if "--input-format stream-json" in c] + + +def model_of(call): + args = call.split(" | ")[0].split() + return args[args.index("--model") + 1] + + +@pytest.fixture +def no_credential(monkeypatch, tmp_path): + # CLAUDE_CODE_REMOTE_SESSION_ID makes every session share one state file. + for var in ("SECURITY_REVIEW_MODEL", "CLAUDE_CODE_EXECPATH", "CLAUDE_CODE_REMOTE_SESSION_ID", + *llm._PROVIDER_ENV_VARS): + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(tmp_path / "no-claude")) + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + monkeypatch.setattr(_base, "DEBUG_LOG_FILE", str(tmp_path / "log.txt")) + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", False) + new_hook_process(monkeypatch) + + +def new_hook_process(monkeypatch): + monkeypatch.setattr(llm, "_gateway_cli", None) + monkeypatch.setattr(llm, "_gateway_check_unanswered", False) + monkeypatch.setattr(llm, "_gateway_review_timed_out", False) + + +class TestGatewaySignInCheck: + @pytest.mark.parametrize("auth_status, signed_in", [ + pytest.param(SIGNED_IN, True, id="signed-in"), + pytest.param(NOT_SIGNED_IN, False, id="gateway-named-but-not-signed-in"), + pytest.param(json.dumps({"loggedIn": True, "apiProvider": "firstParty"}), False, + id="first-party"), + pytest.param(json.dumps({"loggedIn": "true", "apiProvider": "gateway"}), False, + id="logged-in-not-a-boolean"), + pytest.param("Logged in via gateway", False, id="not-json"), + pytest.param("[]", False, id="not-an-object"), + pytest.param("[" * 60000, False, id="too-deeply-nested"), + ]) + def test_reviews_only_for_a_signed_in_gateway_session( + self, no_credential, monkeypatch, tmp_path, auth_status, signed_in): + cli, calls = make_cli(tmp_path, auth_status) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.can_review("s1") is signed_in + assert [c.split(" | ")[0] for c in calls_of(calls)] == ["auth status --json"] + + def test_cli_that_cannot_start_means_no_review(self, no_credential): + assert llm.can_review("s1") is False + + def test_no_cli_found_means_no_review(self, no_credential, monkeypatch): + monkeypatch.setattr(llm, "_user_cli_path", lambda: None) + assert llm.can_review("s1") is False + + def test_relative_cli_path_is_not_run(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", f"./{cli.name}") + assert llm.can_review("s1") is False + assert calls_of(calls) == [] + + def test_asked_from_the_home_directory(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + home, repo = tmp_path / "home", tmp_path / "repo" + home.mkdir() + repo.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) # "~" on Windows + monkeypatch.chdir(repo) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.can_review("s1") + assert calls_of(calls)[0].endswith(f"CWD={home}") + + def test_hung_cli_means_no_review(self, no_credential, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, SIGNED_IN, hang=True) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + monkeypatch.setattr(llm, "_GATEWAY_CHECK_TIMEOUT_S", 1) + assert llm.can_review("s1") is False + + def test_answer_is_read_while_a_process_it_started_holds_stdout( + self, no_credential, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, SIGNED_IN, linger=True) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + monkeypatch.setattr(llm, "_GATEWAY_CHECK_TIMEOUT_S", 3) + assert llm.can_review("s1") is True + + def test_asked_once_per_session(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.can_review("s1") + new_hook_process(monkeypatch) + assert llm.can_review("s1") + assert len(calls_of(calls)) == 1 + new_hook_process(monkeypatch) + assert llm.can_review("s2") + assert len(calls_of(calls)) == 2 + + def test_no_answer_is_asked_again(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, "") + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.can_review("s1") is False + make_cli(tmp_path, SIGNED_IN) + new_hook_process(monkeypatch) + assert llm.can_review("s1") is True + assert len(calls_of(calls)) == 2 + + def test_a_different_cli_is_asked_again(self, no_credential, monkeypatch, tmp_path): + first, _ = make_cli(tmp_path, SIGNED_IN, name="first") + second, second_calls = make_cli(tmp_path, NOT_SIGNED_IN, name="second") + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(first)) + assert llm.can_review("s1") + new_hook_process(monkeypatch) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(second)) + assert llm.can_review("s1") is False + assert len(calls_of(second_calls)) == 1 + + def test_credential_in_env_never_asks_the_cli(self, no_credential, monkeypatch, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + assert llm.can_review("s1") + assert calls_of(calls) == [] + + def test_telemetry_names_the_route(self, no_credential, monkeypatch, tmp_path): + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False) + cli, _ = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert llm.gateway_cfg() == 0 + assert llm.can_review("s1") + assert llm.gateway_cfg() == 4 + + def test_essential_traffic_only_still_reviews(self, no_credential, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + monkeypatch.setenv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1") + assert llm.can_review("s1") + + +class FakeChild: + """Stands in for the child CLI's review; `reply` is what each call returns.""" + + def __init__(self): + self.prompts = [] + self.reply = {"hasVulnerabilities": False, "vulnerabilities": []} + + def __call__(self, prompt, schema, *, max_tokens=16000, model=None, cli_path=None): + self.prompts.append(prompt) + if self.reply is None: + llm._last_call_claude_http_error = -1 + return self.reply + + +class TestGatewayReviewOutcome: + @pytest.fixture + def child(self, no_credential, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, SIGNED_IN) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + fake = FakeChild() + monkeypatch.setattr(llm, "_call_claude_via_sdk", fake) + return fake + + def test_review_is_sent_to_the_child(self, child): + assert llm.can_review("s1") + assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, []) + assert not llm.last_review_failed() + assert "+x = 1" in child.prompts[0] + assert child.prompts[0].startswith(llm._CODE_REVIEW_RUBRIC) + + @pytest.mark.parametrize("reply", [ + pytest.param(None, id="child-failed"), + pytest.param({"findings": []}, id="no-verdict"), + ]) + def test_child_without_a_verdict_is_a_failed_review(self, child, reply): + child.reply = reply + assert llm.can_review("s1") + assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, []) + assert llm.last_review_failed() + + def test_failed_review_is_tried_on_sonnet_unless_it_timed_out(self, child, monkeypatch): + child.reply = None + assert llm.can_review("s1") + llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) + assert len(child.prompts) == 2 + monkeypatch.setattr(llm, "_gateway_review_timed_out", True) + llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) + assert len(child.prompts) == 3 and llm.last_review_failed() + + def test_not_signed_in_sends_nothing(self, child, monkeypatch, tmp_path): + cli, _ = make_cli(tmp_path, NOT_SIGNED_IN, name="signed-out") + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli)) + assert not llm.can_review("s1") + assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, []) + assert not llm.last_review_failed() + assert child.prompts == [] + + +def test_timed_out_review_logs_what_the_cli_retried(no_credential, monkeypatch, tmp_path): + """The CLI retries a refused sign-in by itself until the plugin's time + limit; the retries are in its output, not on stderr.""" + class Retry: + subtype, data = "api_retry", {"error_status": 401} + + async def query(prompt, options): + yield Retry() + raise asyncio.TimeoutError() + + mod = types.ModuleType("claude_agent_sdk") + mod.query = query + mod.ClaudeAgentOptions = lambda **kwargs: kwargs + mod.AssistantMessage = type("AssistantMessage", (), {}) + mod.ResultMessage = type("ResultMessage", (), {}) + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + cli, _ = make_cli(tmp_path, SIGNED_IN) + schema = {"type": "object", "properties": {}} + assert llm._call_claude_via_sdk("review this", schema, cli_path=str(cli)) is None + assert llm._gateway_review_timed_out is True + assert ("gateway sdk-single-turn: timeout after 120s; the CLI's API requests were " + "retried after status 401") in (tmp_path / "log.txt").read_text() + # Not for the cloud-provider route, where the model can be the reason. + monkeypatch.setattr(llm, "_gateway_review_timed_out", False) + assert llm._call_claude_via_sdk("review this", schema) is None + assert llm._gateway_review_timed_out is False + + +def without_credential(hook_env): + return {k: v for k, v in hook_env.items() + if k not in ("ANTHROPIC_API_KEY", "SECURITY_REVIEW_MODEL", + "CLAUDE_CODE_REMOTE_SESSION_ID", *llm._PROVIDER_ENV_VARS)} + + +class TestHooksInASignedInSession: + """The hooks with the real Agent SDK and a fake CLI that signs in but + refuses every review.""" + + @pytest.fixture + def session(self, hook_env, tmp_path): + pytest.importorskip("claude_agent_sdk") + env = without_credential(hook_env) + cli, calls = make_cli(tmp_path, SIGNED_IN) + env["SG_AGENTIC_CLI_PATH"] = str(cli) + return env, calls + + def test_commit_review_goes_through_the_cli_and_fails_loudly(self, session, workspace): + env, calls = session + _, repo = workspace + sha, out = commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env) + assert rc == 2 + assert metrics_of(so)["review_failed"] is True + assert ("did not complete: the review through Claude Code on the Claude apps " + "gateway returned no result.") in se + reviewed = repo / ".git" / "sg-reviewed-shas" + assert not reviewed.exists() or sha not in reviewed.read_text() + made = calls_of(calls) + assert made[0].startswith("auth status --json") + reviews = review_calls(calls) + assert [model_of(r) for r in reviews] == ["opus", "sonnet"] + # Every claude process the plugin starts (the sign-in check and the + # reviews) has this plugin switched off. The Agent SDK's own + # `claude -v` version check starts no session, so it is not checked. + assert " | SGD=1 | " in made[0] + assert all(" | SGD=1 | " in r for r in reviews) + # The single-shot review gets no tools, as on Bedrock and Vertex. + assert all(" --tools --strict-mcp-config" in r for r in reviews) + assert metrics_of(so)["gateway_cfg"] & 4 + + def test_pinned_model_is_sent_as_given(self, session, workspace): + env, calls = session + env["SECURITY_REVIEW_MODEL"] = "claude-sonnet-5-5" + _, repo = workspace + _, out = commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env) + assert rc == 2 + assert [model_of(r) for r in review_calls(calls)] == ["claude-sonnet-5-5"] + assert "SECURITY_REVIEW_MODEL (claude-sonnet-5-5) may also name a model" in se + + def test_agentic_commit_review_runs(self, session, workspace): + env, calls = session + env["SG_AGENTIC_COMMIT_REVIEW"] = "1" + env["SG_AGENTIC_MAX_TURNS"] = "7" + _, repo = workspace + _, out = commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env) + assert rc == 2 and metrics_of(so)["review_failed"] is True + reviews = review_calls(calls) + assert any("--max-turns 7" in r for r in reviews) + # The agentic reviewer gets the file-reading tools and nothing else. + assert any(" --tools Read,Grep,Glob --strict-mcp-config" in r for r in reviews) + + def test_stop_review_goes_through_the_cli(self, session, workspace): + env, calls = session + ws, repo = workspace + assert run_hook(ups_payload(repo), env)[0] == 0 + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + rc, so, se = run_hook(stop_payload(repo), env) + assert metrics_of(so)["review_failed"] is True + assert review_calls(calls) + + def test_push_review_goes_through_the_cli(self, session, workspace, tmp_path): + env, calls = session + ws, repo = workspace + remote = tmp_path / "remote.git" + git(ws, "init", "-q", "--bare", str(remote)) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "-q", "-u", "origin", "main") + base = git(repo, "rev-parse", "HEAD").strip() + sha, _ = commit_file(repo, "app.py", VULN_PY) + git(repo, "push", "-q", "origin", "main") + push_stdout = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n" + rc, so, se = run_hook(bash_payload(repo, "git push origin main", push_stdout), env) + m = metrics_of(so) + assert rc == 2 and m["push_sweep"] is True and m["review_failed"] is True, m + assert review_calls(calls) + + def test_not_signed_in_skips_and_asks_once(self, hook_env, tmp_path, workspace): + env = without_credential(hook_env) + cli, calls = make_cli(tmp_path, NOT_SIGNED_IN) + env["SG_AGENTIC_CLI_PATH"] = str(cli) + _, repo = workspace + for n in range(2): + _, out = commit_file(repo, "app.py", VULN_PY + f"# {n}\n") + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env) + assert rc == 0 and metrics_of(so)["skip_reason"] == 22 + assert len(calls_of(calls)) == 1 + + def test_unanswered_sign_in_check_keeps_the_turn_for_the_next_stop( + self, hook_env, tmp_path, workspace): + pytest.importorskip("claude_agent_sdk") + env = without_credential(hook_env) + cli, calls = make_cli(tmp_path, "") + env["SG_AGENTIC_CLI_PATH"] = str(cli) + _, repo = workspace + assert run_hook(ups_payload(repo), env)[0] == 0 + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env) + rc, so, _ = run_hook(stop_payload(repo), env) + assert metrics_of(so)["skip_reason"] == 3 and not review_calls(calls) + # The CLI answers in the next turn: the first turn's edit is reviewed. + make_cli(tmp_path, SIGNED_IN) + assert run_hook(ups_payload(repo), env)[0] == 0 + rc, so, _ = run_hook(stop_payload(repo), env) + assert metrics_of(so)["review_failed"] is True + assert review_calls(calls) 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..a828e2ed --- /dev/null +++ b/plugins/security-guidance/tests/test_no_credentials_notice.py @@ -0,0 +1,215 @@ +"""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, +) +from test_gateway_sign_in import NOT_SIGNED_IN, SIGNED_IN, calls_of, make_cli + +# Anything in the developer's shell that changes whether a review would run. +_AMBIENT = ( + "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", + # Makes every session share one state file. + "CLAUDE_CODE_REMOTE_SESSION_ID", + "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) + + +def test_no_notice_in_a_signed_in_gateway_session(workspace, hook_env, tmp_path): + # Claude Code passes no credential there, but the reviews run through + # the user's claude, so they are running. + _, repo = workspace + cli, calls = make_cli(tmp_path, SIGNED_IN) + env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli)) + assert _notice(repo, env) is None + # The check counts as this week's: a new session's edit does not ask. + assert _notice(repo, env, session_id="s2") is None + assert os.path.exists(_marker(env)) + assert [c.split(" | ")[0] for c in calls_of(calls)] == ["auth status --json"] + # A week later the edit asks again. + eight_days = time.time() - 8 * 86400 + os.utime(_marker(env), (eight_days, eight_days)) + assert _notice(repo, env, session_id="s3") is None + assert len(calls_of(calls)) == 2 + + +def test_edit_outside_a_git_repo_does_not_ask_claude(workspace, hook_env, tmp_path): + cli, calls = make_cli(tmp_path, SIGNED_IN) + plain = tmp_path / "plain" + plain.mkdir() + env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli)) + assert _notice(plain, env, name="notes.py") is None + assert calls_of(calls) == [] + + +def test_notice_when_the_gateway_session_is_not_signed_in(workspace, hook_env, tmp_path): + _, repo = workspace + cli, calls = make_cli(tmp_path, NOT_SIGNED_IN) + env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli)) + assert "is not running" in _notice(repo, env) + # Within the week no notice is due, so claude is not asked again. + assert _notice(repo, env, session_id="s2") is None + assert len(calls_of(calls)) == 1 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] diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py index 3e2aa86c..3b9521ff 100644 --- a/plugins/security-guidance/tests/test_reviewer_tools.py +++ b/plugins/security-guidance/tests/test_reviewer_tools.py @@ -1,6 +1,8 @@ """The inner Claude Code the plugin starts for a review gets only the tools the review needs.""" +import json import sys +import threading import types import pytest @@ -9,11 +11,22 @@ import llm READ_ONLY = {"tools": "Read,Grep,Glob", "strict-mcp-config": None} NO_TOOLS = {"tools": "", "strict-mcp-config": None} +# Once an inner CLI has refused --strict-mcp-config. +READ_ONLY_NO_MCP = {"tools": "Read,Grep,Glob", "disallowedTools": "mcp__*"} +NO_TOOLS_NO_MCP = {"tools": "", "disallowedTools": "mcp__*"} + + +@pytest.fixture(autouse=True) +def strict_mcp_flag_sent(monkeypatch): + monkeypatch.setattr(llm, "_send_strict_mcp", True) def test_tool_flags(): assert llm._only_tools_args(("Read", "Grep", "Glob")) == READ_ONLY assert llm._only_tools_args() == NO_TOOLS + llm._send_strict_mcp = False + assert llm._only_tools_args(("Read", "Grep", "Glob")) == READ_ONLY_NO_MCP + assert llm._only_tools_args() == NO_TOOLS_NO_MCP def test_flags_reach_the_command_line_of_the_installed_sdk(): @@ -26,6 +39,16 @@ def test_flags_reach_the_command_line_of_the_installed_sdk(): cmd = transport.SubprocessCLITransport(prompt="x", options=opts)._build_command() assert cmd[cmd.index("--tools") + 1] == "Read,Grep,Glob" assert cmd.count("--tools") == 1 and "--strict-mcp-config" in cmd + assert "--disallowedTools" not in cmd + + llm._send_strict_mcp = False + opts = sdk.ClaudeAgentOptions( + cli_path="claude", allowed_tools=["Read", "Grep", "Glob"], + extra_args=llm._only_tools_args(llm._REVIEWER_TOOLS)) + cmd = transport.SubprocessCLITransport(prompt="x", options=opts)._build_command() + assert cmd[cmd.index("--tools") + 1] == "Read,Grep,Glob" + assert cmd[cmd.index("--disallowedTools") + 1] == "mcp__*" + assert cmd.count("--disallowedTools") == 1 and "--strict-mcp-config" not in cmd @pytest.fixture @@ -82,3 +105,103 @@ def test_single_turn_sdk_review_gets_no_tools(sdk): assert llm._call_claude_via_sdk("review this", schema) is not None assert len(sdk) == 1 assert sdk[0]["extra_args"] == NO_TOOLS and sdk[0]["allowed_tools"] == [] + + +# What Claude Code prints, before exiting 1, on a machine whose administrator +# delivers the MCP servers. +REFUSAL = "You cannot use --strict-mcp-config when an enterprise MCP config is present" + + +@pytest.fixture +def managed_mcp(sdk, monkeypatch): + """The stand-in SDK's inner CLI now refuses --strict-mcp-config. Gives + the options of the refused starts and of the ones that ran.""" + answer = sys.modules["claude_agent_sdk"].query + refused = [] + + async def query(prompt, options): + if "strict-mcp-config" in options.kwargs["extra_args"]: + refused.append(options.kwargs) + options.kwargs["stderr"](REFUSAL) + raise RuntimeError("Command failed with exit code 1") + async for msg in answer(prompt, options): + yield msg + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + return refused, sdk + + +def test_agentic_review_runs_where_the_strict_mcp_flag_is_refused(managed_mcp, tmp_path): + _, vulns, metrics = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert len(vulns) == 1 + # The refused start's line is not what child_stderr is there to count. + assert "agentic_fallback" not in metrics and "child_stderr" not in metrics + refused, ran = managed_mcp + assert [o["extra_args"] for o in refused] == [READ_ONLY] + # investigate, second investigate pass, refute + assert [o["extra_args"] for o in ran] == [READ_ONLY_NO_MCP] * 3 + for opts in ran: + assert opts["allowed_tools"] == ["Read", "Grep", "Glob"] + + +def test_single_turn_sdk_review_runs_where_the_strict_mcp_flag_is_refused(managed_mcp): + schema = {"type": "object", "properties": {}} + assert llm._call_claude_via_sdk("review this", schema) is not None + refused, ran = managed_mcp + assert [o["extra_args"] for o in refused] == [NO_TOOLS] + assert [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] + # The refusal is remembered for the rest of the hook process. + assert llm._call_claude_via_sdk("review this", schema) is not None + assert len(refused) == 1 and ran[-1]["extra_args"] == NO_TOOLS_NO_MCP + + +def test_other_start_failures_are_not_retried(sdk, monkeypatch, tmp_path): + async def query(prompt, options): + sdk.append(options.kwargs) + options.kwargs["stderr"]("Fallback model cannot be the same as the main model") + raise RuntimeError("Command failed with exit code 1") + yield + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + guidance, vulns, metrics = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert guidance is None and vulns == [] + assert metrics["agentic_fallback"] == "investigate:RuntimeError" + assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is None + assert [o["extra_args"] for o in sdk] == [READ_ONLY, NO_TOOLS] + + +def test_reviews_started_together_are_each_started_again(managed_mcp): + refused, ran = managed_mcp + both_refused = threading.Barrier(2, timeout=10) + refuse = sys.modules["claude_agent_sdk"].query + + async def query(prompt, options): + if "strict-mcp-config" in options.kwargs["extra_args"]: + both_refused.wait() + async for msg in refuse(prompt, options): + yield msg + + sys.modules["claude_agent_sdk"].query = query + schema = {"type": "object", "properties": {}} + results = [] + threads = [threading.Thread( + target=lambda: results.append(llm._call_claude_via_sdk("review this", schema))) + for _ in range(2)] + for t in threads: + t.start() + for t in threads: + t.join(20) + assert len(results) == 2 and None not in results + assert len(refused) == 2 and [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] * 2 + + +def test_review_rows_say_when_the_flag_was_left_out(managed_mcp, capsys): + import security_reminder_hook as hook + + def row(): + hook.emit_metrics({"vulns_found": 0, "review_ms": 10}) + return json.loads(capsys.readouterr().out)["metrics"] + + assert "strict_mcp_off" not in row() + assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is not None + assert row()["strict_mcp_off"] == 1 diff --git a/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py b/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py new file mode 100644 index 00000000..36f2742b --- /dev/null +++ b/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py @@ -0,0 +1,183 @@ +"""The agent SDK is not installed for reviews that are switched off. + +ensure_agent_sdk.py (SessionStart) and the PostToolUse rescue spawn built a +venv of a few hundred MB whatever the environment said, including under +SECURITY_GUIDANCE_DISABLE=1, and the rescue started ensure_agent_sdk.py again +every five minutes on machines whose SDK lives in that venv. See #5331. +""" +import importlib.util +import subprocess +import sys + +import pytest + +from conftest import HOOKS_DIR +import _base +import ensure_agent_sdk as boot +import llm +import security_reminder_hook as hook + +OFF = [ + {"SECURITY_GUIDANCE_DISABLE": "1"}, + {"SECURITY_GUIDANCE_DISABLE": "true"}, + {"ENABLE_SECURITY_REMINDER": "0"}, + {"ENABLE_CODE_SECURITY_REVIEW": "0"}, + {"ENABLE_STOP_REVIEW": "0", "ENABLE_COMMIT_REVIEW": "0"}, +] +STILL_ON = [{}, {"ENABLE_STOP_REVIEW": "0"}, {"ENABLE_COMMIT_REVIEW": "0"}, + {"SECURITY_GUIDANCE_DISABLE": "0"}] +SWITCHES = ("SECURITY_GUIDANCE_DISABLE", "ENABLE_SECURITY_REMINDER", + "ENABLE_CODE_SECURITY_REVIEW", "ENABLE_STOP_REVIEW", "ENABLE_COMMIT_REVIEW") + + +@pytest.fixture +def state(tmp_path, monkeypatch): + """Empty state dir, no SDK in the interpreter, switches unset.""" + for name in SWITCHES: + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + monkeypatch.setattr(boot, "_sdk_on_syspath", lambda: False) + return tmp_path / "state" + + +@pytest.fixture +def builds(monkeypatch): + """Records the venv / pip commands instead of running them.""" + calls = [] + + def run(cmd, **kwargs): + calls.append([str(c) for c in cmd]) + return subprocess.CompletedProcess(cmd, 0, b"", b"") + monkeypatch.setattr(boot.subprocess, "run", run) + return calls + + +@pytest.fixture +def spawns(state, monkeypatch): + """Records the rescue's detached starts of ensure_agent_sdk.py.""" + calls = [] + monkeypatch.setattr(importlib.util, "find_spec", lambda name: None) + monkeypatch.setattr(hook, "_SDK_BOOTSTRAP_THROTTLE", str(state / ".sdk_bootstrap_spawned")) + monkeypatch.setattr(hook.subprocess, "Popen", lambda cmd, **kw: calls.append(cmd)) + return calls + + +def _install(root, finished=True): + pkg = root / "claude_agent_sdk" + pkg.mkdir(parents=True) + (pkg / "__init__.py").write_text("") + if finished: + (root / "claude_agent_sdk-0.2.0.dist-info").mkdir() + + +@pytest.mark.parametrize("env", OFF) +def test_session_start_builds_nothing_when_reviews_are_off(state, builds, monkeypatch, env): + for k, v in env.items(): + monkeypatch.setenv(k, v) + assert boot.main() == (boot.SKIP_REVIEWS_OFF, "", "") + assert builds == [] and not state.exists() + + +@pytest.mark.parametrize("env", STILL_ON) +def test_session_start_still_builds_when_a_review_can_run(state, builds, monkeypatch, env): + for k, v in env.items(): + monkeypatch.setenv(k, v) + assert boot.main()[0] == boot.BUILT + assert [c[1:3] for c in builds] == [["-m", "venv"], ["-m", "pip"]] + + +@pytest.mark.parametrize("env", OFF[2:]) +def test_rescue_does_not_start_the_bootstrap_when_reviews_are_off(spawns, monkeypatch, env): + for k, v in env.items(): + monkeypatch.setenv(k, v) + hook._maybe_bootstrap_agent_sdk_async() + assert spawns == [] + + +def test_rescue_starts_the_bootstrap_once_when_nothing_is_installed(spawns): + hook._maybe_bootstrap_agent_sdk_async() + hook._maybe_bootstrap_agent_sdk_async() + assert len(spawns) == 1 and spawns[0][1].endswith("ensure_agent_sdk.py") + + +@pytest.mark.parametrize("where", [ + "agent-sdk-venv/lib/python3.12/site-packages", + "agent-sdk-venv/Lib/site-packages", + "agent-sdk-libs", +]) +def test_rescue_leaves_an_existing_install_alone(spawns, state, where): + _install(state / where) + hook._maybe_bootstrap_agent_sdk_async() + assert spawns == [] and not (state / ".sdk_bootstrap_spawned").exists() + + +def test_rescue_still_runs_for_an_install_that_was_cut_short(spawns, state): + _install(state / "agent-sdk-venv/lib/python3.12/site-packages", finished=False) + hook._maybe_bootstrap_agent_sdk_async() + assert len(spawns) == 1 + + +def test_reviewer_and_bootstrap_agree_on_where_the_sdk_is_installed(state, monkeypatch): + for where in ("agent-sdk-venv/lib/python3.12/site-packages", "agent-sdk-libs"): + _install(state / where) + monkeypatch.setattr(sys, "path", list(sys.path)) + assert llm._inject_agent_sdk_venv_into_syspath(str(state)) + assert {str(state / "agent-sdk-venv/lib/python3.12/site-packages"), + str(state / "agent-sdk-libs")} <= set(sys.path) + + +def test_switches_are_read_the_same_way_as_the_hook_reads_them(monkeypatch): + for env in OFF + STILL_ON: + for name in SWITCHES: + monkeypatch.delenv(name, raising=False) + for k, v in env.items(): + monkeypatch.setenv(k, v) + out = subprocess.run( + [sys.executable, "-c", + "import security_reminder_hook as h; " + "print(h.SECURITY_GUIDANCE_DISABLED or not h.ENABLE_CODE_SECURITY_REVIEW" + " or not (h.ENABLE_STOP_REVIEW or h.ENABLE_COMMIT_REVIEW))"], + cwd=HOOKS_DIR, capture_output=True, text=True).stdout.strip() + assert out == str(_base.llm_reviews_switched_off()), env + + +def test_disabled_plugin_says_nothing_on_a_python_below_3_10(state, builds, monkeypatch): + monkeypatch.setenv("SECURITY_GUIDANCE_DISABLE", "1") + monkeypatch.setattr(boot.sys, "version_info", (3, 9, 6, "final", 0)) + assert boot.main()[0] == boot.SKIP_REVIEWS_OFF + + +def test_install_the_session_cannot_use_is_counted(state, tmp_path, monkeypatch): + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", False) + monkeypatch.setattr(boot, "_near_git_repo", lambda: False) + assert boot._install_context_metrics(boot.BUILT, state) == {"sdk_no_creds": 1, "sdk_no_git": 1} + assert boot._install_context_metrics(boot.BUILD_FAILED, state) == {} + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + monkeypatch.setattr(boot, "_near_git_repo", lambda: True) + assert boot._install_context_metrics(boot.NOOP_VENV, state) == {} + + +def test_session_directory_in_or_holding_a_repository(tmp_path, monkeypatch): + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(tmp_path)) + if boot._near_git_repo(): + pytest.skip("the temp dir is itself inside a git work tree") + (tmp_path / "ws" / "repo" / ".git").mkdir(parents=True) + (tmp_path / "ws" / "repo" / "src").mkdir() + for inside in ("ws", "ws/repo", "ws/repo/src"): + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(tmp_path / inside)) + assert boot._near_git_repo(), inside + + +@pytest.mark.parametrize("cfg, counted", [ + ("home = /usr/bin\nversion = 3.99.1\n", {"sdk_venv_py": 399}), + ("home = /usr/bin\nversion_info = 3.99.1.final.0\n", {"sdk_venv_py": 399}), + (f"version = {sys.version_info[0]}.{sys.version_info[1]}.0\n", {}), + ("home = /usr/bin\n", {}), +]) +def test_venv_built_by_another_python_is_counted(state, monkeypatch, cfg, counted): + monkeypatch.setattr(boot, "_near_git_repo", lambda: True) + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + (state / "agent-sdk-venv").mkdir(parents=True) + (state / "agent-sdk-venv" / "pyvenv.cfg").write_text(cfg) + assert boot._install_context_metrics(boot.NOOP_VENV, state) == counted + assert boot._install_context_metrics(boot.BUILT, state) == {} diff --git a/plugins/security-guidance/tests/test_sdk_emptied_install.py b/plugins/security-guidance/tests/test_sdk_emptied_install.py new file mode 100644 index 00000000..415e8d99 --- /dev/null +++ b/plugins/security-guidance/tests/test_sdk_emptied_install.py @@ -0,0 +1,101 @@ +"""An SDK install whose package directory lost its files is rebuilt. + +`import claude_agent_sdk` succeeds on an empty directory (Python imports it +as a namespace package), so the bootstrap reported a healthy venv, the +reviewer's `from claude_agent_sdk import ...` failed on every commit, and +nothing repaired it until the venv was deleted by hand. See #6612. +""" +import importlib.util +import subprocess +import sys +from pathlib import Path + +import pytest + +import _base +import ensure_agent_sdk as boot +from test_sdk_bootstrap_switches import SWITCHES + + +def _fill(pkg): + pkg.mkdir(parents=True, exist_ok=True) + (pkg / "__init__.py").write_text("AssistantMessage = object\n") + (pkg / "__pycache__").mkdir(exist_ok=True) + + +def _empty(pkg): + for f in pkg.rglob("*"): + if f.is_file(): + f.unlink() + + +@pytest.fixture +def venv(tmp_path, monkeypatch): + """A real venv (no pip, so it is quick) holding a stand-in SDK package; + the build commands are recorded instead of run, the probes run for real.""" + for name in SWITCHES + ("PYTHONPATH",): + monkeypatch.delenv(name, raising=False) + state = tmp_path / "state" + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state)) + monkeypatch.setattr(boot, "_sdk_on_syspath", lambda: False) + monkeypatch.setattr(boot, "_near_git_repo", lambda: True) + subprocess.run([sys.executable, "-m", "venv", "--without-pip", + str(state / "agent-sdk-venv")], check=True) + pkg = Path(_base.agent_sdk_site_dirs(str(state))[0]) / "claude_agent_sdk" + _fill(pkg) + real_run = subprocess.run + builds = [] + + def run(cmd, **kwargs): + cmd = [str(c) for c in cmd] + if "-m" in cmd: + builds.append(cmd) + return subprocess.CompletedProcess(cmd, 0, b"", b"") + return real_run(cmd, **kwargs) + monkeypatch.setattr(boot.subprocess, "run", run) + return state, pkg, builds + + +def test_complete_install_is_left_alone(venv): + state, _, builds = venv + outcome = boot.main()[0] + assert outcome == boot.NOOP_VENV and builds == [] + assert "sdk_venv_emptied" not in boot._install_context_metrics(outcome, state) + + +def test_emptied_install_is_rebuilt_and_counted(venv): + state, pkg, builds = venv + _empty(pkg) + outcome = boot.main()[0] + assert outcome == boot.BUILT + assert builds[0][1:4] == ["-m", "venv", "--clear"] + assert any("pip" in c and "claude-agent-sdk" in c for c in builds) + assert boot._install_context_metrics(outcome, state)["sdk_venv_emptied"] == 1 + # The count belongs to the run that found it, not to later ones. + _fill(pkg) + outcome = boot.main()[0] + assert outcome == boot.NOOP_VENV + assert "sdk_venv_emptied" not in boot._install_context_metrics(outcome, state) + + +def test_venv_that_never_held_the_sdk_is_not_counted_as_emptied(venv): + state, pkg, builds = venv + _empty(pkg) + (pkg / "__pycache__").rmdir() + pkg.rmdir() + outcome = boot.main()[0] + assert outcome == boot.BUILT and builds + assert "sdk_venv_emptied" not in boot._install_context_metrics(outcome, state) + + +# An SDK installed for the interpreter running the tests is found behind the +# emptied directory, which hides what this test looks at. +@pytest.mark.skipif(importlib.util.find_spec("claude_agent_sdk") is not None, + reason="claude_agent_sdk is installed for this interpreter") +def test_emptied_fallback_install_is_not_reused(tmp_path, monkeypatch): + monkeypatch.delenv("PYTHONPATH", raising=False) + pkg = boot._target_dir(tmp_path) / "claude_agent_sdk" + _fill(pkg) + assert boot._target_sdk_importable(tmp_path) is True + _empty(pkg) + assert boot._target_sdk_importable(tmp_path) is False diff --git a/plugins/security-guidance/tests/test_secret_named_metric.py b/plugins/security-guidance/tests/test_secret_named_metric.py new file mode 100644 index 00000000..14d71923 --- /dev/null +++ b/plugins/security-guidance/tests/test_secret_named_metric.py @@ -0,0 +1,94 @@ +"""The Stop review counts the data files it sends whose name says they hold +secrets. Measurement only: the files are reviewed as before.""" +import pytest + +from conftest import ( + STUB_VULN, VULN_PY, make_repo, metrics_of, run_hook, stop_payload, ups_payload, +) + +import gitutil + + +@pytest.mark.parametrize("path", [ + "secrets.yml", + "config/secrets.yaml", + "secrets.prod.json", + ".secrets.toml", + "Secrets.YML", + "credentials.json", + "client_secret.json", + "keys/service-account.json", + "service_account.json", + "terraform/secrets.tfvars", + "client-secret.json", + "client_secret_1234-abc.apps.googleusercontent.com.json", + "serviceAccountKey.json", +]) +def test_secret_named_data_files(path): + assert gitutil._is_secret_named(path) + + +@pytest.mark.parametrize("path", [ + "secrets.py", + "src/credentials.ts", + "secrets_manager.yaml", + "app-secrets.json", + "docs/secrets.md", + "secrets", + "config.yaml", + "package.json", + "secrets/config.yaml", + "secrets.example.yml", + "credentials.sample.json", + "secrets.schema.json", + "secrets.enc.yaml", + "secrets.sops.yaml", + ".json", +]) +def test_other_files_are_not_counted(path): + assert not gitutil._is_secret_named(path) + + +def _review(tmp_path, hook_env, files): + repo = make_repo(tmp_path / "repo") + run_hook(ups_payload(repo), hook_env) + for name, body in files.items(): + (repo / name).write_text(body) + return run_hook(stop_payload(repo), hook_env) + + +def test_stop_hook_counts_secret_named_files_and_still_reviews_them(tmp_path, hook_env, stub_api): + _rc, stdout, _err = _review(tmp_path, hook_env, { + "secrets.yml": "db:\n password: example\n", + "credentials.json": '{"token": "example"}\n', + "app.py": "print(1)\n", + }) + m = metrics_of(stdout) + assert m.get("secret_named_reviewed") == 2 + assert m.get("files_reviewed") == 3 + assert "/v1/messages" in stub_api.calls + + +def test_count_is_on_the_findings_row_too(tmp_path, hook_env, stub_api): + stub_api.vulns = [STUB_VULN] + rc, stdout, _err = _review(tmp_path, hook_env, { + "secrets.yml": "db:\n password: example\n", + "app.py": VULN_PY, + }) + assert rc == 2 + assert metrics_of(stdout).get("secret_named_reviewed") == 1 + + +def test_no_key_when_no_such_file_is_reviewed(tmp_path, hook_env, stub_api): + _rc, stdout, _err = _review(tmp_path, hook_env, {"app.py": "print(1)\n"}) + m = metrics_of(stdout) + assert m.get("files_reviewed") == 1 + assert "secret_named_reviewed" not in m + + +def test_count_is_on_the_failed_review_row(tmp_path, hook_env, stub_api): + stub_api.status = 500 + _rc, stdout, _err = _review(tmp_path, hook_env, {"secrets.yml": "a: b\n"}) + m = metrics_of(stdout) + assert m.get("review_failed") is True + assert m.get("secret_named_reviewed") == 1 diff --git a/plugins/security-guidance/tests/test_secret_shaped_paths.py b/plugins/security-guidance/tests/test_secret_shaped_paths.py index bfd5180d..b20beef3 100644 --- a/plugins/security-guidance/tests/test_secret_shaped_paths.py +++ b/plugins/security-guidance/tests/test_secret_shaped_paths.py @@ -25,6 +25,11 @@ import gitutil "private_dot_netrc", "dot_aws/credentials", "Deploy_RSA", + ".credentials.json", + ".claude/.credentials.json", + "private_dot_claude/private_dot_credentials.json", + ".claude.json", + "dot_claude.json", ]) def test_secret_shaped_names_are_not_reviewable(path): assert gitutil._is_secret_shaped(path) @@ -44,6 +49,8 @@ def test_secret_shaped_names_are_not_reviewable(path): "bin/deploy", "Dockerfile.dev", "executable_backup.sh", + "config/credentials.json", + "src/claude.json", ]) def test_ordinary_source_stays_reviewable(path): assert not gitutil._is_secret_shaped(path) @@ -93,3 +100,16 @@ def test_stop_hook_reports_how_many_files_it_left_out(tmp_path, hook_env, stub_a _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) assert metrics_of(stdout).get("secret_shaped_skipped") == 2 assert stub_api.calls == [] + + +@pytest.mark.parametrize("name", [".credentials.json", ".claude.json"]) +def test_claude_code_files_rewritten_during_the_turn_are_not_sent(tmp_path, hook_env, stub_api, name): + repo = make_repo(tmp_path / "repo") + (repo / name).write_text('{"accessToken": "old"}\n') + run_hook(ups_payload(repo), hook_env) + (repo / name).write_text('{"accessToken": "new-and-longer"}\n') + later = (repo / name).stat().st_mtime + 5 + os.utime(repo / name, (later, later)) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + assert metrics_of(stdout).get("secret_shaped_skipped") == 1 + assert stub_api.calls == [] diff --git a/plugins/security-guidance/tests/test_stop_baseline_checkout.py b/plugins/security-guidance/tests/test_stop_baseline_checkout.py new file mode 100644 index 00000000..97c20ab3 --- /dev/null +++ b/plugins/security-guidance/tests/test_stop_baseline_checkout.py @@ -0,0 +1,282 @@ +"""The turn baseline belongs to the checkout the prompt hook captured it in. +A Stop review in another checkout (the session entered a worktree, or edited +another repo) does not use it: commits count from that checkout's own HEAD at +the time of the prompt, files are diffed against HEAD, and uncommitted files +last written before the prompt are left out. Stop rows carry `bl_origin`, +saying which case the row was.""" +import json +import os +import shutil +import time + +import pytest + +from conftest import ( + STUB_VULN, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, +) + + +@pytest.fixture +def checkouts(tmp_path, monkeypatch): + """a: a repo's primary checkout. b: a linked worktree of it whose branch + already holds a committed file that a's branch lacks. Both were last + committed to an hour ago.""" + monkeypatch.setenv("GIT_COMMITTER_DATE", f"@{int(time.time()) - 3600} +0000") + a = make_repo(tmp_path / "ws" / "a", {"app.py": "print('hi')\n"}) + b = tmp_path / "ws" / "b" + git(a, "worktree", "add", "-q", "-b", "feature", str(b)) + (b / "old.py").write_text(VULN_PY) + git(b, "add", "-A") + git(b, "commit", "-q", "-m", "earlier work") + monkeypatch.delenv("GIT_COMMITTER_DATE") + return a, b + + +def _stop(cwd, hook_env): + return metrics_of(run_hook(stop_payload(cwd), hook_env)[1]) + + +def _state(hook_env): + d = hook_env["SECURITY_WARNINGS_STATE_DIR"] + for e in os.scandir(d): + if e.name.endswith(".json"): + with open(e.path) as f: + state = json.load(f) + if "baseline_sha" in state: + return state + raise AssertionError(os.listdir(d)) + + +def test_baseline_from_the_reviewed_checkout(hook_env, checkouts): + a, _ = checkouts + run_hook(ups_payload(a), hook_env) + (a / "app.py").write_text(VULN_PY) + m = _stop(a, hook_env) + assert m["files_reviewed"] == 1 and m["bl_origin"] == 0 + + +def test_sent_on_a_skipped_review_too(hook_env, checkouts): + a, _ = checkouts + run_hook(ups_payload(a), hook_env) + m = _stop(a, hook_env) + assert m["skipped"] is True and m["bl_origin"] == 0 + + +def test_prompt_in_a_subdirectory_is_the_same_checkout(hook_env, checkouts): + a, _ = checkouts + (a / "pkg").mkdir() + run_hook(ups_payload(a / "pkg"), hook_env) + (a / "app.py").write_text(VULN_PY) + assert _stop(a, hook_env)["bl_origin"] == 0 + + +def test_turn_that_only_enters_another_worktree_reviews_nothing( + hook_env, checkouts, stub_api): + a, b = checkouts + run_hook(ups_payload(a), hook_env) + m = _stop(b, hook_env) + # b's earlier commit is not a commit made this turn. + assert m["skipped"] is True and m["bl_origin"] == 1 + assert not stub_api.calls + + +def test_edit_after_entering_another_worktree_is_reviewed( + hook_env, checkouts, stub_api): + a, b = checkouts + run_hook(ups_payload(a), hook_env) + (b / "new.py").write_text(VULN_PY) + run_hook(edit_payload(b, b / "new.py"), hook_env) + m = _stop(b, hook_env) + assert m["files_reviewed"] == 1 and m["bl_origin"] == 1 + assert stub_api.calls.count("/v1/messages") == 1 + + +def test_commit_made_after_entering_another_worktree_is_reviewed( + hook_env, checkouts): + a, b = checkouts + run_hook(ups_payload(a), hook_env) + (b / "new.py").write_text(VULN_PY) + git(b, "add", "-A") + git(b, "commit", "-q", "-m", "this turn") + m = _stop(b, hook_env) + # new.py, not old.py from the earlier commit. + assert m["files_reviewed"] == 1 and m["bl_origin"] == 1 + + +def test_commit_in_a_worktree_created_this_turn_is_reviewed(hook_env, checkouts): + a, _ = checkouts + run_hook(ups_payload(a), hook_env) + c = a.parent / "c" + git(a, "worktree", "add", "-q", "-b", "fresh", str(c)) + (c / "new.py").write_text(VULN_PY) + git(c, "add", "-A") + git(c, "commit", "-q", "-m", "this turn") + (c / "more.py").write_text(VULN_PY) + m = _stop(c, hook_env) + assert m["files_reviewed"] == 2 and m["bl_origin"] == 1 + + +def test_uncommitted_work_already_in_the_other_worktree_is_left_out( + hook_env, checkouts, stub_api): + a, b = checkouts + (b / "scratch.py").write_text(VULN_PY) # untracked + (b / "old.py").write_text(VULN_PY + "# todo\n") # tracked, edited + time.sleep(2.2) # past the slack allowed around the prompt time + run_hook(ups_payload(a), hook_env) + m = _stop(b, hook_env) + assert m["skipped"] is True and m["bl_origin"] == 1 + assert not stub_api.calls + # Both are reviewed once the turn writes to them. + (b / "scratch.py").write_text(VULN_PY + "x = 1\n") + (b / "old.py").write_text(VULN_PY + "# done\n") + m = _stop(b, hook_env) + assert m["files_reviewed"] == 2 and m["bl_origin"] == 1 + + +def test_baseline_kept_from_an_interrupted_turn_in_another_worktree( + hook_env, checkouts, stub_api): + a, b = checkouts + run_hook(ups_payload(a), hook_env) + run_hook(edit_payload(a, a / "app.py"), hook_env) + run_hook(ups_payload(b), hook_env) + m = _stop(b, hook_env) + assert m["skipped"] is True and m["bl_origin"] == 21 + assert not stub_api.calls + + +def test_baseline_kept_from_an_interrupted_turn_in_the_same_checkout(hook_env, checkouts): + a, _ = checkouts + run_hook(ups_payload(a), hook_env) + run_hook(edit_payload(a, a / "app.py"), hook_env) + run_hook(ups_payload(a), hook_env) + (a / "app.py").write_text(VULN_PY) + assert _stop(a, hook_env)["bl_origin"] == 20 + + +def test_interrupted_turn_then_a_prompt_that_cannot_capture(hook_env, checkouts): + a, _ = checkouts + run_hook(ups_payload(a), hook_env) + run_hook(edit_payload(a, a / "app.py"), hook_env) + run_hook(ups_payload(a), hook_env) + run_hook(ups_payload(a.parent), hook_env) + (a / "app.py").write_text(VULN_PY) + assert _stop(a, hook_env)["bl_origin"] == 10 + + +def test_baseline_from_another_repository(hook_env, checkouts, tmp_path): + a, _ = checkouts + other = make_repo(tmp_path / "ws" / "other", {"lib.py": "x = 1\n"}) + run_hook(ups_payload(a), hook_env) + (other / "lib.py").write_text(VULN_PY) + m = _stop(other, hook_env) + assert m["files_reviewed"] == 1 and m["bl_origin"] == 2 + + +def test_baseline_from_a_checkout_that_is_gone(hook_env, checkouts): + a, b = checkouts + run_hook(ups_payload(b), hook_env) + git(a, "worktree", "remove", "--force", str(b)) + shutil.rmtree(b, ignore_errors=True) + (a / "app.py").write_text(VULN_PY) + m = _stop(a, hook_env) + assert m["files_reviewed"] == 1 and m["bl_origin"] == 3 + + +def test_prompt_in_a_folder_that_is_not_a_repo_keeps_the_untracked_snapshot( + hook_env, checkouts): + a, _ = checkouts + ws = a.parent + (a / "notes.py").write_text("n = 0\n") # untracked since before the session + run_hook(ups_payload(a), hook_env) + (a / "first.py").write_text("x = 1\n") + assert _stop(a, hook_env)["bl_origin"] == 0 + run_hook(ups_payload(ws), hook_env) + (a / "second.py").write_text("y = 2\n") + run_hook(edit_payload(ws, a / "second.py"), hook_env) + m = _stop(ws, hook_env) + # The earlier baseline is kept, so the first turn's file is reviewed + # again. notes.py is not: the snapshot that goes with it is kept too. + assert m["files_reviewed"] == 2 and m["bl_origin"] == 10 + # The next prompt in the repo captures a fresh baseline there. + run_hook(ups_payload(a), hook_env) + (a / "third.py").write_text("z = 3\n") + m = _stop(a, hook_env) + assert m["files_reviewed"] == 1 and m["bl_origin"] == 0 + + +def test_baseline_taken_after_a_finding_belongs_to_the_reviewed_checkout( + hook_env, checkouts, stub_api): + a, b = checkouts + run_hook(ups_payload(a), hook_env) + (b / "new.py").write_text(VULN_PY) + stub_api.vulns = [dict(STUB_VULN, filePath="new.py")] + assert _stop(b, hook_env)["bl_origin"] == 1 + st = _state(hook_env) + assert os.path.samefile(st["baseline_root"], b) + # b's HEAD at the prompt, not a's. + assert st["head_at_capture"] == git(b, "rev-parse", "HEAD").strip() + # Same turn, next Stop: only what changed since the finding. + stub_api.vulns = [] + (b / "newer.py").write_text("v = 1\n") + m = _stop(b, hook_env) + assert m["files_reviewed"] == 1 and m["bl_origin"] == 0 + + +def test_baseline_taken_after_a_finding_keeps_the_turns_first_commit( + hook_env, checkouts, stub_api): + a, _ = checkouts + head = git(a, "rev-parse", "HEAD").strip() + run_hook(ups_payload(a), hook_env) + (a / "app.py").write_text(VULN_PY) + git(a, "commit", "-q", "-am", "this turn") + stub_api.vulns = [dict(STUB_VULN, filePath="app.py")] + assert _stop(a, hook_env)["bl_origin"] == 0 + assert _state(hook_env)["head_at_capture"] == head + # A fix folded into the commit is still inside the turn's range. + (a / "app.py").write_text(VULN_PY + "x = 1\n") + git(a, "commit", "-q", "-a", "--amend", "-m", "this turn") + assert _stop(a, hook_env)["files_reviewed"] == 1 + + +def test_first_baseline_taken_after_a_finding_records_its_checkout( + hook_env, checkouts, stub_api): + a, b = checkouts + ws = a.parent + run_hook(ups_payload(ws), hook_env) + (a / "new.py").write_text(VULN_PY) + run_hook(edit_payload(ws, a / "new.py"), hook_env) + stub_api.vulns = [dict(STUB_VULN, filePath="new.py")] + assert _stop(ws, hook_env)["bl_origin"] == 4 + assert os.path.samefile(_state(hook_env)["baseline_root"], a) + stub_api.vulns = [] + assert _stop(b, hook_env)["bl_origin"] == 1 + + +def test_no_baseline_at_all(hook_env, checkouts): + a, _ = checkouts + ws = a.parent + run_hook(ups_payload(ws), hook_env) + (a / "new.py").write_text("v = 1\n") + run_hook(edit_payload(ws, a / "new.py"), hook_env) + m = _stop(ws, hook_env) + assert m["files_reviewed"] == 1 and m["bl_origin"] == 4 + + +def test_prompt_subdirectory_removed_during_the_turn(hook_env, checkouts): + a, _ = checkouts + (a / "pkg").mkdir() + run_hook(ups_payload(a / "pkg"), hook_env) + (a / "pkg").rmdir() + (a / "app.py").write_text(VULN_PY) + assert _stop(a, hook_env)["bl_origin"] == 0 + + +def test_nested_worktree_removed_during_the_turn(hook_env, checkouts): + a, _ = checkouts + nested = a / ".claude" / "worktrees" / "wt" + git(a, "worktree", "add", "-q", "-b", "nested", str(nested)) + run_hook(ups_payload(nested), hook_env) + git(a, "worktree", "remove", "--force", str(nested)) + (a / "app.py").write_text(VULN_PY) + assert _stop(a, hook_env)["bl_origin"] == 3 diff --git a/plugins/security-guidance/tests/test_stop_diff_memory.py b/plugins/security-guidance/tests/test_stop_diff_memory.py new file mode 100644 index 00000000..31a524f9 --- /dev/null +++ b/plugins/security-guidance/tests/test_stop_diff_memory.py @@ -0,0 +1,349 @@ +"""The Stop review reads `git diff` output without holding all of it: files it +would drop come back as a header line, and one file's diff is cut at a cap.""" +import random +import subprocess +import sys +import tempfile +import time +import tracemalloc + +import pytest + +from conftest import ( + GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload, + ups_payload, +) + +import gitutil + + +@pytest.fixture(autouse=True) +def _fresh_read_state(): + yield + gitutil._unparsed_diff_headers.clear() + gitutil._diff_read.update(bytes=0, cut_files=0, cut_bytes=0, timeouts=0) + + +def _rewrite(path, removed, added): + return (f"diff --git a/{path} b/{path}\n" + "index 1111111..2222222 100644\n" + f"--- a/{path}\n+++ b/{path}\n" + f"@@ -1,{len(removed)} +1,{len(added)} @@\n" + + "".join(f"-{ln}\n" for ln in removed) + + "".join(f"+{ln}\n" for ln in added)) + + +@pytest.fixture +def git_env(tmp_path, monkeypatch): + d = tmp_path / "tmproot" + d.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(d)) + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + + +def _section(path, body_lines, old=None): + return (f"diff --git a/{old or path} b/{path}\n" + "index 1111111..2222222 100644\n" + f"--- a/{old or path}\n+++ b/{path}\n" + f"@@ -1,2 +1,{len(body_lines)} @@\n" + + "".join(f"+{ln}\n" for ln in body_lines)) + + +def _keep(raw, chunk_sizes): + keeper = gitutil._DiffKeeper() + pos = 0 + while pos < len(raw): + n = next(chunk_sizes) + keeper.feed(raw[pos:pos + n]) + pos += n + return keeper, keeper.result() + + +def _sizes(*cycle): + while True: + yield from cycle + + +MIXED = ( + _section("app.py", ["import os", "os.system(cmd)"]) + + _section("notes.txt", ["plain text", "diff --git a/fake.py b/fake.py is only text here"]) + + _section("web/café.js", ["eval(x)"]) + + 'diff --git "a/we\\"ird.py" "b/we\\"ird.py"\n--- "a/we\\"ird.py"\n+++ "b/we\\"ird.py"\n@@ -1 +1 @@\n+x = 1\n' + + "diff --git nonsense header\n@@ -1 +1 @@\n+y\n" + + _section("new_name.py", ["z = 2"], old="old_name.txt") + + _section("data.csv", ["1,2,3"] * 50) + + _section("last.sh", ["rm -rf $1"]) +).encode() + + +class TestDiffKeeper: + @pytest.mark.parametrize("seed", range(40)) + def test_same_files_as_reading_it_whole_at_any_chunking(self, seed): + rng = random.Random(seed) + sizes = iter(lambda: rng.choice([1, 2, 3, 7, 11, 12, 13, 64, 500]), None) + gitutil._unparsed_diff_headers.clear() + want = gitutil.parse_diff_into_files(MIXED.decode()) + want_unparsed = set(gitutil._unparsed_diff_headers) + gitutil._unparsed_diff_headers.clear() + keeper, kept = _keep(MIXED, sizes) + assert gitutil.parse_diff_into_files(kept.decode()) == want + assert gitutil._unparsed_diff_headers == want_unparsed + assert [p for p, _ in want] == ["app.py", "web/café.js", 'we"ird.py', "new_name.py", "last.sh"] + assert keeper.seen == len(MIXED) + assert keeper.cut_files == 0 + + def test_dropped_file_keeps_its_header_line_only(self): + _, kept = _keep(MIXED, _sizes(4096)) + text = kept.decode() + assert "diff --git a/notes.txt b/notes.txt\n" in text + assert "plain text" not in text and "1,2,3" not in text + assert len(kept) < len(MIXED) + + def test_untouched_when_every_file_is_reviewable_and_small(self): + raw = (_section("a.py", ["x"]) + _section("b.js", ["y"])).encode() + assert _keep(raw, _sizes(5))[1] == raw + + @pytest.mark.parametrize("chunk", [1, 17, 4096]) + def test_large_file_is_cut_and_the_next_file_survives(self, monkeypatch, chunk): + monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300) + big = _section("big.json", ["k" * 37] * 100) + raw = (big + _section("after.py", ["import os"])).encode() + keeper, kept = _keep(raw, _sizes(chunk)) + files = dict(gitutil.parse_diff_into_files(kept.decode())) + assert set(files) == {"big.json", "after.py"} + assert files["after.py"] == dict(gitutil.parse_diff_into_files(raw.decode()))["after.py"] + # The start of the section, then as much again of its added lines. + assert 300 < len(files["big.json"]) <= 2 * 300 + len(gitutil._CUT_MARK) + 2 + assert keeper.cut_files == 1 + assert keeper.cut_bytes == len(big) - 2 * 300 + + def test_cut_file_says_so_on_its_last_line(self, monkeypatch): + monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300) + raw = (_section("big.json", ["k" * 37] * 100) + _section("after.py", ["x"])).encode() + _, kept = _keep(raw, _sizes(64)) + files = dict(gitutil.parse_diff_into_files(kept.decode())) + assert files["big.json"].endswith(gitutil._CUT_MARK.decode()) + assert "cut by security-guidance" not in files["after.py"] + assert kept.count(gitutil._CUT_MARK) == 1 + + @pytest.mark.parametrize("chunk", [1, 23, 4096]) + def test_rewrite_past_the_cap_keeps_its_added_lines(self, monkeypatch, chunk): + monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 400) + raw = (_rewrite("views.py", ["old line %03d" % i for i in range(200)], + ["os.system(cmd)"] + ["new line %03d" % i for i in range(200)]) + + _section("after.py", ["x"])).encode() + keeper, kept = _keep(raw, _sizes(chunk)) + body = dict(gitutil.parse_diff_into_files(kept.decode()))["views.py"] + assert "+os.system(cmd)\n" in body + assert "-old line 199" not in body + past = body[400:] + assert all(ln.startswith(("+", "\\")) for ln in past.splitlines()[1:]) + assert len(body) <= 2 * 400 + len(gitutil._CUT_MARK) + 2 + assert keeper.cut_files == 1 + + def test_dropped_large_file_is_not_counted_as_cut(self, monkeypatch): + monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300) + raw = (_section("big.log", ["k" * 37] * 100) + _section("after.py", ["x"])).encode() + keeper, kept = _keep(raw, _sizes(64)) + assert keeper.cut_files == 0 and keeper.cut_bytes == 0 + assert [p for p, _ in gitutil.parse_diff_into_files(kept.decode())] == ["after.py"] + + def test_renamed_from_a_secret_shaped_name_keeps_its_header_only(self): + raw = (_section("config.py", ["TOKEN = 'abc'"], old=".env") + + _section("after.py", ["x"])).encode() + want = gitutil.parse_diff_into_files(raw.decode()) + _, kept = _keep(raw, _sizes(64)) + assert gitutil.parse_diff_into_files(kept.decode()) == want + assert [p for p, _ in want] == ["after.py"] + assert b"TOKEN" not in kept + + def test_past_the_total_later_files_keep_less_and_less(self, monkeypatch): + monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 2000) + monkeypatch.setattr(gitutil, "MAX_KEPT_DIFF_BYTES", 3000) + monkeypatch.setattr(gitutil, "_LATE_FILE_DIFF_BYTES", 200) + monkeypatch.setattr(gitutil, "_LAST_FILE_DIFF_BYTES", 120) + raw = "".join(_section(f"f{i}.py", ["v" * 30] * 400) for i in range(40)).encode() + keeper, kept = _keep(raw, _sizes(333)) + files = gitutil.parse_diff_into_files(kept.decode()) + assert [p for p, _ in files] == [f"f{i}.py" for i in range(40)] + sizes = [len(body) for _, body in files] + mark = len(gitutil._CUT_MARK) + 2 + assert sizes[0] > 2000 and sizes[0] <= 4000 + mark + assert 200 < sizes[5] <= 400 + mark + assert sizes[-1] <= 120 + mark + assert sizes[0] > sizes[5] > sizes[-1] + assert keeper.cut_files == 40 + # Everything not kept is counted; a cut may add a newline or two. + from_git = len(kept) - 40 * len(gitutil._CUT_MARK) + assert from_git - 80 <= len(raw) - keeper.cut_bytes <= from_git + + def test_output_cut_inside_a_line_ends_with_a_newline(self, monkeypatch): + monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300) + raw = _rewrite("big.json", ["k" * 37] * 100, []).encode() + keeper, kept = _keep(raw, _sizes(64)) + assert kept == raw[:300] + b"\n" + gitutil._CUT_MARK + assert keeper.cut_bytes == len(raw) - 300 + both = kept + _section("next.py", ["x"]).encode() + assert [p for p, _ in gitutil.parse_diff_into_files(both.decode())] == ["big.json", "next.py"] + + def test_empty_output(self): + keeper, kept = _keep(b"", _sizes(1)) + assert kept == b"" and keeper.seen == 0 + + +class TestRunDiffBounded: + def test_returns_what_run_would(self): + code = ("import sys; sys.stdout.buffer.write(b'diff --git a/a.py b/a.py\\n@@ -1 +1 @@\\n+x\\n'); " + "sys.stderr.write('warn'); sys.exit(3)") + r = gitutil._run_diff_bounded([sys.executable, "-c", code], 30) + assert r.returncode == 3 + assert r.stdout == b"diff --git a/a.py b/a.py\n@@ -1 +1 @@\n+x\n" + assert r.stderr == b"warn" + + def test_timeout_kills_and_raises(self): + code = "import sys, time; sys.stdout.write('x' * 100000); sys.stdout.flush(); time.sleep(60)" + before = gitutil._diff_read["timeouts"] + with pytest.raises(subprocess.TimeoutExpired): + gitutil._run_diff_bounded([sys.executable, "-c", code], 0.5) + assert gitutil._diff_read["timeouts"] == before + 1 + + def test_timeout_holds_while_another_process_keeps_the_pipe_open(self): + # What a `git diff` that started a fetch looks like: the program is + # gone, something it started still holds its stdout. + code = ("import subprocess, sys; " + "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(8)']); " + "sys.stdout.write('x'); sys.stdout.flush()") + before = gitutil._diff_read["timeouts"] + t0 = time.monotonic() + with pytest.raises(subprocess.TimeoutExpired): + gitutil._run_diff_bounded([sys.executable, "-c", code], 1) + assert time.monotonic() - t0 < 5 + assert gitutil._diff_read["timeouts"] == before + 1 + + def test_a_timed_out_read_still_reports_its_size(self): + code = "import sys, time; sys.stdout.write('x' * 300000); sys.stdout.flush(); time.sleep(60)" + with pytest.raises(subprocess.TimeoutExpired): + gitutil._run_diff_bounded([sys.executable, "-c", code], 1) + assert gitutil._diff_read["bytes"] >= 200000 + + def test_a_read_that_breaks_is_an_error_not_a_short_diff(self, monkeypatch): + def broken(self, data): + raise MemoryError("no room") + monkeypatch.setattr(gitutil._DiffKeeper, "feed", broken) + code = "import sys; sys.stdout.write('diff --git a/a.py b/a.py\\n' * 50000)" + t0 = time.monotonic() + with pytest.raises(OSError): + gitutil._run_diff_bounded([sys.executable, "-c", code], 30) + assert time.monotonic() - t0 < 10 + + def test_no_thread_to_read_with_is_an_error(self, monkeypatch): + def refuse(self): + raise RuntimeError("can't start new thread") + monkeypatch.setattr(gitutil.threading.Thread, "start", refuse) + with pytest.raises(OSError): + gitutil._run_diff_bounded([sys.executable, "-c", "print('x')"], 30) + + def test_missing_program_raises_like_run(self): + with pytest.raises(FileNotFoundError): + gitutil._run_diff_bounded(["sg-no-such-program"], 5) + + +class TestGetGitDiff: + def test_large_data_file_is_not_held(self, tmp_path, git_env): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + (repo / "app.py").write_text(VULN_PY) + line = "generated text line that is about eighty bytes long once the number is on it %07d\n" + (repo / "gen.txt").write_text("".join(line % i for i in range(250000))) + paths = [str(repo / "app.py"), str(repo / "gen.txt")] + tracemalloc.start() + try: + diff = gitutil.get_git_diff(str(repo), "HEAD", paths=paths, untracked_paths=["gen.txt"]) + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + assert [p for p, _ in gitutil.parse_diff_into_files(diff)] == ["app.py"] + assert "diff --git a/gen.txt b/gen.txt\n" in diff and "generated text" not in diff + assert gitutil._diff_read["bytes"] > 20 * 1024 * 1024 + assert gitutil._diff_read["cut_files"] == 0 + # Reading it whole took several times the 20 MB of output. + assert peak < 8 * 1024 * 1024 + + def test_timeout_is_none(self, tmp_path, git_env, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + + def slow(cmd, timeout, **kwargs): + raise subprocess.TimeoutExpired(cmd, timeout) + + monkeypatch.setattr(gitutil, "_run_diff_bounded", slow) + assert gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "app.py")], + untracked_paths=[]) is None + + @pytest.mark.parametrize("value, want", [ + ("", 4 * 1024 * 1024), ("junk", 4 * 1024 * 1024), ("0", 4 * 1024 * 1024), + ("-5", 4 * 1024 * 1024), ("1000", 256 * 1024), ("1000000", 1000000)]) + def test_cap_setting_cannot_break_the_read(self, monkeypatch, value, want): + monkeypatch.setenv("SG_MAX_FILE_DIFF_BYTES", value) + assert gitutil._file_diff_cap() == want + + def test_rewritten_large_file_still_shows_what_is_new(self, tmp_path, git_env): + body = "".join(f"def handler_{i}(request):\n return render(request, 'page_{i}.html')\n" + for i in range(18000)) + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "views.py").write_bytes(body.replace("\n", "\r\n").encode()) + subprocess.run(["git", "add", "-A"], cwd=repo, check=True) + subprocess.run(["git", "commit", "-q", "-m", "views"], cwd=repo, check=True) + assert (repo / "views.py").stat().st_size > 1200000 + (repo / "views.py").write_bytes(("import os\nos.system(request.GET['cmd'])\n" + body).encode()) + diff = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "views.py")], untracked_paths=[]) + assert gitutil._diff_read["cut_files"] == 0 + files = gitutil.filter_preexisting_from_diff( + gitutil.parse_diff_into_files(diff), str(repo), "HEAD") + assert "+os.system(request.GET['cmd'])" in files[0][1][:2000] + + def test_rewrite_past_the_cap_still_shows_what_is_new(self, tmp_path, git_env, monkeypatch): + monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 200000) + body = "".join(f"def handler_{i}(request):\n return render(request, 'page_{i}.html')\n" + for i in range(18000)) + repo = make_repo(tmp_path / "repo", {"views.py": body.replace("\n", "\r\n")}) + (repo / "views.py").write_bytes(("import os\nos.system(request.GET['cmd'])\n" + body).encode()) + diff = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "views.py")], untracked_paths=[]) + assert gitutil._diff_read["cut_files"] == 1 + assert len(diff) < 2 * 200000 + 1000 + files = gitutil.filter_preexisting_from_diff( + gitutil.parse_diff_into_files(diff), str(repo), "HEAD") + assert "+os.system(request.GET['cmd'])" in files[0][1][:2000] + + def test_failed_diff_is_still_none(self, tmp_path, git_env): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + assert gitutil.get_git_diff(str(repo), "0" * 40, paths=[str(repo / "app.py")], + untracked_paths=[]) is None + + +class TestStopHook: + def test_reports_what_it_read_and_reviews_the_source(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + (repo / "gen.txt").write_text("some generated text\n" * 150000) + (repo / "big.json").write_text('"k": "some generated value",\n' * 20000) + env = {**hook_env, "SG_MAX_FILE_DIFF_BYTES": "1000"} + rc, so, se = run_hook(stop_payload(repo), env) + m = metrics_of(so) + assert not m.get("skipped"), m + assert m["files_reviewed"] == 2 + assert m["diff_mb"] == 3 + assert m["diff_cut_files"] == 1 + # 256 KiB from the start and as much again of added lines were read; + # the prompt took 80,000 bytes of that. + assert m["diff_truncated"] > 20000 * 29 - 80000 - 1000 + assert "diff_timeout" not in m + assert stub_api.calls + + def test_small_turn_reports_nothing_new(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["files_reviewed"] == 1 + assert not {"diff_mb", "diff_cut_files", "diff_timeout"} & set(m) diff --git a/plugins/security-guidance/tests/test_stop_scope_metrics.py b/plugins/security-guidance/tests/test_stop_scope_metrics.py new file mode 100644 index 00000000..c65103b6 --- /dev/null +++ b/plugins/security-guidance/tests/test_stop_scope_metrics.py @@ -0,0 +1,181 @@ +"""Stop rows carry one count-only number, `review_scope`, saying how the +reviewed files relate to what the session's edit tools wrote and whether the +turn-start snapshot was a real one.""" +import os +import shutil + +import pytest + +from conftest import ( + STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, + ups_payload, +) + +import diffstate + +needs_sh = pytest.mark.skipif(os.name == "nt", reason="uses a /bin/sh git shim") + + +def _stop(repo, env): + return metrics_of(run_hook(stop_payload(repo), env)[1]) + + +def _turn(repo, env, edits=(), during=None): + run_hook(ups_payload(repo), env) + for path in edits: + run_hook(edit_payload(repo, path), env) + if during: + during() + return _stop(repo, env) + + +def _no_stash_env(tmp_path, hook_env): + """An env whose `git stash` fails, like a snapshot that could not be taken.""" + bindir = tmp_path / "bin" + bindir.mkdir() + shim = bindir / "git" + shim.write_text( + '#!/bin/sh\nfor a in "$@"; do [ "$a" = stash ] && exit 1; done\n' + f'exec "{shutil.which("git")}" "$@"\n') + shim.chmod(0o755) + return {**hook_env, "PATH": f"{bindir}{os.pathsep}{hook_env['PATH']}"} + + +class TestScope: + def test_edits_outside_repo_review_of_a_file_they_did_not_write(self, hook_env, workspace): + ws, repo = workspace + m = _turn(repo, hook_env, edits=[ws / "notes.md"], + during=lambda: (repo / "other.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 30001 + + def test_edit_inside_repo(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, edits=[repo / "app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 10000 + + def test_relative_edit_path_is_read_against_the_session_cwd(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, edits=["app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 10000 + + def test_mixed_edits_and_a_file_changed_by_other_means(self, hook_env, workspace): + ws, repo = workspace + + def during(): + (repo / "app.py").write_text(VULN_PY) + (repo / "gen.py").write_text(VULN_PY) + m = _turn(repo, hook_env, edits=[ws / "notes.md", repo / "app.py"], during=during) + assert m["files_reviewed"] == 2 and m["review_scope"] == 20001 + + def test_no_edit_tool_paths(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 1 + + def test_outside_only_turn_with_nothing_to_review(self, hook_env, workspace): + ws, repo = workspace + m = _turn(repo, hook_env, edits=[ws / "notes.md"]) + assert m["skipped"] is True and m["review_scope"] == 30000 + + def test_skipped_review_counts_over_the_review_set(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, during=lambda: (repo / "notes.txt").write_text("x\n")) + assert m["skipped"] is True and m["review_scope"] == 1 + + def test_second_review_of_the_same_turn_still_knows_the_edits(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, edits=[repo / "app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["review_scope"] == 10000 + m = _stop(repo, hook_env) # a rewake: no new prompt, same baseline + assert m["files_reviewed"] == 1 and m["review_scope"] == 10000 + # The next prompt starts a new count. + m = _turn(repo, hook_env, during=lambda: (repo / "gen.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 1 + + def test_no_key_outside_a_repo(self, hook_env, tmp_path): + plain = tmp_path / "plain" + plain.mkdir() + m = _turn(plain, hook_env, edits=[plain / "a.py"], + during=lambda: (plain / "a.py").write_text(VULN_PY)) + assert m["skipped"] is True and "review_scope" not in m + + def test_unreadable_path_does_not_stop_the_review(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, edits=[str(repo / "a\ud800b.py"), repo / "app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 + if os.name == "nt": + # Windows paths can hold a lone surrogate: it is one more file + # in the repo. + assert m["review_scope"] == 10000 + else: + assert "review_scope" not in m + + +class TestSnapshot: + def test_no_prompt_hook_means_no_snapshot(self, hook_env, workspace): + _, repo = workspace + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py"), hook_env) + m = _stop(repo, hook_env) + assert m["files_reviewed"] == 1 and m["review_scope"] == 310000 + + @needs_sh + def test_failed_snapshot_is_counted(self, hook_env, workspace, tmp_path): + ws, repo = workspace + (repo / "app.py").write_text(VULN_PY) # uncommitted work from before the turn + m = _turn(repo, _no_stash_env(tmp_path, hook_env), edits=[ws / "notes.md"]) + assert m["files_reviewed"] == 1 and m["review_scope"] == 130001 + # The next prompt takes a real snapshot and the flag is gone. + m = _turn(repo, hook_env, edits=[repo / "app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY + "# more\n")) + assert m["files_reviewed"] == 1 and m["review_scope"] == 10000 + + @needs_sh + def test_flag_follows_the_snapshot_taken_after_a_finding(self, hook_env, stub_api, + workspace, tmp_path): + _, repo = workspace + broken = _no_stash_env(tmp_path, hook_env) + stub_api.vulns = [STUB_VULN] + # Good snapshot at the prompt; the one taken after the finding fails. + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py"), hook_env) + m = _stop(repo, broken) + assert m["vulns_found"] == 1 and m["review_scope"] == 10000 + (repo / "app.py").write_text(VULN_PY + "# fix\n") + run_hook(edit_payload(repo, repo / "app.py"), hook_env) + m = _stop(repo, hook_env) + assert m["review_scope"] == 110000 + # That Stop took a real one again. + (repo / "app.py").write_text(VULN_PY + "# fix 2\n") + run_hook(edit_payload(repo, repo / "app.py"), hook_env) + m = _stop(repo, hook_env) + assert m["review_scope"] == 10000 + + +class TestCode: + def _code(self, root, cwd, touched, files, fail=0): + scope, inside = diffstate.touched_scope(root, cwd, touched) + return diffstate.review_scope_code(root, scope, inside, files, fail) + + def test_repo_at_the_filesystem_root(self): + root = os.path.abspath(os.sep) + assert self._code(root, root, [os.path.join(root, "x.py")], ["x.py", "y.py"]) == 10001 + + def test_names_that_only_start_like_a_parent_dir(self, tmp_path): + root = str(tmp_path) + assert self._code(root, root, [str(tmp_path / "..hidden.py")], ["..hidden.py"], 2) == 210000 + + def test_untouched_count_is_capped(self, tmp_path): + files = [f"f{i}.py" for i in range(12000)] + assert self._code(str(tmp_path), "", [], files) == 9999 + + def test_absolute_and_relative_file_names_count_the_same(self, tmp_path): + root = str(tmp_path) + touched = [str(tmp_path / "a.py")] + assert self._code(root, root, touched, ["a.py", "b.py"]) == 10001 + assert self._code(root, root, touched, [str(tmp_path / "a.py"), str(tmp_path / "b.py")]) == 10001 |
