summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-14 16:31:17 +0000
committerClaude <noreply@anthropic.com>2026-10-14 16:31:17 +0000
commitacc1870f4c4e2be8b3a27763cc6ad8a716e57e37 (patch)
tree86045d3f423066a43436666961d920bb2b8c9022 /plugins
parent641d925db5a662e72f8650cb1b7670a59dab1abc (diff)
security-guidance: keep the session state when a save is cut short
The state file was rewritten in place, so a hook killed during a save left a truncated file that the next hook read as an empty state: the turn baseline, the touched paths and the shown warnings were gone. Write a temporary file and rename it over the state file. Windows keeps writing in place for now: hooks have no state lock there, and a rename can be refused or make a concurrent read fail. A state file that cannot be decoded no longer stops the hook. The Stop metrics gain two keys, sent only when nonzero: state_resets (the state file was unreadable and the state started over) and state_overwrites (without a lock, a save replaced one made by another hook since the read). Refs #1944
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py7
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py7
-rw-r--r--plugins/security-guidance/hooks/session_state.py72
-rw-r--r--plugins/security-guidance/tests/test_state_file.py197
4 files changed, 277 insertions, 6 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index be839212..31f3105e 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -103,17 +103,22 @@ def consume_stop_state(session_id, clear=True):
"fire_count_expired": expired and state.get("stop_hook_fire_count", 0) > 0,
"previous_findings": [] if findings_expired else list(state.get("previous_findings", [])),
"reviewed_diff_hash": state.get("reviewed_diff_hash"),
+ # State lost or overwritten since the last Stop (session_state).
+ "state_resets": state.get("state_resets", 0),
+ "state_overwrites": state.get("state_overwrites", 0),
}
if clear:
state["touched_paths"] = []
state.pop("reviewed_diff_hash", None)
+ state.pop("state_resets", None)
+ state.pop("state_overwrites", None)
return snap
return with_locked_state(session_id, _snap) or {
"touched_paths": [], "baseline_sha": None, "head_at_capture": None,
"untracked_at_baseline": {},
"fire_count": 0, "fire_count_expired": False, "previous_findings": [],
- "reviewed_diff_hash": None,
+ "reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0,
}
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 580bb8a3..6863a811 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -2090,6 +2090,13 @@ def handle_stop_hook(input_data):
head_at_capture = snap["head_at_capture"]
untracked_at_baseline = snap.get("untracked_at_baseline") or {}
previous_findings = snap["previous_findings"]
+ # Only when it happened: state lost to an unreadable file, and saves that
+ # overwrote another hook's (possible only without locking). SubagentStop
+ # does not clear them, so it does not report them either.
+ if not is_subagent:
+ for _k in ("state_resets", "state_overwrites"):
+ if isinstance(snap.get(_k), int) and snap[_k] > 0:
+ _TAIL_METRICS[_k] = snap[_k]
# Sweep pattern-warning outcomes (pure local work; stop_hook_active is
# already guaranteed False here so no double-count guard needed).
diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py
index 8dbadfd2..c8045532 100644
--- a/plugins/security-guidance/hooks/session_state.py
+++ b/plugins/security-guidance/hooks/session_state.py
@@ -17,6 +17,7 @@ except ImportError:
import json
import os
import re
+import tempfile
from datetime import datetime
from _base import debug_log, state_dir as _state_dir
@@ -47,7 +48,7 @@ def get_lock_file(session_id):
def cleanup_old_state_files():
- """Remove state files and lock files older than 30 days."""
+ """Remove state files, lock files and leftover temporary files older than 30 days."""
try:
state_dir = _state_dir()
if not os.path.exists(state_dir):
@@ -58,7 +59,7 @@ def cleanup_old_state_files():
for filename in os.listdir(state_dir):
if filename.startswith("security_warnings_state_") and (
- filename.endswith(".json") or filename.endswith(".lock")
+ filename.endswith((".json", ".lock", ".tmp"))
):
file_path = os.path.join(state_dir, filename)
try:
@@ -96,25 +97,79 @@ def load_state(session_id):
if isinstance(data, dict):
data.setdefault("shown_warnings", [])
return data
- except (json.JSONDecodeError, IOError, KeyError, TypeError):
+ except FileNotFoundError:
+ return {"shown_warnings": []}
+ except (ValueError, IOError, KeyError, TypeError):
+ # ValueError: not JSON, or bytes that do not decode.
pass
- return {"shown_warnings": []}
+ # The file is there but cannot be used, so everything the session had
+ # recorded is gone. Leave a mark for the Stop hook to report: a flag, not
+ # a count, since an earlier mark is lost with the rest.
+ debug_log(f"State file {state_file} is unreadable, starting from an empty state")
+ return {"shown_warnings": [], "state_resets": 1}
+
+
+# Windows still writes the state file in place: a rename there is refused
+# while another process has the file open and can make a concurrent open fail,
+# and hooks run without a state lock on Windows (see with_locked_state).
+_RENAME_INTO_PLACE = os.name != "nt"
+
+
+def _write_then_rename(state_file, state):
+ """Write `state` to a temporary file and rename it over `state_file`.
+ Returns False, with nothing changed, when this directory does not allow
+ it; any other failure raises OSError and leaves the state file as it was."""
+ tmp = None
+ try:
+ fd, tmp = tempfile.mkstemp(
+ dir=os.path.dirname(state_file),
+ prefix=os.path.basename(state_file) + ".", suffix=".tmp")
+ with os.fdopen(fd, "w") as f:
+ json.dump(state, f)
+ os.replace(tmp, state_file)
+ return True
+ except BaseException as e:
+ if tmp:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ if isinstance(e, PermissionError):
+ return False
+ raise
def save_state(session_id, state):
- """Save the full state dict to file."""
+ """Save the full state dict to file.
+
+ The new contents go to a temporary file that is then renamed over the
+ state file, so a hook killed part-way through a save (a timeout, an
+ interrupt) leaves the previous state. Written in place it left a truncated
+ file, which load_state reads as an empty state: the turn baseline, touched
+ paths and shown warnings were lost.
+ """
state_file = get_state_file(session_id)
try:
state_dir = os.path.dirname(state_file)
if state_dir:
os.makedirs(state_dir, exist_ok=True)
+ if _RENAME_INTO_PLACE and _write_then_rename(state_file, state):
+ return
with open(state_file, "w") as f:
json.dump(state, f)
except (IOError, OSError) as e:
debug_log(f"Failed to save state file {state_file}: {e}")
+def _raw_state(state_file):
+ try:
+ with open(state_file, "rb") as f:
+ return f.read()
+ except OSError:
+ return None
+
+
def with_locked_state(session_id, callback):
"""
Execute callback with exclusive access to the state file.
@@ -132,8 +187,15 @@ def with_locked_state(session_id, callback):
if fcntl is None:
# No file locking available (Windows) — run without locking
+ state_file = get_state_file(session_id)
+ before = _raw_state(state_file)
state = load_state(session_id)
result = callback(state)
+ if _raw_state(state_file) != before:
+ # Another hook changed the state after it was read here, and this
+ # save is about to drop that change. Count how often it happens;
+ # the Stop hook reports the count.
+ state["state_overwrites"] = state.get("state_overwrites", 0) + 1
save_state(session_id, state)
return result
diff --git a/plugins/security-guidance/tests/test_state_file.py b/plugins/security-guidance/tests/test_state_file.py
new file mode 100644
index 00000000..0d3a56b0
--- /dev/null
+++ b/plugins/security-guidance/tests/test_state_file.py
@@ -0,0 +1,197 @@
+import json
+import os
+import signal
+import subprocess
+import sys
+import time
+
+import pytest
+
+from conftest import HOOKS_DIR, make_repo, metrics_of, run_hook, stop_payload, ups_payload
+
+import session_state as ss
+
+
+@pytest.fixture
+def state_dir(tmp_path, monkeypatch):
+ d = tmp_path / "state"
+ d.mkdir()
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ monkeypatch.delenv("CLAUDE_CODE_REMOTE_SESSION_ID", raising=False)
+ # Keep the legacy lock-file sweep and the debug log out of the real home.
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(ss, "debug_log", lambda _msg: None)
+ return d
+
+
+def _seed(session_id="s1"):
+ ss.with_locked_state(session_id, lambda st: st.update(
+ baseline_sha="a" * 40, touched_paths=["x.py"],
+ untracked_at_baseline={f"dir/file_{i:05d}.py": i for i in range(1500)}))
+
+
+def _on_disk(state_dir, session_id="s1"):
+ return json.loads((state_dir / f"security_warnings_state_{session_id}.json").read_text())
+
+
+def _leftovers(state_dir):
+ return sorted(p.name for p in state_dir.iterdir() if p.name.endswith(".tmp"))
+
+
+_MARK_ONE = (
+ "import sys; sys.path.insert(0, sys.argv[1]); import session_state as s; "
+ "s.with_locked_state('s1', lambda st: st['shown_warnings'].append(sys.argv[2]))"
+)
+
+# A save that dies half-way through writing, as a hook killed on timeout does.
+_KILLED_MID_SAVE = """
+import json, os, signal, sys
+sys.path.insert(0, sys.argv[1])
+import session_state as s
+def dump(obj, f, **kw):
+ data = json.dumps(obj)
+ f.write(data[:len(data) // 2]); f.flush()
+ os.kill(os.getpid(), signal.SIGKILL)
+s.json.dump = dump
+s.with_locked_state('s1', lambda st: st['touched_paths'].append('y.py'))
+"""
+
+
+@pytest.mark.skipif(os.name == "nt", reason="rename into place is not used on Windows")
+class TestSaveIsAtomic:
+ def test_a_save_killed_part_way_keeps_the_previous_state(self, state_dir):
+ _seed()
+ r = subprocess.run([sys.executable, "-c", _KILLED_MID_SAVE, str(HOOKS_DIR)],
+ env=dict(os.environ))
+ assert r.returncode == -signal.SIGKILL
+ state = ss.load_state("s1")
+ assert state["baseline_sha"] == "a" * 40
+ assert state["touched_paths"] == ["x.py"]
+ assert len(state["untracked_at_baseline"]) == 1500
+ assert "state_resets" not in state
+
+ def test_no_temporary_file_is_left_behind(self, state_dir):
+ _seed()
+ ss.with_locked_state("s1", lambda st: st["touched_paths"].append("y.py"))
+ assert _on_disk(state_dir)["touched_paths"] == ["x.py", "y.py"]
+ assert _leftovers(state_dir) == []
+
+ def test_state_that_cannot_be_written_leaves_the_file_alone(self, state_dir):
+ _seed()
+ with pytest.raises(TypeError):
+ ss.save_state("s1", {"shown_warnings": [], "bad": object()})
+ assert _on_disk(state_dir)["baseline_sha"] == "a" * 40
+ assert _leftovers(state_dir) == []
+
+ def test_writes_in_place_where_the_directory_refuses_a_rename(self, state_dir, monkeypatch):
+ _seed()
+
+ def refuse(_src, _dst):
+ raise PermissionError("rename refused")
+ monkeypatch.setattr(ss.os, "replace", refuse)
+ ss.with_locked_state("s1", lambda st: st["touched_paths"].append("y.py"))
+ assert _on_disk(state_dir)["touched_paths"] == ["x.py", "y.py"]
+ assert _leftovers(state_dir) == []
+
+ def test_a_full_disk_leaves_the_previous_state(self, state_dir, monkeypatch):
+ _seed()
+
+ def full(_obj, f, **_kw):
+ f.write('{"shown_warn')
+ raise OSError(28, "No space left on device")
+ monkeypatch.setattr(ss.json, "dump", full)
+ ss.save_state("s1", {"shown_warnings": []})
+ assert _on_disk(state_dir)["baseline_sha"] == "a" * 40
+ assert _leftovers(state_dir) == []
+
+ def test_in_place_where_rename_is_not_used(self, state_dir, monkeypatch):
+ monkeypatch.setattr(ss, "_RENAME_INTO_PLACE", False)
+ monkeypatch.setattr(ss.os, "replace", lambda *_a: pytest.fail("renamed"))
+ _seed()
+ assert _on_disk(state_dir)["touched_paths"] == ["x.py"]
+
+
+@pytest.mark.skipif(ss.fcntl is None, reason="needs file locking")
+def test_concurrent_writers_all_land(state_dir):
+ """Eight hooks marking one warning each at the same moment keep all eight."""
+ for _round in range(5):
+ (state_dir / "security_warnings_state_s1.json").unlink(missing_ok=True)
+ procs = [subprocess.Popen([sys.executable, "-c", _MARK_ONE, str(HOOKS_DIR), f"k{i}"],
+ env=dict(os.environ)) for i in range(8)]
+ assert [p.wait() for p in procs] == [0] * 8
+ assert sorted(_on_disk(state_dir)["shown_warnings"]) == [f"k{i}" for i in range(8)]
+ assert _leftovers(state_dir) == []
+
+
+class TestStateLossIsCounted:
+ def test_missing_file_is_a_fresh_state(self, state_dir):
+ assert ss.load_state("s1") == {"shown_warnings": []}
+
+ @pytest.mark.parametrize("content", [
+ b"", b'{"baseline_sha": "abc", "touched_pa', b"42", b'{"baseline_sha": "\xff\xfe"}'])
+ def test_unreadable_file_is_counted(self, state_dir, content):
+ (state_dir / "security_warnings_state_s1.json").write_bytes(content)
+ assert ss.load_state("s1") == {"shown_warnings": [], "state_resets": 1}
+
+ def test_overwriting_another_hooks_save_is_counted_without_locking(
+ self, state_dir, monkeypatch):
+ monkeypatch.setattr(ss, "fcntl", None)
+ _seed()
+ assert "state_overwrites" not in _on_disk(state_dir)
+
+ def slow_hook(state):
+ # Another hook saves while this one is between its read and write.
+ time.sleep(0.01)
+ ss.save_state("s1", {**state, "touched_paths": ["x.py", "other.py"]})
+ state["shown_warnings"].append("k")
+ ss.with_locked_state("s1", slow_hook)
+ after = _on_disk(state_dir)
+ assert after["state_overwrites"] == 1
+ assert after["touched_paths"] == ["x.py"] # the other hook's save was lost
+
+ def test_a_concurrent_save_of_the_same_state_is_not_counted(self, state_dir, monkeypatch):
+ monkeypatch.setattr(ss, "fcntl", None)
+ _seed()
+
+ def reader(state):
+ ss.save_state("s1", dict(state)) # another hook that only read
+ return state["baseline_sha"]
+ assert ss.with_locked_state("s1", reader) == "a" * 40
+ assert "state_overwrites" not in _on_disk(state_dir)
+
+ def test_stop_reports_the_counts_once(self, tmp_path, hook_env):
+ repo = make_repo(tmp_path / "repo")
+ hook_env = {k: v for k, v in hook_env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"}
+ state_file = os.path.join(hook_env["SECURITY_WARNINGS_STATE_DIR"],
+ "security_warnings_state_s1.json")
+ run_hook(ups_payload(repo), hook_env)
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(stdout)
+ assert "state_resets" not in m and "state_overwrites" not in m
+
+ with open(state_file, "w") as f:
+ f.write('{"baseline_sha": "abc", "touched_pa')
+ run_hook(ups_payload(repo), hook_env)
+ with open(state_file) as f:
+ state = json.load(f)
+ state["state_overwrites"] = 3
+ with open(state_file, "w") as f:
+ json.dump(state, f)
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(stdout)
+ assert (m["state_resets"], m["state_overwrites"]) == (1, 3)
+
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(stdout)
+ assert "state_resets" not in m and "state_overwrites" not in m
+
+
+def test_cleanup_removes_old_temporary_files(state_dir):
+ old = state_dir / "security_warnings_state_s1.json.a1b2c3.tmp"
+ new = state_dir / "security_warnings_state_s2.json.a1b2c3.tmp"
+ old.write_text("{}")
+ new.write_text("{}")
+ long_ago = time.time() - 31 * 24 * 60 * 60
+ os.utime(old, (long_ago, long_ago))
+ ss.cleanup_old_state_files()
+ assert not old.exists() and new.exists()