summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-05 14:22:10 -0800
committerGitHub <noreply@github.com>2026-11-05 14:22:10 -0800
commit53a110dc37e6dbcb20426b6b2e2b325e2ca5dc17 (patch)
tree0f96a3a17c97b983c564b7d10fcef93ac58258d6
parent88cc978a56e28d54180fda4e423bfddde1e7f532 (diff)
parent6fe57dc38d8744937b0e01ee2bb79add5f523903 (diff)
Merge pull request #7001 from anthropics/mhegazy/sg-state-dir-owner-only
security-guidance: keep the state folder to its user
-rw-r--r--plugins/security-guidance/hooks/_base.py21
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py11
-rw-r--r--plugins/security-guidance/hooks/llm.py4
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py6
-rw-r--r--plugins/security-guidance/hooks/session_state.py21
-rw-r--r--plugins/security-guidance/tests/test_state_dir_mode.py107
6 files changed, 154 insertions, 16 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 28b189a4..bdddab3d 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -9,6 +9,7 @@ import glob
import json
import os
import re
+import stat
import threading
from datetime import datetime
@@ -42,6 +43,26 @@ def state_dir():
return os.path.abspath(os.path.expanduser(d))
+def make_state_dir(d=None):
+ """Create the state dir (or `d`) with access for its user alone, and
+ narrow the default one to that if it is already there, so a umask such as
+ 002 does not leave the reviewer's venv, logs and session state open to the
+ rest of a shared group. A folder named by SECURITY_WARNINGS_STATE_DIR
+ that already exists is the user's to set. Raises OSError like os.makedirs."""
+ if d is None:
+ d = state_dir()
+ os.makedirs(d, mode=0o700, exist_ok=True)
+ if (os.name != "nt" and not os.environ.get("SECURITY_WARNINGS_STATE_DIR", "").strip()
+ and os.path.abspath(d) == state_dir()):
+ try:
+ st = os.lstat(d)
+ if stat.S_ISDIR(st.st_mode) and st.st_uid == os.getuid() and st.st_mode & 0o077:
+ os.chmod(d, 0o700)
+ except OSError:
+ pass
+ return 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),
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index d3aaf96b..c21c75f8 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -31,7 +31,7 @@ from _base import (
launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir,
write_hook_output,
)
-from _base import llm_reviews_switched_off
+from _base import llm_reviews_switched_off, make_state_dir
def _spawn_cwd() -> str:
@@ -46,8 +46,7 @@ def _spawn_cwd() -> str:
"""
d = _resolve_state_dir()
try:
- os.makedirs(d, exist_ok=True)
- return d
+ return make_state_dir(d)
except OSError:
return str(Path(__file__).resolve().parent.parent)
@@ -256,7 +255,7 @@ def _write_cooldown(state_dir) -> None:
"""Start/refresh the signal-kill cooldown so we stop re-attempting a build
that keeps getting killed every session. Best-effort."""
try:
- Path(state_dir).mkdir(parents=True, exist_ok=True)
+ make_state_dir(str(state_dir))
(Path(state_dir) / "agent-sdk-venv.cooldown").write_text(
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
except OSError:
@@ -681,7 +680,7 @@ def main() -> tuple[int, str, str]:
err_kind = ""
we_own_sentinel = False
try:
- state_dir.mkdir(parents=True, exist_ok=True)
+ make_state_dir(str(state_dir))
# O_EXCL makes the sentinel an atomic lock — if two SessionStarts
# race past the exists() check above, only one creates it.
try:
@@ -857,7 +856,7 @@ def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None:
marker = state_dir / f".agentic_unavailable_notice_v{pv or 0}"
if marker.exists():
return None
- state_dir.mkdir(parents=True, exist_ok=True)
+ make_state_dir(str(state_dir))
# Write timestamp + Python version so the marker is self-documenting
# if a user goes looking. O_EXCL would be racier with no real win
# (two concurrent SessionStarts both showing the notice once is fine).
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 468d9e6d..05ac6658 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -39,7 +39,7 @@ except ImportError: # a Python built without TLS
import extensibility
import review_api
-from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401
+from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs, make_state_dir # noqa: F401
from session_state import load_state, with_locked_state
from gitutil import git_config_env, SAFE_GIT_CONFIG
@@ -735,7 +735,7 @@ def _read_review_model_cache(path, endpoint_key, now):
def _write_review_model_cache(path, endpoint_key, model, now):
tmp = None
try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
+ make_state_dir(os.path.dirname(path))
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".review_model.")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump({"endpoint": endpoint_key, "model": model, "at": now}, f)
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 3efe344e..09ed0076 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -88,7 +88,7 @@ from _base import ( # noqa: E402,F401
_USAGE_CONTEXT, _log_usage,
launcher_probe_metrics, state_dir as _resolve_state_dir,
write_hook_output as _write_hook_output, portable_output,
- llm_reviews_switched_off, agent_sdk_installed,
+ llm_reviews_switched_off, agent_sdk_installed, make_state_dir,
)
import extensibility # noqa: E402
from patterns import ( # noqa: E402,F401
@@ -422,7 +422,7 @@ def _no_credentials_notice(file_path, session_id):
pass
if not _git_toplevel(os.path.dirname(os.path.abspath(file_path))):
return None
- os.makedirs(os.path.dirname(marker), exist_ok=True)
+ make_state_dir(os.path.dirname(marker))
with open(marker, "w"):
pass
# In a session signed in to a Claude apps gateway the reviews do run,
@@ -2877,7 +2877,7 @@ def _maybe_bootstrap_agent_sdk_async():
return
except OSError:
pass
- os.makedirs(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE), exist_ok=True)
+ make_state_dir(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE))
# Touch the throttle BEFORE spawning so a burst of PostToolUse
# fires in the same second don't each spawn a subprocess.
open(_SDK_BOOTSTRAP_THROTTLE, "w").close()
diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py
index c8045532..330abd28 100644
--- a/plugins/security-guidance/hooks/session_state.py
+++ b/plugins/security-guidance/hooks/session_state.py
@@ -20,7 +20,7 @@ import re
import tempfile
from datetime import datetime
-from _base import debug_log, state_dir as _state_dir
+from _base import debug_log, make_state_dir, state_dir as _state_dir
def _state_key(session_id):
@@ -139,6 +139,18 @@ def _write_then_rename(state_file, state):
raise
+def _write_in_place(state_file, state):
+ """The fallback (Windows, or a folder that refuses the rename) writes the
+ state file itself. As with the rename, a link there is replaced, not
+ followed, and a new file is the user's only, as the temporary file is."""
+ if os.path.islink(state_file):
+ os.unlink(state_file)
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
+ fd = os.open(state_file, flags, 0o600)
+ with os.fdopen(fd, "w") as f:
+ json.dump(state, f)
+
+
def save_state(session_id, state):
"""Save the full state dict to file.
@@ -152,12 +164,11 @@ def save_state(session_id, state):
try:
state_dir = os.path.dirname(state_file)
if state_dir:
- os.makedirs(state_dir, exist_ok=True)
+ make_state_dir(state_dir)
if _RENAME_INTO_PLACE and _write_then_rename(state_file, state):
return
- with open(state_file, "w") as f:
- json.dump(state, f)
+ _write_in_place(state_file, state)
except (IOError, OSError) as e:
debug_log(f"Failed to save state file {state_file}: {e}")
@@ -181,7 +192,7 @@ def with_locked_state(session_id, callback):
state_dir = os.path.dirname(lock_file)
try:
- os.makedirs(state_dir, exist_ok=True)
+ make_state_dir(state_dir)
except OSError:
pass
diff --git a/plugins/security-guidance/tests/test_state_dir_mode.py b/plugins/security-guidance/tests/test_state_dir_mode.py
new file mode 100644
index 00000000..d55afaf9
--- /dev/null
+++ b/plugins/security-guidance/tests/test_state_dir_mode.py
@@ -0,0 +1,107 @@
+"""The state dir holds the reviewer's venv, review logs and session state. It
+is created, and kept, with access for its user alone, whatever the umask."""
+import os
+import stat
+import sys
+
+import pytest
+
+import _base
+import session_state
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes")
+
+
+@pytest.fixture
+def loose_umask():
+ old = os.umask(0o002)
+ yield
+ os.umask(old)
+
+
+def _mode(p):
+ return stat.S_IMODE(os.stat(p).st_mode)
+
+
+def test_new_state_dir_is_owner_only(tmp_path, monkeypatch, loose_umask):
+ d = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ session_state.save_state("s1", {"k": 1})
+ assert _mode(d) == 0o700
+
+
+def test_existing_default_state_dir_is_narrowed(tmp_path, monkeypatch, loose_umask):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False)
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ d = tmp_path / ".claude" / "security"
+ d.mkdir(parents=True)
+ os.chmod(d, 0o775)
+ _base.make_state_dir()
+ assert _mode(d) == 0o700
+
+
+def test_existing_folder_named_by_the_user_is_left_alone(tmp_path, monkeypatch):
+ d = tmp_path / "team"
+ d.mkdir()
+ os.chmod(d, 0o2775)
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ _base.make_state_dir()
+ assert _mode(d) == 0o2775
+
+
+def test_a_link_at_the_default_state_dir_is_left_alone(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False)
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ shared = tmp_path / "shared"
+ shared.mkdir()
+ os.chmod(shared, 0o775)
+ (tmp_path / ".claude").mkdir()
+ os.symlink(shared, tmp_path / ".claude" / "security")
+ _base.make_state_dir()
+ assert _mode(shared) == 0o775
+
+
+def test_other_folders_are_left_alone(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False)
+ logs = tmp_path / "logs"
+ logs.mkdir()
+ os.chmod(logs, 0o755)
+ _base.make_state_dir(str(logs))
+ assert _mode(logs) == 0o755
+
+
+def test_debug_log_in_the_working_directory_leaves_the_state_dir_alone(tmp_path, monkeypatch):
+ d = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ with pytest.raises(OSError):
+ _base.make_state_dir("")
+ assert not d.exists()
+
+
+@pytest.mark.parametrize("nofollow", [True, False])
+def test_in_place_save_replaces_a_symlink(tmp_path, monkeypatch, nofollow):
+ d = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ monkeypatch.setattr(session_state, "_RENAME_INTO_PLACE", False)
+ if not nofollow: # the Windows path: no O_NOFOLLOW
+ monkeypatch.delattr(os, "O_NOFOLLOW")
+ _base.make_state_dir()
+ target = tmp_path / "elsewhere.txt"
+ target.write_text("keep\n")
+ state_file = session_state.get_state_file("s1")
+ os.symlink(target, state_file)
+ session_state.save_state("s1", {"k": 1})
+ assert target.read_text() == "keep\n"
+ assert not os.path.islink(state_file)
+ assert session_state.load_state("s1").get("k") == 1
+
+
+def test_in_place_save_creates_an_owner_only_file(tmp_path, monkeypatch, loose_umask):
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.setattr(session_state, "_RENAME_INTO_PLACE", False)
+ session_state.save_state("s1", {"k": 1})
+ assert _mode(session_state.get_state_file("s1")) == 0o600
+ assert session_state.load_state("s1").get("k") == 1