diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-11-03 17:21:12 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-03 17:54:56 +0000 |
| commit | 1b445c78f3a95d12be56b9386e668aef863f5c24 (patch) | |
| tree | c0c41d32b701d82c00a00afdb5cfda598cf5bfff /plugins | |
| parent | a2e251d9b97b909bf728b3e84fc8d17e6aba0063 (diff) | |
security-guidance: keep pip's downloads out of the system temp dir
pip keeps each wheel it downloads in a pip-unpack-* folder under the temp
dir and removes it only on a normal exit. The SDK bootstrap kills pip at
its 120s timeout, so on a slow connection every attempt left its download
in the system temp dir, and attempts repeat while the SDK is missing.
Both pip installs (venv and --target fallback) now run with a temp folder
of their own under the plugin's state dir. It is removed when the attempt
ends, however it ends. A folder left by a bootstrap that was itself killed
is removed by a later bootstrap run.
Refs #6979
Diffstat (limited to 'plugins')
3 files changed, 231 insertions, 5 deletions
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index d3aaf96b..e047956f 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -455,6 +455,63 @@ def _target_sdk_importable(state_dir) -> bool: return False +# pip keeps every wheel it downloads in a `pip-unpack-*` folder under the temp +# dir and removes it only when it exits normally. An install killed at the +# timeout (or by the OOM killer) left those folders in the system temp dir, +# one attempt after another. See #6979. So pip gets a temp folder of its own +# under the state dir: removed when the attempt ends, however it ends, and +# swept on a later run when the bootstrap itself was killed first. +_PIP_TIMEOUT_SEC = 120 +# Older than any install can be: the folder of a bootstrap that was killed. +_PIP_TEMP_STALE_SEC = 15 * 60 + + +def _pip_temp_root(state_dir) -> Path: + return Path(state_dir) / "pip-tmp" + + +def _sweep_pip_temp(state_dir) -> None: + """Remove pip temp folders left by a bootstrap that was killed before it + could remove its own. Best-effort; a folder still in use is too young.""" + try: + entries = list(_pip_temp_root(state_dir).iterdir()) + except OSError: + return # the usual case: nothing was ever left + import shutil + now = time.time() + for entry in entries: + try: + if now - entry.stat().st_mtime > _PIP_TEMP_STALE_SEC: + shutil.rmtree(entry, ignore_errors=True) + except OSError: + pass + + +def _run_pip_install(cmd, state_dir): + """Run a `pip install` command under the timeout, with its temp files in + a folder of ours. Raises what subprocess.run(check=True) raises. Falls + back to the inherited temp dir when the folder can't be made.""" + import shutil + import tempfile + tmp = env = None + try: + root = _pip_temp_root(state_dir) + root.mkdir(parents=True, exist_ok=True) + tmp = tempfile.mkdtemp(dir=root) + # tempfile reads TMPDIR, TEMP, TMP in that order on every platform. + env = {**os.environ, "TMPDIR": tmp, "TEMP": tmp, "TMP": tmp} + except OSError: + pass + try: + return subprocess.run( + cmd, capture_output=True, timeout=_PIP_TIMEOUT_SEC, check=True, + cwd=_spawn_cwd(), env=env, + ) + finally: + if tmp is not None: + shutil.rmtree(tmp, ignore_errors=True) + + def _build_via_target(state_dir) -> tuple[int, str, str]: """Fallback install when `python -m venv` can't bootstrap pip (ensurepip missing — Debian python3-venv absent, or a python.org/pyenv build without @@ -468,12 +525,12 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: preference (ARM64 Windows cryptography).""" target = _target_dir(state_dir) try: - subprocess.run( + _run_pip_install( [sys.executable, "-m", "pip", "install", "--target", str(target), "--upgrade", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), + state_dir, ) return BUILT_TARGET, "", "" except subprocess.CalledProcessError as e: @@ -595,6 +652,8 @@ def main() -> tuple[int, str, str]: """ global _venv_was_emptied _venv_was_emptied = False + # Before any early return: nothing else ever clears the state dir. + _sweep_pip_temp(_resolve_state_dir()) # 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 @@ -712,11 +771,11 @@ def main() -> tuple[int, str, str]: # --no-cache-dir trims pip's peak memory (no cache read/write/unpack # buffering) — helps marginal low-memory machines get under the OOM # threshold that kills the dominant Linux builds (CCR repro). - subprocess.run( + _run_pip_install( [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, cwd=_spawn_cwd(), + state_dir, ) 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 index 2325cd9b..03c35087 100644 --- a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py +++ b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py @@ -27,7 +27,7 @@ def _spawns(tree): 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 + assert len(calls) >= 5 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" diff --git a/plugins/security-guidance/tests/test_sdk_install_timeout.py b/plugins/security-guidance/tests/test_sdk_install_timeout.py new file mode 100644 index 00000000..4c734cea --- /dev/null +++ b/plugins/security-guidance/tests/test_sdk_install_timeout.py @@ -0,0 +1,167 @@ +"""A `pip install` that is killed leaves nothing in the system temp dir. + +pip keeps each wheel it downloads in a `pip-unpack-*` folder under the temp +dir and removes it only on a normal exit. The bootstrap kills pip at its +timeout, so on a slow connection every attempt left a download behind, and +attempts repeat while the SDK is missing. See #6979. +""" +import os +import subprocess +import sys +import time + +import pytest + +import ensure_agent_sdk as boot +from test_sdk_bootstrap_switches import SWITCHES + +pytestmark = pytest.mark.skipif(sys.version_info < (3, 10), + reason="bootstrap stops before the install") + +# Stands in for pip: downloads "a wheel" the way pip does, says where, then +# either hangs (a slow connection) or exits without cleaning up. +_STAND_IN_PIP = """ +import sys, tempfile, time +d = tempfile.mkdtemp(prefix="pip-unpack-") +open(d + "/claude_agent_sdk-0.0.0-py3-none-any.whl", "wb").write(b"x" * 4096) +open(sys.argv[2], "a").write(d + "\\n") +if sys.argv[1] == "hang": + time.sleep(120) +""" + + +class Install: + """Empty state dir, no SDK anywhere. `python -m venv` is skipped and + `pip install` is the stand-in above: in "hang" mode it is killed once it + has downloaded, as subprocess.run does at the timeout.""" + + def __init__(self, tmp_path): + self.state = tmp_path / "state" + self.systmp = tmp_path / "systmp" + self.systmp.mkdir() + self.mode = "hang" + self.calls = [] + self._script = tmp_path / "stand_in_pip.py" + self._script.write_text(_STAND_IN_PIP) + self._log = tmp_path / "downloads.txt" + self._real_run = subprocess.run + + def downloads(self): + """The folders the stand-in downloaded into, one per install.""" + return self._log.read_text().split("\n")[:-1] if self._log.exists() else [] + + def run(self, cmd, **kwargs): + cmd = [str(c) for c in cmd] + if cmd[1:3] == ["-m", "venv"]: + return subprocess.CompletedProcess(cmd, 0, b"", b"") + if cmd[1:4] != ["-m", "pip", "install"]: + return self._real_run(cmd, **kwargs) + self.calls.append(cmd) + stand_in = [sys.executable, str(self._script), self.mode, str(self._log)] + if self.mode != "hang": + return self._real_run(stand_in, **kwargs) + before = len(self.downloads()) + proc = subprocess.Popen(stand_in, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + cwd=kwargs.get("cwd"), env=kwargs.get("env")) + deadline = time.time() + 60 + while len(self.downloads()) == before and time.time() < deadline: + time.sleep(0.02) + proc.kill() + proc.wait() + raise subprocess.TimeoutExpired(cmd, kwargs["timeout"]) + + +@pytest.fixture +def install(tmp_path, monkeypatch): + for name in SWITCHES + ("PYTHONPATH",): + monkeypatch.delenv(name, raising=False) + inst = Install(tmp_path) + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(inst.state)) + for name in ("TMPDIR", "TEMP", "TMP"): + monkeypatch.setenv(name, str(inst.systmp)) + monkeypatch.setattr(boot, "_sdk_on_syspath", lambda: False) + monkeypatch.setattr(boot, "_near_git_repo", lambda: True) + monkeypatch.setattr(boot.subprocess, "run", inst.run) + return inst + + +def _left_in(folder): + return sorted(p.name for p in folder.iterdir()) if folder.is_dir() else [] + + +def _downloaded_under(inst, folder): + return [os.path.realpath(d).startswith(os.path.realpath(folder) + os.sep) + for d in inst.downloads()] + + +def test_timed_out_install_leaves_no_download_behind(install): + assert boot.main() == (boot.BUILD_FAILED, "pip", "subprocess_timeout") + assert _downloaded_under(install, install.state / "pip-tmp") == [True] + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_repeated_timeouts_do_not_add_up(install): + for _ in range(3): + boot._build_via_target(install.state) + assert len(install.downloads()) == 3 + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_fallback_install_is_covered_too(install): + assert boot._build_via_target(install.state) == ( + boot.BUILD_FAILED, "pip_target", "subprocess_timeout") + assert "--target" in install.calls[0] + assert _downloaded_under(install, install.state / "pip-tmp") == [True] + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def test_finished_install_is_cleaned_up_as_well(install): + install.mode = "exit" + assert boot.main()[0] == boot.BUILT + assert len(install.downloads()) == 1 + assert _left_in(install.systmp) == [] + assert _left_in(install.state / "pip-tmp") == [] + + +def _leave_folder(install, name, age): + folder = install.state / "pip-tmp" / name + (folder / "pip-unpack-abc").mkdir(parents=True) + (folder / "pip-unpack-abc" / "half.whl").write_bytes(b"x" * 4096) + then = time.time() - age + os.utime(folder, (then, then)) + + +def test_folder_of_a_killed_bootstrap_is_removed_by_a_later_run(install): + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + # An attempt that is still running keeps its folder. + _leave_folder(install, "tmprunning", 30) + boot._sweep_pip_temp(install.state) + assert _left_in(install.state / "pip-tmp") == ["tmprunning"] + + +def test_sweep_runs_even_when_nothing_is_installed_this_time(install, monkeypatch): + """Otherwise a folder left just before the SDK got installed stays for good.""" + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + monkeypatch.setattr(boot, "_target_sdk_importable", lambda state_dir: True) + assert boot.main()[0] == boot.NOOP_TARGET + assert install.calls == [] + assert _left_in(install.state / "pip-tmp") == [] + + +@pytest.mark.parametrize("switch", ["SECURITY_GUIDANCE_DISABLE=1", "ENABLE_CODE_SECURITY_REVIEW=0"]) +def test_sweep_runs_with_reviews_switched_off(install, monkeypatch, switch): + _leave_folder(install, "tmpkilled", boot._PIP_TEMP_STALE_SEC + 60) + monkeypatch.setenv(*switch.split("=")) + assert boot.main()[0] == boot.SKIP_REVIEWS_OFF + assert _left_in(install.state / "pip-tmp") == [] + + +def test_install_still_runs_when_the_folder_cannot_be_made(install): + install.mode = "exit" + install.state.mkdir() + (install.state / "pip-tmp").write_text("in the way") + assert boot._build_via_target(install.state)[0] == boot.BUILT_TARGET + assert _downloaded_under(install, install.systmp) == [True] |
