diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-10-20 14:58:54 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-20 14:58:54 -0700 |
| commit | b2aa574dae5a7020bfb7cde1fbabea271114892c (patch) | |
| tree | cd2c333d642a351313c7568bade355001b425cb8 /plugins/security-guidance/hooks | |
| parent | c1785e2e56643aec21c99b3d879e9aef39e37d33 (diff) | |
| parent | c5bfe80e88f7ae781597b1368eb9dc90f0933d38 (diff) | |
Merge pull request #6608 from anthropics/mhegazy/sg-sdk-bootstrap-switches
security-guidance: do not install the agent SDK for reviews that are off; rebuild an emptied install
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 42 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/ensure_agent_sdk.py | 106 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 21 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 6 |
4 files changed, 159 insertions, 16 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index eecae8b5..59e8e569 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 @@ -41,6 +42,47 @@ def state_dir(): return os.path.abspath(os.path.expanduser(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), + 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 c1d59ba7..fadeae00 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 def _spawn_cwd() -> str: @@ -73,6 +74,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 @@ -410,6 +414,20 @@ def _pip_err_from_stderr(stderr_b): return f"other:{tail}" if tail else "other" +# A package directory that has lost its files still imports, as a namespace +# package, so a bare `import claude_agent_sdk` calls an emptied install +# healthy and it is never rebuilt. A real install has a __file__; the probe +# exits with _PROBE_EMPTIED when there is none. See #6612. +_PROBE_EMPTIED = 3 +_SDK_IMPORT_PROBE = ( + "import sys, claude_agent_sdk; " + f"sys.exit(0 if getattr(claude_agent_sdk, '__file__', None) else {_PROBE_EMPTIED})" +) + +# Set by main() when the venv's probe exited with _PROBE_EMPTIED. +_venv_was_emptied = False + + def _target_dir(state_dir) -> Path: return Path(state_dir) / "agent-sdk-libs" @@ -425,7 +443,7 @@ def _target_sdk_importable(state_dir) -> bool: try: r = subprocess.run( [sys.executable, "-c", - "import sys; sys.path.insert(0, sys.argv[1]); import claude_agent_sdk", + "import sys; sys.path.insert(0, sys.argv[1]); " + _SDK_IMPORT_PROBE, str(target)], capture_output=True, timeout=10, cwd=_spawn_cwd(), ) @@ -471,6 +489,79 @@ 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 open questions about the private SDK install; no + behaviour depends on them. Only when set, and the first three only on + rows where the install exists. + + 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. + + 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.""" + out = {} + if _venv_was_emptied: + out["sdk_venv_emptied"] = 1 + 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 @@ -499,6 +590,15 @@ 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 + _venv_was_emptied = False + # 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 @@ -551,11 +651,12 @@ def main() -> tuple[int, str, str]: if venv_py.exists(): try: r = subprocess.run( - [str(venv_py), "-c", "import claude_agent_sdk"], + [str(venv_py), "-c", _SDK_IMPORT_PROBE], capture_output=True, timeout=10, cwd=_spawn_cwd(), ) if r.returncode == 0: return NOOP_VENV, "", "" + _venv_was_emptied = r.returncode == _PROBE_EMPTIED except Exception: pass # broken venv; rebuild below @@ -864,6 +965,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 c2c9cdd1..76d04c54 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 @@ -35,7 +34,7 @@ from typing import Optional, Tuple, Dict, Any, List, Callable 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 load_state, with_locked_state from gitutil import git_config_env, SAFE_GIT_CONFIG @@ -60,17 +59,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 71ac3769..99b00ce0 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -88,6 +88,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 @@ -2726,12 +2727,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: |
