summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks
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/security-guidance/hooks
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/security-guidance/hooks')
-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
4 files changed, 135 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: