summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md2
-rw-r--r--plugins/security-guidance/hooks/_base.py6
-rw-r--r--plugins/security-guidance/hooks/llm.py78
-rw-r--r--plugins/security-guidance/tests/test_windows_cli_lookup.py272
4 files changed, 345 insertions, 13 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index caef1866..f3318e78 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:
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 28b189a4..ccc3dc1d 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -12,6 +12,12 @@ import re
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.
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 468d9e6d..a9a84c07 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -805,11 +805,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 +822,69 @@ 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 is the home folder."""
+ skipped = [d for d in (os.getcwd(), os.environ.get("CLAUDE_PROJECT_DIR")) if d and os.path.isdir(d)]
+ home = os.path.expanduser("~")
+ roots = [os.path.normcase(os.path.realpath(d)) for d in skipped
+ if os.path.normcase(os.path.realpath(d)) != os.path.normcase(os.path.realpath(home))]
+ 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.rstrip(os.sep) + os.sep) 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
@@ -980,7 +1032,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
@@ -2009,7 +2061,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,6 +2071,8 @@ 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.
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..e303c7ed
--- /dev/null
+++ b/plugins/security-guidance/tests/test_windows_cli_lookup.py
@@ -0,0 +1,272 @@
+"""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_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():
+ 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"