stacktrace-cli 0.18.0__py3-none-any.whl → 0.19.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.
- stacktrace/__init__.py +1 -1
- stacktrace/analysis.py +9 -2
- stacktrace/correlate/acquire.py +59 -64
- stacktrace/correlate/composition.py +13 -0
- stacktrace/correlate/orchestrate.py +11 -4
- stacktrace/daemon/costs.py +7 -7
- stacktrace/daemon/db.py +149 -19
- stacktrace/daemon/gateway.py +3 -13
- stacktrace/daemon/gateway_policy.py +14 -9
- stacktrace/daemon/inline_hook.py +348 -95
- stacktrace/daemon/observer.py +308 -48
- stacktrace/daemon/policy_collect.py +68 -17
- stacktrace/daemon/policy_inputs.py +13 -2
- stacktrace/daemon/policy_runtime.py +225 -75
- stacktrace/daemon/runtime.py +30 -19
- stacktrace/daemon/scan.py +11 -0
- stacktrace/daemon/server.py +8 -0
- stacktrace/daemon/store.py +212 -32
- stacktrace/detector/deterministic.py +157 -11
- stacktrace/detector/inline.py +41 -7
- stacktrace/detector/rules.py +51 -11
- stacktrace/detector/run.py +15 -3
- stacktrace/gateway/analyzer.py +155 -63
- stacktrace/gateway/marker.py +729 -0
- stacktrace/gateway/service.py +13 -2
- stacktrace/gateway/sink.py +17 -9
- stacktrace/hooks/claude.py +41 -9
- stacktrace/hooks/codex.py +48 -5
- stacktrace/hooks/cursor.py +21 -3
- stacktrace/hooks/devin.py +125 -0
- stacktrace/remote/detect_payload.py +8 -2
- stacktrace/remote/hook_policy.py +21 -1
- {stacktrace_cli-0.18.0.dist-info → stacktrace_cli-0.19.0.dist-info}/METADATA +4 -4
- {stacktrace_cli-0.18.0.dist-info → stacktrace_cli-0.19.0.dist-info}/RECORD +36 -34
- {stacktrace_cli-0.18.0.dist-info → stacktrace_cli-0.19.0.dist-info}/WHEEL +0 -0
- {stacktrace_cli-0.18.0.dist-info → stacktrace_cli-0.19.0.dist-info}/entry_points.txt +0 -0
stacktrace/daemon/inline_hook.py
CHANGED
|
@@ -15,30 +15,58 @@ not move them. The call's own working directory is its `cwd`, as a
|
|
|
15
15
|
transcript records it, so a relative path resolves where the shell is. The
|
|
16
16
|
call's span is named by its `tool_use_id`, so each blocked call is its own
|
|
17
17
|
event in the store.
|
|
18
|
+
|
|
19
|
+
A prompt from `UserPromptSubmit` is read the same way, as the one `user` turn
|
|
20
|
+
of a session ("Hook path: prompts"). A subagent's prompt is marked as a
|
|
21
|
+
sidechain turn, which both prompt rules leave to the main session, so it is
|
|
22
|
+
never blocked.
|
|
23
|
+
|
|
24
|
+
A detection block of a call or a prompt writes no finding here. The daemon
|
|
25
|
+
keeps its marker once the deny reaches the hook, and the scan writes the
|
|
26
|
+
finding from the marker when it reads the call or the prompt in the transcript
|
|
27
|
+
(ADR-0178). A component deny keeps its marker too, and the scan builds its
|
|
28
|
+
finding from it (ADR-0184). A marker whose call never joins gets a slim
|
|
29
|
+
finding (ADR-0186).
|
|
18
30
|
"""
|
|
19
31
|
|
|
20
32
|
from __future__ import annotations
|
|
21
33
|
|
|
34
|
+
import json
|
|
35
|
+
import logging
|
|
36
|
+
import os
|
|
22
37
|
import re
|
|
23
|
-
|
|
38
|
+
import threading
|
|
39
|
+
import uuid
|
|
40
|
+
from collections.abc import Mapping, Sequence
|
|
24
41
|
from dataclasses import dataclass, replace
|
|
42
|
+
from datetime import UTC, datetime
|
|
25
43
|
from pathlib import Path
|
|
26
44
|
from typing import TYPE_CHECKING
|
|
27
45
|
|
|
28
46
|
from stacktrace import __version__
|
|
29
|
-
from stacktrace.
|
|
30
|
-
from stacktrace.
|
|
31
|
-
from stacktrace.detector.
|
|
47
|
+
from stacktrace.daemon.policy_runtime import sub_agent_session
|
|
48
|
+
from stacktrace.daemon.store import marker_from_json, marker_json
|
|
49
|
+
from stacktrace.detector.finding import Detection
|
|
50
|
+
from stacktrace.detector.inline import judge_pending
|
|
32
51
|
from stacktrace.gateway.formats import read
|
|
52
|
+
from stacktrace.gateway.marker import (
|
|
53
|
+
Marker,
|
|
54
|
+
denied_component,
|
|
55
|
+
gate_evidence,
|
|
56
|
+
prompt_key,
|
|
57
|
+
unkeyed_key,
|
|
58
|
+
)
|
|
33
59
|
from stacktrace.gateway.session import AGENT_HEADER, SESSION_HEADER, build
|
|
34
|
-
from stacktrace.gateway.sink import Stamp
|
|
35
60
|
from stacktrace.hooks.claude import inspected
|
|
36
61
|
|
|
37
62
|
if TYPE_CHECKING:
|
|
38
63
|
from collections.abc import Callable
|
|
39
64
|
|
|
40
|
-
from stacktrace.daemon.policy_inputs import PolicyEntry
|
|
41
|
-
from stacktrace.daemon.policy_runtime import
|
|
65
|
+
from stacktrace.daemon.policy_inputs import DetectionEntry, PolicyEntry
|
|
66
|
+
from stacktrace.daemon.policy_runtime import Entry
|
|
67
|
+
from stacktrace.daemon.store import SessionKey
|
|
68
|
+
|
|
69
|
+
logger = logging.getLogger(__name__)
|
|
42
70
|
|
|
43
71
|
#: Claude Code's session ids are UUIDs. Anything else is refused rather than
|
|
44
72
|
#: kept, because the id names the finding's session and a `:` would forge one.
|
|
@@ -47,6 +75,9 @@ _TOOL_USE_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
|
|
|
47
75
|
#: Client-supplied, like the gateway's own agent header; a `:` would forge the
|
|
48
76
|
#: composed identity below.
|
|
49
77
|
_AGENT_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
|
|
78
|
+
#: Claude Code's `prompt_id` is a UUID. It names a turn key, so a `:` would
|
|
79
|
+
#: forge a span.
|
|
80
|
+
_PROMPT_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
|
|
50
81
|
|
|
51
82
|
|
|
52
83
|
@dataclass(frozen=True)
|
|
@@ -104,6 +135,94 @@ def pending_call(action: Mapping[str, object]) -> PendingCall:
|
|
|
104
135
|
)
|
|
105
136
|
|
|
106
137
|
|
|
138
|
+
@dataclass(frozen=True)
|
|
139
|
+
class PendingPrompt:
|
|
140
|
+
"""One validated `UserPromptSubmit` prompt. Hold it for one request; never log it."""
|
|
141
|
+
|
|
142
|
+
agent_kind: str
|
|
143
|
+
session_id: str
|
|
144
|
+
#: Whether the prompt runs inside a subagent. Set by the key alone: a
|
|
145
|
+
#: malformed id still marks a subagent's prompt, or it would be blocked.
|
|
146
|
+
subagent: bool
|
|
147
|
+
agent_id: str | None
|
|
148
|
+
prompt_id: str | None
|
|
149
|
+
project_root: str
|
|
150
|
+
text: str
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def pending_prompt(action: Mapping[str, object]) -> PendingPrompt:
|
|
154
|
+
"""The prompt a `prompt` action carries, or `ValueError` on any wrong shape.
|
|
155
|
+
|
|
156
|
+
`prompt_id` is optional: Claude Code sends none before the first user
|
|
157
|
+
input. A malformed one is dropped, which costs only the turn's key. The
|
|
158
|
+
error text is a fixed code, never a field's value.
|
|
159
|
+
"""
|
|
160
|
+
session_id, call = action.get("session_id"), action.get("call")
|
|
161
|
+
agent_id, prompt_id = action.get("agent_id"), action.get("prompt_id")
|
|
162
|
+
if not isinstance(session_id, str) or not _SESSION_ID.fullmatch(session_id):
|
|
163
|
+
raise ValueError("invalid_session")
|
|
164
|
+
if not isinstance(call, dict) or set(call) != {"prompt"}: # pyright: ignore[reportUnknownArgumentType]
|
|
165
|
+
raise ValueError("invalid_call")
|
|
166
|
+
text = call["prompt"]
|
|
167
|
+
if not isinstance(text, str):
|
|
168
|
+
raise ValueError("invalid_call") # noqa: TRY004 - one refusal type, read by its caller
|
|
169
|
+
agent_kind = action.get("agent_kind")
|
|
170
|
+
if not isinstance(agent_kind, str) or (action.get("name"), action.get("source")) != (
|
|
171
|
+
"prompt",
|
|
172
|
+
"user",
|
|
173
|
+
):
|
|
174
|
+
raise ValueError("unsupported_prompt")
|
|
175
|
+
return PendingPrompt(
|
|
176
|
+
agent_kind=agent_kind,
|
|
177
|
+
session_id=session_id,
|
|
178
|
+
subagent="agent_id" in action,
|
|
179
|
+
agent_id=agent_id if isinstance(agent_id, str) and _AGENT_ID.fullmatch(agent_id) else None,
|
|
180
|
+
prompt_id=(
|
|
181
|
+
prompt_id if isinstance(prompt_id, str) and _PROMPT_ID.fullmatch(prompt_id) else None
|
|
182
|
+
),
|
|
183
|
+
project_root=str(action["project_root"]),
|
|
184
|
+
text=text,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def judge_prompt(prompt: PendingPrompt, rules: frozenset[str]) -> tuple[Detection, ...]:
|
|
189
|
+
"""The detections of `rules` that the prompt would be, if the model received it.
|
|
190
|
+
|
|
191
|
+
The turn's key is the prompt's own id, or a random one when it has none,
|
|
192
|
+
so two blocked prompts in one session are two events. Never a digest of
|
|
193
|
+
the text: the key is in the finding's span, which leaves the machine, and
|
|
194
|
+
a digest of a short prompt, such as one email address, confirms a guess.
|
|
195
|
+
"""
|
|
196
|
+
if not rules:
|
|
197
|
+
return ()
|
|
198
|
+
request = {
|
|
199
|
+
"model": "stacktrace-hook",
|
|
200
|
+
"system": "",
|
|
201
|
+
"messages": [{"role": "user", "content": prompt.text}],
|
|
202
|
+
}
|
|
203
|
+
headers = {SESSION_HEADER: prompt.session_id}
|
|
204
|
+
if prompt.agent_id is not None:
|
|
205
|
+
headers[AGENT_HEADER] = prompt.agent_id
|
|
206
|
+
exchange = read(request, {"content": []}, headers=headers, fmt="anthropic")
|
|
207
|
+
# The launch project, never a directory the prompt's own text names.
|
|
208
|
+
exchange = replace(exchange, working_directory=prompt.project_root)
|
|
209
|
+
session = build(exchange).session
|
|
210
|
+
# The session header names one agent kind. A prompt from another kind is
|
|
211
|
+
# no prompt this can read.
|
|
212
|
+
if session.agent_kind != prompt.agent_kind:
|
|
213
|
+
raise ValueError("unsupported_agent")
|
|
214
|
+
key = f"prompt-{prompt.prompt_id or uuid.uuid4().hex}"
|
|
215
|
+
session = replace(
|
|
216
|
+
session,
|
|
217
|
+
turns=tuple(
|
|
218
|
+
replace(t, key=key, is_sidechain=prompt.subagent)
|
|
219
|
+
for t in session.turns
|
|
220
|
+
if t.role == "user"
|
|
221
|
+
),
|
|
222
|
+
)
|
|
223
|
+
return judge_pending(session, frozenset(), rules, prompt=key)
|
|
224
|
+
|
|
225
|
+
|
|
107
226
|
def judge(call: PendingCall, rules: frozenset[str]) -> tuple[Detection, ...]:
|
|
108
227
|
"""The detections of `rules` that the call would be, if it ran."""
|
|
109
228
|
if not rules:
|
|
@@ -162,119 +281,253 @@ def judge(call: PendingCall, rules: frozenset[str]) -> tuple[Detection, ...]:
|
|
|
162
281
|
|
|
163
282
|
|
|
164
283
|
def inspect_call(action: dict[str, object], rules: frozenset[str]) -> tuple[Detection, ...]:
|
|
165
|
-
"""The policy runtime's `Inspector`: read the call, then judge it."""
|
|
284
|
+
"""The policy runtime's `Inspector`: read the call or the prompt, then judge it."""
|
|
285
|
+
if action.get("action_kind") == "prompt":
|
|
286
|
+
return judge_prompt(pending_prompt(action), rules)
|
|
166
287
|
return judge(pending_call(action), rules)
|
|
167
288
|
|
|
168
289
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
"""
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
290
|
+
#: The marker spool's file name, beside the store (`Markers`).
|
|
291
|
+
MARKER_SPOOL = "blocked-markers.jsonl"
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
class Markers:
|
|
295
|
+
"""The hook's markers: in the store, or in a local spool until a write succeeds.
|
|
296
|
+
|
|
297
|
+
A failed write never costs a block (unified-policy.md, "A marker that
|
|
298
|
+
cannot be stored"). The marker waits here and in `spool`, a small file
|
|
299
|
+
beside the store that the daemon fsyncs before `keep` returns. Each later
|
|
300
|
+
`keep` and each scan's `read` writes it again, and a daemon that starts
|
|
301
|
+
loads the spool first. When every waiting marker is written, the spool is
|
|
302
|
+
removed. Until the write succeeds, `read` still answers with the marker,
|
|
303
|
+
so the scan stamps the call.
|
|
304
|
+
|
|
305
|
+
`owed` answers with every marker whose finding the scan still owes: the
|
|
306
|
+
store's unpaid ones and the ones that wait here. The scan offers each of
|
|
307
|
+
their sessions again until it writes the finding (`SessionObserver`).
|
|
308
|
+
"""
|
|
309
|
+
|
|
310
|
+
def __init__(
|
|
311
|
+
self,
|
|
312
|
+
remember: Callable[[Marker], object],
|
|
313
|
+
stored: Callable[[Sequence[SessionKey]], frozenset[Marker]],
|
|
314
|
+
unpaid: Callable[[str], frozenset[Marker]] | None = None,
|
|
315
|
+
spool: Path | None = None,
|
|
316
|
+
) -> None:
|
|
317
|
+
self._remember = remember
|
|
318
|
+
self._stored = stored
|
|
319
|
+
self._unpaid = unpaid or (lambda _kind: frozenset[Marker]())
|
|
320
|
+
self._spool = spool
|
|
321
|
+
loaded = _read_spool(spool) if spool is not None else []
|
|
322
|
+
#: What the spool holds now, so a write that changes nothing is
|
|
323
|
+
#: skipped. Unknown at start, so the first `retry` rewrites a spool
|
|
324
|
+
#: that held a line it could not read.
|
|
325
|
+
self._spooled: list[Marker] | None = None
|
|
326
|
+
self._unwritten: list[Marker] = loaded
|
|
327
|
+
self._lock = threading.Lock()
|
|
328
|
+
|
|
329
|
+
def keep(self, marker: Marker) -> None:
|
|
330
|
+
"""Write `marker`, or spool it for a later try. Never raises."""
|
|
331
|
+
with self._lock:
|
|
332
|
+
self._unwritten.append(marker)
|
|
333
|
+
self.retry()
|
|
334
|
+
|
|
335
|
+
def owed(self, agent_kind: str) -> frozenset[Marker]:
|
|
336
|
+
"""Every marker of this kind whose finding the scan has not written."""
|
|
337
|
+
self.retry()
|
|
338
|
+
with self._lock:
|
|
339
|
+
waiting = frozenset(
|
|
340
|
+
m for m in self._unwritten if m.agent_kind == agent_kind and (m.stamps or m.builds)
|
|
341
|
+
)
|
|
342
|
+
return self._unpaid(agent_kind) | waiting
|
|
343
|
+
|
|
344
|
+
def retry(self) -> None:
|
|
345
|
+
"""Write each marker that waits. One that fails again stays in the spool."""
|
|
346
|
+
with self._lock:
|
|
347
|
+
waiting: list[Marker] = []
|
|
348
|
+
for marker in self._unwritten:
|
|
349
|
+
try:
|
|
350
|
+
self._remember(marker)
|
|
351
|
+
except Exception as error: # noqa: BLE001 - the deny stands; a later try writes it
|
|
352
|
+
logger.warning("block marker not stored: %s", type(error).__name__)
|
|
353
|
+
waiting.append(marker)
|
|
354
|
+
self._unwritten = waiting
|
|
355
|
+
if self._spool is not None and waiting != self._spooled:
|
|
356
|
+
try:
|
|
357
|
+
_write_spool(self._spool, waiting)
|
|
358
|
+
except OSError as error:
|
|
359
|
+
logger.warning("block marker not spooled: %s", type(error).__name__)
|
|
360
|
+
else:
|
|
361
|
+
self._spooled = list(waiting)
|
|
362
|
+
|
|
363
|
+
def read(self, sessions: Sequence[SessionKey]) -> frozenset[Marker]:
|
|
364
|
+
"""Every marker in these sessions: the stored ones and the ones that wait."""
|
|
365
|
+
self.retry()
|
|
366
|
+
keys = {(s.agent_kind, s.session_id) for s in sessions}
|
|
367
|
+
with self._lock:
|
|
368
|
+
waiting = frozenset(m for m in self._unwritten if (m.agent_kind, m.session_id) in keys)
|
|
369
|
+
return self._stored(sessions) | waiting
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _read_spool(path: Path) -> list[Marker]:
|
|
373
|
+
"""The markers a spool holds. A line that does not read is left out."""
|
|
374
|
+
try:
|
|
375
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
376
|
+
except FileNotFoundError:
|
|
377
|
+
return []
|
|
378
|
+
except (OSError, UnicodeDecodeError) as error:
|
|
379
|
+
logger.warning("block marker spool not read: %s", type(error).__name__)
|
|
380
|
+
return []
|
|
381
|
+
markers: list[Marker] = []
|
|
382
|
+
for line in lines:
|
|
383
|
+
try:
|
|
384
|
+
marker = marker_from_json(json.loads(line))
|
|
385
|
+
except (ValueError, TypeError):
|
|
386
|
+
continue
|
|
387
|
+
if marker is not None:
|
|
388
|
+
markers.append(marker)
|
|
389
|
+
return markers
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _write_spool(path: Path, markers: Sequence[Marker]) -> None:
|
|
393
|
+
"""Replace the spool with `markers`, durably, or remove it when there are none."""
|
|
394
|
+
if not markers:
|
|
395
|
+
path.unlink(missing_ok=True)
|
|
396
|
+
return
|
|
397
|
+
temporary = path.with_name(path.name + ".tmp")
|
|
398
|
+
with temporary.open("w", encoding="utf-8") as file:
|
|
399
|
+
for marker in markers:
|
|
400
|
+
file.write(json.dumps(marker_json(marker), separators=(",", ":")) + "\n")
|
|
401
|
+
file.flush()
|
|
402
|
+
os.fsync(file.fileno())
|
|
403
|
+
temporary.replace(path)
|
|
404
|
+
directory = os.open(path.parent, os.O_RDONLY)
|
|
405
|
+
try:
|
|
406
|
+
os.fsync(directory)
|
|
407
|
+
finally:
|
|
408
|
+
os.close(directory)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def block_marker(
|
|
412
|
+
keep: Callable[[Marker], None],
|
|
413
|
+
) -> Callable[[dict[str, object], Detection, DetectionEntry, int], None]:
|
|
414
|
+
"""Keep the marker of a detection block of a tool call or a prompt. Write
|
|
415
|
+
no finding (ADR-0178).
|
|
416
|
+
|
|
417
|
+
Called once the deny is written to the hook, before the hook hands it to
|
|
418
|
+
the agent, so the marker exists before the agent writes the call or the
|
|
419
|
+
prompt to its transcript. A deny that never reached the hook keeps no
|
|
420
|
+
marker (`Result.commit`). The scan reads the call's `tool_use_id` back as
|
|
421
|
+
its `provider_call_id`, and the prompt's text back as its prompt key
|
|
422
|
+
(`prompt_key`). It judges each with the marker's rule as if it ran, and
|
|
423
|
+
writes the finding stamped `action: blocked`, `where: hook`, with the
|
|
424
|
+
marker's revision. A block always notifies, whatever its entry's `notify`
|
|
425
|
+
(unified-policy.md, "Off, Detect and Block").
|
|
192
426
|
"""
|
|
193
427
|
|
|
194
428
|
def record(
|
|
195
|
-
action: dict[str, object], detection: Detection,
|
|
429
|
+
action: dict[str, object], detection: Detection, entry: DetectionEntry, revision: int
|
|
196
430
|
) -> None:
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
"
|
|
200
|
-
|
|
201
|
-
notify=notify,
|
|
202
|
-
where="hook",
|
|
431
|
+
call_key = (
|
|
432
|
+
prompt_key(pending_prompt(action).text)
|
|
433
|
+
if action.get("action_kind") == "prompt"
|
|
434
|
+
else pending_call(action).tool_use_id
|
|
203
435
|
)
|
|
204
436
|
# The judged session's id, not the hook's: for a subagent's call it is
|
|
205
437
|
# `<session>:agent-<id>`, the session the scan reads the transcript as.
|
|
206
438
|
session = detection.session
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
439
|
+
keep(
|
|
440
|
+
Marker(
|
|
441
|
+
agent_kind=session.agent_kind,
|
|
442
|
+
session_id=session.session_id,
|
|
443
|
+
call_key=call_key,
|
|
444
|
+
rule_id=detection.rule_id,
|
|
445
|
+
entry_id=entry.id,
|
|
446
|
+
entry_name=entry.name,
|
|
447
|
+
policy_revision=revision,
|
|
448
|
+
outcome="blocked",
|
|
449
|
+
where="hook",
|
|
450
|
+
rules_version=__version__,
|
|
451
|
+
blocked_at=datetime.now(UTC),
|
|
452
|
+
)
|
|
453
|
+
)
|
|
215
454
|
|
|
216
455
|
return record
|
|
217
456
|
|
|
218
457
|
|
|
219
|
-
#: A component deny's one citation: what the call was and that it never ran.
|
|
220
|
-
_DENIED_KIND = "component"
|
|
221
|
-
_DENIED_DETAIL = "in a call that was blocked before it ran"
|
|
222
|
-
|
|
223
|
-
|
|
224
458
|
def component_denial_recorder(
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
The
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
(
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
459
|
+
keep: Callable[[Marker], object],
|
|
460
|
+
) -> Callable[[dict[str, object], str, PolicyEntry | None, int, Entry | None], None]:
|
|
461
|
+
"""Keep a component deny's marker. Write no finding (ADR-0184).
|
|
462
|
+
|
|
463
|
+
Called once the deny reached the hook (`Result.commit`), before the hook
|
|
464
|
+
hands it to the agent, so the marker exists before the agent writes the
|
|
465
|
+
denied call to its transcript. The marker names the call by its
|
|
466
|
+
`tool_use_id`, which the transcript reader gives back as the call's
|
|
467
|
+
`provider_call_id`. It holds the selector, and, when the decision named one
|
|
468
|
+
component (`resolved`), that component's identity and version and the ids
|
|
469
|
+
its gate matched. The scan builds the finding from it at the call's own
|
|
470
|
+
span (unified-policy.md, "The finding of a component deny"). `keep` writes
|
|
471
|
+
the marker, or spools it until a write succeeds (`Markers`).
|
|
472
|
+
|
|
473
|
+
A deny whose hook sent no call key, or a malformed one, still keeps a
|
|
474
|
+
marker, with a key of its own (`unkeyed_key`) and the session when it is
|
|
475
|
+
known. The scan pays it with its slim finding (ADR-0186). A deny that
|
|
476
|
+
names no policy entry keeps its marker too, with the rule that denied it
|
|
477
|
+
and no entry: no finding reads the entry.
|
|
238
478
|
"""
|
|
239
479
|
|
|
240
|
-
def record(
|
|
480
|
+
def record(
|
|
481
|
+
action: dict[str, object],
|
|
482
|
+
rule_id: str,
|
|
483
|
+
entry: PolicyEntry | None,
|
|
484
|
+
revision: int,
|
|
485
|
+
resolved: Entry | None,
|
|
486
|
+
) -> None:
|
|
241
487
|
agent_kind, session_id = action.get("agent_kind"), action.get("session_id")
|
|
242
488
|
call_id, agent_id = action.get("tool_use_id"), action.get("agent_id")
|
|
489
|
+
kind, name = action.get("action_kind"), action.get("name")
|
|
243
490
|
if (
|
|
244
491
|
not isinstance(agent_kind, str)
|
|
245
|
-
or not isinstance(
|
|
246
|
-
or not
|
|
247
|
-
or not isinstance(call_id, str)
|
|
248
|
-
or not _TOOL_USE_ID.fullmatch(call_id)
|
|
492
|
+
or not isinstance(kind, str)
|
|
493
|
+
or not isinstance(name, str)
|
|
249
494
|
):
|
|
250
495
|
return
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
if isinstance(agent_id, str) and _AGENT_ID.fullmatch(agent_id):
|
|
254
|
-
session_id = f"{session_id}:agent-{agent_id}"
|
|
255
|
-
title, fix = COMPONENT_DENIALS[entry.rule_id]
|
|
256
|
-
detection = Detection(
|
|
257
|
-
rule_id=entry.rule_id,
|
|
258
|
-
severity="high",
|
|
259
|
-
confidence="high",
|
|
260
|
-
title=title,
|
|
261
|
-
session=SessionRef(session_id, agent_kind, None, 0),
|
|
262
|
-
evidence=(Evidence(f"{session_id}:{call_id}:0", _DENIED_KIND, _DENIED_DETAIL),),
|
|
263
|
-
remediation=fix,
|
|
496
|
+
session = (
|
|
497
|
+
session_id if isinstance(session_id, str) and _SESSION_ID.fullmatch(session_id) else ""
|
|
264
498
|
)
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
499
|
+
# Composed as the agent's transcript reader names a sub-agent's
|
|
500
|
+
# session, which is how the scan reads it.
|
|
501
|
+
if session and isinstance(agent_id, str) and _AGENT_ID.fullmatch(agent_id):
|
|
502
|
+
session = sub_agent_session(agent_kind, session, agent_id)
|
|
503
|
+
call_key = (
|
|
504
|
+
call_id
|
|
505
|
+
if session and isinstance(call_id, str) and _TOOL_USE_ID.fullmatch(call_id)
|
|
506
|
+
else unkeyed_key()
|
|
507
|
+
)
|
|
508
|
+
keep(
|
|
509
|
+
Marker(
|
|
510
|
+
agent_kind=agent_kind,
|
|
511
|
+
session_id=session,
|
|
512
|
+
call_key=call_key,
|
|
513
|
+
rule_id=rule_id,
|
|
514
|
+
entry_id=entry.id if entry is not None else None,
|
|
515
|
+
entry_name=entry.name if entry is not None else None,
|
|
516
|
+
policy_revision=revision,
|
|
517
|
+
outcome="blocked",
|
|
518
|
+
where="hook",
|
|
519
|
+
rules_version=__version__,
|
|
520
|
+
component=denied_component(
|
|
521
|
+
kind,
|
|
522
|
+
name,
|
|
523
|
+
resolved.version if resolved is not None else None,
|
|
524
|
+
resolved.identity if resolved is not None else None,
|
|
525
|
+
),
|
|
526
|
+
gate_evidence=gate_evidence(
|
|
527
|
+
rule_id, resolved.evidence if resolved is not None else ()
|
|
528
|
+
),
|
|
529
|
+
blocked_at=datetime.now(UTC),
|
|
530
|
+
)
|
|
271
531
|
)
|
|
272
|
-
inserted = remember(agent_kind, session_id, call_id, entry.rule_id)
|
|
273
|
-
try:
|
|
274
|
-
write(detection, stamp)
|
|
275
|
-
except Exception:
|
|
276
|
-
if inserted:
|
|
277
|
-
forget(agent_kind, session_id, call_id, entry.rule_id)
|
|
278
|
-
raise
|
|
279
532
|
|
|
280
533
|
return record
|