stacktrace-cli 0.16.0__py3-none-any.whl → 0.18.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/cloud/__init__.py +10 -5
- stacktrace/cloud/agent_metadata.py +108 -0
- stacktrace/cloud/boot.py +12 -1
- stacktrace/core/policy.py +34 -0
- stacktrace/correlate/composition.py +28 -6
- stacktrace/cost/baseline.py +3 -6
- stacktrace/cost/measures.py +15 -4
- stacktrace/cost/reasons.py +6 -9
- stacktrace/cost/rules.py +2 -1
- stacktrace/daemon/costs.py +7 -0
- stacktrace/daemon/db.py +101 -0
- stacktrace/daemon/fleet.py +11 -3
- stacktrace/daemon/gateway.py +22 -6
- stacktrace/daemon/gateway_policy.py +33 -1
- stacktrace/daemon/inline_hook.py +280 -0
- stacktrace/daemon/observer.py +48 -4
- stacktrace/daemon/policy_collect.py +38 -2
- stacktrace/daemon/policy_inputs.py +460 -35
- stacktrace/daemon/policy_runtime.py +275 -21
- stacktrace/daemon/presentation.py +13 -1
- stacktrace/daemon/protocol.py +7 -0
- stacktrace/daemon/runtime.py +41 -10
- stacktrace/daemon/scan.py +26 -7
- stacktrace/daemon/server.py +22 -3
- stacktrace/daemon/store.py +75 -2
- stacktrace/daemon/webhook.py +13 -3
- stacktrace/detector/deterministic.py +86 -7
- stacktrace/detector/inline.py +53 -0
- stacktrace/detector/personal_data.py +111 -20
- stacktrace/detector/prompts/jev-v3/stacktrace-infra-unsafe-action.json +1 -1
- stacktrace/detector/reasoning.py +7 -0
- stacktrace/detector/rules.py +318 -3
- stacktrace/detector/tlds.txt +1289 -0
- stacktrace/finding_contract.py +20 -1
- stacktrace/gateway/analyzer.py +103 -7
- stacktrace/gateway/check.py +55 -42
- stacktrace/gateway/cli.py +2 -1
- stacktrace/gateway/service.py +62 -7
- stacktrace/gateway/session.py +19 -3
- stacktrace/gateway/sink.py +16 -26
- stacktrace/gateway/tetrate/__init__.py +18 -0
- stacktrace/gateway/tetrate/guardrail.py +171 -0
- stacktrace/gateway/tetrate/otlp.py +154 -0
- stacktrace/gateway/tetrate/requestlog.py +162 -0
- stacktrace/hooks/claude.py +208 -30
- stacktrace/hooks/cursor.py +90 -0
- stacktrace/hooks/journal.py +195 -0
- stacktrace/monitor/render.py +1 -0
- stacktrace/monitor/site/app.js +1 -0
- stacktrace/remote/client.py +23 -7
- stacktrace/remote/detect_payload.py +20 -0
- stacktrace/remote/hook_policy.py +25 -3
- stacktrace/remote/policy.py +8 -2
- stacktrace/remote/policy_service.py +12 -7
- stacktrace/remote/policy_show.py +47 -0
- stacktrace/remote/redact.py +11 -25
- stacktrace/remote/upload_contract.py +3 -0
- stacktrace/sessions/access.py +80 -4
- stacktrace/sessions/entrypoint.py +3 -2
- stacktrace/sessions/hook_journal.py +498 -0
- stacktrace/sessions/protocols.py +0 -6
- stacktrace/telemetry/events.py +3 -0
- {stacktrace_cli-0.16.0.dist-info → stacktrace_cli-0.18.0.dist-info}/METADATA +7 -6
- {stacktrace_cli-0.16.0.dist-info → stacktrace_cli-0.18.0.dist-info}/RECORD +67 -55
- {stacktrace_cli-0.16.0.dist-info → stacktrace_cli-0.18.0.dist-info}/WHEEL +1 -1
- {stacktrace_cli-0.16.0.dist-info → stacktrace_cli-0.18.0.dist-info}/entry_points.txt +0 -0
stacktrace/daemon/gateway.py
CHANGED
|
@@ -6,6 +6,9 @@ rules, the fail-open behaviour and the reply are the guard's own. What changes
|
|
|
6
6
|
is where a finding goes: into the daemon's `FindingStore`, so the Fleet drain
|
|
7
7
|
uploads it and the notification sinks hear of it, as for a transcript finding.
|
|
8
8
|
|
|
9
|
+
The same listener serves Tetrate Agent Router's guardrail contract and its
|
|
10
|
+
request log under `/tetrate/` (ADR-0167): two other contracts, the same token.
|
|
11
|
+
|
|
9
12
|
Off unless `STACKTRACE_GATEWAY_LISTEN` names an address. The private Unix
|
|
10
13
|
socket and its `authorize` message are untouched: a gateway turn is far larger
|
|
11
14
|
than that socket's frame and carries the arguments its contract excludes.
|
|
@@ -22,10 +25,11 @@ from http.server import ThreadingHTTPServer
|
|
|
22
25
|
from stacktrace.cost.usage import AccountCard
|
|
23
26
|
from stacktrace.detector.finding import Detection
|
|
24
27
|
from stacktrace.detector.render import detection_json
|
|
25
|
-
from stacktrace.gateway.analyzer import PolicyCheck
|
|
28
|
+
from stacktrace.gateway.analyzer import Entries, PolicyCheck
|
|
26
29
|
from stacktrace.gateway.principal import Principal, session_key_id
|
|
27
30
|
from stacktrace.gateway.service import Guard, loopback, make_server, serve_in_thread
|
|
28
31
|
from stacktrace.gateway.sink import Recorder, Stamp
|
|
32
|
+
from stacktrace.gateway.tetrate import EVALUATE_PATH, LOGS_PATH, guardrail, requestlog
|
|
29
33
|
|
|
30
34
|
from .accounts import email_digest
|
|
31
35
|
from .config import DaemonConfig, parse_listen
|
|
@@ -86,7 +90,7 @@ def _card(principal: Principal) -> AccountCard:
|
|
|
86
90
|
)
|
|
87
91
|
|
|
88
92
|
|
|
89
|
-
def
|
|
93
|
+
def store_finding(
|
|
90
94
|
store: FindingStore,
|
|
91
95
|
publish: Callable[[Notification], None],
|
|
92
96
|
on_commit: Callable[[], None],
|
|
@@ -107,6 +111,11 @@ def _store_finding(
|
|
|
107
111
|
payload["actor"] = stamp.actor
|
|
108
112
|
payload["action"] = stamp.action
|
|
109
113
|
payload["decided_by"] = stamp.decided_by
|
|
114
|
+
payload["where"] = stamp.where
|
|
115
|
+
if not stamp.notify:
|
|
116
|
+
# Store-only: never sent to Fleet (`GATEWAY_FIELDS` in
|
|
117
|
+
# `remote/detect_payload.py` does not declare it).
|
|
118
|
+
payload["notify"] = False
|
|
110
119
|
if stamp.principal is not None:
|
|
111
120
|
# The run's account and its card, as a laptop run's sign-in has
|
|
112
121
|
# them, so Fleet names the person with no new field (ADR-0153).
|
|
@@ -115,8 +124,11 @@ def _store_finding(
|
|
|
115
124
|
notifications = store.record(session, (payload,), underbuilt=None)
|
|
116
125
|
# As a scan commit does, so the finding leaves before the next drain interval.
|
|
117
126
|
on_commit()
|
|
118
|
-
|
|
119
|
-
|
|
127
|
+
# The finding is stored either way; an entry with `notify: false` keeps
|
|
128
|
+
# it out of Slack and the session only.
|
|
129
|
+
if stamp.notify:
|
|
130
|
+
for notification in notifications:
|
|
131
|
+
publish(notification)
|
|
120
132
|
|
|
121
133
|
return write
|
|
122
134
|
|
|
@@ -129,6 +141,7 @@ def start_gateway(
|
|
|
129
141
|
token: str | None = None,
|
|
130
142
|
on_commit: Callable[[], None] = lambda: None,
|
|
131
143
|
policy: PolicyCheck | None = None,
|
|
144
|
+
entries: Entries | None = None,
|
|
132
145
|
) -> ThreadingHTTPServer | None:
|
|
133
146
|
"""Serve the guard contract on the configured address, or nothing when it is off."""
|
|
134
147
|
address = parse_listen(config.gateway_listen.value)
|
|
@@ -139,10 +152,13 @@ def start_gateway(
|
|
|
139
152
|
return None
|
|
140
153
|
mode = "observe" if config.gateway_mode.value == "observe" else "enforce"
|
|
141
154
|
recorder = Recorder(
|
|
142
|
-
[_LogSink()], on_finding=
|
|
155
|
+
[_LogSink()], on_finding=store_finding(store, publish, on_commit), verdicts=True
|
|
143
156
|
)
|
|
157
|
+
guard = Guard(recorder=recorder, mode=mode, policy=policy, entries=entries)
|
|
158
|
+
# Tetrate Agent Router's contracts, on the same listener and token (ADR-0167).
|
|
159
|
+
routes = {EVALUATE_PATH: guardrail.route, LOGS_PATH: requestlog.route(guard)}
|
|
144
160
|
try:
|
|
145
|
-
server = make_server(
|
|
161
|
+
server = make_server(guard, *address, token, routes)
|
|
146
162
|
except OSError as error:
|
|
147
163
|
# The gateway fails open without us; scans and hooks must not stop too.
|
|
148
164
|
logger.error("gateway listener not started on %s:%s: %s", *address, error)
|
|
@@ -23,7 +23,8 @@ from __future__ import annotations
|
|
|
23
23
|
from collections.abc import Callable
|
|
24
24
|
from dataclasses import dataclass
|
|
25
25
|
|
|
26
|
-
from stacktrace.
|
|
26
|
+
from stacktrace.detector.rules import gateway_blockable
|
|
27
|
+
from stacktrace.gateway.analyzer import EntrySet, PolicyVerdict
|
|
27
28
|
from stacktrace.hooks.claude import policy_message
|
|
28
29
|
from stacktrace.policy_display import policy_rows
|
|
29
30
|
from stacktrace.sessions.access import GatewayToolCall
|
|
@@ -159,3 +160,34 @@ def runtime_inputs(runtime: PolicyRuntime) -> Callable[[], Inputs]:
|
|
|
159
160
|
return Inputs(policy, revision, None if refreshed is None else runtime.clock() - refreshed)
|
|
160
161
|
|
|
161
162
|
return read
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def runtime_entries(
|
|
166
|
+
runtime: PolicyRuntime, *, ttl_s: float = POLICY_TTL_S
|
|
167
|
+
) -> Callable[[], EntrySet]:
|
|
168
|
+
"""The rules whose entry blocks at the response check, each with its entry's
|
|
169
|
+
name, and the revision that published them.
|
|
170
|
+
|
|
171
|
+
The same time to live as the policy: a gateway stops trusting both together.
|
|
172
|
+
With no policy, a stale one, or no entry, nothing blocks (ADR-0159).
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
def read() -> EntrySet:
|
|
176
|
+
with runtime.cache.guard:
|
|
177
|
+
entries = runtime.cache.state.detection_rules
|
|
178
|
+
revision = runtime.cache.state.desired_revision
|
|
179
|
+
unified = runtime.cache.state.entries
|
|
180
|
+
refreshed = runtime.refreshed_at
|
|
181
|
+
if refreshed is None or runtime.clock() - refreshed > ttl_s:
|
|
182
|
+
return EntrySet()
|
|
183
|
+
blocking = [
|
|
184
|
+
e for e in entries if e.action == "block" and gateway_blockable(e.rule_id, "response")
|
|
185
|
+
]
|
|
186
|
+
names = {e.rule_id: e.name for e in blocking}
|
|
187
|
+
notify = {e.rule_id: e.notify for e in blocking}
|
|
188
|
+
# The unified policy's `notify` mutes every finding of its rule, not
|
|
189
|
+
# only a block (unified-policy.md, "Notification").
|
|
190
|
+
notify.update({e.rule_id: e.notify for e in unified})
|
|
191
|
+
return EntrySet(names, revision, notify)
|
|
192
|
+
|
|
193
|
+
return read
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Judge a hook's pending call against the rules a policy entry blocks (ADR-0158).
|
|
2
|
+
|
|
3
|
+
The hook sends one built-in call's input. This module rebuilds it as the one
|
|
4
|
+
call of a session, the way the gateway reads a model response, and asks the
|
|
5
|
+
shared pending-call judge (ADR-0159). The input is held for this one request:
|
|
6
|
+
nothing here logs, stores or raises it, and only the content-free detection
|
|
7
|
+
leaves (ADR-0006).
|
|
8
|
+
|
|
9
|
+
The session is keyed on the agent's own session id, and on its agent id when
|
|
10
|
+
the call runs inside a subagent, so a blocked finding is filed under the run
|
|
11
|
+
it belongs to rather than colliding with its parent's. Its working directory
|
|
12
|
+
is the launch project, never the call's `cwd`: destructive action reads its
|
|
13
|
+
workspace boundary and `$HOME` from it, and a `cd` during the session must
|
|
14
|
+
not move them. The call's own working directory is its `cwd`, as a
|
|
15
|
+
transcript records it, so a relative path resolves where the shell is. The
|
|
16
|
+
call's span is named by its `tool_use_id`, so each blocked call is its own
|
|
17
|
+
event in the store.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from collections.abc import Mapping
|
|
24
|
+
from dataclasses import dataclass, replace
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import TYPE_CHECKING
|
|
27
|
+
|
|
28
|
+
from stacktrace import __version__
|
|
29
|
+
from stacktrace.detector.finding import Detection, Evidence, SessionRef
|
|
30
|
+
from stacktrace.detector.inline import blocked, judge_pending
|
|
31
|
+
from stacktrace.detector.rules import COMPONENT_DENIALS
|
|
32
|
+
from stacktrace.gateway.formats import read
|
|
33
|
+
from stacktrace.gateway.session import AGENT_HEADER, SESSION_HEADER, build
|
|
34
|
+
from stacktrace.gateway.sink import Stamp
|
|
35
|
+
from stacktrace.hooks.claude import inspected
|
|
36
|
+
|
|
37
|
+
if TYPE_CHECKING:
|
|
38
|
+
from collections.abc import Callable
|
|
39
|
+
|
|
40
|
+
from stacktrace.daemon.policy_inputs import PolicyEntry
|
|
41
|
+
from stacktrace.daemon.policy_runtime import DecidedBy
|
|
42
|
+
|
|
43
|
+
#: Claude Code's session ids are UUIDs. Anything else is refused rather than
|
|
44
|
+
#: kept, because the id names the finding's session and a `:` would forge one.
|
|
45
|
+
_SESSION_ID = re.compile(r"[A-Za-z0-9-]{1,128}")
|
|
46
|
+
_TOOL_USE_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
|
|
47
|
+
#: Client-supplied, like the gateway's own agent header; a `:` would forge the
|
|
48
|
+
#: composed identity below.
|
|
49
|
+
_AGENT_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class PendingCall:
|
|
54
|
+
"""One validated hook call. Hold it for one request; never log it."""
|
|
55
|
+
|
|
56
|
+
agent_kind: str
|
|
57
|
+
session_id: str
|
|
58
|
+
agent_id: str | None
|
|
59
|
+
project_root: str
|
|
60
|
+
tool_name: str
|
|
61
|
+
tool_use_id: str
|
|
62
|
+
cwd: str
|
|
63
|
+
tool_input: Mapping[str, object]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def pending_call(action: Mapping[str, object]) -> PendingCall:
|
|
67
|
+
"""The call an `authorize` action carries, or `ValueError` on any wrong shape.
|
|
68
|
+
|
|
69
|
+
The error text is a fixed code, never a field's value.
|
|
70
|
+
"""
|
|
71
|
+
session_id, call = action.get("session_id"), action.get("call")
|
|
72
|
+
agent_kind, tool = action.get("agent_kind"), action.get("name")
|
|
73
|
+
agent_id = action.get("agent_id")
|
|
74
|
+
if not isinstance(session_id, str) or not _SESSION_ID.fullmatch(session_id):
|
|
75
|
+
raise ValueError("invalid_session")
|
|
76
|
+
# Malformed is dropped, not refused: losing the subagent's own identity
|
|
77
|
+
# costs only attribution, where refusing the call would cost the block.
|
|
78
|
+
if not isinstance(agent_id, str) or not _AGENT_ID.fullmatch(agent_id):
|
|
79
|
+
agent_id = None
|
|
80
|
+
if not isinstance(call, dict) or set(call) != {"tool_use_id", "cwd", "tool_input"}: # pyright: ignore[reportUnknownArgumentType]
|
|
81
|
+
raise ValueError("invalid_call")
|
|
82
|
+
tool_use_id, cwd, tool_input = call["tool_use_id"], call["cwd"], call["tool_input"]
|
|
83
|
+
if not isinstance(tool_use_id, str) or not _TOOL_USE_ID.fullmatch(tool_use_id):
|
|
84
|
+
raise ValueError("invalid_call")
|
|
85
|
+
if not isinstance(cwd, str) or len(cwd) > 4096 or "\x00" in cwd or not Path(cwd).is_absolute():
|
|
86
|
+
raise ValueError("invalid_call")
|
|
87
|
+
if not isinstance(tool_input, dict):
|
|
88
|
+
raise ValueError("invalid_call") # noqa: TRY004 - one refusal type, read by its caller
|
|
89
|
+
if (
|
|
90
|
+
not isinstance(agent_kind, str)
|
|
91
|
+
or not isinstance(tool, str)
|
|
92
|
+
or not inspected(agent_kind, tool)
|
|
93
|
+
):
|
|
94
|
+
raise ValueError("uninspected_tool")
|
|
95
|
+
return PendingCall(
|
|
96
|
+
agent_kind=agent_kind,
|
|
97
|
+
session_id=session_id,
|
|
98
|
+
agent_id=agent_id,
|
|
99
|
+
project_root=str(action["project_root"]),
|
|
100
|
+
tool_name=tool,
|
|
101
|
+
tool_use_id=tool_use_id,
|
|
102
|
+
cwd=cwd,
|
|
103
|
+
tool_input={str(k): v for k, v in tool_input.items()}, # pyright: ignore[reportUnknownVariableType]
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def judge(call: PendingCall, rules: frozenset[str]) -> tuple[Detection, ...]:
|
|
108
|
+
"""The detections of `rules` that the call would be, if it ran."""
|
|
109
|
+
if not rules:
|
|
110
|
+
return ()
|
|
111
|
+
request = {
|
|
112
|
+
"model": "stacktrace-hook",
|
|
113
|
+
"system": "",
|
|
114
|
+
"messages": [{"role": "user", "content": ""}],
|
|
115
|
+
}
|
|
116
|
+
response = {
|
|
117
|
+
"content": [
|
|
118
|
+
{
|
|
119
|
+
"type": "tool_use",
|
|
120
|
+
"id": call.tool_use_id,
|
|
121
|
+
"name": call.tool_name,
|
|
122
|
+
"input": dict(call.tool_input),
|
|
123
|
+
}
|
|
124
|
+
]
|
|
125
|
+
}
|
|
126
|
+
headers = {SESSION_HEADER: call.session_id}
|
|
127
|
+
if call.agent_id is not None:
|
|
128
|
+
headers[AGENT_HEADER] = call.agent_id
|
|
129
|
+
exchange = read(request, response, headers=headers, fmt="anthropic")
|
|
130
|
+
# Stated outright, not left to the system-prompt text above: a workspace
|
|
131
|
+
# path holding `\n` or `\r` (legal on POSIX) would otherwise truncate at
|
|
132
|
+
# `_WORKING_DIRECTORY`'s line boundary, misjudging a delete as inside the
|
|
133
|
+
# workspace when it is not (ADR-0158). `call.project_root` is this call's
|
|
134
|
+
# own launch root, not text recovered from a prompt.
|
|
135
|
+
exchange = replace(exchange, working_directory=call.project_root)
|
|
136
|
+
turn = build(exchange, pending_as_succeeded=True)
|
|
137
|
+
# The session header names one agent kind, and the call is read with that
|
|
138
|
+
# kind's tool table. A call from another kind is no call this can read.
|
|
139
|
+
if turn.session.agent_kind != call.agent_kind:
|
|
140
|
+
raise ValueError("unsupported_agent")
|
|
141
|
+
# A one-call session numbers every call alike, so the span is named by the
|
|
142
|
+
# agent's own call id: two blocked calls in one session are two events.
|
|
143
|
+
# `turn.session.session_id` is already `<session>:agent-<id>` for a
|
|
144
|
+
# subagent's call, so its finding files under its own identity, not its
|
|
145
|
+
# parent's -- the same composition `session_id_of` gives the gateway.
|
|
146
|
+
span = f"{turn.session.session_id}:{call.tool_use_id}:0"
|
|
147
|
+
pending = frozenset(turn.pending_spans)
|
|
148
|
+
session = replace(
|
|
149
|
+
turn.session,
|
|
150
|
+
turns=tuple(
|
|
151
|
+
replace(
|
|
152
|
+
t,
|
|
153
|
+
tool_calls=tuple(
|
|
154
|
+
replace(c, span=span, working_directory=call.cwd) if c.span in pending else c
|
|
155
|
+
for c in t.tool_calls
|
|
156
|
+
),
|
|
157
|
+
)
|
|
158
|
+
for t in turn.session.turns
|
|
159
|
+
),
|
|
160
|
+
)
|
|
161
|
+
return judge_pending(session, frozenset({span}) if pending else frozenset(), rules)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def inspect_call(action: dict[str, object], rules: frozenset[str]) -> tuple[Detection, ...]:
|
|
165
|
+
"""The policy runtime's `Inspector`: read the call, then judge it."""
|
|
166
|
+
return judge(pending_call(action), rules)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def blocked_recorder(
|
|
170
|
+
write: Callable[[Detection, Stamp], None],
|
|
171
|
+
remember: Callable[[str, str, str, str], bool],
|
|
172
|
+
forget: Callable[[str, str, str, str], None],
|
|
173
|
+
) -> Callable[[dict[str, object], Detection, DecidedBy, bool], None]:
|
|
174
|
+
"""Store each blocked finding as the gateway stores one: `action: blocked`.
|
|
175
|
+
|
|
176
|
+
`remember` keeps the call's agent kind, session, `tool_use_id` and rule
|
|
177
|
+
first, before the deny returns and the agent writes the call to its
|
|
178
|
+
transcript, so the scan drops every rule's finding on the call rather than
|
|
179
|
+
reporting it as completed (`docs/specs/inline-detection-enforcement.md`).
|
|
180
|
+
The scan reads the same `tool_use_id` back as the call's `provider_call_id`.
|
|
181
|
+
|
|
182
|
+
`remember` and `write` are two separate commits. If `write` fails after
|
|
183
|
+
`remember` lands, the marker would outlive the finding it stands for and
|
|
184
|
+
suppress a scan that never has anything to drop; `forget` undoes `remember`
|
|
185
|
+
so a later, working write can be seen. It undoes only a marker this call
|
|
186
|
+
inserted: a repeated call's marker stands for an earlier, stored finding.
|
|
187
|
+
|
|
188
|
+
`decided_by` keeps the shape Fleet declares today (`rules`, `policy_revision`).
|
|
189
|
+
The entry id joins it when Fleet declares that field. The audit finding is
|
|
190
|
+
stored either way; `notify` is the entry's own choice of whether it also
|
|
191
|
+
reaches Slack and the session (`docs/specs/inline-detection-enforcement.md`).
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
def record(
|
|
195
|
+
action: dict[str, object], detection: Detection, decided: DecidedBy, notify: bool
|
|
196
|
+
) -> None:
|
|
197
|
+
stamp = Stamp(
|
|
198
|
+
None,
|
|
199
|
+
"blocked",
|
|
200
|
+
{"rules": __version__, "policy_revision": decided.policy_revision},
|
|
201
|
+
notify=notify,
|
|
202
|
+
where="hook",
|
|
203
|
+
)
|
|
204
|
+
# The judged session's id, not the hook's: for a subagent's call it is
|
|
205
|
+
# `<session>:agent-<id>`, the session the scan reads the transcript as.
|
|
206
|
+
session = detection.session
|
|
207
|
+
call_id = pending_call(action).tool_use_id
|
|
208
|
+
inserted = remember(session.agent_kind, session.session_id, call_id, detection.rule_id)
|
|
209
|
+
try:
|
|
210
|
+
write(blocked(detection), stamp)
|
|
211
|
+
except Exception:
|
|
212
|
+
if inserted:
|
|
213
|
+
forget(session.agent_kind, session.session_id, call_id, detection.rule_id)
|
|
214
|
+
raise
|
|
215
|
+
|
|
216
|
+
return record
|
|
217
|
+
|
|
218
|
+
|
|
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
|
+
def component_denial_recorder(
|
|
225
|
+
write: Callable[[Detection, Stamp], None],
|
|
226
|
+
remember: Callable[[str, str, str, str], bool],
|
|
227
|
+
forget: Callable[[str, str, str, str], None],
|
|
228
|
+
) -> Callable[[dict[str, object], PolicyEntry, int], None]:
|
|
229
|
+
"""Store a component deny as its entry's finding: `action: blocked`, at the hook.
|
|
230
|
+
|
|
231
|
+
The finding cites the call by its `tool_use_id`, as a detection block does,
|
|
232
|
+
and `remember` keeps the call before the deny returns, so the scan drops
|
|
233
|
+
every rule's match on it, the vulnerability rule's included
|
|
234
|
+
(unified-policy.md, "The finding of a component deny"). Its title and
|
|
235
|
+
remediation are fixed per rule and name no component: a component's name
|
|
236
|
+
is configuration text. Ids of the wrong shape record nothing; the deny
|
|
237
|
+
stands either way.
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
def record(action: dict[str, object], entry: PolicyEntry, revision: int) -> None:
|
|
241
|
+
agent_kind, session_id = action.get("agent_kind"), action.get("session_id")
|
|
242
|
+
call_id, agent_id = action.get("tool_use_id"), action.get("agent_id")
|
|
243
|
+
if (
|
|
244
|
+
not isinstance(agent_kind, str)
|
|
245
|
+
or not isinstance(session_id, str)
|
|
246
|
+
or not _SESSION_ID.fullmatch(session_id)
|
|
247
|
+
or not isinstance(call_id, str)
|
|
248
|
+
or not _TOOL_USE_ID.fullmatch(call_id)
|
|
249
|
+
):
|
|
250
|
+
return
|
|
251
|
+
# Composed as the gateway composes a subagent's session, which is how
|
|
252
|
+
# the scan names it (`gateway/session.py`, `session_id_of`).
|
|
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,
|
|
264
|
+
)
|
|
265
|
+
stamp = Stamp(
|
|
266
|
+
None,
|
|
267
|
+
"blocked",
|
|
268
|
+
{"rules": __version__, "policy_revision": revision},
|
|
269
|
+
notify=entry.notify,
|
|
270
|
+
where="hook",
|
|
271
|
+
)
|
|
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
|
+
|
|
280
|
+
return record
|
stacktrace/daemon/observer.py
CHANGED
|
@@ -38,11 +38,13 @@ from stacktrace.correlate.orchestrate import (
|
|
|
38
38
|
advisory_attacher,
|
|
39
39
|
)
|
|
40
40
|
from stacktrace.cost.components import Placement, placement_of
|
|
41
|
+
from stacktrace.detector.reasoning import DENIAL_IS_EVIDENCE_FOR
|
|
41
42
|
from stacktrace.detector.render import detection_json, unknown_json
|
|
42
43
|
from stacktrace.detector.run import NO_ANALYZER
|
|
43
44
|
from stacktrace.sessions.access import IncrementalSessions, SessionView
|
|
45
|
+
from stacktrace.sessions.outcome import failed, succeeded
|
|
44
46
|
|
|
45
|
-
from .store import FindingStore, Notification, SessionKey
|
|
47
|
+
from .store import BlockedCall, FindingStore, Notification, SessionKey
|
|
46
48
|
|
|
47
49
|
|
|
48
50
|
@dataclass(frozen=True)
|
|
@@ -180,8 +182,12 @@ class SessionObserver:
|
|
|
180
182
|
composition_generation: Callable[[], int] | None = None,
|
|
181
183
|
pending_kinds: Callable[[], frozenset[str]] | None = None,
|
|
182
184
|
cold_read: Callable[[str], SessionView] | None = None,
|
|
185
|
+
muted: Callable[[], frozenset[str]] | None = None,
|
|
183
186
|
) -> None:
|
|
184
187
|
self.agent_kind = agent_kind
|
|
188
|
+
#: The rules whose policy entry says `notify: false`; their findings are
|
|
189
|
+
#: stored but never sent (`PolicyRuntime.muted`).
|
|
190
|
+
self._muted = muted or frozenset
|
|
185
191
|
self.store = store
|
|
186
192
|
self.publish = publish
|
|
187
193
|
self.attach_advisories = advisory_attacher(CachingAdvisoryLookup())
|
|
@@ -603,9 +609,13 @@ class SessionObserver:
|
|
|
603
609
|
# stays off. Enabling reasoning starts coverage from that point
|
|
604
610
|
# forward; it does not requeue what was already scanned while it was
|
|
605
611
|
# off.
|
|
612
|
+
muted = self._muted()
|
|
606
613
|
notifications = self.store.record(
|
|
607
614
|
collected.session,
|
|
608
|
-
|
|
615
|
+
tuple(
|
|
616
|
+
{**finding, "notify": False} if finding.get("rule_id") in muted else finding
|
|
617
|
+
for finding in result.findings
|
|
618
|
+
),
|
|
609
619
|
unknowns=result.unknowns,
|
|
610
620
|
working_directories=result.working_directories,
|
|
611
621
|
source_visible_at=collected.source_visible_at,
|
|
@@ -675,6 +685,7 @@ def analyse_batch(
|
|
|
675
685
|
analyzer: str = NO_ANALYZER,
|
|
676
686
|
attach_advisories: Any = None,
|
|
677
687
|
build_all: Any = None,
|
|
688
|
+
blocked: Callable[[tuple[SessionKey, ...]], frozenset[BlockedCall]] | None = None,
|
|
678
689
|
) -> dict[SessionKey, ScanResult]:
|
|
679
690
|
"""**One** analysis pass over every changed session, split per session.
|
|
680
691
|
|
|
@@ -692,6 +703,13 @@ def analyse_batch(
|
|
|
692
703
|
`reasoning`/`analyzer` default off (ADR-0081): the caller passes the
|
|
693
704
|
daemon's own resolved `DaemonConfig.reasoning_enabled`, so stage three
|
|
694
705
|
only runs when the operator opted in, `TYPESAFE_API_KEY` notwithstanding.
|
|
706
|
+
|
|
707
|
+
`blocked` answers which calls a hook blocked. Every rule's finding on such
|
|
708
|
+
a call is dropped here, except a rule in `DENIAL_IS_EVIDENCE_FOR`: the call
|
|
709
|
+
did not run, so no other match on it is evidence, and the blocking rule's
|
|
710
|
+
finding is already stored with the blocked wording (ADR-0165). A rule in
|
|
711
|
+
that set asks the opposite question — whether the denial itself disproves a
|
|
712
|
+
claim the session made — and dropping its finding would remove the proof.
|
|
695
713
|
"""
|
|
696
714
|
by_qualified_id = {item.qualified_id: item.session for item in collected}
|
|
697
715
|
analysis = analyse_sessions(
|
|
@@ -717,10 +735,36 @@ def analyse_batch(
|
|
|
717
735
|
directories: dict[SessionKey, list[Path]] = {}
|
|
718
736
|
placements: dict[SessionKey, dict[str, Placement]] = {}
|
|
719
737
|
|
|
738
|
+
# The agent's own id for each call that neither succeeded nor failed, by
|
|
739
|
+
# span. The hook remembered a block by that id: it cannot build OpenAIDR's
|
|
740
|
+
# span before the call is written. The row is written before the deny is
|
|
741
|
+
# sent, so a call whose deny never arrived ran; the transcript says so, and
|
|
742
|
+
# it stays -- whether the tool then reported success or its own failure. A
|
|
743
|
+
# call whose outcome reads as unknown still drops; this is a stated gap.
|
|
744
|
+
dropped = {
|
|
745
|
+
(session, call_id)
|
|
746
|
+
for session, call_id, _rule in (blocked(tuple(results)) if blocked is not None else ())
|
|
747
|
+
}
|
|
748
|
+
call_ids: dict[SessionKey, dict[str, str | None]] = {}
|
|
749
|
+
if dropped:
|
|
750
|
+
for correlated in analysis.view.sessions:
|
|
751
|
+
session = _for(correlated.session.session_id)
|
|
752
|
+
if session is not None:
|
|
753
|
+
call_ids.setdefault(session, {}).update(
|
|
754
|
+
(call.span, call.provider_call_id)
|
|
755
|
+
for turn in correlated.session.turns
|
|
756
|
+
for call in turn.tool_calls
|
|
757
|
+
if not succeeded(call) and not failed(call)
|
|
758
|
+
)
|
|
720
759
|
for finding in analysis.run.detections:
|
|
721
760
|
session = _for(finding.session.session_id)
|
|
722
|
-
if session is
|
|
723
|
-
|
|
761
|
+
if session is None:
|
|
762
|
+
continue
|
|
763
|
+
if dropped and finding.evidence and finding.rule_id not in DENIAL_IS_EVIDENCE_FOR:
|
|
764
|
+
call_id = call_ids.get(session, {}).get(finding.evidence[0].span)
|
|
765
|
+
if (session, call_id) in dropped:
|
|
766
|
+
continue
|
|
767
|
+
findings.setdefault(session, []).append(detection_json(finding))
|
|
724
768
|
for unknown in analysis.run.unknowns:
|
|
725
769
|
session = _for(unknown.session.session_id)
|
|
726
770
|
if session is not None:
|
|
@@ -37,6 +37,9 @@ def collector_available(agent_kind: str = "claude-code") -> bool:
|
|
|
37
37
|
collector = getattr(openaca.core, "collect_policy_evidence", None)
|
|
38
38
|
if not callable(collector):
|
|
39
39
|
return False
|
|
40
|
+
if agent_kind == "cursor":
|
|
41
|
+
# Releases before Cursor accept `agent_kind` but reject this kind at runtime.
|
|
42
|
+
return agent_kind in getattr(openaca.core, "POLICY_EVIDENCE_AGENT_KINDS", ())
|
|
40
43
|
return agent_kind != "codex" or "agent_kind" in inspect.signature(collector).parameters
|
|
41
44
|
|
|
42
45
|
|
|
@@ -120,6 +123,22 @@ def evaluate_bundle(
|
|
|
120
123
|
if scope.agent_kind == "codex":
|
|
121
124
|
entries.append((Entry("mcp_tool", name, "codex", blocked, rule, detail), 0))
|
|
122
125
|
continue
|
|
126
|
+
if scope.agent_kind == "cursor":
|
|
127
|
+
if component_type != "mcp_server" or ref.extra.get("enabled") is False:
|
|
128
|
+
continue
|
|
129
|
+
# Cursor names a plugin's server `plugin-<plugin>-<server>`, and a project
|
|
130
|
+
# server shadows a user server of the same name.
|
|
131
|
+
manifest = Path(ref.source_manifest).resolve()
|
|
132
|
+
if decision.controlled_by_plugin:
|
|
133
|
+
alias, rank = f"plugin-{decision.subject.ref.name}-{name}", 0
|
|
134
|
+
elif manifest == (Path(scope.project_root) / ".cursor" / "mcp.json").resolve():
|
|
135
|
+
alias, rank = name, 1
|
|
136
|
+
elif manifest == Path(scope.global_config).resolve():
|
|
137
|
+
alias, rank = name, 0
|
|
138
|
+
else:
|
|
139
|
+
continue
|
|
140
|
+
entries.append((Entry("mcp_tool", alias, "cursor", blocked, rule, detail), rank))
|
|
141
|
+
continue
|
|
123
142
|
owner = decision.subject.ref.name if decision.controlled_by_plugin else None
|
|
124
143
|
source = "plugin" if owner else _source(ref, scope)
|
|
125
144
|
rank = 1 if source in {"project", "local"} and not owner and ":" not in name else 0
|
|
@@ -329,7 +348,14 @@ def main() -> int:
|
|
|
329
348
|
# as the launching host, without mutating the resident daemon's env.
|
|
330
349
|
root = Path(scope.config_root)
|
|
331
350
|
target: Path | None = root
|
|
332
|
-
if scope.agent_kind == "
|
|
351
|
+
if scope.agent_kind == "cursor":
|
|
352
|
+
# OpenACA reads Cursor only from this home's root (its ADR-0054).
|
|
353
|
+
if root != (Path.home() / ".cursor").resolve() or Path(scope.global_config) != (
|
|
354
|
+
root / "mcp.json"
|
|
355
|
+
):
|
|
356
|
+
raise ValueError("invalid_global_config")
|
|
357
|
+
target = None
|
|
358
|
+
elif scope.agent_kind == "codex":
|
|
333
359
|
if Path(scope.global_config) != (root / "config.toml").resolve():
|
|
334
360
|
raise ValueError("invalid_global_config")
|
|
335
361
|
os.environ["CODEX_HOME"] = str(root)
|
|
@@ -354,7 +380,7 @@ def main() -> int:
|
|
|
354
380
|
os.dup2(quiet.fileno(), 2)
|
|
355
381
|
policy = parse_policy(request["document"])
|
|
356
382
|
options: dict[str, Any] = (
|
|
357
|
-
{"agent_kind": scope.agent_kind} if scope.agent_kind
|
|
383
|
+
{"agent_kind": scope.agent_kind} if scope.agent_kind != "claude-code" else {}
|
|
358
384
|
)
|
|
359
385
|
if "allow_partial_inventory" in inspect.signature(collector).parameters:
|
|
360
386
|
options["allow_partial_inventory"] = True
|
|
@@ -402,6 +428,16 @@ def main() -> int:
|
|
|
402
428
|
paths = sorted(
|
|
403
429
|
{*paths, *(p for name in builtins for p in builtin_claim_paths(scope, name))}
|
|
404
430
|
)
|
|
431
|
+
if scope.agent_kind == "cursor":
|
|
432
|
+
# Cursor caches each plugin at `<marketplace>/<plugin>/<version>`. A new
|
|
433
|
+
# plugin or version changes only the directory above it.
|
|
434
|
+
cache = root / "plugins" / "cache"
|
|
435
|
+
paths = sorted(
|
|
436
|
+
{
|
|
437
|
+
*paths,
|
|
438
|
+
*(str(p) for p in (*cache.glob("*"), *cache.glob("*/*")) if p.is_dir()),
|
|
439
|
+
}
|
|
440
|
+
)
|
|
405
441
|
os.dup2(saved_stdout, 1)
|
|
406
442
|
os.close(saved_stdout)
|
|
407
443
|
output = json.dumps(
|