summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/session_state.py
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-06 00:54:48 +0000
committerClaude <noreply@anthropic.com>2026-11-06 00:54:48 +0000
commit7aba3deae3ff17d032c37e07d2929d1426b34278 (patch)
tree9c482f9acda1599bd2f9bed95a6a46b75e634e80 /plugins/security-guidance/hooks/session_state.py
parent5472f5f56e0070feeeb464318b316714fe3e9105 (diff)
parentb8331dd69ab3e132bbf8cd6e89b5d8c1747e21b1 (diff)
Merge remote-tracking branch 'origin/main' into add-plugin/xcodeadd-plugin/xcode
Diffstat (limited to 'plugins/security-guidance/hooks/session_state.py')
-rw-r--r--plugins/security-guidance/hooks/session_state.py93
1 files changed, 83 insertions, 10 deletions
diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py
index 8dbadfd2..330abd28 100644
--- a/plugins/security-guidance/hooks/session_state.py
+++ b/plugins/security-guidance/hooks/session_state.py
@@ -17,9 +17,10 @@ except ImportError:
import json
import os
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):
@@ -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,90 @@ 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 _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."""
+ """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)
+ make_state_dir(state_dir)
- with open(state_file, "w") as f:
- json.dump(state, f)
+ if _RENAME_INTO_PLACE and _write_then_rename(state_file, state):
+ return
+ _write_in_place(state_file, state)
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.
@@ -126,14 +192,21 @@ 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
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