summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-14 16:56:05 +0000
committerClaude <noreply@anthropic.com>2026-10-19 16:29:44 +0000
commit49484affa8f5730ec9bcfd6e25c393bc021cdd34 (patch)
treed3a6dbed3a15f8ea358d560cab870afef007951e /plugins
parentea10b213686c90bb1984b2016937310e05336cf3 (diff)
security-guidance: do not install the agent SDK for reviews that are off
The SessionStart bootstrap and its PostToolUse rescue built a venv of a few hundred MB for the agent SDK whatever the environment said, including under SECURITY_GUIDANCE_DISABLE=1, and the rescue started the bootstrap again every five minutes on machines whose SDK lives in that venv (#5331). - Nothing is installed when the environment turns off every review that loads the SDK: the kill switch, ENABLE_CODE_SECURITY_REVIEW=0, or ENABLE_STOP_REVIEW=0 with ENABLE_COMMIT_REVIEW=0. Reported as sdk_bootstrap 10. A disabled plugin also no longer shows the "reviewer unavailable" notice on a Python below 3.10. - The rescue leaves a finished install under the state dir alone instead of starting the bootstrap for it every five minutes. - New counts on the bootstrap's metrics row, set only when true and only when the install exists: sdk_no_creds and sdk_no_git (the session cannot run the reviews the install serves), sdk_venv_py (the venv was built by another Python version than the one running the hooks, #5706). They size follow-up changes; no behaviour depends on them. With the reviews on, what is built and when is unchanged.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/_base.py42
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py80
-rw-r--r--plugins/security-guidance/hooks/llm.py21
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py6
-rw-r--r--plugins/security-guidance/tests/test_sdk_bootstrap_switches.py183
5 files changed, 318 insertions, 14 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 1daa6642..6f2944be 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -5,6 +5,7 @@ This module exists so that ``patterns``/``session_state``/``gitutil`` can use
``debug_log`` without importing ``security_reminder_hook`` (which would be a
circular import). It must stay free of any other intra-plugin imports.
"""
+import glob
import json
import os
import re
@@ -40,6 +41,47 @@ def state_dir():
return os.path.expanduser("~/.claude/security")
+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),
+ ENABLE_CODE_SECURITY_REVIEW=0, or ENABLE_STOP_REVIEW=0 together with
+ ENABLE_COMMIT_REVIEW=0. Nothing loads the agent SDK then, so nothing
+ should install it. Same reading of each variable as
+ security_reminder_hook.py."""
+ env = os.environ.get
+ if env("SECURITY_GUIDANCE_DISABLE", "").strip().lower() in ("1", "true", "yes", "on"):
+ return True
+ if env("ENABLE_SECURITY_REMINDER", "1") == "0":
+ return True
+ if env("ENABLE_CODE_SECURITY_REVIEW", "1") == "0":
+ return True
+ return env("ENABLE_STOP_REVIEW", "1") == "0" and env("ENABLE_COMMIT_REVIEW", "1") == "0"
+
+
+def agent_sdk_site_dirs(state_dir):
+ """Directories under the state dir that ensure_agent_sdk.py installs the
+ agent SDK into and llm.py adds to sys.path: the venv's site-packages
+ (POSIX `lib/pythonX.Y/site-packages`, Windows `Lib/site-packages`) and
+ the flat `pip install --target` fallback."""
+ venv_root = os.path.join(state_dir, "agent-sdk-venv")
+ return (
+ glob.glob(os.path.join(venv_root, "lib", "python*", "site-packages"))
+ + glob.glob(os.path.join(venv_root, "Lib", "site-packages"))
+ + [os.path.join(state_dir, "agent-sdk-libs")]
+ )
+
+
+def agent_sdk_installed(state_dir):
+ """True iff one of those directories holds a finished install of the SDK:
+ its package and the metadata pip writes once the package is unpacked. A
+ file check only, no import."""
+ return any(
+ os.path.isfile(os.path.join(d, "claude_agent_sdk", "__init__.py"))
+ and glob.glob(os.path.join(d, "claude_agent_sdk-*.dist-info"))
+ for d in agent_sdk_site_dirs(state_dir)
+ )
+
+
# Debug log file. Lives under the plugin state dir (default ~/.claude/security/)
# rather than /tmp because /tmp is world-writable on multi-user hosts (TOCTOU /
# symlink-attack surface, cross-user log leakage). Overridable per-process via
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index 059f3825..923d4822 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -28,6 +28,7 @@ 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 portable_output, state_dir as _resolve_state_dir, write_hook_output
+from _base import llm_reviews_switched_off
# Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry.
NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python
@@ -55,6 +56,9 @@ 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.
+SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would
+ # load the SDK (kill switch included), so nothing is
+ # installed. See #5331.
# How long to skip rebuilds after a signal kill. Retries at most once per
# window so a machine whose memory frees up still recovers (just not every
@@ -453,6 +457,74 @@ def _build_via_target(state_dir) -> tuple[int, str, str]:
return BUILD_FAILED, "pip_target", f"exc:{type(e).__name__}"
+def _near_git_repo() -> bool:
+ """Whether the session's directory is in a git work tree (a `.git` entry
+ here or above) or directly holds one (a workspace of repositories). The
+ reviews the SDK serves only run on a repository."""
+ try:
+ top = d = os.path.abspath(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
+ while True:
+ if os.path.exists(os.path.join(d, ".git")):
+ return True
+ parent = os.path.dirname(d)
+ if parent == d:
+ break
+ d = parent
+ with os.scandir(top) as entries:
+ for i, entry in enumerate(entries):
+ if i >= 500:
+ return True # too large to say; not counted
+ if entry.is_dir() and os.path.exists(os.path.join(entry.path, ".git")):
+ return True
+ return False
+ except OSError:
+ return True
+
+
+def _venv_python_version(venv) -> int:
+ """The Python the venv was built with, as major*100+minor (312), read
+ from its pyvenv.cfg; 0 if unknown."""
+ try:
+ for line in (Path(venv) / "pyvenv.cfg").read_text(errors="replace").splitlines():
+ key, _, value = line.partition("=")
+ if key.strip() in ("version", "version_info"):
+ major, minor = value.strip().split(".")[:2]
+ return int(major) * 100 + int(minor)
+ except (OSError, ValueError):
+ pass
+ return 0
+
+
+def _install_context_metrics(outcome, state_dir) -> dict:
+ """Counts that size two open questions about the private SDK install; no
+ behaviour depends on them. Only on rows where the install exists, and
+ only when set.
+
+ sdk_no_creds / sdk_no_git: the session holds the install while the
+ reviews it serves cannot run, for lack of model credentials or of a git
+ repository. Should the build wait for those? See #5331.
+
+ sdk_venv_py: the venv was built by another Python version than the one
+ running the hooks, which is the one that loads it; its compiled
+ dependencies do not load there. See #5706."""
+ out = {}
+ if outcome not in (NOOP_VENV, BUILT, BUILT_TARGET, NOOP_TARGET):
+ return out
+ try:
+ import llm
+ if not llm.HAS_API_CREDENTIALS:
+ out["sdk_no_creds"] = 1
+ except Exception:
+ pass
+ if not _near_git_repo():
+ out["sdk_no_git"] = 1
+ if outcome == NOOP_VENV:
+ built_by = _venv_python_version(Path(state_dir) / "agent-sdk-venv")
+ if built_by and built_by != sys.version_info[0] * 100 + sys.version_info[1]:
+ out["sdk_venv_py"] = built_by
+ return out
+
+
def _sdk_on_syspath() -> bool:
# find_spec is ~10ms; actually importing the SDK pulls in
# transitive deps and costs ~800ms — too heavy for a
@@ -481,6 +553,13 @@ 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.
"""
+ # 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
+ # advertise a reviewer the user turned off. See #5331.
+ if llm_reviews_switched_off():
+ return SKIP_REVIEWS_OFF, "", ""
+
# Honesty check (fixes the misleading NOOP_VENV in #2071): the SDK
# requires Python >=3.10 and uses 3.10+ syntax (match statements,
# PEP 604 unions). On a 3.9 hook interpreter we CANNOT import it no
@@ -846,6 +925,7 @@ if __name__ == "__main__":
# HOOK_PY_INCOMPATIBLE (whose "py_3.9" err_kind otherwise collapses to
# err=99, losing the version). Cheap — no subprocess, just sys.version_info.
metrics["sdk_hook_py"] = sys.version_info[0] * 100 + sys.version_info[1]
+ metrics.update(_install_context_metrics(outcome, _resolve_state_dir()))
pv = _plugin_version_int()
if pv:
metrics["pv"] = pv
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 9fe8640c..dfddf6a0 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -17,7 +17,6 @@ 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 glob
import hashlib
import json
import logging
@@ -34,7 +33,7 @@ from typing import Optional, Tuple, Dict, Any, List
import extensibility
import review_api
-from _base import debug_log, _record_usage, _record_http_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir # noqa: F401
+from _base import debug_log, _record_usage, _record_http_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401
from session_state import with_locked_state
from gitutil import git_config_env, SAFE_GIT_CONFIG
@@ -59,17 +58,13 @@ def _inject_agent_sdk_venv_into_syspath(state_dir):
fails with `ModuleNotFoundError: pywintypes` and the agentic reviewer
falls back to single-shot silently. Replicate what site.py would do.
"""
- venv_root = os.path.join(state_dir, "agent-sdk-venv")
- candidates = (
- glob.glob(os.path.join(venv_root, "lib", "python*", "site-packages"))
- + glob.glob(os.path.join(venv_root, "Lib", "site-packages"))
- # `pip install --target` fallback (ensure_agent_sdk BUILT_TARGET, used
- # when venv can't bootstrap pip): a FLAT layout — packages sit directly
- # in agent-sdk-libs/, not under a site-packages subdir. See #2154
- # follow-up. The pywin32 .pth bootstrap below applies here too (target
- # installs don't process .pth at runtime, same as a manual venv insert).
- + [os.path.join(state_dir, "agent-sdk-libs")]
- )
+ # `agent-sdk-libs` is the `pip install --target` fallback
+ # (ensure_agent_sdk BUILT_TARGET, used when venv can't bootstrap pip): a
+ # FLAT layout, packages sit directly in it, not under a site-packages
+ # subdir. See #2154 follow-up. The pywin32 .pth bootstrap below applies
+ # there too (target installs don't process .pth at runtime, same as a
+ # manual venv insert).
+ candidates = agent_sdk_site_dirs(state_dir)
added = False
for sp in candidates:
if not os.path.isdir(sp) or sp in sys.path:
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index ea5bab18..fcb04973 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -86,6 +86,7 @@ from _base import ( # noqa: E402,F401
_USAGE_CONTEXT, _log_usage,
state_dir as _resolve_state_dir,
write_hook_output as _write_hook_output,
+ llm_reviews_switched_off, agent_sdk_installed,
)
import extensibility # noqa: E402
from patterns import ( # noqa: E402,F401
@@ -2483,12 +2484,15 @@ def _maybe_bootstrap_agent_sdk_async():
is idempotent and O_EXCL-locked, so concurrent/repeat spawns are safe;
the throttle file only avoids spawning dozens of subprocesses during
the build window. No-ops in ~10ms on local installs (SDK already
- importable).
+ importable, or already installed under the state dir, which is not on
+ sys.path here) and when the environment turns the LLM reviews off.
"""
try:
import importlib.util
if importlib.util.find_spec("claude_agent_sdk") is not None:
return
+ if llm_reviews_switched_off() or agent_sdk_installed(_resolve_state_dir()):
+ return
import time as _t
try:
if _t.time() - os.path.getmtime(_SDK_BOOTSTRAP_THROTTLE) < 300:
diff --git a/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py b/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py
new file mode 100644
index 00000000..36f2742b
--- /dev/null
+++ b/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py
@@ -0,0 +1,183 @@
+"""The agent SDK is not installed for reviews that are switched off.
+
+ensure_agent_sdk.py (SessionStart) and the PostToolUse rescue spawn built a
+venv of a few hundred MB whatever the environment said, including under
+SECURITY_GUIDANCE_DISABLE=1, and the rescue started ensure_agent_sdk.py again
+every five minutes on machines whose SDK lives in that venv. See #5331.
+"""
+import importlib.util
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR
+import _base
+import ensure_agent_sdk as boot
+import llm
+import security_reminder_hook as hook
+
+OFF = [
+ {"SECURITY_GUIDANCE_DISABLE": "1"},
+ {"SECURITY_GUIDANCE_DISABLE": "true"},
+ {"ENABLE_SECURITY_REMINDER": "0"},
+ {"ENABLE_CODE_SECURITY_REVIEW": "0"},
+ {"ENABLE_STOP_REVIEW": "0", "ENABLE_COMMIT_REVIEW": "0"},
+]
+STILL_ON = [{}, {"ENABLE_STOP_REVIEW": "0"}, {"ENABLE_COMMIT_REVIEW": "0"},
+ {"SECURITY_GUIDANCE_DISABLE": "0"}]
+SWITCHES = ("SECURITY_GUIDANCE_DISABLE", "ENABLE_SECURITY_REMINDER",
+ "ENABLE_CODE_SECURITY_REVIEW", "ENABLE_STOP_REVIEW", "ENABLE_COMMIT_REVIEW")
+
+
+@pytest.fixture
+def state(tmp_path, monkeypatch):
+ """Empty state dir, no SDK in the interpreter, switches unset."""
+ for name in SWITCHES:
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.setattr(boot, "_sdk_on_syspath", lambda: False)
+ return tmp_path / "state"
+
+
+@pytest.fixture
+def builds(monkeypatch):
+ """Records the venv / pip commands instead of running them."""
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append([str(c) for c in cmd])
+ return subprocess.CompletedProcess(cmd, 0, b"", b"")
+ monkeypatch.setattr(boot.subprocess, "run", run)
+ return calls
+
+
+@pytest.fixture
+def spawns(state, monkeypatch):
+ """Records the rescue's detached starts of ensure_agent_sdk.py."""
+ calls = []
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ monkeypatch.setattr(hook, "_SDK_BOOTSTRAP_THROTTLE", str(state / ".sdk_bootstrap_spawned"))
+ monkeypatch.setattr(hook.subprocess, "Popen", lambda cmd, **kw: calls.append(cmd))
+ return calls
+
+
+def _install(root, finished=True):
+ pkg = root / "claude_agent_sdk"
+ pkg.mkdir(parents=True)
+ (pkg / "__init__.py").write_text("")
+ if finished:
+ (root / "claude_agent_sdk-0.2.0.dist-info").mkdir()
+
+
+@pytest.mark.parametrize("env", OFF)
+def test_session_start_builds_nothing_when_reviews_are_off(state, builds, monkeypatch, env):
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ assert boot.main() == (boot.SKIP_REVIEWS_OFF, "", "")
+ assert builds == [] and not state.exists()
+
+
+@pytest.mark.parametrize("env", STILL_ON)
+def test_session_start_still_builds_when_a_review_can_run(state, builds, monkeypatch, env):
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ assert boot.main()[0] == boot.BUILT
+ assert [c[1:3] for c in builds] == [["-m", "venv"], ["-m", "pip"]]
+
+
+@pytest.mark.parametrize("env", OFF[2:])
+def test_rescue_does_not_start_the_bootstrap_when_reviews_are_off(spawns, monkeypatch, env):
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ hook._maybe_bootstrap_agent_sdk_async()
+ assert spawns == []
+
+
+def test_rescue_starts_the_bootstrap_once_when_nothing_is_installed(spawns):
+ hook._maybe_bootstrap_agent_sdk_async()
+ hook._maybe_bootstrap_agent_sdk_async()
+ assert len(spawns) == 1 and spawns[0][1].endswith("ensure_agent_sdk.py")
+
+
+@pytest.mark.parametrize("where", [
+ "agent-sdk-venv/lib/python3.12/site-packages",
+ "agent-sdk-venv/Lib/site-packages",
+ "agent-sdk-libs",
+])
+def test_rescue_leaves_an_existing_install_alone(spawns, state, where):
+ _install(state / where)
+ hook._maybe_bootstrap_agent_sdk_async()
+ assert spawns == [] and not (state / ".sdk_bootstrap_spawned").exists()
+
+
+def test_rescue_still_runs_for_an_install_that_was_cut_short(spawns, state):
+ _install(state / "agent-sdk-venv/lib/python3.12/site-packages", finished=False)
+ hook._maybe_bootstrap_agent_sdk_async()
+ assert len(spawns) == 1
+
+
+def test_reviewer_and_bootstrap_agree_on_where_the_sdk_is_installed(state, monkeypatch):
+ for where in ("agent-sdk-venv/lib/python3.12/site-packages", "agent-sdk-libs"):
+ _install(state / where)
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ assert llm._inject_agent_sdk_venv_into_syspath(str(state))
+ assert {str(state / "agent-sdk-venv/lib/python3.12/site-packages"),
+ str(state / "agent-sdk-libs")} <= set(sys.path)
+
+
+def test_switches_are_read_the_same_way_as_the_hook_reads_them(monkeypatch):
+ for env in OFF + STILL_ON:
+ for name in SWITCHES:
+ monkeypatch.delenv(name, raising=False)
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ out = subprocess.run(
+ [sys.executable, "-c",
+ "import security_reminder_hook as h; "
+ "print(h.SECURITY_GUIDANCE_DISABLED or not h.ENABLE_CODE_SECURITY_REVIEW"
+ " or not (h.ENABLE_STOP_REVIEW or h.ENABLE_COMMIT_REVIEW))"],
+ cwd=HOOKS_DIR, capture_output=True, text=True).stdout.strip()
+ assert out == str(_base.llm_reviews_switched_off()), env
+
+
+def test_disabled_plugin_says_nothing_on_a_python_below_3_10(state, builds, monkeypatch):
+ monkeypatch.setenv("SECURITY_GUIDANCE_DISABLE", "1")
+ monkeypatch.setattr(boot.sys, "version_info", (3, 9, 6, "final", 0))
+ assert boot.main()[0] == boot.SKIP_REVIEWS_OFF
+
+
+def test_install_the_session_cannot_use_is_counted(state, tmp_path, monkeypatch):
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", False)
+ monkeypatch.setattr(boot, "_near_git_repo", lambda: False)
+ assert boot._install_context_metrics(boot.BUILT, state) == {"sdk_no_creds": 1, "sdk_no_git": 1}
+ assert boot._install_context_metrics(boot.BUILD_FAILED, state) == {}
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True)
+ monkeypatch.setattr(boot, "_near_git_repo", lambda: True)
+ assert boot._install_context_metrics(boot.NOOP_VENV, state) == {}
+
+
+def test_session_directory_in_or_holding_a_repository(tmp_path, monkeypatch):
+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(tmp_path))
+ if boot._near_git_repo():
+ pytest.skip("the temp dir is itself inside a git work tree")
+ (tmp_path / "ws" / "repo" / ".git").mkdir(parents=True)
+ (tmp_path / "ws" / "repo" / "src").mkdir()
+ for inside in ("ws", "ws/repo", "ws/repo/src"):
+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(tmp_path / inside))
+ assert boot._near_git_repo(), inside
+
+
+@pytest.mark.parametrize("cfg, counted", [
+ ("home = /usr/bin\nversion = 3.99.1\n", {"sdk_venv_py": 399}),
+ ("home = /usr/bin\nversion_info = 3.99.1.final.0\n", {"sdk_venv_py": 399}),
+ (f"version = {sys.version_info[0]}.{sys.version_info[1]}.0\n", {}),
+ ("home = /usr/bin\n", {}),
+])
+def test_venv_built_by_another_python_is_counted(state, monkeypatch, cfg, counted):
+ monkeypatch.setattr(boot, "_near_git_repo", lambda: True)
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True)
+ (state / "agent-sdk-venv").mkdir(parents=True)
+ (state / "agent-sdk-venv" / "pyvenv.cfg").write_text(cfg)
+ assert boot._install_context_metrics(boot.NOOP_VENV, state) == counted
+ assert boot._install_context_metrics(boot.BUILT, state) == {}