diff options
| author | Claude <noreply@anthropic.com> | 2026-11-05 00:55:20 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-05 00:55:20 +0000 |
| commit | 94aad60c27bde35441c9b05c515f74fe67e10837 (patch) | |
| tree | b60b6d71987457d8b4f4d00daa562288f37d27ce /plugins/security-guidance/tests | |
| parent | fa4eb54397ee2faccb6940512a19c017cb1337f3 (diff) | |
Merged candidate for security-guidance 2.0.18 with platform tests (6999 update)mhegazy/sg2018batch
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins/security-guidance/tests')
25 files changed, 3126 insertions, 61 deletions
diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 464f4695..b0df08de 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -89,8 +89,10 @@ def workspace(tmp_path): class _Stub(http.server.BaseHTTPRequestHandler): def do_POST(self): n = int(self.headers.get("Content-Length") or 0) - if n: - self.rfile.read(n) + body = self.rfile.read(n).decode("utf-8", "replace") if n else "" + # Only the stub_api fixture keeps the request bodies. + if hasattr(self.server, "bodies"): + self.server.bodies.append(body) self.server.calls.append(self.path) if self.server.delay: time.sleep(self.server.delay) @@ -121,6 +123,7 @@ class _Stub(http.server.BaseHTTPRequestHandler): def stub_api(): srv = http.server.HTTPServer(("127.0.0.1", 0), _Stub) srv.calls = [] + srv.bodies = [] srv.status = 200 srv.delay = 0 srv.vulns = [] diff --git a/plugins/security-guidance/tests/test_add_failure_metric.py b/plugins/security-guidance/tests/test_add_failure_metric.py index 3a86a8ac..228b68b7 100644 --- a/plugins/security-guidance/tests/test_add_failure_metric.py +++ b/plugins/security-guidance/tests/test_add_failure_metric.py @@ -1,6 +1,11 @@ -"""A failed `git add --intent-to-add` leaves new files out of the Stop review's -diff. The review goes on as before; the Stop row says that it happened.""" +"""`git add --intent-to-add` puts new files in the Stop review's diff. A user +who cannot write the object store gets a retry with a private object directory; +a failure that stays leaves the new files for a later review, unless the turn's +tracked files were reviewed, and tells Claude which files were left out. The +Stop row says what happened.""" +import json import os +import shutil import subprocess import tempfile from types import SimpleNamespace @@ -8,11 +13,12 @@ from types import SimpleNamespace import pytest from conftest import ( - GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload, - ups_payload, + GIT_ENV, STUB_VULN, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, write_cli, ) import gitutil +import security_reminder_hook as hook def _cannot_write_read_only_dirs(): @@ -43,15 +49,16 @@ class TestObjectStoreNotWritable: def test_turn_that_only_adds_a_file(self, tmp_path, hook_env, stub_api, read_only_objects): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) read_only_objects(repo) + before = sorted(p for p in (repo / ".git" / "objects").rglob("*")) run_hook(ups_payload(repo), hook_env) (repo / "handlers.py").write_text(VULN_PY) m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) - assert m["skip_reason"] == 6, m - assert m["review_set_count"] == 1 - assert m["add_fail"] == 100001 - assert not stub_api.calls + assert m["files_reviewed"] == 1, m + assert m["add_fail"] == 400001 + assert stub_api.calls + assert sorted(p for p in (repo / ".git" / "objects").rglob("*")) == before - def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api, read_only_objects): + def test_tracked_edit_and_new_files(self, tmp_path, hook_env, stub_api, read_only_objects): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) read_only_objects(repo) run_hook(ups_payload(repo), hook_env) @@ -60,21 +67,247 @@ class TestObjectStoreNotWritable: (repo / "b.py").write_text("print('b')\n") m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) assert not m.get("skipped"), m - assert m["files_reviewed"] == 1 - assert m["add_fail"] == 100002 + assert m["files_reviewed"] == 3 + assert m["add_fail"] == 400002 + def test_linked_worktree_and_packed_repo(self, tmp_path, hook_env, stub_api, read_only_objects): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + git(repo, "repack", "-adq") + wt = tmp_path / "wt" + git(repo, "worktree", "add", "-q", "-b", "side", str(wt)) + read_only_objects(repo) + run_hook(ups_payload(wt), hook_env) + (wt / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(wt), hook_env)[1]) + assert m["files_reviewed"] == 1, m + assert m["add_fail"] == 400001 -class TestStopRow: - def test_other_git_error(self, tmp_path, hook_env, stub_api): - # git refuses --literal-pathspecs together with a user's icase setting. + def test_private_directory_is_gone_afterwards(self, tmp_path, monkeypatch, read_only_objects): + d = tmp_path / "tmproot" + d.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(d)) + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + read_only_objects(repo) + (repo / "new.py").write_text("print('new')\n") + out = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + gitutil._add_failed["code"] = 0 + assert "new.py" in out + assert not [p for p in d.rglob("*") if gitutil._TEMP_INDEX_PREFIX in p.name] + + +class TestPathspecSettings: + @pytest.mark.parametrize("name", ["GIT_ICASE_PATHSPECS", "GIT_GLOB_PATHSPECS"]) + def test_new_file_is_reviewed(self, tmp_path, hook_env, stub_api, name): + # git refuses --literal-pathspecs together with these two. repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) - env = {**hook_env, "GIT_ICASE_PATHSPECS": "1"} + env = {**hook_env, name: "1"} run_hook(ups_payload(repo), env) (repo / "handlers.py").write_text(VULN_PY) m = metrics_of(run_hook(stop_payload(repo), env)[1]) + assert m["files_reviewed"] == 1, m + assert "add_fail" not in m + + +@pytest.mark.skipif(os.name == "nt", reason="the stand-in git is a shell script") +def _env_refusing_add(tmp_path, hook_env, unless_set=None): + """`hook_env` with a git that fails `add -N`, unless `unless_set` is in its + environment.""" + d = tmp_path / "shim" + d.mkdir() + write_cli(d, "git", ( + "import os, subprocess, sys\n" + f"if '--intent-to-add' in sys.argv and not os.environ.get({unless_set!r}):\n" + " sys.stderr.write('fatal: refused\\n')\n" + " sys.exit(128)\n" + f"sys.exit(subprocess.call([{shutil.which('git')!r}, *sys.argv[1:]]))\n")) + return {**hook_env, "PATH": f"{d}{os.pathsep}{hook_env['PATH']}"} + + +class TestAddThatKeepsFailing: + def test_new_file_is_reviewed_once_git_works(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + bad = _env_refusing_add(tmp_path, hook_env) + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + run_hook(edit_payload(repo, str(repo / "handlers.py")), bad) + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) assert m["skip_reason"] == 6, m assert m["add_fail"] == 200001 + assert not stub_api.calls + + run_hook(ups_payload(repo), hook_env) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["files_reviewed"] == 1, m + assert stub_api.calls + + def test_file_no_edit_tool_wrote(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + bad = _env_refusing_add(tmp_path, hook_env) + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) + assert m["skip_reason"] == 6, m + + run_hook(ups_payload(repo), hook_env) + m = metrics_of(run_hook(stop_payload(repo), hook_env)[1]) + assert m["files_reviewed"] == 1, m + + def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + bad = _env_refusing_add(tmp_path, hook_env) + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + (repo / "a.py").write_text("print('a')\n") + m = metrics_of(run_hook(stop_payload(repo), bad)[1]) + assert m["files_reviewed"] == 1, m + assert m["add_fail"] == 200001 + + +class TestNoticeForLeftOutFiles: + """A failure that stays is said once per set of files: Claude is woken with + their names, and the Stop that wake ends in stays quiet.""" + + @pytest.fixture + def bad(self, tmp_path, hook_env): + return _env_refusing_add(tmp_path, hook_env) + + @pytest.fixture + def repo(self, tmp_path): + return make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + + def test_turn_that_only_adds_a_file(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "handlers.py").write_text(VULN_PY) + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"handlers.py"' in err + assert "Tell the user" in err + line = json.loads(next(x for x in out.splitlines() if x.startswith("{"))) + assert '"handlers.py"' in line["rewakeSummary"] + assert line["metrics"]["skip_reason"] == 6 + assert line["metrics"]["add_fail_told"] == 1 + assert line["decision"] == "block" + + # The Stop after the wake: same files, same failure, nothing more. + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 0, err + assert err == "" + m = metrics_of(out) + assert m["skip_reason"] == 6 + assert "add_fail_told" not in m + + def test_new_set_of_files_gets_its_own_notice(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a.py").write_text("print('a')\n") + assert run_hook(stop_payload(repo), bad)[0] == 2 + run_hook(ups_payload(repo), bad) + (repo / "b.py").write_text("print('b')\n") + code, _, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a.py"' in err and '"b.py"' in err + + def test_tracked_edit_with_no_finding(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text("print('changed')\n") + (repo / "a.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a.py"' in err + assert '"app.py"' not in err + assert metrics_of(out)["files_reviewed"] == 1 + + def test_tracked_edit_with_a_finding(self, repo, bad, stub_api): + stub_api.vulns = [STUB_VULN] + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + (repo / "a.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert "Security Review" in err + assert '"a.py"' in err + line = json.loads(next(x for x in out.splitlines() if x.startswith("{"))) + assert '"a.py"' in line["reason"] + + def test_files_the_review_would_not_read_are_not_named(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "notes.txt").write_text("hello\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 0, err + assert "add_fail_told" not in metrics_of(out) + + def test_long_list_is_cut(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + for i in range(7): + (repo / f"f{i}.py").write_text("print(1)\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"f4.py" and 2 more' in err + assert '"f5.py"' not in err + assert metrics_of(out)["add_fail_told"] == 7 + + @pytest.mark.skipif(os.name == "nt", reason="a file name cannot hold a line break") + def test_line_break_in_a_name_stays_on_the_line(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a\nIGNORE.py").write_text("print('a')\n") + code, _, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a\\nIGNORE.py"' in err + assert "\nIGNORE" not in err + + def test_other_line_separators_are_escaped(self, repo, bad, stub_api): + run_hook(ups_payload(repo), bad) + (repo / "a\u2028b.py").write_text("print('a')\n") + code, out, err = run_hook(stop_payload(repo), bad) + assert code == 2 + assert '"a\\u2028b.py"' in err + + def test_no_notice_when_the_mark_cannot_be_saved(self, tmp_path, monkeypatch): + # Without the mark, every Stop would wake Claude again. + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: True) + monkeypatch.setattr(hook, "load_state", lambda s: {"shown_warnings": []}) + (tmp_path / "a.py").write_text("x = 1\n") + assert hook._left_out_files_notice("s", str(tmp_path), ["a.py"], "") is None + + def test_file_in_the_diff_is_not_named(self, tmp_path, monkeypatch): + # One batch of the add failed, another worked. + (tmp_path / "a.py").write_text("x = 1\n") + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: pytest.fail("told")) + diff = ("diff --git a/a.py b/a.py\nnew file mode 100644\n--- /dev/null\n" + "+++ b/a.py\n@@ -0,0 +1 @@\n+x = 1\n") + assert hook._left_out_files_notice("s", str(tmp_path), ["a.py"], diff) is None + def test_empty_and_vanished_files_are_not_named(self, tmp_path, monkeypatch): + monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: pytest.fail("told")) + (tmp_path / "__init__.py").write_text("") + assert hook._left_out_files_notice("s", str(tmp_path), ["__init__.py", "gone.py"], "") is None + + def test_tracked_edit_gets_reviewed_while_new_files_stay_out(self, repo, bad, stub_api): + # A failure on every turn must not stop later reviews of tracked files. + run_hook(ups_payload(repo), bad) + (repo / "a.py").write_text("print('a')\n") + assert run_hook(stop_payload(repo), bad)[0] == 2 + run_hook(ups_payload(repo), bad) + (repo / "app.py").write_text(VULN_PY) + code, out, _ = run_hook(stop_payload(repo), bad) + assert code == 0 + assert metrics_of(out)["files_reviewed"] == 1 + assert stub_api.calls + + def test_retry_that_works_says_nothing(self, repo, tmp_path, hook_env, stub_api): + env = _env_refusing_add(tmp_path, hook_env, unless_set="GIT_OBJECT_DIRECTORY") + run_hook(ups_payload(repo), env) + (repo / "handlers.py").write_text(VULN_PY) + code, out, err = run_hook(stop_payload(repo), env) + assert code == 0, err + m = metrics_of(out) + assert m["add_fail"] == 400001 + assert "add_fail_told" not in m + + +class TestStopRow: def test_add_that_works_reports_nothing(self, tmp_path, hook_env, stub_api): repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) run_hook(ups_payload(repo), hook_env) @@ -122,13 +355,26 @@ class TestGetGitDiff: untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 200001 - def test_timeout_counts_and_still_gives_no_diff(self, repo, monkeypatch): + def test_timeout_counts_and_keeps_the_tracked_diff(self, repo, monkeypatch): self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10)) - assert gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], - untracked_paths=["new.py"]) is None - assert gitutil._add_failed["code"] == 300001 + (repo / "app.py").write_text("print('edited')\n") + out = gitutil.get_git_diff(str(repo), "HEAD", + paths=[str(repo / "new.py"), str(repo / "app.py")], + untracked_paths=["new.py"]) + assert "app.py" in out + assert "new.py" not in out + assert gitutil._add_failed == {"code": 300001, "left_out": True} - def test_object_store_refusal(self, repo, monkeypatch): + def test_a_fallback_diff_that_works_clears_left_out(self, repo, monkeypatch): + self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10)) + gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + monkeypatch.undo() + assert "new.py" in gitutil.get_git_diff( + str(repo), "HEAD", paths=[str(repo / "new.py")], untracked_paths=["new.py"]) + assert gitutil._add_failed == {"code": 300001, "left_out": False} + + def test_object_store_refusal_on_both_tries(self, repo, monkeypatch): self._adds_fail_with(monkeypatch, [SimpleNamespace( returncode=128, stderr=b"fatal: cannot create an empty blob in the object database")]) @@ -136,8 +382,92 @@ class TestGetGitDiff: untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 100001 + def test_retry_reads_the_repositorys_objects_and_writes_elsewhere(self, repo, monkeypatch): + seen = [] + real = gitutil._run_git_on_review_paths + + def run(args, paths, timeout, **kwargs): + if args[0] != "add": + return real(args, paths, timeout, **kwargs) + seen.append(kwargs["env"]) + return real(args, paths, timeout, **kwargs) if len(seen) > 1 else [ + SimpleNamespace(returncode=128, stderr=b"nope")] + + monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run) + out = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], + untracked_paths=["new.py"]) + assert "new.py" in out + assert "GIT_OBJECT_DIRECTORY" not in seen[0] + assert seen[1]["GIT_OBJECT_DIRECTORY"].endswith(".objects") + assert os.path.samefile(seen[1]["GIT_ALTERNATE_OBJECT_DIRECTORIES"], + repo / ".git" / "objects") + assert gitutil._add_failed["code"] == 400001 + + def test_retry_timeout_keeps_the_tracked_diff(self, repo, monkeypatch): + (repo / "app.py").write_text("print('changed')\n") + real = gitutil._run_git_on_review_paths + adds = [] + + def run(args, paths, timeout, **kwargs): + if args[0] != "add": + return real(args, paths, timeout, **kwargs) + adds.append(args) + if len(adds) > 1: + raise subprocess.TimeoutExpired("git", 10) + return [SimpleNamespace(returncode=128, stderr=b"fatal: nope")] + + monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run) + out = gitutil.get_git_diff(str(repo), "HEAD", untracked_paths=["new.py"]) + assert "app.py" in out + assert gitutil._add_failed["code"] == 200001 + def test_a_later_add_that_works_keeps_the_failure(self, repo, monkeypatch): gitutil._add_failed["code"] = 300001 gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")], untracked_paths=["new.py"]) assert gitutil._add_failed["code"] == 300001 + + +class TestLeftovers: + def _private_dir(self, parent, name): + d = parent / name + (d / "e6").mkdir(parents=True) + blob = d / "e6" / "9de29" + blob.write_bytes(b"x") + blob.chmod(0o444) + return d + + def test_removed_with_its_copy(self, tmp_path): + copy = tmp_path / "security_hook_idx_pid1_abcdefgh" + copy.write_bytes(b"i") + self._private_dir(tmp_path, copy.name + ".objects") + gitutil._remove_copy(str(copy)) + assert not list(tmp_path.iterdir()) + + @pytest.mark.skipif(os.name == "nt", reason="no pid check on Windows") + def test_killed_hooks_directory_is_swept(self, tmp_path): + p = subprocess.Popen(["git", "--version"], stdout=subprocess.DEVNULL) + p.wait() + self._private_dir(tmp_path, f"security_hook_idx_pid{p.pid}_abcdefgh.objects") + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert not list(tmp_path.iterdir()) + + def test_live_hooks_directory_stays(self, tmp_path): + self._private_dir(tmp_path, f"security_hook_idx_pid{os.getpid()}_abcdefgh.objects") + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert list(tmp_path.iterdir()) + + def test_other_directories_stay(self, tmp_path): + (tmp_path / "security_hook_idx_pid1_abcdefgh.other").mkdir() + gitutil._sweep_stale_indexes(str(tmp_path), None) + assert list(tmp_path.iterdir()) + + @pytest.mark.skipif(os.name == "nt", reason="needs symlinks") + def test_link_at_the_private_directory_is_not_followed(self, tmp_path): + victim = tmp_path / "victim" + victim.mkdir() + (victim / "keep").write_text("x") + copy = tmp_path / "security_hook_idx_pid1_abcdefgh" + (tmp_path / (copy.name + ".objects")).symlink_to(victim) + gitutil._remove_copy(str(copy)) + assert (victim / "keep").exists() diff --git a/plugins/security-guidance/tests/test_agentic_auth_stop.py b/plugins/security-guidance/tests/test_agentic_auth_stop.py new file mode 100644 index 00000000..a2108cfc --- /dev/null +++ b/plugins/security-guidance/tests/test_agentic_auth_stop.py @@ -0,0 +1,148 @@ +"""The agentic reviewer stops as soon as its credentials are refused, instead +of waiting for the inner CLI to give up, and leaves every other run alone.""" +import os +import subprocess +import sys +import types + +import pytest + +import llm +from conftest import write_cli + + +class _Assistant: + def __init__(self, error=None): + self.content, self.error = [], error + + +class _System: + subtype = "api_retry" + + def __init__(self, status): + self.data = {"error_status": status} + + +@pytest.fixture +def sdk(monkeypatch, tmp_path): + """Replays `script.messages`, then a clean result, and counts what the + review read of them.""" + script = types.SimpleNamespace(messages=[], read=0) + + class ClaudeAgentOptions: + def __init__(self, **kwargs): + self.kwargs = kwargs + + class ResultMessage: + subtype, usage, total_cost_usd = "success", {}, 0.0 + structured_output = {"findings": []} + + async def query(prompt, options): + for m in script.messages: + script.read += 1 + yield m + yield ResultMessage() + + mod = types.ModuleType("claude_agent_sdk") + mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query + mod.AssistantMessage = _Assistant + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + monkeypatch.delenv("CLAUDE_CODE_REMOTE", raising=False) + return script + + +def _review(repo): + return llm.agentic_review(str(repo), [("a.py", "+x = 1\n")], ["a.py"])[2] + + +class TestStopsOnRefusedCredentials: + def test_first_auth_failure_ends_the_review(self, sdk, tmp_path): + sdk.messages = [_Assistant(error="authentication_failed") for _ in range(50)] + m = _review(tmp_path) + assert sdk.read == 1 + assert m["agentic_fallback"] == "investigate:_ReviewerAuthFailed" + + def test_repeated_401_retries_end_the_review(self, sdk, tmp_path): + sdk.messages = [_System(401) for _ in range(10)] + m = _review(tmp_path) + assert sdk.read == llm._AGENTIC_MAX_401_RETRIES + assert m["agentic_fallback"] == "investigate:_ReviewerAuthFailed" + + +class TestLeavesOtherRunsAlone: + def test_a_remote_session_rides_out_401_retries(self, sdk, tmp_path, monkeypatch): + monkeypatch.setenv("CLAUDE_CODE_REMOTE", "true") + sdk.messages = [_System(401) for _ in range(10)] + assert "agentic_fallback" not in _review(tmp_path) + + def test_a_login_renewed_after_one_401_goes_on(self, sdk, tmp_path): + sdk.messages = [_System(401), _Assistant()] + assert "agentic_fallback" not in _review(tmp_path) + + def test_401s_that_are_not_in_a_row_do_not_add_up(self, sdk, tmp_path): + sdk.messages = [_System(401), _System(401), _Assistant()] * 3 + assert "agentic_fallback" not in _review(tmp_path) + + def test_other_retries_do_not_count(self, sdk, tmp_path): + sdk.messages = [_System(s) for s in (529, 429, None, 500, 529, 529)] + assert "agentic_fallback" not in _review(tmp_path) + + def test_other_assistant_errors_do_not_stop_it(self, sdk, tmp_path): + sdk.messages = [_Assistant(error="rate_limit"), _Assistant(error="server_error")] + assert "agentic_fallback" not in _review(tmp_path) + + def test_a_message_without_the_field_is_read_as_before(self, sdk, tmp_path): + class Old: + content = [] + sys.modules["claude_agent_sdk"].AssistantMessage = Old + sdk.messages = [Old()] + assert "agentic_fallback" not in _review(tmp_path) + + +_REFUSED_CLI = """ +import json, os, sys, time +open(os.environ["SG_TEST_PID_FILE"], "w").write(str(os.getpid())) +def send(m): + sys.stdout.write(json.dumps(m) + chr(10)); sys.stdout.flush() +for line in sys.stdin: + m = json.loads(line) + if m.get("type") == "control_request": + send({"type": "control_response", "response": {"subtype": "success", + "request_id": m["request_id"], "response": {}}}) + elif m.get("type") == "user": + for _ in range(500): + send({"type": "assistant", "error": "authentication_failed", "message": { + "role": "assistant", "model": "m", "content": [{"type": "text", "text": "401"}]}}) + time.sleep(0.02) + time.sleep(60) +""" + +_DRIVER = """ +import json, llm, os, sys, time +start = time.time() +metrics = llm.agentic_review(sys.argv[1], [("a.py", "+x = 1")], ["a.py"])[2] +pid = int(open(os.environ["SG_TEST_PID_FILE"]).read()) +try: + os.kill(pid, 0); alive = True +except OSError: + alive = False +print(json.dumps({"fallback": metrics.get("agentic_fallback"), "alive": alive}), flush=True) +os._exit(0) +""" + + +def test_real_sdk_closes_the_cli_quietly(tmp_path): + """Stops the real SDK's child, and prints no traceback for the hook's + stderr, which reaches the session.""" + pytest.importorskip("claude_agent_sdk") + env = {**os.environ, "SG_TEST_PID_FILE": str(tmp_path / "pid"), + "SG_AGENTIC_CLI_PATH": str(write_cli(tmp_path, "claude", _REFUSED_CLI)), + "SECURITY_WARNINGS_STATE_DIR": str(tmp_path / "state"), + "PYTHONPATH": str(os.path.dirname(llm.__file__))} + r = subprocess.run([sys.executable, "-c", _DRIVER, str(tmp_path)], env=env, + capture_output=True, text=True, timeout=60) + assert "Traceback" not in r.stderr, r.stderr + assert '"fallback": "investigate:_ReviewerAuthFailed"' in r.stdout, (r.stdout, r.stderr) + assert '"alive": false' in r.stdout, r.stdout diff --git a/plugins/security-guidance/tests/test_base_url.py b/plugins/security-guidance/tests/test_base_url.py new file mode 100644 index 00000000..26317549 --- /dev/null +++ b/plugins/security-guidance/tests/test_base_url.py @@ -0,0 +1,87 @@ +"""A blank ANTHROPIC_BASE_URL means the default endpoint, as it does for the +Anthropic SDK and Claude Code, for every call the plugin makes.""" +import io +import json + +import pytest + +import llm +import security_reminder_hook as hook + +DEFAULT = "https://api.anthropic.com" +BLANK = ["", " ", "\t\n"] + + +@pytest.mark.parametrize("value", BLANK) +def test_blank_is_the_default_endpoint(monkeypatch, value): + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + assert llm._anthropic_base_url() == DEFAULT + + +@pytest.mark.parametrize("value, expected", [ + ("https://gw.example.com/", "https://gw.example.com"), + (" https://gw.example.com/base/ \n", "https://gw.example.com/base"), +]) +def test_a_real_value_is_kept(monkeypatch, value, expected): + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + assert llm._anthropic_base_url() == expected + + +def test_a_stray_slash_is_not_taken_for_blank(monkeypatch): + # A broken gateway setting must not quietly send code to the default host. + monkeypatch.setenv("ANTHROPIC_BASE_URL", "/") + assert llm._anthropic_base_url() == "" + + +def test_unset_is_the_default_endpoint(monkeypatch): + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + assert llm._anthropic_base_url() == DEFAULT + + +class _Reply(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +@pytest.mark.parametrize("value", BLANK) +def test_requests_go_to_the_default_endpoint(monkeypatch, value): + urls = [] + + def urlopen(request, timeout): + urls.append(request.full_url) + return _Reply(json.dumps({ + "data": [{"id": "claude-opus-4-8"}], + "content": [{"type": "text", "text": "{}"}], + "usage": {}, + }).encode()) + + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + monkeypatch.setattr(llm, "ANTHROPIC_API_KEY", "key") + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + monkeypatch.setattr(llm, "_urlopen", urlopen) + assert llm._probe_anthropic() + llm._fetch_newest_opus() + llm._call_claude("prompt", {"type": "object"}, thinking_budget=0, model="claude-x") + assert urls == [f"{DEFAULT}/", f"{DEFAULT}/v1/models?limit=100", f"{DEFAULT}/v1/messages"] + + +@pytest.mark.parametrize("value", BLANK) +def test_blank_is_not_reported_as_a_gateway(monkeypatch, value): + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + assert llm.gateway_cfg() == 0 + + +@pytest.mark.parametrize("value", BLANK) +def test_blank_gets_no_gateway_hint(monkeypatch, value): + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", value) + assert "ANTHROPIC_CUSTOM_HEADERS" not in hook._review_failure_reason(401)[2] diff --git a/plugins/security-guidance/tests/test_baseline_snapshot.py b/plugins/security-guidance/tests/test_baseline_snapshot.py new file mode 100644 index 00000000..eaa0e5c2 --- /dev/null +++ b/plugins/security-guidance/tests/test_baseline_snapshot.py @@ -0,0 +1,257 @@ +"""The turn baseline is a commit of the tracked changes (#6854), where it used +to be `git stash create`. These pin the states where the two could differ.""" +import os +import subprocess + +import pytest + +import diffstate +import gitutil +from conftest import GIT_ENV, git, make_repo + + +@pytest.fixture(autouse=True) +def safe_env(monkeypatch): + for k, v in gitutil.git_config_env(gitutil.SAFE_GIT_CONFIG).items(): + monkeypatch.setenv(k, v) + + +def _tree(repo, sha): + return git(repo, "rev-parse", f"{sha}^{{tree}}").strip() + + +def _plain_stash_tree(repo): + """What `git stash create` would have produced, on the real index.""" + out = subprocess.run(["git", "stash", "create"], cwd=repo, capture_output=True, + text=True, env={**os.environ, **GIT_ENV}) + sha = out.stdout.strip() + return _tree(repo, sha) if sha else _tree(repo, "HEAD") + + +def _capture(repo): + sha = diffstate.capture_git_baseline(str(repo)) + return sha, diffstate.last_baseline_fail + + +def _repo(tmp_path, name="r"): + return make_repo(tmp_path / name, {"a.txt": "a\n", "b.txt": "b\n", "d/c.txt": "c\n"}) + + +def test_unstaged_and_staged_changes_are_in_the_snapshot(tmp_path): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("staged\n") + git(repo, "add", "a.txt") + (repo / "a.txt").write_text("staged\nunstaged\n") + (repo / "b.txt").write_text("also dirty\n") + sha, fail = _capture(repo) + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == "staged\nunstaged\n" + assert git(repo, "show", f"{sha}:b.txt") == "also dirty\n" + assert git(repo, "rev-parse", f"{sha}^").strip() == git(repo, "rev-parse", "HEAD").strip() + + +@pytest.mark.parametrize("state", [ + "unstaged", "staged", "staged-plus-unstaged", "worktree-delete", "staged-delete", + "staged-rename", "staged-new", "mode-change", "symlink", "untracked-only", "stale-stat", +]) +def test_same_tree_as_stash_create(tmp_path, state): + repo = _repo(tmp_path, state) + if state == "unstaged": + (repo / "a.txt").write_text("x\n") + elif state == "staged": + (repo / "a.txt").write_text("x\n"); git(repo, "add", "a.txt") + elif state == "staged-plus-unstaged": + (repo / "a.txt").write_text("x\n"); git(repo, "add", "a.txt") + (repo / "a.txt").write_text("y\n") + elif state == "worktree-delete": + (repo / "a.txt").unlink() + elif state == "staged-delete": + git(repo, "rm", "-q", "a.txt") + elif state == "staged-rename": + git(repo, "mv", "a.txt", "z.txt") + elif state == "staged-new": + (repo / "n.txt").write_text("n\n"); git(repo, "add", "n.txt") + elif state == "mode-change": + os.chmod(repo / "a.txt", 0o755) + elif state == "symlink": + (repo / "a.txt").unlink(); os.symlink("b.txt", repo / "a.txt") + elif state == "untracked-only": + (repo / "u.txt").write_text("u\n") + elif state == "stale-stat": + t = os.stat(repo / "a.txt").st_mtime + 2 + os.utime(repo / "a.txt", (t, t)) + # Capture FIRST: `git stash create` refreshes the real index, which would + # cancel the stale stat entry the last state is about. + sha, fail = _capture(repo) + assert fail == 0 + assert _tree(repo, sha) == _plain_stash_tree(repo) + + +def test_clean_tree_is_head(tmp_path): + repo = _repo(tmp_path) + assert _capture(repo) == (git(repo, "rev-parse", "HEAD").strip(), 0) + + +def test_conflicted_merge_snapshots_the_conflicted_files(tmp_path): + """`stash create` refused here and the whole conflicted file was then + reviewed as the turn's work. `add -u` resolves the conflict in the index + COPY, so the baseline holds what the work tree had, markers and all, and + the user's own index keeps its unmerged entries.""" + repo = _repo(tmp_path) + git(repo, "checkout", "-q", "-b", "other") + (repo / "a.txt").write_text("theirs\n"); git(repo, "commit", "-qam", "theirs") + git(repo, "checkout", "-q", "main") + (repo / "a.txt").write_text("ours\n"); git(repo, "commit", "-qam", "ours") + subprocess.run(["git", "merge", "other"], cwd=repo, capture_output=True, + env={**os.environ, **GIT_ENV}) + assert "UU" in git(repo, "status", "--porcelain") + conflicted = (repo / "a.txt").read_text() + sha, fail = _capture(repo) + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == conflicted + assert "UU" in git(repo, "status", "--porcelain") + assert git(repo, "ls-files", "-u") + + +def test_intent_to_add_file_is_snapshotted_with_its_content(tmp_path): + """`git add -N` marks a file to be committed without staging content. + `stash create` refused on such an index and the baseline fell back to + HEAD, so the file's pre-existing content was reviewed as the turn's work. + The snapshot holds that content, so only what the turn changes is.""" + repo = _repo(tmp_path) + (repo / "n.txt").write_text("secret = 1\n") + git(repo, "add", "-N", "n.txt") + sha, fail = _capture(repo) + assert fail == 0 + assert sha != git(repo, "rev-parse", "HEAD").strip() + assert git(repo, "show", f"{sha}:n.txt") == "secret = 1\n" + # The path is still named in the review set, as it was before, but its + # content is in the baseline now, so the reviewer is sent nothing for it + # where `stash create` failing sent the whole file. + + +def test_subdirectory_cwd_snapshots_the_whole_tree(tmp_path): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("top changed\n") + (repo / "d" / "c.txt").write_text("below changed\n") + sha, fail = _capture(repo / "d") + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == "top changed\n" + assert git(repo, "show", f"{sha}:d/c.txt") == "below changed\n" + + +def test_nested_repository_stays_out_of_the_snapshot(tmp_path): + """A directory with its own .git is another repository: #6837 keeps its + gitlink out of the index copy, so it must stay out of the tree too.""" + repo = _repo(tmp_path) + nested = repo / "vendor" + make_repo(nested, {"x.txt": "x\n"}) + git(repo, "add", "vendor") + git(repo, "commit", "-qm", "add nested") + (nested / "x.txt").write_text("changed inside\n") + (repo / "a.txt").write_text("changed outside\n") + sha, fail = _capture(repo) + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == "changed outside\n" + assert "vendor" not in git(repo, "ls-tree", "--name-only", sha) + + +def test_clean_tree_with_a_nested_repository_is_head(tmp_path): + """The index copy has no gitlink, so its tree can never equal HEAD's. + Without a second look that would mint a commit object on every prompt in + a repo with submodules, and the baseline would be a prunable dangling + commit instead of HEAD.""" + repo = _repo(tmp_path) + make_repo(repo / "vendor", {"x.txt": "x\n"}) + git(repo, "add", "vendor") + git(repo, "commit", "-qm", "add nested") + head = git(repo, "rev-parse", "HEAD").strip() + assert _capture(repo) == (head, 0) + + # A change inside the nested repository is still not this repo's work. + (repo / "vendor" / "x.txt").write_text("changed inside\n") + assert _capture(repo) == (head, 0) + + # A real change outside it still gets a snapshot. + (repo / "a.txt").write_text("changed outside\n") + sha, fail = _capture(repo) + assert fail == 0 and sha != head + assert git(repo, "show", f"{sha}:a.txt") == "changed outside\n" + + +def test_snapshot_leaves_the_real_index_and_worktree_alone(tmp_path): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("dirty\n") + before_index = (repo / ".git" / "index").read_bytes() + before_status = git(repo, "status", "--porcelain") + before_stash = git(repo, "stash", "list") + _capture(repo) + assert (repo / ".git" / "index").read_bytes() == before_index + assert git(repo, "status", "--porcelain") == before_status + assert git(repo, "stash", "list") == before_stash + assert [p for p in os.listdir(repo / ".git") if p.startswith("index.")] == [] + + +def test_snapshot_commit_is_unreferenced(tmp_path): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("dirty\n") + sha, _ = _capture(repo) + assert sha not in git(repo, "log", "--all", "--format=%H") + assert git(repo, "rev-parse", "HEAD").strip() != sha + + +def test_partial_clone_snapshots_without_fetching(tmp_path): + """A blobless clone has no blob for an unchanged file. git counts a + promisor object as present, so write-tree neither fetches nor fails; + this pins that, since the snapshot must never make a network call.""" + origin = _repo(tmp_path, "origin") + git(origin, "config", "uploadpack.allowFilter", "true") + for i in range(3): + (origin / f"big{i}.txt").write_text(f"content {i}\n") + git(origin, "add", "-A") + git(origin, "commit", "-qm", "more") + clone = tmp_path / "clone" + subprocess.run(["git", "clone", "-q", "--filter=blob:none", "--no-local", + str(origin), str(clone)], check=True, capture_output=True, + env={**os.environ, **GIT_ENV}) + # Nothing can be fetched from here on: a snapshot that tried would fail. + git(clone, "config", "remote.origin.url", "/nonexistent-origin") + (clone / "a.txt").write_text("dirty\n") + sha, fail = _capture(clone) + assert fail == 0 and sha + assert git(clone, "show", f"{sha}:a.txt") == "dirty\n" + + +def test_literal_pathspecs_in_the_environment(tmp_path, monkeypatch): + """A user who exports GIT_LITERAL_PATHSPECS gets it in the hook's + environment, and a magic pathspec would then fail outright and drop the + baseline to HEAD on every prompt of the session.""" + repo = _repo(tmp_path) + monkeypatch.setenv("GIT_LITERAL_PATHSPECS", "1") + (repo / "a.txt").write_text("dirty\n") + sha, fail = _capture(repo) + assert fail == 0 + assert git(repo, "show", f"{sha}:a.txt") == "dirty\n" + + +def test_no_identity_configured_still_snapshots(tmp_path, monkeypatch): + repo = _repo(tmp_path) + (repo / "a.txt").write_text("dirty\n") + for var in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", + "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "EMAIL"): + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("GIT_CONFIG_SYSTEM", os.devnull) + sha, fail = _capture(repo) + assert fail == 0 and sha + assert "security-guidance" in git(repo, "show", "-s", "--format=%an", sha) + + +def test_signing_configured_does_not_sign_the_snapshot(tmp_path): + repo = _repo(tmp_path) + git(repo, "config", "commit.gpgsign", "true") + git(repo, "config", "gpg.program", "/nonexistent-gpg") + (repo / "a.txt").write_text("dirty\n") + sha, fail = _capture(repo) + assert fail == 0 and sha + assert git(repo, "show", "-s", "--format=%G?", sha).strip() in ("N", "") diff --git a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py index 2325cd9b..03c35087 100644 --- a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py +++ b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py @@ -27,7 +27,7 @@ def _spawns(tree): 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 + assert len(calls) >= 5 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" diff --git a/plugins/security-guidance/tests/test_git_index_locks.py b/plugins/security-guidance/tests/test_git_index_locks.py index 17a877ff..6faaddd3 100644 --- a/plugins/security-guidance/tests/test_git_index_locks.py +++ b/plugins/security-guidance/tests/test_git_index_locks.py @@ -65,12 +65,13 @@ def _make_stat_stale(path): os.utime(path, (t, t)) -def _is_stash_create(args): - return list(args[-2:]) == ["stash", "create"] +def _is_snapshot_add(args): + """The `git add -u` that stages the turn baseline's tracked changes.""" + return list(args[-2:]) == ["add", "-u"] class TestBaselineCapture: - def test_stash_create_gets_a_throwaway_index(self, tmp_path, tmproot, monkeypatch): + def test_snapshot_gets_a_throwaway_index(self, tmp_path, tmproot, monkeypatch): repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) (repo / "app.py").write_text("x = 2\n") before = _index_sig(repo / ".git") @@ -78,7 +79,7 @@ class TestBaselineCapture: real_run = subprocess.run def spy(args, **kw): - if _is_stash_create(args): + if _is_snapshot_add(args): seen.append(kw["env"]["GIT_INDEX_FILE"]) return real_run(args, **kw) @@ -90,13 +91,13 @@ class TestBaselineCapture: assert _index_litter(repo / ".git") == [] assert _leftovers(tmproot) == [] - def test_killed_stash_create_leaves_nothing(self, tmp_path, tmproot, monkeypatch): + def test_killed_snapshot_leaves_nothing(self, tmp_path, tmproot, monkeypatch): repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) (repo / "app.py").write_text("x = 2\n") real_run = subprocess.run def killed(args, **kw): - if _is_stash_create(args): + if _is_snapshot_add(args): idx = kw["env"]["GIT_INDEX_FILE"] for suffix in (".lock", ".stash.4242", ".stash.4242.lock"): with open(idx + suffix, "wb") as f: @@ -211,7 +212,7 @@ class TestReadOnlyGitLeavesTheRealIndexAlone: assert _leftovers(tmproot) == [] def test_diffs_need_no_index_copy(self, tmp_path, tmproot, monkeypatch): - """Every copy is index-sized, so only `add -N` and stash get one.""" + """Every copy is index-sized, so only `add -N` and the snapshot get one.""" repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n", "b.py": "b = 1\n"}) first = git(repo, "rev-parse", "HEAD").strip() commit_file(repo, "app.py", "x = 2\n") @@ -293,10 +294,10 @@ class TestWholeHook: assert m.get("skip_reason") is None and m["files_reviewed"] == 2, m calls = read_log() - assert {"stash", "status", "diff", "add"} <= {sub[0] for _, _, sub in calls} + assert {"write-tree", "status", "diff", "add"} <= {sub[0] for _, _, sub in calls} assert [c for c in calls if c[0] != "0"] == [] for _, index_file, sub in calls: - if sub[0] in ("stash", "add"): + if sub[0] in ("write-tree", "commit-tree", "add"): assert index_file.startswith(str(tmproot)), sub assert _index_sig(repo / ".git") == before assert _index_litter(repo / ".git") == [] diff --git a/plugins/security-guidance/tests/test_git_program.py b/plugins/security-guidance/tests/test_git_program.py new file mode 100644 index 00000000..9249c6e4 --- /dev/null +++ b/plugins/security-guidance/tests/test_git_program.py @@ -0,0 +1,115 @@ +"""On Windows the hooks name git by its full path, found on PATH, so a git.exe +in the project is not the one that starts.""" +import json +import os +import subprocess +import sys + +import pytest + +from conftest import HOOK_SCRIPT, make_repo, ups_payload, write_cli + +import gitutil + +windows_only = pytest.mark.skipif(os.name != "nt", reason="Windows program lookup") + + +def _git_in(d): + d.mkdir(parents=True, exist_ok=True) + (d / "git.exe").write_bytes(b"") + return str(d / "git.exe") + + +def test_bare_name_outside_windows(): + assert gitutil._git_program(windows=False) == "git" + + +def test_first_git_on_path(tmp_path, monkeypatch): + first, second = tmp_path / "a", tmp_path / "b" + first.mkdir() + expected = _git_in(second) + _git_in(tmp_path / "c") + monkeypatch.setenv("PATH", os.pathsep.join([str(first), str(second), str(tmp_path / "c")])) + assert gitutil._git_program(windows=True) == expected + + +def test_working_directory_and_relative_entries_are_left_out(tmp_path, monkeypatch): + project = tmp_path / "project" + _git_in(project) + _git_in(project / "bin") + expected = _git_in(tmp_path / "installed") + monkeypatch.chdir(project) + monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) + monkeypatch.setenv("PATH", os.pathsep.join( + ["", ".", "bin", str(project), str(project) + os.sep, str(tmp_path / "installed")])) + assert gitutil._git_program(windows=True) == expected + + +def test_folder_inside_the_project_is_left_out(tmp_path, monkeypatch): + project = tmp_path / "project" + _git_in(project) + _git_in(project / ".venv" / "Scripts") + (project / "pkg").mkdir() + expected = _git_in(tmp_path / "installed") + monkeypatch.chdir(project / "pkg") + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project)) + monkeypatch.setenv("PATH", os.pathsep.join( + [str(project), str(project / ".venv" / "Scripts"), str(tmp_path / "installed")])) + assert gitutil._git_program(windows=True) == expected + + +def test_project_above_the_home_folder_keeps_the_users_tools(tmp_path, monkeypatch): + home = tmp_path / "me" + expected = _git_in(home / "scoop" / "shims") + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) + monkeypatch.setenv("PATH", str(home / "scoop" / "shims")) + assert gitutil._git_program(windows=True) == expected + + +def test_similar_folder_name_stays(tmp_path, monkeypatch): + project = tmp_path / "project" + project.mkdir() + expected = _git_in(tmp_path / "project-tools") + monkeypatch.chdir(project) + monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) + monkeypatch.setenv("PATH", str(tmp_path / "project-tools")) + assert gitutil._git_program(windows=True) == expected + + +def test_quoted_entry(tmp_path, monkeypatch): + expected = _git_in(tmp_path / "installed") + monkeypatch.setenv("PATH", f'"{tmp_path / "installed"}"') + assert gitutil._git_program(windows=True) == expected + + +def test_no_git_on_path_names_nothing_that_exists(tmp_path, monkeypatch): + project = tmp_path / "project" + _git_in(project) + monkeypatch.chdir(project) + monkeypatch.setenv("PATH", str(project)) + program = gitutil._git_program(windows=True) + assert os.path.isabs(program) and not os.path.exists(program) + + +def test_working_directory_that_is_gone(tmp_path, monkeypatch): + expected = _git_in(tmp_path / "installed") + monkeypatch.setattr(gitutil.os, "getcwd", lambda: (_ for _ in ()).throw(OSError())) + monkeypatch.setenv("PATH", str(tmp_path / "installed")) + assert gitutil._git_program(windows=True) == expected + + +@windows_only +def test_git_exe_in_the_project_does_not_start(tmp_path, env): + marker = tmp_path / "started" + repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"}) + write_cli(repo, "git", f"open({str(marker)!r}, 'a').write('x')\n") + + r = subprocess.run( + [sys.executable, str(HOOK_SCRIPT)], input=json.dumps(ups_payload(repo)), + capture_output=True, text=True, env=env, cwd=repo, timeout=120) + + assert r.returncode == 0, r.stderr + assert not marker.exists() diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py index 4c339a5f..fa998501 100644 --- a/plugins/security-guidance/tests/test_inflight_reviews.py +++ b/plugins/security-guidance/tests/test_inflight_reviews.py @@ -4,6 +4,7 @@ import json import os import subprocess import sys +import threading import time import pytest @@ -152,6 +153,63 @@ def test_push_stops_waiting_after_the_limit(tmp_path, hook_env, stub_api): assert len(_reviews(stub_api)) == 1 +def test_a_push_that_waited_ends_within_the_hook_limit(tmp_path, monkeypatch): + """The wait for a commit review and the race share one limit; a race that + restarts it runs the hook past Claude Code's timeout, with no notice.""" + import security_reminder_hook as hook + + repo, remote = _repo_with_remote(tmp_path) + _, sha, _, _ = _commit_and_push(repo, remote) + monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 1.0) + monkeypatch.setattr(hook, "_RACE_END_S", 1.5) + monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0") + release = threading.Event() + monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20)) + monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(20)) + + started = time.monotonic() + try: + with _held_by_another_review(repo, sha): + _, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 1.0, poll_s=0.05) + _, _, m = hook._agentic_review_with_race( + str(repo), [], [], [], spent_s=waited) + finally: + release.set() + assert 1.0 <= waited < 1.5 + assert 1.5 <= time.monotonic() - started < 2.4 + assert m["review_failed"] is True and m["api_error"] == hook._RACE_TIMED_OUT + + +def test_the_push_handler_counts_its_wait(tmp_path, agentic_env, stub_api): + repo, remote = _repo_with_remote(tmp_path) + _, sha, _, push_out = _commit_and_push(repo, remote) + log = tmp_path / "race.log" + env = {**agentic_env, "SG_INFLIGHT_WAIT_S": "2", "SG_AGENTIC_RACE_DELAY_S": "60", + "SECURITY_GUIDANCE_DEBUG_LOG": str(log)} + with _held_by_another_review(repo, sha): + _, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), env) + assert metrics_of(so)["inflight_wait_s"] >= 2 + assert "already spent, fallback starts after 5" in log.read_text() + + +def test_the_fallback_starts_sooner_after_a_wait(tmp_path, monkeypatch): + import security_reminder_hook as hook + + monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "180") + release = threading.Event() + monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20)) + monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: ("guidance", [])) + monkeypatch.setattr(hook.llm, "last_review_failed", lambda: False) + try: + g, _, m = hook._agentic_review_with_race(str(tmp_path), [], [], [], spent_s=240.0) + finally: + release.set() + assert g == "guidance" + assert (m["race_winner"], m["race_delay_s"], m["race_started"]) == (2, 0, 1) + + def test_push_does_not_wait_when_an_earlier_commit_needs_review_anyway(tmp_path, hook_env, stub_api): repo, remote = _repo_with_remote(tmp_path) base = git(repo, "rev-parse", "HEAD").strip() @@ -376,3 +434,61 @@ def test_windows_lock_is_off_where_the_call_is_missing(monkeypatch): monkeypatch.setattr(diffstate, "_win_lock_file_ex", None) with pytest.raises(OSError): diffstate._win_lock_nb(7, exclusive=True) + + +_SHORT_LIMIT = ( + "import sys\n" + "sys.path.insert(0, sys.argv[1])\n" + "import security_reminder_hook as hook\n" + "hook._RACE_END_S = float(sys.argv[2])\n" + "hook.main()\n" +) + + +def _run_with_limit(payload, env, limit_s): + started = time.monotonic() + r = subprocess.run( + [sys.executable, "-c", _SHORT_LIMIT, _HOOKS_DIR, str(limit_s)], + input=json.dumps(payload), capture_output=True, text=True, env=env, timeout=30) + return time.monotonic() - started, r + + +def test_single_shot_after_a_fast_agentic_failure_ends_in_time( + tmp_path, hook_env, failing_inner_cli, stub_api): + """The agentic run fails before the fallback starts, and the single-shot + review that follows hangs: the session still hears before the hook limit.""" + pytest.importorskip("claude_agent_sdk") + repo, _ = _repo_with_remote(tmp_path) + _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + stub_api.delay = 6 + env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli, + "SG_AGENTIC_RACE_DELAY_S": "60"} + took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4) + assert 4 <= took < 10, r.stderr + assert r.returncode == 2 and "did not finish in time" in r.stderr + assert metrics_of(r.stdout)["agentic_fallback"] == 2 + + +def test_single_shot_after_a_push_wait_ends_in_time( + tmp_path, hook_env, failing_inner_cli, stub_api): + pytest.importorskip("claude_agent_sdk") + repo, remote = _repo_with_remote(tmp_path) + _, sha, _, push_out = _commit_and_push(repo, remote) + stub_api.delay = 10 + env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli, + "SG_INFLIGHT_WAIT_S": "4", "SG_AGENTIC_RACE_DELAY_S": "60"} + with _held_by_another_review(repo, sha): + took, r = _run_with_limit(bash_payload(repo, "git push origin main", push_out), env, 8) + assert 8 <= took < 11.5, r.stderr # 12 s if the wait did not count + assert r.returncode == 2 and "did not finish in time" in r.stderr + assert metrics_of(r.stdout)["inflight_wait_s"] >= 4 + + +def test_single_shot_with_the_agentic_review_off_ends_in_time(tmp_path, hook_env, stub_api): + repo, _ = _repo_with_remote(tmp_path) + _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n") + stub_api.delay = 6 + env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "0"} + took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4) + assert 4 <= took < 10, r.stderr + assert r.returncode == 2 and "did not finish in time" in r.stderr diff --git a/plugins/security-guidance/tests/test_interp_reparse_metric.py b/plugins/security-guidance/tests/test_interp_reparse_metric.py new file mode 100644 index 00000000..5d3f6f13 --- /dev/null +++ b/plugins/security-guidance/tests/test_interp_reparse_metric.py @@ -0,0 +1,209 @@ +"""`interp_reparse` counts sessions whose interpreter is reached through a +symbolic link or junction on Windows. + +Measurement only, for anthropics/claude-code#96870: inside the packaged +Claude Desktop app Windows leaks kernel memory on every file opened through +such a link under AppData, and each hook starts an interpreter. + +The interpreter paths and the Windows file attributes are passed in, so +these run everywhere. +""" +import json +import os +import subprocess +import sys +import types + +import pytest + +import _base +from conftest import HOOKS_DIR + +REPARSE = 0x400 +SYMLINK, JUNCTION, APP_ALIAS = 0xA000000C, 0xA0000003, 0x8000001B +ROAMING = os.path.join(os.sep, "Users", "u", "AppData", "Roaming") +LOCAL = os.path.join(os.sep, "Users", "u", "AppData", "Local") +ENV = {"APPDATA": ROAMING, "LOCALAPPDATA": LOCAL} +REGULAR = os.path.join(os.sep, "Program Files", "Python312") + + +def _key(path): + return os.path.normcase(os.path.abspath(path)) + + +def measure(executable, base_prefix, links=None, missing=(), targets=None, calls=None, old_python=False, + broken=(), environ=ENV): + links = {_key(k): v for k, v in (links or {}).items()} + targets = {_key(k): v for k, v in (targets or {}).items()} + missing = {_key(k) for k in missing} + broken = {_key(k) for k in broken} + + def lstat(path): + if calls is not None: + calls.append(path) + if _key(path) in missing: + raise FileNotFoundError(path) + if _key(path) in broken: + raise ValueError(path) + tag = links.get(_key(path)) + st = types.SimpleNamespace(st_file_attributes=REPARSE if tag else 0) + if not old_python: + st.st_reparse_tag = tag or 0 + return st + + def readlink(path): + if _key(path) not in targets: + raise OSError("not readable") + return targets[_key(path)] + + return _base.interp_reparse_metric(executable=executable, base_prefix=base_prefix, environ=environ, + platform="win32", lstat=lstat, readlink=readlink)["interp_reparse"] + + +def exe(folder): + return os.path.join(folder, "python.exe") + + +def test_regular_install_is_zero_not_absent(): + assert measure(exe(REGULAR), REGULAR) == 0 + + +@pytest.mark.parametrize("tag", [JUNCTION, SYMLINK]) +def test_link_under_appdata(tag): + # uv keeps a minor-version junction beside the real folder. + link = os.path.join(ROAMING, "uv", "python", "cpython-3.12-windows-x86_64-none") + targets = {link: "\\\\?\\C:\\Users\\u\\AppData\\Roaming\\uv\\python\\cpython-3.12.7"} + assert measure(exe(link), link, {link: tag}, targets=targets) == 7 + + +def test_link_under_local_appdata_counts_too(): + link = os.path.join(LOCAL, "Programs", "py") + assert measure(exe(link), link, {link: SYMLINK}) == 7 + + +def test_link_elsewhere_has_no_appdata_bit(): + link = os.path.join(os.sep, "tools", "python") + assert measure(exe(link), link, {link: SYMLINK}) == 3 + + +def test_only_the_standard_library_behind_a_link(): + # A virtual environment's python.exe is a regular file; its base install is linked. + link = os.path.join(ROAMING, "uv", "python", "cpython-3.12") + venv = os.path.join(os.sep, "proj", ".venv", "Scripts", "python.exe") + assert measure(venv, link, {link: SYMLINK}) == 6 + + +def test_only_the_executable_behind_a_link(): + link = os.path.join(os.sep, "tools", "python.exe") + assert measure(link, REGULAR, {link: SYMLINK}) == 1 + + +@pytest.mark.parametrize("link", [ROAMING, os.path.join(os.sep, "Users", "u")]) +def test_appdata_itself_or_the_profile_moved_by_a_link(link): + prefix = os.path.join(ROAMING, "uv", "python", "cpython-3.12.7") + assert measure(exe(prefix), prefix, {link: SYMLINK}) == 7 + + +def test_folder_that_only_starts_like_appdata(): + link = ROAMING + "Other" + assert measure(exe(link), link, {link: SYMLINK}) == 3 + + +def test_app_execution_alias_is_not_a_link(): + alias = os.path.join(LOCAL, "Microsoft", "WindowsApps", "python.exe") + assert measure(alias, REGULAR, {alias: APP_ALIAS}) == 0 + + +def test_mounted_volume_is_not_a_link(): + mount = os.path.join(os.sep, "tools") + prefix = os.path.join(mount, "Python312") + targets = {mount: "\\\\?\\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}\\"} + assert measure(exe(prefix), prefix, {mount: JUNCTION}, targets=targets) == 0 + # A junction whose target cannot be read still counts. + assert measure(exe(prefix), prefix, {mount: JUNCTION}) == 3 + + +def test_junction_to_a_folder_named_by_volume_is_a_link(): + link = os.path.join(os.sep, "tools", "py") + targets = {link: "\\\\?\\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}\\Users\\u\\py"} + assert measure(exe(link), link, {link: JUNCTION}, targets=targets) == 3 + + +def test_python_without_reparse_tags_says_it_cannot_tell(): + link = os.path.join(ROAMING, "uv", "python", "cpython-3.7") + assert measure(exe(link), link, {link: JUNCTION}, old_python=True) == 8 + assert measure(exe(REGULAR), REGULAR, old_python=True) == 0 + + +def test_unreadable_folder_is_skipped(): + link = os.path.join(ROAMING, "uv", "python", "cpython-3.12") + assert measure(exe(link), link, {link: SYMLINK}, missing=(exe(link),)) == 7 + + +def test_each_folder_is_looked_at_once_and_only_up_to_the_link(): + # abspath: on Windows the metric adds the current drive. + prefix = os.path.abspath(os.path.join(os.sep, "a", "b", "c")) + calls = [] + measure(exe(prefix), prefix, calls=calls) + assert sorted(calls) == sorted({exe(prefix), prefix, os.path.dirname(prefix), os.path.dirname(os.path.dirname(prefix))}) + calls.clear() + measure(exe(prefix), prefix, {prefix: SYMLINK}, calls=calls) + assert calls == [exe(prefix), prefix] + + +def test_failure_on_one_path_keeps_the_other(): + link = os.path.join(ROAMING, "uv", "python", "cpython-3.12") + venv = os.path.join(os.sep, "proj", ".venv", "Scripts", "python.exe") + # The executable's folder cannot be read; the standard library's link is still found. + assert measure(venv, link, {link: SYMLINK}, broken=(os.path.dirname(venv),)) == 2 | 4 | 8 + assert measure(exe(REGULAR), REGULAR, broken=(REGULAR,)) == 8 + assert measure(exe(link), link, {link: SYMLINK}, environ={"APPDATA": 7}) == 3 + + +def test_real_system_calls_are_usable(): + # The defaults (sys.executable, os.lstat, os.readlink) on whatever runs the tests. + found = _base.interp_reparse_metric(platform="win32") + assert set(found) == {"interp_reparse"} and 0 <= found["interp_reparse"] < 16 + if sys.platform != "win32": + assert found == {"interp_reparse": 0} + + +def test_other_systems_do_not_look(): + def lstat(path): + raise AssertionError("looked") + assert _base.interp_reparse_metric(platform="linux", lstat=lstat) == {} + if sys.platform != "win32": + assert _base.interp_reparse_metric(lstat=lstat) == {} + + +# SessionStart runs ensure_agent_sdk.py; the wrapper makes the SDK look +# installed (nothing is built) and stands in for the measurement. +_SESSION_START = """ +import importlib.util, os, runpy, sys +script, value = sys.argv[1], sys.argv[2] +sys.path.insert(0, os.path.dirname(script)) +real = importlib.util.find_spec +importlib.util.find_spec = lambda name, *a, **k: object() if name == "claude_agent_sdk" else real(name, *a, **k) +import _base +_base.interp_reparse_metric = lambda: {} if value == "None" else {"interp_reparse": int(value)} +sys.argv = [script] +runpy.run_path(script, run_name="__main__") +""" + + +@pytest.mark.parametrize("value", [7, None]) +def test_session_start_row_carries_it_last(tmp_path, value): + state = tmp_path / "state" + state.mkdir() + env = dict(os.environ, SECURITY_WARNINGS_STATE_DIR=str(state), HOME=str(tmp_path), CLAUDECODE="1", + PYTHONDONTWRITEBYTECODE="1", SG_LAUNCHER_PROBE_MS="4350", SG_LAUNCHER_PROBE_MAX_MS="4200") + r = subprocess.run([sys.executable, "-c", _SESSION_START, str(HOOKS_DIR / "ensure_agent_sdk.py"), str(value)], + input="{}", capture_output=True, text=True, env=env, timeout=60) + assert r.returncode == 0, r.stderr + keys = list(json.loads(r.stdout.splitlines()[-1])["metrics"]) + if value: + assert keys[-3:] == ["launcher_probe_ms", "launcher_probe_max_ms", "interp_reparse"] + else: + assert "interp_reparse" not in keys + # The healthy row fits the 10 keys older Claude Code versions kept (20 now). + assert len(keys) <= 10 diff --git a/plugins/security-guidance/tests/test_launcher_alias_own_path.py b/plugins/security-guidance/tests/test_launcher_alias_own_path.py new file mode 100644 index 00000000..2dd133d0 --- /dev/null +++ b/plugins/security-guidance/tests/test_launcher_alias_own_path.py @@ -0,0 +1,372 @@ +"""sg-python.sh stops starting a packaged Windows alias on every hook. + +When the name that answers is an alias under ...\\Microsoft\\WindowsApps and +its interpreter is a regular file elsewhere, the hook runs with that file and +the path is remembered for a day, so later hooks are one process and none +through the alias. See anthropics/claude-code#98929. + +Aliases and interpreters are shell wrappers, so these tests need a POSIX +shell; the launcher's Windows branch is switched on with OSTYPE. +""" +import os +import shutil +import subprocess +import sys +import time + +import pytest + +from conftest import HOOKS_DIR, metrics_of, run_hook, stop_payload + +SHIM = HOOKS_DIR / "sg-python.sh" +BASH = shutil.which("bash") or "/bin/bash" +REAL = os.path.realpath(sys.executable) +VERSION = f"{sys.version_info[0]}.{sys.version_info[1]}" +try: + BASH_MAJOR = int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True, + text=True, timeout=30).stdout.strip() or 0) +except (OSError, ValueError, subprocess.SubprocessError): + BASH_MAJOR = 0 + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers") + +HOOK = ( + "import os, sys\n" + "print('direct=' + os.environ.get('SG_LAUNCHER_DIRECT', ''))\n" + "print('exe=' + os.environ.get('SG_NAME', ''))\n" + "print('argv=' + ' '.join(sys.argv[1:]))\n" + "print('stdin=' + sys.stdin.read())\n" +) + +# A packaged alias: answers the probe like Windows Python does (version, then +# sys.executable, CRLF), and runs the hook itself when asked to. +ALIAS = """#!{bash} +[ "${{0##*/}}" = "py" ] && [ "${{1:-}}" = "-3" ] && shift +if [ "${{1:-}}" = "-c" ]; then + echo "${{0##*/}} probe" >> '{log}'; printf '{version}\\r\\n{own}\\r\\n'; exit 0 +fi +echo "${{0##*/}} run" >> '{log}' +SG_NAME=alias exec '{real}' "$@" +""" +# The interpreter behind it: the real one, logging its starts. +OWN = """#!{bash} +if [ "${{1:-}}" = "-c" ]; then + echo "own probe" >> '{log}' + [ {rc} -eq 0 ] || exit {rc} +else + echo "own run" >> '{log}' +fi +SG_NAME=own exec '{real}' "$@" +""" + + +class Box: + def __init__(self, tmp_path): + self.root = tmp_path + self.apps = tmp_path / "AppData" / "Local" / "Microsoft" / "WindowsApps" + self.own = tmp_path / "AppData" / "Local" / "Python" / "pythoncore-3-64" / "python.exe" + self.state = tmp_path / "state" + self.log = tmp_path / "log" + self.hooks = tmp_path / "plugin" / "hooks" + for d in (self.apps, self.own.parent, self.state, self.hooks): + d.mkdir(parents=True) + self.log.write_text("") + self.script = self.hooks / "hook.py" + self.script.write_text(HOOK) + self.memo = self.state / "launcher-python" + + def write(self, path, template, **kw): + kw = {"version": VERSION, "own": self.own, "rc": 0, **kw} + path.write_text(template.format(bash=BASH, log=self.log, real=REAL, **kw)) + path.chmod(0o755) + + def alias(self, name="py", **kw): + self.write(self.apps / name, ALIAS, **kw) + + def interpreter(self, **kw): + self.write(self.own, OWN, **kw) + + def launch(self, *args, script=None, ostype="msys", path=None, **extra_env): + env = {"PATH": path or str(self.apps), "HOME": str(self.root), "OSTYPE": ostype, + "SECURITY_WARNINGS_STATE_DIR": str(self.state)} + env.update(extra_env) + self.log.write_text("") + return subprocess.run([BASH, str(SHIM), str(script or self.script), *args], input="payload", + capture_output=True, text=True, timeout=60, env=env) + + def run(self, *args, **kw): + r = self.launch(*args, **kw) + assert r.returncode == 0 and r.stderr == "", r.stderr + out = dict(line.split("=", 1) for line in r.stdout.splitlines()) + return out, self.starts() + + def starts(self): + return self.log.read_text().splitlines() + + +@pytest.fixture +def box(tmp_path): + if BASH_MAJOR < 5: + pytest.skip("the remembered route needs bash 5") + b = Box(tmp_path) + b.alias() + b.interpreter() + return b + + +def test_first_hook_checks_the_interpreter_and_runs_it(box): + out, starts = box.run("extra") + assert starts == ["py probe", "own probe", "own run"] + assert (out["exe"], out["direct"], out["argv"], out["stdin"]) == ("own", "2", "extra", "payload") + assert box.memo.read_text().splitlines()[3] == str(box.own) + + +def test_later_hooks_are_one_process_and_never_the_alias(box): + box.run() + for _ in range(3): + out, starts = box.run("extra") + assert starts == ["own run"] + assert (out["exe"], out["direct"], out["argv"], out["stdin"]) == ("own", "1", "extra", "payload") + + +def test_state_folder_follows_the_config_dir(box): + (box.root / "cfg" / "security").mkdir(parents=True) + env = {"SECURITY_WARNINGS_STATE_DIR": "", "CLAUDE_CONFIG_DIR": str(box.root / "cfg")} + box.run(**env) + assert (box.root / "cfg" / "security" / "launcher-python").exists() + assert box.run(**env)[1] == ["own run"] + (box.root / ".claude" / "security").mkdir(parents=True) + env["CLAUDE_CONFIG_DIR"] = "" + box.run(**env) + assert (box.root / ".claude" / "security" / "launcher-python").exists() + assert not box.memo.exists() + + +def test_changed_path_is_searched_again(box): + box.run() + other = box.root / "other" + other.mkdir() + out, starts = box.run(path=f"{box.apps}{os.pathsep}{other}") + assert starts == ["py probe", "own probe", "own run"] and out["direct"] == "2" + + +def test_another_hook_folder_is_checked_again(box): + box.run() + moved = box.root / "plugin-next" / "hooks" + moved.mkdir(parents=True) + (moved / "hook.py").write_text(HOOK) + out, starts = box.run(script=moved / "hook.py") + assert starts == ["py probe", "own probe", "own run"] + # Same folder, another hook script: still the remembered route. + (moved / "other.py").write_text(HOOK) + assert box.run(script=moved / "other.py")[1] == ["own run"] + + +@pytest.mark.parametrize("shift", [-86400 - 60, 3600]) +def test_entry_is_trusted_for_a_day(box, shift): + box.run() + lines = box.memo.read_text().splitlines() + lines[1] = str(int(time.time()) + shift) + box.memo.write_text("\n".join(lines) + "\n") + out, starts = box.run() + assert starts == ["py probe", "own probe", "own run"] + assert abs(int(box.memo.read_text().splitlines()[1]) - time.time()) < 120 + + +@pytest.mark.parametrize("damage", [ + lambda lines: lines[:4], # cut short while being written + lambda lines: ["sg-launcher-python 0"] + lines[1:], # another format + lambda lines: lines[:1] + ["soon"] + lines[2:], + lambda lines: lines[:1] + ["9" * 30] + lines[2:], + lambda lines: lines[:3] + ["/bin/sh"] + lines[4:], # not an interpreter + lambda lines: lines[:3] + ["tools/python.exe"] + lines[4:], # not absolute + lambda lines: lines[:3] + [lines[4] + "/python.exe"] + lines[4:], # a folder (made below) + lambda lines: lines[:5] + ["more"], + lambda lines: [], +]) +def test_damaged_entry_is_ignored_and_replaced(box, damage): + box.run() + (box.hooks / "python.exe").mkdir() + good = box.memo.read_text() + box.memo.write_text("".join(line + "\n" for line in damage(good.splitlines()))) + out, starts = box.run() + assert starts == ["py probe", "own probe", "own run"] and out["stdin"] == "payload" + assert box.memo.read_text().splitlines()[2:] == good.splitlines()[2:] + + +def test_remembered_alias_path_is_never_started(box): + box.run() + lines = box.memo.read_text().splitlines() + inner = box.apps / "python.exe" + box.write(inner, OWN) + lines[3] = str(inner) + box.memo.write_text("\n".join(lines) + "\n") + assert box.run()[1] == ["py probe", "own probe", "own run"] + + +def test_removed_interpreter_falls_back_to_the_alias(box): + box.run() + box.own.unlink() + out, starts = box.run() + assert starts == ["py probe", "py run"] + assert (out["exe"], out["direct"], out["stdin"]) == ("alias", "", "payload") + + +def test_missing_hook_script_is_not_run_from_memory(box): + box.run() + box.script.unlink() + box.launch() + # The full search ran: the remembered interpreter was not started first. + assert box.starts()[0] == "py probe" + + +@pytest.mark.parametrize("code", [1, 2]) +def test_failed_hook_on_the_remembered_path_empties_the_entry(box, code): + box.run() + failing = box.hooks / "fails.py" + failing.write_text(f"import sys\nsys.stderr.write('findings')\nsys.exit({code})\n") + r = box.launch(script=failing) + # Its exit code and output pass through unchanged, once. + assert (r.returncode, r.stderr, box.starts()) == (code, "findings", ["own run"]) + assert box.memo.read_text() == "" + out, starts = box.run() + assert starts == ["py probe", "own probe", "own run"] and out["direct"] == "2" + assert box.run()[1] == ["own run"] + + +def test_virtual_environment_keeps_the_alias(box): + box.run() + out, starts = box.run(VIRTUAL_ENV=str(box.root / "venv")) + assert starts == ["py probe", "py run"] and (out["exe"], out["direct"]) == ("alias", "") + + +def test_tilde_and_userprofile_resolve_like_the_hooks_do(box): + profile = box.root / "profile" + (profile / "st").mkdir(parents=True) + env = {"SECURITY_WARNINGS_STATE_DIR": "~/st", "USERPROFILE": str(profile)} + box.run(**env) + assert (profile / "st" / "launcher-python").exists() + assert box.run(**env)[1] == ["own run"] + (profile / ".claude" / "security").mkdir(parents=True) + env["SECURITY_WARNINGS_STATE_DIR"] = "" + box.run(**env) + assert (profile / ".claude" / "security" / "launcher-python").exists() + + +def test_unwritable_entry_is_silent(box): + box.memo.mkdir() + for _ in range(2): + out, starts = box.run() # run() asserts an empty stderr + assert starts == ["py probe", "own probe", "own run"] + + +def test_windows_form_path_goes_through_cygpath(box): + # OSTYPE=cygwin has no /<drive> mounts: the answer is converted by cygpath. + box.write(box.apps / "cygpath", """#!{bash} +echo "cygpath $1" >> '{log}' +[ "$1" = "-u" ] && [ "$2" = 'C:\\Py\\python.exe' ] && {{ echo '{own}'; exit 0; }} +echo "$2" +""") + box.alias(own="C:\\\\Py\\\\python.exe") + out, starts = box.run(ostype="cygwin") + assert [s for s in starts if not s.startswith("cygpath -w")] == [ + "py probe", "cygpath -u", "own probe", "own run"] + assert (out["exe"], out["direct"]) == ("own", "2") + assert box.memo.read_text().splitlines()[3] == str(box.own) + assert [s for s in box.run(ostype="cygwin")[1] if not s.startswith("cygpath -w")] == ["own run"] + + +@pytest.mark.parametrize("name", ["pypy3.exe", "python"]) +def test_interpreter_by_another_name_is_neither_checked_nor_remembered(box, name): + other = box.own.parent / name + box.write(other, OWN) + box.alias(own=other) + out, starts = box.run() + assert starts == ["py probe", "py run"] and not box.memo.exists() + + +def test_interpreter_that_cannot_read_the_script_is_not_used(box): + box.interpreter(rc=3) + out, starts = box.run() + assert starts == ["py probe", "own probe", "py run"] + assert (out["exe"], out["direct"]) == ("alias", "") and not box.memo.exists() + + +def test_other_version_behind_the_alias_is_not_used(box): + box.alias(version="3.10" if VERSION != "3.10" else "3.11") + out, starts = box.run() + assert starts == ["py probe", "own probe", "py run"] + assert (out["exe"], out["direct"]) == ("alias", "") and not box.memo.exists() + + +def test_interpreter_inside_the_alias_folder_is_left_alone(box): + # Microsoft Store Python: sys.executable is itself under WindowsApps. + inner = box.apps / "PythonSoftwareFoundation.Python.3" / "python.exe" + inner.parent.mkdir() + box.write(inner, OWN) + box.alias(own=inner) + out, starts = box.run() + assert starts == ["py probe", "py run"] and out["direct"] == "" and not box.memo.exists() + + +def test_regular_install_is_left_alone(box): + regular = box.root / "Python312" + regular.mkdir() + box.write(regular / "python", ALIAS) + out, starts = box.run(path=str(regular)) + assert starts == ["python probe", "python run"] and out["direct"] == "" and not box.memo.exists() + + +@pytest.mark.parametrize("ostype", ["linux-gnu", "darwin23", ""]) +def test_other_systems_are_left_alone(box, ostype): + box.run() + out, starts = box.run(ostype=ostype) + assert starts == ["py probe", "py run"] and out["direct"] == "" + + +def test_missing_state_folder_is_not_created(box): + gone = box.root / "nowhere" + out, starts = box.run(SECURITY_WARNINGS_STATE_DIR=str(gone)) + assert starts == ["py probe", "own probe", "own run"] and out["exe"] == "own" + assert not gone.exists() + + +def test_versioned_alias_is_remembered_too(box): + (box.apps / "py").unlink() + box.alias("python3.12", version="3.12") + box.write(box.own, ALIAS.replace("SG_NAME=alias", "SG_NAME=own").replace("${{0##*/}}", "own"), + version="3.12") + out, starts = box.run() + assert starts == ["python3.12 probe", "own probe", "own run"] and out["direct"] == "2" + assert box.run()[1] == ["own run"] + + +def test_newer_python_answering_with_two_lines_is_still_chosen(box): + # Pass 2b reads the probe without `ask`. + (box.apps / "py").unlink() + box.alias("python3.14", version="3.14") + out, starts = box.run() + assert starts == ["python3.14 probe", "python3.14 run"] and out["exe"] == "alias" + + +@pytest.mark.parametrize("value,expected", [("1", 1), ("2", 2), ("", None), ("3", None), ("yes", None)]) +def test_stop_hook_reports_the_direct_route(hook_env, workspace, value, expected): + _, repo = workspace + rc, out, err = run_hook(stop_payload(repo), {**hook_env, "SG_LAUNCHER_DIRECT": value}) + m = metrics_of(out) + assert m is not None, err + assert m.get("launcher_direct") == expected + + +def test_direct_route_key_is_the_last_one(hook_env, workspace): + """Claude Code keeps the first 20 keys, so this one never displaces another.""" + _, repo = workspace + rc, out, err = run_hook(stop_payload(repo), {**hook_env, "SG_LAUNCHER_DIRECT": "1"}) + assert list(metrics_of(out))[-1] == "launcher_direct" + + +def test_value_is_read_once(monkeypatch): + import _base + monkeypatch.setenv("SG_LAUNCHER_DIRECT", "1") + assert _base.launcher_direct_metric() == {"launcher_direct": 1} + assert "SG_LAUNCHER_DIRECT" not in os.environ and _base.launcher_direct_metric() == {} diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py index 3c93a580..6fdcdad6 100644 --- a/plugins/security-guidance/tests/test_nested_repos.py +++ b/plugins/security-guidance/tests/test_nested_repos.py @@ -6,7 +6,7 @@ import pytest from conftest import ( GIT_ENV, STUB_VULN, VULN_PY, git, make_repo, metrics_of, run_hook, - stop_payload, ups_payload, + stop_payload, ups_payload, write_cli, ) import diffstate @@ -318,8 +318,9 @@ def test_untracked_file_name_is_not_read_as_a_pattern(outer, git_env): assert name in copy and "other.py" not in copy -def test_gitlink_without_a_repository_stays_in_the_copy(outer, marker, git_env): - """A submodule that is not checked out: an empty directory.""" +def test_gitlink_without_a_repository_is_removed_from_the_copy(outer, marker, git_env): + """A submodule that is not checked out: an empty directory. Its entry goes + too, since a `.git` can appear there before git runs.""" nested = _record_nested_repo(outer, marker) # Moved, not deleted: git's object files are read-only on Windows. nested.rename(outer.parent / "moved-away") @@ -330,9 +331,16 @@ def test_gitlink_without_a_repository_stays_in_the_copy(outer, marker, git_env): copy = _index_entries(outer, env) baseline = diffstate.capture_git_baseline(str(outer)) - assert "160000" in copy - assert baseline and baseline != git(outer, "rev-parse", "HEAD").strip() - assert diffstate.last_baseline_fail == 0 + assert "160000" not in copy + assert "160000" in git(outer, "ls-files", "-s") + head = git(outer, "rev-parse", "HEAD").strip() + version = tuple(int(n) for n in git(outer, "--version").split()[2].split(".")[:2]) + if version >= (2, 34): + assert baseline and baseline != head + assert diffstate.last_baseline_fail == 0 + else: # `git stash create` fails on the empty directory + assert baseline == head + assert diffstate.last_baseline_fail == 1 def test_gitlinks_listed_by_a_git_without_sparse_listing(outer, marker, git_env, monkeypatch): @@ -425,3 +433,49 @@ def test_gitlink_found_in_every_index_format(outer, marker, git_env, monkeypatch assert seen and "160000" not in copy and "later.py" in copy assert baseline != git(outer, "rev-parse", "HEAD").strip() assert not marker.exists() + + +def _signed_head(repo, tmp_path, marker): + """Make HEAD a commit that carries a signature, with log.showSignature on + and gpg.program naming a stand-in that leaves a line in `marker`.""" + program = write_cli(tmp_path, "signature-check", ( + "import sys\n" + f"open({str(marker)!r}, 'a').write('ran\\n')\n" + "sys.exit(1)\n")) + head = git(repo, "rev-parse", "HEAD").strip() + tree = git(repo, "rev-parse", "HEAD^{tree}").strip() + who = "t <t@example.com> 1800000000 +0000" + commit = ( + f"tree {tree}\nparent {head}\nauthor {who}\ncommitter {who}\n" + "gpgsig -----BEGIN PGP SIGNATURE-----\n \n xx\n" + " -----END PGP SIGNATURE-----\n\nsigned\n") + sha = subprocess.run( + ["git", "hash-object", "-t", "commit", "-w", "--stdin"], cwd=repo, + input=commit.encode(), capture_output=True, check=True, + ).stdout.decode().strip() + git(repo, "update-ref", "--create-reflog", "-m", "commit: signed", "HEAD", sha) + git(repo, "config", "log.showSignature", "true") + git(repo, "config", "gpg.program", str(program)) + return sha + + +def test_reading_the_reflog_does_not_check_signatures(outer, marker, tmp_path, git_env): + sha = _signed_head(outer, tmp_path, marker) + # The stand-in does run for a plain `git log` in this repository. + git(outer, "log", "-1") + assert marker.exists() + marker.unlink() + + fresh, _stale = gitutil._git_reflog_recent_commits(str(outer), max_age_s=10**10) + + assert sha in fresh + assert not marker.exists(), marker.read_text() + + +def test_reviewer_environment_turns_signature_display_off(outer, marker, tmp_path, git_env): + _signed_head(outer, tmp_path, marker) + + gitutil.apply_safe_git_env() + git(outer, "log", "-1") + + assert not marker.exists(), marker.read_text() diff --git a/plugins/security-guidance/tests/test_network_failure_class.py b/plugins/security-guidance/tests/test_network_failure_class.py index 896a251f..7a2229ad 100644 --- a/plugins/security-guidance/tests/test_network_failure_class.py +++ b/plugins/security-guidance/tests/test_network_failure_class.py @@ -5,6 +5,7 @@ import http.client import socket import ssl import sys +import threading import types import urllib.error @@ -326,6 +327,117 @@ class TestEmittedRow: assert "net_err" not in self._row(capsys) +class TestClearedOnALaterResponse: + """`net_err` says why the last call got no response, so a failed call + followed by one that got through leaves nothing on the review's row.""" + + @pytest.fixture(autouse=True) + def _clean(self, monkeypatch): + monkeypatch.setitem(_base._USAGE, "net_err", 0) + monkeypatch.setattr(llm, "_last_call_claude_http_error", None) + + @pytest.fixture + def remote(self, direct, monkeypatch): + monkeypatch.setenv("CLAUDE_CODE_REMOTE", "1") + monkeypatch.delenv("NO_PROXY", raising=False) + monkeypatch.delenv("no_proxy", raising=False) + monkeypatch.setattr(llm, "_anthropic_reachable", None) + + def _probes(self, monkeypatch, *outcomes): + def urlopen(request, timeout): + outcome = outcomes[len(calls)] + calls.append(request) + if isinstance(outcome, BaseException): + raise outcome + return _Reply("") + calls = [] + monkeypatch.setattr(llm, "_urlopen", urlopen) + return calls + + def _status(self, code): + return urllib.error.HTTPError("https://api.anthropic.com/", code, "x", {}, None) + + @pytest.mark.parametrize("second", ["reply", "status"]) + def test_second_probe_that_gets_through(self, remote, monkeypatch, second): + calls = self._probes(monkeypatch, urllib.error.URLError(ConnectionRefusedError()), + None if second == "reply" else self._status(404)) + assert llm.ensure_anthropic_reachable() is True + assert len(calls) == 2 + assert _base._net_error_metric() == 0 + + def test_second_probe_that_fails_keeps_its_class(self, remote, monkeypatch): + self._probes(monkeypatch, urllib.error.URLError(ConnectionRefusedError()), + urllib.error.URLError(socket.gaierror(-2, "x"))) + assert llm.ensure_anthropic_reachable() is False + assert _base._net_error_metric() == llm.NET_ERR_DNS + + def _race(self, monkeypatch, agentic_result): + """A fallback that records a refused connection and has no verdict, + then an agentic run that ends with `agentic_result`.""" + tried = threading.Event() + + def fallback(diff_files, is_diff, previous_findings): + _base._record_net_error(llm.NET_ERR_CONNECT) + llm._last_call_claude_http_error = -1 + tried.set() + return None, [] + + def agentic(repo_root, diff_files, rel_touched): + assert tried.wait(10) + return agentic_result + + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0") + monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) + monkeypatch.setattr(hook, "analyze_code_security", fallback) + monkeypatch.setattr(hook, "agentic_review", agentic) + monkeypatch.setattr(hook.llm, "last_review_failed", lambda: True) + monkeypatch.setattr(hook.llm, "last_review_status", lambda: -1) + return hook._agentic_review_with_race(".", [], [], []) + + @pytest.mark.parametrize("guidance", ["findings", None]) + def test_agentic_verdict_after_a_failed_fallback(self, monkeypatch, guidance): + _, _, m = self._race(monkeypatch, (guidance, [], {"agentic": True})) + assert (m["race_winner"], m["race_started"]) == (1, 1) + assert _base._net_error_metric() == 0 + assert llm._last_call_claude_http_error is None + + def test_no_verdict_from_either_side_keeps_the_class(self, monkeypatch): + _, _, m = self._race(monkeypatch, (None, [], {"agentic_fallback": "investigate:x"})) + assert m["race_winner"] == 2 and m["review_failed"] + assert _base._net_error_metric() == llm.NET_ERR_CONNECT + + def _dual_legs(self, monkeypatch, *replies): + """The first leg records a refused connection before the second ends.""" + lock, failed = threading.Lock(), threading.Event() + pending = list(replies) + + def call(*a, **k): + with lock: + reply = pending.pop(0) + if reply is None: + _base._record_net_error(llm.NET_ERR_CONNECT) + llm._last_call_claude_http_error = -1 + failed.set() + else: + assert failed.wait(10) + return reply + + monkeypatch.setenv("SG_DUAL_OR", "on") + monkeypatch.setenv("SECURITY_REVIEW_MODEL", "claude-opus-5-5") + monkeypatch.setattr(llm, "_call_claude", call) + return llm._call_claude_dual_or("p", {}, bool_key="found", list_key="items") + + def test_dual_review_with_one_leg_that_gets_through(self, monkeypatch): + merged = self._dual_legs(monkeypatch, None, {"found": False, "items": []}) + assert merged["found"] is False + assert _base._net_error_metric() == 0 + assert llm._last_call_claude_http_error is None + + def test_dual_review_with_no_leg_through_keeps_the_class(self, monkeypatch): + assert self._dual_legs(monkeypatch, None, None) is None + assert _base._net_error_metric() == llm.NET_ERR_CONNECT + + def _free_port(): with socket.socket() as s: s.bind(("127.0.0.1", 0)) diff --git a/plugins/security-guidance/tests/test_project_config_files.py b/plugins/security-guidance/tests/test_project_config_files.py new file mode 100644 index 00000000..5cef98c0 --- /dev/null +++ b/plugins/security-guidance/tests/test_project_config_files.py @@ -0,0 +1,117 @@ +"""Project guidance and pattern files are read only as real files in the +project, and the guidance block ends where the plugin ends it.""" +import os +import re +import sys + +import pytest + +import extensibility + + +GUIDANCE = extensibility.GUIDANCE_BASENAME +RULE = '{"patterns": [{"rule_name": "r", "reminder": "from the file", "substrings": ["zz"]}]}' + + +@pytest.fixture +def project(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("USERPROFILE", str(tmp_path / "home")) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + monkeypatch.setattr(extensibility, "_guidance_block", "") + monkeypatch.setattr(extensibility, "_user_patterns", []) + repo = tmp_path / "repo" + (repo / ".claude").mkdir(parents=True) + return repo + + +def _link(link, target, is_dir=False): + try: + os.symlink(target, link, target_is_directory=is_dir) + except (OSError, NotImplementedError) as e: + pytest.skip(f"cannot make a link here: {e}") + + +def _guidance(cwd): + extensibility.load_for_session(str(cwd)) + return extensibility.guidance_block() + + +def test_guidance_file_in_the_project_is_read(project): + (project / ".claude" / GUIDANCE).write_text("use the vault\n") + assert "use the vault" in _guidance(project) + + +def test_guidance_link_inside_the_repository_is_skipped(project): + (project / ".env").write_text("TOKEN=abc\n") + _link(project / ".claude" / GUIDANCE, project / ".env") + assert _guidance(project) == "" + + +def test_guidance_link_outside_is_skipped(project, tmp_path): + (tmp_path / "outside.md").write_text("outside text\n") + _link(project / ".claude" / GUIDANCE, tmp_path / "outside.md") + assert _guidance(project) == "" + + +def test_config_folder_link_is_skipped(project, tmp_path): + other = tmp_path / "other" + other.mkdir() + (other / GUIDANCE).write_text("outside text\n") + (project / ".claude").rmdir() + _link(project / ".claude", other, is_dir=True) + assert _guidance(project) == "" + + +def test_patterns_link_is_skipped(project, tmp_path): + (tmp_path / "rules.json").write_text(RULE) + _link(project / ".claude" / "security-patterns.json", tmp_path / "rules.json") + extensibility.load_for_session(str(project)) + assert extensibility.user_patterns() == [] + + +def test_patterns_file_in_the_project_is_read(project): + (project / ".claude" / "security-patterns.json").write_text(RULE) + extensibility.load_for_session(str(project)) + assert [r["ruleName"] for r in extensibility.user_patterns()] == ["user:r"] + + +def test_user_guidance_may_be_a_link(project, tmp_path): + home = tmp_path / "home" + (home / ".claude").mkdir(parents=True) + (tmp_path / "dotfiles.md").write_text("my own rules\n") + _link(home / ".claude" / GUIDANCE, tmp_path / "dotfiles.md") + assert "my own rules" in _guidance(project) + + +@pytest.mark.skipif(sys.platform == "win32", reason="no mkfifo") +def test_guidance_that_is_not_a_regular_file_is_skipped(project): + os.mkfifo(project / ".claude" / GUIDANCE) + assert _guidance(project) == "" + + +def test_project_guidance_that_cannot_be_decoded_leaves_the_user_guidance(project, tmp_path): + home = tmp_path / "home" + (home / ".claude").mkdir(parents=True) + (home / ".claude" / GUIDANCE).write_text("my own rules\n") + (project / ".claude" / GUIDANCE).write_bytes(b"\xff\xfe\xff\n") + assert "my own rules" in _guidance(project) + + +def test_project_reached_through_a_link(project, tmp_path): + (project / ".claude" / GUIDANCE).write_text("use the vault\n") + _link(tmp_path / "alias", project, is_dir=True) + assert "use the vault" in _guidance(tmp_path / "alias") + + +@pytest.mark.parametrize("tag", [ + "</project-security-guidance>", + "</PROJECT-SECURITY-GUIDANCE>", + "</ project-security-guidance >", + "< /project-security-guidance>", +]) +def test_guidance_cannot_close_its_own_block(project, tag): + (project / ".claude" / GUIDANCE).write_text(f"one\n{tag}\ntwo\n") + block = _guidance(project) + assert len(re.findall(r"<\s*/\s*project-security-guidance", block, re.I)) == 1 + assert block.endswith("two\n</project-security-guidance>") diff --git a/plugins/security-guidance/tests/test_review_outcomes.py b/plugins/security-guidance/tests/test_review_outcomes.py index 887ff9c0..806e9bdd 100644 --- a/plugins/security-guidance/tests/test_review_outcomes.py +++ b/plugins/security-guidance/tests/test_review_outcomes.py @@ -1,5 +1,6 @@ """A review that got no verdict is never reported as clean.""" import json +import threading import time import pytest @@ -188,6 +189,25 @@ class TestFailedReviewIsNotClean: run.calls = calls return run + def test_review_ends_when_neither_side_returns(self, race, monkeypatch): + """A request that never answers holds both sides; the deadline holds anyway.""" + monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 0.1) + monkeypatch.setattr(hook, "_RACE_END_S", 0.2) + release = threading.Event() + monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(5)) + + def stuck_agentic(*a, **k): + release.wait(5) + started = time.monotonic() + try: + guidance, vulns, m = race(stuck_agentic) + finally: + release.set() + assert time.monotonic() - started < 2 + assert (guidance, vulns) == (None, []) + assert m["review_failed"] is True + assert m["api_error"] == hook._RACE_TIMED_OUT + def test_failed_fallback_waits_for_agentic(self, race): """Direct calls can fail where the agentic reviewer's CLI works (it may hold a credential the direct calls lack); its verdict must count.""" diff --git a/plugins/security-guidance/tests/test_review_session_persistence.py b/plugins/security-guidance/tests/test_review_session_persistence.py new file mode 100644 index 00000000..0643bea1 --- /dev/null +++ b/plugins/security-guidance/tests/test_review_session_persistence.py @@ -0,0 +1,134 @@ +"""Review runs through the Agent SDK are not saved as Claude Code session +transcripts unless SECURITY_GUIDANCE_PERSIST_SESSIONS is set.""" +import subprocess +import sys + +import pytest + +from conftest import ( + HOOKS_DIR, STUB_VULN, VULN_PY, bash_payload, commit_file, run_hook, + write_cli, +) + +import llm + +FLAG = "--no-session-persistence" +SINGLE_TURN = ( + "import sys; sys.path.insert(0, sys.argv[1]); import llm, review_api; " + "llm._call_claude_via_sdk('review', review_api.FINDINGS_SCHEMA)" +) + + +def _stub_cli(tmp_path, reject_flag=False): + """An inner CLI that records each launch's arguments on one line and + exits 1. With reject_flag it first refuses the flag the way a Claude Code + older than the flag does.""" + log = tmp_path / "inner-cli-launches" + reject = ( + f"if {FLAG!r} in sys.argv:\n" + f" sys.stderr.write(\"error: unknown option '{FLAG}'\\n\")\n" + " sys.exit(1)\n" + ) if reject_flag else "" + cli = write_cli(tmp_path, "claude", ( + "import sys\n" + # utf-8: the reviewer's prompt has characters cp1252 cannot write. + f"with open({str(log)!r}, 'a', encoding='utf-8') as f:\n" + " f.write(' '.join(sys.argv[1:]) + '\\n')\n" + f"{reject}" + "sys.exit(1)\n")) + return str(cli), log + + +def _reviews(log): + """Argument lines of the review launches (the SDK also probes `-v`).""" + return [l for l in log.read_text(encoding="utf-8").splitlines() + if "--input-format" in l] + + +@pytest.fixture +def sdk_env(env): + pytest.importorskip("claude_agent_sdk") + e = {**env, "SG_AGENTIC_COMMIT_REVIEW": "1"} + e.pop("SECURITY_GUIDANCE_PERSIST_SESSIONS", None) + return e + + +def _commit(repo, env): + _, out = commit_file(repo, "app.py", VULN_PY) + return run_hook(bash_payload(repo, "git commit -m change", out), env) + + +def _single_turn(env): + subprocess.run([sys.executable, "-c", SINGLE_TURN, str(HOOKS_DIR)], + env=env, capture_output=True, text=True, timeout=120) + + +class TestSessionArgs: + @pytest.mark.parametrize("value", [None, "", "0", "off"]) + def test_not_saved_by_default(self, monkeypatch, value): + monkeypatch.setattr(llm, "_send_session_flag", True) + if value is None: + monkeypatch.delenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", raising=False) + else: + monkeypatch.setenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", value) + assert llm._reviewer_session_args() == {"no-session-persistence": None} + + @pytest.mark.parametrize("value", ["1", " on ", "TRUE", "yes"]) + def test_opt_in_keeps_sessions(self, monkeypatch, value): + monkeypatch.setattr(llm, "_send_session_flag", True) + monkeypatch.setenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", value) + assert llm._reviewer_session_args() == {} + + def test_only_a_rejection_of_this_flag_counts(self): + assert llm._refused_flags(["error: unknown option '--other'"]) == [] + assert llm._refused_flags([f"error: unknown option '{FLAG}'"]) == [FLAG] + + def test_left_out_once_refused(self, monkeypatch): + monkeypatch.setattr(llm, "_send_session_flag", False) + monkeypatch.delenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", raising=False) + assert llm._reviewer_session_args() == {} + + +class TestInnerCliArguments: + def test_commit_reviewer_gets_the_flag(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert reviews and all(FLAG in r for r in reviews) + + def test_commit_reviewer_opt_in_drops_the_flag(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli, + "SECURITY_GUIDANCE_PERSIST_SESSIONS": "1"}) + reviews = _reviews(log) + assert reviews and not any(FLAG in r for r in reviews) + + def test_single_turn_review_gets_the_flag(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert reviews and all(FLAG in r for r in reviews) + + def test_single_turn_review_opt_in_drops_the_flag(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli, + "SECURITY_GUIDANCE_PERSIST_SESSIONS": "1"}) + reviews = _reviews(log) + assert reviews and not any(FLAG in r for r in reviews) + + +class TestInnerCliOlderThanTheFlag: + def test_commit_reviewer_runs_again_without_it(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path, reject_flag=True) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert [FLAG in r for r in reviews] == [True, False] + + def test_single_turn_review_runs_again_without_it(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path, reject_flag=True) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert [FLAG in r for r in reviews] == [True, False] diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py index 3b9521ff..555ef0ad 100644 --- a/plugins/security-guidance/tests/test_reviewer_tools.py +++ b/plugins/security-guidance/tests/test_reviewer_tools.py @@ -14,11 +14,14 @@ NO_TOOLS = {"tools": "", "strict-mcp-config": None} # Once an inner CLI has refused --strict-mcp-config. READ_ONLY_NO_MCP = {"tools": "Read,Grep,Glob", "disallowedTools": "mcp__*"} NO_TOOLS_NO_MCP = {"tools": "", "disallowedTools": "mcp__*"} +# Every review start also asks for its session not to be saved. +NOT_SAVED = {"no-session-persistence": None} @pytest.fixture(autouse=True) def strict_mcp_flag_sent(monkeypatch): monkeypatch.setattr(llm, "_send_strict_mcp", True) + monkeypatch.setattr(llm, "_send_session_flag", True) def test_tool_flags(): @@ -82,6 +85,7 @@ def sdk(monkeypatch, tmp_path): mod.AssistantMessage = type("AssistantMessage", (), {}) monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + monkeypatch.delenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", raising=False) monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) for var in ("CONTEXT_DIR", "DEBUG_DIR", "MODEL", "ITER2", "FILTER", "NO_ADJUDICATE", "DIFF_INTERSECT", "EXCLUDE_MEDIUM", "MAX_TURNS"): @@ -95,7 +99,7 @@ def test_every_agentic_stage_gets_only_the_read_tools(sdk, tmp_path): # investigate, second investigate pass, refute assert len(sdk) == 3 for opts in sdk: - assert opts["extra_args"] == READ_ONLY + assert opts["extra_args"] == {**READ_ONLY, **NOT_SAVED} assert opts["allowed_tools"] == ["Read", "Grep", "Glob"] assert "permission_mode" not in opts @@ -104,7 +108,8 @@ def test_single_turn_sdk_review_gets_no_tools(sdk): schema = {"type": "object", "properties": {}} assert llm._call_claude_via_sdk("review this", schema) is not None assert len(sdk) == 1 - assert sdk[0]["extra_args"] == NO_TOOLS and sdk[0]["allowed_tools"] == [] + assert sdk[0]["extra_args"] == {**NO_TOOLS, **NOT_SAVED} + assert sdk[0]["allowed_tools"] == [] # What Claude Code prints, before exiting 1, on a machine whose administrator @@ -137,9 +142,9 @@ def test_agentic_review_runs_where_the_strict_mcp_flag_is_refused(managed_mcp, t # The refused start's line is not what child_stderr is there to count. assert "agentic_fallback" not in metrics and "child_stderr" not in metrics refused, ran = managed_mcp - assert [o["extra_args"] for o in refused] == [READ_ONLY] + assert [o["extra_args"] for o in refused] == [{**READ_ONLY, **NOT_SAVED}] # investigate, second investigate pass, refute - assert [o["extra_args"] for o in ran] == [READ_ONLY_NO_MCP] * 3 + assert [o["extra_args"] for o in ran] == [{**READ_ONLY_NO_MCP, **NOT_SAVED}] * 3 for opts in ran: assert opts["allowed_tools"] == ["Read", "Grep", "Glob"] @@ -148,11 +153,11 @@ def test_single_turn_sdk_review_runs_where_the_strict_mcp_flag_is_refused(manage schema = {"type": "object", "properties": {}} assert llm._call_claude_via_sdk("review this", schema) is not None refused, ran = managed_mcp - assert [o["extra_args"] for o in refused] == [NO_TOOLS] - assert [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] + assert [o["extra_args"] for o in refused] == [{**NO_TOOLS, **NOT_SAVED}] + assert [o["extra_args"] for o in ran] == [{**NO_TOOLS_NO_MCP, **NOT_SAVED}] # The refusal is remembered for the rest of the hook process. assert llm._call_claude_via_sdk("review this", schema) is not None - assert len(refused) == 1 and ran[-1]["extra_args"] == NO_TOOLS_NO_MCP + assert len(refused) == 1 and ran[-1]["extra_args"] == {**NO_TOOLS_NO_MCP, **NOT_SAVED} def test_other_start_failures_are_not_retried(sdk, monkeypatch, tmp_path): @@ -167,7 +172,7 @@ def test_other_start_failures_are_not_retried(sdk, monkeypatch, tmp_path): assert guidance is None and vulns == [] assert metrics["agentic_fallback"] == "investigate:RuntimeError" assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is None - assert [o["extra_args"] for o in sdk] == [READ_ONLY, NO_TOOLS] + assert [o["extra_args"] for o in sdk] == [{**READ_ONLY, **NOT_SAVED}, {**NO_TOOLS, **NOT_SAVED}] def test_reviews_started_together_are_each_started_again(managed_mcp): @@ -192,7 +197,7 @@ def test_reviews_started_together_are_each_started_again(managed_mcp): for t in threads: t.join(20) assert len(results) == 2 and None not in results - assert len(refused) == 2 and [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] * 2 + assert len(refused) == 2 and [o["extra_args"] for o in ran] == [{**NO_TOOLS_NO_MCP, **NOT_SAVED}] * 2 def test_review_rows_say_when_the_flag_was_left_out(managed_mcp, capsys): @@ -205,3 +210,63 @@ def test_review_rows_say_when_the_flag_was_left_out(managed_mcp, capsys): assert "strict_mcp_off" not in row() assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is not None assert row()["strict_mcp_off"] == 1 + + +# What a Claude Code older than --no-session-persistence prints, before exiting 1. +UNKNOWN = "error: unknown option '--no-session-persistence'" + + +@pytest.fixture +def old_cli(sdk, monkeypatch): + """The stand-in SDK's inner CLI now refuses --no-session-persistence + and, once that is gone, --strict-mcp-config: one flag per start, as + Claude Code does. Gives the options of the refused starts and of the + ones that ran.""" + answer = sys.modules["claude_agent_sdk"].query + refused = [] + + async def query(prompt, options): + args = options.kwargs["extra_args"] + line = (UNKNOWN if "no-session-persistence" in args + else REFUSAL if "strict-mcp-config" in args else None) + if line: + refused.append(options.kwargs) + options.kwargs["stderr"](line) + raise RuntimeError("Command failed with exit code 1") + async for msg in answer(prompt, options): + yield msg + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + return refused, sdk + + +def test_agentic_review_runs_where_both_flags_are_refused(old_cli, tmp_path): + _, vulns, metrics = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"]) + assert len(vulns) == 1 + assert "agentic_fallback" not in metrics and "child_stderr" not in metrics + refused, ran = old_cli + assert [o["extra_args"] for o in refused] == [{**READ_ONLY, **NOT_SAVED}, READ_ONLY] + assert [o["extra_args"] for o in ran] == [READ_ONLY_NO_MCP] * 3 + + +def test_single_turn_sdk_review_runs_where_both_flags_are_refused(old_cli): + schema = {"type": "object", "properties": {}} + assert llm._call_claude_via_sdk("review this", schema) is not None + refused, ran = old_cli + assert [o["extra_args"] for o in refused] == [{**NO_TOOLS, **NOT_SAVED}, NO_TOOLS] + assert [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] + # Both refusals are remembered for the rest of the hook process. + assert llm._call_claude_via_sdk("review this", schema) is not None + assert len(refused) == 2 and ran[-1]["extra_args"] == NO_TOOLS_NO_MCP + + +def test_a_flag_refused_again_after_it_was_left_out_is_not_retried(sdk, monkeypatch): + async def query(prompt, options): + sdk.append(options.kwargs) + options.kwargs["stderr"](UNKNOWN) + raise RuntimeError("Command failed with exit code 1") + yield + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is None + assert [o["extra_args"] for o in sdk] == [{**NO_TOOLS, **NOT_SAVED}, NO_TOOLS] diff --git a/plugins/security-guidance/tests/test_sdk_install_timeout.py b/plugins/security-guidance/tests/test_sdk_install_timeout.py new file mode 100644 index 00000000..92edde46 --- /dev/null +++ b/plugins/security-guidance/tests/test_sdk_install_timeout.py @@ -0,0 +1,228 @@ +"""A `pip install` that is killed leaves nothing in the system temp dir. + +pip keeps each wheel it downloads in a `pip-unpack-*` folder under the temp +dir and removes it only on a normal exit. The bootstrap kills pip at its +timeout, so on a slow connection every attempt left a download behind, and +attempts repeat while the SDK is missing. See #6979. +""" +import os +import subprocess +import sys +import time + +import pytest + +import ensure_agent_sdk as boot +from test_sdk_bootstrap_switches import SWITCHES + +pytestmark = pytest.mark.skipif(sys.version_info < (3, 10), + reason="bootstrap stops before the install") + +# Stands in for pip: downloads "a wheel" the way pip does, says where, then +# either hangs (a slow connection) or exits without cleaning up. +_STAND_IN_PIP = """ +import sys, tempfile, time +d = tempfile.mkdtemp(prefix="pip-unpack-") +open(d + "/claude_agent_sdk-0.0.0-py3-none-any.whl", "wb").write(b"x" * 4096) +open(sys.argv[2], "a").write(d + "\\n") +if sys.argv[1] == "hang": + time.sleep(120) +""" + + +class Install: + """Empty state dir, no SDK anywhere. `python -m venv` is skipped and + `pip install` is the stand-in above: in "hang" mode it is killed once it + has downloaded, as subprocess.run does at the timeout.""" + + def __init__(self, tmp_path): + self.state = tmp_path / "state" + self.systmp = tmp_path / "systmp" + self.systmp.mkdir() + self.mode = "hang" + self.calls = [] + self._script = tmp_path / "stand_in_pip.py" + self._script.write_text(_STAND_IN_PIP) + self._log = tmp_path / "downloads.txt" + self._real_run = subprocess.run + + def downloads(self): + """The folders the stand-in downloaded into, one per install.""" + return self._log.read_text().split("\n")[:-1] if self._log.exists() else [] + + def run(self, cmd, **kwargs): + cmd = [str(c) for c in cmd] + if cmd[1:3] == ["-m", "venv"]: + return subprocess.CompletedProcess(cmd, 0, b"", b"") + if cmd[1:4] != ["-m", "pip", "install"]: + return self._real_run(cmd, **kwargs) + self.calls.append(cmd) + stand_in = [sys.executable, str(self._script), self.mode, str(self._log)] + if self.mode != "hang": + return self._real_run(stand_in, **kwargs) + before = len(self.downloads()) + proc = subprocess.Popen(stand_in, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + cwd=kwargs.get("cwd"), env=kwargs.get("env")) + deadline = time.time() + 60 + while len(self.downloads()) == before and time.time() < deadline: + time.sleep(0.02) + proc.kill() + proc.wait() + raise subprocess.TimeoutExpired(cmd, kwargs["timeout"]) + + +@pytest.fixture +def install(tmp_path, monkeypatch): + for name in SWITCHES + ("PYTHONPATH",): + monkeypatch.delenv(name, raising=False) + inst = Install(tmp_path) + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(inst.state)) + for name in ("TMPDIR", "TEMP", "TMP"): + monkeypatch.setenv(name, str(inst.systmp)) + monkeypatch.setattr(boot, "_sdk_on_syspath", lambda: False) + monkeypatch.setattr(boot, "_near_git_repo", lambda: True) + monkeypatch.setattr(boot.subprocess, "run", inst.run) + return inst + + +def _left_in(folder): + return sorted(p.name for p in folder.iterdir()) if folder.is_dir() else [] + + +def _downloaded_under(inst, folder): + return [os.path.realpath(d).startswith(os.path.realpath(folder) + os.sep) + for d in inst.downloads()] + + +def test_timed_out_install_leaves_no_download_behind(install): + assert boot.main() == (boot.BUILD_FAILED, "pip", "subprocess_timeout") + assert _downloaded_under(install, install.state / "pip-tmp") == [True] + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_repeated_timeouts_do_not_add_up(install): + for _ in range(3): + boot._build_via_target(install.state) + assert len(install.downloads()) == 3 + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_fallback_install_is_covered_too(install): + assert boot._build_via_target(install.state) == ( + boot.BUILD_FAILED, "pip_target", "subprocess_timeout") + assert "--target" in install.calls[0] + assert _downloaded_under(install, install.state / "pip-tmp") == [True] + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_finished_install_is_cleaned_up_as_well(install): + install.mode = "exit" + assert boot.main()[0] == boot.BUILT + assert len(install.downloads()) == 1 + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def _leave_folder(install, name, age): + folder = install.state / "pip-tmp" / name + (folder / "pip-unpack-abc").mkdir(parents=True) + (folder / "pip-unpack-abc" / "half.whl").write_bytes(b"x" * 4096) + then = time.time() - age + os.utime(folder, (then, then)) + + +def test_folder_of_a_killed_bootstrap_is_removed_by_a_later_run(install): + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + # An attempt that is still running keeps its folder. + _leave_folder(install, "tmprunning", 30) + boot._sweep_pip_temp(install.state) + assert _left_in(install.state / "pip-tmp") == ["tmprunning"] + + +def test_sweep_runs_even_when_nothing_is_installed_this_time(install, monkeypatch): + """Otherwise a folder left just before the SDK got installed stays for good.""" + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + monkeypatch.setattr(boot, "_target_sdk_importable", lambda state_dir: True) + assert boot.main()[0] == boot.NOOP_TARGET + assert install.calls == [] + assert _left_in(install.state / "pip-tmp") == [] + + +@pytest.mark.parametrize("switch", ["SECURITY_GUIDANCE_DISABLE=1", "ENABLE_CODE_SECURITY_REVIEW=0"]) +def test_sweep_runs_with_reviews_switched_off(install, monkeypatch, switch): + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + monkeypatch.setenv(*switch.split("=")) + assert boot.main()[0] == boot.SKIP_REVIEWS_OFF + assert _left_in(install.state / "pip-tmp") == [] + + +def test_install_still_runs_when_the_folder_cannot_be_made(install): + install.mode = "exit" + install.state.mkdir() + (install.state / "pip-tmp").write_text("in the way") + assert boot._build_via_target(install.state)[0] == boot.BUILT_TARGET + assert _downloaded_under(install, install.systmp) == [True] + + +def test_pip_timeout_starts_a_cooldown(install): + assert boot.main()[0] == boot.BUILD_FAILED + # The next attempts (every SessionStart, and every 5 minutes from the + # tool hooks) do not download the SDK again. + outcome = boot.main() + assert outcome == (boot.SKIP_COOLDOWN, "", "") + assert len(install.calls) == 1 + assert boot._install_context_metrics(outcome[0], install.state) == {"sdk_timeout_cooldown": 1} + + +def test_timeout_of_the_fallback_install_starts_it_too(install): + boot._build_via_target(install.state) + assert boot._timeout_cooldown_remaining(install.state) > 0 + + +def test_timeout_cooldown_is_shorter_than_the_signal_kill_one(install): + boot.main() + assert boot._cooldown_remaining(install.state) == 0 + assert 0 < boot._timeout_cooldown_remaining(install.state) <= 3600 + then = time.time() - boot.PIP_TIMEOUT_COOLDOWN_SEC - 60 + os.utime(install.state / "agent-sdk-venv.timeout", (then, then)) + install.mode = "exit" + assert boot.main()[0] == boot.BUILT + assert len(install.calls) == 2 + + +def test_slow_venv_creation_does_not_start_it(install, monkeypatch): + def run(cmd, **kwargs): + if [str(c) for c in cmd][1:3] == ["-m", "venv"]: + raise subprocess.TimeoutExpired(cmd, kwargs["timeout"]) + return install.run(cmd, **kwargs) + monkeypatch.setattr(boot.subprocess, "run", run) + assert boot.main() == (boot.BUILD_FAILED, "venv", "subprocess_timeout") + assert boot._timeout_cooldown_remaining(install.state) == 0 + + +def test_signal_kill_cooldown_is_not_counted_as_a_timeout(install): + boot._write_cooldown(install.state) + boot._write_cooldown(install.state, boot._PIP_TIMEOUT_MARKER) + outcome = boot.main()[0] + assert outcome == boot.SKIP_COOLDOWN + assert "sdk_timeout_cooldown" not in boot._install_context_metrics(outcome, install.state) + + +def test_count_belongs_to_the_run_that_skipped(install): + boot.main() + assert boot.main()[0] == boot.SKIP_COOLDOWN + install.mode = "exit" + (install.state / "agent-sdk-venv.timeout").unlink() + outcome = boot.main()[0] + assert outcome == boot.BUILT + assert "sdk_timeout_cooldown" not in boot._install_context_metrics(outcome, install.state) + + +def test_marker_from_the_future_does_not_stretch_the_cooldown(install): + boot._write_cooldown(install.state, boot._PIP_TIMEOUT_MARKER) + ahead = time.time() + 6 * 3600 + os.utime(install.state / "agent-sdk-venv.timeout", (ahead, ahead)) + assert boot._timeout_cooldown_remaining(install.state) == boot.PIP_TIMEOUT_COOLDOWN_SEC diff --git a/plugins/security-guidance/tests/test_secret_renames.py b/plugins/security-guidance/tests/test_secret_renames.py new file mode 100644 index 00000000..7d4e38fb --- /dev/null +++ b/plugins/security-guidance/tests/test_secret_renames.py @@ -0,0 +1,149 @@ +"""A tracked file renamed away from a secret-shaped name stays out of the +Stop review, however the rename reached git.""" +import errno +import os +import subprocess + +import pytest + +from conftest import ( + GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, +) + +import diffstate +import gitutil + +SECRET_BODY = "".join(f"KEY_{i}=SECRET_VALUE_{i}\n" for i in range(30)) +EDIT = "import os\nos.system(input())\n" + + +def _repo(tmp_path): + return make_repo(tmp_path / "repo", {"deploy_rsa": SECRET_BODY, "app.py": "x = 1\n"}) + + +def _sent(stub_api): + return "".join(stub_api.bodies) + + +def _rename(repo, how): + if how == "moved": + os.rename(repo / "deploy_rsa", repo / "settings.py") + return + git(repo, "mv", "deploy_rsa", "settings.py") + if how == "committed": + git(repo, "commit", "-qm", "rename") + elif how == "amended": + git(repo, "commit", "-q", "--amend", "-m", "init, renamed") + # Edited after the commit, so the file is still part of the turn. + with open(repo / "settings.py", "a") as f: + f.write("KEY_NEW=SECRET_VALUE_NEW\n") + + +@pytest.mark.parametrize("how", ["moved", "staged", "committed", "amended"]) +def test_stop_review_leaves_the_renamed_file_out(tmp_path, hook_env, stub_api, how): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), hook_env) + _rename(repo, how) + (repo / "app.py").write_text(EDIT) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert m.get("skip_reason") is None, m + assert m.get("files_reviewed") == 1 + # A plain mv is not a rename to git: the old name is listed as deleted. + assert m.get("secret_renamed") == (None if how == "moved" else 1) + assert "os.system" in _sent(stub_api) + assert "SECRET_VALUE" not in _sent(stub_api) + + +def test_stop_review_with_nothing_but_the_rename_sends_nothing(tmp_path, hook_env, stub_api): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), hook_env) + git(repo, "mv", "deploy_rsa", "settings.py") + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + assert metrics_of(stdout).get("skip_reason") == 7 + assert stub_api.bodies == [] + + +def test_commit_review_leaves_the_renamed_file_out(tmp_path, hook_env, stub_api): + repo = _repo(tmp_path) + git(repo, "mv", "deploy_rsa", "settings.py") + _sha, out = commit_file(repo, "app.py", EDIT) + run_hook(bash_payload(repo, "git commit -m change", stdout=out), hook_env) + assert "os.system" in _sent(stub_api) + assert "SECRET_VALUE" not in _sent(stub_api) + + +@pytest.fixture +def git_env(monkeypatch): + """The suite's git settings for calls made in this process.""" + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + monkeypatch.setattr(gitutil, "_secret_rename_origins", {}) + monkeypatch.setattr(diffstate, "_secret_rename_origins", gitutil._secret_rename_origins) + + +def test_listings_are_unchanged_and_note_the_secret_origin(tmp_path, git_env): + repo = make_repo(tmp_path / "repo", { + "deploy_rsa": SECRET_BODY, "old name.py": SECRET_BODY + "x = 1\n", + "gone.py": "x = 1\n", "edit.py": "x = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + git(repo, "mv", "old name.py", "new name.py") + git(repo, "rm", "-q", "gone.py") + (repo / "edit.py").write_text("x = 2\n") + names = {"settings.py", "new name.py", "gone.py", "edit.py"} + assert gitutil._git_name_only(str(repo), "HEAD") == names + assert gitutil._secret_rename_origins == {"settings.py": "deploy_rsa"} + gitutil._secret_rename_origins.clear() + assert gitutil._git_status_porcelain(str(repo)) == (names, set()) + assert gitutil._secret_rename_origins == {"settings.py": "deploy_rsa"} + + +def test_review_set_gains_only_the_origin_of_a_reviewed_file(tmp_path, git_env): + repo = make_repo(tmp_path / "repo", { + "deploy_rsa": SECRET_BODY, "old.py": SECRET_BODY + "x = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + git(repo, "mv", "old.py", "new.py") + paths, _base, root, _untracked, metrics = diffstate.compute_v2_review_set(str(repo), None, None, {}) + assert sorted(os.path.relpath(p, root) for p in paths) == ["deploy_rsa", "new.py", "settings.py"] + assert metrics["dirty_now_count"] == 2 and metrics["review_set_count"] == 3 + assert metrics["secret_renamed"] == 1 + + +def test_origin_still_pairs_beside_a_nested_repo_and_a_split_path_list( + tmp_path, git_env, monkeypatch): + repo = make_repo(tmp_path / "repo", {"deploy_rsa": SECRET_BODY, "app.py": "x = 1\n"}) + make_repo(repo / "nested", {"inner.py": "y = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + (repo / "app.py").write_text(EDIT) + (repo / "a_much_longer_module_name.py").write_text("y = 1\n") + (repo / "another_quite_long_module_name.py").write_text("y = 2\n") + for i in range(20): + (repo / f"note{i:02d}.txt").write_text("x\n") + paths, base, root, untracked, metrics = diffstate.compute_v2_review_set(str(repo), None, None, {}) + names = [os.path.relpath(p, root) for p in paths] + assert "deploy_rsa" in names and "settings.py" in names + assert not any(n.startswith("nested") for n in names) + assert metrics["secret_renamed"] == 1 + + # The OS refuses the one command that holds every path, so the paths go + # out in several: the old name has to be in the one with the new name. + real_popen = subprocess.Popen + limit = sum(len(a) + 1 for a in gitutil.GIT_CMD) + 220 + diffs = [] + + def popen(cmd, *args, **kwargs): + if sum(len(a) + 1 for a in cmd) > limit: + raise OSError(errno.E2BIG, "Argument list too long") + if "diff" in cmd: + diffs.append(cmd) + return real_popen(cmd, *args, **kwargs) + + monkeypatch.setattr(subprocess, "Popen", popen) + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 80) + diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert len(diffs) > 1 and all("deploy_rsa" in c for c in diffs) + reviewed = gitutil.parse_diff_into_files(diff) + assert sorted(f for f, _ in reviewed) == [ + "a_much_longer_module_name.py", "another_quite_long_module_name.py", "app.py"] + assert "SECRET_VALUE" not in "".join(d for _, d in reviewed) diff --git a/plugins/security-guidance/tests/test_slow_prompt_metrics.py b/plugins/security-guidance/tests/test_slow_prompt_metrics.py index fa947507..827b4642 100644 --- a/plugins/security-guidance/tests/test_slow_prompt_metrics.py +++ b/plugins/security-guidance/tests/test_slow_prompt_metrics.py @@ -10,7 +10,7 @@ import gitutil from conftest import git, make_repo, metrics_of, run_hook, ups_payload SLOW = 1.2 -STASH = '*"stash create"*' +SNAPSHOT = '*"add -u"*' MOUNTS = ( "25 30 8:32 / / rw,relatime - ext4 /dev/sdc rw\n" "60 25 0:50 / /mnt/c rw,noatime - 9p C:\\134 rw,aname=drivers\n" @@ -42,7 +42,7 @@ def _slow(hook_env, tmp_path, match): def test_slow_capture_reports_where_the_time_went(repo, hook_env, tmp_path): - rc, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH)) + rc, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, SNAPSHOT)) m = metrics_of(out) assert rc == 0 assert m["ups_ms"] >= SLOW * 1000 @@ -60,7 +60,7 @@ def test_slow_untracked_listing_is_told_apart(repo, hook_env, tmp_path): def test_slow_prompt_with_stop_review_off_lists_nothing(repo, hook_env, tmp_path): - env = {**_slow(hook_env, tmp_path, STASH), "ENABLE_STOP_REVIEW": "0"} + env = {**_slow(hook_env, tmp_path, SNAPSHOT), "ENABLE_STOP_REVIEW": "0"} m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) assert m["ups_baseline_ms"] >= SLOW * 1000 assert m["ups_untracked_ms"] == 0 @@ -90,7 +90,7 @@ def test_failed_snapshot_is_flagged(repo, hook_env, tmp_path): shim = tmp_path / "bin" shim.mkdir() (shim / "git").write_text( - f'#!/bin/sh\ncase "$*" in {STASH}) sleep {SLOW}; exit 1;; esac\n' + f'#!/bin/sh\ncase "$*" in *"write-tree"*) sleep {SLOW}; exit 1;; esac\n' f'exec "{shutil.which("git")}" "$@"\n') (shim / "git").chmod(0o755) env = {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"} @@ -110,14 +110,14 @@ def test_slow_launcher_is_reported_on_a_fast_prompt(repo, hook_env): def test_other_hosts_get_no_output(repo, hook_env, tmp_path): - env = {k: v for k, v in _slow(hook_env, tmp_path, STASH).items() + env = {k: v for k, v in _slow(hook_env, tmp_path, SNAPSHOT).items() if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT")} env["SECURITY_GUIDANCE_PORTABLE_OUTPUT"] = "1" assert run_hook(ups_payload(str(repo)), env)[1].strip() == "" def test_row_holds_no_path_and_valid_keys(repo, hook_env, tmp_path): - _, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH)) + _, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, SNAPSHOT)) assert str(repo) not in out and str(tmp_path) not in out metrics = json.loads(out)["metrics"] assert all(re.fullmatch(r"[a-z][a-z0-9_]{0,39}", k) for k in metrics) @@ -128,7 +128,7 @@ def test_slow_capture_saves_the_same_baseline(repo, hook_env, tmp_path): (repo / "app.py").write_text("print('changed')\n") (repo / "new.txt").write_text("untracked\n") states = [] - for name, env in (("fast", hook_env), ("slow", _slow(hook_env, tmp_path, STASH))): + for name, env in (("fast", hook_env), ("slow", _slow(hook_env, tmp_path, SNAPSHOT))): d = tmp_path / name d.mkdir() env = {k: v for k, v in env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} diff --git a/plugins/security-guidance/tests/test_state_dir_mode.py b/plugins/security-guidance/tests/test_state_dir_mode.py new file mode 100644 index 00000000..d55afaf9 --- /dev/null +++ b/plugins/security-guidance/tests/test_state_dir_mode.py @@ -0,0 +1,107 @@ +"""The state dir holds the reviewer's venv, review logs and session state. It +is created, and kept, with access for its user alone, whatever the umask.""" +import os +import stat +import sys + +import pytest + +import _base +import session_state + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes") + + +@pytest.fixture +def loose_umask(): + old = os.umask(0o002) + yield + os.umask(old) + + +def _mode(p): + return stat.S_IMODE(os.stat(p).st_mode) + + +def test_new_state_dir_is_owner_only(tmp_path, monkeypatch, loose_umask): + d = tmp_path / "state" + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d)) + session_state.save_state("s1", {"k": 1}) + assert _mode(d) == 0o700 + + +def test_existing_default_state_dir_is_narrowed(tmp_path, monkeypatch, loose_umask): + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + d = tmp_path / ".claude" / "security" + d.mkdir(parents=True) + os.chmod(d, 0o775) + _base.make_state_dir() + assert _mode(d) == 0o700 + + +def test_existing_folder_named_by_the_user_is_left_alone(tmp_path, monkeypatch): + d = tmp_path / "team" + d.mkdir() + os.chmod(d, 0o2775) + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d)) + _base.make_state_dir() + assert _mode(d) == 0o2775 + + +def test_a_link_at_the_default_state_dir_is_left_alone(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + shared = tmp_path / "shared" + shared.mkdir() + os.chmod(shared, 0o775) + (tmp_path / ".claude").mkdir() + os.symlink(shared, tmp_path / ".claude" / "security") + _base.make_state_dir() + assert _mode(shared) == 0o775 + + +def test_other_folders_are_left_alone(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False) + logs = tmp_path / "logs" + logs.mkdir() + os.chmod(logs, 0o755) + _base.make_state_dir(str(logs)) + assert _mode(logs) == 0o755 + + +def test_debug_log_in_the_working_directory_leaves_the_state_dir_alone(tmp_path, monkeypatch): + d = tmp_path / "state" + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d)) + with pytest.raises(OSError): + _base.make_state_dir("") + assert not d.exists() + + +@pytest.mark.parametrize("nofollow", [True, False]) +def test_in_place_save_replaces_a_symlink(tmp_path, monkeypatch, nofollow): + d = tmp_path / "state" + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d)) + monkeypatch.setattr(session_state, "_RENAME_INTO_PLACE", False) + if not nofollow: # the Windows path: no O_NOFOLLOW + monkeypatch.delattr(os, "O_NOFOLLOW") + _base.make_state_dir() + target = tmp_path / "elsewhere.txt" + target.write_text("keep\n") + state_file = session_state.get_state_file("s1") + os.symlink(target, state_file) + session_state.save_state("s1", {"k": 1}) + assert target.read_text() == "keep\n" + assert not os.path.islink(state_file) + assert session_state.load_state("s1").get("k") == 1 + + +def test_in_place_save_creates_an_owner_only_file(tmp_path, monkeypatch, loose_umask): + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + monkeypatch.setattr(session_state, "_RENAME_INTO_PLACE", False) + session_state.save_state("s1", {"k": 1}) + assert _mode(session_state.get_state_file("s1")) == 0o600 + assert session_state.load_state("s1").get("k") == 1 diff --git a/plugins/security-guidance/tests/test_stop_scope_metrics.py b/plugins/security-guidance/tests/test_stop_scope_metrics.py index c65103b6..7ae6dc64 100644 --- a/plugins/security-guidance/tests/test_stop_scope_metrics.py +++ b/plugins/security-guidance/tests/test_stop_scope_metrics.py @@ -29,13 +29,13 @@ def _turn(repo, env, edits=(), during=None): return _stop(repo, env) -def _no_stash_env(tmp_path, hook_env): - """An env whose `git stash` fails, like a snapshot that could not be taken.""" +def _no_write_tree_env(tmp_path, hook_env): + """An env whose `git write-tree` fails, like a snapshot that could not be taken.""" bindir = tmp_path / "bin" bindir.mkdir() shim = bindir / "git" shim.write_text( - '#!/bin/sh\nfor a in "$@"; do [ "$a" = stash ] && exit 1; done\n' + '#!/bin/sh\nfor a in "$@"; do [ "$a" = write-tree ] && exit 1; done\n' f'exec "{shutil.which("git")}" "$@"\n') shim.chmod(0o755) return {**hook_env, "PATH": f"{bindir}{os.pathsep}{hook_env['PATH']}"} @@ -127,7 +127,7 @@ class TestSnapshot: def test_failed_snapshot_is_counted(self, hook_env, workspace, tmp_path): ws, repo = workspace (repo / "app.py").write_text(VULN_PY) # uncommitted work from before the turn - m = _turn(repo, _no_stash_env(tmp_path, hook_env), edits=[ws / "notes.md"]) + m = _turn(repo, _no_write_tree_env(tmp_path, hook_env), edits=[ws / "notes.md"]) assert m["files_reviewed"] == 1 and m["review_scope"] == 130001 # The next prompt takes a real snapshot and the flag is gone. m = _turn(repo, hook_env, edits=[repo / "app.py"], @@ -138,7 +138,7 @@ class TestSnapshot: def test_flag_follows_the_snapshot_taken_after_a_finding(self, hook_env, stub_api, workspace, tmp_path): _, repo = workspace - broken = _no_stash_env(tmp_path, hook_env) + broken = _no_write_tree_env(tmp_path, hook_env) stub_api.vulns = [STUB_VULN] # Good snapshot at the prompt; the one taken after the finding fails. run_hook(ups_payload(repo), hook_env) diff --git a/plugins/security-guidance/tests/test_temp_index_cleanup.py b/plugins/security-guidance/tests/test_temp_index_cleanup.py index 4ac19ea5..9b103a71 100644 --- a/plugins/security-guidance/tests/test_temp_index_cleanup.py +++ b/plugins/security-guidance/tests/test_temp_index_cleanup.py @@ -220,7 +220,7 @@ class TestOwnerGone: @pytest.mark.skipif(os.name == "nt", reason="uses signals and a /bin/sh git shim") class TestHookProcessKilled: def _start_slow_hook(self, tmp_path, hook_env, repo): - """Start a UserPromptSubmit hook whose `git stash create` hangs, and + """Start a UserPromptSubmit hook whose snapshot `git add -u` hangs, and return once its index copy exists.""" import shutil import subprocess @@ -233,7 +233,7 @@ class TestHookProcessKilled: shim = bindir / "git" shim.write_text( "#!/bin/sh\n" - 'case "$*" in *"stash create"*) [ -n "$SLOW_GIT" ] && exec sleep 60;; esac\n' + 'case "$*" in *"add -u"*) [ -n "$SLOW_GIT" ] && exec sleep 60;; esac\n' f'exec "{real_git}" "$@"\n' ) shim.chmod(0o755) diff --git a/plugins/security-guidance/tests/test_unmatched_bash_metric.py b/plugins/security-guidance/tests/test_unmatched_bash_metric.py new file mode 100644 index 00000000..8933bbd1 --- /dev/null +++ b/plugins/security-guidance/tests/test_unmatched_bash_metric.py @@ -0,0 +1,162 @@ +"""Bash hook starts that match no commit or push are counted; nothing changes.""" +import itertools +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from conftest import HOOK_SCRIPT, STUB_VULN, VULN_PY, bash_payload, commit_file, metrics_of, run_hook + +import security_reminder_hook as hook + +WEIGHT = hook._UNMATCHED_BASH_SAMPLE +SHELL_PATTERN = "|".join(f"*{a}*{b}*" for a, b in hook._SHELL_PRECHECK_PAIRS) + + +def _call_id(sampled): + for n in itertools.count(): + tool_use_id = f"toolu_{n}" + if hook._unmatched_bash_sampled({"tool_use_id": tool_use_id}) is sampled: + return tool_use_id + + +def _raw(command, stdout="ok"): + return json.dumps(bash_payload("/w", command, stdout=stdout)) + + +def test_unmatched_call_reports_what_a_text_check_would_do(workspace, hook_env): + ws, _ = workspace + loop = bash_payload("/w", "for f in a b; do echo $f; done", tool_use_id=_call_id(True)) + rc, so, se = run_hook(loop, hook_env) + m = metrics_of(so) + assert rc == 0 and se == "" + assert m["bash_no_match"] == WEIGHT and m["precheck_skip"] == WEIGHT and m["pv"] + + # Text mentions pass a text check and still match nothing. + for command, stdout in (("git log --grep commit", ""), ("ls", "run git push next")): + p = bash_payload("/w", command, stdout, tool_use_id=_call_id(True)) + rc, so, se = run_hook(p, hook_env) + m = metrics_of(so) + assert rc == 0 and m["bash_no_match"] == WEIGHT and m["precheck_skip"] == 0 + + +def test_unsampled_call_stays_silent(workspace, hook_env): + loop = "for f in a b; do echo $f; done" + assert run_hook(bash_payload("/w", loop, tool_use_id=_call_id(False)), hook_env) == (0, "", "") + assert run_hook(bash_payload("/w", loop), hook_env) == (0, "", "") # no call id + + +def test_other_hosts_get_no_row(workspace, hook_env): + markers = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "SECURITY_GUIDANCE_PORTABLE_OUTPUT") + env = {k: v for k, v in hook_env.items() if k not in markers} + env["PLUGIN_ROOT"] = "/p" + p = bash_payload("/w", "for f in a b; do echo $f; done", tool_use_id=_call_id(True)) + assert run_hook(p, env) == (0, "", "") + + +def test_one_call_in_ten_is_sampled(): + picked = sum(hook._unmatched_bash_sampled({"tool_use_id": f"toolu_{n}"}) for n in range(20000)) + assert 20000 / WEIGHT * 0.85 < picked < 20000 / WEIGHT * 1.15 + assert not hook._unmatched_bash_sampled({}) and not hook._unmatched_bash_sampled({"tool_use_id": 7}) + + +def test_pairs_cover_every_verb_in_the_regexes(): + # A verb added to either regex has to be added to _SHELL_PRECHECK_PAIRS + # and to _commands() below. + assert hook._GIT_COMMIT_RE.pattern.endswith(r"\s+commit\b(?!-)|\bgt\s+(?:create|modify)\b") + assert hook._GIT_PUSH_RE.pattern.endswith(r"\s+push\b|\bgt\s+submit\b)") + + +def _commands(): + """Commands the commit and push regexes match, in the spellings they allow.""" + opts = ["", " -C sub", " -c user.name=x", " -c 'a.b=c d'", " --git-dir=.git", " --no-pager", + " -P", " --namespace=n", " --work-tree .", " -C a -c b=c --no-pager"] + seps = [" ", "\t", " ", "\n"] + heads = ["", "cd x && ", "FOO=1 ", "(", "for i in 1; do ", "echo \"$(", "/usr/bin/", "x=`"] + for head, opt, sep, verb in itertools.product(heads, opts, seps, ["commit", "push"]): + yield f"{head}git{opt}{sep}{verb} -m 'é \"q\" \\ done'" + for head, sep, verb in itertools.product(heads, seps, ["create", "modify", "submit"]): + yield f"{head}gt{sep}{verb} --all" + + +def test_text_check_never_drops_a_reviewed_command(): + matched = [c for c in _commands() if hook._GIT_COMMIT_RE.search(c) or hook._GIT_PUSH_RE.search(c)] + assert len(matched) > 600 + for command in matched: + for ensure_ascii in (True, False): + raw = json.dumps(bash_payload("/w", command), ensure_ascii=ensure_ascii) + assert hook._shell_precheck_passes(raw), command + + +CASES = [ + ("ls -la | head", False), + ("echo commit the git way", False), # wrong order + ("grep -c gt app.py", False), + ("git status && echo 'ready to commit'", True), + ("gt log; echo submit", True), + ("git\tpush", True), + ("digit; echo pushed", True), +] + + +def test_text_check_on_known_strings(): + for command, passes in CASES: + assert hook._shell_precheck_passes(_raw(command)) is passes, command + + +def _working_bash(): + """A bash that runs a script. On Windows that is the one shipped with + git: the `bash` on PATH there can be the WSL launcher, which is not one.""" + found = [] + git = shutil.which("git") + if sys.platform == "win32" and git: + root = Path(git).resolve().parent.parent + found += [root / "bin" / "bash.exe", root / "usr" / "bin" / "bash.exe"] + if shutil.which("bash"): + found.append(Path(shutil.which("bash"))) + for bash in found: + try: + r = subprocess.run([str(bash), "-c", "echo ok"], capture_output=True, timeout=30) + except (OSError, subprocess.SubprocessError): + continue + if r.returncode == 0 and r.stdout.strip() == b"ok": + return str(bash) + return None + + +def test_text_check_agrees_with_the_shell_pattern(): + bash = _working_bash() + if not bash: + pytest.skip("needs a working bash") + script = f'input=$(cat); case "$input" in {SHELL_PATTERN}) echo pass ;; *) echo skip ;; esac' + for command, _ in CASES: + raw = _raw(command) + r = subprocess.run([bash, "-c", script], input=raw.encode(), capture_output=True, timeout=30) + assert r.stdout.strip() in (b"pass", b"skip"), r.stderr + assert (r.stdout.strip() == b"pass") is hook._shell_precheck_passes(raw), command + + +def test_reviewed_command_a_text_check_would_drop_is_flagged(workspace, hook_env, stub_api): + ws, repo = workspace + stub_api.vulns = [STUB_VULN] + _, out = commit_file(repo, "app.py", VULN_PY) + raw = json.dumps(bash_payload(repo, "git commit -m change", out)) + # Same command, with one letter written as a JSON escape. + raw = raw.replace('"git commit -m change"', '"git \\u0063ommit -m change"') + assert json.loads(raw)["tool_input"]["command"] == "git commit -m change" + if hook._shell_precheck_passes(raw): + pytest.skip("the temporary path itself passes the text check") + r = subprocess.run([sys.executable, str(HOOK_SCRIPT)], input=raw, capture_output=True, + text=True, env=hook_env, timeout=120) + m = metrics_of(r.stdout) + assert m["precheck_miss"] == 1 and m.get("commit_review") is True + assert list(m).index("precheck_miss") < 3 # ahead of the row's own keys + + # The ordinary spelling carries no flag. + _, out = commit_file(repo, "b.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), hook_env) + m = metrics_of(so) + assert m.get("commit_review") is True and "precheck_miss" not in m diff --git a/plugins/security-guidance/tests/test_windows_cli_lookup.py b/plugins/security-guidance/tests/test_windows_cli_lookup.py new file mode 100644 index 00000000..3afea8e5 --- /dev/null +++ b/plugins/security-guidance/tests/test_windows_cli_lookup.py @@ -0,0 +1,279 @@ +"""Which Claude Code the Agent SDK is told to start on Windows.""" +import os +import subprocess +import sys +import types + +import pytest + +from conftest import HOOKS_DIR + +import _base +import llm + +VAR = "NoDefaultCurrentDirectoryInExePath" +windows_only = pytest.mark.skipif(os.name != "nt", reason="needs Windows path rules") + + +def put(folder, name="claude.exe"): + folder.mkdir(parents=True, exist_ok=True) + (folder / name).write_text("") + return str(folder / name) + + +def set_path(monkeypatch, *entries): + monkeypatch.setenv("PATH", os.pathsep.join(str(e) for e in entries)) + + +@pytest.fixture +def win(monkeypatch, tmp_path): + """llm as on Windows: an empty home and PATH, no CLI named in the + environment, and a working directory that has a claude.exe of its own.""" + ns = types.SimpleNamespace(home=tmp_path / "home", repo=tmp_path / "repo", tools=tmp_path / "tools") + for d in (ns.home, ns.repo, ns.tools): + d.mkdir() + put(ns.repo) + monkeypatch.setattr(llm, "_WINDOWS", True) + monkeypatch.setattr(llm, "_gateway_cli", None) + monkeypatch.setattr(_base, "DEBUG_LOG_FILE", str(tmp_path / "log.txt")) + monkeypatch.setenv("HOME", str(ns.home)) + monkeypatch.setenv("USERPROFILE", str(ns.home)) # "~" on Windows + for var in ("SG_AGENTIC_CLI_PATH", "CLAUDE_CODE_EXECPATH", "CLAUDE_PROJECT_DIR"): + monkeypatch.delenv(var, raising=False) + set_path(monkeypatch) + monkeypatch.chdir(ns.repo) + return ns + + +class TestUsersOwnCli: + def test_native_installers_folder_comes_first(self, win, monkeypatch): + put(win.tools) + set_path(monkeypatch, win.tools) + native = put(win.home / ".local" / "bin") + assert llm._windows_user_cli() == native + + @pytest.mark.parametrize("spelling", [ + pytest.param("{}", id="plain"), + pytest.param('"{}"', id="quoted"), + pytest.param("{}" + os.sep, id="trailing-separator"), + ]) + def test_found_on_path(self, win, monkeypatch, spelling): + put(win.tools) + set_path(monkeypatch, win.tools / "empty", spelling.format(win.tools)) + assert os.path.samefile(llm._windows_user_cli(), win.tools / "claude.exe") + + def test_batch_file_is_not_used(self, win, monkeypatch): + put(win.tools, "claude.cmd") + set_path(monkeypatch, win.tools) + assert llm._windows_user_cli() is None + + @pytest.mark.parametrize("entry", [ + pytest.param("", id="empty"), + pytest.param(".", id="dot"), + pytest.param("{repo}", id="full-path"), + pytest.param("{repo}" + os.sep, id="trailing-separator"), + pytest.param(os.path.join("..", "repo"), id="relative"), + ]) + def test_working_directory_is_not_searched(self, win, monkeypatch, entry): + set_path(monkeypatch, entry.format(repo=win.repo)) + assert llm._windows_user_cli() is None + + def test_search_continues_past_the_working_directory(self, win, monkeypatch): + exe = put(win.tools) + set_path(monkeypatch, ".", win.repo, win.tools) + assert llm._windows_user_cli() == exe + + def test_relative_entry_is_skipped(self, win, monkeypatch): + put(win.tools) + set_path(monkeypatch, os.path.join("..", "tools")) + assert llm._windows_user_cli() is None + + @pytest.mark.parametrize("home", ["~", "", "home"]) + def test_home_that_is_not_a_full_path_is_skipped(self, win, monkeypatch, home): + put(win.repo / home / ".local" / "bin") + monkeypatch.setattr(llm.os.path, "expanduser", lambda p: home) + assert llm._windows_user_cli() is None + + def test_project_root_is_not_searched_from_a_subfolder(self, win, monkeypatch): + (win.repo / "sub").mkdir() + monkeypatch.chdir(win.repo / "sub") + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(win.repo).replace(os.sep, "/")) + set_path(monkeypatch, win.repo) + assert llm._windows_user_cli() is None + + def test_link_to_the_working_directory_is_not_searched(self, win, monkeypatch, tmp_path): + try: + if os.name == "nt": + import _winapi + _winapi.CreateJunction(str(win.repo), str(tmp_path / "link")) + else: + os.symlink(win.repo, tmp_path / "link", target_is_directory=True) + except OSError: + pytest.skip("cannot make a link here") + set_path(monkeypatch, tmp_path / "link") + assert llm._windows_user_cli() is None + + @pytest.mark.parametrize("project", [False, True]) + def test_folder_inside_the_project_is_not_searched(self, win, monkeypatch, project): + put(win.repo / ".venv" / "Scripts") + if project: + (win.repo / "sub").mkdir() + monkeypatch.chdir(win.repo / "sub") + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(win.repo)) + set_path(monkeypatch, win.repo / ".venv" / "Scripts") + assert llm._windows_user_cli() is None + + def test_folder_that_only_shares_a_prefix_is_found(self, win, monkeypatch, tmp_path): + exe = put(tmp_path / "repo-tools") + set_path(monkeypatch, tmp_path / "repo-tools") + assert llm._windows_user_cli() == exe + + def test_session_above_the_home_folder_still_finds_the_native_install(self, win, monkeypatch): + native = put(win.home / ".local" / "bin") + monkeypatch.chdir(win.home.parent) + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(win.home.parent)) + assert llm._windows_user_cli() == native + + def test_tools_under_the_home_folder_are_found(self, win, monkeypatch): + exe = put(win.home / "AppData" / "tool") + monkeypatch.chdir(win.home) + set_path(monkeypatch, win.home / "AppData" / "tool") + assert llm._windows_user_cli() == exe + + @windows_only + def test_entries_without_a_drive_or_a_root_are_skipped(self, win, monkeypatch): + put(win.tools) + drive, rest = os.path.splitdrive(str(win.tools)) + set_path(monkeypatch, rest, rest.replace("\\", "/"), drive + os.path.relpath(str(win.tools))) + assert llm._windows_user_cli() is None + + @windows_only + def test_other_spellings_of_the_working_directory_are_skipped(self, win, monkeypatch): + import ctypes + short = ctypes.create_unicode_buffer(1024) + ctypes.windll.kernel32.GetShortPathNameW(str(win.repo), short, 1024) + repo = str(win.repo) + set_path(monkeypatch, repo.upper(), repo.replace("\\", "/"), "\\\\?\\" + repo, short.value or repo) + assert llm._windows_user_cli() is None + + +class TestFixedPaths: + @pytest.fixture + def installed_as_on_linux(self, win, monkeypatch): + monkeypatch.setattr(llm.os.path, "isfile", lambda p: p.endswith("/bin/claude")) + + def test_not_used_on_windows(self, installed_as_on_linux): + assert llm._user_cli_path() is None + + def test_used_elsewhere(self, installed_as_on_linux, monkeypatch): + monkeypatch.setattr(llm, "_WINDOWS", False) + assert llm._user_cli_path().endswith("/.local/bin/claude") + + +@pytest.fixture +def sdk(monkeypatch, tmp_path): + """Stand-in for claude_agent_sdk, installed in tmp_path, that records the + options of each spawn in .spawned.""" + class ResultMessage: + subtype, usage, total_cost_usd = "success", {}, 0.0 + structured_output = {"findings": []} + + async def query(prompt, options): + yield ResultMessage() + + mod = types.ModuleType("claude_agent_sdk") + mod.spawned = [] + mod.ClaudeAgentOptions = lambda **kwargs: mod.spawned.append(kwargs) + mod.AssistantMessage = type("AssistantMessage", (), {}) + mod.ResultMessage, mod.query = ResultMessage, query + mod.__file__ = str(tmp_path / "site" / "claude_agent_sdk" / "__init__.py") + mod.bundled = str(tmp_path / "site" / "claude_agent_sdk" / "_bundled" / "claude.exe") + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + monkeypatch.setenv("SECURITY_REVIEW_MODEL", "opus") + return mod + + +def bundle(tmp_path): + return put(tmp_path / "site" / "claude_agent_sdk" / "_bundled") + + +REVIEWS = [ + pytest.param(lambda: llm.agentic_review(os.getcwd(), [("a.py", "+x = 1\n")], ["a.py"]), id="agentic"), + pytest.param(lambda: llm._call_claude_via_sdk("review this", {"type": "object"}), id="cloud-provider"), +] + + +@pytest.mark.parametrize("review", REVIEWS) +class TestWhatTheSdkIsTold: + @staticmethod + def told(sdk): + assert sdk.spawned + return {o["cli_path"] for o in sdk.spawned} + + def test_bundled_cli_before_the_users(self, win, sdk, tmp_path, review): + put(win.home / ".local" / "bin") + bundle(tmp_path) + review() + assert self.told(sdk) == {sdk.bundled} + + def test_users_cli_when_nothing_is_bundled(self, win, sdk, monkeypatch, review): + tolerant = [] + monkeypatch.setattr(llm, "_tolerate_unknown_sdk_messages", lambda: tolerant.append(1)) + set_path(monkeypatch, ".", win.tools) + cli = put(win.tools) + review() + assert self.told(sdk) == {cli} and tolerant + + def test_full_path_is_named_when_no_cli_exists(self, win, sdk, review): + review() + assert self.told(sdk) == {sdk.bundled} + + def test_named_cli_is_used_as_named(self, win, sdk, tmp_path, monkeypatch, review): + bundle(tmp_path) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "X:\\my\\claude.exe") + review() + assert self.told(sdk) == {"X:\\my\\claude.exe"} + + def test_empty_name_is_no_name(self, win, sdk, tmp_path, monkeypatch, review): + put(win.home / ".local" / "bin") + bundle(tmp_path) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + review() + assert self.told(sdk) == {sdk.bundled} + + def test_sdk_chooses_off_windows(self, win, sdk, tmp_path, monkeypatch, review): + monkeypatch.setattr(llm, "_WINDOWS", False) + monkeypatch.setattr(llm, "_user_cli_path", lambda: None) + bundle(tmp_path) + review() + assert self.told(sdk) == {None} + + +def test_empty_name_is_no_name_off_windows(monkeypatch): + monkeypatch.setattr(llm, "_WINDOWS", False) + assert llm._cli_for_sdk("") is None + + +def test_sdk_module_without_a_file_still_gets_a_full_path(win, sdk): + del sdk.__file__ + assert os.path.isabs(llm._cli_for_sdk(None)) + + +class TestSearchOrderVariable: + @staticmethod + def after_import(os_name, **env): + code = (f"import os; os.name = {os_name!r}; import _base; " + f"print(os.environ.get({VAR!r}))") + base = {k: v for k, v in os.environ.items() if k.upper() != VAR.upper()} + return subprocess.run([sys.executable, "-c", code], cwd=HOOKS_DIR, env={**base, **env}, + capture_output=True, text=True, check=True).stdout.strip() + + def test_set_on_windows_when_absent(self): + assert self.after_import("nt") == "1" + + def test_existing_value_is_kept(self): + assert self.after_import("nt", **{VAR: "0"}) == "0" + + @pytest.mark.skipif(os.name == "nt", reason="checks that the variable is not set off Windows") + def test_not_set_elsewhere(self): + assert self.after_import(os.name) == "None" |
