diff options
41 files changed, 5432 insertions, 320 deletions
diff --git a/.github/scripts/sg_platform_annotate.py b/.github/scripts/sg_platform_annotate.py new file mode 100644 index 00000000..e8567d81 --- /dev/null +++ b/.github/scripts/sg_platform_annotate.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Print ten chunks of a text file as notice annotations, starting at chunk N.""" +import sys + +CHUNK = 3600 # an annotation keeps 4096 bytes +lines = open(sys.argv[1], encoding="utf-8", errors="replace").read().splitlines() +chunks, current = [], "" +for line in lines: + if current and len((current + line).encode("utf-8")) + 1 > CHUNK: + chunks.append(current) + current = "" + current += line[:CHUNK] + "\n" +if current: + chunks.append(current) +first = int(sys.argv[2]) +for index in range(first, min(first + 10, len(chunks))): + body = chunks[index].replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print("::notice title=report %03d of %03d::%s" % (index + 1, len(chunks), body)) +if first == 0: + print("%d chunks, %d characters" % (len(chunks), sum(map(len, chunks)))) diff --git a/.github/scripts/sg_platform_compare.py b/.github/scripts/sg_platform_compare.py new file mode 100644 index 00000000..0d897775 --- /dev/null +++ b/.github/scripts/sg_platform_compare.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Print, per runner image, how each tested tree's suite differs from main's.""" +import os +import sys +import xml.etree.ElementTree as ET + + +SKIP_REASONS = {} +FAILURE_TEXT = {} +# Failing tests whose whole failure text is printed for every tree. +FULL_TEXT_FOR = ("test_agentic_commit_review_runs", "test_findings_not_replaced_by_the_inner_cli_warning") +FULL_TEXT = {} +# Trees whose behaviour-check output is printed: main and the pull requests the checks were written for. +EXTRAS_FOR = {"main", "6628", "6721", "6722", "6807", "6808", "6875", "6922"} +LATER = [] +FIRST = [] + + +def read_suite(folder): + path = os.path.join(folder, "junit.xml") + if not os.path.exists(path): + return None + outcomes = {} + for case in ET.parse(path).getroot().iter("testcase"): + name = "%s::%s" % (case.get("classname", ""), case.get("name", "")) + skipped = case.find("skipped") + failure = case.find("failure") if case.find("failure") is not None else case.find("error") + if failure is not None: + outcomes[name] = "failed" + FAILURE_TEXT[(folder, name)] = ( + (failure.text or failure.get("message", ""))[-3000:] + + "\n--- captured stderr ---\n" + (case.findtext("system-err") or "")[-1500:]) + FULL_TEXT[(folder, name)] = (failure.text or failure.get("message", ""))[-20000:] + elif skipped is not None: + outcomes[name] = "skipped" + SKIP_REASONS[name] = skipped.get("message", "") + else: + outcomes[name] = "passed" + return outcomes + + +def module_of(name): + """tests.test_x.TestY::test_z -> test_x; a module-level skip has no class part.""" + parts = [p for p in name.replace("::", ".").split(".") if p.startswith("test_")] + return parts[0] if parts else name + + +def read_text(folder, name): + try: + with open(os.path.join(folder, name), encoding="utf-8", errors="replace") as handle: + return handle.read().strip() + except OSError: + return "?" + + +def main(root): + trees = {} + for entry in sorted(os.listdir(root)): + if not entry.startswith("results-"): + continue + image, _, ref = entry[len("results-"):].rpartition("-") + trees.setdefault(image, {})[ref] = os.path.join(root, entry) + for entry in sorted(os.listdir(root)): + if entry.startswith("sdk-"): + for name in ("launcher-choice.txt", "sdk-bootstrap.txt"): + LATER.append("\n## %s: %s\n\n```\n%s\n```" % (entry[len("sdk-"):], name, read_text(os.path.join(root, entry), name))) + for image, refs in trees.items(): + base = read_suite(refs["main"]) if "main" in refs else None + print("\n## %s\n" % image) + print("| Tree | Commit | Passed | Failed | Skipped | Launch exit | Five launches | Fails here, not on main |") + print("|---|---|---|---|---|---|---|---|") + details, extra, skips = [], [], {} + base_modules = {module_of(n) for n in base or {}} + for ref in sorted(refs, key=lambda r: (r != "main", r)): + suite = read_suite(refs[ref]) + sha = read_text(refs[ref], "sha")[:8] + launch = read_text(refs[ref], "launch.exit") + timing = [ln.split(": ")[1] for ln in read_text(refs[ref], "launch.txt").splitlines() + if ln.startswith("five launches")] + launch = "%s | %s" % (launch, timing[0] if timing else "?") + if suite is None: + print("| %s | %s | no result | | | %s | |" % (ref, sha, launch)) + continue + failed = sorted(n for n, o in suite.items() if o == "failed") + counts = [sum(1 for o in suite.values() if o == kind) for kind in ("passed", "failed", "skipped")] + if ref == "main" or base is None: + added = [] + cell = "baseline" if ref == "main" else "no baseline" + else: + added = [n for n in failed if base.get(n) != "failed"] + cell = str(len(added)) + print("| %s | %s | %d | %d | %d | %s | %s |" % (ref, sha, counts[0], counts[1], counts[2], launch, cell)) + for name in failed: + if name.endswith(FULL_TEXT_FOR): + FIRST.append("\n## %s, %s: `%s` (whole failure text)\n\n```\n%s\n```" + % (image, ref, name, FULL_TEXT.get((refs[ref], name), ""))) + if ref == "main": + details.append(("main (baseline failures)", failed)) + elif added: + marked = ["%s%s" % (n, "" if n in base else " (new test)") for n in added] + details.append((ref, marked)) + seen = set() + for name in added: + text = FAILURE_TEXT.get((refs[ref], name), "") + last = text.strip().splitlines()[-1:] or [""] + if last[0][:60] not in seen: + seen.add(last[0][:60]) + FIRST.append("\n## %s, %s: `%s` (end of the failure text)\n\n```\n%s\n```" + % (image, ref, name, text)) + if base is not None and ref != "main": + per_file = {} + for name, outcome in suite.items(): + module = module_of(name) + if module not in base_modules: + per_file.setdefault(module, {"passed": 0, "failed": 0, "skipped": 0})[outcome] += 1 + for module, tally in sorted(per_file.items()): + extra.append("- %s adds `%s`: %d passed, %d failed, %d skipped" + % (ref, module, tally["passed"], tally["failed"], tally["skipped"])) + for name in sorted(n for n, o in suite.items() if o == "skipped"): + skips.setdefault("%s: %s" % (name, SKIP_REASONS.get(name, "")), []).append(ref) + for title, names in details: + print("\n**%s**\n" % title) + for name in names: + print("- `%s`" % name) + if extra: + print("\n**Test files a tree adds over main**\n") + print("\n".join(extra)) + if skips: + print("\n**Skipped tests (trees)**\n") + for text, where in sorted(skips.items()): + print("- `%s` (%s)" % (text, ", ".join(where))) + for ref in sorted(refs, key=lambda r: (r != "main", r)): + if read_text(refs[ref], "launch.exit") != "0" or ref == "main": + print("\n**%s launcher**\n\n```\n%s\n```" % (ref, read_text(refs[ref], "launch.txt"))) + for ref in sorted(refs, key=lambda r: (r != "main", r)): + if ref in EXTRAS_FOR: + LATER.append("\n## %s, %s: behaviour checks\n\n```\n%s\n```" + % (image, ref, read_text(refs[ref], "extras.txt"))) + print("\n".join(FIRST + LATER)) + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/.github/scripts/sg_platform_extras.py b/.github/scripts/sg_platform_extras.py new file mode 100644 index 00000000..6240dbf6 --- /dev/null +++ b/.github/scripts/sg_platform_extras.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Behaviour checks for one checkout of the security-guidance plugin that the +unit suite does not make on its own: path handling with platform spellings, +files written by other tools, and the Stop hook's memory on large new files. + + sg_platform_extras.py <plugin dir> [--memory] + +Every check prints what it saw. A check whose code is not in this checkout +prints "not in this tree". Nothing here decides pass or fail.""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import textwrap +import time + +PLUGIN = os.path.abspath(sys.argv[1]) +HOOKS = os.path.join(PLUGIN, "hooks") +TESTS = os.path.join(PLUGIN, "tests") +WINDOWS = os.name == "nt" + + +def snippet(title, code, env=None, cwd=None): + """Run `code` in a fresh interpreter with the hooks folder importable.""" + print("\n### %s\n" % title, flush=True) + full_env = dict(os.environ, PYTHONPATH=os.pathsep.join([HOOKS, TESTS]), + PYTHONDONTWRITEBYTECODE="1", PYTHONIOENCODING="utf-8") + full_env.update(env or {}) + r = subprocess.run([sys.executable, "-c", textwrap.dedent(code)], env=full_env, + cwd=cwd, capture_output=True, text=True, encoding="utf-8", + errors="replace", timeout=900) + print(r.stdout.rstrip()) + if r.returncode or r.stderr.strip(): + print("exit=%d stderr:\n%s" % (r.returncode, r.stderr.rstrip())) + sys.stdout.flush() + + +def inflight_markers(): + snippet("In-flight review markers without fcntl", """ + import importlib.util, os, subprocess, tempfile + import diffstate + if not hasattr(diffstate, "_mark_inflight"): + raise SystemExit("not in this tree") + d = tempfile.mkdtemp() + subprocess.run(["git", "init", "-q", d], check=True) + r = diffstate._mark_inflight(d, ["a" * 40]) + print("fcntl", importlib.util.find_spec("fcntl") is not None) + print("returned", r) + print("held", len(diffstate._inflight_held)) + print("markers", [n for n in os.listdir(os.path.join(d, ".git")) if n.startswith("sg-inflight-")]) + """) + + +def secret_paths(): + snippet("Secret-shaped and secret-named paths", r""" + import gitutil + shaped = [".credentials.json", ".claude.json", r"C:\Users\x\.claude\.credentials.json", + ".CREDENTIALS.JSON", "config/credentials.json", r"src\claude.json"] + for p in shaped: + print("shaped", repr(p), gitutil._is_secret_shaped(p)) + if not hasattr(gitutil, "_is_secret_named"): + raise SystemExit("_is_secret_named: not in this tree") + named = ["secrets.yml", r"config\secrets.yml", "Credentials.JSON", "client_secret_123.apps.json", + "service-account.json", "secrets.example.yml", "secrets.enc.yaml", "secretsmanager.py", + "secret.txt"] + for p in named: + print("named", repr(p), gitutil._is_secret_named(p)) + print("count", gitutil.count_secret_named([("a\\secrets.yml", ""), ("b.py", "")])) + """) + + +def patterns_files(): + home = tempfile.mkdtemp(prefix="sg-home-") + valid = json.dumps({"patterns": [{"rule_name": "demo_rule", "regex": "AKIA[0-9A-Z]{16}", + "reminder": "DEMO_RULE_REMINDER"}]}) + load = """ + import sys + import extensibility + extensibility.load_for_session(sys.argv[1] if len(sys.argv) > 1 else %r) + print("loaded", [r["ruleName"] for r in extensibility.user_patterns()]) + """ + cases = [("local file is [1,2], written as UTF-8", "[1,2]", None)] + if WINDOWS and shutil.which("powershell.exe"): + cases.append(("local file is [1,2], written by Windows PowerShell Set-Content -Encoding Unicode", + "[1,2]", "Unicode")) + cases.append(("local file is a valid rule file, written by Windows PowerShell Set-Content -Encoding Unicode", + valid.replace("demo_rule", "local_rule"), "Unicode")) + for title, body, encoding in cases: + proj = tempfile.mkdtemp(prefix="sg-proj-") + subprocess.run(["git", "init", "-q", proj], check=True) + os.makedirs(os.path.join(proj, ".claude")) + with open(os.path.join(proj, ".claude", "security-patterns.json"), "w") as handle: + handle.write(valid) + local = os.path.join(proj, ".claude", "security-patterns.local.json") + if encoding: + subprocess.run(["powershell.exe", "-NoProfile", "-Command", + "Set-Content -Encoding %s -Path $env:SG_LOCAL -Value $env:SG_BODY" % encoding], + env=dict(os.environ, SG_LOCAL=local, SG_BODY=body), check=True) + else: + with open(local, "w") as handle: + handle.write(body) + with open(local, "rb") as handle: + print("\nfirst bytes of the local file:", handle.read(8)) + env = {"HOME": home, "USERPROFILE": home, "CLAUDE_CONFIG_DIR": ""} + snippet("Pattern files: " + title, load % proj, env=env, cwd=proj) + + +def review_scope(): + root = os.path.realpath(tempfile.mkdtemp(prefix="sg-Scope-")) + repo = os.path.join(root, "Root") + out = os.path.join(root, "Out") + os.makedirs(os.path.join(repo, "src")) + os.makedirs(out) + subprocess.run(["git", "init", "-q", repo], check=True) + with open(os.path.join(repo, "src", "app.py"), "w") as handle: + handle.write("x = 1\n") + snippet("Review scope: path spellings", r""" + import os, sys + import diffstate + if not hasattr(diffstate, "touched_scope"): + raise SystemExit("not in this tree") + from diffstate import touched_scope, review_scope_code + ROOT, OUT = sys.argv[1] if len(sys.argv) > 1 else %r, %r + app = os.path.join(ROOT, "src", "app.py") + def show(label, *args): + try: + print(label, touched_scope(*args)) + except Exception as e: + print(label, "EXCEPTION", type(e).__name__, e) + show("a absolute", ROOT, ROOT, [app]) + show("b case changed", ROOT.swapcase(), ROOT.swapcase(), [os.path.join(ROOT.swapcase(), "SRC", "APP.PY")]) + show("b root as given, path case changed", ROOT, ROOT, [os.path.join(ROOT, "SRC", "APP.PY")]) + show("c relative", ROOT, ROOT, ["src/app.py"]) + show("d outside", ROOT, ROOT, [os.path.join(OUT, "x.py")]) + show("d mixed", ROOT, ROOT, [app, os.path.join(OUT, "x.py")]) + show("d none", ROOT, ROOT, []) + if os.name == "nt": + show("e forward slashes", ROOT.replace("\\", "/"), ROOT.replace("\\", "/"), [app.replace("\\", "/")]) + show("e backslashes", ROOT.replace("/", "\\"), ROOT.replace("/", "\\"), [app.replace("/", "\\")]) + show("e other drive", ROOT, ROOT, ["Q:\\x.py"]) + import ctypes + buf = ctypes.create_unicode_buffer(1024) + n = ctypes.windll.kernel32.GetShortPathNameW(ROOT, buf, 1024) + short = buf.value if n else "" + print("e short form:", short if short and short != ROOT else "none different from the long form") + if short and short != ROOT: + show("e short root", short, short, [app]) + s, inside = touched_scope(ROOT, ROOT, [app]) + print("g one file", review_scope_code(ROOT, s, inside, ["src/app.py"], 0)) + print("g with untouched", review_scope_code(ROOT, s, inside, ["src/app.py", "other.py"], 0)) + print("g case changed", review_scope_code(ROOT, s, inside, ["SRC/App.py"], 0)) + print("g base_fail 1", review_scope_code(ROOT, s, inside, ["src/app.py"], 1)) + """ % (repo, out)) + + +def peak_memory_mb(proc): + if WINDOWS: + import ctypes + from ctypes import wintypes + + class Counters(ctypes.Structure): + _fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD)] + [ + (name, ctypes.c_size_t) for name in ( + "PeakWorkingSetSize", "WorkingSetSize", "QuotaPeakPagedPoolUsage", + "QuotaPagedPoolUsage", "QuotaPeakNonPagedPoolUsage", + "QuotaNonPagedPoolUsage", "PagefileUsage", "PeakPagefileUsage")] + + counters = Counters() + counters.cb = ctypes.sizeof(counters) + call = ctypes.windll.kernel32.K32GetProcessMemoryInfo + call.argtypes = [wintypes.HANDLE, ctypes.POINTER(Counters), wintypes.DWORD] + if not call(int(proc._handle), ctypes.byref(counters), counters.cb): + return -1 + return counters.PeakWorkingSetSize / 1e6 + import resource + peak = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss + return peak / (1e6 if sys.platform == "darwin" else 1e3) + + +def stop_memory(): + """Peak memory of the Stop hook's own process on a turn that adds four + 50 MB data files next to one changed source file.""" + sys.path[:0] = [HOOKS, TESTS] + import http.server + import threading + from pathlib import Path + import conftest + + for kind in ("txt", "json"): + print("\n### Stop hook memory: four 50 MB .%s files\n" % kind, flush=True) + work = Path(tempfile.mkdtemp(prefix="sg-mem-")) + repo = conftest.make_repo(work / "repo", {"app.py": "print('hi')\n"}) + state = work / "state" + state.mkdir() + server = http.server.HTTPServer(("127.0.0.1", 0), conftest._Stub) + server.calls, server.status, server.delay, server.vulns = [], 200, 0, [] + threading.Thread(target=server.serve_forever, daemon=True).start() + env = {k: v for k, v in os.environ.items() + if k not in ("ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_REMOTE", "CLAUDE_PROJECT_DIR", + "CLAUDE_CODE_REMOTE_SESSION_ID", "HTTP_PROXY", "HTTPS_PROXY", + "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy")} + env.update(conftest.GIT_ENV) + env.update({ + "SECURITY_WARNINGS_STATE_DIR": str(state), "ANTHROPIC_API_KEY": "test-key", + "ANTHROPIC_BASE_URL": "http://127.0.0.1:%d" % server.server_port, + "NO_PROXY": "*", "no_proxy": "*", "SG_AGENTIC_COMMIT_REVIEW": "0", + "PYTHONDONTWRITEBYTECODE": "1", + }) + + def hook(payload): + started = time.perf_counter() + proc = subprocess.Popen([sys.executable, str(conftest.HOOK_SCRIPT)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) + try: + out, err = proc.communicate(json.dumps(payload).encode(), timeout=900) + except subprocess.TimeoutExpired: + proc.kill() + out, err = proc.communicate() + print("TIMED OUT after 900 s") + return proc, time.perf_counter() - started, out.decode("utf-8", "replace"), err.decode("utf-8", "replace") + + proc, seconds, out, err = hook(conftest.ups_payload(repo)) + print("UserPromptSubmit: exit %d in %.1f s" % (proc.returncode, seconds)) + (repo / "app.py").write_text(conftest.VULN_PY) + for index in range(4): + mark = " \U0001F600" if index == 2 else "" + if kind == "txt": + line = "line %%09d of ordinary generated text for file %d%s\n" % (index, mark) + else: + line = '{"id": %%09d, "file": %d, "note": "ordinary generated record%s"}\n' % (index, mark) + count = 50 * 1024 * 1024 // len((line % 0).encode("utf-8")) + 1 + with open(repo / ("data%d.%s" % (index, kind)), "w", encoding="utf-8", newline="\n") as handle: + for start in range(0, count, 100000): + handle.write("".join(line % n for n in range(start, min(start + 100000, count)))) + proc, seconds, out, err = hook(conftest.stop_payload(repo)) + print("Stop: exit %d in %.1f s, peak memory of the hook process %.0f MB" + % (proc.returncode, seconds, peak_memory_mb(proc))) + print("review requests at the stub API:", len(server.calls)) + print("metrics:", json.dumps(conftest.metrics_of(out), sort_keys=True)) + if err.strip(): + print("stderr (last 15 lines):\n" + "\n".join(err.strip().splitlines()[-15:])) + server.shutdown() + shutil.rmtree(work, ignore_errors=True) + + +def main(): + for check in (inflight_markers, secret_paths, patterns_files, review_scope): + try: + check() + except Exception as error: + print("CHECK FAILED TO RUN: %s: %s: %s" % (check.__name__, type(error).__name__, error), flush=True) + if "--memory" in sys.argv: + try: + stop_memory() + except Exception as error: + print("CHECK FAILED TO RUN: stop_memory: %s: %s" % (type(error).__name__, error), flush=True) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/sg_platform_sdk_bootstrap.py b/.github/scripts/sg_platform_sdk_bootstrap.py new file mode 100644 index 00000000..8ac8da52 --- /dev/null +++ b/.github/scripts/sg_platform_sdk_bootstrap.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Real agent-SDK installs with the plugin's bootstrap script, on two +checkouts of the plugin, printing the outcome code of each run. + + sg_platform_sdk_bootstrap.py <main plugin dir> <pull request plugin dir> + +Prints what each step returned next to what is expected; decides nothing.""" +import json +import os +import subprocess +import sys +import tempfile +import time + +MAIN, PR = (os.path.abspath(p) for p in sys.argv[1:3]) +WORK = tempfile.mkdtemp(prefix="sg-sdk-") + + +def bootstrap_env(state, extra=None): + env = {k: v for k, v in os.environ.items() + if k not in ("SECURITY_GUIDANCE_DISABLE", "ENABLE_CODE_SECURITY_REVIEW")} + env.update({"SECURITY_WARNINGS_STATE_DIR": state, "PYTHONDONTWRITEBYTECODE": "1"}) + env.update(extra or {}) + return env + + +def run(label, plugin, state, expect, extra=None): + started = time.perf_counter() + r = subprocess.run([sys.executable, os.path.join(plugin, "hooks", "ensure_agent_sdk.py")], + stdin=subprocess.DEVNULL, capture_output=True, text=True, + env=bootstrap_env(state, extra), timeout=1500) + metrics = {} + for line in r.stdout.splitlines(): + try: + metrics = json.loads(line).get("metrics") or metrics + except (json.JSONDecodeError, AttributeError): + pass + shown = {k: v for k, v in metrics.items() if k.startswith("sdk_")} + print("%s: sdk_bootstrap=%s (expected %s), exit %d, %.0f s, %s" + % (label, metrics.get("sdk_bootstrap"), expect, r.returncode, + time.perf_counter() - started, json.dumps(shown, sort_keys=True)), flush=True) + if r.stderr.strip(): + print(" stderr (last 8 lines):\n " + "\n ".join(r.stderr.strip().splitlines()[-8:])) + return metrics.get("sdk_bootstrap") + + +def sdk_package_dirs(state): + return [os.path.join(root, "claude_agent_sdk") for root, dirs, _ in os.walk(state) + if "claude_agent_sdk" in dirs] + + +def reviewer_import(label, plugin, state): + """Import the SDK the way the plugin's reviewer does (its own path setup, + which also handles pywin32's .pth files on Windows).""" + code = ("import sys; sys.path.insert(0, sys.argv[1]); import llm, _base; " + "llm._inject_agent_sdk_venv_into_syspath(_base.state_dir()); " + "from claude_agent_sdk import query; print('import ok')") + r = subprocess.run([sys.executable, "-c", code, os.path.join(plugin, "hooks")], + capture_output=True, text=True, env=bootstrap_env(state)) + print("%s: %s" % (label, (r.stdout + r.stderr).strip().splitlines()[-1:])) + + +print("## a. whole plugin switched off") +off = os.path.join(WORK, "off") +run("pull request, SECURITY_GUIDANCE_DISABLE=1", PR, off, 10, {"SECURITY_GUIDANCE_DISABLE": "1"}) +print("state folder created:", os.path.exists(off), "(expected False)") + +print("\n## b. first install, then a second run") +state = os.path.join(WORK, "state") +run("pull request, first run", PR, state, 2) +run("pull request, second run", PR, state, 1) + +print("\n## c. installed package emptied of its files") +packages = sdk_package_dirs(state) +print("SDK package folders:", packages) +removed = 0 +for package in packages: + for root, _, files in os.walk(package): + for name in files: + os.remove(os.path.join(root, name)) + removed += 1 +print("files removed:", removed) +run("main on the emptied install", MAIN, state, "1 (the bug)") +run("pull request on the emptied install", PR, state, "2 with sdk_venv_emptied 1") +run("pull request again", PR, state, 1) +reviewer_import("reviewer import after the rebuild", PR, state) + +print("\n## d. review switched off: is the bootstrap still started from a tool hook") +payload = json.dumps({"session_id": "s", "hook_event_name": "PostToolUse", "tool_name": "Write", + "tool_input": {"file_path": "x.txt", "content": "hi"}, "cwd": "."}) +for label, plugin, expect in (("main", MAIN, True), ("pull request", PR, False)): + folder = os.path.join(WORK, "w-" + label.replace(" ", "-")) + r = subprocess.run([sys.executable, os.path.join(plugin, "hooks", "security_reminder_hook.py")], + input=payload, capture_output=True, text=True, cwd=WORK, + env=bootstrap_env(folder, {"ENABLE_CODE_SECURITY_REVIEW": "0"}), timeout=300) + time.sleep(3) + marker = os.path.join(folder, ".sdk_bootstrap_spawned") + print("%s: hook exit %d, marker file exists: %s (expected %s)" + % (label, r.returncode, os.path.exists(marker), expect)) + +print("\n## e. install killed part way, then run again") +killed = os.path.join(WORK, "k") +proc = subprocess.Popen([sys.executable, os.path.join(PR, "hooks", "ensure_agent_sdk.py")], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=bootstrap_env(killed)) +time.sleep(5) +proc.kill() +proc.wait() +print("after the kill the state folder holds:", sorted(os.listdir(killed)) if os.path.isdir(killed) else "nothing") +time.sleep(10) +outcome = run("pull request, 10 s after the kill", PR, killed, "2, or 5 while a cooldown holds") +if outcome == 5: + print("waiting 6 minutes for the cooldown") + time.sleep(365) + # The kill ends the bootstrap script only. Killed while it creates the venv, + # the next run rebuilds (2). Killed while pip runs, pip finishes the install + # by itself and the next run finds it complete (1). + outcome = run("pull request, 6 minutes later", PR, killed, "2, or 1 when pip was already running") +run("pull request, once more", PR, killed, 1) +reviewer_import("reviewer import after the killed install", PR, killed) diff --git a/.github/scripts/sg_platform_store_cert.py b/.github/scripts/sg_platform_store_cert.py new file mode 100644 index 00000000..31191f5d --- /dev/null +++ b/.github/scripts/sg_platform_store_cert.py @@ -0,0 +1,219 @@ +"""A Windows certificate store entry that OpenSSL cannot read: does Python's default TLS context +still build, and do the plugin's API calls still connect and still verify? + +Usage: sg_platform_store_cert.py <main plugin dir> <pull request plugin dir> + +Adds test certificates, one at a time, to the current user's "CA" store (which makes nothing +trusted), runs the checks, and removes each one again. Every certificate here is a throwaway +self-signed test certificate, damaged on purpose; no private key is kept anywhere. +""" +import base64 +import hashlib +import inspect +import os +import ssl +import struct +import subprocess +import sys +import tempfile + +VALID = base64.b64decode( + "MIIDHzCCAgegAwIBAgIUOc9sRb2irMM4tVz+MQXfAetMqk0wDQYJKoZIhvcNAQELBQAwHzEdMBsGA1UEAwwUc2cgdGVzdCB1bnJlbGF0ZWQgQ0EwHhcNMjYxMDIxMTYyMTEzWhcNMjYxMTIwMTYyMTEzWjAfMR0wGwYDVQQDDBRzZyB0ZXN0IHVucmVsYXRlZCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJem7dZt60IjCVS8hLJFacbGIdCwitR+EwfK3RfRbtGUeR8VDfAI2uQUF9KNCQQ0jUDLAzKxTXhje5bDW4eBs/HC86uYBPRvSmSnkh0QXc9FRGsoryI5smLtr//mFoXmyCd/xdX/mThEoamP50mH+mCrwt9UuiS8uUPD0EXMsfKSyWJLx+fPzcquOClCx+RAhGqtFhUMLZvAhRAzwodJaZ+6Rmuajii9W3YuTwUASK00IVF9m+DrvdwMSZBtOC6psyli9boD908SHI1YAR0u5hAeMUVbMC/09gNXrMeuoVghygluujCxUrPfsMtxYBE3+F6S7AbXwBDXjgTfDLP6cSMCAwEAAaNTMFEwHQYDVR0OBBYEFBzXby0JI0yF361xBLC1d/uTc8NjMB8GA1UdIwQYMBaAFBzXby0JI0yF361xBLC1d/uTc8NjMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAG/cFyLiNq1wIUceHcx04Z/frqpzCk360w6HcJ4lfWEEE1Yeyt++3dnKpkvxUT6FvAa63aIXQmaZIRZNtF6bpB937ycGovbCPMIDXj0KLwxYORqQ/kCjh6o8nCMxJ6H2UJ1Wkhvy4t4d0cYKwYxwxLo8cZ+nRn5cwYWlJBTXvVMHP5+WuYYSuatvBmpgCTdR96Setu2CMF+WohyiqXIYCrZDkNyOYS0t9hhzHK9C08eCHsHqE1KaAjUomjGjGjDehtujwBqVi9saCedXFX93MRtiZhVSBC9FHkOYdYYSdmCQi/PBpfMXaPFcfvR9gNKDaxKRRQxaQfrvv+OIVKhP+Z8=") +SUBJECT_A = base64.b64decode( + "MIIBkjCCATmgAwIBAgIUbv89EXoDEbZBR6jKRVAU1V/0fGgwCgYIKoZIzj0EAwIwHzEdMBsGA1UEAwwUc2cgdGVzdCB1bnJlbGF0ZWQgQ0EwHhcNMjYxMDIxMTYyMjQ1WhcNMzYxMDE4MTYyMjQ1WjAfMR0EGwYDVQQDDBRzZyB0ZXN0IHVucmVsYXRlZCBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPNt0cYQuFTK2120/wnrAXDuqQUE8Cu0MpykWGDKTpymrBpKT9tB3wtr6Z951brKADRTgA7sKsIRoo9WmwnJKdyjUzBRMB0GA1UdDgQWBBQbn4fFArXUPihIY/CG7IxtVswc1DAfBgNVHSMEGDAWgBQbn4fFArXUPihIY/CG7IxtVswc1DAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0cAMEQCIDuCfFRxNvoQhAXHiaA+Pgd7nuZ7hHVE16dERXHiVT6JAiACb2vks3dsL40uUAQ7MEoy37JzJExADeVOBhztTqTkkw==") +SUBJECT_B = base64.b64decode( + "MIIBkjCCATmgAwIBAgIUbv89EXoDEbZBR6jKRVAU1V/0fGgwCgYIKoZIzj0EAwIwHzEdMBsGA1UEAwwUc2cgdGVzdCB1bnJlbGF0ZWQgQ0EwHhcNMjYxMDIxMTYyMjQ1WhcNMzYxMDE4MTYyMjQ1WjAfMB0wGwYDVQQDDBRzZyB0ZXN0IHVucmVsYXRlZCBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPNt0cYQuFTK2120/wnrAXDuqQUE8Cu0MpykWGDKTpymrBpKT9tB3wtr6Z951brKADRTgA7sKsIRoo9WmwnJKdyjUzBRMB0GA1UdDgQWBBQbn4fFArXUPihIY/CG7IxtVswc1DAfBgNVHSMEGDAWgBQbn4fFArXUPihIY/CG7IxtVswc1DAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0cAMEQCIDuCfFRxNvoQhAXHiaA+Pgd7nuZ7hHVE16dERXHiVT6JAiACb2vks3dsL40uUAQ7MEoy37JzJExADeVOBhztTqTkkw==") +CN = b"sg test unrelated CA" + +REPORT = [] + + +def say(line=""): + print(line, flush=True) + REPORT.append(line) + + +def _tlv(data, at): + length, header = data[at + 1], 2 + if length & 0x80: + n = length & 0x7F + length, header = int.from_bytes(data[at + 2:at + 2 + n], "big"), 2 + n + return header, length + + +def _der(tag, body): + n = len(body) + if n < 0x80: + return bytes([tag, n]) + body + size = n.to_bytes((n.bit_length() + 7) // 8, "big") + return bytes([tag, 0x80 | len(size)]) + size + body + + +def candidates(): + # A subject name that is not valid UTF-8. + name = bytearray(VALID) + name[VALID.find(CN, VALID.find(CN) + 1) + 3] = 0xFF + # A serial number with a leading zero byte it must not have. + h, n = _tlv(VALID, 0) + outer = VALID[h:h + n] + h, n = _tlv(outer, 0) + tbs, rest = outer[h:h + n], outer[h + n:] + h, n = _tlv(tbs, 0) + version, at = tbs[:h + n], h + n + h, n = _tlv(tbs, at) + serial, tail = tbs[at + h:at + h + n], tbs[at + h + n:] + padded = _der(0x30, _der(0x30, version + _der(0x02, b"\x00" + serial) + tail) + rest) + # A serial number under the wrong type. + tag = bytearray(VALID) + tag[13] = 0x04 + return [ + ("name not UTF-8", bytes(name)), + ("serial with illegal padding", padded), + ("subject name wrongly nested (1)", SUBJECT_A), + ("subject name wrongly nested (2)", SUBJECT_B), + ("serial under the wrong type", bytes(tag)), + ] + + +def run(cmd, **kw): + p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + errors="replace", timeout=300, **kw) + return p.returncode, p.stdout.strip() + + +def last(text, n=1): + return " | ".join(text.splitlines()[-n:]) if text else "" + + +def context_builds(): + code, out = run([sys.executable, "-c", "import ssl; ssl.create_default_context(); print('builds')"]) + return "builds" if code == 0 else "FAILS: " + last(out) + + +def in_store(der): + return any(cert == der for cert, _, _ in ssl.enum_certificates("CA")) + + +REG_KEY = r"Software\Microsoft\SystemCertificates\CA\Certificates" + + +def add(der, path): + code, out = run(["certutil", "-user", "-addstore", "CA", path]) + if in_store(der): + return "certutil" + say(f" certutil: exit {code}: {last(out, 2)}") + code, out = run(["powershell", "-NoProfile", "-Command", + "$s = New-Object System.Security.Cryptography.X509Certificates.X509Store('CA','CurrentUser');" + "$s.Open('ReadWrite');" + "$c = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList '%s';" + "$s.Add($c); $s.Close()" % path]) + if in_store(der): + return "X509Store" + say(f" X509Store: exit {code}: {last(out, 2)}") + import winreg + thumb = hashlib.sha1(der).hexdigest().upper() + with winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_KEY + "\\" + thumb) as key: + winreg.SetValueEx(key, "Blob", 0, winreg.REG_BINARY, struct.pack("<III", 32, 1, len(der)) + der) + if in_store(der): + return "registry" + say(" registry entry: not listed by the store") + return None + + +def remove(der): + thumb = hashlib.sha1(der).hexdigest().upper() + run(["certutil", "-user", "-delstore", "CA", thumb]) + if in_store(der): + run(["powershell", "-NoProfile", "-Command", + "Remove-Item -Path 'Cert:\\CurrentUser\\CA\\%s' -ErrorAction SilentlyContinue" % thumb]) + try: + import winreg + winreg.DeleteKey(winreg.HKEY_CURRENT_USER, REG_KEY + "\\" + thumb) + except OSError: + pass + return not in_store(der) + + +CONNECT = r""" +import sys, urllib.request, urllib.error +import llm +op = getattr(llm, "_urlopen", None) or (lambda r, t: urllib.request.urlopen(r, timeout=t)) +for url in sys.argv[1:]: + try: + op(urllib.request.Request(url, method="HEAD"), 20) + print(url, "-> connected") + except urllib.error.HTTPError as e: + print(url, "-> connected, HTTP", e.code) + except urllib.error.URLError as e: + print(url, "-> refused:", type(e.reason).__name__, str(e.reason)[:110]) + except Exception as e: + print(url, "-> FAILED before a request:", type(e).__name__, str(e)[:110]) +print("store entries left out:", getattr(llm, "_store_certs_skipped", "n/a")) +""" + +API = "https://api.anthropic.com/" +MUST_REFUSE = ["https://wrong.host.badssl.com/", "https://self-signed.badssl.com/", + "https://untrusted-root.badssl.com/", "https://expired.badssl.com/"] + + +def connect(plugin, urls): + env = {k: v for k, v in os.environ.items() if not k.startswith(("ANTHROPIC_", "SSL_CERT"))} + code, out = run([sys.executable, "-c", CONNECT] + urls, cwd=os.path.join(plugin, "hooks"), env=env) + return out if code == 0 else f"exit {code}: {last(out, 3)}" + + +def main(): + main_plugin, pr_plugin = (os.path.abspath(p) for p in sys.argv[1:3]) + say(f"Python {sys.version.split()[0]} {os.environ.get('PROCESSOR_ARCHITECTURE', '')}, {ssl.OPENSSL_VERSION}") + source = inspect.getsource(ssl.SSLContext._load_windows_store_certs) + say("this Python loads the store: " + + ("one certificate at a time" if "for cert" in source and "except" in source else "in one call")) + say(f"store before: CA {len(ssl.enum_certificates('CA'))} entries, ROOT {len(ssl.enum_certificates('ROOT'))}; " + f"default context {context_builds()}") + say("pull request has the change: " + str(os.path.exists( + os.path.join(pr_plugin, "tests", "test_tls_store_unreadable_cert.py")))) + say("clean store, main: " + connect(main_plugin, [API]).replace("\n", " ; ")) + say("clean store, pull request: " + connect(pr_plugin, [API]).replace("\n", " ; ")) + refusals_done = suite_done = False + work = tempfile.mkdtemp(prefix="sg-store-cert-") + for number, (label, der) in enumerate(candidates(), 1): + say() + say(f"== candidate {number}: {label}") + path = os.path.join(work, f"candidate{number}.cer") + with open(path, "wb") as f: + f.write(der) + try: + how = add(der, path) + if how is None: + say(" Windows did not take it into the store") + continue + builds = context_builds() + say(f" in the store (through {how}); default context {builds}") + say(" main: " + connect(main_plugin, [API]).replace("\n", " ; ")) + say(" pull request: " + connect(pr_plugin, [API]).replace("\n", " ; ")) + if builds != "builds" and not refusals_done: + refusals_done = True + for line in connect(pr_plugin, MUST_REFUSE).splitlines(): + say(" pull request, must be refused: " + line) + if builds != "builds" and not suite_done: + suite_done = True + code, out = run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", + "tests/test_tls_store_unreadable_cert.py"], cwd=pr_plugin) + say(f" new test file with this store: exit {code}: {last(out)}") + if code: + say(" " + last(out, 25)) + finally: + say(" removed: " + str(remove(der)) + f"; default context {context_builds()}") + say() + say(f"store after: CA {len(ssl.enum_certificates('CA'))} entries; default context {context_builds()}") + # The report again as annotations, for reading through the API. + text, part = "\n".join(REPORT), 0 + while text and part < 9: + chunk, text = text[:3000], text[3000:] + part += 1 + chunk = chunk.replace("%", "%25").replace("\r", "").replace("\n", "%0A") + print(f"::notice title=store cert {sys.version.split()[0]} part {part}::{chunk}") + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/security-guidance-platform-tests.yml b/.github/workflows/security-guidance-platform-tests.yml new file mode 100644 index 00000000..e0d1414a --- /dev/null +++ b/.github/workflows/security-guidance-platform-tests.yml @@ -0,0 +1,276 @@ +name: security-guidance platform tests + +# Runs the security-guidance plugin's own test suite, its hook launcher and a +# few behaviour checks on Windows and macOS runners, for main and for a list of open pull +# requests, and prints which failures a pull request adds over main. Triggered by pushes to its own +# branch only; it reads the repository and holds no secrets. + +on: + push: + branches: + - mhegazy/sg2018batch + +permissions: + contents: read + actions: read + +env: + # A push whose commit message contains [report] skips the suite and prints + # the results of this earlier run instead. + REPORT_RUN_ID: '39946738961' + REPORT_SDK_RUN_ID: '39946738961' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + suite: + name: ${{ matrix.ref }} on ${{ matrix.os }} + if: ${{ !contains(github.event.head_commit.message, '[report]') && !contains(github.event.head_commit.message, '[store-cert]') }} + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + os: [windows-latest, windows-11-arm, macos-latest] + ref: [main, batch] + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + with: + path: harness + + - uses: actions/checkout@v4 + with: + ref: ${{ matrix.ref == 'main' && 'main' || github.sha }} + path: tree + + - uses: actions/setup-python@v5 + with: + python-version: '3.13' + + - name: Describe the machine + run: | + cmd.exe //c ver 2>/dev/null || { sw_vers; uname -a; } + echo "PROCESSOR_ARCHITECTURE=$PROCESSOR_ARCHITECTURE" + git --version + bash --version | head -1 + git -C tree rev-parse HEAD + for p in python3 python py; do + echo "== $p" + where "$p" 2>&1 || true + "$p" --version 2>&1 || true + done + python -c "import platform, sys; print(platform.platform(), platform.machine(), sys.version)" + + - name: Plugin test suite + id: suite + working-directory: tree/plugins/security-guidance + continue-on-error: true + run: | + mkdir -p "$RUNNER_TEMP/results" + python -m pip install -q pytest + if python -m pip install -q claude-agent-sdk > "$RUNNER_TEMP/sdk-install.txt" 2>&1; then + echo "::notice title=agent sdk::installed $(python -m pip show claude-agent-sdk | sed -n 2p)" + else + echo "::notice title=agent sdk::install failed: $(tail -c 1500 "$RUNNER_TEMP/sdk-install.txt" | tr '\n' ' ')" + fi + python -m pytest -q -p no:cacheprovider tests -rfEs \ + --junitxml="$RUNNER_TEMP/results/junit.xml" -o junit_logging=system-err + + - name: Hook launch through the launcher script + id: launch + continue-on-error: true + run: | + R="$PWD/tree/plugins/security-guidance" + launch() { + echo '{"hook_event_name":"UserPromptSubmit","session_id":"platform-test","cwd":"'"$PWD"'","prompt":"hello"}' \ + | CLAUDE_PLUGIN_ROOT="$R" bash "$@" "$R/hooks/sg-python.sh" "$R/hooks/security_reminder_hook.py" + } + set +e + launch -x > "$RUNNER_TEMP/results/launch.out" 2> "$RUNNER_TEMP/results/launch.err" + code=$? + echo "$code" > "$RUNNER_TEMP/results/launch.exit" + { + echo "exit=$code" + grep -E '^[+]+ exec|open file|No such file' "$RUNNER_TEMP/results/launch.err" + cat "$RUNNER_TEMP/results/launch.out" + start=$(date +%s%N) + for i in 1 2 3 4 5; do launch > /dev/null 2>&1; done + echo "five launches: $(( ($(date +%s%N) - start) / 1000000 )) ms" + } 2>&1 | tee "$RUNNER_TEMP/results/launch.txt" + test "$code" -eq 0 + + - name: Behaviour checks + if: always() + continue-on-error: true + env: + PYTHONUTF8: '1' + run: | + python harness/.github/scripts/sg_platform_extras.py tree/plugins/security-guidance \ + ${{ (matrix.ref == 'main' || matrix.ref == '6591') && '--memory' || '' }} 2>&1 \ + | tee "$RUNNER_TEMP/results/extras.txt" + + - name: Record the commit + if: always() + run: git -C tree rev-parse HEAD > "$RUNNER_TEMP/results/sha" + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: results-${{ matrix.os }}-${{ matrix.ref }} + path: ${{ runner.temp }}/results + if-no-files-found: warn + + sdk-bootstrap: + name: SDK bootstrap and launcher on ${{ matrix.os }} + if: ${{ !contains(github.event.head_commit.message, '[report]') && !contains(github.event.head_commit.message, '[store-cert]') }} + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + os: [windows-latest, windows-11-arm] + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + with: + path: harness + - uses: actions/checkout@v4 + with: + ref: main + fetch-depth: 2 + path: main + - uses: actions/checkout@v4 + with: + ref: refs/pull/6608/head + path: pr + - uses: actions/setup-python@v5 + with: + python-version: '3.13' + + - name: Launcher picks a new enough interpreter + continue-on-error: true + run: | + git -C main worktree add -q ../base HEAD^1 + for t in base main pr; do echo "$t $(git -C $t rev-parse --short HEAD)"; done + T="$RUNNER_TEMP/launcher"; B="$T/bin"; mkdir -p "$B" + PY="$(cygpath -u "$(python -c 'import sys; print(sys.executable)')")" + printf '#!/bin/bash\nif [ "$1" = "-c" ]; then echo 3.9; else echo RAN-3.9; fi\n' > "$B/python3" + printf '#!/bin/bash\nexec "%s" "$@"\n' "$PY" > "$B/python3.14" + chmod +x "$B"/* + echo 'import sys; print(sys.version)' > "$T/hello.py" + echo "interpreters in /usr/bin and /bin: $(ls /usr/bin/python3* /bin/python3* 2>/dev/null | tr '\n' ' ')" + set +e + mkdir -p "$RUNNER_TEMP/results" + for round in "python3 (3.9) and python3.14" "plus python3.12"; do + echo "== on PATH: $round" + for t in base main pr; do + out=$(PATH="$B:/usr/bin:/bin" bash "$t/plugins/security-guidance/hooks/sg-python.sh" "$T/hello.py" 2>&1) + echo "$t: exit=$? $out" + done + cp "$B/python3.14" "$B/python3.12" + done 2>&1 | tee "$RUNNER_TEMP/results/launcher-choice.txt" + + - name: Real SDK installs + env: + PYTHONUTF8: '1' + run: | + mkdir -p "$RUNNER_TEMP/results" + python harness/.github/scripts/sg_platform_sdk_bootstrap.py \ + main/plugins/security-guidance pr/plugins/security-guidance 2>&1 \ + | tee "$RUNNER_TEMP/results/sdk-bootstrap.txt" + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: sdk-${{ matrix.os }} + path: ${{ runner.temp }}/results + if-no-files-found: warn + + # A push whose commit message contains [store-cert] runs only this job: a test certificate + # that OpenSSL cannot read goes into the runner user's own certificate store, and main and the + # pull request are run against it. + store-cert: + name: Unreadable store certificate, Python ${{ matrix.python }} on ${{ matrix.os }} + if: ${{ contains(github.event.head_commit.message, '[store-cert]') }} + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + os: [windows-latest] + python: ['3.11', '3.12', '3.13'] + include: + - os: windows-11-arm + python: '3.12' + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + with: + path: harness + - uses: actions/checkout@v4 + with: + ref: main + path: main + - uses: actions/checkout@v4 + with: + ref: refs/pull/6849/head + path: pr + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - name: Store check + env: + PYTHONUTF8: '1' + run: | + python -m pip install -q pytest + python harness/.github/scripts/sg_platform_store_cert.py \ + main/plugins/security-guidance pr/plugins/security-guidance + + compare: + name: Compare with main + needs: [suite, sdk-bootstrap] + if: ${{ always() && !contains(github.event.head_commit.message, '[store-cert]') }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + if: ${{ !contains(github.event.head_commit.message, '[report]') }} + with: + path: results + - uses: actions/download-artifact@v4 + if: ${{ contains(github.event.head_commit.message, '[report]') }} + with: + path: results + pattern: results-* + run-id: ${{ env.REPORT_RUN_ID }} + github-token: ${{ github.token }} + - uses: actions/download-artifact@v4 + if: ${{ contains(github.event.head_commit.message, '[report]') }} + with: + path: results + pattern: sdk-* + run-id: ${{ env.REPORT_SDK_RUN_ID }} + github-token: ${{ github.token }} + - name: Table + shell: bash + run: python3 .github/scripts/sg_platform_compare.py results | tee report.md | tee -a "$GITHUB_STEP_SUMMARY" + # The report again as annotations, ten to a step, for reading through the API. + - name: Report part 1 + run: python3 .github/scripts/sg_platform_annotate.py report.md 0 + - name: Report part 2 + run: python3 .github/scripts/sg_platform_annotate.py report.md 10 + - name: Report part 3 + run: python3 .github/scripts/sg_platform_annotate.py report.md 20 + - name: Report part 4 + run: python3 .github/scripts/sg_platform_annotate.py report.md 30 + - name: Report part 5 + run: python3 .github/scripts/sg_platform_annotate.py report.md 40 diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index caef1866..e0c4a888 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -31,7 +31,7 @@ All configuration is via environment variables. None are required for default be By default both reviews run on the newest Claude Opus, and move to the next one when it is released — there is no model version to bump: - The LLM diff review asks your API endpoint (`GET /v1/models`) which Opus models it serves and uses the newest. The answer is cached for a day in the plugin's state directory. If the endpoint can't answer, the review uses `claude-opus-5-5`. -- The agentic commit reviewer, and every review in a session signed in to a Claude apps gateway with `/login`, run through your installed Claude Code. Other reviews on Bedrock, Vertex, and Foundry run through the copy of Claude Code bundled with the Agent SDK, or `SG_AGENTIC_CLI_PATH` if set. All of them use Claude Code's `opus` alias: the model `/model opus` selects, including any `ANTHROPIC_DEFAULT_OPUS_MODEL` you have set. On a gateway that alias may name an older Opus than the newest one. +- The agentic commit reviewer, and every review in a session signed in to a Claude apps gateway with `/login`, run through your installed Claude Code. Other reviews on Bedrock, Vertex, and Foundry run through the copy of Claude Code bundled with the Agent SDK, or `SG_AGENTIC_CLI_PATH` if set. On Windows the agentic commit reviewer runs through the bundled copy too, unless `SG_AGENTIC_CLI_PATH` is set. Where the Agent SDK has no bundled copy for Windows, those reviews run through `~\.local\bin\claude.exe`, or else a `claude.exe` on `PATH`; if there is neither, set `SG_AGENTIC_CLI_PATH`. All of them use Claude Code's `opus` alias: the model `/model opus` selects, including any `ANTHROPIC_DEFAULT_OPUS_MODEL` you have set. On a gateway that alias may name an older Opus than the newest one. To pin a model, or to use a cheaper one: @@ -68,6 +68,7 @@ Claude Code does not pass your sign-in to plugins in a session started with `CLA | `ENABLE_CODE_SECURITY_REVIEW=0` | on | Disable all LLM reviews (Stop hook + commit/push) | | `ENABLE_STOP_REVIEW=0` | on | Disable only the Stop-hook diff review, keeping commit/push reviews. Useful for multi-agent / shared-worktree setups where another agent can move HEAD between a worker's turns | | `ENABLE_COMMIT_REVIEW=0` | on | Disable layer 3 (agentic commit review) | +| `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` | unset | Keep the reviewer's own Claude Code runs as session transcripts (see [Privacy and data handling](#privacy-and-data-handling)) | ### Hook output for other hosts @@ -93,6 +94,8 @@ Drop a `claude-security-guidance.md` in any of: - `<project>/.claude/claude-security-guidance.md` — project rules, intended to be committed - `<project>/.claude/claude-security-guidance.local.md` — local overrides, intended to be `.gitignore`'d +Project files must be regular files: a link there, or a `.claude` folder that is a link, is skipped. + All three are loaded and concatenated into the LLM diff review's prompt in the order user → project → project-local. If the combined size exceeds the 8 KB prompt budget, the tail is truncated, so user-wide rules are kept and project-local rules are dropped first. The agentic commit reviewer (layer 3) does not currently read this file. Example: ```markdown @@ -114,12 +117,14 @@ The plugin sends data to a model endpoint to perform its reviews. Specifically, Where that data goes depends on your Claude Code configuration: - **Default (Anthropic API / subscription):** sent to `api.anthropic.com` and handled under Anthropic's [Commercial Terms](https://www.anthropic.com/legal/commercial-terms) and [Privacy Policy](https://www.anthropic.com/legal/privacy). -- **LLM gateway** (`ANTHROPIC_BASE_URL` set): sent to your gateway URL instead, with the headers in `ANTHROPIC_CUSTOM_HEADERS` (except `anthropic-beta`). The gateway operator's terms apply. +- **LLM gateway** (`ANTHROPIC_BASE_URL` set to a URL): sent to your gateway URL instead, with the headers in `ANTHROPIC_CUSTOM_HEADERS` (except `anthropic-beta`). The gateway operator's terms apply. - **Claude apps gateway, signed in with `/login`:** your installed Claude Code sends the reviews to the gateway, using its own stored sign-in. The plugin never reads the sign-in. The gateway operator's terms apply. - **3rd-party providers** (Bedrock / Vertex / Foundry / Mantle): sent to your configured provider endpoint. The provider's data-handling terms apply (e.g., AWS / GCP / Azure). The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata, finding categories, the Agent SDK's own warnings and errors, and up to 20 lines of stderr from each Claude Code run the plugin starts for a review (20 in all for each agentic commit review, which starts several runs) — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded. +The agentic commit reviewer, and every review on a 3rd-party provider, runs an inner Claude Code through the Agent SDK. The plugin starts it with `--no-session-persistence`, so these runs are not saved as session transcripts under `~/.claude/projects/`. Set `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` to keep them, for example to debug a review; a saved transcript contains the full review prompt, including diff hunks, and is removed by Claude Code's normal session cleanup (`cleanupPeriodDays`). A Claude Code older than 2.0.63 does not have the flag; the review then runs without it and is saved as before. + ### Review usage and cost The LLM reviews use your API path, so they cost tokens (or subscription usage) on top of your own session. The default reviewer is the newest Opus model. On the Anthropic API path the diff review on Stop calls the API directly, so it does not appear in Claude Code's own cost figures or transcripts. After each review the plugin writes one line to its debug log: @@ -143,6 +148,8 @@ This is a best-effort assistive tool, not a guarantee. Treat findings as suggest **Plugin doesn't seem to fire** — check that `~/.claude/claude-security-guidance.md` (or hook activity) shows in debug logs. Run Claude Code with `--debug-file /tmp/claude/debug.txt` and grep for `security_reminder_hook`. The plugin also writes its own log to `~/.claude/security/log.txt`. +**Looking into one commit review** — set `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` before the run; the reviewer's prompt, tool calls and answer are then kept as session transcripts under `~/.claude/projects/`. + **Review never finds anything** — verify your API path works, and that credentials reach the plugin (see [Credentials](#credentials)): `~/.claude/security/log.txt` says `no API credentials` when they don't. When a commit or push review gets no usable answer from the model, Claude is told once per session for each kind of review and failure (for example "Commit security review did not complete: …"), and the reason is logged. If a commit whose review failed is pushed later from Claude Code, the push review checks it. On 3P providers, if you set `SECURITY_REVIEW_MODEL`, check it is a provider-specific id your account can invoke. On LLM gateways, check the gateway's logs for `POST /v1/messages` traffic from the plugin. In a session signed in to a Claude apps gateway with `/login`, reviews run only when `claude auth status` shows the gateway and that you are logged in. They run through the Claude Code at `~/.local/bin/claude`, where the native installer puts it on macOS and Linux. On Windows, or for any other install, set `SG_AGENTIC_CLI_PATH` to its full path. **Too many false positives** — set `SECURITY_REVIEW_MODEL` to a cheaper model (`claude-sonnet-5-5`) and re-evaluate; if precision is the priority, stay on the default. diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 28b189a4..99607e4a 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -9,9 +9,17 @@ import glob import json import os import re +import stat +import sys import threading from datetime import datetime +if os.name == "nt": + # Unless this variable exists, Windows looks for a program that is started + # by name in the working directory before PATH. + os.environ.setdefault("NoDefaultCurrentDirectoryInExePath", "1") + + def state_dir(): """Return the absolute path of the plugin's state directory. @@ -42,6 +50,26 @@ def state_dir(): return os.path.abspath(os.path.expanduser(d)) +def make_state_dir(d=None): + """Create the state dir (or `d`) with access for its user alone, and + narrow the default one to that if it is already there, so a umask such as + 002 does not leave the reviewer's venv, logs and session state open to the + rest of a shared group. A folder named by SECURITY_WARNINGS_STATE_DIR + that already exists is the user's to set. Raises OSError like os.makedirs.""" + if d is None: + d = state_dir() + os.makedirs(d, mode=0o700, exist_ok=True) + if (os.name != "nt" and not os.environ.get("SECURITY_WARNINGS_STATE_DIR", "").strip() + and os.path.abspath(d) == state_dir()): + try: + st = os.lstat(d) + if stat.S_ISDIR(st.st_mode) and st.st_uid == os.getuid() and st.st_mode & 0o077: + os.chmod(d, 0o700) + except OSError: + pass + return d + + def llm_reviews_switched_off(): """True when the environment turns off every review that calls a model: the kill switch (SECURITY_GUIDANCE_DISABLE=1 / ENABLE_SECURITY_REMINDER=0), @@ -212,7 +240,7 @@ _USAGE = { # reported it manually. "http_err_last": 0, # most recent HTTP error code this invocation "http_err_count": 0, # total HTTP errors (4xx + 5xx + network) - "net_err": 0, # why the last call got no HTTP response, 0 if it got one + "net_err": 0, # why the deciding call got no HTTP response, 0 if it got one # For the usage log line only: model ids as recorded (the requested alias # on the Agent SDK path), and whether any call had no price-table entry. "models": [], @@ -308,7 +336,9 @@ def _record_net_error(code): raises outside its own error type (a default TLS context that cannot be built, a connection closed before the reply) has no `api_error` at all. Emitted as `net_err` on the row of a hook whose last call failed this - way; a later call clears it.""" + way; a later call clears it, and so does a call that gets through beside + it (a second probe, the other leg of a dual review, the agentic run that + wins a race).""" try: c = int(code) except (TypeError, ValueError): @@ -378,6 +408,117 @@ def launcher_probe_metrics(): return {"launcher_probe_ms": min(total, cap), "launcher_probe_max_ms": min(slowest, cap)} +def launcher_direct_metric(): + """`launcher_direct` when sg-python.sh ran this hook with the interpreter + behind a packaged Windows alias instead of the alias: 1 from the path it + remembered (one process for the hook), 2 when it had just worked that + path out. Read once, like the probe timings. + """ + how = os.environ.pop("SG_LAUNCHER_DIRECT", "") + return {"launcher_direct": int(how)} if how in ("1", "2") else {} + + +# Reparse tags that redirect every open below them: symbolic links and +# junctions. App execution aliases (the entries under WindowsApps) carry +# another tag and are not counted. +_SYMLINK_TAG, _MOUNT_POINT_TAG = 0xA000000C, 0xA0000003 + + +def _is_link(path, st, readlink): + """True iff `path` (with lstat result `st`) is a symbolic link or a + junction, None when that cannot be told (Python older than 3.8 has no + reparse tag). A volume mounted at a folder has the junction tag too; its + target is the bare volume name.""" + if not getattr(st, "st_file_attributes", 0) & 0x400: # FILE_ATTRIBUTE_REPARSE_POINT + return False + tag = getattr(st, "st_reparse_tag", None) + if tag is None: + return None + if tag == _MOUNT_POINT_TAG: + try: + target = readlink(path).lstrip("\\?").rstrip("\\").lower() + except (OSError, ValueError, NotImplementedError): + return True + return not (target.startswith("volume{") and target.endswith("}")) + return tag == _SYMLINK_TAG + + +def interp_reparse_metric(executable=None, base_prefix=None, environ=None, platform=None, + lstat=None, readlink=None): + """`interp_reparse`, on Windows: whether the interpreter running this + hook is reached through a symbolic link or junction. Bits: + + 1 the path of the executable goes through one + 2 the path of the standard library (sys.base_prefix) goes through one + 4 such a path, as spelled, is under the user's AppData folders (a + uv-managed Python, for one) + 8 one of the two paths could not be checked + + 0 is sent too, so a Windows row without the key is a row that lost it, + not a "no". Measurement only, on the SessionStart row. It sizes how many + sessions start Python through such a link: inside the packaged Claude + Desktop app, Windows leaks kernel memory on every file opened that way, + and each hook starts an interpreter. See anthropics/claude-code#96870. + + No process is started: one lstat per folder on the two paths, up to the + first link. Where the link points is not followed, and an 8.3 short name + on one side reads as "not under AppData" (bit 4 missing, 1 and 2 right). + The plugin's own folders are not looked at. + + The arguments stand in for the interpreter and the system in tests. + """ + if (platform or sys.platform) != "win32": + return {} + executable = sys.executable if executable is None else executable + base_prefix = getattr(sys, "base_prefix", "") if base_prefix is None else base_prefix + environ = os.environ if environ is None else environ + lstat = lstat or os.lstat + readlink = readlink or os.readlink + + def spelled(p): + # For comparing only: lower case, no \\?\ prefix. + p = os.path.normcase(p) + return p[4:] if p.startswith("\\\\?\\") and not p.startswith("\\\\?\\unc\\") else p + + value = 0 + roots = [] + for name in ("APPDATA", "LOCALAPPDATA"): + try: + root = environ.get(name) + if root: + roots.append(spelled(os.path.abspath(root)).rstrip("\\/")) + except Exception: + pass + checked = {} + for bit, start in ((1, executable), (2, base_prefix)): + try: + if not start: + continue + p = start = os.path.abspath(start) + linked = False + while not linked: + parent = os.path.dirname(p) + if parent == p: + break + if p not in checked: + try: + checked[p] = _is_link(p, lstat(p), readlink) + except FileNotFoundError: + checked[p] = False + if checked[p] is None: + value |= 8 + linked = bool(checked[p]) + p = parent + if linked: + value |= bit + here = spelled(start) + if any(here == r or here.startswith(r + os.sep) for r in roots): + value |= 4 + except Exception: + value |= 8 + return {"interp_reparse": value} + + def _usage_metrics(): """Snapshot the accumulator as metric keys. Returns {} when no API calls AND no HTTP errors were made so skip-path emits don't burn key budget. diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 9ba40385..34655335 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -13,11 +13,12 @@ import sys import time from _base import debug_log, portable_output, _PV +import gitutil from gitutil import ( GIT_CMD, _git_dir, _git_toplevel, _git_status_porcelain, _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, - index_entry_count, + _secret_rename_origins, index_entry_count, ) from session_state import with_locked_state from extensibility import _same_dir @@ -319,7 +320,7 @@ def get_baseline_file_content(session_id, file_path, cwd): # How the last capture_git_baseline call got its SHA: 0 a real snapshot, -# 1 `stash create` failed and HEAD was returned, 2 no index copy and HEAD was +# 1 the snapshot failed and HEAD was returned, 2 no index copy and HEAD was # returned. With 1 or 2 the next Stop review cannot tell the turn's changes # from uncommitted work that was already there. Stored with baseline_sha. # Telemetry only. @@ -328,29 +329,110 @@ last_baseline_fail = 0 last_index_entries = None +# Who the snapshot commit is made by. Set on every commit-tree call, so the +# user's own name never appears on a commit they did not make and a repo with +# no identity configured still works. The commit object does land in +# `.git/objects`, but nothing refers to it, like the one `git stash create` +# used to make here: it is prunable from the moment it is written. +_SNAPSHOT_IDENT = { + "GIT_AUTHOR_NAME": "security-guidance", "GIT_AUTHOR_EMAIL": "security-guidance@localhost", + "GIT_COMMITTER_NAME": "security-guidance", "GIT_COMMITTER_EMAIL": "security-guidance@localhost", +} + +# The whole snapshot, not one command: `stash create` was capped at 15 s and a +# per-command cap would let a slow filesystem hold the prompt for far longer. +_SNAPSHOT_BUDGET_S = 15 + + +def _snapshot_commit(cwd, env, head_tree): + """A commit of every tracked change, on the index copy `env` names. + + Returns its SHA, "" when nothing tracked has changed (so the caller uses + HEAD, `head_tree` being HEAD's tree), or None when git refused or the + time budget ran out. + + No `--missing-ok`: git counts a partial clone's promisor blobs as + present, so write-tree neither fetches nor fails on one, and the + existence check it would turn off is worth keeping. + """ + deadline = time.monotonic() + _SNAPSHOT_BUDGET_S + + def run(args, extra=None): + left = deadline - time.monotonic() + if left <= 0: + raise subprocess.TimeoutExpired(args, _SNAPSHOT_BUDGET_S) + return subprocess.run( + [*GIT_CMD, *args], cwd=cwd, capture_output=True, timeout=left, + env={**env, **(extra or {})}, + ) + + # No pathspec: `add -u` has staged the whole work tree, whatever directory + # of it `cwd` is, since git 2.0. `-- :/` would say the same but fails + # outright under a user's GIT_LITERAL_PATHSPECS. + add = run(["add", "-u"]) + if add.returncode != 0: + debug_log(f"Snapshot: add -u failed: {_stderr_of(add)}") + return None + tree = run(["write-tree"]) + sha = (tree.stdout or b"").decode("utf-8", errors="replace").strip() + if tree.returncode != 0 or not sha: + debug_log(f"Snapshot: write-tree failed: {_stderr_of(tree)}") + return None + if sha == head_tree: + return "" + if gitutil.last_dropped_gitlinks: + # A nested repository's entry is gone from the index copy, so the + # tree cannot equal HEAD's even on a clean work tree. Ask whether + # anything but those entries differs, rather than writing a commit + # object on every prompt in a repo with submodules. + same = run(["diff-tree", "--quiet", "--ignore-submodules=all", head_tree, sha]) + if same.returncode == 0: + return "" + commit = run(["-c", "commit.gpgsign=false", "commit-tree", sha, "-p", "HEAD", + "-m", "security-guidance turn baseline"], _SNAPSHOT_IDENT) + out = (commit.stdout or b"").decode("utf-8", errors="replace").strip() + if commit.returncode != 0 or not out: + debug_log(f"Snapshot: commit-tree failed: {_stderr_of(commit)}") + return None + return out + + +def _stderr_of(result): + return (result.stderr or b"").decode("utf-8", errors="replace").strip()[:200] + + def capture_git_baseline(cwd): """ Capture a git ref representing the current working tree state. - Uses `git stash create` which creates a commit object for the current state - (HEAD + uncommitted changes) without modifying the stash list or working tree. + Builds a commit object for the current state (HEAD + uncommitted changes) + without touching the stash list or the working tree: `add -u` stages every + tracked change into a throwaway index copy, `write-tree` turns that into a + tree, and `commit-tree` hangs it off HEAD. Falls back to HEAD if the working tree is clean. Returns the SHA string, or None if not in a git repo or if the repo has no commits. - `stash create` runs on a throwaway copy of the index (GIT_INDEX_FILE), so - its `index.lock` and `index.stash.<pid>` files land next to the copy, not - in `.git`: it cannot collide with a concurrent git command, and a timeout - kill cannot leave a lock that blocks the user's next one. - GIT_OPTIONAL_LOCKS does not cover stash. Copying the real index without a - lock is safe: git replaces it by atomic rename. - - NOTE: `git stash create` does NOT capture untracked files. UPS pairs this + This was `git stash create`, which does the same thing in one command but + checks the work tree on a single thread, while `add -u` uses git's index + preload (one thread per 500 entries, up to 20). On a filesystem where each + file status is slow — a WSL repository on a Windows drive, a network mount + — that is the whole cost of the prompt: see #6854, where `stash create` + took 4 s on 1,424 files and never finished on 10,000. + + The commands run on a throwaway copy of the index (GIT_INDEX_FILE), so + their `index.lock` lands next to the copy, not in `.git`: they cannot + collide with a concurrent git command, and a timeout kill cannot leave a + lock that blocks the user's next one. GIT_OPTIONAL_LOCKS does not cover + these. Copying the real index without a lock is safe: git replaces it by + atomic rename. + + NOTE: the snapshot does NOT capture untracked files. UPS pairs this SHA with a `_list_untracked()` snapshot stored as `untracked_at_baseline`, and `compute_v2_review_set` subtracts that set so pre-existing untracked files are not reviewed as Claude-authored. UPS takes no snapshot while the Stop review, its only reader, is switched off. """ # stdout is a SHA so text=True is safe on stdout, but a non-ASCII - # filename in `git stash create`'s STDERR warning (e.g. a worktree + # filename in git's STDERR warning (e.g. a worktree # with `Ávila_report.txt` triggers a quotePath/locale warning) would # trip the stderr reader thread on Windows cp1252. Decode both streams # leniently for symmetry with _list_untracked. See #2056. @@ -358,15 +440,19 @@ def capture_git_baseline(cwd): last_baseline_fail = 0 last_index_entries = None try: - # Check if HEAD exists (i.e., repo has at least one commit) + # HEAD's commit and its tree in one call: the commit is the answer + # for a clean tree, the tree is what the snapshot is compared with. + # A failure here means the repo has no commits — skip the review + # rather than create commits in the user's repo. head_check = subprocess.run( - [*GIT_CMD, "rev-parse", "HEAD"], + [*GIT_CMD, "rev-parse", "HEAD", "HEAD^{tree}"], cwd=cwd, capture_output=True, timeout=5 ) - if head_check.returncode != 0: - # No commits yet — skip review rather than creating commits in the user's repo + head_out = (head_check.stdout or b"").decode("utf-8", errors="replace").split() + if head_check.returncode != 0 or len(head_out) != 2: debug_log("No commits in repo, skipping baseline capture") return None + head_sha, head_tree = head_out sha = "" # untracked_paths=[]: a plain copy of the index, no `add -N` pass. @@ -375,25 +461,14 @@ def capture_git_baseline(cwd): # back to HEAD. if env is not None: last_index_entries = index_entry_count(env["GIT_INDEX_FILE"]) - result = subprocess.run( - [*GIT_CMD, "stash", "create"], - cwd=cwd, capture_output=True, timeout=15, env=env - ) - sha = (result.stdout or b"").decode("utf-8", errors="replace").strip() - if not sha and result.returncode != 0: + sha = _snapshot_commit(cwd, env, head_tree) + if sha is None: last_baseline_fail = 1 + sha = "" else: last_baseline_fail = 2 - if sha: - return sha - - # Working tree is clean — stash create returns empty. Use HEAD. - result = subprocess.run( - [*GIT_CMD, "rev-parse", "HEAD"], - cwd=cwd, capture_output=True, timeout=5 - ) - sha = (result.stdout or b"").decode("utf-8", errors="replace").strip() - return sha if sha else None + # No snapshot: nothing tracked has changed, or it could not be taken. + return sha or head_sha except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: debug_log(f"Failed to capture git baseline: {e}") return None @@ -997,12 +1072,12 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel review_set = (files dirty vs current HEAD, plus files committed this turn when HEAD advanced linearly) ∩ (files whose content differs from the - pre-turn stash baseline). The first term is immune to checkout/pull + pre-turn baseline). The first term is immune to checkout/pull ballooning; the second filters out the user's untouched pre-turn WIP. Falls back to dirty_now alone when no baseline is available. untracked_at_baseline: {repo-root-relative path: mtime_ns} captured at - UPS. `git stash create` doesn't include untracked files, so without this + UPS. The baseline snapshot doesn't include untracked files, so without this snapshot a pre-existing untracked file looks "new since baseline" forever. A file is excluded only if it was untracked at baseline AND its mtime is unchanged — an in-place edit during the turn is still reviewed. @@ -1073,11 +1148,11 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel dirty_now |= _git_name_only(repo, f"{head_at_capture}..HEAD") or set() diff_base = head_at_capture - # changed_since: tracked files vs the stash baseline (no `add -N` — the - # stash never contained untracked files anyway), then union with + # changed_since: tracked files vs the turn baseline (no `add -N` — the + # baseline never contained untracked files anyway), then union with # currently-untracked. The previous `include_untracked=True` arm cost a # full `git add -N .` (slow in large repos) per call to surface - # untracked files in the diff output — but `git diff <stash>` already + # untracked files in the diff output — but `git diff <baseline>` already # lists them as "only in worktree" without that, and we have the explicit # set from status regardless. if baseline_sha: @@ -1087,9 +1162,13 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel else: changed_since = None # changed_since is None on missing baseline OR on git error (e.g. the - # dangling stash SHA was pruned). Either way, don't intersect with ∅ — + # dangling baseline SHA was pruned). Either way, don't intersect with ∅ — # that would silently zero the review set. Fall back to dirty_now. review_set = (dirty_now & changed_since) if changed_since is not None else dirty_now + # Kept beside its new name so that the content diff pairs the two. + secret_origins = { + old for new, old in _secret_rename_origins.items() if new in review_set} + review_set = review_set | secret_origins review_paths = [os.path.join(repo, p) for p in sorted(review_set)] untracked_in_review = sorted(new_untracked & review_set) @@ -1101,4 +1180,6 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel # Only emit when nonzero to stay under the 10-key telemetry cap. if preexisting_unchanged: metrics["preexisting_untracked_excluded"] = len(preexisting_unchanged) + if secret_origins: + metrics["secret_renamed"] = len(secret_origins) return review_paths, diff_base, repo, untracked_in_review, metrics diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index d3aaf96b..30119f8c 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -28,10 +28,11 @@ from pathlib import Path # here to match the existing local name (state_dir was already a local var in # main() and _maybe_emit_user_notice). from _base import ( - launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir, + interp_reparse_metric, launcher_direct_metric, launcher_probe_metrics, portable_output, + state_dir as _resolve_state_dir, write_hook_output, ) -from _base import llm_reviews_switched_off +from _base import llm_reviews_switched_off, make_state_dir def _spawn_cwd() -> str: @@ -46,8 +47,7 @@ def _spawn_cwd() -> str: """ d = _resolve_state_dir() try: - os.makedirs(d, exist_ok=True) - return d + return make_state_dir(d) except OSError: return str(Path(__file__).resolve().parent.parent) @@ -77,6 +77,8 @@ SKIP_COOLDOWN = 9 # a recent build was signal-killed (memory pressure) — no # repro confirmed the dominant Linux BUILD_FAILED is a # SIGKILL/SIGSEGV of the memory-heavy venv+pip subprocess # (rc<0, empty streams). See #2154 follow-up. + # Also, for a shorter time, after a pip install ran out + # of time (sdk_timeout_cooldown says which). See #6979. SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would # load the SDK (kill switch included), so nothing is # installed. See #5331. @@ -86,6 +88,14 @@ SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would # session). Keyed by marker mtime. SIGNAL_KILL_COOLDOWN_SEC = 24 * 3600 +# How long to skip rebuilds after a pip install ran out of time. On a +# connection too slow to fetch the SDK wheel inside the limit, every attempt +# downloads most of the wheel and throws it away, and attempts come at every +# SessionStart and every 5 minutes from the tool hooks. Shorter than the +# signal-kill window because a slow or stalled connection is often temporary. +# See #6979. +PIP_TIMEOUT_COOLDOWN_SEC = 3600 + # Phase + err-kind integer encoding for sdk_bootstrap_phase / sdk_bootstrap_err. # @@ -241,23 +251,37 @@ def _is_signal_kill(returncode) -> bool: return returncode < 0 or returncode in (134, 137, 139) -def _cooldown_remaining(state_dir) -> float: - """Seconds left in the signal-kill cooldown (0 if none/expired). Reads the - marker's mtime; a missing/unreadable marker means not in cooldown.""" - marker = Path(state_dir) / "agent-sdk-venv.cooldown" +_SIGNAL_KILL_MARKER = "agent-sdk-venv.cooldown" +_PIP_TIMEOUT_MARKER = "agent-sdk-venv.timeout" + + +def _marker_remaining(state_dir, name, window) -> float: + """Seconds left of the `window` that started at the marker's mtime; a + missing/unreadable marker means not in cooldown.""" try: - age = time.time() - marker.stat().st_mtime + age = time.time() - (Path(state_dir) / name).stat().st_mtime except OSError: return 0.0 - return max(0.0, SIGNAL_KILL_COOLDOWN_SEC - age) + # A marker stamped in the future (clock set back since) counts as fresh. + return min(float(window), max(0.0, window - age)) + + +def _cooldown_remaining(state_dir) -> float: + """Seconds left in the signal-kill cooldown (0 if none/expired).""" + return _marker_remaining(state_dir, _SIGNAL_KILL_MARKER, SIGNAL_KILL_COOLDOWN_SEC) + +def _timeout_cooldown_remaining(state_dir) -> float: + """Seconds left in the pip-timeout cooldown (0 if none/expired).""" + return _marker_remaining(state_dir, _PIP_TIMEOUT_MARKER, PIP_TIMEOUT_COOLDOWN_SEC) -def _write_cooldown(state_dir) -> None: - """Start/refresh the signal-kill cooldown so we stop re-attempting a build - that keeps getting killed every session. Best-effort.""" + +def _write_cooldown(state_dir, name=_SIGNAL_KILL_MARKER) -> None: + """Start/refresh a cooldown (the signal-kill one unless named) so we stop + re-attempting a build that keeps failing the same way. Best-effort.""" try: - Path(state_dir).mkdir(parents=True, exist_ok=True) - (Path(state_dir) / "agent-sdk-venv.cooldown").write_text( + make_state_dir(str(state_dir)) + (Path(state_dir) / name).write_text( time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())) except OSError: pass @@ -429,6 +453,8 @@ _SDK_IMPORT_PROBE = ( # Set by main() when the venv's probe exited with _PROBE_EMPTIED. _venv_was_emptied = False +# Set by main() when it skipped the build for the pip-timeout cooldown. +_skipped_for_pip_timeout = False def _target_dir(state_dir) -> Path: @@ -455,6 +481,63 @@ def _target_sdk_importable(state_dir) -> bool: return False +# pip keeps every wheel it downloads in a `pip-unpack-*` folder under the temp +# dir and removes it only when it exits normally. An install killed at the +# timeout (or by the OOM killer) left those folders in the system temp dir, +# one attempt after another. See #6979. So pip gets a temp folder of its own +# under the state dir: removed when the attempt ends, however it ends, and +# swept on a later run when the bootstrap itself was killed first. +_PIP_TIMEOUT_SEC = 120 +# Older than any install can be: the folder of a bootstrap that was killed. +_PIP_TEMP_STALE_SEC = 15 * 60 + + +def _pip_temp_root(state_dir) -> Path: + return Path(state_dir) / "pip-tmp" + + +def _sweep_pip_temp(state_dir) -> None: + """Remove pip temp folders left by a bootstrap that was killed before it + could remove its own. Best-effort; a folder still in use is too young.""" + try: + entries = list(_pip_temp_root(state_dir).iterdir()) + except OSError: + return # the usual case: nothing was ever left + import shutil + now = time.time() + for entry in entries: + try: + if now - entry.stat().st_mtime > _PIP_TEMP_STALE_SEC: + shutil.rmtree(entry, ignore_errors=True) + except OSError: + pass + + +def _run_pip_install(cmd, state_dir): + """Run a `pip install` command under the timeout, with its temp files in + a folder of ours. Raises what subprocess.run(check=True) raises. Falls + back to the inherited temp dir when the folder can't be made.""" + import shutil + import tempfile + tmp = env = None + try: + root = _pip_temp_root(state_dir) + root.mkdir(parents=True, exist_ok=True) + tmp = tempfile.mkdtemp(dir=root) + # tempfile reads TMPDIR, TEMP, TMP in that order on every platform. + env = {**os.environ, "TMPDIR": tmp, "TEMP": tmp, "TMP": tmp} + except OSError: + pass + try: + return subprocess.run( + cmd, capture_output=True, timeout=_PIP_TIMEOUT_SEC, check=True, + cwd=_spawn_cwd(), env=env, + ) + finally: + if tmp is not None: + shutil.rmtree(tmp, ignore_errors=True) + + def _build_via_target(state_dir) -> tuple[int, str, str]: """Fallback install when `python -m venv` can't bootstrap pip (ensurepip missing — Debian python3-venv absent, or a python.org/pyenv build without @@ -468,12 +551,12 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: preference (ARM64 Windows cryptography).""" target = _target_dir(state_dir) try: - subprocess.run( + _run_pip_install( [sys.executable, "-m", "pip", "install", "--target", str(target), "--upgrade", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), + state_dir, ) return BUILT_TARGET, "", "" except subprocess.CalledProcessError as e: @@ -484,6 +567,7 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: return BUILD_FAILED, "pip_target", f"signal_killed:{e.returncode}" return BUILD_FAILED, "pip_target", _pip_err_from_stderr(e.stderr) except subprocess.TimeoutExpired: + _write_cooldown(state_dir, _PIP_TIMEOUT_MARKER) return BUILD_FAILED, "pip_target", "subprocess_timeout" except Exception as e: errno = getattr(e, "errno", None) @@ -544,10 +628,16 @@ def _install_context_metrics(outcome, state_dir) -> dict: dependencies do not load there. See #5706. sdk_venv_emptied: the venv's SDK package directory had lost its files - and this run went on to rebuild it, whatever the outcome. See #6612.""" + and this run went on to rebuild it, whatever the outcome. See #6612. + + sdk_timeout_cooldown: this run skipped the build (SKIP_COOLDOWN) because + a pip install ran out of time, not because one was signal-killed. See + #6979.""" out = {} if _venv_was_emptied: out["sdk_venv_emptied"] = 1 + if _skipped_for_pip_timeout: + out["sdk_timeout_cooldown"] = 1 if outcome not in (NOOP_VENV, BUILT, BUILT_TARGET, NOOP_TARGET): return out try: @@ -593,8 +683,11 @@ def main() -> tuple[int, str, str]: err_phase / err_kind are non-empty only on BUILD_FAILED — they let telemetry split bootstrap failures by root cause. """ - global _venv_was_emptied + global _venv_was_emptied, _skipped_for_pip_timeout _venv_was_emptied = False + _skipped_for_pip_timeout = False + # Before any early return: nothing else ever clears the state dir. + _sweep_pip_temp(_resolve_state_dir()) # The SDK only serves the LLM reviews. With those switched off, or the # whole plugin (SECURITY_GUIDANCE_DISABLE=1), a venv of a few hundred MB # would be built for code that never runs, and the notice below would @@ -676,12 +769,16 @@ def main() -> tuple[int, str, str]: # system/venv/target still short-circuits above. if _cooldown_remaining(state_dir) > 0: return SKIP_COOLDOWN, "", "" + # Likewise after a pip install that ran out of time, for a shorter while. + if _timeout_cooldown_remaining(state_dir) > 0: + _skipped_for_pip_timeout = True + return SKIP_COOLDOWN, "", "" err_phase = "" err_kind = "" we_own_sentinel = False try: - state_dir.mkdir(parents=True, exist_ok=True) + make_state_dir(str(state_dir)) # O_EXCL makes the sentinel an atomic lock — if two SessionStarts # race past the exists() check above, only one creates it. try: @@ -712,11 +809,11 @@ def main() -> tuple[int, str, str]: # --no-cache-dir trims pip's peak memory (no cache read/write/unpack # buffering) — helps marginal low-memory machines get under the OOM # threshold that kills the dominant Linux builds (CCR repro). - subprocess.run( + _run_pip_install( [str(venv_py), "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), + state_dir, ) return BUILT, "", "" except subprocess.CalledProcessError as e: @@ -814,6 +911,10 @@ def main() -> tuple[int, str, str]: return _build_via_target(state_dir) return BUILD_FAILED, err_phase, err_kind except subprocess.TimeoutExpired: + # Only the download is known to repeat; a slow `python -m venv` is + # more likely a busy machine, and the next attempt may be quicker. + if err_phase == "pip": + _write_cooldown(state_dir, _PIP_TIMEOUT_MARKER) return BUILD_FAILED, err_phase, "subprocess_timeout" except Exception as e: # Embed errno for OSError-family exceptions ("exc:OSError:28") so @@ -847,8 +948,9 @@ def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None: Currently only HOOK_PY_INCOMPATIBLE qualifies. BUILD_FAILED is intentionally excluded — it covers transient causes (network failure, - pip registry hiccup, in-flight rebuild) where the next session may - succeed and a permanent notice would mislead. + pip registry hiccup, in-flight rebuild, a download that ran out of + time) where a later session may succeed and a permanent notice would + mislead. """ if outcome != HOOK_PY_INCOMPATIBLE: return None @@ -857,7 +959,7 @@ def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None: marker = state_dir / f".agentic_unavailable_notice_v{pv or 0}" if marker.exists(): return None - state_dir.mkdir(parents=True, exist_ok=True) + make_state_dir(str(state_dir)) # Write timestamp + Python version so the marker is self-documenting # if a user goes looking. O_EXCL would be racier with no real win # (two concurrent SessionStarts both showing the notice once is fine). @@ -977,6 +1079,10 @@ if __name__ == "__main__": if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": metrics["launcher_fallback"] = 1 metrics.update(launcher_probe_metrics()) + metrics.update(launcher_direct_metric()) + # Last, so it is the first key a row over Claude Code's key cap (20, 10 + # in older versions) loses. + metrics.update(interp_reparse_metric()) response: dict[str, object] = {"metrics": metrics} # One-time user-visible notice when the agentic reviewer is dead on # arrival. Uses hookSpecificOutput.additionalContext (SessionStart's diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index ed332c99..d27e9173 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -30,6 +30,9 @@ Trust model: built-in ones. Reminder length is capped. - Custom regexes are validated at load for catastrophic-backtracking structure and skipped (with a debug log) if they look ReDoS-prone. + - A project file that is a link, or sits under a ``.claude`` that is one, is + skipped (with a debug log). User files may be links, as dotfile managers + make them. - Built-in patterns cannot be disabled. ``ENABLE_PATTERN_RULES=0`` disables all pattern checks; there is no per-rule kill switch in v1. """ @@ -125,13 +128,30 @@ def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str]]: return paths +def _readable_config(path: str, cwd: Optional[str]) -> bool: + """Whether a config file may be read. A project file (`cwd` given) must be + a regular file at that very place: a link, or a `.claude` that is one, + would bring in text from wherever it points.""" + if cwd is None or not os.path.lexists(path): + return True + expected = os.path.join(os.path.realpath(cwd), os.path.relpath(path, cwd)) + real = os.path.realpath(path) + if os.path.normcase(real) == os.path.normcase(expected) and os.path.isfile(real): + return True + debug_log(f"extensibility: skipping {path}: a link, or not a regular file") + return False + + def _load_guidance(cwd: Optional[str]) -> str: parts = [] for label, path in _config_paths(cwd, GUIDANCE_BASENAME): + if not _readable_config(path, cwd if label.startswith("Project") else None): + continue try: with open(path, encoding="utf-8") as f: txt = f.read().strip() - except OSError: + except (OSError, UnicodeDecodeError) as e: + debug_log(f"extensibility: skipping {path}: {type(e).__name__}") continue if txt: parts.append(f"### {label} security guidance\n{txt}") @@ -148,9 +168,14 @@ def _load_guidance(cwd: Optional[str]) -> str: return combined +_GUIDANCE_END_TAG = re.compile(r"<(\s*/\s*project-security-guidance)", re.IGNORECASE) + + def _wrap_guidance(guidance: str) -> str: if not guidance: return "" + # The block ends at its own closing tag, not at one in the text it holds. + guidance = _GUIDANCE_END_TAG.sub(r"<\1", guidance) return ( "\n\n<project-security-guidance>\n" "The user has provided project-specific security guidance below. " @@ -178,6 +203,8 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]: # One unusable file is skipped on its own, so the rules from the # other locations still load. try: + if not _readable_config(candidate, cwd if label.startswith("Project") else None): + continue found = _rules_from_file(candidate, label) except Exception as e: debug_log(f"extensibility: skipping {candidate}: {type(e).__name__}: {e}") diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index ec51e3c6..4c363ef4 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -27,8 +27,39 @@ import time from _base import debug_log +def _git_program(windows=os.name == "nt"): + """How to start git. On Windows a bare name is looked up in the process's + working directory before PATH, and the hooks run in the project, so a + `git.exe` there would start in place of the installed one. Name the first + git.exe on PATH instead, leaving out relative entries, the working + directory, and folders inside the project (unless the project holds the + home folder, and with it the user's own tools). With none, a path that + does not exist: git is reported missing, as it would be anywhere else.""" + if not windows: + return "git" + def norm(p): + return os.path.normcase(os.path.normpath(p)) + try: + cwd = norm(os.getcwd()) + except OSError: + cwd = "" + home = norm(os.path.expanduser("~")) + os.sep + roots = [norm(r) for r in (cwd, os.environ.get("CLAUDE_PROJECT_DIR")) if r] + roots = [r.rstrip(os.sep) + os.sep for r in roots if not home.startswith(r.rstrip(os.sep) + os.sep)] + for d in os.environ.get("PATH", "").split(os.pathsep): + d = d.strip().strip('"') + if not d or not os.path.isabs(d) or norm(d) == cwd: + continue + if any((norm(d) + os.sep).startswith(r) for r in roots): + continue + path = os.path.join(d, "git.exe") + if os.path.isfile(path): + return path + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "git.exe") + + GIT_CMD = [ - "git", + _git_program(), "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", # core.quotePath=false: emit raw UTF-8 in path-emitting commands instead @@ -62,6 +93,10 @@ GIT_CMD = [ # _drop_gitlinks for the commands that take no such setting. "-c", "diff.ignoreSubmodules=all", "-c", "diff.submodule=short", + # `git log` and `git show` print commit metadata for the hooks to parse. + # With log.showSignature set they would also verify each signed commit, + # adding lines to the output and starting the program gpg.program names. + "-c", "log.showSignature=false", ] # diff.ignoreSubmodules is a default that the repository's own settings for @@ -74,6 +109,7 @@ SAFE_GIT_CONFIG = ( ("core.hooksPath", "/dev/null"), ("diff.ignoreSubmodules", "all"), ("diff.submodule", "short"), + ("log.showSignature", "false"), ) # The hook's git runs in the background beside the session's own git. Without @@ -295,12 +331,17 @@ _path_list_too_long = set() # A failed `git add --intent-to-add` during this hook run, for the Stop hook's # metrics: kind * 100000 + the paths the add was given. One number because a -# review row is near CC's key cap. A failed add leaves the new files out of the -# diff, so a turn that only added files looks like a turn with no changes; a -# timeout loses the whole diff. kind: 1 git could not write the empty blob to -# the object store, 2 any other git error, 3 timeout. A git that speaks another -# language counts as 2. -_add_failed = {"code": 0} +# review row is near CC's key cap. kind: 1 git could not write the empty blob +# to the object store and the retry failed too, 2 any other git error, 3 +# timeout, 4 the retry with a private object directory worked. A git that +# speaks another language reports a failed retry as 2. With 1 to 3 the new +# files are not in the diff, so a turn that only added files looks like a turn +# with no changes. `left_out` says so for the last get_git_diff alone: the code +# stays set through a fallback diff that worked. +_add_failed = {"code": 0, "left_out": False} + +# Next to an index copy: where a retried `git add -N` stores the empty blob. +_OBJECTS_DIR_SUFFIX = ".objects" def _too_many_args(e): @@ -398,8 +439,9 @@ def _owner_is_gone(name): def _sweep_stale_indexes(dirpath, uid): - """Delete index copies in `dirpath` that a killed run left behind. Only - regular files owned by `uid` (None: no ownership check) are touched. + """Delete index copies in `dirpath` that a killed run left behind, and + their private object directories. Only regular files and directories owned + by `uid` (None: no ownership check) are touched. A copy goes as soon as the hook that made it is gone: a killed hook can leave one per run, and index-sized files fill a disk long before the age @@ -422,12 +464,16 @@ def _sweep_stale_indexes(dirpath, uid): p = os.path.join(dirpath, name) try: st = os.lstat(p) - if not stat.S_ISREG(st.st_mode): + is_dir = stat.S_ISDIR(st.st_mode) and name.endswith(_OBJECTS_DIR_SUFFIX) + if not (is_dir or stat.S_ISREG(st.st_mode)): continue if uid is not None and st.st_uid != uid: continue if max(st.st_mtime, st.st_ctime) < cutoff or _owner_is_gone(name): - os.unlink(p) + if is_dir: + _remove_objects_dir(p) + else: + os.unlink(p) if time.monotonic() > deadline: return except OSError: @@ -531,6 +577,24 @@ def _copy_slot(tmpdir, index_bytes=0): os.close(held) +def _remove_objects_dir(path): + """Remove a private object directory. git writes objects read-only, which + stops Windows from deleting them.""" + import shutil + import stat + + def writable_then_retry(func, p, _exc): + # Not a link: chmod would follow it to whatever it points at. + if func in (os.unlink, os.rmdir) and not os.path.islink(p): + os.chmod(p, stat.S_IWRITE) + func(p) + + try: + shutil.rmtree(path, onerror=writable_then_retry) + except OSError: + pass + + def _remove_copy(tmp_index): """Remove an index copy and the files git wrote next to it.""" import glob @@ -539,6 +603,7 @@ def _remove_copy(tmp_index): os.unlink(p) except OSError: pass + _remove_objects_dir(tmp_index + _OBJECTS_DIR_SUFFIX) def remove_copies_on_termination(): @@ -597,6 +662,75 @@ def _hook_tmpdir(): def _note_add_failure(kind, paths): _add_failed["code"] = kind * 100000 + min(len(paths), 99999) + _add_failed["left_out"] = kind != 4 + + +def _env_with_private_objects(env, cwd, objects_dir): + """`env` for a git that writes objects to `objects_dir` and still reads + the repository's own, wherever git says they are (a linked worktree shares + them). A path holding the list separator is left out, since git would + split it; the add then fails only if it has to read an object.""" + out = {**env, "GIT_OBJECT_DIRECTORY": objects_dir} + try: + r = subprocess.run([*GIT_CMD, "rev-parse", "--git-path", "objects"], + cwd=cwd, capture_output=True, timeout=5, env=env) + except (subprocess.TimeoutExpired, OSError): + return out + own = os.path.join(cwd, os.fsdecode(r.stdout).strip()) + if r.returncode == 0 and os.pathsep not in own: + out["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = os.pathsep.join( + p for p in (own, env.get("GIT_ALTERNATE_OBJECT_DIRECTORIES")) if p) + return out + + +def _add_new_files(cwd, paths, env, tmp_index): + """`git add --intent-to-add` the untracked `paths` to the index copy `env` + names, so the diff shows them. The add has to store the empty blob, so a + user who cannot write the object store gets a second try that stores it in + a private directory next to the copy. Nothing needs that blob afterwards: + `git diff` reads these files from the work tree. `git stash create` would + fail on such an index, and only runs on a copy with nothing added. + + No stdout used here (only returncode matters), but text=True still spawns + reader threads that decode stderr — git error messages can reference + non-ASCII filenames and crash on cp1252. See #2099. Drop text=True so bytes + stay raw.""" + # The paths are file names, not patterns, for this git add only: an + # untracked file named `:(glob)**` must add only itself. git refuses that + # together with a glob or icase setting from the user's environment. + env = {k: v for k, v in env.items() + if k not in ("GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS")} + env["GIT_LITERAL_PATHSPECS"] = "1" + + def add(add_env): + results = _run_git_on_review_paths( + ["add", "--intent-to-add"], paths, timeout=10, cwd=cwd, env=add_env) + return next((r for r in results if r.returncode != 0), None) + + try: + failed = add(env) + except subprocess.TimeoutExpired: + # No retry: git is slow here, not refused. The diff goes on for the + # tracked files, so a timeout on every turn cannot stop their reviews. + _note_add_failure(3, paths) + return + if not failed: + return + debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") + # Whatever happens to the retry, the diff goes on for the tracked files. + try: + objects_dir = tmp_index + _OBJECTS_DIR_SUFFIX + os.mkdir(objects_dir, 0o700) + retry_failed = add(_env_with_private_objects(env, cwd, objects_dir)) + if retry_failed: + debug_log(f"git add -N retry failed: {retry_failed.stderr[:200].decode('utf-8', errors='replace')}") + except (subprocess.TimeoutExpired, OSError) as e: + debug_log(f"git add -N retry failed: {e}") + retry_failed = True + if retry_failed: + _note_add_failure(1 if b"empty blob" in failed.stderr else 2, paths) + else: + _note_add_failure(4, paths) @contextlib.contextmanager @@ -685,24 +819,7 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths): else: add_args = None if add_args: - # No stdout used here (only returncode matters), but text=True - # still spawns reader threads that decode stderr — git error - # messages can reference non-ASCII filenames and crash on - # cp1252. See #2099. Drop text=True so bytes stay raw. - try: - results = _run_git_on_review_paths( - ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd, - # The paths are file names, not patterns, for this git add - # only: an untracked file named `:(glob)**` must add only - # itself. - env={**env, "GIT_LITERAL_PATHSPECS": "1"}) - except subprocess.TimeoutExpired: - _note_add_failure(3, add_args) - raise - failed = next((r for r in results if r.returncode != 0), None) - if failed: - _note_add_failure(1 if b"empty blob" in failed.stderr else 2, add_args) - debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") + _add_new_files(cwd, add_args, env, tmp_index) # A whole-tree add puts a nested repository back. if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index): yield None @@ -794,26 +911,33 @@ def _gitlink_paths(top, env): return found +# True when the last _drop_gitlinks call removed at least one gitlink, so the +# index copy and HEAD can no longer have the same tree even on a clean tree. +last_dropped_gitlinks = False + + def _drop_gitlinks(top, env, tmp_index): """Remove the gitlink (mode 160000) entry of every nested repository from the index copy that `env` names, never from the real index, before anything else runs on the copy. A gitlink marks a directory that is, or can be, another repository (see diff.ignoreSubmodules in GIT_CMD): `git stash create` takes no flag like IGNORE_SUBMODULES, and `git add` - reads the gitlinks its paths cover. An entry whose directory has no - `.git` stays: git starts nothing there, and without the entry an older - `git stash create` fails on the empty directory. `top` is the work - tree's top directory. Returns True on success, False on any failure; the - copy must not be used then.""" + reads the gitlinks its paths cover. Every gitlink goes, including one + whose directory has no `.git` now: whether git starts something there is + decided when git runs, not here. Without the entry, `git stash create` on + git older than 2.34 fails on a submodule that is not checked out, and the + baseline falls back to HEAD. `top` is the work tree's top directory. + Returns True on success, False on any failure; the copy must not be used + then.""" + global last_dropped_gitlinks + last_dropped_gitlinks = False try: if not _may_have_gitlinks(tmp_index): return True gitlinks = _gitlink_paths(top, env) if gitlinks is None: return False - top_b = os.fsencode(top) - nested = sorted(p for p in gitlinks - if os.path.lexists(os.path.join(top_b, p, b".git"))) + nested = sorted(gitlinks) if not nested: return True mtime_ns = os.stat(tmp_index).st_mtime_ns @@ -829,6 +953,7 @@ def _drop_gitlinks(top, env, tmp_index): return False # Keep the mtime the copy came with; see _copied_index. os.utime(tmp_index, ns=(mtime_ns, mtime_ns)) + last_dropped_gitlinks = True debug_log(f"gitlink entries (nested repositories) removed from the " f"index copy: {len(nested)}; their contents are not reviewed") return True @@ -1058,6 +1183,18 @@ def _git_reflog_recent_commits(repo_root, max_age_s=120, max_n=5): return fresh, stale +# New name -> secret-shaped old name, for the renames and copies git reported +# during this hook run. The Stop review limits its diff to a list of paths: +# with only the new name in it, git shows the secret's content as a new file, +# and the diff parsers cannot tell it came from a name they leave out. +_secret_rename_origins = {} + + +def _note_rename(old_path, new_path): + if _is_secret_shaped(old_path): + _secret_rename_origins[new_path] = old_path + + def _git_name_only(cwd, base, include_untracked=False): """Return the set of repo-root-relative paths that differ from `base`, or None if git failed (unresolvable ref, not a repo, timeout). Callers @@ -1077,7 +1214,7 @@ def _git_name_only(cwd, base, include_untracked=False): def _run(env): # core.quotePath=false comes from GIT_CMD globally (see definition). result = subprocess.run( - [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base], + [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-status", "-z", base], cwd=cwd, capture_output=True, timeout=30, env=env, ) @@ -1086,7 +1223,18 @@ def _git_name_only(cwd, base, include_untracked=False): debug_log(f"_git_name_only({base!r}) rc={result.returncode}: {stderr_str[:200]}") return None stdout = (result.stdout or b"").decode("utf-8", errors="replace") - return {p for p in stdout.split("\0") if p} + # Fields are `status\0path\0`, or `R<score>\0old\0new\0` for a rename + # or copy, which is listed by its new name only. + fields = stdout.split("\0") + names = set() + i = 0 + while i + 1 < len(fields): + if fields[i][:1] in ("R", "C") and i + 2 < len(fields): + _note_rename(fields[i + 1], fields[i + 2]) + i += 1 + names.add(fields[i + 1]) + i += 2 + return names try: # The diff only reads the index (diff.autoRefreshIndex is off in @@ -1147,6 +1295,8 @@ def _git_status_porcelain(cwd): # 2-char-status entry. if "R" in xy or "C" in xy: i += 1 + if i < len(entries): + _note_rename(entries[i], path) i += 1 return tracked, untracked except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: @@ -1453,6 +1603,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa MAX_FILE_DIFF_BYTES is cut down to its added lines. """ _path_list_too_long.clear() + _add_failed["left_out"] = False pathspec = _diff_pathspec(cwd, paths) if paths and not pathspec: # Caller restricted to specific paths but none are inside this repo diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 468d9e6d..ee9ad2be 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -17,6 +17,7 @@ Two reassignable globals here are read by handlers in ``_last_review_truncated_bytes``. Handlers reference them as ``llm.X`` (not via ``from``-import) so they observe reassignment. """ +import contextlib import hashlib import json import logging @@ -39,7 +40,7 @@ except ImportError: # a Python built without TLS import extensibility import review_api -from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401 +from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs, make_state_dir # noqa: F401 from session_state import load_state, with_locked_state from gitutil import git_config_env, SAFE_GIT_CONFIG @@ -195,10 +196,13 @@ def _anthropic_base_url() -> str: Honors ANTHROPIC_BASE_URL (the convention the Anthropic SDK and CC itself use) so customers behind an LLM gateway (LiteLLM, Bifrost, self-hosted Anthropic-compatible proxy) can route the plugin's reviews through their - gateway. Defaults to https://api.anthropic.com. Always returns a string - with no trailing slash so callers can safely append /v1/messages etc. + gateway. Defaults to https://api.anthropic.com, also when the variable is + set but blank, which is how the SDK and CC read it. Always returns a + string with no trailing slash so callers can safely append /v1/messages + etc. """ - return os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com").rstrip("/") + base = os.environ.get("ANTHROPIC_BASE_URL", "").strip() + return (base or "https://api.anthropic.com").rstrip("/") # ── Windows certificate store with an entry OpenSSL cannot read ────────── @@ -282,6 +286,10 @@ def _urlopen(request, timeout): return urllib.request.urlopen(request, timeout=timeout, context=_store_tls_context) +def _is_remote_session() -> bool: + return os.environ.get("CLAUDE_CODE_REMOTE", "").lower() in ("1", "true", "yes", "on") + + def _probe_anthropic(timeout: float = 5.0) -> bool: req = urllib.request.Request(_anthropic_base_url() + "/", method="HEAD") try: @@ -420,7 +428,7 @@ def ensure_anthropic_reachable() -> bool: global _anthropic_reachable if _anthropic_reachable is not None: return _anthropic_reachable - if os.environ.get("CLAUDE_CODE_REMOTE", "").lower() not in ("1", "true", "yes", "on"): + if not _is_remote_session(): _anthropic_reachable = True return True if _probe_anthropic(): @@ -429,7 +437,9 @@ def ensure_anthropic_reachable() -> bool: debug_log("Remote env: api.anthropic.com unreachable, stripping anthropic.com from NO_PROXY") _strip_anthropic_from_no_proxy() _anthropic_reachable = _probe_anthropic() - if not _anthropic_reachable: + if _anthropic_reachable: + _clear_net_error() # the first probe's failure; this one got through + else: debug_log("Remote env: api.anthropic.com still unreachable after NO_PROXY scrub") return _anthropic_reachable @@ -735,7 +745,7 @@ def _read_review_model_cache(path, endpoint_key, now): def _write_review_model_cache(path, endpoint_key, model, now): tmp = None try: - os.makedirs(os.path.dirname(path), exist_ok=True) + make_state_dir(os.path.dirname(path)) fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".review_model.") with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump({"endpoint": endpoint_key, "model": model, "at": now}, f) @@ -805,11 +815,12 @@ _gateway_check_unanswered = False # depend on the model, so the Sonnet attempt is not made after it. _gateway_review_timed_out = False +_WINDOWS = os.name == "nt" + def _user_cli_path() -> Optional[str]: - """The user's own `claude`: SG_AGENTIC_CLI_PATH if set ("" selects the - SDK's bundled CLI), else the first of the absolute paths below that - exists, else None.""" + """The user's own `claude`: SG_AGENTIC_CLI_PATH if set ("" names none), else + the first of the absolute paths below that exists, else None.""" cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") if cli_path is not None: return cli_path @@ -821,18 +832,71 @@ def _user_cli_path() -> Optional[str]: # user's (potentially attacker-supplied) repo, and Windows shutil.which # searches cwd first — a checked-in ./claude.exe would get spawned. # Absolute-path probes only. - for p in ( - os.environ.get("CLAUDE_CODE_EXECPATH"), - os.path.expanduser("~/.local/bin/claude"), - "/root/.local/bin/claude", - # Claude Code Remote container install path. - "/opt/claude-code/bin/claude", - ): + probes = [os.environ.get("CLAUDE_CODE_EXECPATH")] + if not _WINDOWS: + # Where Claude Code is installed on macOS and Linux. + probes += [ + os.path.expanduser("~/.local/bin/claude"), + "/root/.local/bin/claude", + # Claude Code Remote container install path. + "/opt/claude-code/bin/claude", + ] + for p in probes: if p and os.path.isfile(p): return p return None +def _windows_user_cli() -> Optional[str]: + """Windows: the full path of the user's claude.exe, from the native + installer's folder, else from PATH; None when neither has one. Skips any + folder that is not given as a full path, and the working directory and + project root, and any folder inside them (unless that root holds the home + folder, and with it the user's own tools).""" + skipped = [d for d in (os.getcwd(), os.environ.get("CLAUDE_PROJECT_DIR")) if d and os.path.isdir(d)] + home = os.path.expanduser("~") + real_home = os.path.normcase(os.path.realpath(home)).rstrip(os.sep) + os.sep + roots = [r.rstrip(os.sep) + os.sep for r in (os.path.normcase(os.path.realpath(d)) for d in skipped)] + roots = [r for r in roots if not real_home.startswith(r)] + home_bin = os.path.join(home, ".local", "bin") + for folder in [home_bin] + os.environ.get("PATH", "").split(os.pathsep): + folder = folder.strip().strip('"') + cli = os.path.join(folder, "claude.exe") + try: + real = os.path.normcase(os.path.realpath(folder)) + # A full path is one that abspath leaves as it is. + if (os.path.normcase(os.path.abspath(folder)) == os.path.normcase(os.path.normpath(folder)) + and os.path.isfile(cli) + and not any(os.path.samefile(folder, d) for d in skipped) + and not any(real.startswith(r) for r in roots)): + return cli + except OSError: + pass + return None + + +def _cli_for_sdk(cli_path: Optional[str]) -> Optional[str]: + """What to pass the Agent SDK as `cli_path`: a given one as it is. With none + given, the SDK chooses, except on Windows. There this names the CLI bundled + with the SDK, else the user's own, by its full path, and when neither exists + the bundled path anyway, so that the start fails.""" + if cli_path or not _WINDOWS: + return cli_path or None + # When the SDK module has no file, any full path at which nothing exists will do. + sdk_file = getattr(sys.modules.get("claude_agent_sdk"), "__file__", None) or __file__ + bundled = os.path.join(os.path.dirname(os.path.abspath(sdk_file)), "_bundled", "claude.exe") + if os.path.isfile(bundled): + return bundled + cli_path = _windows_user_cli() + if not cli_path: + debug_log("no Claude Code for the Agent SDK: none is bundled with it, and there is no claude.exe " + "in ~\\.local\\bin or on PATH outside this project (SG_AGENTIC_CLI_PATH can name one)") + return bundled + debug_log(f"the Agent SDK has no bundled Claude Code; using {cli_path}") + _tolerate_unknown_sdk_messages() + return cli_path + + def _tolerate_unknown_sdk_messages() -> None: """Make the SDK's message parser pass unknown message types through instead of raising: a CLI newer than the SDK emits types the SDK does not @@ -932,6 +996,14 @@ def can_review(session_id) -> bool: return HAS_API_CREDENTIALS or gateway_review_cli(session_id) is not None +def _forget_failed_call(): + """A review got its answer from another call running beside the one that + failed, so the row should not report that failure.""" + global _last_call_claude_http_error + _last_call_claude_http_error = None + _clear_net_error() + + def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, cli_path=None): """Single-turn SDK call as a substitute for the HTTP _call_claude path on @@ -980,7 +1052,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, if cli_path: _tolerate_unknown_sdk_messages() else: - cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None + cli_path = _cli_for_sdk(os.environ.get("SG_AGENTIC_CLI_PATH") or None) default_model = default_review_model() chosen_model = model or default_model @@ -996,7 +1068,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, system_prompt=CLAUDE_CODE_SYSTEM_PROMPT, cli_path=cli_path, allowed_tools=[], - extra_args=_only_tools_args(), + extra_args={**_only_tools_args(), **_reviewer_session_args()}, setting_sources=[], max_turns=2, model=chosen_model, @@ -1023,9 +1095,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, _record_usage(getattr(msg, "usage", None) or {}, chosen_model, cost_usd=getattr(msg, "total_cost_usd", None)) elif getattr(msg, "subtype", None) == "api_retry": - data = getattr(msg, "data", None) - status = data.get("error_status") if isinstance(data, dict) else None - _retried_after.add(str(status) if isinstance(status, int) else "no response") + status = _api_retry_status(msg) + _retried_after.add(str(status) if status is not None else "no response") return structured # 60s ceiling: a single review request on a healthy 3P endpoint completes @@ -1323,6 +1394,7 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, merged.append(item) elif item not in merged: merged.append(item) + _forget_failed_call() # one leg got through; the other may have failed return {bool_key: bool(merged) or bool((ra or {}).get(bool_key)) or bool((rb or {}).get(bool_key)), list_key: merged} @@ -1786,6 +1858,32 @@ def _send_sdk_logs_to_debug_log() -> None: sdk_logger.propagate = False +# Claude Code older than 2.0.63 exits at startup with "unknown option" when +# given --no-session-persistence. The flag is sent until an inner CLI +# refuses it. +_SESSION_FLAG = "no-session-persistence" +_send_session_flag = True + + +def _reviewer_session_args() -> Dict[str, Optional[str]]: + """Extra CLI flags for the SDK-spawned inner `claude`. + + Review runs are one-shot and never resumed, so by default the inner CLI + is told not to save them as session transcripts (they hold the full + review prompt, including diff hunks). SECURITY_GUIDANCE_PERSIST_SESSIONS=1 + keeps the transcripts, e.g. to debug a review. + """ + keep = os.environ.get("SECURITY_GUIDANCE_PERSIST_SESSIONS", "").strip().lower() + if not _send_session_flag or keep in ("1", "on", "true", "yes"): + return {} + return {_SESSION_FLAG: None} + + +def _names_session_flag(stderr_line: Any) -> bool: + text = str(stderr_line) + return _SESSION_FLAG in text and "unknown option" in text.lower() + + # The agentic reviewer reads a diff it must not trust, so it gets # file-reading tools and nothing else. _REVIEWER_TOOLS = ("Read", "Grep", "Glob") @@ -1820,22 +1918,57 @@ def _names_strict_mcp_flag(stderr_line: Any) -> bool: return "--strict-mcp-config" in str(stderr_line) +def _refused_flags(stderr_lines: List[Any]) -> List[str]: + """Which of the flags this plugin can leave out the lines refuse.""" + refused = [] + if any(_names_strict_mcp_flag(l) for l in stderr_lines): + refused.append("--strict-mcp-config") + if any(_names_session_flag(l) for l in stderr_lines): + refused.append("--" + _SESSION_FLAG) + return refused + + def _run_inner_cli(start: Callable[[], Any], stderr_lines: List[str]) -> Any: """start() runs one inner CLI to its result; stderr_lines receives what that CLI writes to stderr. A start the CLI refused over - --strict-mcp-config is made once more without the flag, and the flag is - left out for the rest of this process.""" - global _send_strict_mcp - del stderr_lines[:] - try: - return start() - except Exception: - if not any(_names_strict_mcp_flag(l) for l in stderr_lines): - raise - _send_strict_mcp = False - debug_log("inner CLI refused --strict-mcp-config; starting it again without the flag") + --strict-mcp-config or --no-session-persistence is made again without + that flag, and the flag is left out for the rest of this process. A CLI + names one flag per start, so one that refuses both is started three + times.""" + global _send_strict_mcp, _send_session_flag + left_out: List[str] = [] + while True: del stderr_lines[:] - return start() + try: + return start() + except Exception: + refused = [f for f in _refused_flags(stderr_lines) if f not in left_out] + if not refused: + raise + if "--strict-mcp-config" in refused: + _send_strict_mcp = False + if "--" + _SESSION_FLAG in refused: + _send_session_flag = False + left_out += refused + debug_log(f"inner CLI refused {' and '.join(refused)}; " + "starting it again without") + + +class _ReviewerAuthFailed(Exception): + """The agentic reviewer's credentials were refused; retrying cannot help.""" + + +# Retry notices in a row, each after a 401, at which the review stops. One is +# normal: the CLI renews a stored login after a 401 and tries again. Not used +# in a remote session, where the CLI waits out a short sign-in outage on purpose. +_AGENTIC_MAX_401_RETRIES = 3 + + +def _api_retry_status(msg: Any) -> Optional[int]: + """The HTTP status of the CLI's api_retry notice, if it gives one.""" + data = getattr(msg, "data", None) + status = data.get("error_status") if isinstance(data, dict) else None + return status if isinstance(status, int) else None def _agentic_spawn_env() -> Dict[str, str]: @@ -2009,7 +2142,7 @@ def _agentic_review( "the findings list." ) - # Always prefer the user's installed `claude` over the SDK's bundled CLI. + # Prefer the `claude` that _user_cli_path finds over the SDK's bundled CLI. # The bundled CLI is whatever shipped with the pip-installed SDK version # and can lag the user's CLI by months — protocol skew between them is a # top cause of agentic_fallback=2 in production (the SDK reads @@ -2019,19 +2152,21 @@ def _agentic_review( cli_path = _gateway_cli or _user_cli_path() if cli_path: _tolerate_unknown_sdk_messages() + else: + cli_path = _cli_for_sdk(cli_path) # Without a callback the inner CLI writes to this hook's stderr, which # Claude Code shows Claude as the review notice. Log it instead. child_stderr_lines = [0] - # Lines of the current start that name --strict-mcp-config (_run_inner_cli). + # Lines of the current start that refuse a flag (_run_inner_cli). flag_refusals: List[str] = [] def _child_stderr_metric() -> Dict[str, int]: return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {} def _on_child_stderr(line: str) -> None: - if _names_strict_mcp_flag(line): - # Not counted: where the flag is refused, every review gets this + if _refused_flags([line]): + # Not counted: where a flag is refused, every review gets this # line once, from the start that is then made again. flag_refusals.append(str(line)) debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}") @@ -2057,7 +2192,8 @@ def _agentic_review( # Pre-approved, and the only tools the reviewer has: no # permission mode can then let it write, run or fetch anything. allowed_tools=list(_REVIEWER_TOOLS), - extra_args=_only_tools_args(_REVIEWER_TOOLS), + extra_args={**_only_tools_args(_REVIEWER_TOOLS), + **_reviewer_session_args()}, setting_sources=[], max_turns=turns if turns is not None else max_turns, model=model, @@ -2116,39 +2252,54 @@ def _agentic_review( # Blocks are matched by shape so older SDK builds need no extra import. file_tool_ids = set() - async for msg in query(prompt=_once(), options=opts): - if isinstance(msg, AssistantMessage): - n += 1 - for b in getattr(msg, "content", None) or []: - if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS - and getattr(b, "id", None)): - file_tool_ids.add(b.id) - ctx["rv_tool_calls"] += 1 - elif isinstance(msg, ResultMessage): - subtype = msg.subtype - if msg.structured_output is not None: - structured = msg.structured_output - # SDK ResultMessage carries aggregate usage + cache-aware - # cost across the whole multi-turn run; prefer its cost over - # the price-table estimate. getattr guards older SDK builds. - _record_usage(getattr(msg, "usage", None) or {}, model, - cost_usd=getattr(msg, "total_cost_usd", None)) - for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): - value = getattr(msg, attr, None) - # Counting must never fail the review: anything that - # is not a positive finite number adds nothing. - if (isinstance(value, (int, float)) and not isinstance(value, bool) - and 0 < value < float("inf")): - ctx[key] += int(value) - else: - # Tool results come back as user messages. - content = getattr(msg, "content", None) - if isinstance(content, list): - ctx["rv_tool_err"] += sum( - 1 for b in content - if getattr(b, "is_error", None) is True - and getattr(b, "tool_use_id", None) in file_tool_ids - ) + auth_retries = 0 + # Closed on the way out, also on a raise, so the CLI stops with the review. + async with contextlib.aclosing(query(prompt=_once(), options=opts)) as messages: + async for msg in messages: + if isinstance(msg, AssistantMessage): + # Old CLIs answer each refused request by asking the model + # again, hundreds of times; the message is the same on all. + if getattr(msg, "error", None) == "authentication_failed": + raise _ReviewerAuthFailed("authentication_failed") + auth_retries = 0 + n += 1 + for b in getattr(msg, "content", None) or []: + if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS + and getattr(b, "id", None)): + file_tool_ids.add(b.id) + ctx["rv_tool_calls"] += 1 + elif isinstance(msg, ResultMessage): + subtype = msg.subtype + if msg.structured_output is not None: + structured = msg.structured_output + # SDK ResultMessage carries aggregate usage + cache-aware + # cost across the whole multi-turn run; prefer its cost over + # the price-table estimate. getattr guards older SDK builds. + _record_usage(getattr(msg, "usage", None) or {}, model, + cost_usd=getattr(msg, "total_cost_usd", None)) + for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): + value = getattr(msg, attr, None) + # Counting must never fail the review: anything that + # is not a positive finite number adds nothing. + if (isinstance(value, (int, float)) and not isinstance(value, bool) + and 0 < value < float("inf")): + ctx[key] += int(value) + elif getattr(msg, "subtype", None) == "api_retry": + # A gateway's 401 without the API's x-should-retry: false + # keeps the CLI retrying for about three minutes. + auth_retries = auth_retries + 1 if _api_retry_status(msg) == 401 else 0 + if (auth_retries >= _AGENTIC_MAX_401_RETRIES + and not _is_remote_session()): + raise _ReviewerAuthFailed(f"{auth_retries} retries after HTTP 401") + else: + # Tool results come back as user messages. + content = getattr(msg, "content", None) + if isinstance(content, list): + ctx["rv_tool_err"] += sum( + 1 for b in content + if getattr(b, "is_error", None) is True + and getattr(b, "tool_use_id", None) in file_tool_ids + ) return structured, n, subtype def _run(system: str, prompt: str, *, schema: Dict[str, Any] diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 3efe344e..47a992aa 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -23,7 +23,7 @@ The plugin has two layers: ## How the git baseline works -On each UserPromptSubmit, the plugin runs `git stash create` to get a SHA representing +On each UserPromptSubmit, the plugin takes a snapshot commit to get a SHA representing the current working tree state (HEAD + any uncommitted changes). This SHA is saved to the session state file. When the Stop hook fires, it runs `git diff <baseline_sha>` to get only the changes made since that snapshot. After analysis, the baseline is updated @@ -68,6 +68,7 @@ import re import subprocess import sys import threading +import time import urllib.request from datetime import datetime from enum import IntEnum @@ -86,9 +87,9 @@ from _base import ( # noqa: E402,F401 _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, _net_error_metric, _USAGE_CONTEXT, _log_usage, - launcher_probe_metrics, state_dir as _resolve_state_dir, + launcher_direct_metric, launcher_probe_metrics, state_dir as _resolve_state_dir, write_hook_output as _write_hook_output, portable_output, - llm_reviews_switched_off, agent_sdk_installed, + llm_reviews_switched_off, agent_sdk_installed, make_state_dir, ) import extensibility # noqa: E402 from patterns import ( # noqa: E402,F401 @@ -219,6 +220,9 @@ CONTINUATION_SUFFIX = ( "response." ) +# New files named in the notice for a failed `git add -N`. +_LEFT_OUT_NAMES_SHOWN = 5 + # Extra keys emit_metrics appends to every row this invocation emits. _TAIL_METRICS: Dict[str, Any] = {} # Of those, the ones that go after the others whenever they were set: a row @@ -228,6 +232,8 @@ _LAST_METRIC_KEYS = ("diff_seen",) # The launcher's slow interpreter probes, if any. After the keys above. _LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics() +# Whether the launcher skipped a packaged alias. Only on rows sent anyway. +_LAUNCHER_DIRECT: Dict[str, Any] = launcher_direct_metric() # Reviewer context diagnostics from llm.agentic_review, most useful first. _REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls") @@ -324,6 +330,10 @@ def emit_metrics( # names on PATH were launcher aliases that cannot read the plugin files. if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": head["launcher_fallback"] = 1 + if _precheck_miss: + # Up front: this is the key that says a text check would have lost a + # review, so it must not be the one cut by the key cap. + head["precheck_miss"] = 1 usage = _usage_metrics() head.update(usage) # Why the last call got no HTTP response (api_error -1 says only that it @@ -357,6 +367,8 @@ def emit_metrics( tail[k] = tail.pop(k) tail.update(_LAUNCHER_METRICS) tail.update(_REVIEWER_EFFORT_METRICS) + # Last of all: the first key a full row loses. + tail.update(_LAUNCHER_DIRECT) metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} if rewake_summary: @@ -422,7 +434,7 @@ def _no_credentials_notice(file_path, session_id): pass if not _git_toplevel(os.path.dirname(os.path.abspath(file_path))): return None - os.makedirs(os.path.dirname(marker), exist_ok=True) + make_state_dir(os.path.dirname(marker)) with open(marker, "w"): pass # In a session signed in to a Claude apps gateway the reviews do run, @@ -760,7 +772,7 @@ def handle_user_prompt_submit(input_data): # The untracked snapshot has one reader: the Stop-hook diff review, which # skips before reading it when either of these switches is off (see # handle_stop_hook). Listing the worktree on every prompt then buys - # nothing, so only the stash baseline (still read by the Write pattern + # nothing, so only the turn baseline (still read by the Write pattern # filter) is captured. snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW spent = {"baseline": 0.0, "untracked": 0.0} @@ -775,15 +787,15 @@ def handle_user_prompt_submit(input_data): def _capture(repo_cwd): if not snapshot_untracked: return _timed("baseline", capture_git_baseline, repo_cwd), None - # stash-create and ls-files both walk the worktree (~2-5s each in a + # the baseline snapshot and ls-files both walk the worktree (~2-5s each in a # very large repo). Run them concurrently so UPS latency stays # ≈ max(both). import concurrent.futures as _cf with _cf.ThreadPoolExecutor(max_workers=2) as _ex: _f_sha = _ex.submit(_timed, "baseline", capture_git_baseline, repo_cwd) _f_ut = _ex.submit(_timed, "untracked", _list_untracked, repo_cwd) - # Taken whether or not the stash produced a SHA. `git stash - # create` returns empty when there are no TRACKED changes, but + # Taken whether or not the snapshot produced a SHA. The baseline + # falls back to HEAD when there are no TRACKED changes, but # pre-existing untracked files still need to be excluded from the # next Stop's review_set — otherwise an untracked-only working # tree gets every untracked file reviewed on every turn until @@ -851,7 +863,7 @@ def handle_user_prompt_submit(input_data): # When the turn began: what a Stop review in another checkout has # to go on. state["prompt_at"] = captured_at - # untracked_at_baseline is independent of whether the stash produced + # untracked_at_baseline is independent of whether the snapshot produced # a SHA, so compute_v2_review_set's preexisting-untracked exclusion # works in untracked-only trees. None means no snapshot was taken # (Stop review off): drop the previous one, which belongs to an older @@ -1056,6 +1068,47 @@ try: except ValueError: INFLIGHT_WAIT_S = 240 +# Word pairs a shell `case` pattern (`*git*commit*|*git*push*|...`) would look +# for in the raw hook input: wider than _GIT_COMMIT_RE / _GIT_PUSH_RE, so a +# command those match always contains one of these pairs in this order. +_SHELL_PRECHECK_PAIRS = ( + ("git", "commit"), ("git", "push"), + ("gt", "create"), ("gt", "modify"), ("gt", "submit"), +) +# One in this many unmatched Bash calls reports, to keep the row count down. +_UNMATCHED_BASH_SAMPLE = 10 +# Set when a command that is reviewed would not have passed the text check. +_precheck_miss = False + + +def _shell_precheck_passes(raw): + """True when `raw` holds one of _SHELL_PRECHECK_PAIRS, first word first. + + Measurement only. Tells how many hook starts that match no commit or push + a text check in the launcher could avoid (`precheck_skip`), and whether + that check would ever drop a command that is reviewed (`precheck_miss`). + """ + for first, second in _SHELL_PRECHECK_PAIRS: + at = raw.find(first) + if at != -1 and raw.find(second, at + len(first)) != -1: + return True + return False + + +def _unmatched_bash_sampled(input_data): + """Pick the same one call in _UNMATCHED_BASH_SAMPLE in every start of it. + + One Bash call can start this hook once per hooks.json entry, so the choice + is made from the call's id: all its starts report or none do. A call with + no id is not reported. + """ + tool_use_id = input_data.get("tool_use_id") + if not isinstance(tool_use_id, str) or not tool_use_id: + return False + digest = hashlib.sha256(tool_use_id.encode("utf-8", "replace")).digest() + return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0 + + def _claim_bash_hook_once(input_data): """De-dupe across hooks.json `if` matchers firing for the same Bash call. @@ -1266,18 +1319,68 @@ def is_commit_review_enabled(): COMMIT_REVIEW_ENABLED = is_commit_review_enabled() -# Seconds from the start of a commit or push review's race after which -# neither side waits for the other any longer; well inside Claude Code's -# 10-minute hook timeout. +_HOOK_STARTED = time.monotonic() + +# Seconds into the hook after which neither side of a commit or push review's +# race waits for the other any longer; well inside Claude Code's 10-minute hook +# timeout. _RACE_MAX_WAIT_S = 480 +# Seconds after which the review ends even if a side is still waiting on a +# request that does not answer, with time left to tell the session before +# Claude Code kills the hook. The inner CLI exits with the hook. The same limit +# holds for a commit or push review's single-shot review outside a race. +_RACE_END_S = 570 # api_error for a race that hit that deadline with no verdict. _RACE_TIMED_OUT = -2 +def _hook_spent_s() -> float: + return time.monotonic() - _HOOK_STARTED + +def _single_shot_review( + diff_files: List[Tuple[str, str]], + previous_findings: List[Dict[str, Any]], +) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: + """A single-shot review as (guidance, vulns, metrics); failures are in the + metrics, not raised.""" + try: + g, v = analyze_code_security( + diff_files, is_diff=True, previous_findings=previous_findings + ) + # Read on this thread: the outcome is per thread. + failed = llm.last_review_failed() + return g, v, {"agentic": False, "review_failed": failed, + "api_error": llm.last_review_status() if failed else None} + except Exception as e: + debug_log(f"single-shot review crashed: {type(e).__name__}: {e}") + return None, [], {"agentic": False, "review_failed": True, "api_error": None} + +def _single_shot_review_in_time( + diff_files: List[Tuple[str, str]], + previous_findings: List[Dict[str, Any]], +) -> Tuple[Optional[str], List[Dict[str, Any]], bool, Optional[int]]: + """A single-shot review outside a race, as (guidance, vulns, failed, status). + + It ends at _RACE_END_S into the hook, whatever is pending. + """ + done: List[Any] = [] + worker = threading.Thread( + target=lambda: done.append(_single_shot_review(diff_files, previous_findings)), + daemon=True, + ) + worker.start() + worker.join(timeout=max(0.0, _RACE_END_S - _hook_spent_s())) + if not done: + debug_log("single-shot review: nothing returned in time") + return None, [], True, _RACE_TIMED_OUT + g, v, m = done[0] + return g, v, m["review_failed"], m["api_error"] + def _agentic_review_with_race( repo_root: str, diff_files: List[Tuple[str, str]], rel_touched: List[str], previous_findings: List[Dict[str, Any]], + spent_s: float = 0.0, ) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: """Race the agentic reviewer against a delayed single-shot fallback. @@ -1289,10 +1392,13 @@ def _agentic_review_with_race( verdict) is returned so the caller never starts another review. If agentic finishes before the delay, the fallback never runs. + `spent_s`, the time the hook has already run, comes off the delay and both + limits: the hook's time limit does not restart with the race. + Metrics added: race_winner : 1 = agentic won, 2 = fallback won (CC accepts only bool/finite-number metric values — strings would discard the dict) - race_delay_s : the configured delay + race_delay_s : the delay used race_started : 1 if the fallback was actually launched, else 0 Only the commit-review and push-sweep handlers call this — external @@ -1306,13 +1412,16 @@ def _agentic_review_with_race( if os.environ.get("SG_AGENTIC_NO_RACE") == "1": return agentic_review(repo_root, diff_files, rel_touched) - delay_s = int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) + delay_s = max(0, int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) - int(spent_s)) + if spent_s >= 1: + debug_log(f"Review race: {spent_s:.0f}s already spent, fallback starts after {delay_s}s") q: "_queue.Queue[Tuple[str, Any]]" = _queue.Queue(maxsize=1) fallback_started = _th.Event() fallback_done = _th.Event() agentic_done = _th.Event() fallback_result: Dict[str, Any] = {} - deadline = _t.monotonic() + _RACE_MAX_WAIT_S + deadline = _t.monotonic() + max(0.0, _RACE_MAX_WAIT_S - spent_s) + timed_out = (None, [], {"agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) def _agentic() -> None: try: @@ -1330,33 +1439,26 @@ def _agentic_review_with_race( if agentic_done.is_set(): return # agentic finished within the delay — never start fallback fallback_started.set() - result = (None, [], {"agentic": False, "review_failed": True, "api_error": None}) + result = _single_shot_review(diff_files, previous_findings) + fallback_result["r"] = result + fallback_done.set() + if result[2]["review_failed"]: + # A failed fallback does not win: the agentic review's inner + # CLI may still get a verdict where direct calls cannot. + agentic_done.wait(timeout=max(0.0, deadline - _t.monotonic())) try: - g, v = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings - ) - # Read on this thread: the outcome is per thread. - failed = llm.last_review_failed() - result = (g, v, {"agentic": False, "review_failed": failed, - "api_error": llm.last_review_status() if failed else None}) - except Exception: # pragma: no cover + q.put_nowait(("fallback", result)) + except _queue.Full: pass - finally: - fallback_result["r"] = result - fallback_done.set() - if result[2]["review_failed"]: - # A failed fallback does not win: the agentic review's inner - # CLI may still get a verdict where direct calls cannot. - agentic_done.wait(timeout=max(0.0, deadline - _t.monotonic())) - try: - q.put_nowait(("fallback", result)) - except _queue.Full: - pass _th.Thread(target=_agentic, daemon=True).start() _th.Thread(target=_fallback, daemon=True).start() - winner, (g, v, m) = q.get() + try: + winner, (g, v, m) = q.get(timeout=max(0.0, _RACE_END_S - spent_s)) + except _queue.Empty: + debug_log("review race: nothing returned in time") + winner, (g, v, m) = "fallback", timed_out # What the agentic run saw of its directory, and how much work it did, # is kept when the fallback's result replaces it below. reviewer_context = ( @@ -1369,8 +1471,11 @@ def _agentic_review_with_race( if fallback_done.wait(timeout=max(0.0, deadline - _t.monotonic())): winner, (g, v, m) = "fallback", fallback_result["r"] else: - winner, (g, v, m) = "fallback", (None, [], { - "agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) + winner, (g, v, m) = "fallback", timed_out + if winner == "agentic" and not m.get("agentic_fallback"): + # The agentic run reached the model; any failure on record is the + # fallback's, which lost. + llm._forget_failed_call() m = {**m, **reviewer_context} # a copy: don't mutate the callee's metrics dict m["race_winner"] = 1 if winner == "agentic" else 2 m["race_delay_s"] = delay_s @@ -1385,7 +1490,7 @@ def _review_failure_reason(status): _RACE_TIMED_OUT. """ gateway = (", or an LLM gateway may need its key in ANTHROPIC_CUSTOM_HEADERS" - if os.environ.get("ANTHROPIC_BASE_URL") else "") + if os.environ.get("ANTHROPIC_BASE_URL", "").strip() else "") if status == _RACE_TIMED_OUT: return ("timeout", "the review did not finish in time", "") if llm._is_3p_provider(): @@ -1416,6 +1521,44 @@ def _review_failure_reason(status): return ("reply", "the model's reply could not be read", "") +def _left_out_files_notice(session_id, repo_root, untracked, diff_output): + """(one line for the terminal, text for Claude) naming the source files a + failed `git add -N` kept out of this Stop review, or None. + + Each set of files gets one notice a session: the wake ends in another Stop + that fails the same way, and a notice there would wake Claude for ever. So + no notice unless the mark is saved. Paths are JSON quoted in ASCII: a file + name can hold a line break. + """ + in_diff = set(extract_file_paths_from_diff(diff_output or "")) + + def has_content(p): + try: + return os.path.getsize(os.path.join(repo_root, p)) > 0 + except OSError: + return False + + names = sorted(p for p in untracked or () + if p not in in_diff and _is_reviewable_source(p) and has_content(p)) + if not names: + return None + key = "new_files_left_out:" + hashlib.sha256( + "\0".join(names).encode("utf-8", "replace")).hexdigest()[:16] + if not atomic_check_and_mark_warning(session_id, key): + return None + if key not in load_state(session_id).get("shown_warnings", ()): + return None + _TAIL_METRICS["add_fail_told"] = len(names) + shown = ", ".join(json.dumps(p) for p in names[:_LEFT_OUT_NAMES_SHOWN]) + if len(names) > _LEFT_OUT_NAMES_SHOWN: + shown += f" and {len(names) - _LEFT_OUT_NAMES_SHOWN} more" + return (f"Security review left out new files: {shown}. Log: {DEBUG_LOG_FILE}", + f"The security review did not see these new files, so it did not " + f"review them: {shown}. git could not add them to the review's " + f"diff. Tell the user this in one sentence, and that details are " + f"in {DEBUG_LOG_FILE}.") + + def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): """End a commit ("Commit") or push ("Push") review that got no verdict. @@ -1845,7 +1988,7 @@ def handle_commit_review_posttooluse(input_data): if _agentic_commit_review_enabled(): rel_touched = [fp for fp, _ in diff_files] concrete_guidance, vulns, _am = _agentic_review_with_race( - repo_root, diff_files, rel_touched, previous_findings + repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s() ) agentic_metrics.update(_am) if _am.get("child_stderr"): @@ -1859,17 +2002,13 @@ def handle_commit_review_posttooluse(input_data): # Fall back to single-shot only on agentic FAILURE (SDK/investigate # crash). If agentic completed and returned 0 findings, trust that. if agentic_metrics.get("agentic_fallback"): - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() else: - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() review_ms = int((_time.time() - review_start) * 1000) # `survived` is the raw self-refute count BEFORE the high/critical-only @@ -2286,7 +2425,7 @@ def handle_push_sweep_posttooluse(input_data): rel_touched = [fp for fp, _ in diff_files] if _agentic_commit_review_enabled(): concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race( - repo_root, diff_files, rel_touched, previous_findings + repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s(), ) if agentic_metrics.get("child_stderr"): _TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"] @@ -2294,24 +2433,20 @@ def handle_push_sweep_posttooluse(input_data): review_failed = bool(agentic_metrics.get("review_failed")) api_status = agentic_metrics.get("api_error") if agentic_metrics.get("agentic_fallback"): - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() else: - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() agentic_metrics = {} review_ms = int((_time.time() - review_start) * 1000) if review_failed: # Not marked reviewed. A later push does not re-check these commits: # its range starts from the new upstream. _exit_review_failed("Push", session_id, { - **_base, "pushed": len(push_range), "unreviewed": len(tail), + **_base, **_wait_m, "pushed": len(push_range), "unreviewed": len(tail), "files_reviewed": len(diff_files), "review_ms": review_ms, }, api_status) @@ -2485,10 +2620,29 @@ def handle_stop_hook(input_data): _TAIL_METRICS["warn_fired_mask"] = warn_fired_mask v2_metrics = {} + left_out = False + restore_paths = touched_paths + + def _left_out_notice(): + # Asked for as the row goes out: the mark must not outlive a hook + # killed during the review. + if not left_out: + return None + return _left_out_files_notice(session_id, repo_root, untracked, diff_output) + + def _left_out_wake(): + """emit_metrics arguments that wake Claude to say new files were left out.""" + notice = _left_out_notice() + if not notice: + return {} + return {"rewake_summary": notice[0], "hook_event_name": hook_event_name, + "additional_context": (PROVENANCE_BANNER + "\n\n" + notice[1] + + CONTINUATION_SUFFIX + "\n")} def _skip(reason, restore=False, **extra): if restore: - restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) + restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline) + wake = _left_out_wake() # CC truncates metrics to 10 keys by # insertion order. v2_metrics (3) must precede sweep (3) so the v2 # diagnostics survive when extra adds touched_paths_count + ip_* keys. @@ -2500,8 +2654,8 @@ def handle_stop_hook(input_data): if gitutil._unparsed_diff_headers else {}), **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), - }) - sys.exit(0) + }, **wake) + sys.exit(2 if wake else 0) # Limit stop hook firings per asyncRewake loop to prevent infinite loops. # fire_count auto-expires after STOP_LOOP_STATE_TTL_SEC so a stale count @@ -2615,13 +2769,13 @@ def handle_stop_hook(input_data): f"{MAX_REVIEW_SET_PATHS} paths), skipping") _skip(8) # Run from repo_root so the toplevel-relative review_paths resolve. - # Diff CONTENT against the turn-start stash (baseline_sha) so the LLM + # Diff CONTENT against the turn-start snapshot (baseline_sha) so the LLM # sees only this-turn edits — diffing against HEAD includes the user's # pre-turn uncommitted WIP, which inflates review_ms and can re-flag # the same pre-existing pattern every turn. The file LIST still comes # from git state (compute_v2_review_set), so Bash/subagent edits are # caught either way. Fall back to diff_base (HEAD/head_at_capture) - # when the stash is missing or pruned. + # when the baseline commit is missing or pruned. content_base = baseline_sha or diff_base diff_output = get_git_diff(repo_root, content_base, full_context=False, paths=review_paths, untracked_paths=untracked) @@ -2644,6 +2798,15 @@ def handle_stop_hook(input_data): if not baseline_sha: baseline_sha = "HEAD" + # New files a failed `git add -N` hid: when nothing gets reviewed they are + # put back, listed as touched so the next prompt keeps this baseline even + # if an edit tool never wrote them. A review of the tracked files goes on + # without them, rather than repeating that review every turn. + left_out = gitutil._add_failed["left_out"] + if left_out: + restore_paths = list(touched_paths) + [ + os.path.join(repo_root, p) for p in untracked or ()] + if not diff_output or not diff_output.strip(): if "gave_up" in gitutil._path_list_too_long: debug_log("Stop hook: changed paths do not fit the git commands, skipping") @@ -2652,7 +2815,7 @@ def handle_stop_hook(input_data): debug_log("Stop hook: no source code files among the changed paths") _skip(7) debug_log("Stop hook: no changes since baseline") - _skip(6) + _skip(6, restore=left_out) diff_hash = hashlib.sha256(diff_output.encode("utf-8", "replace")).hexdigest() if snap.get("reviewed_diff_hash") == diff_hash: @@ -2663,7 +2826,7 @@ def handle_stop_hook(input_data): diff_files = parse_diff_into_files(diff_output) if not diff_files: debug_log("Stop hook: no source code files in diff") - _skip(7) + _skip(7, restore=left_out) # Mirror commit-review: hard-bail only on pathological diffs (>300 files, # usually a bad baseline), otherwise prioritize by security-risk path @@ -2787,6 +2950,7 @@ def handle_stop_hook(input_data): # untracked_baseline_n is the signal for whether the UPS-time # untracked-snapshot capture actually ran. sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"} + left_out_notice = _left_out_notice() # Guidance goes to stderr plus top-level decision/reason (see # emit_metrics). exit(2) preserved as the asyncRewake "force fix" # signal — that's the documented mechanism. @@ -2808,8 +2972,9 @@ def handle_stop_hook(input_data): **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), }, rewake_summary=_format_vulns_summary(vulns), - additional_context=(PROVENANCE_BANNER + "\n\n" - + concrete_guidance + CONTINUATION_SUFFIX + "\n"), + additional_context=(PROVENANCE_BANNER + "\n\n" + concrete_guidance + + ("\n\n" + left_out_notice[1] if left_out_notice else "") + + CONTINUATION_SUFFIX + "\n"), hook_event_name=hook_event_name) sys.exit(2) @@ -2817,11 +2982,12 @@ def handle_stop_hook(input_data): if stop_review_failed: debug_log(f"Stop hook: review got no verdict " f"({_review_failure_reason(llm.last_review_status())[1]})") - restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) + restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline) else: debug_log("Stop hook: no security issues found") if is_subagent: record_reviewed_diff(session_id, diff_hash) + wake = _left_out_wake() # CC keeps the first 20 metric keys (10 in older versions), in insertion # order, after the pv and usage keys emit_metrics puts first. The previous # **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced @@ -2843,8 +3009,8 @@ def handle_stop_hook(input_data): if gitutil._unparsed_diff_headers else {}), **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), - }) - sys.exit(0) + }, **wake) + sys.exit(2 if wake else 0) _SDK_BOOTSTRAP_THROTTLE = os.path.join(_resolve_state_dir(), ".sdk_bootstrap_spawned") @@ -2877,7 +3043,7 @@ def _maybe_bootstrap_agent_sdk_async(): return except OSError: pass - os.makedirs(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE), exist_ok=True) + make_state_dir(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE)) # Touch the throttle BEFORE spawning so a burst of PostToolUse # fires in the same second don't each spawn a subprocess. open(_SDK_BOOTSTRAP_THROTTLE, "w").close() @@ -2977,12 +3143,27 @@ def main(): if tool_name == "Bash" and hook_event_name == "PostToolUse": cmd = (input_data.get("tool_input") or {}).get("command", "") or "" if not (_GIT_COMMIT_RE.search(cmd) or _GIT_PUSH_RE.search(cmd)): + # Measurement only: this start matched no commit or push. Count + # it, and say whether a plain text check could have told so before + # Python. Both values carry the sample weight, so they sum to + # estimates of all such starts. + if _unmatched_bash_sampled(input_data) and not portable_output(): + skip = 0 if _shell_precheck_passes(raw_input) else _UNMATCHED_BASH_SAMPLE + emit_metrics({"bash_no_match": _UNMATCHED_BASH_SAMPLE, "precheck_skip": skip}) return + if not _shell_precheck_passes(raw_input): + # The text check would have dropped a command that is reviewed. + # Rides on whichever row this start emits; nothing is skipped. + global _precheck_miss + _precheck_miss = True if not _claim_bash_hook_once(input_data): # Another spawn for this same tool_use_id already claimed the # work (compound matched multiple `if` configs). Emit a single # metric so telemetry can count how often the de-dupe kicks in. - _write_hook_output({"metrics": {"bash_hook_dedup": True}}) + dedup = {"bash_hook_dedup": True} + if _precheck_miss and not portable_output(): + dedup = {"pv": _PV, "precheck_miss": 1, **dedup} + _write_hook_output({"metrics": dedup}) sys.exit(0) if _GIT_COMMIT_RE.search(cmd): handle_commit_review_posttooluse(input_data) diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py index c8045532..330abd28 100644 --- a/plugins/security-guidance/hooks/session_state.py +++ b/plugins/security-guidance/hooks/session_state.py @@ -20,7 +20,7 @@ import re import tempfile from datetime import datetime -from _base import debug_log, state_dir as _state_dir +from _base import debug_log, make_state_dir, state_dir as _state_dir def _state_key(session_id): @@ -139,6 +139,18 @@ def _write_then_rename(state_file, state): raise +def _write_in_place(state_file, state): + """The fallback (Windows, or a folder that refuses the rename) writes the + state file itself. As with the rename, a link there is replaced, not + followed, and a new file is the user's only, as the temporary file is.""" + if os.path.islink(state_file): + os.unlink(state_file) + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(state_file, flags, 0o600) + with os.fdopen(fd, "w") as f: + json.dump(state, f) + + def save_state(session_id, state): """Save the full state dict to file. @@ -152,12 +164,11 @@ def save_state(session_id, state): try: state_dir = os.path.dirname(state_file) if state_dir: - os.makedirs(state_dir, exist_ok=True) + make_state_dir(state_dir) if _RENAME_INTO_PLACE and _write_then_rename(state_file, state): return - with open(state_file, "w") as f: - json.dump(state, f) + _write_in_place(state_file, state) except (IOError, OSError) as e: debug_log(f"Failed to save state file {state_file}: {e}") @@ -181,7 +192,7 @@ def with_locked_state(session_id, callback): state_dir = os.path.dirname(lock_file) try: - os.makedirs(state_dir, exist_ok=True) + make_state_dir(state_dir) except OSError: pass diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh index e0c2730e..b1a5d5b9 100755 --- a/plugins/security-guidance/hooks/sg-python.sh +++ b/plugins/security-guidance/hooks/sg-python.sh @@ -100,10 +100,12 @@ probe() { # the model, whose reply runs the Stop hook again: an endless loop that # never reviewed anything. See #6251, #5781. # + # On Windows a second line carries sys.executable (see sg_own_path). + # # Only for `$(probe ...)`: the `exec` replaces that subshell instead of # forking a second process from it. [ "${BASH_SUBSHELL:-0}" -gt 0 ] || return 1 - exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}")' "$SG_TARGET" 2>/dev/null + exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}"); sys.platform == "win32" and sys.version_info >= (3, 10) and print(sys.executable)' "$SG_TARGET" 2>/dev/null } # Use as `ask ... || { note_unreadable "<name>"; continue; }` (see ask below). @@ -142,11 +144,17 @@ sg_clock() { esac } ask() { - # Sets $v; same exit status as probe. + # Sets $v and $sg_exe; same exit status as probe. local rc=0 t0 ms sg_clock; t0=$sg_now [ -n "$sg_probe_first" ] || sg_probe_first=$t0 v=$(probe "$@") || rc=$? + sg_exe="" + case "$v" in + *$'\n'*) + sg_exe=${v#*$'\n'}; sg_exe=${sg_exe%$'\r'} + v=${v%%$'\n'*} ;; + esac sg_clock; ms=$((sg_now - t0)) if [ -n "$sg_coarse" ]; then [ "$ms" -ge 2000 ] || ms=0 @@ -175,6 +183,145 @@ is_sdk_compatible() { esac } +# Packaged launcher aliases on Windows (python, python3 and py under +# ...\Microsoft\WindowsApps): starting one starts more than Python. The +# Python Install Manager's aliases make Windows check the package for an +# update on each start, and the launcher started the chosen name twice per +# hook, on every Edit, prompt and Stop. See anthropics/claude-code#98929. +# +# So when the name that answers is such an alias and its interpreter is a +# regular file elsewhere, the hook runs with that file instead, and its path +# is kept in the plugin's state folder (`launcher-python`) for a day. Later +# hooks start it directly: one process, and none through the alias. The +# remembered path is used only while PATH and the hook folder are what they +# were when it was checked and the file is still there; anything else is the +# full search below, which writes the entry again. A hook that fails on the +# remembered path empties the entry, so the next one searches again; deleting +# the file does the same by hand. One entry: sessions with different PATHs +# take turns checking, which is still one alias start per hook instead of two. +# +# Not while a virtual environment is active: the alias may be answering for +# that environment's interpreter, which other sessions should not inherit. +# +# Builtins only: nothing here starts a process on the remembered route. +unset SG_LAUNCHER_DIRECT +sg_args=("$@") +sg_exe="" # sys.executable from the last `ask` (Windows, Python 3.10+) +sg_own="" # set by sg_recall and sg_own_path +sg_memo="" # the entry's file; empty where none of this applies +sg_target_dir="" +case "${OSTYPE:-}" in + msys*|cygwin*) + if [ "${BASH_VERSINFO[0]:-0}" -ge 5 ] && [ -n "$SG_TARGET" ] && [ -z "${VIRTUAL_ENV:-}" ]; then + # The folder _base.state_dir() resolves to. + sg_home="${USERPROFILE:-${HOME:-}}" + sg_memo="${SECURITY_WARNINGS_STATE_DIR:-}" + if [ -z "$sg_memo" ] && [ -n "${CLAUDE_CONFIG_DIR:-}" ]; then + sg_memo="$CLAUDE_CONFIG_DIR/security" + fi + [ -n "$sg_memo" ] || sg_memo="~/.claude/security" + case "$sg_memo" in + "~"|"~"[\\/]*) + if [ -n "$sg_home" ]; then sg_memo="$sg_home${sg_memo:1}"; else sg_memo=""; fi ;; + esac + [ -z "$sg_memo" ] || sg_memo="$sg_memo/launcher-python" + sg_target_dir="${SG_TARGET%[\\/]*}" + fi ;; +esac + +sg_is_alias_path() { + case "${1,,}" in + */microsoft/windowsapps/*|*\\microsoft\\windowsapps\\*) return 0 ;; + esac + return 1 +} + +# An interpreter the remembered route may start: python*.exe by absolute +# path, a regular file, and not an alias itself. +sg_startable() { + local name="${1##*/}" + case "$1" in + /*) ;; + *) return 1 ;; + esac + case "${name,,}" in + python*.exe) ;; + *) return 1 ;; + esac + ! sg_is_alias_path "$1" || return 1 + [ -f "$1" ] && [ -x "$1" ] +} + +sg_recall() { + # Sets $sg_own to the remembered interpreter iff it may run this hook. + local tag saved path exe dir end age + [ -n "$sg_memo" ] && [ -r "$sg_memo" ] || return 1 + { + IFS= read -r tag && IFS= read -r saved && IFS= read -r path && + IFS= read -r exe && IFS= read -r dir && IFS= read -r end + } 2>/dev/null < "$sg_memo" || return 1 + [ "$tag" = "sg-launcher-python 1" ] && [ "$end" = "end" ] || return 1 + case "$saved" in + ""|*[!0-9]*|????????????*) return 1 ;; + esac + age=$((EPOCHSECONDS - 10#$saved)) + [ "$age" -ge 0 ] && [ "$age" -lt 86400 ] || return 1 + [ "$path" = "$PATH" ] && [ "$dir" = "$sg_target_dir" ] || return 1 + sg_startable "$exe" && [ -r "$SG_TARGET" ] || return 1 + sg_own="$exe" +} + +sg_own_path() { + # $1: the name that just answered `ask` with version $v. Succeeds, with + # $sg_own set, iff that name is a packaged alias whose interpreter is a + # regular file elsewhere that reads the hook script when started by + # itself and is the same version. Remembers it for the next hooks. + local alias="" own="$sg_exe" want="$v" drive + [ -n "$sg_memo" ] && [ -n "$own" ] || return 1 + hash "$1" 2>/dev/null && alias="${BASH_CMDS[$1]:-}" + sg_is_alias_path "$alias" || return 1 + case "$own" in + [A-Za-z]:[\\/]*) + if [ -n "${sg_drive_mounts:-}" ]; then + drive="${own:0:1}"; own="/${drive,,}/${own:3}"; own="${own//\\//}" + else + own=$(cygpath -u "$own" 2>/dev/null) || return 1 + fi ;; + esac + sg_startable "$own" || return 1 + ask "$own" || { v=$want; return 1; } + v=${v%$'\r'} + [ "$v" = "$want" ] || { v=$want; return 1; } + sg_own="$own" + if [ -d "${sg_memo%/*}" ]; then + { printf '%s\n' "sg-launcher-python 1" "$EPOCHSECONDS" "$PATH" "$own" "$sg_target_dir" "end"; } \ + 2>/dev/null > "$sg_memo" || true + fi + return 0 +} + +# Use right before `exec <name> "$@"`: runs the hook with the interpreter +# behind <name> instead when sg_own_path finds one, else returns. +sg_direct() { + if sg_own_path "$@"; then + export SG_LAUNCHER_DIRECT=2 + exec "$sg_own" "${sg_args[@]}" + fi + return 0 +} + +if sg_recall; then + export SG_LAUNCHER_DIRECT=1 + # Not exec'd, so a failure can empty the entry: no probe checked this + # interpreter today, and a broken one must not fail every hook for a day. + sg_rc=0 + "$sg_own" "$@" || sg_rc=$? + if [ "$sg_rc" -ne 0 ]; then + { : > "$sg_memo"; } 2>/dev/null || true + fi + exit "$sg_rc" +fi + # Pass 1 — try minor-versioned binaries in descending order. These are only # present if the user explicitly installed them (Homebrew / python.org / pyenv), # so picking one here always upgrades over the system `python3`. Highest @@ -185,6 +332,7 @@ for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do ask "$cmd" || { note_unreadable "$cmd"; continue; } v=${v%$'\r'} if is_sdk_compatible "$v"; then + sg_direct "$cmd" exec "$cmd" "$@" fi done @@ -201,6 +349,8 @@ for cmd in "python3" "python" "py -3"; do v=${v%$'\r'} if is_sdk_compatible "$v"; then # shellcheck disable=SC2086 + sg_direct $cmd + # shellcheck disable=SC2086 exec $cmd "$@" fi # Anything that successfully reported a "M.m" string. @@ -219,6 +369,7 @@ done for cmd in "python3.14" "python3.15" "python3.16" "python3.17" "python3.18" "python3.19"; do on_path "$cmd" || continue v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + v=${v%%$'\n'*} v=${v%$'\r'} if is_sdk_compatible "$v"; then exec "$cmd" "$@" 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" |
