summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-20 13:27:28 -0700
committerGitHub <noreply@github.com>2026-10-20 13:27:28 -0700
commit7bcf8f3757d158e023b98c151d8091cbf130db91 (patch)
tree39c6290b24268c366c2506cc66fb9a230b0185cd
parent62bb122f3052d547bdc4e5e2d0e4029fdcb2e8e5 (diff)
parent1eee6df1f032b8719fecdd987273d908d168f467 (diff)
Merge pull request #6812 from anthropics/mhegazy/sg-bootstrap-spawn-cwd
security-guidance: run SDK bootstrap subprocesses from the state dir
-rw-r--r--plugins/security-guidance/hooks/_base.py11
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py30
-rw-r--r--plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py75
3 files changed, 105 insertions, 11 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 1daa6642..eecae8b5 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -33,11 +33,12 @@ def state_dir():
"""
explicit = os.environ.get("SECURITY_WARNINGS_STATE_DIR")
if explicit:
- return os.path.expanduser(explicit)
- cc_config = os.environ.get("CLAUDE_CONFIG_DIR")
- if cc_config:
- return os.path.expanduser(os.path.join(cc_config, "security"))
- return os.path.expanduser("~/.claude/security")
+ d = explicit
+ elif os.environ.get("CLAUDE_CONFIG_DIR"):
+ d = os.path.join(os.environ["CLAUDE_CONFIG_DIR"], "security")
+ else:
+ d = "~/.claude/security"
+ return os.path.abspath(os.path.expanduser(d))
# Debug log file. Lives under the plugin state dir (default ~/.claude/security/)
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index 059f3825..c1d59ba7 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -29,6 +29,24 @@ from pathlib import Path
# main() and _maybe_emit_user_notice).
from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output
+
+def _spawn_cwd() -> str:
+ """Working directory for every Python this file starts.
+
+ `python -c` and `python -m` put the working directory first on the import
+ path, and hooks run in the user's repository, so a repository file named
+ `claude_agent_sdk.py`, `venv.py` or `pip.py` would be imported in place
+ of the real module. The state dir is the plugin's own (the venv is built
+ there, so the interpreter can reach it); the plugin folder is the
+ fallback when it can't be created.
+ """
+ d = _resolve_state_dir()
+ try:
+ os.makedirs(d, exist_ok=True)
+ return d
+ except OSError:
+ return str(Path(__file__).resolve().parent.parent)
+
# Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry.
NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python
NOOP_VENV = 1 # venv already built and SDK imports from it
@@ -311,7 +329,7 @@ def _probe_has_pip() -> bool:
try:
r = subprocess.run(
[sys.executable, "-m", "pip", "--version"],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
return r.returncode == 0
except Exception:
@@ -409,7 +427,7 @@ def _target_sdk_importable(state_dir) -> bool:
[sys.executable, "-c",
"import sys; sys.path.insert(0, sys.argv[1]); import claude_agent_sdk",
str(target)],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
return r.returncode == 0
except Exception:
@@ -434,7 +452,7 @@ def _build_via_target(state_dir) -> tuple[int, str, str]:
"--target", str(target), "--upgrade",
"--disable-pip-version-check", "--prefer-binary", "--no-cache-dir",
"claude-agent-sdk"],
- capture_output=True, timeout=120, check=True,
+ capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(),
)
return BUILT_TARGET, "", ""
except subprocess.CalledProcessError as e:
@@ -534,7 +552,7 @@ def main() -> tuple[int, str, str]:
try:
r = subprocess.run(
[str(venv_py), "-c", "import claude_agent_sdk"],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
if r.returncode == 0:
return NOOP_VENV, "", ""
@@ -570,7 +588,7 @@ def main() -> tuple[int, str, str]:
err_phase = "venv"
subprocess.run(
[sys.executable, "-m", "venv", "--clear", str(venv)],
- capture_output=True, timeout=60, check=True,
+ capture_output=True, timeout=60, check=True, cwd=_spawn_cwd(),
)
# Some machines route pip through a private registry; we
# don't pass --index-url here so we inherit that default. Outside
@@ -594,7 +612,7 @@ def main() -> tuple[int, str, str]:
[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,
+ capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(),
)
return BUILT, "", ""
except subprocess.CalledProcessError as e:
diff --git a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py
new file mode 100644
index 00000000..2325cd9b
--- /dev/null
+++ b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py
@@ -0,0 +1,75 @@
+"""The SDK bootstrap's Python subprocesses must not import from the repository.
+
+`python -c` and `python -m` put the working directory first on the import
+path, and hooks run in the user's repository, so every interpreter the
+bootstrap starts runs from a directory the plugin owns.
+"""
+import ast
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+import ensure_agent_sdk
+
+from conftest import HOOKS_DIR, make_repo
+
+
+def _spawns(tree):
+ for node in ast.walk(tree):
+ if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ and node.func.attr in ("run", "Popen", "call", "check_call", "check_output")
+ and isinstance(node.func.value, ast.Name) and node.func.value.id == "subprocess"):
+ yield node
+
+
+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
+ 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"
+ assert ast.unparse(cwd[0].value) == "_spawn_cwd()", call.lineno
+
+
+def test_spawn_cwd_is_the_state_dir(tmp_path, monkeypatch):
+ state = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state))
+ assert ensure_agent_sdk._spawn_cwd() == str(state)
+ assert state.is_dir()
+
+
+def test_relative_state_dir_is_made_absolute(tmp_path, monkeypatch):
+ # Children run in the state dir, so a relative one would be resolved twice.
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", "rel")
+ assert ensure_agent_sdk._spawn_cwd() == str(tmp_path / "rel")
+
+
+@pytest.mark.skipif(sys.platform == "win32", reason="symlinked interpreter")
+@pytest.mark.skipif(sys.version_info < (3, 10), reason="bootstrap stops before the probe")
+def test_health_check_ignores_module_in_repo(tmp_path, monkeypatch):
+ repo = tmp_path / "repo"
+ make_repo(repo)
+ marker = tmp_path / "imported-from-repo"
+ (repo / "claude_agent_sdk.py").write_text(
+ f"open({str(marker)!r}, 'w').write('x')\n")
+
+ state = tmp_path / "state"
+ venv_bin = state / "agent-sdk-venv" / ("Scripts" if sys.platform == "win32" else "bin")
+ venv_bin.mkdir(parents=True)
+ venv_py = venv_bin / ("python.exe" if sys.platform == "win32" else "python")
+ os.symlink(sys.executable, venv_py)
+
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state))
+ monkeypatch.chdir(repo)
+ monkeypatch.setattr(ensure_agent_sdk, "_sdk_on_syspath", lambda: False)
+ # No rebuild if the probe fails: this test only covers the probe.
+ ensure_agent_sdk._write_cooldown(state)
+
+ outcome, _, _ = ensure_agent_sdk.main()
+
+ assert outcome in (ensure_agent_sdk.NOOP_VENV, ensure_agent_sdk.SKIP_COOLDOWN)
+ assert not marker.exists()