stacktrace-cli 0.23.0__py3-none-any.whl → 0.24.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/agentspec/grants.py +16 -5
- stacktrace/agentspec/serve.py +6 -1
- stacktrace/analysis.py +7 -0
- stacktrace/cli.py +15 -1
- stacktrace/daemon/db.py +5 -0
- stacktrace/daemon/inline_hook.py +121 -16
- stacktrace/daemon/observer.py +76 -8
- stacktrace/daemon/policy_inputs.py +57 -0
- stacktrace/daemon/policy_result.py +36 -4
- stacktrace/daemon/policy_runtime.py +31 -34
- stacktrace/daemon/runtime.py +1 -0
- stacktrace/daemon/store.py +21 -3
- stacktrace/detector/deterministic.py +148 -1
- stacktrace/detector/hook_table.py +2 -0
- stacktrace/detector/inline.py +16 -16
- stacktrace/detector/profanity-en.txt +375 -0
- stacktrace/detector/profanity.py +234 -0
- stacktrace/detector/rules.py +105 -2
- stacktrace/detector/run.py +6 -2
- stacktrace/detector/settings.py +27 -0
- stacktrace/finding_titles.py +2 -0
- stacktrace/gateway/marker.py +53 -2
- stacktrace/hooks/claude.py +41 -6
- stacktrace/hooks/codex.py +5 -2
- stacktrace/hooks/cursor.py +5 -2
- stacktrace/hooks/devin.py +21 -5
- stacktrace/monitor/render.py +6 -1
- stacktrace/monitor/site/app.js +2 -0
- stacktrace/prompt_text.py +50 -0
- stacktrace/remote/sync_detect.py +8 -0
- {stacktrace_cli-0.23.0.dist-info → stacktrace_cli-0.24.0.dist-info}/METADATA +2 -2
- {stacktrace_cli-0.23.0.dist-info → stacktrace_cli-0.24.0.dist-info}/RECORD +35 -31
- {stacktrace_cli-0.23.0.dist-info → stacktrace_cli-0.24.0.dist-info}/WHEEL +0 -0
- {stacktrace_cli-0.23.0.dist-info → stacktrace_cli-0.24.0.dist-info}/entry_points.txt +0 -0
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
"""An admission answer, apart from the runtime
|
|
1
|
+
"""An admission answer, and the scope a hook sends, apart from the runtime.
|
|
2
2
|
|
|
3
|
-
The hook builds these
|
|
4
|
-
|
|
5
|
-
them
|
|
3
|
+
The hook builds these on every covered call, so this module imports only the
|
|
4
|
+
standard library (ADR-0194). `policy_runtime` imports them from here. Every
|
|
5
|
+
agent's hook adapter reads them, so none of them pays the runtime's import
|
|
6
|
+
time on a prompt (ADR-0226).
|
|
6
7
|
"""
|
|
7
8
|
|
|
8
9
|
from __future__ import annotations
|
|
9
10
|
|
|
10
11
|
from collections.abc import Callable
|
|
11
12
|
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
12
14
|
|
|
13
15
|
|
|
14
16
|
@dataclass(frozen=True)
|
|
@@ -40,3 +42,33 @@ class Result:
|
|
|
40
42
|
#: the agent reads as the call's result, and what the person is shown.
|
|
41
43
|
steer: str | None = None
|
|
42
44
|
notice: str | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
#: Each agent's global configuration file, under its configuration root.
|
|
48
|
+
GLOBAL_CONFIG = {
|
|
49
|
+
"claude-code": ".claude.json",
|
|
50
|
+
"codex": "config.toml",
|
|
51
|
+
"cursor": "mcp.json",
|
|
52
|
+
"devin": "config.json",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Scope:
|
|
58
|
+
config_root: str
|
|
59
|
+
project_root: str
|
|
60
|
+
global_config: str = ""
|
|
61
|
+
agent_kind: str = "claude-code"
|
|
62
|
+
|
|
63
|
+
def __post_init__(self) -> None:
|
|
64
|
+
if self.agent_kind not in GLOBAL_CONFIG:
|
|
65
|
+
raise ValueError("unsupported_agent")
|
|
66
|
+
if not self.global_config:
|
|
67
|
+
object.__setattr__(
|
|
68
|
+
self,
|
|
69
|
+
"global_config",
|
|
70
|
+
str(Path(self.config_root) / GLOBAL_CONFIG[self.agent_kind]),
|
|
71
|
+
)
|
|
72
|
+
for value in (self.config_root, self.project_root, self.global_config):
|
|
73
|
+
if not value or len(value) > 4096 or "\x00" in value or not Path(value).is_absolute():
|
|
74
|
+
raise ValueError("invalid_scope")
|
|
@@ -27,8 +27,9 @@ from stacktrace.daemon.policy_inputs import (
|
|
|
27
27
|
PolicyState,
|
|
28
28
|
Tenant,
|
|
29
29
|
off_rules,
|
|
30
|
+
rule_settings,
|
|
30
31
|
)
|
|
31
|
-
from stacktrace.daemon.policy_result import DecidedBy, Result
|
|
32
|
+
from stacktrace.daemon.policy_result import GLOBAL_CONFIG, DecidedBy, Result, Scope
|
|
32
33
|
from stacktrace.detector.rules import (
|
|
33
34
|
ADMISSION_RULES,
|
|
34
35
|
BLOCKABLE,
|
|
@@ -36,6 +37,7 @@ from stacktrace.detector.rules import (
|
|
|
36
37
|
POSTURE_RULE,
|
|
37
38
|
VULNERABILITY_RULE,
|
|
38
39
|
)
|
|
40
|
+
from stacktrace.detector.settings import NO_SETTINGS, RuleSettings
|
|
39
41
|
from stacktrace.package_logger import get_logger
|
|
40
42
|
from stacktrace.policy_display import default_description
|
|
41
43
|
from stacktrace.remote.config import ConfigError, RemoteConfig, load_remote_config
|
|
@@ -46,9 +48,12 @@ if TYPE_CHECKING:
|
|
|
46
48
|
from stacktrace.daemon.policy_engine import PolicyEngine
|
|
47
49
|
from stacktrace.detector.finding import Detection
|
|
48
50
|
|
|
49
|
-
#: Judges a hook's pending call for the given rules
|
|
50
|
-
#: `ValueError` with a fixed
|
|
51
|
-
|
|
51
|
+
#: Judges a hook's pending call for the given rules, each with its entry's
|
|
52
|
+
#: parsed parameters (ADR-0158, ADR-0228). It raises `ValueError` with a fixed
|
|
53
|
+
#: code for a call it cannot read.
|
|
54
|
+
Inspector = Callable[
|
|
55
|
+
[dict[str, object], Mapping[str, Mapping[str, object]]], "tuple[Detection, ...]"
|
|
56
|
+
]
|
|
52
57
|
#: Keeps a detection block's marker: the call, its detection, the entry that
|
|
53
58
|
#: blocked it, and the policy revision. For a tool call it writes no finding;
|
|
54
59
|
#: the scan does (ADR-0178). A blocked prompt still writes its own until
|
|
@@ -165,38 +170,11 @@ MAX_SCOPES = 64
|
|
|
165
170
|
#: How long `authorize` waits for one transcript to be read (ADR-0154).
|
|
166
171
|
CATCH_UP_TIMEOUT = 0.2
|
|
167
172
|
#: Agent kinds with a native admission adapter, and each one's global configuration file.
|
|
168
|
-
GLOBAL_CONFIG = {
|
|
169
|
-
"claude-code": ".claude.json",
|
|
170
|
-
"codex": "config.toml",
|
|
171
|
-
"cursor": "mcp.json",
|
|
172
|
-
"devin": "config.json",
|
|
173
|
-
}
|
|
174
173
|
#: Agent kinds whose evidence OpenACA does not collect. The worker never collects
|
|
175
174
|
#: for them, and the category default of the same policy decides each subject.
|
|
176
175
|
UNCOLLECTED = frozenset({"devin"})
|
|
177
176
|
|
|
178
177
|
|
|
179
|
-
@dataclass(frozen=True)
|
|
180
|
-
class Scope:
|
|
181
|
-
config_root: str
|
|
182
|
-
project_root: str
|
|
183
|
-
global_config: str = ""
|
|
184
|
-
agent_kind: str = "claude-code"
|
|
185
|
-
|
|
186
|
-
def __post_init__(self) -> None:
|
|
187
|
-
if self.agent_kind not in GLOBAL_CONFIG:
|
|
188
|
-
raise ValueError("unsupported_agent")
|
|
189
|
-
if not self.global_config:
|
|
190
|
-
object.__setattr__(
|
|
191
|
-
self,
|
|
192
|
-
"global_config",
|
|
193
|
-
str(Path(self.config_root) / GLOBAL_CONFIG[self.agent_kind]),
|
|
194
|
-
)
|
|
195
|
-
for value in (self.config_root, self.project_root, self.global_config):
|
|
196
|
-
if not value or len(value) > 4096 or "\x00" in value or not Path(value).is_absolute():
|
|
197
|
-
raise ValueError("invalid_scope")
|
|
198
|
-
|
|
199
|
-
|
|
200
178
|
@dataclass(frozen=True)
|
|
201
179
|
class Binding:
|
|
202
180
|
api_url: str
|
|
@@ -1029,7 +1007,9 @@ class PolicyRuntime:
|
|
|
1029
1007
|
return None
|
|
1030
1008
|
by_rule = {e.rule_id: e for e in entries}
|
|
1031
1009
|
try:
|
|
1032
|
-
|
|
1010
|
+
# Each rule with its own entry's parameters, from the snapshot that
|
|
1011
|
+
# decides the block, so a limit never comes from another revision.
|
|
1012
|
+
detections = self.inspector(action, {r: e.params for r, e in by_rule.items()})
|
|
1033
1013
|
except ValueError:
|
|
1034
1014
|
return Result("defer", "invalid_action")
|
|
1035
1015
|
except Exception as error: # noqa: BLE001 - a rule's bug is never a block
|
|
@@ -1085,7 +1065,7 @@ class PolicyRuntime:
|
|
|
1085
1065
|
prompt = pending_prompt(action)
|
|
1086
1066
|
except ValueError:
|
|
1087
1067
|
return
|
|
1088
|
-
if not prompt.subagent:
|
|
1068
|
+
if not prompt.subagent and prompt.whole:
|
|
1089
1069
|
self.engine.on_prompt(prompt.agent_kind, prompt.session_id, prompt.text)
|
|
1090
1070
|
|
|
1091
1071
|
def _engine_decision(
|
|
@@ -1136,7 +1116,9 @@ class PolicyRuntime:
|
|
|
1136
1116
|
{"transport": transport} if mcp and declares_remote_transport(transport) else {}
|
|
1137
1117
|
)
|
|
1138
1118
|
try:
|
|
1139
|
-
|
|
1119
|
+
# The engine judges tool calls, and no tool-call rule reads
|
|
1120
|
+
# an entry's parameters, so each rule is judged with none.
|
|
1121
|
+
detections = self.inspector({**action, **remote}, {r: {} for r in inspected})
|
|
1140
1122
|
except ValueError as error:
|
|
1141
1123
|
# The coded rules read Claude Code's and Codex's calls today. Another
|
|
1142
1124
|
# agent's call is still the engine's to judge; its built-in
|
|
@@ -1302,6 +1284,21 @@ class PolicyRuntime:
|
|
|
1302
1284
|
return entry.company_domains, f"policy entry {entry.id}"
|
|
1303
1285
|
return fallback, fallback_source
|
|
1304
1286
|
|
|
1287
|
+
def rule_settings(self) -> RuleSettings:
|
|
1288
|
+
"""What the current policy's entries give the rules that run only
|
|
1289
|
+
under one: the scan judges with it (ADR-0228, ADR-0229). Any failure
|
|
1290
|
+
to read the policy leaves those rules Off."""
|
|
1291
|
+
try:
|
|
1292
|
+
with _enrollment_lock(self.config_path, timeout=0.05):
|
|
1293
|
+
config = load_remote_config(self.config_path)
|
|
1294
|
+
self._read_inputs(config)
|
|
1295
|
+
if not config.token:
|
|
1296
|
+
return NO_SETTINGS
|
|
1297
|
+
with self.cache.guard:
|
|
1298
|
+
return rule_settings(self.cache.state)
|
|
1299
|
+
except (ConfigError, OSError, PolicyInputError, ValueError, sqlite3.Error):
|
|
1300
|
+
return NO_SETTINGS
|
|
1301
|
+
|
|
1305
1302
|
def off(self) -> frozenset[str]:
|
|
1306
1303
|
"""The rules that are Off (unified-policy.md, "Off, Detect and Block").
|
|
1307
1304
|
No pass records their findings, so none reaches the session, the
|
stacktrace/daemon/runtime.py
CHANGED
|
@@ -687,6 +687,7 @@ def run_daemon(
|
|
|
687
687
|
blocked=markers.read,
|
|
688
688
|
gate_conditions=policy.gate_conditions(),
|
|
689
689
|
company_domains=domains,
|
|
690
|
+
settings=policy.rule_settings(),
|
|
690
691
|
)
|
|
691
692
|
# Each witness sets its server's account record (ADR-0154). A
|
|
692
693
|
# failed write costs only the block, never the findings.
|
stacktrace/daemon/store.py
CHANGED
|
@@ -1177,8 +1177,9 @@ class FindingStore:
|
|
|
1177
1177
|
"INSERT OR IGNORE INTO blocked_calls"
|
|
1178
1178
|
" (agent_kind, session_id, call_id, rule_id, blocked_at, entry_id, entry_name,"
|
|
1179
1179
|
" policy_revision, outcome, decided_where, rules_version, component_kind,"
|
|
1180
|
-
" component_name, component_version, component_identity, gate_evidence
|
|
1181
|
-
"
|
|
1180
|
+
" component_name, component_version, component_identity, gate_evidence,"
|
|
1181
|
+
" rule_params)"
|
|
1182
|
+
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
1182
1183
|
(
|
|
1183
1184
|
marker.agent_kind,
|
|
1184
1185
|
marker.session_id,
|
|
@@ -1196,6 +1197,7 @@ class FindingStore:
|
|
|
1196
1197
|
component.version if component is not None else None,
|
|
1197
1198
|
component.identity if component is not None else None,
|
|
1198
1199
|
json.dumps(list(marker.gate_evidence)) if marker.gate_evidence else None,
|
|
1200
|
+
json.dumps(marker.rule_params) if marker.rule_params is not None else None,
|
|
1199
1201
|
),
|
|
1200
1202
|
)
|
|
1201
1203
|
return cursor.rowcount == 1
|
|
@@ -1203,7 +1205,7 @@ class FindingStore:
|
|
|
1203
1205
|
_MARKER_COLUMNS = (
|
|
1204
1206
|
"session_id, call_id, rule_id, entry_id, entry_name, policy_revision, outcome,"
|
|
1205
1207
|
" decided_where, rules_version, component_kind, component_name, component_version,"
|
|
1206
|
-
" component_identity, gate_evidence, paid_at, blocked_at"
|
|
1208
|
+
" component_identity, gate_evidence, paid_at, blocked_at, rule_params"
|
|
1207
1209
|
)
|
|
1208
1210
|
|
|
1209
1211
|
def blocked_calls(self, sessions: Sequence[SessionKey]) -> frozenset[Marker]:
|
|
@@ -2772,6 +2774,18 @@ def _stored_evidence(rule_id: str, stored: object) -> tuple[str, ...]:
|
|
|
2772
2774
|
return marked_ids(rule_id, ids) if isinstance(ids, list) else ()
|
|
2773
2775
|
|
|
2774
2776
|
|
|
2777
|
+
def _stored_params(stored: object) -> Mapping[str, object] | None:
|
|
2778
|
+
"""A marker's rule params as stored. A value that is not a JSON object
|
|
2779
|
+
reads as none, so an older row without them still reads as a marker."""
|
|
2780
|
+
if not isinstance(stored, str):
|
|
2781
|
+
return None
|
|
2782
|
+
try:
|
|
2783
|
+
params = json.loads(stored)
|
|
2784
|
+
except ValueError:
|
|
2785
|
+
return None
|
|
2786
|
+
return params if isinstance(params, dict) else None
|
|
2787
|
+
|
|
2788
|
+
|
|
2775
2789
|
def _marker_of(agent_kind: str, row: Sequence[object]) -> Marker:
|
|
2776
2790
|
"""One `blocked_calls` row as the marker it stores (`FindingStore._MARKER_COLUMNS`)."""
|
|
2777
2791
|
(
|
|
@@ -2791,6 +2805,7 @@ def _marker_of(agent_kind: str, row: Sequence[object]) -> Marker:
|
|
|
2791
2805
|
evidence,
|
|
2792
2806
|
paid_at,
|
|
2793
2807
|
blocked_at,
|
|
2808
|
+
params,
|
|
2794
2809
|
) = row
|
|
2795
2810
|
known = outcome in ("blocked", "observed") and where in ("hook", "gateway")
|
|
2796
2811
|
return Marker(
|
|
@@ -2801,6 +2816,7 @@ def _marker_of(agent_kind: str, row: Sequence[object]) -> Marker:
|
|
|
2801
2816
|
entry_id=entry_id if isinstance(entry_id, str) else None,
|
|
2802
2817
|
entry_name=entry_name if isinstance(entry_name, str) else None,
|
|
2803
2818
|
policy_revision=revision if isinstance(revision, int) else None,
|
|
2819
|
+
rule_params=_stored_params(params),
|
|
2804
2820
|
outcome=outcome if known else None, # pyright: ignore[reportArgumentType]
|
|
2805
2821
|
where=where if known else None, # pyright: ignore[reportArgumentType]
|
|
2806
2822
|
rules_version=rules if isinstance(rules, str) else None,
|
|
@@ -2844,6 +2860,7 @@ _SPOOLED = (
|
|
|
2844
2860
|
"gate_evidence",
|
|
2845
2861
|
"paid_at",
|
|
2846
2862
|
"blocked_at",
|
|
2863
|
+
"rule_params",
|
|
2847
2864
|
)
|
|
2848
2865
|
|
|
2849
2866
|
|
|
@@ -2869,6 +2886,7 @@ def marker_json(marker: Marker) -> dict[str, object]:
|
|
|
2869
2886
|
"gate_evidence": json.dumps(list(marker.gate_evidence)) if marker.gate_evidence else None,
|
|
2870
2887
|
"paid_at": None,
|
|
2871
2888
|
"blocked_at": marker.blocked_at.isoformat() if marker.blocked_at is not None else None,
|
|
2889
|
+
"rule_params": json.dumps(marker.rule_params) if marker.rule_params is not None else None,
|
|
2872
2890
|
}
|
|
2873
2891
|
|
|
2874
2892
|
|
|
@@ -91,6 +91,7 @@ from stacktrace.detector.persistence_files import MIXED_KINDS as PERSISTENCE_MIX
|
|
|
91
91
|
from stacktrace.detector.persistence_files import git_setting_runs_code, runs_code
|
|
92
92
|
from stacktrace.detector.persistence_files import kind_of as persistence_kind
|
|
93
93
|
from stacktrace.detector.personal_data import CHECKSUMMED, find_personal_data
|
|
94
|
+
from stacktrace.detector.profanity import Profanity, find_profanity
|
|
94
95
|
from stacktrace.detector.rules import WORDING, title_of
|
|
95
96
|
from stacktrace.detector.secret_paths import folder_kind, glob_kind, has_glob, kind_of
|
|
96
97
|
from stacktrace.detector.secret_refs import (
|
|
@@ -102,6 +103,7 @@ from stacktrace.detector.secret_refs import (
|
|
|
102
103
|
unquoted,
|
|
103
104
|
)
|
|
104
105
|
from stacktrace.detector.secrets import _MAX_DEPTH, SecretMatch, find_secrets
|
|
106
|
+
from stacktrace.detector.settings import NO_SETTINGS, RuleSettings
|
|
105
107
|
from stacktrace.detector.wipers import (
|
|
106
108
|
Reach,
|
|
107
109
|
Wiper,
|
|
@@ -122,6 +124,7 @@ from stacktrace.finding_contract import (
|
|
|
122
124
|
FindingTarget,
|
|
123
125
|
)
|
|
124
126
|
from stacktrace.finding_titles import MAX_FINDING_TARGETS, title_for
|
|
127
|
+
from stacktrace.prompt_text import is_relayed
|
|
125
128
|
from stacktrace.sessions.lineage import parent_session_id
|
|
126
129
|
from stacktrace.sessions.outcome import (
|
|
127
130
|
denied,
|
|
@@ -995,7 +998,10 @@ def _reads_a_truncated_result(call: ToolCallLike) -> bool:
|
|
|
995
998
|
|
|
996
999
|
|
|
997
1000
|
def run_deterministic(
|
|
998
|
-
session: SessionLike,
|
|
1001
|
+
session: SessionLike,
|
|
1002
|
+
*,
|
|
1003
|
+
company_domains: frozenset[str] | None = None,
|
|
1004
|
+
settings: RuleSettings = NO_SETTINGS,
|
|
999
1005
|
) -> tuple[tuple[Detection, ...], tuple[Unknown, ...]]:
|
|
1000
1006
|
"""Run every deterministic rule over one session.
|
|
1001
1007
|
|
|
@@ -1008,6 +1014,10 @@ def run_deterministic(
|
|
|
1008
1014
|
MCP server's account against. `None` reads `STACKTRACE_COMPANY_DOMAINS`,
|
|
1009
1015
|
so the daemon and the gateway need no setting of their own; unset, the
|
|
1010
1016
|
rule is off.
|
|
1017
|
+
|
|
1018
|
+
`settings` carries what the policy's entries give the prompt length and
|
|
1019
|
+
profanity rules. With none, the default, both are Off: each runs only when
|
|
1020
|
+
a Detect or Block entry sets it (ADR-0228, ADR-0229).
|
|
1011
1021
|
"""
|
|
1012
1022
|
if company_domains is None:
|
|
1013
1023
|
company_domains = configured_company_domains()
|
|
@@ -1050,6 +1060,8 @@ def run_deterministic(
|
|
|
1050
1060
|
detections.extend(_unknown_install(session, ref))
|
|
1051
1061
|
detections.extend(_credential_in_prompt(session, ref))
|
|
1052
1062
|
detections.extend(_pii_in_prompt(session, ref))
|
|
1063
|
+
detections.extend(_prompt_too_long(session, ref, settings.prompt_max_chars))
|
|
1064
|
+
detections.extend(_profanity_in_prompt(session, ref, settings.profanity))
|
|
1053
1065
|
detections.extend(_credential_switched(session, ref))
|
|
1054
1066
|
detections.extend(_mcp_personal_account(session, ref, company_domains))
|
|
1055
1067
|
return tuple(detections), tuple(unknowns)
|
|
@@ -4592,6 +4604,141 @@ def _pii_in_prompt(session: SessionLike, ref: SessionRef) -> tuple[Detection, ..
|
|
|
4592
4604
|
return tuple(detections)
|
|
4593
4605
|
|
|
4594
4606
|
|
|
4607
|
+
def _prompt_too_long(
|
|
4608
|
+
session: SessionLike, ref: SessionRef, max_chars: int | None
|
|
4609
|
+
) -> tuple[Detection, ...]:
|
|
4610
|
+
"""A typed prompt with more characters than its policy entry's limit.
|
|
4611
|
+
|
|
4612
|
+
Off with no limit (ADR-0228). It reads the prompts the two leak rules
|
|
4613
|
+
read, except a relay block, which Claude Code submits for someone other
|
|
4614
|
+
than the person (prompt-guards.md, "Relay blocks").
|
|
4615
|
+
"""
|
|
4616
|
+
if max_chars is None or _is_subagent(session):
|
|
4617
|
+
return ()
|
|
4618
|
+
detections: list[Detection] = []
|
|
4619
|
+
for turn in _prompt_turns(session):
|
|
4620
|
+
text = turn.text
|
|
4621
|
+
if len(text) <= max_chars or is_relayed(text):
|
|
4622
|
+
continue
|
|
4623
|
+
detections.append(prompt_length_detection(session, turn, len(text), max_chars, ref=ref))
|
|
4624
|
+
return tuple(detections)
|
|
4625
|
+
|
|
4626
|
+
|
|
4627
|
+
def prompt_length_detection(
|
|
4628
|
+
session: SessionLike,
|
|
4629
|
+
turn: TurnLike,
|
|
4630
|
+
length: int,
|
|
4631
|
+
max_chars: int,
|
|
4632
|
+
*,
|
|
4633
|
+
ref: SessionRef | None = None,
|
|
4634
|
+
) -> Detection:
|
|
4635
|
+
"""The finding of one prompt of `length` characters over `max_chars`.
|
|
4636
|
+
|
|
4637
|
+
Shared with the hook's judge of a prompt over 1 MiB, which has the count
|
|
4638
|
+
and not the text (prompt-guards.md, "A prompt over 1 MiB"). Two numbers,
|
|
4639
|
+
and nothing of the prompt.
|
|
4640
|
+
"""
|
|
4641
|
+
return Detection(
|
|
4642
|
+
rule_id="stacktrace-prompt-too-long",
|
|
4643
|
+
severity="medium",
|
|
4644
|
+
confidence="high",
|
|
4645
|
+
title=title_of("stacktrace-prompt-too-long"),
|
|
4646
|
+
label=WORDING["stacktrace-prompt-too-long"].name,
|
|
4647
|
+
session=ref if ref is not None else _session_ref(session),
|
|
4648
|
+
evidence=(
|
|
4649
|
+
Evidence(
|
|
4650
|
+
span=_prompt_span(session, turn, 0),
|
|
4651
|
+
kind="prompt_length",
|
|
4652
|
+
detail=prompt_length_detail(length, max_chars),
|
|
4653
|
+
turn=turn.position,
|
|
4654
|
+
),
|
|
4655
|
+
),
|
|
4656
|
+
remediation=WORDING["stacktrace-prompt-too-long"].fix,
|
|
4657
|
+
verdict=_VERDICT,
|
|
4658
|
+
)
|
|
4659
|
+
|
|
4660
|
+
|
|
4661
|
+
#: Where a counted prompt went, as the two acceptable-use rules' details say
|
|
4662
|
+
#: it. A blocked finding names the block in its place (`inline.blocked`), and
|
|
4663
|
+
#: keeps the numbers (prompt-guards.md, "What a finding counts").
|
|
4664
|
+
PROMPT_SENT = "in a prompt sent to the model"
|
|
4665
|
+
|
|
4666
|
+
|
|
4667
|
+
def prompt_length_detail(chars: int, limit: int, where: str = PROMPT_SENT) -> str:
|
|
4668
|
+
"""The length rule's detail: the prompt's count and the limit, never its text."""
|
|
4669
|
+
return f"{chars:,} characters {where}, over the limit of {limit:,}"
|
|
4670
|
+
|
|
4671
|
+
|
|
4672
|
+
def profanity_detail(count: int, where: str = PROMPT_SENT) -> str:
|
|
4673
|
+
"""The profanity rule's detail: how many listed words, never one of them."""
|
|
4674
|
+
return f"{count} {'word' if count == 1 else 'words'} from the profanity list {where}"
|
|
4675
|
+
|
|
4676
|
+
|
|
4677
|
+
_LENGTH_COUNTS = re.compile(r"([0-9][0-9,]*) characters .+, over the limit of ([0-9][0-9,]*)")
|
|
4678
|
+
_PROFANITY_COUNTS = re.compile(r"([0-9]+) words? from the profanity list .+")
|
|
4679
|
+
|
|
4680
|
+
|
|
4681
|
+
def prompt_counts(rule_id: str, detail: str) -> dict[str, int]:
|
|
4682
|
+
"""The numbers in a detail that `prompt_length_detail` or
|
|
4683
|
+
`profanity_detail` wrote, by name; empty for any other detail. A prompt
|
|
4684
|
+
block's marker keeps them, so its finding counts what was blocked."""
|
|
4685
|
+
if rule_id == "stacktrace-prompt-too-long":
|
|
4686
|
+
match = _LENGTH_COUNTS.fullmatch(detail)
|
|
4687
|
+
if match:
|
|
4688
|
+
return {
|
|
4689
|
+
"chars": int(match[1].replace(",", "")),
|
|
4690
|
+
"limit": int(match[2].replace(",", "")),
|
|
4691
|
+
}
|
|
4692
|
+
elif rule_id == "stacktrace-profanity-in-prompt":
|
|
4693
|
+
match = _PROFANITY_COUNTS.fullmatch(detail)
|
|
4694
|
+
if match:
|
|
4695
|
+
return {"words": int(match[1])}
|
|
4696
|
+
return {}
|
|
4697
|
+
|
|
4698
|
+
|
|
4699
|
+
def _profanity_in_prompt(
|
|
4700
|
+
session: SessionLike, ref: SessionRef, words: Profanity | None
|
|
4701
|
+
) -> tuple[Detection, ...]:
|
|
4702
|
+
"""Profanity in a typed prompt: a word from the list, through its
|
|
4703
|
+
disguises (`profanity.py`). Off with no word list (ADR-0229).
|
|
4704
|
+
|
|
4705
|
+
The same prompts the length rule reads, every character of each, as the
|
|
4706
|
+
personal-data rule reads them. The hook reads less (`INLINE_READ_CHARS`,
|
|
4707
|
+
ADR-0226). The finding names how many, never a word.
|
|
4708
|
+
"""
|
|
4709
|
+
if words is None or _is_subagent(session):
|
|
4710
|
+
return ()
|
|
4711
|
+
detections: list[Detection] = []
|
|
4712
|
+
for turn in _prompt_turns(session):
|
|
4713
|
+
text = turn.text
|
|
4714
|
+
if is_relayed(text):
|
|
4715
|
+
continue
|
|
4716
|
+
count = len(find_profanity(text, words))
|
|
4717
|
+
if not count:
|
|
4718
|
+
continue
|
|
4719
|
+
detections.append(
|
|
4720
|
+
Detection(
|
|
4721
|
+
rule_id="stacktrace-profanity-in-prompt",
|
|
4722
|
+
severity="medium",
|
|
4723
|
+
confidence="high",
|
|
4724
|
+
title=title_of("stacktrace-profanity-in-prompt"),
|
|
4725
|
+
label=WORDING["stacktrace-profanity-in-prompt"].name,
|
|
4726
|
+
session=ref,
|
|
4727
|
+
evidence=(
|
|
4728
|
+
Evidence(
|
|
4729
|
+
span=_prompt_span(session, turn, 0),
|
|
4730
|
+
kind="profanity",
|
|
4731
|
+
detail=profanity_detail(count),
|
|
4732
|
+
turn=turn.position,
|
|
4733
|
+
),
|
|
4734
|
+
),
|
|
4735
|
+
remediation=WORDING["stacktrace-profanity-in-prompt"].fix,
|
|
4736
|
+
verdict=_VERDICT,
|
|
4737
|
+
)
|
|
4738
|
+
)
|
|
4739
|
+
return tuple(detections)
|
|
4740
|
+
|
|
4741
|
+
|
|
4595
4742
|
# --- credential-switched -------------------------------------------------------
|
|
4596
4743
|
|
|
4597
4744
|
_AUTH_FAILURE_WORDS = (
|
|
@@ -24,6 +24,8 @@ DENY_NAMES: Mapping[str, str] = MappingProxyType(
|
|
|
24
24
|
"stacktrace-unknown-install": "Unknown package or remote script installed",
|
|
25
25
|
"stacktrace-credential-in-prompt": "Credential in a prompt",
|
|
26
26
|
"stacktrace-pii-in-prompt": "Personal data in a prompt",
|
|
27
|
+
"stacktrace-prompt-too-long": "Prompt over the length limit",
|
|
28
|
+
"stacktrace-profanity-in-prompt": "Profanity in a prompt",
|
|
27
29
|
"stacktrace-mcp-personal-account": "MCP server on a non-company account",
|
|
28
30
|
}
|
|
29
31
|
)
|
stacktrace/detector/inline.py
CHANGED
|
@@ -10,17 +10,18 @@ pending call. Those rules run again on the completed turn, after the fact.
|
|
|
10
10
|
|
|
11
11
|
from __future__ import annotations
|
|
12
12
|
|
|
13
|
-
import hashlib
|
|
14
13
|
from dataclasses import replace
|
|
15
14
|
|
|
16
15
|
from stacktrace.correlate.observed import declares_remote_transport
|
|
17
16
|
from stacktrace.detector.deterministic import (
|
|
17
|
+
PROMPT_SENT,
|
|
18
18
|
blocked_sent_to,
|
|
19
19
|
declared_egress_of,
|
|
20
20
|
run_deterministic,
|
|
21
21
|
)
|
|
22
22
|
from stacktrace.detector.finding import Detection, Evidence
|
|
23
|
-
from stacktrace.detector.rules import BLOCKABLE, COMPONENT_DENIALS, Blocking
|
|
23
|
+
from stacktrace.detector.rules import ACCEPTABLE_USE_RULES, BLOCKABLE, COMPONENT_DENIALS, Blocking
|
|
24
|
+
from stacktrace.detector.settings import NO_SETTINGS, RuleSettings
|
|
24
25
|
from stacktrace.sessions.protocols import SessionLike
|
|
25
26
|
|
|
26
27
|
|
|
@@ -31,6 +32,7 @@ def judge_pending(
|
|
|
31
32
|
*,
|
|
32
33
|
prompt: str | None = None,
|
|
33
34
|
declared_transport: str | None = None,
|
|
35
|
+
settings: RuleSettings = NO_SETTINGS,
|
|
34
36
|
) -> tuple[Detection, ...]:
|
|
35
37
|
"""The detections of `rules` that cite a call in `pending`, or the prompt
|
|
36
38
|
turn whose key is `prompt`, in `BLOCKABLE` order.
|
|
@@ -43,12 +45,17 @@ def judge_pending(
|
|
|
43
45
|
transport of its own is also read by the declared-transport rule
|
|
44
46
|
(ADR-0134, ADR-0195), beside `run_deterministic`, as `run_detector` reads
|
|
45
47
|
it after the fact. The transport is never written into the call.
|
|
48
|
+
|
|
49
|
+
`settings` carries the Block entries' parameters for the rules that run
|
|
50
|
+
only under an entry; with none they are Off (ADR-0228).
|
|
46
51
|
"""
|
|
47
52
|
if (not pending and prompt is None) or not rules:
|
|
48
53
|
return ()
|
|
49
54
|
# No company domains: no rule judged here reads them, and a mistyped
|
|
50
55
|
# STACKTRACE_COMPANY_DOMAINS must not cost a block (ADR-0152).
|
|
51
|
-
detections, _unknowns = run_deterministic(
|
|
56
|
+
detections, _unknowns = run_deterministic(
|
|
57
|
+
session, company_domains=frozenset(), settings=settings
|
|
58
|
+
)
|
|
52
59
|
if declares_remote_transport(declared_transport):
|
|
53
60
|
detections = [
|
|
54
61
|
*detections,
|
|
@@ -114,19 +121,12 @@ _NAMES_DESTINATION = {"stacktrace-credential-egress": False, "stacktrace-pii-egr
|
|
|
114
121
|
|
|
115
122
|
def _blocked_detail(rule_id: str, rule: Blocking, evidence: Evidence) -> str:
|
|
116
123
|
"""A blocked citation's detail: where the call would have gone, for an
|
|
117
|
-
egress rule whose citation names it,
|
|
124
|
+
egress rule whose citation names it, the numbers for an acceptable-use
|
|
125
|
+
rule, else the rule's fixed words."""
|
|
126
|
+
if rule_id in ACCEPTABLE_USE_RULES and PROMPT_SENT in evidence.detail:
|
|
127
|
+
# The count and the limit stay; only where the prompt went changes
|
|
128
|
+
# (prompt-guards.md, "What a finding counts").
|
|
129
|
+
return evidence.detail.replace(PROMPT_SENT, rule.blocked_detail)
|
|
118
130
|
counted = _NAMES_DESTINATION.get(rule_id)
|
|
119
131
|
named = None if counted is None else blocked_sent_to(evidence.detail, counted=counted)
|
|
120
132
|
return named or rule.blocked_detail
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
def prompt_digest(text: str) -> str:
|
|
124
|
-
"""The SHA-256 of a prompt's text: how a blocked prompt's marker names
|
|
125
|
-
it, and how the scan names the transcript turn it compares
|
|
126
|
-
(`gateway/marker.py`, `prompt_key`).
|
|
127
|
-
|
|
128
|
-
One function for both sides, so they cannot hash differently. A hook's
|
|
129
|
-
JSON can carry a lone surrogate; `surrogatepass` hashes it rather than
|
|
130
|
-
raising, which would let the prompt continue unjudged.
|
|
131
|
-
"""
|
|
132
|
-
return hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()
|