summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-22 00:12:11 +0000
committerClaude <noreply@anthropic.com>2026-10-22 00:12:11 +0000
commitde9e075c828f2c4438d26571dc6046472381a085 (patch)
treec3183dd3a3dbd529c517c18500a0dd95c533760c /plugins/security-guidance/tests
parent437cb57a9d19329a8e6ef3ed79e19adb45e83d50 (diff)
parentaf59ee3a1051a29dda4a2e7a2af221aa457ae08b (diff)
Merge branch 'main' into mhegazy/sg-diff-seen-countmhegazy/sg-diff-seen-count
Keeps both sides in emit_metrics: diff_seen stays after the other review tail keys, and the launcher probe keys stay after everything else.
Diffstat (limited to 'plugins/security-guidance/tests')
-rw-r--r--plugins/security-guidance/tests/test_baseline_lookup.py145
-rw-r--r--plugins/security-guidance/tests/test_launcher_probe_timing.py196
-rw-r--r--plugins/security-guidance/tests/test_nested_repos.py265
-rw-r--r--plugins/security-guidance/tests/test_pattern_fired_metrics.py90
-rw-r--r--plugins/security-guidance/tests/test_patterns_file_shape.py116
-rw-r--r--plugins/security-guidance/tests/test_stop_review_paths.py319
-rw-r--r--plugins/security-guidance/tests/test_tls_store_unreadable_cert.py387
7 files changed, 1518 insertions, 0 deletions
diff --git a/plugins/security-guidance/tests/test_baseline_lookup.py b/plugins/security-guidance/tests/test_baseline_lookup.py
new file mode 100644
index 00000000..d6d2e34d
--- /dev/null
+++ b/plugins/security-guidance/tests/test_baseline_lookup.py
@@ -0,0 +1,145 @@
+import os
+
+import pytest
+
+from conftest import git, make_repo, run_hook, ups_payload
+
+import diffstate
+
+OLD = "import os\nos.system(cmd)\n"
+FILE = "packages/app/main.py"
+
+
+def write_payload(cwd, file_path, content, session_id="s1"):
+ return {
+ "session_id": session_id,
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Write",
+ "tool_input": {"file_path": str(file_path), "content": content},
+ "tool_response": {},
+ "cwd": str(cwd),
+ }
+
+
+@pytest.fixture
+def repo(tmp_path):
+ repo = make_repo(tmp_path / "ws" / "mono")
+ # Bytes, so the committed text is OLD on every platform: write_text turns
+ # "\n" into "\r\n" on Windows.
+ for name in (FILE, "top.py"):
+ (repo / name).parent.mkdir(parents=True, exist_ok=True)
+ (repo / name).write_bytes(OLD.encode())
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "-m", "add files")
+ return repo
+
+
+def _symlink(link, target):
+ try:
+ link.symlink_to(target, target_is_directory=target.is_dir())
+ except (OSError, NotImplementedError):
+ if os.name != "nt":
+ raise
+ pytest.skip("this Windows account cannot create symlinks")
+
+
+@pytest.fixture
+def linked(repo, tmp_path):
+ """The same repo, reached through a symlinked parent directory."""
+ _symlink(tmp_path / "alias", tmp_path / "ws")
+ return tmp_path / "alias" / "mono"
+
+
+@pytest.fixture
+def baseline(repo, monkeypatch):
+ sha = git(repo, "rev-parse", "HEAD").strip()
+ monkeypatch.setattr(diffstate, "load_baseline_sha", lambda _sid: sha)
+ return sha
+
+
+class TestBaselineFileContent:
+ """`git show <rev>:<path>` reads the path from the repo root, so the lookup
+ must not depend on where in the repo the session was started."""
+
+ @pytest.mark.parametrize("session_dir", ["", "packages", "packages/app"])
+ def test_found_from_any_session_directory(self, repo, baseline, session_dir):
+ cwd = str(repo / session_dir)
+ assert diffstate.get_baseline_file_content("s1", str(repo / FILE), cwd) == OLD
+ assert diffstate.get_baseline_file_content("s1", str(repo / "top.py"), cwd) == OLD
+
+ def test_native_separators_are_not_passed_to_git(self, repo, baseline, monkeypatch):
+ # What os.path.relpath returns on Windows.
+ monkeypatch.setattr(diffstate.os, "sep", "\\")
+ monkeypatch.setattr(diffstate.os.path, "relpath",
+ lambda _p, _start: "packages\\app\\main.py")
+ assert diffstate.get_baseline_file_content("s1", str(repo / FILE), str(repo)) == OLD
+
+ def test_file_not_in_baseline(self, repo, baseline):
+ (repo / "packages" / "app" / "new.py").write_text(OLD)
+ for p in ("packages/app/new.py", "packages/gone/main.py"):
+ assert diffstate.get_baseline_file_content(
+ "s1", str(repo / p), str(repo / "packages")) is None
+
+ def test_file_outside_the_session_repo(self, repo, baseline, tmp_path):
+ outside = tmp_path / "ws" / "main.py"
+ outside.write_text(OLD)
+ assert diffstate.get_baseline_file_content("s1", str(outside), str(repo)) is None
+ # A second checkout of the same repo shares its objects; its files are
+ # still not this session's baseline.
+ git(repo, "worktree", "add", "-q", str(tmp_path / "ws" / "other"), "-b", "other")
+ twin = tmp_path / "ws" / "other" / FILE
+ assert twin.read_bytes().replace(b"\r\n", b"\n") == OLD.encode()
+ for cwd in (repo, repo / "packages" / "app"):
+ assert diffstate.get_baseline_file_content("s1", str(twin), str(cwd)) is None
+
+ @pytest.mark.parametrize("session_dir", ["", "packages/app"])
+ def test_found_through_a_symlinked_directory(self, repo, baseline, linked, session_dir):
+ """macOS reaches /tmp and /var through symlinks, so the tool's path and
+ the session directory can spell the same repo differently."""
+ real, alias = repo / session_dir, linked / session_dir
+ for cwd, path in ((real, linked / FILE), (alias, repo / FILE), (alias, linked / FILE)):
+ assert diffstate.get_baseline_file_content("s1", str(path), str(cwd)) == OLD
+
+ def test_session_directory_is_a_symlink_into_the_repo(self, repo, baseline, tmp_path):
+ _symlink(tmp_path / "app", repo / "packages" / "app")
+ for path in (tmp_path / "app" / "main.py", repo / FILE):
+ assert diffstate.get_baseline_file_content(
+ "s1", str(path), str(tmp_path / "app")) == OLD
+
+ def test_committed_content_not_the_working_copy(self, repo, baseline):
+ (repo / FILE).write_text("print('rewritten')\n")
+ assert diffstate.get_baseline_file_content(
+ "s1", str(repo / FILE), str(repo / "packages" / "app")) == OLD
+
+
+@pytest.mark.parametrize("session_dir", ["", "packages/app"])
+def test_rewrite_through_a_symlinked_path_does_not_re_flag(repo, linked, hook_env, session_dir):
+ """The session runs in the real directory and the tool names the file
+ through the symlink, as under /tmp on macOS."""
+ cwd = repo / session_dir
+ env = {**hook_env, "CLAUDE_PROJECT_DIR": str(cwd)}
+ run_hook(ups_payload(cwd), env)
+
+ _rc, stdout, _err = run_hook(write_payload(cwd, linked / FILE, OLD + "print('x')\n"), env)
+ assert "additionalContext" not in stdout
+
+ _rc, stdout, _err = run_hook(
+ write_payload(cwd, linked / FILE, OLD + "import pickle\npickle.loads(data)\n"), env)
+ assert "pickle" in stdout and "os.system" not in stdout
+
+
+@pytest.mark.parametrize("session_dir", ["", "packages/app"])
+def test_rewrite_does_not_re_flag_code_that_was_already_there(repo, hook_env, session_dir):
+ """A full-file Write that keeps a pre-existing risky call is not a new
+ finding, whether the session runs at the repo root or below it."""
+ cwd = repo / session_dir
+ env = {**hook_env, "CLAUDE_PROJECT_DIR": str(cwd)}
+ run_hook(ups_payload(cwd), env)
+
+ _rc, stdout, _err = run_hook(write_payload(cwd, repo / FILE, OLD + "print('x')\n"), env)
+ assert "additionalContext" not in stdout
+
+ _rc, stdout, _err = run_hook(
+ write_payload(cwd, repo / FILE, OLD + "import pickle\npickle.loads(data)\n"), env)
+ assert "additionalContext" in stdout
+ assert "pickle" in stdout and "os.system" not in stdout
diff --git a/plugins/security-guidance/tests/test_launcher_probe_timing.py b/plugins/security-guidance/tests/test_launcher_probe_timing.py
new file mode 100644
index 00000000..69b867a6
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_probe_timing.py
@@ -0,0 +1,196 @@
+"""sg-python.sh times its interpreter probes and the hooks report slow ones.
+
+Measurement only: the launcher still waits for every probe and still picks
+the interpreter it picked before.
+
+The slow interpreter is a shell wrapper around the real one, so these tests
+need a POSIX shell.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR, edit_payload, metrics_of, run_hook, stop_payload
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+
+SHIM = HOOKS_DIR / "sg-python.sh"
+BASH = shutil.which("bash") or "/bin/bash"
+REAL = os.path.realpath(sys.executable)
+
+
+def _bash_major():
+ try:
+ return int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"],
+ capture_output=True, text=True, timeout=30).stdout)
+ except (OSError, ValueError, subprocess.SubprocessError):
+ return 0
+
+
+BASH5 = sys.platform != "win32" and _bash_major() >= 5
+
+# Prints what the launcher handed over, then its stdin.
+HOOK = (
+ "import os, sys\n"
+ "print('max=' + os.environ.get('SG_LAUNCHER_PROBE_MAX_MS', ''))\n"
+ "print('total=' + os.environ.get('SG_LAUNCHER_PROBE_MS', ''))\n"
+ "print('name=' + os.environ.get('SG_NAME', ''))\n"
+ "print('stdin=' + sys.stdin.read())\n"
+)
+
+WRAPPER = """#!{bash}
+# Answers the launcher's `-c` probe after DELAY seconds; RC != 0 fails it.
+if [ "${{1:-}}" = "-c" ]; then
+ sleep {delay}
+ [ {rc} -eq 0 ] || exit {rc}
+fi
+SG_NAME={name} exec '{real}' "$@"
+"""
+
+
+def _python(bindir, name, delay=0, rc=0):
+ bindir.mkdir(parents=True, exist_ok=True)
+ p = bindir / name
+ p.write_text(WRAPPER.format(bash=BASH, delay=delay, rc=rc, name=name, real=REAL))
+ p.chmod(0o755)
+
+
+def _run(bindir, script, extra_env=None, shim=SHIM):
+ env = {"PATH": f"{bindir}{os.pathsep}/usr/bin{os.pathsep}/bin", "HOME": os.environ.get("HOME", "/")}
+ env.update(extra_env or {})
+ r = subprocess.run([BASH, str(shim), str(script)], input="payload", capture_output=True,
+ text=True, timeout=60, env=env)
+ assert r.returncode == 0, r.stderr
+ return dict(line.split("=", 1) for line in r.stdout.splitlines())
+
+
+@pytest.fixture
+def script(tmp_path):
+ p = tmp_path / "hook.py"
+ p.write_text(HOOK)
+ return p
+
+
+@pytest.fixture
+def bindir(tmp_path):
+ """A PATH entry with only what the tests put there (plus sleep)."""
+ return tmp_path / "bin"
+
+
+def _only_these(bindir):
+ # Hide the system interpreters: PATH is bindir plus /usr/bin:/bin, so every
+ # name the launcher tries gets an entry here, failing unless a test set it.
+ for name in ("python3.13", "python3.12", "python3.11", "python3.10", "python3", "python", "py"):
+ if not (bindir / name).exists():
+ _python(bindir, name, rc=1)
+
+
+@pytest.mark.skipif(not BASH5, reason="millisecond clock needs bash 5")
+def test_fast_probes_are_timed_in_milliseconds(bindir, script):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ assert out["name"] == "python3" and out["stdin"] == "payload"
+ assert 0 < int(out["max"]) <= int(out["total"])
+
+
+def test_slow_probe_is_waited_for_and_measured(bindir, script):
+ _python(bindir, "python3", delay=2.2)
+ _python(bindir, "python")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ # Still the first name that answers, however long it took.
+ assert out["name"] == "python3" and out["stdin"] == "payload"
+ assert 2000 <= int(out["max"]) < 10000
+ assert int(out["total"]) >= int(out["max"])
+
+
+def test_slow_failing_probe_counts_towards_the_wait(bindir, script):
+ _python(bindir, "python3", delay=2.2, rc=49)
+ _python(bindir, "python")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ assert out["name"] == "python"
+ assert int(out["max"]) >= 2000
+
+
+def test_inherited_values_are_not_reported_again(bindir, script):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script, {"SG_LAUNCHER_PROBE_MAX_MS": "999999", "SG_LAUNCHER_PROBE_MS": "999999"})
+ assert out["max"] != "999999" and out["total"] != "999999"
+
+
+@pytest.fixture
+def whole_second_shim(tmp_path):
+ """The launcher as bash 3.2 runs it: no EPOCHREALTIME, only SECONDS."""
+ src = SHIM.read_text()
+ assert 'case "${EPOCHREALTIME:-}" in' in src
+ p = tmp_path / "sg-python-coarse.sh"
+ p.write_text(src.replace('case "${EPOCHREALTIME:-}" in', 'case "" in'))
+ return p
+
+
+def test_whole_second_clock_ignores_fast_probes(bindir, script, whole_second_shim):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script, shim=whole_second_shim)
+ assert out["name"] == "python3"
+ # A probe of a few ms can straddle a second; that is not reported as 1 s.
+ assert out["max"] == "" and out["total"] == ""
+
+
+def test_whole_second_clock_measures_slow_probes(bindir, script, whole_second_shim):
+ _python(bindir, "python3", delay=2.2)
+ _only_these(bindir)
+ out = _run(bindir, script, shim=whole_second_shim)
+ assert out["name"] == "python3"
+ assert int(out["max"]) in (2000, 3000) and int(out["total"]) >= int(out["max"])
+
+
+@pytest.mark.parametrize("slowest,total,expected", [
+ ("4200", "4350", {"launcher_probe_ms": 4350, "launcher_probe_max_ms": 4200}),
+ ("900", "1500", {"launcher_probe_ms": 1500, "launcher_probe_max_ms": 900}),
+ ("999", "999", {}),
+ ("86400000", "86400000", {"launcher_probe_ms": 3600000, "launcher_probe_max_ms": 3600000}),
+ ("5000", "5", {}),
+ ("", "", {}),
+ ("junk", "5", {}),
+])
+def test_stop_hook_reports_only_slow_probes(hook_env, workspace, slowest, total, expected):
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": slowest, "SG_LAUNCHER_PROBE_MS": total}
+ rc, out, err = run_hook(stop_payload(repo), env)
+ m = metrics_of(out)
+ assert m is not None, err
+ assert {k: v for k, v in m.items() if k.startswith("launcher_probe")} == expected
+
+
+def test_launcher_keys_come_last(hook_env, workspace):
+ """Claude Code keeps the first 20 keys, so these never displace another."""
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": "4200", "SG_LAUNCHER_PROBE_MS": "4350"}
+ rc, out, err = run_hook(stop_payload(repo), env)
+ assert list(metrics_of(out))[-2:] == ["launcher_probe_ms", "launcher_probe_max_ms"]
+
+
+def test_edit_hook_reports_slow_probes_on_pattern_rows(hook_env, workspace):
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": "4200", "SG_LAUNCHER_PROBE_MS": "4350"}
+ payload = edit_payload(repo, repo / "app.py", new_string="import os\nos.system('ls ' + x)\n")
+ rc, out, err = run_hook(payload, env)
+ m = metrics_of(out)
+ assert m is not None and "rule_id" in m, (out, err)
+ assert m["launcher_probe_ms"] == 4350 and m["launcher_probe_max_ms"] == 4200
+
+
+def test_values_are_read_once(monkeypatch):
+ import _base
+ monkeypatch.setenv("SG_LAUNCHER_PROBE_MAX_MS", "7000")
+ monkeypatch.setenv("SG_LAUNCHER_PROBE_MS", "7100")
+ assert _base.launcher_probe_metrics() == {"launcher_probe_ms": 7100, "launcher_probe_max_ms": 7000}
+ assert "SG_LAUNCHER_PROBE_MS" not in os.environ and _base.launcher_probe_metrics() == {}
diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py
index cb010018..3c93a580 100644
--- a/plugins/security-guidance/tests/test_nested_repos.py
+++ b/plugins/security-guidance/tests/test_nested_repos.py
@@ -9,6 +9,7 @@ from conftest import (
stop_payload, ups_payload,
)
+import diffstate
import gitutil
@@ -160,3 +161,267 @@ def test_commit_range_diff_does_not_enter_nested_repo(outer, marker, git_env, tm
assert not ext_marker.exists() and not marker.exists()
assert "lib.py" not in (out or "")
+
+
+def _record_during_turn(outer, marker, commit):
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "app.py").write_text(VULN_PY)
+ git(outer, "add", "-A")
+ if commit:
+ git(outer, "commit", "-q", "-m", "wip")
+ marker.unlink(missing_ok=True) # only what the hooks run counts
+
+
+@pytest.mark.parametrize("finding", [False, True], ids=["no-finding", "finding"])
+@pytest.mark.parametrize("commit", [False, True], ids=["staged", "committed"])
+def test_nested_repo_recorded_during_the_turn_filter_not_run(
+ outer, marker, hook_env, stub_api, commit, finding):
+ stub_api.vulns = [STUB_VULN] if finding else []
+ ran_at = []
+
+ def hook(name, payload):
+ rc, out, err = run_hook(payload, hook_env)
+ # 2 is a Stop that hands a finding back.
+ assert rc == (2 if finding and name.startswith("stop") else 0), (name, out, err)
+ if marker.exists():
+ ran_at.append(name)
+ marker.unlink()
+
+ hook("prompt 1", ups_payload(outer))
+ _record_during_turn(outer, marker, commit)
+ hook("stop 1", stop_payload(outer))
+ hook("prompt 2", ups_payload(outer))
+ (outer / "app.py").write_text(VULN_PY + "# one more edit\n")
+ hook("stop 2", stop_payload(outer))
+ hook("prompt 3", ups_payload(outer))
+
+ assert ran_at == []
+ assert stub_api.calls # the turn's own edit is still reviewed
+
+
+@pytest.mark.skipif(os.name == "nt", reason="'*' is not allowed in Windows file names")
+@pytest.mark.parametrize("commit", [False, True], ids=["staged", "committed"])
+def test_glob_shaped_file_name_beside_recorded_nested_repo(
+ outer, marker, hook_env, stub_api, commit):
+ assert run_hook(ups_payload(outer), hook_env)[0] == 0
+ _record_during_turn(outer, marker, commit)
+ (outer / "vendor" / "p*").write_text("x = 1\n")
+ (outer / "new.py").write_text(VULN_PY)
+
+ rc, out, err = run_hook(stop_payload(outer), hook_env)
+
+ assert not marker.exists(), marker.read_text()
+ assert stub_api.calls, (rc, out, err)
+
+
+def _index_copies():
+ return [f for _, _, files in os.walk(tempfile.gettempdir()) for f in files
+ if f.startswith(gitutil._TEMP_INDEX_PREFIX)]
+
+
+def _index_entries(repo, env=None):
+ return subprocess.run(
+ ["git", "ls-files", "-s"], cwd=repo, capture_output=True, text=True,
+ env=env, check=True,
+ ).stdout
+
+
+@pytest.mark.parametrize("subdir", ["", "src"])
+def test_index_copy_has_no_gitlinks_and_real_index_is_unchanged(
+ outer, marker, git_env, subdir):
+ (outer / "src").mkdir()
+ (outer / "src" / "a.py").write_text("x = 1\n")
+ _add_nested_repo(outer, "src/third party/dep", marker)
+ _record_nested_repo(outer, marker)
+ real = outer / ".git" / "index"
+ before = (real.read_bytes(), real.stat().st_mtime_ns)
+
+ with gitutil._temp_index(str(outer / subdir), untracked_paths=[]) as env:
+ assert env is not None
+ assert len(_index_copies()) == 1
+ copy = _index_entries(outer, env)
+ copy_mtime = os.stat(env["GIT_INDEX_FILE"]).st_mtime_ns
+
+ assert "160000" not in copy
+ assert "app.py" in copy and "src/a.py" in copy
+ assert copy_mtime == before[1]
+ assert (real.read_bytes(), real.stat().st_mtime_ns) == before
+ assert _index_entries(outer).count("160000") == 2
+ assert not marker.exists()
+
+
+def test_baseline_and_diff_with_recorded_nested_repo(outer, marker, git_env):
+ nested = _record_nested_repo(outer, marker)
+ (nested / "lib.py").write_text("print('abc')\n")
+ (outer / "app.py").write_text(VULN_PY)
+ (outer / "new.py").write_text("x = 1\n")
+
+ baseline = diffstate.capture_git_baseline(str(outer))
+ diff = gitutil.get_git_diff(str(outer), "HEAD", untracked_paths=["new.py"])
+ since = gitutil.get_git_diff(str(outer), baseline, untracked_paths=["new.py"])
+ # The snapshot has no entry for the nested repository; the real index does.
+ tracked_since = gitutil.get_git_diff(str(outer), baseline, untracked_paths=[])
+ names_since = gitutil._git_name_only(str(outer), baseline)
+
+ # The baseline is a snapshot with the edit in it, not HEAD.
+ assert baseline and baseline != git(outer, "rev-parse", "HEAD").strip()
+ assert "app.py" in diff and "new.py" in diff and "vendor/pkg" not in diff
+ assert "new.py" in since and "app.py" not in since and "vendor/pkg" not in since
+ assert tracked_since == "" and "vendor/pkg" not in names_since
+ assert not marker.exists()
+
+
+def test_whole_tree_index_copy_with_recorded_nested_repo(outer, marker, git_env):
+ nested = _record_nested_repo(outer, marker)
+ (nested / "lib.py").write_text("print('abc')\n")
+ (outer / "new.py").write_text("x = 1\n")
+
+ with gitutil._temp_index(str(outer)) as env:
+ assert env is not None
+ copy = _index_entries(outer, env)
+
+ assert "new.py" in copy and "160000" not in copy
+ assert not marker.exists()
+
+
+def test_no_index_copy_when_gitlinks_cannot_be_removed(
+ outer, marker, git_env, monkeypatch):
+ _record_nested_repo(outer, marker)
+ (outer / "app.py").write_text(VULN_PY)
+ real_run = subprocess.run
+
+ def run(cmd, *a, **kw):
+ if "update-index" in cmd:
+ return subprocess.CompletedProcess(cmd, 1, b"", b"no")
+ return real_run(cmd, *a, **kw)
+
+ monkeypatch.setattr(gitutil.subprocess, "run", run)
+
+ with gitutil._temp_index(str(outer), untracked_paths=[]) as env:
+ assert env is None
+ # Without the copy the baseline is HEAD.
+ assert diffstate.capture_git_baseline(str(outer)) == git(outer, "rev-parse", "HEAD").strip()
+ assert diffstate.last_baseline_fail == 2
+ assert not marker.exists()
+ assert _index_copies() == []
+
+
+@pytest.mark.skipif(os.name == "nt", reason="':' and '*' are not allowed in Windows file names")
+def test_untracked_file_name_is_not_read_as_a_pattern(outer, git_env):
+ name = ":(glob)**"
+ (outer / name).write_text("x = 1\n")
+ (outer / "other.py").write_text("x = 2\n")
+
+ with gitutil._temp_index(str(outer), [name]) as env:
+ copy = _index_entries(outer, 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."""
+ nested = _record_nested_repo(outer, marker)
+ # Moved, not deleted: git's object files are read-only on Windows.
+ nested.rename(outer.parent / "moved-away")
+ nested.mkdir()
+ (outer / "app.py").write_text(VULN_PY)
+
+ with gitutil._temp_index(str(outer), untracked_paths=[]) as 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
+
+
+def test_gitlinks_listed_by_a_git_without_sparse_listing(outer, marker, git_env, monkeypatch):
+ _record_nested_repo(outer, marker)
+ real_popen = subprocess.Popen
+ seen = []
+
+ def popen(cmd, *a, **kw):
+ if "ls-files" in cmd and "-z" in cmd: # the plugin's own listing
+ seen.append("--sparse" in cmd)
+ if "--sparse" in cmd:
+ cmd = [*gitutil.GIT_CMD, "ls-files", "--no-such-option"]
+ return real_popen(cmd, *a, **kw)
+
+ monkeypatch.setattr(gitutil.subprocess, "Popen", popen)
+ monkeypatch.setattr(gitutil, "_ls_files_sparse", True)
+
+ for _ in range(2):
+ with gitutil._temp_index(str(outer), untracked_paths=[]) as env:
+ assert "160000" not in _index_entries(outer, env)
+
+ assert seen == [True, False, False]
+
+
+def test_no_index_copy_when_the_listing_cannot_be_watched(outer, marker, git_env, monkeypatch):
+ _record_nested_repo(outer, marker)
+
+ def no_thread(self):
+ raise RuntimeError("can't start new thread")
+
+ monkeypatch.setattr(gitutil.threading.Timer, "start", no_thread)
+
+ with gitutil._temp_index(str(outer), untracked_paths=[]) as env:
+ assert env is None
+ assert _index_copies() == []
+
+
+def _listings(monkeypatch):
+ """Counts the plugin's own `git ls-files` runs."""
+ real_popen = subprocess.Popen
+ seen = []
+
+ def popen(cmd, *a, **kw):
+ if "ls-files" in cmd and "-z" in cmd:
+ seen.append(cmd)
+ return real_popen(cmd, *a, **kw)
+
+ monkeypatch.setattr(gitutil.subprocess, "Popen", popen)
+ return seen
+
+
+def test_index_without_gitlinks_is_not_listed(outer, git_env, monkeypatch):
+ for i in range(300):
+ (outer / f"f{i}.py").write_text(f"x = {i}\n")
+ git(outer, "add", "-A")
+ seen = _listings(monkeypatch)
+
+ with gitutil._temp_index(str(outer), untracked_paths=[]) as env:
+ assert env is not None
+
+ assert seen == []
+
+
+@pytest.mark.parametrize("setup", [
+ [],
+ [("config", "index.version", "4")],
+ [("config", "core.splitIndex", "true")],
+ [("config", "feature.manyFiles", "true")],
+], ids=["default", "index-v4", "split-index", "many-files"])
+def test_gitlink_found_in_every_index_format(outer, marker, git_env, monkeypatch, setup):
+ for args in setup:
+ git(outer, *args)
+ for i in range(50):
+ (outer / f"f{i}.py").write_text(f"x = {i}\n")
+ git(outer, "add", "-A")
+ git(outer, "commit", "-q", "-m", "files")
+ nested = _record_nested_repo(outer, marker)
+ # One more index write after the gitlink went in.
+ (outer / "later.py").write_text("x = 1\n")
+ git(outer, "add", "later.py")
+ marker.unlink(missing_ok=True)
+ (nested / "lib.py").write_text("print('abc')\n")
+ (outer / "app.py").write_text(VULN_PY)
+ seen = _listings(monkeypatch)
+
+ with gitutil._temp_index(str(outer), untracked_paths=[]) as env:
+ copy = _index_entries(outer, env)
+ baseline = diffstate.capture_git_baseline(str(outer))
+
+ assert seen and "160000" not in copy and "later.py" in copy
+ assert baseline != git(outer, "rev-parse", "HEAD").strip()
+ assert not marker.exists()
diff --git a/plugins/security-guidance/tests/test_pattern_fired_metrics.py b/plugins/security-guidance/tests/test_pattern_fired_metrics.py
new file mode 100644
index 00000000..c1e31300
--- /dev/null
+++ b/plugins/security-guidance/tests/test_pattern_fired_metrics.py
@@ -0,0 +1,90 @@
+import json
+
+from conftest import (
+ STUB_VULN, edit_payload, metrics_of, run_hook, stop_payload, ups_payload,
+)
+
+from patterns import RuleId
+
+EVAL = 1 << RuleId.EVAL_INJECTION
+SHELL = 1 << RuleId.PYTHON_SUBPROCESS_SHELL
+
+
+def _edit(repo, env, name, content):
+ (repo / name).write_text(content)
+ run_hook(edit_payload(repo, repo / name, content), env)
+
+
+def _turn(repo, env, edits, after=None):
+ run_hook(ups_payload(repo), env)
+ for name, content in edits.items():
+ _edit(repo, env, name, content)
+ for name, content in (after or {}).items():
+ (repo / name).write_text(content)
+ rc, so, se = run_hook(stop_payload(repo), env)
+ return metrics_of(so)
+
+
+class TestFiredRulesReachTheStopRow:
+ def test_clean_review(self, env, gateway, workspace):
+ _, repo = workspace
+ m = _turn(repo, env, {"calc.js": "const v = eval(src)\n"})
+ assert m["vulns_found"] == 0 and "review_ms" in m
+ assert m["warn_fired_mask"] == EVAL
+ assert m["warn_unresolved_mask"] == EVAL
+ assert list(m).index("warn_fired_mask") < 20
+
+ def test_fired_mask_follows_the_unresolved_mask(self, env, gateway, workspace):
+ """A row cut at the key cap loses the fired mask before the
+ unresolved one."""
+ _, repo = workspace
+ gateway.vulns = [STUB_VULN]
+ m = _turn(repo, env, {"calc.js": "const v = eval(src)\n"})
+ keys = list(m)
+ assert keys.index("warn_unresolved_mask") < keys.index("warn_fired_mask")
+ assert m["warn_fixed"] == 0 and m["warn_unresolved"] == 1
+
+ def test_review_with_findings(self, env, gateway, workspace):
+ _, repo = workspace
+ gateway.vulns = [STUB_VULN]
+ m = _turn(repo, env, {"calc.js": "const v = eval(src)\n"})
+ assert m["vulns_found"] == 1
+ assert m["warn_fired_mask"] == EVAL and m["warn_unresolved_mask"] == EVAL
+
+ def test_review_skipped(self, env, gateway, workspace):
+ _, repo = workspace
+ m = _turn(repo, {**env, "ENABLE_STOP_REVIEW": "0"},
+ {"calc.js": "const v = eval(src)\n"})
+ assert m["skipped"] is True
+ assert m["warn_fired_mask"] == EVAL and m["warn_unresolved_mask"] == EVAL
+
+ def test_fixed_rule_is_fired_but_not_unresolved(self, env, gateway, workspace):
+ _, repo = workspace
+ m = _turn(
+ repo, env,
+ {"calc.js": "const v = eval(src)\n",
+ "run.py": "import subprocess\nsubprocess.run(cmd, shell=True)\n"},
+ after={"calc.js": "const v = JSON.parse(src)\n"},
+ )
+ assert m["warn_fired_mask"] == EVAL | SHELL
+ assert m["warn_unresolved_mask"] == SHELL
+
+ def test_no_warning_no_keys(self, env, gateway, workspace):
+ _, repo = workspace
+ m = _turn(repo, env, {"ok.py": "def ok():\n return 1\n"})
+ assert "warn_fired_mask" not in m and "warn_unresolved_mask" not in m
+
+ def test_masks_are_reported_once(self, env, gateway, workspace):
+ _, repo = workspace
+ _turn(repo, env, {"calc.js": "const v = eval(src)\n"})
+ m = _turn(repo, env, {"ok.py": "def ok():\n return 2\n"})
+ assert "warn_fired_mask" not in m and "warn_unresolved_mask" not in m
+
+ def test_user_rule_is_not_counted_as_a_builtin_of_the_same_name(self, env, gateway, workspace):
+ _, repo = workspace
+ (repo / ".claude").mkdir()
+ (repo / ".claude" / "security-patterns.json").write_text(json.dumps({"patterns": [
+ {"rule_name": "eval_injection", "regex": "FORBIDDEN_CALL", "reminder": "no"}]}))
+ m = _turn(repo, {**env, "ENABLE_STOP_REVIEW": "0"}, {"a.py": "FORBIDDEN_CALL()\n"})
+ assert "warn_fired_mask" not in m
+ assert m["warn_fixed"] == 0 and m["warn_unresolved"] == 1
diff --git a/plugins/security-guidance/tests/test_patterns_file_shape.py b/plugins/security-guidance/tests/test_patterns_file_shape.py
new file mode 100644
index 00000000..a63494b6
--- /dev/null
+++ b/plugins/security-guidance/tests/test_patterns_file_shape.py
@@ -0,0 +1,116 @@
+"""A security-patterns file that parses to something other than a mapping is
+skipped on its own; rules from the other locations still load."""
+import json
+
+import pytest
+
+import extensibility
+
+from conftest import run_hook
+
+VALID = {"patterns": [{"rule_name": "demo_rule", "regex": "AKIA[0-9A-Z]{16}",
+ "reminder": "DEMO_RULE_REMINDER"}]}
+
+
+@pytest.fixture
+def project(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.setattr(extensibility, "_user_patterns", [])
+ monkeypatch.setattr(extensibility, "_guidance_block", "")
+ proj = tmp_path / "proj"
+ (proj / ".claude").mkdir(parents=True)
+ (proj / ".claude" / "security-patterns.json").write_text(json.dumps(VALID))
+ return proj
+
+
+def loaded(proj):
+ extensibility.load_for_session(str(proj))
+ return [r["ruleName"] for r in extensibility.user_patterns()]
+
+
+def rule(name="x", **kw):
+ return dict(VALID["patterns"][0], rule_name=name, **kw)
+
+
+WRONG_SHAPE_JSON = [
+ json.dumps([rule()]),
+ "5",
+ '"just a string"',
+ '{"patterns": 5}',
+ '{"patterns": "demo"}',
+ '{"patterns": {"rule_name": "x"}}',
+ '{"patterns": {}}',
+ '{"patterns": null}',
+ "{not json",
+ json.dumps({"patterns": [rule(regex="a{99999999999}")]}),
+]
+
+
+@pytest.mark.parametrize("body", WRONG_SHAPE_JSON)
+def test_wrong_shape_local_json_keeps_the_project_rules(project, body):
+ (project / ".claude" / "security-patterns.local.json").write_text(body)
+ assert loaded(project) == ["user:demo_rule"]
+
+
+@pytest.mark.parametrize("body", [
+ "just a bare scalar\n",
+ "- rule_name: x\n regex: a\n reminder: r\n",
+ "patterns: 5\n",
+ "a: [1\n",
+ "when: 2001-13-45\n",
+])
+def test_wrong_shape_local_yaml_keeps_the_project_rules(project, body):
+ pytest.importorskip("yaml")
+ (project / ".claude" / "security-patterns.local.yaml").write_text(body)
+ assert loaded(project) == ["user:demo_rule"]
+
+
+def test_file_that_is_not_utf8_keeps_the_project_rules(project):
+ body = json.dumps({"patterns": [rule("local_rule")]}).encode("utf-16")
+ (project / ".claude" / "security-patterns.local.json").write_bytes(body)
+ assert loaded(project) == ["user:demo_rule"]
+
+
+@pytest.mark.parametrize("body", ["- a\n- b\n", "patterns: 5\n"])
+def test_unusable_yaml_does_not_hide_the_json_next_to_it(project, body):
+ pytest.importorskip("yaml")
+ (project / ".claude" / "security-patterns.yaml").write_text(body)
+ assert loaded(project) == ["user:demo_rule"]
+
+
+def test_one_bad_rule_does_not_drop_the_rest_of_its_file(project):
+ local = {"patterns": [rule("bad", regex="a{99999999999}"), rule("local_rule")]}
+ (project / ".claude" / "security-patterns.local.json").write_text(json.dumps(local))
+ assert loaded(project) == ["user:demo_rule", "user:local_rule"]
+
+
+def test_rules_from_a_valid_local_file_still_load(project):
+ local = {"patterns": [rule("local_rule")]}
+ (project / ".claude" / "security-patterns.local.json").write_text(json.dumps(local))
+ assert loaded(project) == ["user:demo_rule", "user:local_rule"]
+
+
+def test_wrong_shape_file_is_named_in_the_debug_log(project, monkeypatch):
+ lines = []
+ monkeypatch.setattr(extensibility, "debug_log", lines.append)
+ (project / ".claude" / "security-patterns.local.json").write_text("[1, 2]")
+ assert loaded(project) == ["user:demo_rule"]
+ assert any("security-patterns.local.json" in l and "got list" in l for l in lines)
+
+
+def test_edit_hook_still_warns_with_a_wrong_shape_file_present(project, hook_env):
+ (project / ".claude" / "security-patterns.local.json").write_text("[1, 2]")
+ env = dict(hook_env, HOME=str(project.parent / "home"), CLAUDE_PROJECT_DIR=str(project))
+ env.pop("CLAUDE_CONFIG_DIR", None)
+ payload = {
+ "session_id": "s1", "hook_event_name": "PostToolUse", "tool_name": "Write",
+ "tool_input": {"file_path": str(project / "cfg.py"),
+ "content": "KEY = 'AKIAABCDEFGHIJKLMNOP'\n"},
+ "cwd": str(project), "tool_response": {},
+ }
+ _rc, stdout, stderr = run_hook(payload, env)
+ assert "DEMO_RULE_REMINDER" in stdout + stderr
diff --git a/plugins/security-guidance/tests/test_stop_review_paths.py b/plugins/security-guidance/tests/test_stop_review_paths.py
new file mode 100644
index 00000000..b6f9793c
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_review_paths.py
@@ -0,0 +1,319 @@
+"""The Stop review still runs when the changed paths of a turn do not fit in
+one git command."""
+import errno
+import os
+import subprocess
+import tempfile
+import types
+
+import pytest
+
+from conftest import (
+ GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload,
+ ups_payload,
+)
+
+import diffstate
+import gitutil
+
+GIT_CMD_CHARS = sum(len(a) + 1 for a in gitutil.GIT_CMD)
+
+
+@pytest.fixture
+def git_env(tmp_path, monkeypatch):
+ """Git identity for in-process calls, and a temp dir of our own for the
+ index copies."""
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ monkeypatch.setattr(gitutil, "_path_list_too_long", set())
+ for k, v in GIT_ENV.items():
+ monkeypatch.setenv(k, v)
+
+
+def _more_than_one_command_holds(repo, exts):
+ """3,000 untracked files, cycling through `exts`, whose names add up to
+ more than a single command can carry on any platform (the largest limit
+ is about 2 MB, on Linux)."""
+ deep = repo / ("d" * 180) / ("e" * 180) / ("f" * 180) / ("g" * 180)
+ deep.mkdir(parents=True)
+ for i in range(3000):
+ (deep / f"file_{i:05d}{exts[i % len(exts)]}").write_text("x\n")
+
+
+def _unusual_argument_limit():
+ """The long-path tests are sized for the usual limits: 1 MB (macOS) to
+ 2 MB (Linux with an 8 MB stack)."""
+ try:
+ return not 1024 * 1024 <= os.sysconf("SC_ARG_MAX") <= 2 * 1024 * 1024 + 200000
+ except (AttributeError, ValueError, OSError):
+ return False
+
+
+long_paths = pytest.mark.skipif(
+ os.name == "nt" or _unusual_argument_limit(),
+ reason="needs paths longer than Windows allows by default, and the usual "
+ "1 to 2 MB limit on one command's arguments")
+
+
+def _refuse_long_commands(monkeypatch, limit, error):
+ """Make starting a command fail like the OS does when its arguments
+ exceed `limit` characters. Returns the list of commands run. Popen is
+ where subprocess.run and the bounded diff reader both start theirs."""
+ real_popen = subprocess.Popen
+ ran = []
+
+ def popen(cmd, *args, **kwargs):
+ if sum(len(a) + 1 for a in cmd) > limit:
+ raise error
+ ran.append(cmd)
+ return real_popen(cmd, *args, **kwargs)
+
+ monkeypatch.setattr(subprocess, "Popen", popen)
+ return ran
+
+
+class TestPathBatches:
+ def test_every_path_once_and_each_batch_bounded(self):
+ paths = [f"dir/file_{i}.py" for i in range(100000)]
+ batches = list(gitutil._path_batches(paths))
+ assert [p for b in batches for p in b] == paths
+ assert len(batches) > 1
+ assert all(sum(len(p) for p in b) <= gitutil._MAX_PATH_ARGS_BYTES
+ for b in batches)
+
+ def test_budget_is_in_bytes(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 100)
+ assert len(list(gitutil._path_batches(["\u6f22" * 20 + ".py"] * 3))) == 3
+
+ def test_one_overlong_path_still_goes_out(self):
+ long = "x" * (gitutil._MAX_PATH_ARGS_BYTES + 10)
+ assert list(gitutil._path_batches(["a", long, "b"])) == [["a"], [long], ["b"]]
+
+ def test_no_paths_no_batches(self):
+ assert list(gitutil._path_batches([])) == []
+
+
+class TestGetGitDiff:
+ def _review_set(self, tmp_path):
+ repo = make_repo(tmp_path / "repo", {f"t{i}.py": "x = 1\n" for i in range(6)})
+ for i in range(6):
+ (repo / f"t{i}.py").write_text("x = 2\n")
+ (repo / f"new{i}.py").write_text("y = 1\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ assert len(paths) == 12 and len(untracked) == 6
+ return root, base, paths, untracked
+
+ def test_one_command_when_the_paths_fit(self, tmp_path, git_env, monkeypatch):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ ran = _refuse_long_commands(monkeypatch, 10**9, OSError(errno.E2BIG, "too long"))
+ diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert len(gitutil.parse_diff_into_files(diff)) == 12
+ assert len([c for c in ran if "diff" in c]) == 1
+ assert len([c for c in ran if "add" in c]) == 1
+
+ @pytest.mark.parametrize("error", [
+ OSError(errno.E2BIG, "Argument list too long"),
+ # What Python raises on Windows for ERROR_FILENAME_EXCED_RANGE.
+ type("WinTooLong", (FileNotFoundError,), {"winerror": 206})(errno.ENOENT, "too long"),
+ ], ids=["posix", "windows"])
+ def test_batches_when_one_command_is_refused(self, tmp_path, git_env, monkeypatch, error):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60)
+ limit = GIT_CMD_CHARS + 100 # the six-path add fits, the twelve-path diff does not
+ ran = _refuse_long_commands(monkeypatch, limit, error)
+ batched = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert sorted(gitutil.parse_diff_into_files(batched)) == \
+ sorted(gitutil.parse_diff_into_files(whole))
+ assert len([c for c in ran if "diff" in c]) > 1
+ # The batches are read through the bounded reader, which counts them.
+ assert gitutil._diff_read["bytes"] > 0
+
+ def test_only_reviewable_paths_after_a_refusal(self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ for i in range(20):
+ (repo / f"note{i:02d}.txt").write_text("x\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert whole.count("diff --git ") == 21
+ _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long"))
+ cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert cut.count("diff --git ") == 1
+ assert gitutil.parse_diff_into_files(cut) == gitutil.parse_diff_into_files(whole)
+
+ def test_rename_away_from_a_secret_shaped_name_stays_out_after_a_refusal(
+ self, tmp_path, git_env, monkeypatch):
+ secret = "".join(f"KEY_{i}=value-{i}\n" for i in range(20))
+ repo = make_repo(tmp_path / "repo", {".env": secret, "app.py": "x = 1\n"})
+ os.rename(repo / ".env", repo / "settings.py")
+ (repo / "app.py").write_text("x = 2\n")
+ (repo / "a_much_longer_module_name.py").write_text("y = 1\n")
+ for i in range(20):
+ (repo / f"note{i:02d}.txt").write_text("x\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ reviewed = ["a_much_longer_module_name.py", "app.py"]
+ assert sorted(f for f, _ in gitutil.parse_diff_into_files(whole)) == reviewed
+ # Room for .env beside each batch, and not for the three .py together.
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 120, OSError(errno.E2BIG, "too long"))
+ cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ diffs = [c for c in ran if "diff" in c]
+ assert len(diffs) > 1 and all(".env" in c for c in diffs)
+ assert sorted(f for f, _ in gitutil.parse_diff_into_files(cut)) == reviewed
+ assert "KEY_1=" not in "".join(d for _, d in gitutil.parse_diff_into_files(cut))
+
+ def test_gives_up_when_the_secret_shaped_paths_alone_are_too_many(
+ self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {
+ "app.py": "x = 1\n", **{f"dir{i:02d}/.env": "K=v\n" for i in range(20)}})
+ (repo / "app.py").write_text("x = 2\n")
+ for i in range(20):
+ os.remove(repo / f"dir{i:02d}" / ".env")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 200)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long"))
+ assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) is None
+ assert [c for c in ran if "diff" in c] == []
+ assert "gave_up" in gitutil._path_list_too_long
+
+ def test_secret_shaped_files_still_in_the_work_tree_do_not_ride_along(
+ self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ for i in range(20):
+ (repo / f"dir{i:02d}").mkdir()
+ (repo / f"dir{i:02d}" / ".env").write_text("K=v\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 200)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long"))
+ cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert [f for f, _ in gitutil.parse_diff_into_files(cut)] == ["app.py"]
+ assert not any(".env" in a for c in ran for a in c)
+ assert not gitutil._path_list_too_long
+
+ def test_batches_shrink_to_a_lower_system_limit(self, monkeypatch):
+ monkeypatch.setattr(os, "sysconf", lambda name: 100000, raising=False)
+ budget = gitutil._path_args_budget({"A": "b" * 9997})
+ # Half of what the environment leaves, or the platform figure where
+ # that is lower (Windows).
+ assert budget == min(45000, gitutil._MAX_PATH_ARGS_BYTES)
+ paths = [f"dir/file_{i}.py" for i in range(10000)]
+ assert all(sum(len(p) + 9 for p in b) <= budget
+ for b in gitutil._path_batches(paths, budget))
+ # Never above the platform figure, never uselessly small.
+ monkeypatch.setattr(os, "sysconf", lambda name: 10**9, raising=False)
+ assert gitutil._path_args_budget({}) == gitutil._MAX_PATH_ARGS_BYTES
+ monkeypatch.setattr(os, "sysconf", lambda name: 100, raising=False)
+ assert gitutil._path_args_budget({}) == 4096
+
+ def test_gives_up_past_the_batch_limit(self, tmp_path, git_env, monkeypatch):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60)
+ monkeypatch.setattr(gitutil, "_MAX_PATH_BATCHES", 2)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long"))
+ assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) is None
+ assert [c for c in ran if "diff" in c] == []
+
+ def test_other_start_failures_are_not_retried(self, tmp_path, git_env, monkeypatch):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ ran = _refuse_long_commands(monkeypatch, 0, FileNotFoundError(errno.ENOENT, "git"))
+ assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=[]) is None
+ assert ran == []
+
+ def test_batches_share_one_time_limit(self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo")
+ clock = iter([0, 0, 31])
+ monkeypatch.setattr(gitutil, "time", types.SimpleNamespace(monotonic=lambda: next(clock)))
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 30)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 60, OSError(errno.E2BIG, "too long"))
+ with pytest.raises(subprocess.TimeoutExpired):
+ gitutil._run_git_on_review_paths(
+ ["status"], ["a" * 40, "b" * 40, "c" * 40], timeout=30, cwd=str(repo))
+ assert len(ran) == 1
+
+ @long_paths
+ def test_more_paths_than_one_command_holds(self, tmp_path, git_env):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ _more_than_one_command_holds(repo, [".py", ".txt"])
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ assert sum(len(p) for p in untracked) > 2 * 1024 * 1024
+ diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert diff is not None
+ # app.py and the 1,500 .py files, from more than one command.
+ assert len(gitutil.parse_diff_into_files(diff)) == 1501
+ assert diff.count("diff --git ") == 1501
+
+
+class TestWholeHook:
+ @long_paths
+ def test_edit_reviewed_beside_more_paths_than_one_command_holds(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ _more_than_one_command_holds(repo, [".txt"])
+ rc, so, se = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(so)
+ assert m.get("skip_reason") is None, m
+ assert m.get("review_set_count") == 3001
+ assert stub_api.calls
+
+ def test_review_set_past_the_cap_skips_without_a_diff(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "new.py").write_text(VULN_PY)
+ rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "1"})
+ m = metrics_of(so)
+ assert m.get("skip_reason") == 8, m
+ # The skip taken after a diff reports how many files the diff held.
+ assert "diff_files_count" not in m
+ assert not stub_api.calls
+
+ def test_cap_counts_only_reviewable_paths(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ for i in range(20):
+ (repo / f"note{i:02d}.txt").write_text("x\n")
+ rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "5"})
+ m = metrics_of(so)
+ assert m.get("skip_reason") is None, m
+ assert m.get("review_set_count") == 21
+ assert stub_api.calls
+
+ @long_paths
+ def test_giving_up_is_reported_as_too_many_paths(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ # 3,000 reviewable names of about 750 bytes: more than four commands.
+ _more_than_one_command_holds(repo, [".py"])
+ rc, so, se = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(so)
+ assert m.get("skip_reason") == 8, m
+ assert not stub_api.calls
+
+ @long_paths
+ def test_nothing_reviewable_is_reported_as_no_source_files(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ _more_than_one_command_holds(repo, [".txt"])
+ rc, so, se = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(so)
+ assert m.get("skip_reason") == 7, m
+ assert not stub_api.calls
+
+ def test_cap_reads_paths_from_the_repo_root(self, tmp_path, hook_env, stub_api):
+ # A directory above the repo named like a skipped one (build/) must
+ # not make every path look unreviewable.
+ repo = make_repo(tmp_path / "build" / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "new.py").write_text(VULN_PY)
+ rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "1"})
+ assert metrics_of(so).get("skip_reason") == 8
+ assert not stub_api.calls
diff --git a/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py b/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py
new file mode 100644
index 00000000..c76aa8aa
--- /dev/null
+++ b/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py
@@ -0,0 +1,387 @@
+"""A Windows certificate store with an entry OpenSSL cannot read must not stop reviews.
+
+Older Python releases load each Windows store in one call, so one unreadable
+certificate makes the default TLS context fail to build. The store and that
+loading are stood in for here, so the cases run on every platform.
+"""
+import http.server
+import json
+import shutil
+import ssl
+import subprocess
+import threading
+import urllib.error
+import urllib.request
+
+import pytest
+
+from conftest import _Stub
+
+import _base
+import llm
+
+# A self-signed test CA (public certificate only).
+UNRELATED_CA_PEM = """-----BEGIN CERTIFICATE-----
+MIIBkjCCATmgAwIBAgIUbv89EXoDEbZBR6jKRVAU1V/0fGgwCgYIKoZIzj0EAwIw
+HzEdMBsGA1UEAwwUc2cgdGVzdCB1bnJlbGF0ZWQgQ0EwHhcNMjYxMDIxMTYyMjQ1
+WhcNMzYxMDE4MTYyMjQ1WjAfMR0wGwYDVQQDDBRzZyB0ZXN0IHVucmVsYXRlZCBD
+QTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPNt0cYQuFTK2120/wnrAXDuqQUE
+8Cu0MpykWGDKTpymrBpKT9tB3wtr6Z951brKADRTgA7sKsIRoo9WmwnJKdyjUzBR
+MB0GA1UdDgQWBBQbn4fFArXUPihIY/CG7IxtVswc1DAfBgNVHSMEGDAWgBQbn4fF
+ArXUPihIY/CG7IxtVswc1DAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0cA
+MEQCIDuCfFRxNvoQhAXHiaA+Pgd7nuZ7hHVE16dERXHiVT6JAiACb2vks3dsL40u
+UAQ7MEoy37JzJExADeVOBhztTqTkkw==
+-----END CERTIFICATE-----
+"""
+UNRELATED_CA = ssl.PEM_cert_to_DER_cert(UNRELATED_CA_PEM)
+# The same certificate with its serial number's tag overwritten.
+UNREADABLE = UNRELATED_CA[:13] + b"\x04" + UNRELATED_CA[14:]
+
+SERVER_AUTH = ssl.Purpose.SERVER_AUTH.oid
+CLIENT_AUTH = ssl.Purpose.CLIENT_AUTH.oid
+
+_real_create_default_context = ssl.create_default_context
+
+
+class _Store:
+ """Stand-in for the Windows certificate stores and for a Python that
+ loads each of them in one call."""
+
+ def __init__(self):
+ self.stores = {"CA": [], "ROOT": []}
+ self.enumerations = 0
+ self.default_builds = 0
+
+ def enum_certificates(self, name):
+ self.enumerations += 1
+ return list(self.stores.get(name, []))
+
+ def create_default_context(self, purpose=ssl.Purpose.SERVER_AUTH, *,
+ cafile=None, capath=None, cadata=None):
+ if cafile or capath or cadata:
+ return _real_create_default_context(
+ purpose, cafile=cafile, capath=capath, cadata=cadata)
+ self.default_builds += 1
+ # Never the machine's own trust: only what the test puts in the store.
+ context = _real_create_default_context(purpose, cadata=UNRELATED_CA)
+ for name in ("CA", "ROOT"):
+ certs = b"".join(
+ cert for cert, encoding, trust in self.stores[name]
+ if encoding == "x509_asn" and (trust is True or purpose.oid in trust))
+ if certs:
+ context.load_verify_locations(cadata=certs)
+ return context
+
+
+@pytest.fixture
+def store(monkeypatch):
+ s = _Store()
+ monkeypatch.setattr(ssl, "enum_certificates", s.enum_certificates, raising=False)
+ monkeypatch.setattr(ssl, "create_default_context", s.create_default_context)
+ monkeypatch.setattr(ssl, "_create_default_https_context", s.create_default_context)
+ # urllib keeps one opener per process, and on newer Pythons it holds the
+ # context it was built with; a hook process starts without one.
+ monkeypatch.setattr(urllib.request, "_opener", None)
+ # The store is checked once per process.
+ monkeypatch.setattr(llm, "_store_tls_context", llm._STORE_TLS_UNSET)
+ monkeypatch.setattr(llm, "_store_certs_skipped", 0)
+ for var in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy",
+ "ALL_PROXY", "all_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("NO_PROXY", "*")
+ monkeypatch.setenv("no_proxy", "*")
+ return s
+
+
+def _entry(cert, trust=True, encoding="x509_asn"):
+ return (cert, encoding, trust)
+
+
+def _subjects(context):
+ """The test certificates in a context (it also holds the machine's default file)."""
+ names = {dict(x[0] for x in c["subject"]).get("commonName", "")
+ for c in context.get_ca_certs()}
+ return {n for n in names if n.startswith("sg test ")}
+
+
+# ── certificates and an HTTPS endpoint for the handshake cases ───────────
+
+def _openssl(*args, cwd):
+ r = subprocess.run(["openssl", *args], cwd=cwd, capture_output=True, text=True)
+ assert r.returncode == 0, r.stderr
+
+
+@pytest.fixture(scope="module")
+def pki(tmp_path_factory):
+ if not shutil.which("openssl"):
+ pytest.skip("needs the openssl command to make test certificates")
+ d = tmp_path_factory.mktemp("pki")
+ leaf = ("basicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n"
+ "subjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n")
+ (d / "leaf.cnf").write_text("subjectAltName=DNS:localhost,IP:127.0.0.1\n" + leaf)
+ (d / "other-host.cnf").write_text("subjectAltName=DNS:other.invalid\n" + leaf)
+ # The subject goes in the config file: LibreSSL ignores -subj when the config has prompt=no.
+ def req_config(common_name):
+ (d / "req.cnf").write_text(
+ "[req]\ndistinguished_name=dn\nx509_extensions=v3\nprompt=no\n"
+ f"[dn]\nCN={common_name}\n"
+ "[v3]\nbasicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\n"
+ "subjectKeyIdentifier=hash\n")
+ out = {}
+ # server certificate -> (the CA that signs it, its extensions)
+ servers = {"trusted": ("trusted", "leaf.cnf"), "untrusted": ("untrusted", "leaf.cnf"),
+ "other-host": ("trusted", "other-host.cnf")}
+ for ca in ("trusted", "untrusted"):
+ req_config(f"sg test {ca} CA")
+ _openssl("req", "-x509", "-newkey", "rsa:2048", "-nodes", "-config", "req.cnf",
+ "-keyout", f"{ca}-ca.key", "-out", f"{ca}-ca.pem", "-days", "2", cwd=d)
+ req_config("sg test server")
+ for name, (ca, extensions) in servers.items():
+ _openssl("req", "-newkey", "rsa:2048", "-nodes", "-config", "req.cnf",
+ "-keyout", f"{name}.key", "-out", f"{name}.csr", cwd=d)
+ _openssl("x509", "-req", "-in", f"{name}.csr", "-CA", f"{ca}-ca.pem",
+ "-CAkey", f"{ca}-ca.key", "-CAcreateserial", "-out", f"{name}.pem",
+ "-days", "2", "-extfile", extensions, cwd=d)
+ out[name] = {
+ "ca": ssl.PEM_cert_to_DER_cert((d / f"{ca}-ca.pem").read_text()),
+ "cert": str(d / f"{name}.pem"), "key": str(d / f"{name}.key"),
+ }
+ return out
+
+
+@pytest.fixture
+def https_api(pki, store, tmp_path, monkeypatch):
+ servers = []
+
+ def start(signed_by):
+ srv = http.server.HTTPServer(("127.0.0.1", 0), _Stub)
+ srv.calls, srv.status, srv.delay, srv.vulns = [], 200, 0, []
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.load_cert_chain(pki[signed_by]["cert"], pki[signed_by]["key"])
+ srv.socket = context.wrap_socket(srv.socket, server_side=True)
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ servers.append(srv)
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", f"https://localhost:{srv.server_port}")
+ return srv
+
+ for var in ("SG_AGENTIC_MODEL", "SG_DUAL_OR", "CLAUDE_CODE_EXECPATH",
+ "SG_AGENTIC_CLI_PATH", "CLAUDE_CODE_REMOTE", *llm._PROVIDER_ENV_VARS):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("SECURITY_REVIEW_MODEL", "claude-opus-5-5")
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.setattr(llm, "ANTHROPIC_API_KEY", "test-key")
+ monkeypatch.setattr(llm, "ANTHROPIC_AUTH_TOKEN", "")
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True)
+ monkeypatch.setattr(llm, "_auth_prefer_token", False)
+ monkeypatch.setattr(llm, "_review_model_memo", None, raising=False)
+ monkeypatch.setattr(llm, "_last_call_claude_http_error", None)
+ monkeypatch.setattr(_base, "_USAGE", {**_base._USAGE, "models": []})
+ # No waiting between the attempts of a call that keeps failing.
+ monkeypatch.setattr("time.sleep", lambda s: None)
+ try:
+ yield start
+ finally:
+ for srv in servers:
+ srv.shutdown()
+ srv.server_close()
+
+
+def _review():
+ return llm.analyze_code_security([("app.py", "+print('hi')\n")], is_diff=True)
+
+
+# ── the stand-in behaves like the reported machines ──────────────────────
+
+class TestStandIn:
+ def test_the_unreadable_certificate_is_unreadable(self):
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
+ with pytest.raises(ssl.SSLError):
+ context.load_verify_locations(cadata=UNREADABLE)
+
+ @pytest.mark.parametrize("entries", [
+ [UNRELATED_CA, UNREADABLE], [UNREADABLE, UNRELATED_CA],
+ ], ids=["after a readable one", "first in the store"])
+ def test_one_unreadable_certificate_breaks_the_default_context(self, store, entries):
+ store.stores["ROOT"] = [_entry(c) for c in entries]
+ with pytest.raises(ssl.SSLError):
+ ssl.create_default_context()
+
+ def test_a_readable_store_builds(self, store):
+ store.stores["ROOT"] = [_entry(UNRELATED_CA)]
+ ssl.create_default_context()
+
+
+# ── the context built without the unreadable entries ─────────────────────
+
+def _context():
+ return llm._context_without_unreadable_store_certs()
+
+
+class TestContext:
+ def test_none_when_the_default_context_builds(self, store):
+ store.stores["ROOT"] = [_entry(UNRELATED_CA)]
+ assert _context() == (None, 0)
+ assert store.enumerations == 0
+
+ def test_none_off_windows(self, store, monkeypatch):
+ store.stores["ROOT"] = [_entry(UNREADABLE), _entry(UNRELATED_CA)]
+ monkeypatch.delattr(ssl, "enum_certificates")
+ assert _context() == (None, 0)
+ assert store.default_builds == 0
+
+ def test_none_when_no_certificate_is_readable(self, store):
+ store.stores["ROOT"] = [_entry(UNREADABLE)]
+ assert _context() == (None, 1)
+
+ def test_still_verifies_the_chain_and_the_host_name(self, store):
+ store.stores["ROOT"] = [_entry(UNREADABLE), _entry(UNRELATED_CA)]
+ context, _ = _context()
+ assert context.verify_mode == ssl.CERT_REQUIRED
+ assert context.check_hostname is True
+ default = _real_create_default_context(cadata=UNRELATED_CA)
+ assert context.verify_flags == default.verify_flags
+ assert context.options == default.options
+ assert context.minimum_version == default.minimum_version
+
+ def test_readable_certificates_from_both_stores_are_kept(self, store, pki):
+ store.stores["CA"] = [_entry(UNREADABLE), _entry(pki["trusted"]["ca"])]
+ store.stores["ROOT"] = [_entry(UNRELATED_CA), _entry(UNREADABLE), _entry(UNREADABLE)]
+ context, skipped = _context()
+ assert _subjects(context) == {"sg test trusted CA", "sg test unrelated CA"}
+ assert skipped == 3
+
+ def test_only_certificates_trusted_for_servers_are_loaded(self, store, pki):
+ store.stores["ROOT"] = [
+ _entry(UNREADABLE),
+ _entry(UNRELATED_CA, trust={SERVER_AUTH}),
+ _entry(pki["trusted"]["ca"], trust={CLIENT_AUTH}),
+ _entry(pki["untrusted"]["ca"], encoding="pkcs_7_asn"),
+ _entry(UNREADABLE, trust={CLIENT_AUTH}),
+ ]
+ context, skipped = _context()
+ assert _subjects(context) == {"sg test unrelated CA"}
+ assert skipped == 1
+
+ def test_a_store_that_cannot_be_listed_is_left_out(self, store, monkeypatch):
+ store.stores["ROOT"] = [_entry(UNREADABLE), _entry(UNRELATED_CA)]
+ listed = store.enum_certificates
+
+ def enum_certificates(name):
+ if name == "CA":
+ raise PermissionError("denied")
+ return listed(name)
+
+ monkeypatch.setattr(ssl, "enum_certificates", enum_certificates)
+ context, skipped = _context()
+ assert _subjects(context) == {"sg test unrelated CA"}
+ assert skipped == 1
+
+
+# ── the plugin's HTTPS calls ─────────────────────────────────────────────
+
+@pytest.fixture
+def urlopen_calls(monkeypatch):
+ calls = []
+ monkeypatch.setattr(urllib.request, "urlopen",
+ lambda request, **kw: calls.append(kw) or "response")
+ return calls
+
+
+def _head():
+ return urllib.request.Request(llm._anthropic_base_url() + "/", method="HEAD")
+
+
+class TestUrlopen:
+ def test_default_context_is_used_when_it_builds(self, store, urlopen_calls):
+ store.stores["ROOT"] = [_entry(UNRELATED_CA)]
+ assert llm._urlopen("request", 7) == "response"
+ assert llm._urlopen("request", 7) == "response"
+ assert urlopen_calls == [{"timeout": 7}] * 2
+ assert (store.default_builds, store.enumerations) == (1, 0)
+ assert llm._store_certs_skipped == 0
+
+ def test_nothing_is_checked_off_windows(self, store, urlopen_calls, monkeypatch):
+ monkeypatch.delattr(ssl, "enum_certificates")
+ assert llm._urlopen("request", 7) == "response"
+ assert urlopen_calls == [{"timeout": 7}]
+ assert store.default_builds == 0
+
+ def test_each_request_is_sent_once(self, store, urlopen_calls):
+ store.stores["ROOT"] = [_entry(UNREADABLE), _entry(UNRELATED_CA)]
+ assert llm._urlopen("request", 7) == "response"
+ assert len(urlopen_calls) == 1
+ assert urlopen_calls[0]["timeout"] == 7
+ assert isinstance(urlopen_calls[0]["context"], ssl.SSLContext)
+
+ def test_a_store_check_that_fails_leaves_the_default_route(
+ self, store, urlopen_calls, monkeypatch):
+ def enum_certificates(name):
+ raise OSError("store unavailable")
+
+ store.stores["ROOT"] = [_entry(UNREADABLE)]
+ monkeypatch.setattr(ssl, "enum_certificates", enum_certificates)
+ assert llm._urlopen("request", 7) == "response"
+ assert urlopen_calls == [{"timeout": 7}]
+
+ def test_review_runs_with_an_unreadable_certificate_in_the_store(
+ self, store, pki, https_api):
+ srv = https_api("trusted")
+ store.stores["CA"] = [_entry(UNRELATED_CA), _entry(UNREADABLE)]
+ store.stores["ROOT"] = [_entry(UNREADABLE), _entry(pki["trusted"]["ca"])]
+ _review()
+ assert not llm.last_review_failed()
+ assert len(srv.calls) == 1
+ assert llm._store_certs_skipped == 2
+
+ def test_the_store_is_read_once_per_process(self, store, pki, https_api):
+ srv = https_api("trusted")
+ store.stores["ROOT"] = [_entry(UNREADABLE), _entry(pki["trusted"]["ca"])]
+ _review()
+ builds, enumerations = store.default_builds, store.enumerations
+ _review()
+ assert len(srv.calls) == 2
+ assert (store.default_builds, store.enumerations) == (builds, enumerations) == (1, 2)
+
+ def test_a_server_the_store_does_not_trust_is_still_refused(
+ self, store, pki, https_api):
+ srv = https_api("untrusted")
+ store.stores["ROOT"] = [_entry(UNREADABLE), _entry(pki["trusted"]["ca"])]
+ with pytest.raises(urllib.error.URLError) as raised:
+ llm._urlopen(_head(), 5)
+ assert isinstance(raised.value.reason, ssl.SSLCertVerificationError)
+ _review()
+ assert llm.last_review_failed()
+ assert srv.calls == []
+
+ def test_a_host_name_the_certificate_does_not_cover_is_still_refused(
+ self, store, pki, https_api):
+ srv = https_api("other-host")
+ store.stores["ROOT"] = [_entry(UNREADABLE), _entry(pki["trusted"]["ca"])]
+ with pytest.raises(urllib.error.URLError) as raised:
+ llm._urlopen(_head(), 5)
+ assert isinstance(raised.value.reason, ssl.SSLCertVerificationError)
+ assert "localhost" in str(raised.value.reason)
+ _review()
+ assert llm.last_review_failed()
+ assert srv.calls == []
+
+ def test_review_runs_on_a_readable_store(self, store, pki, https_api):
+ srv = https_api("trusted")
+ store.stores["ROOT"] = [_entry(pki["trusted"]["ca"])]
+ _review()
+ assert not llm.last_review_failed()
+ assert len(srv.calls) == 1
+ assert llm._store_certs_skipped == 0
+
+
+def test_review_rows_count_the_skipped_store_entries(monkeypatch, capsys):
+ import security_reminder_hook as hook
+
+ def row():
+ hook.emit_metrics({"vulns_found": 0, "review_ms": 10})
+ return json.loads(capsys.readouterr().out)["metrics"]
+
+ monkeypatch.setattr(llm, "_store_certs_skipped", 0)
+ assert "tls_store_skipped" not in row()
+ monkeypatch.setattr(llm, "_store_certs_skipped", 7)
+ assert row()["tls_store_skipped"] == 7