damage-control-dev 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- damage_control/__init__.py +9 -0
- damage_control/__main__.py +7 -0
- damage_control/adapter.py +179 -0
- damage_control/audit.py +432 -0
- damage_control/breakglass.py +155 -0
- damage_control/claude_code.py +148 -0
- damage_control/cli.py +173 -0
- damage_control/engine.py +10656 -0
- damage_control/groups.py +114 -0
- damage_control/harness_config.py +205 -0
- damage_control/hook.py +54 -0
- damage_control/install.py +618 -0
- damage_control/packs.py +219 -0
- damage_control/policy.py +323 -0
- damage_control/profile.py +177 -0
- damage_control/rules/aws.json +85 -0
- damage_control/rules/aws.yaml +76 -0
- damage_control/rules/cloud-hosting.json +162 -0
- damage_control/rules/cloud-hosting.yaml +163 -0
- damage_control/rules/containers.json +67 -0
- damage_control/rules/containers.yaml +69 -0
- damage_control/rules/control-plane.json +7 -0
- damage_control/rules/control-plane.yaml +21 -0
- damage_control/rules/core.json +332 -0
- damage_control/rules/core.yaml +441 -0
- damage_control/rules/databases.json +117 -0
- damage_control/rules/databases.yaml +123 -0
- damage_control/rules/firebase.json +34 -0
- damage_control/rules/firebase.yaml +30 -0
- damage_control/rules/gcp.json +60 -0
- damage_control/rules/gcp.yaml +57 -0
- damage_control/rules/git.json +119 -0
- damage_control/rules/git.yaml +120 -0
- damage_control/rules/infrastructure.json +69 -0
- damage_control/rules/infrastructure.yaml +66 -0
- damage_control/rules/mcp-tools.json +11 -0
- damage_control/rules/mcp-tools.yaml +47 -0
- damage_control/rules/outbound.json +40 -0
- damage_control/rules/outbound.yaml +58 -0
- damage_control/rules/payloads.json +120 -0
- damage_control/rules/payloads.yaml +155 -0
- damage_control/rules/publish.json +46 -0
- damage_control/rules/publish.yaml +46 -0
- damage_control/rules/registry.json +10 -0
- damage_control/rules/registry.yaml +11 -0
- damage_control/rules/remote.json +31 -0
- damage_control/rules/remote.yaml +53 -0
- damage_control/rules/tmux.json +17 -0
- damage_control/rules/tmux.yaml +16 -0
- damage_control/ruleset.py +94 -0
- damage_control/tooldefs/aws.json +140 -0
- damage_control/tooldefs/aws.yaml +119 -0
- damage_control/tooldefs/docker.json +146 -0
- damage_control/tooldefs/docker.yaml +123 -0
- damage_control/tooldefs/gcp.json +186 -0
- damage_control/tooldefs/gcp.yaml +158 -0
- damage_control/tooldefs/gh.json +172 -0
- damage_control/tooldefs/gh.yaml +145 -0
- damage_control/tooldefs/git.json +166 -0
- damage_control/tooldefs/git.yaml +143 -0
- damage_control/tooldefs/kubectl.json +101 -0
- damage_control/tooldefs/kubectl.yaml +85 -0
- damage_control/tooldefs/npm.json +77 -0
- damage_control/tooldefs/npm.yaml +65 -0
- damage_control/tooldefs/terraform.json +68 -0
- damage_control/tooldefs/terraform.yaml +57 -0
- damage_control/tooldefs/uv.json +112 -0
- damage_control/tooldefs/uv.yaml +97 -0
- damage_control_dev-0.1.0.dist-info/METADATA +15 -0
- damage_control_dev-0.1.0.dist-info/RECORD +74 -0
- damage_control_dev-0.1.0.dist-info/WHEEL +4 -0
- damage_control_dev-0.1.0.dist-info/entry_points.txt +2 -0
- damage_control_dev-0.1.0.dist-info/licenses/LICENSE +201 -0
- damage_control_dev-0.1.0.dist-info/licenses/NOTICE +4 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Damage control for AI coding agents.
|
|
2
|
+
|
|
3
|
+
This module stays import-free on purpose: ``python -I -m damage_control.hook`` imports
|
|
4
|
+
the package before it runs a line of ``hook.py``, and an exception raised here would
|
|
5
|
+
escape the hook's fail-closed wrapper (a Python crash exits 1, which Claude Code treats
|
|
6
|
+
as non-blocking).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Claude Code adapter (#1209 M3/M4): hook payload -> ``ToolCall``/``Context``, ``Verdict`` -> exit code.
|
|
2
|
+
|
|
3
|
+
The five PreToolUse hooks differ only in WHICH tools they handle and how their rule
|
|
4
|
+
sources load; every one is ``parse -> decide -> render``, and this file holds the parse
|
|
5
|
+
and render halves (``policy.Guard`` is the decide half) plus ``run_hook``, the entry
|
|
6
|
+
``hook.py`` calls. A hook kind declares a tool table ``{tool_name: (kind, (payload
|
|
7
|
+
fields...))}``.
|
|
8
|
+
|
|
9
|
+
``render`` is the only place a decision becomes an exit code, a stderr line, an audit row
|
|
10
|
+
and a notification, so a verdict that reaches it can only be rendered one way.
|
|
11
|
+
|
|
12
|
+
Standard library only.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import types
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
21
|
+
|
|
22
|
+
from damage_control import audit, engine
|
|
23
|
+
from damage_control.policy import BYPASS, Context, Guard, ToolCall
|
|
24
|
+
from damage_control.profile import load_profile
|
|
25
|
+
|
|
26
|
+
# ``permission_mode`` values that mean the human opted out of ask-escalation friction:
|
|
27
|
+
# - "bypassPermissions" -> --dangerously-skip-permissions
|
|
28
|
+
# - "auto" -> autonomous /loop or similar auto mode
|
|
29
|
+
# Hard blocks still fire either way; an ``ask`` becomes an allow — EXCEPT an unverifiable one.
|
|
30
|
+
BYPASS_PERMISSION_MODES = frozenset({"bypassPermissions", "auto"})
|
|
31
|
+
|
|
32
|
+
# stdout of an ask: Claude Code's PreToolUse permission-decision envelope.
|
|
33
|
+
_HOOK_EVENT = "PreToolUse"
|
|
34
|
+
|
|
35
|
+
_Tools = Optional[Dict[str, Tuple[str, Tuple[str, ...]]]]
|
|
36
|
+
|
|
37
|
+
# hook kind -> (tool table, whether it judges shell commands and so loads the tooldefs).
|
|
38
|
+
# ``None`` for a table means every tool is an ``mcp`` call; the decision itself lives in
|
|
39
|
+
# ``policy.Guard``.
|
|
40
|
+
HOOK_KINDS: Dict[str, Tuple[_Tools, bool]] = {
|
|
41
|
+
# Bash and PowerShell calls: judge the command line.
|
|
42
|
+
"bash": ({"Bash": ("shell", ("command",)), "PowerShell": ("shell", ("command",))}, True),
|
|
43
|
+
# Edit and NotebookEdit calls: judge the target path. NotebookEdit writes files exactly
|
|
44
|
+
# like Edit but names its target ``notebook_path``: an operation refused via Edit must
|
|
45
|
+
# not be permitted via NotebookEdit (#923).
|
|
46
|
+
"edit": ({"Edit": ("edit", ("file_path", "notebook_path")),
|
|
47
|
+
"NotebookEdit": ("edit", ("file_path", "notebook_path"))}, False),
|
|
48
|
+
"write": ({"Write": ("write", ("file_path",))}, False),
|
|
49
|
+
# Read, Grep and Glob: judge the path they read or list. ``Glob`` only reveals filenames,
|
|
50
|
+
# but a zero-access directory is still off-limits.
|
|
51
|
+
"read": ({"Read": ("read", ("file_path",)), "Grep": ("read", ("path",)),
|
|
52
|
+
"Glob": ("read", ("path",))}, False),
|
|
53
|
+
"mcp": (None, True),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class HookUsageError(ValueError):
|
|
58
|
+
"""The hook was invoked with arguments it does not understand. Blocks, like any hook failure."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def parse_args(argv: List[str]) -> Tuple[str, Optional[str]]:
|
|
62
|
+
"""``(hook kind, profile manifest path | None)`` from the hook's command-line arguments."""
|
|
63
|
+
args = list(argv)
|
|
64
|
+
profile: Optional[str] = None
|
|
65
|
+
if "--profile" in args:
|
|
66
|
+
i = args.index("--profile")
|
|
67
|
+
if i + 1 >= len(args):
|
|
68
|
+
raise HookUsageError("--profile needs a path")
|
|
69
|
+
profile = args[i + 1]
|
|
70
|
+
del args[i:i + 2]
|
|
71
|
+
if len(args) != 1 or args[0] not in HOOK_KINDS:
|
|
72
|
+
raise HookUsageError(f"usage: hook {{{'|'.join(HOOK_KINDS)}}} [--profile PATH]; got {argv!r}")
|
|
73
|
+
return args[0], profile
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def hook_namespace() -> Any:
|
|
77
|
+
"""What ``Guard`` and ``render`` reach engine functions and audit writers through."""
|
|
78
|
+
names = {n: getattr(audit, n) for n in ("log_allowed", "log_asked", "log_blocked", "log_disabled", "log_escape")}
|
|
79
|
+
return types.SimpleNamespace(**{**vars(engine), **names})
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def parse_payload(payload: Dict[str, Any], tools: Optional[Dict[str, Tuple[str, Tuple[str, ...]]]],
|
|
83
|
+
engine: Any) -> Tuple[Any, Any]:
|
|
84
|
+
"""``(ToolCall | None, Context)``; no call means this hook has nothing to judge.
|
|
85
|
+
|
|
86
|
+
``tools`` maps a tool name to ``(kind, fields)``: for ``shell`` the field names the
|
|
87
|
+
command, for read/write/edit the target path (the first non-empty field wins). ``None``
|
|
88
|
+
means every tool is an ``mcp`` call.
|
|
89
|
+
"""
|
|
90
|
+
tool_call, context, bypass = ToolCall, Context, BYPASS
|
|
91
|
+
# Session attribution for audit rows (#940): hand the parsed payload to the audit writers
|
|
92
|
+
# so every log_* call carries the conversation id.
|
|
93
|
+
audit.HOOK_INPUT = payload
|
|
94
|
+
|
|
95
|
+
tool_name = payload.get("tool_name", "")
|
|
96
|
+
tool_input = payload.get("tool_input", {})
|
|
97
|
+
ctx = context(
|
|
98
|
+
mode=bypass if payload.get("permission_mode", "") in BYPASS_PERMISSION_MODES else "default",
|
|
99
|
+
unattended=engine.is_unattended(),
|
|
100
|
+
)
|
|
101
|
+
if tools is None:
|
|
102
|
+
return tool_call("mcp", tool_name, tool_input=tool_input or {}), ctx
|
|
103
|
+
if tool_name not in tools:
|
|
104
|
+
return None, ctx
|
|
105
|
+
kind, fields = tools[tool_name]
|
|
106
|
+
value = next((tool_input.get(f, "") for f in fields if tool_input.get(f, "")), "")
|
|
107
|
+
if not value:
|
|
108
|
+
return None, ctx
|
|
109
|
+
if kind == "shell":
|
|
110
|
+
return tool_call(kind, tool_name, command=value, cwd=payload.get("cwd")), ctx
|
|
111
|
+
return tool_call(kind, tool_name, paths=(value,)), ctx
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def notify_unattended_block(engine: Any, subject: str, reason: str, rule_id: Optional[str]) -> None:
|
|
115
|
+
"""Fire-and-forget: tell the owner an unattended action was blocked.
|
|
116
|
+
|
|
117
|
+
Runs the profile's notifier argv, detached and non-blocking so it never sits on the
|
|
118
|
+
hook's hot path, with the event as one JSON object on its stdin:
|
|
119
|
+
``{"event": "unattended_block", "reason": ..., "rule_id": ..., "command": ...}``
|
|
120
|
+
(``command`` is truncated to 500 characters). Failures are swallowed (the block has
|
|
121
|
+
already fired and is audit-logged regardless). A hook never imports the host, hence the
|
|
122
|
+
subprocess.
|
|
123
|
+
"""
|
|
124
|
+
argv = engine.PROFILE.unattended_block_notifier
|
|
125
|
+
if not argv:
|
|
126
|
+
return
|
|
127
|
+
event = {"event": "unattended_block", "reason": reason or "", "rule_id": rule_id or "", "command": subject[:500]}
|
|
128
|
+
try:
|
|
129
|
+
child = subprocess.Popen(
|
|
130
|
+
list(argv), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.PIPE,
|
|
131
|
+
start_new_session=True,
|
|
132
|
+
)
|
|
133
|
+
child.stdin.write(json.dumps(event).encode())
|
|
134
|
+
child.stdin.close()
|
|
135
|
+
except Exception:
|
|
136
|
+
pass
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def render(verdict: Any, engine: Any) -> None:
|
|
140
|
+
"""Carry out ``verdict`` and exit: audit row, notification, stderr, then the exit code / ask envelope."""
|
|
141
|
+
if verdict.audit:
|
|
142
|
+
event, args, kwargs = verdict.audit
|
|
143
|
+
# An audit-log failure never changes the decision (#1108).
|
|
144
|
+
engine.audit_best_effort(getattr(engine, f"log_{event}"))(*args, **kwargs)
|
|
145
|
+
if verdict.notify:
|
|
146
|
+
notify_unattended_block(engine, *verdict.notify)
|
|
147
|
+
for line in verdict.stderr:
|
|
148
|
+
print(line, file=sys.stderr)
|
|
149
|
+
if verdict.decision == "block":
|
|
150
|
+
sys.exit(2)
|
|
151
|
+
if verdict.decision == "ask":
|
|
152
|
+
print(json.dumps({"hookSpecificOutput": {
|
|
153
|
+
"hookEventName": _HOOK_EVENT,
|
|
154
|
+
"permissionDecision": "ask",
|
|
155
|
+
"permissionDecisionReason": verdict.reason,
|
|
156
|
+
}}))
|
|
157
|
+
sys.exit(0)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def run_hook(argv: List[str]) -> None:
|
|
161
|
+
"""The hook entry: parse the arguments, install the profile, judge one payload, exit.
|
|
162
|
+
|
|
163
|
+
Everything runs under ``run_hook_guarded``, so any failure here (a bad argument, an
|
|
164
|
+
unreadable profile, a crashed rule load) is a blocking exit 2, never Python's own exit 1.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def main() -> None:
|
|
168
|
+
kind, profile_path = parse_args(argv)
|
|
169
|
+
if profile_path:
|
|
170
|
+
engine.install_profile(load_profile(Path(profile_path)))
|
|
171
|
+
namespace = hook_namespace()
|
|
172
|
+
tools, tooldefs = HOOK_KINDS[kind]
|
|
173
|
+
guard = Guard(namespace.load_effective_config(tooldefs), namespace)
|
|
174
|
+
call, ctx = parse_payload(namespace.read_hook_input(), tools, namespace)
|
|
175
|
+
if call is None:
|
|
176
|
+
sys.exit(0)
|
|
177
|
+
render(guard.decide(call, ctx), namespace)
|
|
178
|
+
|
|
179
|
+
engine.run_hook_guarded(main)
|
damage_control/audit.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Damage Control Audit Logger
|
|
4
|
+
===========================
|
|
5
|
+
Logs all security decisions (blocked, asked, allowed) to JSONL files for analysis.
|
|
6
|
+
|
|
7
|
+
Storage: <config home>/<profile.audit.log_dir>/YYYY-MM-DD.jsonl (the config home and the
|
|
8
|
+
host's attribution env vars come from the profile: ``configure(profile)``).
|
|
9
|
+
Format: One JSON object per line (JSONL)
|
|
10
|
+
|
|
11
|
+
Fields:
|
|
12
|
+
- timestamp: ISO 8601 timestamp
|
|
13
|
+
- session_id: host session name (profile env override → tmux pane → host session records)
|
|
14
|
+
- conversation_id: Claude conversation UUID (from the hook stdin payload)
|
|
15
|
+
- agent_id: Agent identifier (if in parallel execution)
|
|
16
|
+
- tool: Tool name (Bash, Edit, Write)
|
|
17
|
+
- command: Command/path that was checked
|
|
18
|
+
- decision: "blocked", "asked", "allowed"
|
|
19
|
+
- blocked_by: Pattern/rule that triggered block (if blocked)
|
|
20
|
+
- user_approved: Boolean (if asked pattern)
|
|
21
|
+
- pattern_matched: Regex pattern that matched
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import subprocess
|
|
27
|
+
from datetime import datetime
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Optional
|
|
30
|
+
|
|
31
|
+
# The profile's audit field plus the config home it resolves against. ``configure`` is
|
|
32
|
+
# called by ``engine.install_profile``; until then the generic defaults apply.
|
|
33
|
+
_AUDIT_LOG_DIR = "logs/damage-control"
|
|
34
|
+
_SESSION_ENV = ""
|
|
35
|
+
_AGENT_ENV = ""
|
|
36
|
+
_SESSIONS_DIR = ""
|
|
37
|
+
_CONFIG_DIR = "~/.damage-control"
|
|
38
|
+
_CONFIG_DIR_ENV = "DAMAGE_CONTROL_HOME"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def configure(profile) -> None:
|
|
42
|
+
"""Point attribution and storage at ``profile`` (its config home and ``audit`` field)."""
|
|
43
|
+
global _AUDIT_LOG_DIR, _SESSION_ENV, _AGENT_ENV, _SESSIONS_DIR, _CONFIG_DIR, _CONFIG_DIR_ENV
|
|
44
|
+
_AUDIT_LOG_DIR = profile.audit.log_dir
|
|
45
|
+
_SESSION_ENV = profile.audit.session_env
|
|
46
|
+
_AGENT_ENV = profile.audit.agent_env
|
|
47
|
+
_SESSIONS_DIR = profile.audit.sessions_dir
|
|
48
|
+
_CONFIG_DIR = profile.config_dir
|
|
49
|
+
_CONFIG_DIR_ENV = profile.config_dir_env
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _config_home() -> Path:
|
|
53
|
+
default = os.path.expanduser(_CONFIG_DIR)
|
|
54
|
+
return Path(os.environ.get(_CONFIG_DIR_ENV, default) if _CONFIG_DIR_ENV else default)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _safe_cwd() -> str:
|
|
58
|
+
"""Standalone mirror of ``safety._core.safe_cwd`` (#1238) — never raises.
|
|
59
|
+
|
|
60
|
+
This module cannot import the engine (hooks run as isolated scripts), and a
|
|
61
|
+
dead cwd must not crash the audit write on the hook hot path.
|
|
62
|
+
"""
|
|
63
|
+
pwd = os.environ.get("PWD")
|
|
64
|
+
if pwd:
|
|
65
|
+
return pwd
|
|
66
|
+
try:
|
|
67
|
+
return os.getcwd()
|
|
68
|
+
except OSError:
|
|
69
|
+
return os.path.expanduser("~") or "/"
|
|
70
|
+
|
|
71
|
+
# The hook's parsed stdin payload. Each damage-control hook assigns this right
|
|
72
|
+
# after ``json.load(sys.stdin)`` so every log_* call in that process carries
|
|
73
|
+
# attribution without threading a kwarg through every call site. Claude Code
|
|
74
|
+
# puts the conversation UUID in the payload's ``session_id`` field — the
|
|
75
|
+
# harness's recorded identity, not a scrape.
|
|
76
|
+
HOOK_INPUT: dict = {}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_log_dir() -> Path:
|
|
80
|
+
"""Get or create the audit log directory."""
|
|
81
|
+
log_dir = _config_home() / _AUDIT_LOG_DIR
|
|
82
|
+
log_dir.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
return log_dir
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def get_log_file() -> Path:
|
|
87
|
+
"""Get today's log file path."""
|
|
88
|
+
log_dir = get_log_dir()
|
|
89
|
+
today = datetime.now().strftime("%Y-%m-%d")
|
|
90
|
+
return log_dir / f"{today}.jsonl"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _conversation_id() -> Optional[str]:
|
|
94
|
+
"""Claude's conversation UUID for this hook invocation, or None.
|
|
95
|
+
|
|
96
|
+
Comes from the hook stdin payload (``session_id`` there is the
|
|
97
|
+
conversation id).
|
|
98
|
+
"""
|
|
99
|
+
cid = HOOK_INPUT.get("session_id") if isinstance(HOOK_INPUT, dict) else None
|
|
100
|
+
return cid if isinstance(cid, str) and cid else None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _hook_field(name: str) -> Optional[str]:
|
|
104
|
+
"""A string field of the hook stdin payload, or None."""
|
|
105
|
+
value = HOOK_INPUT.get(name) if isinstance(HOOK_INPUT, dict) else None
|
|
106
|
+
return value if isinstance(value, str) and value else None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _tmux_session_name() -> Optional[str]:
|
|
110
|
+
"""The tmux session this hook process runs inside, or None.
|
|
111
|
+
|
|
112
|
+
The hook inherits ``TMUX``/``TMUX_PANE`` from the pane's shell, so asking
|
|
113
|
+
tmux for ``#S`` names the session directly. Never raises; a couple-second timeout bounds the
|
|
114
|
+
worst case.
|
|
115
|
+
"""
|
|
116
|
+
if not os.environ.get("TMUX"):
|
|
117
|
+
return None
|
|
118
|
+
cmd = ["tmux", "display-message", "-p", "#S"]
|
|
119
|
+
pane = os.environ.get("TMUX_PANE")
|
|
120
|
+
if pane:
|
|
121
|
+
cmd[2:2] = ["-t", pane]
|
|
122
|
+
try:
|
|
123
|
+
result = subprocess.run(
|
|
124
|
+
cmd, capture_output=True, text=True, timeout=2, check=False,
|
|
125
|
+
)
|
|
126
|
+
except Exception:
|
|
127
|
+
return None
|
|
128
|
+
name = result.stdout.strip() if result.returncode == 0 else ""
|
|
129
|
+
return name or None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _sessions_dir() -> Optional[Path]:
|
|
133
|
+
"""The host's session-record root (``profile.audit.sessions_dir``), or None if it keeps none."""
|
|
134
|
+
return _config_home() / _SESSIONS_DIR if _SESSIONS_DIR else None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _session_from_metadata(conversation_id: str) -> Optional[str]:
|
|
138
|
+
"""Resolve a session name by scanning the host's recorded launch metadata.
|
|
139
|
+
|
|
140
|
+
``<sessions dir>/<name>/metadata.json`` carries the
|
|
141
|
+
``conversation_ids`` chain; the entry containing this conversation id names
|
|
142
|
+
the session. Best-effort — corrupt/missing records are skipped.
|
|
143
|
+
"""
|
|
144
|
+
root = _sessions_dir()
|
|
145
|
+
if root is None:
|
|
146
|
+
return None
|
|
147
|
+
try:
|
|
148
|
+
entries = list(root.iterdir())
|
|
149
|
+
except OSError:
|
|
150
|
+
return None
|
|
151
|
+
for entry in entries:
|
|
152
|
+
meta_file = entry / "metadata.json"
|
|
153
|
+
try:
|
|
154
|
+
metadata = json.loads(meta_file.read_text())
|
|
155
|
+
except (OSError, ValueError):
|
|
156
|
+
continue
|
|
157
|
+
if not isinstance(metadata, dict):
|
|
158
|
+
continue
|
|
159
|
+
chain = metadata.get("conversation_ids") or []
|
|
160
|
+
if isinstance(chain, list) and conversation_id in chain:
|
|
161
|
+
return entry.name
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def get_session_context() -> dict:
|
|
166
|
+
"""Session attribution for an audit row (#940 prerequisite).
|
|
167
|
+
|
|
168
|
+
``session_id`` is the host's session NAME; ``conversation_id`` is the
|
|
169
|
+
Claude conversation UUID from the hook payload. Resolution order for the
|
|
170
|
+
name: explicit env override → tmux (the pane the hook runs in) → #871
|
|
171
|
+
metadata scan by conversation id → ``"unknown"``.
|
|
172
|
+
|
|
173
|
+
FAIL-OPEN by design: attribution must never block an action or crash the
|
|
174
|
+
hook, so every probe swallows its own failures and the worst outcome is
|
|
175
|
+
the pre-#940 row shape ("unknown").
|
|
176
|
+
"""
|
|
177
|
+
conversation_id = None
|
|
178
|
+
session = (os.environ.get(_SESSION_ENV) if _SESSION_ENV else None) or None
|
|
179
|
+
try:
|
|
180
|
+
conversation_id = _conversation_id()
|
|
181
|
+
if not session:
|
|
182
|
+
session = _tmux_session_name()
|
|
183
|
+
if not session and conversation_id:
|
|
184
|
+
session = _session_from_metadata(conversation_id)
|
|
185
|
+
except Exception:
|
|
186
|
+
pass
|
|
187
|
+
return {
|
|
188
|
+
"session_id": session or "unknown",
|
|
189
|
+
"conversation_id": conversation_id,
|
|
190
|
+
"agent_id": os.environ.get(_AGENT_ENV, "main") if _AGENT_ENV else "main",
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def log_entry(
|
|
195
|
+
tool: str,
|
|
196
|
+
command: str,
|
|
197
|
+
decision: str,
|
|
198
|
+
blocked_by: Optional[str] = None,
|
|
199
|
+
user_approved: Optional[bool] = None,
|
|
200
|
+
pattern_matched: Optional[str] = None,
|
|
201
|
+
rule_id: Optional[str] = None,
|
|
202
|
+
escape_reason: Optional[str] = None,
|
|
203
|
+
cwd: Optional[str] = None,
|
|
204
|
+
allowed_by: Optional[str] = None,
|
|
205
|
+
) -> None:
|
|
206
|
+
"""
|
|
207
|
+
Write a log entry to the audit log.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
tool: Tool name (Bash, Edit, Write)
|
|
211
|
+
command: Command or path that was checked
|
|
212
|
+
decision: "blocked", "asked", "allowed", "allowed_by_escape", or "allowed_by_disabled"
|
|
213
|
+
blocked_by: Reason/pattern that triggered block
|
|
214
|
+
user_approved: Whether user approved (for ask patterns)
|
|
215
|
+
pattern_matched: The regex pattern that matched
|
|
216
|
+
rule_id: Stable identifier of the matched rule (when applicable)
|
|
217
|
+
escape_reason: Reason supplied via "# allow:" escape hatch (when applicable)
|
|
218
|
+
cwd: Working directory where the command would have run
|
|
219
|
+
allowed_by: The user-owned allowlist entry that allowed a command a rule
|
|
220
|
+
would otherwise block (e.g. ``delete-recursive: /repo/dist/*``)
|
|
221
|
+
"""
|
|
222
|
+
context = get_session_context()
|
|
223
|
+
|
|
224
|
+
entry = {
|
|
225
|
+
"timestamp": datetime.now().isoformat(),
|
|
226
|
+
"session_id": context["session_id"],
|
|
227
|
+
"conversation_id": context["conversation_id"],
|
|
228
|
+
"agent_id": context["agent_id"],
|
|
229
|
+
"tool": tool,
|
|
230
|
+
"command": command,
|
|
231
|
+
"decision": decision,
|
|
232
|
+
"blocked_by": blocked_by,
|
|
233
|
+
"user_approved": user_approved,
|
|
234
|
+
"pattern_matched": pattern_matched,
|
|
235
|
+
"rule_id": rule_id,
|
|
236
|
+
"escape_reason": escape_reason,
|
|
237
|
+
"cwd": cwd or _safe_cwd(),
|
|
238
|
+
# Join keys for the outcome rows written by hooks/outcome_logger.py.
|
|
239
|
+
"tool_use_id": _hook_field("tool_use_id"),
|
|
240
|
+
"permission_mode": _hook_field("permission_mode"),
|
|
241
|
+
}
|
|
242
|
+
if allowed_by:
|
|
243
|
+
entry["allowed_by"] = allowed_by
|
|
244
|
+
|
|
245
|
+
log_file = get_log_file()
|
|
246
|
+
|
|
247
|
+
# Append to JSONL file
|
|
248
|
+
with open(log_file, "a") as f:
|
|
249
|
+
f.write(json.dumps(entry) + "\n")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def log_blocked(
|
|
253
|
+
tool: str,
|
|
254
|
+
command: str,
|
|
255
|
+
reason: str,
|
|
256
|
+
pattern: Optional[str] = None,
|
|
257
|
+
rule_id: Optional[str] = None,
|
|
258
|
+
) -> None:
|
|
259
|
+
"""
|
|
260
|
+
Log a blocked operation.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
tool: Tool name (Bash, Edit, Write)
|
|
264
|
+
command: Command or path that was blocked
|
|
265
|
+
reason: Human-readable reason for block
|
|
266
|
+
pattern: The regex pattern that matched
|
|
267
|
+
rule_id: Stable identifier of the matched rule
|
|
268
|
+
"""
|
|
269
|
+
log_entry(
|
|
270
|
+
tool=tool,
|
|
271
|
+
command=command,
|
|
272
|
+
decision="blocked",
|
|
273
|
+
blocked_by=reason,
|
|
274
|
+
pattern_matched=pattern,
|
|
275
|
+
rule_id=rule_id,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def log_escape(
|
|
280
|
+
tool: str,
|
|
281
|
+
command: str,
|
|
282
|
+
escape_reason: str,
|
|
283
|
+
) -> None:
|
|
284
|
+
"""
|
|
285
|
+
Log a command that was allowed through the ``# allow: <reason>`` escape hatch.
|
|
286
|
+
"""
|
|
287
|
+
log_entry(
|
|
288
|
+
tool=tool,
|
|
289
|
+
command=command,
|
|
290
|
+
decision="allowed_by_escape",
|
|
291
|
+
blocked_by=f"Escape hatch: {escape_reason}",
|
|
292
|
+
escape_reason=escape_reason,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def log_disabled(
|
|
297
|
+
tool: str,
|
|
298
|
+
command: str,
|
|
299
|
+
) -> None:
|
|
300
|
+
"""
|
|
301
|
+
Log a command that was allowed because the safety system is disabled.
|
|
302
|
+
"""
|
|
303
|
+
log_entry(
|
|
304
|
+
tool=tool,
|
|
305
|
+
command=command,
|
|
306
|
+
decision="allowed_by_disabled",
|
|
307
|
+
blocked_by="safety disabled",
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def log_asked(
|
|
312
|
+
tool: str,
|
|
313
|
+
command: str,
|
|
314
|
+
reason: str,
|
|
315
|
+
pattern: Optional[str] = None,
|
|
316
|
+
) -> None:
|
|
317
|
+
"""
|
|
318
|
+
Log an operation that requires user confirmation.
|
|
319
|
+
|
|
320
|
+
Note: This logs the ASK event. A subsequent log_allowed() or log_blocked()
|
|
321
|
+
should be called after user responds.
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
tool: Tool name (Bash, Edit, Write)
|
|
325
|
+
command: Command or path that requires confirmation
|
|
326
|
+
reason: Human-readable reason for asking
|
|
327
|
+
pattern: The regex pattern that matched
|
|
328
|
+
"""
|
|
329
|
+
log_entry(
|
|
330
|
+
tool=tool,
|
|
331
|
+
command=command,
|
|
332
|
+
decision="asked",
|
|
333
|
+
blocked_by=reason,
|
|
334
|
+
pattern_matched=pattern,
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def log_allowed(
|
|
339
|
+
tool: str,
|
|
340
|
+
command: str,
|
|
341
|
+
user_approved: bool = False,
|
|
342
|
+
allowed_by: Optional[str] = None,
|
|
343
|
+
) -> None:
|
|
344
|
+
"""
|
|
345
|
+
Log an allowed operation.
|
|
346
|
+
|
|
347
|
+
Args:
|
|
348
|
+
tool: Tool name (Bash, Edit, Write)
|
|
349
|
+
command: Command or path that was allowed
|
|
350
|
+
user_approved: Whether this was explicitly approved by user (for ask patterns)
|
|
351
|
+
allowed_by: The allowlist entry that allowed it, when one did
|
|
352
|
+
"""
|
|
353
|
+
log_entry(
|
|
354
|
+
tool=tool,
|
|
355
|
+
command=command,
|
|
356
|
+
decision="allowed",
|
|
357
|
+
user_approved=user_approved if user_approved else None,
|
|
358
|
+
allowed_by=allowed_by,
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def log_user_approval(
|
|
363
|
+
tool: str,
|
|
364
|
+
command: str,
|
|
365
|
+
approved: bool,
|
|
366
|
+
) -> None:
|
|
367
|
+
"""
|
|
368
|
+
Log user's response to an ask pattern.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
tool: Tool name (Bash, Edit, Write)
|
|
372
|
+
command: Command or path that was asked about
|
|
373
|
+
approved: Whether user approved (True) or rejected (False)
|
|
374
|
+
"""
|
|
375
|
+
if approved:
|
|
376
|
+
log_entry(
|
|
377
|
+
tool=tool,
|
|
378
|
+
command=command,
|
|
379
|
+
decision="allowed",
|
|
380
|
+
user_approved=True,
|
|
381
|
+
)
|
|
382
|
+
else:
|
|
383
|
+
log_entry(
|
|
384
|
+
tool=tool,
|
|
385
|
+
command=command,
|
|
386
|
+
decision="blocked",
|
|
387
|
+
blocked_by="User rejected",
|
|
388
|
+
user_approved=False,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# CLI for testing
|
|
393
|
+
if __name__ == "__main__":
|
|
394
|
+
import sys
|
|
395
|
+
|
|
396
|
+
if len(sys.argv) < 2:
|
|
397
|
+
print("Usage: python audit_logger.py <test|blocked|asked|allowed>")
|
|
398
|
+
sys.exit(1)
|
|
399
|
+
|
|
400
|
+
cmd = sys.argv[1]
|
|
401
|
+
|
|
402
|
+
if cmd == "test":
|
|
403
|
+
# Write test entries
|
|
404
|
+
log_blocked("Bash", "rm -rf /", "rm with recursive/force flags", r"\brm\s+-[rRf]")
|
|
405
|
+
log_asked("Bash", "git checkout -- .", "Discards all uncommitted changes", r"\bgit\s+checkout\s+--\s*\.")
|
|
406
|
+
log_allowed("Bash", "ls -la", user_approved=False)
|
|
407
|
+
log_user_approval("Bash", "git branch -D old-feature", approved=True)
|
|
408
|
+
print(f"✓ Test entries written to {get_log_file()}")
|
|
409
|
+
|
|
410
|
+
elif cmd == "blocked":
|
|
411
|
+
tool = sys.argv[2] if len(sys.argv) > 2 else "Bash"
|
|
412
|
+
command = sys.argv[3] if len(sys.argv) > 3 else "test command"
|
|
413
|
+
reason = sys.argv[4] if len(sys.argv) > 4 else "test reason"
|
|
414
|
+
log_blocked(tool, command, reason)
|
|
415
|
+
print("✓ Blocked entry logged")
|
|
416
|
+
|
|
417
|
+
elif cmd == "asked":
|
|
418
|
+
tool = sys.argv[2] if len(sys.argv) > 2 else "Bash"
|
|
419
|
+
command = sys.argv[3] if len(sys.argv) > 3 else "test command"
|
|
420
|
+
reason = sys.argv[4] if len(sys.argv) > 4 else "test reason"
|
|
421
|
+
log_asked(tool, command, reason)
|
|
422
|
+
print("✓ Asked entry logged")
|
|
423
|
+
|
|
424
|
+
elif cmd == "allowed":
|
|
425
|
+
tool = sys.argv[2] if len(sys.argv) > 2 else "Bash"
|
|
426
|
+
command = sys.argv[3] if len(sys.argv) > 3 else "test command"
|
|
427
|
+
log_allowed(tool, command)
|
|
428
|
+
print("✓ Allowed entry logged")
|
|
429
|
+
|
|
430
|
+
else:
|
|
431
|
+
print(f"Unknown command: {cmd}")
|
|
432
|
+
sys.exit(1)
|