xtrom-engine 0.3.1__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.
- xtrom/__init__.py +12 -0
- xtrom/allowances.py +63 -0
- xtrom/brokers/__init__.py +217 -0
- xtrom/brokers/_http.py +266 -0
- xtrom/cli_fuzz.py +169 -0
- xtrom/cli_fuzz_cross.py +306 -0
- xtrom/core.py +1519 -0
- xtrom/interfaces/__init__.py +42 -0
- xtrom/interfaces/corpus_sink.py +147 -0
- xtrom/interfaces/idp_broker.py +118 -0
- xtrom/interfaces/policy_engine.py +120 -0
- xtrom/memory.py +178 -0
- xtrom/reason_text.json +30 -0
- xtrom/sinks/__init__.py +325 -0
- xtrom/telemetry/__init__.py +169 -0
- xtrom_engine-0.3.1.dist-info/METADATA +142 -0
- xtrom_engine-0.3.1.dist-info/RECORD +19 -0
- xtrom_engine-0.3.1.dist-info/WHEEL +4 -0
- xtrom_engine-0.3.1.dist-info/licenses/LICENSE +190 -0
xtrom/core.py
ADDED
|
@@ -0,0 +1,1519 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Xtrom Core — deterministic runtime enforcement engine for AI agents.
|
|
3
|
+
|
|
4
|
+
The differentiator: we do NOT try to detect malicious text. We track data
|
|
5
|
+
*provenance* (taint / information-flow control) and enforce deterministically at
|
|
6
|
+
the tool-call boundary. Untrusted data can never parameterize a sensitive action,
|
|
7
|
+
and secrets can never leave via a non-allowlisted egress — regardless of wording.
|
|
8
|
+
|
|
9
|
+
This is the productized, developer-friendly form of the CaMeL / IFC research line.
|
|
10
|
+
Pure-Python reference implementation; the hot path is intended to be reimplemented
|
|
11
|
+
in Go for the inline gateway (see ARCHITECTURE.md). No ML required for the guarantee.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import collections
|
|
16
|
+
import base64
|
|
17
|
+
import functools
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import re
|
|
22
|
+
import time
|
|
23
|
+
import uuid
|
|
24
|
+
import urllib.parse
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from enum import Enum
|
|
27
|
+
from typing import Any, Callable, Iterable
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# ─────────────────────────────── labels ────────────────────────────────
|
|
31
|
+
class Trust(str, Enum):
|
|
32
|
+
TRUSTED = "TRUSTED" # system prompt, verified user input, config
|
|
33
|
+
UNTRUSTED = "UNTRUSTED" # web, email, RAG, file contents, tool outputs
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Sensitivity(int, Enum):
|
|
37
|
+
LOW = 0 # read-only, local, reversible
|
|
38
|
+
MEDIUM = 1 # writes, non-prod mutations
|
|
39
|
+
HIGH = 2 # egress, money, prod infra, credential use
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Label:
|
|
44
|
+
"""Provenance label attached to every value flowing through an agent."""
|
|
45
|
+
trust: Trust
|
|
46
|
+
is_secret: bool
|
|
47
|
+
origin: str # human-readable source, e.g. "file:README.md"
|
|
48
|
+
derived_from: tuple[str, ...] = () # ids of parent values (the taint graph)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def join(labels: Iterable[Label]) -> Label:
|
|
52
|
+
"""Lattice join: derived value is UNTRUSTED if ANY parent is untrusted,
|
|
53
|
+
and SECRET if ANY parent is secret. This is how taint propagates."""
|
|
54
|
+
labels = list(labels)
|
|
55
|
+
trust = Trust.UNTRUSTED if any(l.trust is Trust.UNTRUSTED for l in labels) else Trust.TRUSTED
|
|
56
|
+
is_secret = any(l.is_secret for l in labels)
|
|
57
|
+
origins = ", ".join(dict.fromkeys(l.origin for l in labels))
|
|
58
|
+
derived = tuple(x for l in labels for x in (l.derived_from or (l.origin,)))
|
|
59
|
+
return Label(trust=trust, is_secret=is_secret, origin=origins, derived_from=derived)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Value:
|
|
64
|
+
"""A tainted value: the data plus its provenance label."""
|
|
65
|
+
data: Any
|
|
66
|
+
label: Label
|
|
67
|
+
id: str = field(default_factory=lambda: "val_" + uuid.uuid4().hex[:8])
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# ───────────────────────── secret / entropy detection (L0) ─────────────────────────
|
|
71
|
+
_SECRET_PATTERNS = [
|
|
72
|
+
re.compile(r"AKIA[0-9A-Z]{16}"), # AWS access key id
|
|
73
|
+
re.compile(r"(?i)aws_secret_access_key"),
|
|
74
|
+
re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}"), # GitHub tokens
|
|
75
|
+
re.compile(r"sk-[A-Za-z0-9]{20,}"), # OpenAI-style keys
|
|
76
|
+
re.compile(r"-----BEGIN (?:RSA |EC )?PRIVATE KEY-----"),
|
|
77
|
+
re.compile(r"(?i)(password|passwd|secret|api[_-]?key|token)\s*[=:]\s*\S+"),
|
|
78
|
+
re.compile(r"postgres(?:ql)?://\S+:\S+@\S+"), # DB URLs with creds
|
|
79
|
+
# Any URL carrying a password (user:pass@). Starts at the literal "://": a leading scheme class would be
|
|
80
|
+
# retried from every position of a long run of letters (quadratic on hostile input).
|
|
81
|
+
re.compile(r"://[^\s/:@]+:[^\s/@]+@"),
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
_ENCODED_SECRET_MIN_LEN = 6
|
|
85
|
+
_ENCODING_TOKEN_RX = re.compile(r"[A-Za-z0-9+/_%-]{8,}={0,2}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _b64_nopad(s: str) -> str:
|
|
89
|
+
return s.rstrip("=")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
_ENCODINGS: tuple[tuple[str, Callable[[str], str]], ...] = (
|
|
93
|
+
("base64", lambda s: base64.b64encode(s.encode()).decode()),
|
|
94
|
+
("base64_nopad", lambda s: _b64_nopad(base64.b64encode(s.encode()).decode())),
|
|
95
|
+
("base64url", lambda s: base64.urlsafe_b64encode(s.encode()).decode()),
|
|
96
|
+
("base64url_nopad", lambda s: _b64_nopad(base64.urlsafe_b64encode(s.encode()).decode())),
|
|
97
|
+
("hex_lower", lambda s: s.encode().hex()),
|
|
98
|
+
("hex_upper", lambda s: s.encode().hex().upper()),
|
|
99
|
+
("url_percent", lambda s: urllib.parse.quote(s, safe="")),
|
|
100
|
+
("reversed", lambda s: s[::-1]),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def encoded_variants(secret: Any, min_len: int = _ENCODED_SECRET_MIN_LEN) -> tuple[str, ...]:
|
|
105
|
+
"""Common one-step encodings of a registered secret, computed at registration time.
|
|
106
|
+
|
|
107
|
+
Short secrets are skipped to avoid noisy substring matches (exact whole-value fingerprinting
|
|
108
|
+
still applies elsewhere). Split/chunked secrets are intentionally out of scope.
|
|
109
|
+
"""
|
|
110
|
+
s = _safe_str(secret)
|
|
111
|
+
if len(s) < min_len:
|
|
112
|
+
return ()
|
|
113
|
+
out = {s}
|
|
114
|
+
for _, fn in _ENCODINGS:
|
|
115
|
+
try:
|
|
116
|
+
v = fn(s)
|
|
117
|
+
if len(v) >= min_len:
|
|
118
|
+
out.add(v)
|
|
119
|
+
except Exception: # noqa: BLE001 — a codec failure must not break registration
|
|
120
|
+
pass
|
|
121
|
+
return tuple(sorted(out))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _safe_str(data: Any) -> str:
|
|
125
|
+
"""Defect 2 — ingress must never raise on hostile data. Return str(data), or a
|
|
126
|
+
deterministic sentinel if __str__ raises. Used by every ingress code path that
|
|
127
|
+
needs the stringified value (fingerprinting, laundering check, secret scan) so a
|
|
128
|
+
value whose __str__ explodes cannot crash untrusted()/trusted()/secret()/derive()
|
|
129
|
+
— which run OUTSIDE authorize()'s fail-closed wrapper. Conservative: on failure the
|
|
130
|
+
value is still correctly trust-labeled (UNTRUSTED stays UNTRUSTED, blocked at sinks
|
|
131
|
+
by Rule 1); only the advisory is_secret scan may read the sentinel and return False."""
|
|
132
|
+
try:
|
|
133
|
+
return str(data)
|
|
134
|
+
except Exception: # noqa: BLE001 — any __str__ failure must degrade, not crash ingress
|
|
135
|
+
return "<unstringable>"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _shannon_entropy(s: str) -> float:
|
|
139
|
+
if not s:
|
|
140
|
+
return 0.0
|
|
141
|
+
counts = {c: s.count(c) for c in set(s)}
|
|
142
|
+
return -sum((n / len(s)) * math.log2(n / len(s)) for n in counts.values())
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def looks_like_secret(text: str) -> bool:
|
|
146
|
+
"""Deterministic secret detection: known patterns + high-entropy tokens.
|
|
147
|
+
|
|
148
|
+
ADVISORY BACKSTOP ONLY — NOT a guarantee. Authoritative secret labeling comes
|
|
149
|
+
from Engine.secret() (broker-minted credentials, labeled is_secret=True
|
|
150
|
+
unconditionally) and from Policy.secret_fingerprints (sha256 of known-issued
|
|
151
|
+
credentials). This regex/entropy check catches COMMON unlabeled secrets but can be
|
|
152
|
+
bypassed (short/low-entropy secrets, custom token formats); NEVER rely on it as the
|
|
153
|
+
sole control for the "secrets cannot egress" guarantee."""
|
|
154
|
+
if not isinstance(text, str):
|
|
155
|
+
text = _safe_str(text) # Defect 2 — never raise on a hostile __str__
|
|
156
|
+
if any(p.search(text) for p in _SECRET_PATTERNS):
|
|
157
|
+
return True
|
|
158
|
+
for tok in re.split(r"\s+", text):
|
|
159
|
+
parts, split = _entropy_candidates(tok)
|
|
160
|
+
for part in parts:
|
|
161
|
+
if _WORDY_RX.fullmatch(part):
|
|
162
|
+
continue # words joined by . _ - (billing_support_archive, jane.doe2026): a name, not a key
|
|
163
|
+
if len(part) >= 20 and _shannon_entropy(part) > 4.0:
|
|
164
|
+
return True
|
|
165
|
+
# Hex tops out at 4.0 bits/char, so a hex secret inside a URL or address was only ever caught by
|
|
166
|
+
# its surroundings' entropy; keep catching it explicitly where the token was split.
|
|
167
|
+
if split and len(part) >= 32 and _HEX_RX.fullmatch(part):
|
|
168
|
+
return True
|
|
169
|
+
# A short random secret (a 24-character webhook or password) sits just under 4.0; split out of a
|
|
170
|
+
# URL it lost the surrounding characters that used to lift it. Mixed case and digits is the tell.
|
|
171
|
+
if split and len(part) >= 20 and _shannon_entropy(part) > 3.5 and _char_classes(part) >= 3:
|
|
172
|
+
return True
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
_URL_TOKEN_RX = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*://")
|
|
177
|
+
_EMAIL_TOKEN_RX = re.compile(r"^([^@\s]+)@([A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,24}$")
|
|
178
|
+
# The last label is a real top-level domain shape (letters only), so a JWT (dot-separated base64) is never a host.
|
|
179
|
+
_HOST_TOKEN_RX = re.compile(r"^(?=.{4,253}$)([A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,24}\.?(:\d{1,5})?$")
|
|
180
|
+
# One way to match each character (a "/" before every segment): no nested-quantifier backtracking (ReDoS).
|
|
181
|
+
_PATH_TOKEN_RX = re.compile(r"^(?:~|\.{1,2})?(?:/[A-Za-z0-9._-]+)+/?$")
|
|
182
|
+
_HEX_RX = re.compile(r"[0-9A-Fa-f]+")
|
|
183
|
+
# Two or more word-like segments (a letter, then lowercase, then up to six digits) joined by . _ or -.
|
|
184
|
+
# Separators can't occur inside a segment, so each character has one way to match (linear).
|
|
185
|
+
_WORDY_RX = re.compile(r"[A-Za-z][a-z]{1,15}[0-9]{0,6}(?:[._-][A-Za-z][a-z]{1,15}[0-9]{0,6})+")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _char_classes(s: str) -> int:
|
|
189
|
+
return sum(1 for cls in (str.islower, str.isupper, str.isdigit) if any(cls(c) for c in s))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _subdomain_labels(host: str) -> list[str]:
|
|
193
|
+
"""The labels left of a host's last two (`<data>.evil.example` → [<data>]). The registrable name can't
|
|
194
|
+
carry a secret, but labels in front of it can: that is DNS exfiltration, so they are judged."""
|
|
195
|
+
labels = host.split(":")[0].rstrip(".").split(".")
|
|
196
|
+
return labels[:-2]
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _entropy_candidates(tok: str) -> tuple[list[str], bool]:
|
|
200
|
+
"""The parts of one token the entropy check judges. A URL's scheme and host, an email's domain and a bare
|
|
201
|
+
hostname can't hold a secret, and judged whole they made about half of ordinary addresses and URLs look
|
|
202
|
+
like one (a support agent emailing customers was blocked as exfiltration). So: a URL → its user-info,
|
|
203
|
+
path segments, query values and subdomain labels; an email → its local part and subdomain labels; a
|
|
204
|
+
hostname → its subdomain labels (never the registrable name); a plain file path → its segments; anything
|
|
205
|
+
else → whole. Returns (parts, split). Identical in the TypeScript SDK."""
|
|
206
|
+
m = _URL_TOKEN_RX.match(tok)
|
|
207
|
+
if m:
|
|
208
|
+
rest = tok[m.end():]
|
|
209
|
+
cut = min((i for i in (rest.find(c) for c in "/?#\\") if i >= 0), default=len(rest))
|
|
210
|
+
authority, tail = rest[:cut], rest[cut:]
|
|
211
|
+
parts = authority.rpartition("@")[0].split(":") if "@" in authority else []
|
|
212
|
+
parts += _subdomain_labels(authority.rpartition("@")[2])
|
|
213
|
+
path, _, rest2 = tail.partition("?")
|
|
214
|
+
query, _, frag = rest2.partition("#")
|
|
215
|
+
if not rest2 and "#" in path:
|
|
216
|
+
path, _, frag = path.partition("#")
|
|
217
|
+
parts += [p for p in re.split(r"[/\\]", path) if p]
|
|
218
|
+
# Query values are judged whole (base64 often carries an unencoded "/"); the key is never secret.
|
|
219
|
+
parts += [kv.partition("=")[2] or kv for kv in query.split("&") if kv]
|
|
220
|
+
if frag:
|
|
221
|
+
parts.append(frag)
|
|
222
|
+
return [p for p in parts if p], True
|
|
223
|
+
m = _EMAIL_TOKEN_RX.match(tok)
|
|
224
|
+
if m:
|
|
225
|
+
return [m.group(1)] + _subdomain_labels(tok.rpartition("@")[2]), True
|
|
226
|
+
if _HOST_TOKEN_RX.match(tok):
|
|
227
|
+
return _subdomain_labels(tok), True
|
|
228
|
+
if _PATH_TOKEN_RX.match(tok):
|
|
229
|
+
return [p for p in tok.split("/") if p], True
|
|
230
|
+
return [tok], False
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _decoded_views(text: str, max_tokens: int = 32) -> tuple[str, ...]:
|
|
234
|
+
"""Bounded decoded views for encoded secret matching (result inspection + registries)."""
|
|
235
|
+
views = {text, text[::-1]}
|
|
236
|
+
for m in _ENCODING_TOKEN_RX.finditer(text):
|
|
237
|
+
if len(views) >= max_tokens:
|
|
238
|
+
break
|
|
239
|
+
tok = m.group(0)
|
|
240
|
+
if "%" in tok:
|
|
241
|
+
try:
|
|
242
|
+
u = urllib.parse.unquote(tok)
|
|
243
|
+
if u != tok:
|
|
244
|
+
views.add(u)
|
|
245
|
+
except Exception: # noqa: BLE001
|
|
246
|
+
pass
|
|
247
|
+
bare = tok.rstrip("=")
|
|
248
|
+
# Standard alphabet, then URL-safe. The URL-safe pass maps -_ to +/ itself rather than passing
|
|
249
|
+
# altchars: Python 3.15 warns that a future version will DISCARD a literal + or / in altchars mode,
|
|
250
|
+
# which would silently change what gets decoded (and so which encoded secrets are caught).
|
|
251
|
+
for alt in (bare, bare.replace("-", "+").replace("_", "/")):
|
|
252
|
+
padded = alt + ("=" * (-len(alt) % 4))
|
|
253
|
+
try:
|
|
254
|
+
b = base64.b64decode(padded.encode(), validate=False)
|
|
255
|
+
if b:
|
|
256
|
+
views.add(b.decode("utf-8", "ignore"))
|
|
257
|
+
except Exception: # noqa: BLE001
|
|
258
|
+
pass
|
|
259
|
+
if len(bare) % 2 == 0 and len(bare) >= 12 and re.fullmatch(r"[0-9A-Fa-f]+", bare):
|
|
260
|
+
try:
|
|
261
|
+
views.add(bytes.fromhex(bare).decode("utf-8", "ignore"))
|
|
262
|
+
except Exception: # noqa: BLE001
|
|
263
|
+
pass
|
|
264
|
+
return tuple(v for v in views if v)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def result_taints_context(flags: Iterable[str]) -> bool:
|
|
268
|
+
"""Rule 2b trigger: secret/steering or truncated output taints the session context."""
|
|
269
|
+
return any(f in {"secret", "instruction", "hidden_unicode", "truncated"} for f in flags)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
# ───────────────────── tool-RESULT inspection (the "effect" side) ─────────────────────
|
|
273
|
+
# What came BACK from a tool, reduced to a closed set of flags. Observational: it never changes
|
|
274
|
+
# the verdict of the call that produced the result. It feeds session state (a result carrying
|
|
275
|
+
# injected instructions taints the session) and the evidence trail (`result_flags`). Only flags
|
|
276
|
+
# and a byte count ever leave the process, never content.
|
|
277
|
+
#
|
|
278
|
+
# Parity: the Go gateway (mcp.go inspectResult) and the TS SDK (src/inspect.ts) implement the
|
|
279
|
+
# same rules and are gated on ../result_golden.json. Patterns mirror toolintegrity.go.
|
|
280
|
+
RESULT_FLAGS = ("hidden_unicode", "instruction", "pii", "secret", "truncated")
|
|
281
|
+
RESULT_SCAN_BUDGET = 256 * 1024 # bytes of text scanned per result
|
|
282
|
+
_RESULT_MAX_STRINGS = 10_000
|
|
283
|
+
_RESULT_MAX_DEPTH = 32
|
|
284
|
+
|
|
285
|
+
# Result-side twins of _SECRET_PATTERNS with BOUNDED quantifiers: a result is attacker-controlled
|
|
286
|
+
# and up to RESULT_SCAN_BUDGET long, so no pattern may backtrack super-linearly.
|
|
287
|
+
_RESULT_SECRET_RX = [
|
|
288
|
+
re.compile(r"AKIA[0-9A-Z]{16}"),
|
|
289
|
+
re.compile(r"(?i)aws_secret_access_key"),
|
|
290
|
+
re.compile(r"gh[pousr]_[A-Za-z0-9]{20}"),
|
|
291
|
+
re.compile(r"sk-[A-Za-z0-9]{20}"),
|
|
292
|
+
re.compile(r"-----BEGIN (?:RSA |EC )?PRIVATE KEY-----"),
|
|
293
|
+
re.compile(r"(?i)(password|passwd|secret|api[_-]?key|token)[ \t]{0,8}[=:][ \t]{0,8}\S"),
|
|
294
|
+
re.compile(r"postgres(?:ql)?://[^\s:@/]{1,256}:[^\s@/]{1,256}@[^\s@]"),
|
|
295
|
+
]
|
|
296
|
+
_INSTRUCTION_RX = [
|
|
297
|
+
re.compile(r"(?i)<\s{0,8}/?\s{0,8}(important|system|instructions?|secret|admin)\b[^>]{0,200}>", re.ASCII),
|
|
298
|
+
re.compile(r"(?i)\b(ignore|disregard|forget)\s+(all\s+|any\s+)?((your|my|the)\s+)?(previous|prior|above|earlier|other)\s+(instructions?|prompts?|rules?)", re.ASCII),
|
|
299
|
+
re.compile(r"(?i)\bdo\s+not\s+(tell|inform|mention|reveal|show|alert|notify)\b[^.\n]{0,60}\b(user|human|operator)", re.ASCII),
|
|
300
|
+
re.compile(r"(?i)\b(you|the\s+(assistant|model|ai|agent))\s+(must|should|need\s+to)\s+(first|also|always|secretly|silently|quietly)\s+(read|send|include|pass|forward|upload|exfiltrate|attach|call)\b", re.ASCII),
|
|
301
|
+
re.compile(r"(?i)\bbefore\s+(using|calling|invoking)\s+(this|any)\s+tool\b[^.\n]{0,40}\b(read|send|include|pass|forward|upload|call|access|fetch|attach)\b", re.ASCII),
|
|
302
|
+
re.compile(r"(?i)\b(secretly|silently|covertly|without\s+(telling|informing|notifying)\s+the\s+user)\b", re.ASCII),
|
|
303
|
+
re.compile(r"(?i)\b(when|whenever|if)\s+(the\s+user|you)\s+(calls?|uses?|invokes?)\s+(the\s+)?[\w.-]+\s+tool\b", re.ASCII),
|
|
304
|
+
re.compile(r"(?i)\binstead\s+of\s+(calling|using)\s+(the\s+)?[\w.-]+\s+tool\b", re.ASCII),
|
|
305
|
+
# Text addressed to the model, chat-template / role spoofing, declarations of new instructions,
|
|
306
|
+
# override banners (held-out set: injection_heldout.json). ASCII semantics, bounded, linear.
|
|
307
|
+
re.compile(r"(?i)\b(dear|hey|hi|hello|attention|note\s+to(\s+the)?|message\s+(for|to)(\s+you,?)?(\s+the)?|to\s+the|for\s+the)\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))\s{0,4}(,|:|!|\breading\b|\bprocessing\b)", re.ASCII),
|
|
308
|
+
re.compile(r"(?i)\byou,?\s+the\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))\b", re.ASCII),
|
|
309
|
+
re.compile(r"(?i)\bif\s+you(\s+are|'re)\s+an?\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))\b", re.ASCII),
|
|
310
|
+
re.compile(r"(?i)\bas\s+an?\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))\b[^.\n]{0,40}\b(must|required|need\s+to|have\s+to)\b", re.ASCII),
|
|
311
|
+
re.compile(r"<\|\s{0,4}im_(start|end)\s{0,4}\|>|\[/?INST\]|<<\s{0,4}/?SYS\s{0,4}>>", re.ASCII),
|
|
312
|
+
re.compile(r"(?im)^\s{0,8}#{1,6}\s{0,8}(system|instructions?)\s{0,8}:", re.ASCII),
|
|
313
|
+
re.compile(r"(?im)^\s{0,8}(system|assistant)\s{0,4}:\s", re.ASCII),
|
|
314
|
+
re.compile(r"(?i)\"role\"\s{0,4}:\s{0,4}\"(system|developer)\"", re.ASCII),
|
|
315
|
+
re.compile(r"(?i)\b(new|updated|additional|real|actual)\s+(instructions?|task|objective|directive|orders?)(\s+(for|to)\s+(you|the\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))))?\s{0,4}:", re.ASCII),
|
|
316
|
+
re.compile(r"(?i)\byour\s+(new|real|actual|true)\s+(instructions?|task|objective|directive|goal|purpose)\s+(is|are)\b", re.ASCII),
|
|
317
|
+
re.compile(r"(?i)\b(begin|end|start)\s+(admin|administrator|developer|system)\s+(override|mode|instructions?)\b", re.ASCII),
|
|
318
|
+
re.compile(r"(?i)\b(admin|administrator|developer|system)\s+(message|prompt\s+update|mode\s+(enabled|activated|on))\s{0,4}[:!.]", re.ASCII),
|
|
319
|
+
re.compile(r"(?i)\b(ignore|disregard)\s+(what\s+the\s+user|the\s+user'?s?\s+(request|question|instructions?))\b", re.ASCII),
|
|
320
|
+
re.compile(r"(?i)-{2,}\s{0,4}end\s+of\s+(document|context|email|page|file|input)\s{0,4}-{2,}", re.ASCII),
|
|
321
|
+
]
|
|
322
|
+
_SSN_RX = re.compile(r"\b(\d{3})-(\d{2})-(\d{4})\b", re.ASCII)
|
|
323
|
+
_CARD_RX = re.compile(r"\b(?:\d[ -]?){12,18}\d\b", re.ASCII)
|
|
324
|
+
# Bounded quantifiers keep every pattern linear on hostile input (an unbounded local part is
|
|
325
|
+
# quadratic on a long run of letters with no '@').
|
|
326
|
+
_EMAIL_RX = re.compile(r"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63}){0,8}\.[A-Za-z]{2,24}", re.ASCII)
|
|
327
|
+
_EMAIL_BULK = 5 # one address is normal; a list of people is a data exposure
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _hidden_rune(c: str) -> bool:
|
|
331
|
+
o = ord(c)
|
|
332
|
+
return (0x200B <= o <= 0x200F or 0x202A <= o <= 0x202E or 0x2060 <= o <= 0x2064
|
|
333
|
+
or 0x2066 <= o <= 0x2069 or o == 0xFEFF or 0xE0000 <= o <= 0xE007F)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _luhn(digits: str) -> bool:
|
|
337
|
+
total = 0
|
|
338
|
+
for i, ch in enumerate(reversed(digits)):
|
|
339
|
+
n = ord(ch) - 48
|
|
340
|
+
if i % 2:
|
|
341
|
+
n = n * 2 - 9 if n > 4 else n * 2
|
|
342
|
+
total += n
|
|
343
|
+
return total % 10 == 0
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _has_pii(text: str) -> bool:
|
|
347
|
+
for m in _SSN_RX.finditer(text):
|
|
348
|
+
area, group, serial = m.group(1), m.group(2), m.group(3)
|
|
349
|
+
if area not in ("000", "666") and area[0] != "9" and group != "00" and serial != "0000":
|
|
350
|
+
return True
|
|
351
|
+
for m in _CARD_RX.finditer(text):
|
|
352
|
+
digits = m.group(0).replace(" ", "").replace("-", "")
|
|
353
|
+
if 13 <= len(digits) <= 19 and len(set(digits)) > 1 and _luhn(digits):
|
|
354
|
+
return True
|
|
355
|
+
emails: set[str] = set()
|
|
356
|
+
for m in _EMAIL_RX.finditer(text):
|
|
357
|
+
emails.add(m.group(0).lower())
|
|
358
|
+
if len(emails) >= _EMAIL_BULK:
|
|
359
|
+
return True
|
|
360
|
+
return False
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _result_strings(value: Any, out: list[str], depth: int = 0) -> None:
|
|
364
|
+
"""Every string in a tool result, object keys included (the Go collectStrings twin)."""
|
|
365
|
+
if len(out) >= _RESULT_MAX_STRINGS or depth > _RESULT_MAX_DEPTH:
|
|
366
|
+
return
|
|
367
|
+
if isinstance(value, str):
|
|
368
|
+
out.append(value)
|
|
369
|
+
elif isinstance(value, dict):
|
|
370
|
+
for k in sorted(value, key=_safe_str):
|
|
371
|
+
out.append(k if isinstance(k, str) else _safe_str(k))
|
|
372
|
+
_result_strings(value[k], out, depth + 1)
|
|
373
|
+
elif isinstance(value, (list, tuple)):
|
|
374
|
+
for x in value:
|
|
375
|
+
_result_strings(x, out, depth + 1)
|
|
376
|
+
elif value is None or isinstance(value, (bool, int, float, bytes, bytearray)):
|
|
377
|
+
return
|
|
378
|
+
else:
|
|
379
|
+
out.append(_safe_str(value))
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
@dataclass(frozen=True)
|
|
383
|
+
class ResultInspection:
|
|
384
|
+
flags: tuple[str, ...] = () # sorted subset of RESULT_FLAGS
|
|
385
|
+
bytes: int = 0 # UTF-8 size of every string in the result (pre-budget)
|
|
386
|
+
|
|
387
|
+
def signals(self) -> dict:
|
|
388
|
+
return {"result_flags": list(self.flags), "result_bytes": self.bytes}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def inspect_result(result: Any, budget: int = RESULT_SCAN_BUDGET) -> ResultInspection:
|
|
392
|
+
"""Deterministic, bounded inspection of a tool's output. Never raises.
|
|
393
|
+
|
|
394
|
+
secret — a known credential pattern (no entropy heuristic: results are full of hashes/ids)
|
|
395
|
+
pii — a valid SSN, a Luhn-valid card number, or ≥5 distinct e-mail addresses
|
|
396
|
+
instruction — text addressed to the model (the tool-poisoning patterns, applied to output)
|
|
397
|
+
hidden_unicode — zero-width / bidi / tag characters that hide text from the human
|
|
398
|
+
truncated — the result exceeded the scan budget; only the first `budget` bytes were read
|
|
399
|
+
"""
|
|
400
|
+
try:
|
|
401
|
+
strings: list[str] = []
|
|
402
|
+
_result_strings(result, strings)
|
|
403
|
+
total, scanned, parts = 0, 0, []
|
|
404
|
+
for s in strings:
|
|
405
|
+
b = s.encode("utf-8", "surrogatepass")
|
|
406
|
+
total += len(b)
|
|
407
|
+
if scanned < budget:
|
|
408
|
+
take = b[: budget - scanned]
|
|
409
|
+
scanned += len(take)
|
|
410
|
+
parts.append(take.decode("utf-8", "ignore"))
|
|
411
|
+
flags: set[str] = set()
|
|
412
|
+
if total > budget:
|
|
413
|
+
flags.add("truncated")
|
|
414
|
+
for text in parts:
|
|
415
|
+
if not text:
|
|
416
|
+
continue
|
|
417
|
+
if "secret" not in flags and any(
|
|
418
|
+
p.search(view) for view in _decoded_views(text) for p in _RESULT_SECRET_RX
|
|
419
|
+
):
|
|
420
|
+
flags.add("secret")
|
|
421
|
+
if "instruction" not in flags and any(p.search(text) for p in _INSTRUCTION_RX):
|
|
422
|
+
flags.add("instruction")
|
|
423
|
+
if "hidden_unicode" not in flags and any(_hidden_rune(c) for c in text):
|
|
424
|
+
flags.add("hidden_unicode")
|
|
425
|
+
if _has_pii("\n".join(parts)):
|
|
426
|
+
flags.add("pii")
|
|
427
|
+
return ResultInspection(tuple(sorted(flags)), total)
|
|
428
|
+
except Exception: # noqa: BLE001 — observational; a hostile result must never break the call path
|
|
429
|
+
return ResultInspection(("truncated",), 0)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
# ─────────────────────────────── decisions ────────────────────────────────
|
|
433
|
+
class Verdict(str, Enum):
|
|
434
|
+
ALLOW = "ALLOW"
|
|
435
|
+
STEP_UP = "STEP_UP" # requires human approval
|
|
436
|
+
BLOCK = "BLOCK"
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
@dataclass
|
|
440
|
+
class Decision:
|
|
441
|
+
verdict: Verdict
|
|
442
|
+
layer: str # which deterministic rule decided
|
|
443
|
+
reason: str # human + machine readable reason chain
|
|
444
|
+
action: str
|
|
445
|
+
identity: str
|
|
446
|
+
reason_code: str = "" # Stable machine key (see ReasonCode); "" = legacy
|
|
447
|
+
policy_version: str = "" # The policy revision that produced this decision;
|
|
448
|
+
# "" when the engine has no bound version (embedded/dev use)
|
|
449
|
+
# Signals v2 — metadata-only evidence for the control plane's value ledger / exposure map.
|
|
450
|
+
# Never carries argument values: provenance is reduced to coarse origin TAGS (origin_tag).
|
|
451
|
+
sink_class: str = "" # read | write | egress | destructive | financial | credential
|
|
452
|
+
tainted: bool = False # an arg carried PROVEN untrusted provenance
|
|
453
|
+
taint_sources: tuple[str, ...] = ()
|
|
454
|
+
secret_in_args: bool = False
|
|
455
|
+
context_tainted: bool = False # the session had ingested untrusted content
|
|
456
|
+
latency_us: int = 0
|
|
457
|
+
# WHAT the call targeted, as categories + a host fingerprint (see target_signals) — never the
|
|
458
|
+
# raw destination, path or argument values.
|
|
459
|
+
target: dict = field(default_factory=dict)
|
|
460
|
+
planned: bool = False # the call matched a step of a plan written from the user's request
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
# ─────────────────────────── plan-then-execute (planned calls) ───────────────────────────
|
|
464
|
+
# A plan is written from the USER'S REQUEST alone (a planner that never sees tool output). Each step
|
|
465
|
+
# names a tool, the argument values the planner fixed, and typed SLOTS that later data may fill. A call
|
|
466
|
+
# that matches an unused step may carry untrusted data in its slots without being held: the data can't
|
|
467
|
+
# choose the tool, the destination or any fixed value. A destination is never a slot. Secret, destructive,
|
|
468
|
+
# transfer and risk rules still apply. Each step is used once (the session tracks that). Identical in the
|
|
469
|
+
# TS SDK and the Rust engine (plan_golden.json). The gateway accepts only plans a planner registered under its
|
|
470
|
+
# own sign-in (docs/design/GATEWAY-PLANS.md), never one the agent supplies: that could be forged.
|
|
471
|
+
#
|
|
472
|
+
# A destination may instead be CHOSEN FROM A LIST (`choose_from`): its value must be a whole element of a list
|
|
473
|
+
# a named read-only tool returned earlier in this session (extract_choices), and also a known destination or
|
|
474
|
+
# a value from a tool the policy marks as the organisation's own directory. Free text never qualifies.
|
|
475
|
+
PLAN_TEXT_MAX = 8000
|
|
476
|
+
# Name tokens that make a tool a write, never a fetch (known-site reads). Identical in every engine and the
|
|
477
|
+
# control plane's policy validation.
|
|
478
|
+
WRITE_VERBS = frozenset({
|
|
479
|
+
"add", "append", "approve", "assign", "book", "call", "cancel", "charge", "chmod", "comment", "commit", "create",
|
|
480
|
+
"delete", "deploy", "destroy", "drop", "edit", "email", "eval", "exec", "execute", "forward", "grant", "insert",
|
|
481
|
+
"invite", "invoke", "kill", "merge", "message", "modify", "move", "notify", "patch", "pay", "payment", "post",
|
|
482
|
+
"publish", "purge", "push", "put", "remove", "rename", "reserve", "schedule", "send", "set", "share", "shell",
|
|
483
|
+
"transfer", "update", "upload", "wire", "write",
|
|
484
|
+
})
|
|
485
|
+
_NAME_SPLIT_RX = re.compile(r"[_\-.:/]+")
|
|
486
|
+
_CAMEL_RX = re.compile(r"(?<=.)([A-Z])")
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def write_like_name(tool: str) -> bool:
|
|
490
|
+
"""Any token of the tool's name (after "mcp:", split on _ - . : / and camelCase) is a write verb."""
|
|
491
|
+
name = tool[4:] if tool.startswith("mcp:") else tool
|
|
492
|
+
return any(t in WRITE_VERBS for t in _NAME_SPLIT_RX.split(_CAMEL_RX.sub(r"_\1", name).lower()) if t)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
PLAN_CHOICES_MAX = 1000 # list elements taken from one result
|
|
496
|
+
PLAN_CHOICE_LEN_MAX = 256 # longer elements are never choices
|
|
497
|
+
_PLAN_DATE_RX = re.compile(r"^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2})?)?", re.ASCII)
|
|
498
|
+
_PLAN_ID_RX = re.compile(r"^[A-Za-z0-9_.:@-]{1,128}$", re.ASCII)
|
|
499
|
+
_PLAN_NUM_RX = re.compile(r"^-?\d{1,15}(\.\d{1,6})?$", re.ASCII)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
@dataclass(frozen=True)
|
|
503
|
+
class PlanStep:
|
|
504
|
+
action: str
|
|
505
|
+
fixed: dict = field(default_factory=dict) # arg → the exact value the planner wrote
|
|
506
|
+
slots: dict = field(default_factory=dict) # arg → text | number | date | id | enum:a|b|c
|
|
507
|
+
choose_from: dict = field(default_factory=dict) # arg → {"tool": read tool, "field": "" | element key}
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def extract_choices(result: Any, field_name: str) -> list[str]:
|
|
511
|
+
"""The values a list-chosen destination may take from one tool result. Whole elements only:
|
|
512
|
+
with field "" the result is a JSON array of strings; with a field name it is an array of objects, each
|
|
513
|
+
contributing its string value under that key. An object with exactly one key is unwrapped first (MCP
|
|
514
|
+
servers wrap a list as {"result": [...]}), and a string is parsed as JSON. Anything else gives nothing."""
|
|
515
|
+
v = result
|
|
516
|
+
if isinstance(v, (bytes, bytearray)):
|
|
517
|
+
v = v.decode("utf-8", "replace")
|
|
518
|
+
if isinstance(v, str):
|
|
519
|
+
t = v.strip()
|
|
520
|
+
if not t.startswith(("[", "{")):
|
|
521
|
+
return []
|
|
522
|
+
try:
|
|
523
|
+
v = json.loads(t)
|
|
524
|
+
except ValueError:
|
|
525
|
+
return []
|
|
526
|
+
if isinstance(v, dict) and len(v) == 1:
|
|
527
|
+
v = next(iter(v.values()))
|
|
528
|
+
if not isinstance(v, list):
|
|
529
|
+
return []
|
|
530
|
+
out: list[str] = []
|
|
531
|
+
for e in v[:PLAN_CHOICES_MAX]:
|
|
532
|
+
x = e if field_name == "" else (e.get(field_name) if isinstance(e, dict) else None)
|
|
533
|
+
if isinstance(x, str) and 0 < len(x) <= PLAN_CHOICE_LEN_MAX:
|
|
534
|
+
out.append(x)
|
|
535
|
+
return out
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _read_only(policy: "Policy", tool: str) -> bool:
|
|
539
|
+
return (policy.sens(tool) is Sensitivity.LOW and tool not in SINK_ACTIONS
|
|
540
|
+
and not policy.is_destructive(tool))
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def plan_choice_ok(src: Any, value: Any, choices: "dict | None", policy: "Policy | None") -> bool:
|
|
544
|
+
"""A list-chosen value: from a read-only source tool's list in this session, and known or from a directory."""
|
|
545
|
+
if policy is None or not isinstance(src, dict):
|
|
546
|
+
return False
|
|
547
|
+
tool, fld = src.get("tool"), src.get("field", "")
|
|
548
|
+
if not isinstance(tool, str) or not tool or not isinstance(fld, str) or not _read_only(policy, tool):
|
|
549
|
+
return False
|
|
550
|
+
s = _safe_str(value)
|
|
551
|
+
if s not in ((choices or {}).get(tool) or {}).get(fld, ()):
|
|
552
|
+
return False
|
|
553
|
+
return s in policy.known_destinations or tool in policy.directory_tools
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def plan_slot_ok(kind: str, value: Any) -> bool:
|
|
557
|
+
s = _safe_str(value)
|
|
558
|
+
if kind == "text":
|
|
559
|
+
return len(s) <= PLAN_TEXT_MAX
|
|
560
|
+
if kind == "number":
|
|
561
|
+
return bool(_PLAN_NUM_RX.match(s.strip()))
|
|
562
|
+
if kind == "date":
|
|
563
|
+
return bool(_PLAN_DATE_RX.match(s.strip()))
|
|
564
|
+
if kind == "id":
|
|
565
|
+
return bool(_PLAN_ID_RX.match(s))
|
|
566
|
+
if kind.startswith("enum:"):
|
|
567
|
+
return s in kind[5:].split("|")
|
|
568
|
+
return False
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def plan_matches(step: "PlanStep | None", action: str, args: dict, choices: "dict | None" = None,
|
|
572
|
+
policy: "Policy | None" = None) -> bool:
|
|
573
|
+
"""The call is exactly what the step planned: same tool, every fixed value present and equal, every
|
|
574
|
+
other argument a declared slot of the right type or a list choice that holds (plan_choice_ok), and no
|
|
575
|
+
destination argument left to a slot. `choices`: tool → field → values seen this session."""
|
|
576
|
+
if step is None or step.action != action:
|
|
577
|
+
return False
|
|
578
|
+
fixed, slots = dict(step.fixed or {}), dict(step.slots or {})
|
|
579
|
+
chosen = dict(getattr(step, "choose_from", None) or {})
|
|
580
|
+
if any(is_destination_arg(k) for k in slots):
|
|
581
|
+
return False # untrusted data must never choose who or where
|
|
582
|
+
if set(chosen) & (set(fixed) | set(slots)):
|
|
583
|
+
return False # one rule per argument
|
|
584
|
+
names = set(args)
|
|
585
|
+
if not set(fixed) <= names or not names <= set(fixed) | set(slots) | set(chosen):
|
|
586
|
+
return False
|
|
587
|
+
for k, src in chosen.items():
|
|
588
|
+
if k in args:
|
|
589
|
+
v = args[k].data if isinstance(args[k], Value) else args[k]
|
|
590
|
+
if not plan_choice_ok(src, v, choices, policy):
|
|
591
|
+
return False
|
|
592
|
+
for k, want in fixed.items():
|
|
593
|
+
v = args[k].data if isinstance(args[k], Value) else args[k]
|
|
594
|
+
if _safe_str(v) != _safe_str(want):
|
|
595
|
+
return False
|
|
596
|
+
for k, kind in slots.items():
|
|
597
|
+
if k in args:
|
|
598
|
+
v = args[k].data if isinstance(args[k], Value) else args[k]
|
|
599
|
+
if not plan_slot_ok(str(kind), v):
|
|
600
|
+
return False
|
|
601
|
+
return True
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
# ─────────────────────────────── policy (L4) ────────────────────────────────
|
|
605
|
+
# Sensitivity + egress classification are policy data, tunable per tenant.
|
|
606
|
+
DEFAULT_SENSITIVITY: dict[str, Sensitivity] = {
|
|
607
|
+
"read_file": Sensitivity.LOW,
|
|
608
|
+
"query_ledger": Sensitivity.LOW,
|
|
609
|
+
"list_dir": Sensitivity.LOW,
|
|
610
|
+
"git_commit": Sensitivity.MEDIUM,
|
|
611
|
+
"send_email": Sensitivity.HIGH,
|
|
612
|
+
"http_post": Sensitivity.HIGH,
|
|
613
|
+
"http_fetch": Sensitivity.MEDIUM,
|
|
614
|
+
"wire_transfer": Sensitivity.HIGH,
|
|
615
|
+
"kms_decrypt": Sensitivity.HIGH,
|
|
616
|
+
"execute_shell": Sensitivity.HIGH,
|
|
617
|
+
"rds_delete": Sensitivity.HIGH,
|
|
618
|
+
"kubectl_delete": Sensitivity.HIGH,
|
|
619
|
+
"terraform_apply": Sensitivity.HIGH,
|
|
620
|
+
}
|
|
621
|
+
EGRESS_ACTIONS = {"http_post", "http_fetch", "send_email"}
|
|
622
|
+
DESTRUCTIVE_ACTIONS = {"rds_delete", "kubectl_delete", "terraform_apply", "execute_shell"}
|
|
623
|
+
# A wire_transfer above this asks a person. A policy may lower it, never raise it (docs/design/POLICY-THRESHOLDS.md).
|
|
624
|
+
TRANSFER_STEPUP_THRESHOLD = 10_000
|
|
625
|
+
|
|
626
|
+
# Explicit SINK set. Any action producing an observable side-effect on the outside
|
|
627
|
+
# world or on persistent/durable state is a "sink"; untrusted data reaching a sink argument
|
|
628
|
+
# is an indirect-injection attack surface and must be blocked regardless of the action's
|
|
629
|
+
# nominal sensitivity tier. This closes the "MEDIUM-sensitivity actions (e.g., git_commit,
|
|
630
|
+
# http_fetch) let untrusted data through" audit gap.
|
|
631
|
+
SINK_ACTIONS = (
|
|
632
|
+
EGRESS_ACTIONS
|
|
633
|
+
| DESTRUCTIVE_ACTIONS
|
|
634
|
+
| {"git_commit", "wire_transfer", "kms_decrypt", "send_email"}
|
|
635
|
+
)
|
|
636
|
+
# Common names for writing to and recalling from agent memory, including the MCP memory server's tools.
|
|
637
|
+
DEFAULT_MEMORY_WRITE_ACTIONS = frozenset({
|
|
638
|
+
"memory_write", "remember", "save_memory", "store_memory", "add_memory", "memory_add", "update_memory",
|
|
639
|
+
"vector_upsert", "upsert_memory", "create_entities", "add_observations", "create_relations",
|
|
640
|
+
})
|
|
641
|
+
DEFAULT_MEMORY_READ_ACTIONS = frozenset({
|
|
642
|
+
"memory_read", "recall", "search_memory", "memory_search", "retrieve_memory", "get_memory", "load_memory",
|
|
643
|
+
"query_memory", "vector_query", "search_nodes", "open_nodes", "read_graph",
|
|
644
|
+
})
|
|
645
|
+
|
|
646
|
+
FINANCIAL_ACTIONS = {"wire_transfer"}
|
|
647
|
+
CREDENTIAL_ACTIONS = {"kms_decrypt", "get_secret", "assume_role", "create_access_key"}
|
|
648
|
+
SINK_CLASSES = ("read", "write", "egress", "destructive", "financial", "credential")
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def sink_class(action: str, policy: "Policy | None" = None) -> str:
|
|
652
|
+
"""Coarse blast-radius class of an action — the unit the value ledger reports in
|
|
653
|
+
("3 exfiltration attempts stopped"). Deterministic and policy-aware: an unknown action
|
|
654
|
+
resolves through Policy.sens (fail-closed → HIGH) and is therefore at least a 'write'."""
|
|
655
|
+
if action in EGRESS_ACTIONS:
|
|
656
|
+
return "egress"
|
|
657
|
+
if action in DESTRUCTIVE_ACTIONS or (policy is not None and action in policy.destructive_actions):
|
|
658
|
+
return "destructive"
|
|
659
|
+
if action in FINANCIAL_ACTIONS:
|
|
660
|
+
return "financial"
|
|
661
|
+
if action in CREDENTIAL_ACTIONS:
|
|
662
|
+
return "credential"
|
|
663
|
+
sens = policy.sens(action) if policy is not None else DEFAULT_SENSITIVITY.get(action, Sensitivity.HIGH)
|
|
664
|
+
if sens is Sensitivity.LOW and action not in SINK_ACTIONS:
|
|
665
|
+
return "read"
|
|
666
|
+
return "write"
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
_ORIGIN_TAG_RX = re.compile(r"^[a-z][a-z0-9_.-]{0,31}(?::[A-Za-z0-9_.-]{1,48})?$")
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def origin_tag(origin: str) -> str:
|
|
673
|
+
"""Reduce a free-text provenance origin to a coarse, privacy-safe tag for telemetry.
|
|
674
|
+
'tool:http_fetch' → 'tool:http_fetch', 'file:/etc/x' → 'file', 'rag:https://…' → 'rag'.
|
|
675
|
+
Only the KIND survives (plus the tool name for tool/mcp origins) — never a path, URL or
|
|
676
|
+
content; anything that doesn't fit the strict shape collapses to 'other'."""
|
|
677
|
+
first = _safe_str(origin).split(",")[0].strip()
|
|
678
|
+
parts = first.split(":")
|
|
679
|
+
kind = parts[0].lower()
|
|
680
|
+
tag = f"{kind}:{parts[1]}" if kind in ("tool", "mcp", "session") and len(parts) > 1 else kind
|
|
681
|
+
if not _ORIGIN_TAG_RX.match(tag) or looks_like_secret(tag):
|
|
682
|
+
return "other"
|
|
683
|
+
return tag
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def _taint_tags(labels: Iterable[Label], limit: int = 8) -> tuple[str, ...]:
|
|
687
|
+
tags: dict[str, None] = {}
|
|
688
|
+
for l in labels:
|
|
689
|
+
for o in _safe_str(l.origin).split(", "):
|
|
690
|
+
tags.setdefault(origin_tag(o), None)
|
|
691
|
+
if len(tags) >= limit:
|
|
692
|
+
return tuple(tags)
|
|
693
|
+
return tuple(tags)
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
# Structured reason codes (stable, machine-readable). The `reason` string keeps
|
|
697
|
+
# its human-readable form for logs, but downstream systems (control plane telemetry,
|
|
698
|
+
# console rendering, SIEM export) should key off `reason_code` — it never carries raw
|
|
699
|
+
# argument values or hostnames.
|
|
700
|
+
class ReasonCode:
|
|
701
|
+
SCOPE_DENY = "scope.deny"
|
|
702
|
+
IFC_UNTRUSTED_TO_SINK = "ifc.untrusted_to_sink"
|
|
703
|
+
SECRET_EGRESS_DENY = "egress.secret_non_allowlisted"
|
|
704
|
+
SECRET_TO_SINK_STEPUP = "egress.secret_to_durable_sink"
|
|
705
|
+
DESTRUCTIVE_STEPUP = "policy.destructive_prod_stepup"
|
|
706
|
+
TRANSFER_THRESHOLD_STEPUP = "policy.transfer_threshold_stepup"
|
|
707
|
+
CONTEXT_TAINT_STEPUP = "ifc.context_tainted_stepup"
|
|
708
|
+
UNTRUSTED_CONTENT_STEPUP = "ifc.untrusted_content_stepup"
|
|
709
|
+
RISK_HIGH_BLOCK = "risk.high_block"
|
|
710
|
+
RISK_ELEVATED_STEPUP = "risk.elevated_stepup"
|
|
711
|
+
ALLOW_WITHIN_POLICY = "policy.allow"
|
|
712
|
+
PLANNED_CALL = "plan.planned_call" # untrusted data only in the slots of a step planned from the user's request
|
|
713
|
+
ALLOWLISTED_READ = "ifc.allowlisted_read" # untrusted data steered a read of an allowlisted site (Policy.allowlisted_reads)
|
|
714
|
+
FAIL_CLOSED = "fail_closed"
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
# Arg-name tokens that say WHERE an action's effect lands (recipient, URL, account, channel,
|
|
718
|
+
# invitee…). Matched per "_"-separated token, so "recipient_email" and "to_address" match.
|
|
719
|
+
DEFAULT_DESTINATION_ARGS = frozenset({
|
|
720
|
+
"to", "cc", "bcc", "recipient", "recipients", "email", "emails", "address", "url", "uri",
|
|
721
|
+
"host", "domain", "endpoint", "webhook", "iban", "account", "phone", "channel", "user",
|
|
722
|
+
"users", "participants", "attendees", "member", "members", "destination", "dest", "target",
|
|
723
|
+
"remote", "repo", "bucket",
|
|
724
|
+
})
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def is_destination_arg(name: str, tokens: frozenset[str] = DEFAULT_DESTINATION_ARGS) -> bool:
|
|
728
|
+
return any(t in tokens for t in str(name).lower().split("_"))
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
@dataclass
|
|
732
|
+
class Policy:
|
|
733
|
+
capabilities: set[str] # tools this identity may call at all
|
|
734
|
+
allowlist_hosts: set[str] = field(default_factory=set)
|
|
735
|
+
env: str = "prod"
|
|
736
|
+
sensitivity: dict[str, Sensitivity] = field(default_factory=lambda: dict(DEFAULT_SENSITIVITY))
|
|
737
|
+
fail_closed: bool = True
|
|
738
|
+
# Policy revision string. Bound at load time from the control-plane bundle
|
|
739
|
+
# (or set by the gateway's PolicyCache after a refresh). "" means "not versioned"
|
|
740
|
+
# — legitimate for tests and embedded/dev, but a production gateway that fetched
|
|
741
|
+
# a bundle without a version should treat that as a config bug.
|
|
742
|
+
version: str = ""
|
|
743
|
+
# Authoritative secret registry. SHA-256 hex digests of known-issued
|
|
744
|
+
# credentials (e.g. supplied by the JIT broker / secrets manager). Default empty →
|
|
745
|
+
# no effect, fully backward compatible. When populated, any value whose sha256
|
|
746
|
+
# matches is treated as secret regardless of what the regex backstop thinks.
|
|
747
|
+
secret_fingerprints: set[str] = field(default_factory=set)
|
|
748
|
+
# Session (context) taint declassification: sink actions explicitly allowed to run
|
|
749
|
+
# without step-up while the session context is tainted (e.g. a coding agent's
|
|
750
|
+
# git_commit after reading docs). Proven taint (Rule 1) is NEVER declassified here.
|
|
751
|
+
context_taint_exempt: set[str] = field(default_factory=set)
|
|
752
|
+
# Proven-taint mode. False (default, "strict"): untrusted data in ANY arg of a sink → BLOCK.
|
|
753
|
+
# True ("balanced"): untrusted data that only reaches CONTENT args (body, amount, subject…)
|
|
754
|
+
# → STEP_UP, so a human can approve "pay the bill in this file". Untrusted data in a
|
|
755
|
+
# DESTINATION arg (who/where it goes) still BLOCKs unless that destination is already known
|
|
756
|
+
# (known_destinations, or a URL to an allowlisted host). Unlabeled args always BLOCK.
|
|
757
|
+
# Implemented identically in the TypeScript SDK, the Go gateway and the Rust engine (shared golden vectors).
|
|
758
|
+
untrusted_content_stepup: bool = False
|
|
759
|
+
destination_args: frozenset[str] = DEFAULT_DESTINATION_ARGS
|
|
760
|
+
known_destinations: set[str] = field(default_factory=set)
|
|
761
|
+
# Agent memory (docs/design/MEMORY-PROVENANCE.md): which tools write to and recall from it, and the
|
|
762
|
+
# trust of recalled content Xtrom never saw written (untrusted unless memory is curated by people).
|
|
763
|
+
memory_write_actions: frozenset[str] = DEFAULT_MEMORY_WRITE_ACTIONS
|
|
764
|
+
memory_read_actions: frozenset[str] = DEFAULT_MEMORY_READ_ACTIONS
|
|
765
|
+
memory_unknown: Trust = Trust.UNTRUSTED
|
|
766
|
+
# Tighten-only approval thresholds (docs/design/POLICY-THRESHOLDS.md): a lower transfer hold and tools added
|
|
767
|
+
# to DESTRUCTIVE_ACTIONS. Neither can loosen a built-in; the helpers below clamp a value that would.
|
|
768
|
+
transfer_stepup_threshold: float = TRANSFER_STEPUP_THRESHOLD
|
|
769
|
+
destructive_actions: frozenset[str] = frozenset()
|
|
770
|
+
# Read tools that list the organisation's own users, channels or accounts: a plan may choose a destination
|
|
771
|
+
# from their results (docs/design/GATEWAY-PLANS.md). Empty → only known destinations can be chosen.
|
|
772
|
+
directory_tools: frozenset[str] = frozenset()
|
|
773
|
+
# Known-site reads (docs/design/GATEWAY-PLANS.md, "Reads of allowlisted sites"): when on, a FETCH whose every
|
|
774
|
+
# destination is an allowlisted host is not held or blocked for untrusted data in its arguments or session;
|
|
775
|
+
# it can only reach sites the organisation trusts. A fetch is http_fetch or a tool in fetch_actions; a
|
|
776
|
+
# built-in write or destructive tool is never one. Off by default: it loosens enforcement.
|
|
777
|
+
allowlisted_reads: bool = False
|
|
778
|
+
fetch_actions: frozenset[str] = frozenset()
|
|
779
|
+
|
|
780
|
+
def is_fetch(self, action: str) -> bool:
|
|
781
|
+
if action == "http_fetch":
|
|
782
|
+
return True
|
|
783
|
+
return (action in self.fetch_actions and action not in SINK_ACTIONS and not self.is_destructive(action)
|
|
784
|
+
and not write_like_name(action))
|
|
785
|
+
|
|
786
|
+
def transfer_threshold(self) -> float:
|
|
787
|
+
"""The transfer hold in force: the policy's when it is above 0 and at most the built-in, else the built-in."""
|
|
788
|
+
t = self.transfer_stepup_threshold
|
|
789
|
+
ok = isinstance(t, (int, float)) and not isinstance(t, bool) and 0 < t <= TRANSFER_STEPUP_THRESHOLD
|
|
790
|
+
return t if ok else TRANSFER_STEPUP_THRESHOLD
|
|
791
|
+
|
|
792
|
+
def is_destructive(self, action: str) -> bool:
|
|
793
|
+
return action in DESTRUCTIVE_ACTIONS or action in self.destructive_actions
|
|
794
|
+
|
|
795
|
+
def is_known_secret(self, data: Any) -> bool:
|
|
796
|
+
"""Authoritative lookup: registered sha256 fingerprints, with bounded
|
|
797
|
+
checks of common encodings in the candidate value (base64/url/hex/reversed).
|
|
798
|
+
Prefer register_secret() when the raw secret is available; it precomputes the
|
|
799
|
+
encoded variant fingerprints at registration time."""
|
|
800
|
+
if not self.secret_fingerprints:
|
|
801
|
+
return False
|
|
802
|
+
for view in _decoded_views(_safe_str(data)):
|
|
803
|
+
if hashlib.sha256(view.encode()).hexdigest() in self.secret_fingerprints:
|
|
804
|
+
return True
|
|
805
|
+
return False
|
|
806
|
+
|
|
807
|
+
def register_secret(self, data: Any) -> None:
|
|
808
|
+
"""Register a raw secret plus common encoded variants by sha256 fingerprint."""
|
|
809
|
+
for v in encoded_variants(data):
|
|
810
|
+
self.secret_fingerprints.add(hashlib.sha256(v.encode()).hexdigest())
|
|
811
|
+
|
|
812
|
+
@classmethod
|
|
813
|
+
def default(cls) -> "Policy":
|
|
814
|
+
return cls(capabilities={
|
|
815
|
+
"read_file", "query_ledger", "list_dir", "git_commit",
|
|
816
|
+
"send_email", "http_post", "http_fetch", "wire_transfer", "kms_decrypt",
|
|
817
|
+
})
|
|
818
|
+
|
|
819
|
+
def sens(self, action: str) -> Sensitivity:
|
|
820
|
+
return self.sensitivity.get(action, Sensitivity.HIGH if self.fail_closed else Sensitivity.LOW)
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
# ─────────────────────────────── the engine ────────────────────────────────
|
|
824
|
+
class Engine:
|
|
825
|
+
"""Adjudicates every tool call. Deterministic layers only — the guarantee."""
|
|
826
|
+
|
|
827
|
+
def __init__(self, policy: Policy, identity: str = "svc-agent", audit_path: str | None = None,
|
|
828
|
+
strict_ingress: bool = True):
|
|
829
|
+
self.policy = policy
|
|
830
|
+
self.identity = identity
|
|
831
|
+
self._audit_path = audit_path
|
|
832
|
+
self.events: list[dict] = []
|
|
833
|
+
# Anti-laundering, ON by default (opt out with strict_ingress=False). When True,
|
|
834
|
+
# trusted() refuses to launder data it recognises as previously-seen untrusted content.
|
|
835
|
+
self.strict_ingress = strict_ingress
|
|
836
|
+
# TRULY bounded record of sha256(_safe_str(data)) for every UNTRUSTED value
|
|
837
|
+
# we've issued. A deque(maxlen=N) is the recency window (FIFO-evicts oldest once
|
|
838
|
+
# full); the parallel set is the O(1) membership index kept in lockstep on eviction.
|
|
839
|
+
# Used by strict_ingress to detect VERBATIM re-wrapping of tainted data as "trusted".
|
|
840
|
+
self._fp_window: collections.deque[str] = collections.deque(maxlen=4096)
|
|
841
|
+
self._untrusted_fingerprints: set[str] = set()
|
|
842
|
+
# Sub-value secret IFC: secrets minted through secret() are remembered (bounded, insertion
|
|
843
|
+
# ordered, oldest evicted) so a value that EMBEDS one — "conn=postgres://u:<pw>@db",
|
|
844
|
+
# f"token {pw}" — is labeled secret too, not only an exact whole-value match. Raw values
|
|
845
|
+
# are held because a keyed-hash sliding window costs O(len × distinct lengths) in Python;
|
|
846
|
+
# they are already resident in the caller's Value objects, and are never logged/emitted.
|
|
847
|
+
self._minted: dict[str, None] = {}
|
|
848
|
+
self._minted_lower: tuple[str, ...] = () # lowercased view, rebuilt on remember (not per scan)
|
|
849
|
+
|
|
850
|
+
@staticmethod
|
|
851
|
+
def _fingerprint(data: Any) -> str:
|
|
852
|
+
return hashlib.sha256(_safe_str(data).encode()).hexdigest()
|
|
853
|
+
|
|
854
|
+
_MINTED_MAX = 1024 # remembered minted secrets (FIFO)
|
|
855
|
+
_MINTED_MIN_LEN = 6 # shorter secrets match whole-value only (substring too noisy)
|
|
856
|
+
_MINTED_SCAN_MAX = 1 << 20 # chars of a composed value scanned for embedded secrets
|
|
857
|
+
|
|
858
|
+
def _remember_minted(self, data: Any) -> None:
|
|
859
|
+
variants = encoded_variants(data, self._MINTED_MIN_LEN)
|
|
860
|
+
if not variants:
|
|
861
|
+
return
|
|
862
|
+
for s in variants:
|
|
863
|
+
self._minted.pop(s, None)
|
|
864
|
+
self._minted[s] = None
|
|
865
|
+
while len(self._minted) > self._MINTED_MAX:
|
|
866
|
+
self._minted.pop(next(iter(self._minted)))
|
|
867
|
+
self._minted_lower = tuple({m.lower() for m in self._minted})
|
|
868
|
+
|
|
869
|
+
def _embeds_minted(self, text: str) -> bool:
|
|
870
|
+
if not self._minted_lower or len(text) < self._MINTED_MIN_LEN:
|
|
871
|
+
return False
|
|
872
|
+
# Case-fold for matching (uppercasing an embedded secret is trivial obfuscation; parity with the
|
|
873
|
+
# gateway's canonical matcher) against the pre-lowercased set — NOT re-lowered per call.
|
|
874
|
+
if len(text) > self._MINTED_SCAN_MAX:
|
|
875
|
+
# Slice HEAD and TAIL *before* lowercasing so a 100 MB value isn't copied in full each scan.
|
|
876
|
+
# Mirrors the gateway taint tracker's head+tail retention: a secret padded past the head
|
|
877
|
+
# window (`<1 MiB bulk> + AKIA…`) still lands in the tail. Residual (bounded cost): a secret
|
|
878
|
+
# buried in the MIDDLE of a > _MINTED_SCAN_MAX value, touching neither window, is not found.
|
|
879
|
+
half = self._MINTED_SCAN_MAX // 2
|
|
880
|
+
head, tail = text[:half].lower(), text[-half:].lower()
|
|
881
|
+
return any(m in head or m in tail for m in self._minted_lower)
|
|
882
|
+
text = text.lower()
|
|
883
|
+
return any(m in text for m in self._minted_lower)
|
|
884
|
+
|
|
885
|
+
def _known_secret(self, data: Any) -> bool:
|
|
886
|
+
"""Authoritative registry lookup, tolerant of a policy that predates/lacks
|
|
887
|
+
the hook (e.g. a stub/corrupt policy). Absent hook → False (regex backstop still
|
|
888
|
+
applies). Ingress must not throw here; adjudication's fail-closed wrapper is the
|
|
889
|
+
safety net, but labeling a value should degrade gracefully, not crash."""
|
|
890
|
+
try:
|
|
891
|
+
if self._embeds_minted(_safe_str(data)):
|
|
892
|
+
return True
|
|
893
|
+
except Exception: # noqa: BLE001 — ingress must degrade, not crash (Defect 2)
|
|
894
|
+
pass
|
|
895
|
+
fn = getattr(self.policy, "is_known_secret", None)
|
|
896
|
+
if not callable(fn):
|
|
897
|
+
return False
|
|
898
|
+
try:
|
|
899
|
+
return bool(fn(data))
|
|
900
|
+
except Exception: # noqa: BLE001 — ingress must degrade, not crash (Defect 2)
|
|
901
|
+
return False
|
|
902
|
+
|
|
903
|
+
def _record_untrusted(self, data: Any) -> None:
|
|
904
|
+
"""Remember the fingerprint of untrusted data we issue, so strict_ingress
|
|
905
|
+
can later refuse to launder it. Always recorded (even when strict_ingress=False)
|
|
906
|
+
so the capability is testable and the gateway can inspect it. BOUNDED: the deque
|
|
907
|
+
caps at maxlen; when it evicts the oldest fingerprint we drop it from the set too
|
|
908
|
+
(unless a newer identical fingerprint is still in the window), so neither structure
|
|
909
|
+
grows without bound."""
|
|
910
|
+
fp = self._fingerprint(data)
|
|
911
|
+
if len(self._fp_window) == self._fp_window.maxlen:
|
|
912
|
+
evicted = self._fp_window[0] # about to be pushed out by the append
|
|
913
|
+
if evicted not in list(self._fp_window)[1:]:
|
|
914
|
+
self._untrusted_fingerprints.discard(evicted)
|
|
915
|
+
self._fp_window.append(fp)
|
|
916
|
+
self._untrusted_fingerprints.add(fp)
|
|
917
|
+
|
|
918
|
+
def _is_laundered(self, data: Any) -> bool:
|
|
919
|
+
"""True ONLY if `data` is a VERBATIM re-wrap of previously-seen untrusted
|
|
920
|
+
content: exact sha256-fingerprint match. The former substring heuristic was
|
|
921
|
+
deleted — it catastrophically over-blocked (one short untrusted token flipped
|
|
922
|
+
every later trusted() string containing it) and was unsound (defeated by any
|
|
923
|
+
transform). Exact-match catches the canonical, common laundering path
|
|
924
|
+
`trusted(str(untrusted_value.data))` with near-zero false positives.
|
|
925
|
+
Deterministic; no wall-clock/network."""
|
|
926
|
+
return self._fingerprint(data) in self._untrusted_fingerprints
|
|
927
|
+
|
|
928
|
+
# -- data ingress: label values by provenance --------------------------------
|
|
929
|
+
def trusted(self, data: Any, origin: str) -> Value:
|
|
930
|
+
"""Assert a genuinely trusted origin (config, verified user input, system prompt).
|
|
931
|
+
|
|
932
|
+
NEVER call trusted() on data derived from tool output / untrusted content — use
|
|
933
|
+
derive() so taint propagates.
|
|
934
|
+
|
|
935
|
+
Engine-level anti-laundering (strict_ingress=True) catches only VERBATIM re-wrap
|
|
936
|
+
(exact content match). It is a backstop, not a guarantee — an integration that
|
|
937
|
+
transforms tainted content before re-wrapping defeats it. Real structural
|
|
938
|
+
laundering-prevention belongs to the gateway/SDK provenance tracker (WS2), which
|
|
939
|
+
must route all tool output through untrusted()/derive() and never call trusted()
|
|
940
|
+
on derived data. With strict_ingress=True a verbatim re-wrap of previously-seen
|
|
941
|
+
untrusted content returns an UNTRUSTED-labeled Value (taint preserved) instead of
|
|
942
|
+
trusting it (the default). With strict_ingress=False a re-wrap is trusted as asserted."""
|
|
943
|
+
# Anti-laundering: refuse to bless VERBATIM re-wrapped untrusted data when strict.
|
|
944
|
+
if self.strict_ingress and self._is_laundered(data):
|
|
945
|
+
# Taint preserved — treat exactly as an untrusted ingress.
|
|
946
|
+
return self.untrusted(data, f"strict_ingress:refused_launder:{origin}")
|
|
947
|
+
# Authoritative-first secret determination, regex as advisory backstop.
|
|
948
|
+
# Defect 2 — _safe_str so a hostile __str__ cannot crash this out-of-wrapper path.
|
|
949
|
+
is_secret = self._known_secret(data) or looks_like_secret(_safe_str(data))
|
|
950
|
+
return Value(data, Label(Trust.TRUSTED, is_secret, origin))
|
|
951
|
+
|
|
952
|
+
def untrusted(self, data: Any, origin: str) -> Value:
|
|
953
|
+
self._record_untrusted(data) # Track for anti-laundering (bounded)
|
|
954
|
+
# Authoritative-first secret determination, regex as advisory backstop.
|
|
955
|
+
# Defect 2 — _safe_str so a hostile __str__ cannot crash this out-of-wrapper path.
|
|
956
|
+
is_secret = self._known_secret(data) or looks_like_secret(_safe_str(data))
|
|
957
|
+
return Value(data, Label(Trust.UNTRUSTED, is_secret, origin))
|
|
958
|
+
|
|
959
|
+
def secret(self, data: Any, origin: str) -> Value:
|
|
960
|
+
"""Explicit secret ingress. Returns a TRUSTED value labeled is_secret=True
|
|
961
|
+
UNCONDITIONALLY. This is the path the JIT broker uses to hand back minted
|
|
962
|
+
credentials already labeled — it does not depend on the regex backstop, so
|
|
963
|
+
short/low-entropy secrets (e.g. a DB password) are still correctly labeled and
|
|
964
|
+
cannot egress to a non-allowlisted host."""
|
|
965
|
+
self._remember_minted(data)
|
|
966
|
+
return Value(data, Label(Trust.TRUSTED, True, origin))
|
|
967
|
+
|
|
968
|
+
def derive(self, data: Any, parents: list[Value], origin: str) -> Value:
|
|
969
|
+
"""A value computed from others inherits their joined taint (propagation)."""
|
|
970
|
+
lbl = join([p.label for p in parents])
|
|
971
|
+
# Authoritative registry OR parent secrecy OR regex backstop.
|
|
972
|
+
# Defect 2 — _safe_str so a hostile __str__ cannot crash this out-of-wrapper path.
|
|
973
|
+
is_secret = lbl.is_secret or self._known_secret(data) or looks_like_secret(_safe_str(data))
|
|
974
|
+
lbl = Label(lbl.trust, is_secret, origin or lbl.origin,
|
|
975
|
+
tuple(p.id for p in parents))
|
|
976
|
+
# A derived value that joins to UNTRUSTED is itself untrusted content; record it.
|
|
977
|
+
if lbl.trust is Trust.UNTRUSTED:
|
|
978
|
+
self._record_untrusted(data)
|
|
979
|
+
return Value(data, lbl)
|
|
980
|
+
|
|
981
|
+
# -- the action boundary: the deterministic guarantee ------------------------
|
|
982
|
+
@staticmethod
|
|
983
|
+
def inspect_result(result: Any, budget: int = RESULT_SCAN_BUDGET) -> "ResultInspection":
|
|
984
|
+
"""See module-level inspect_result(). Observational — never changes a verdict."""
|
|
985
|
+
return inspect_result(result, budget)
|
|
986
|
+
|
|
987
|
+
def authorize(self, action: str, args: dict[str, Value], risk: float = 0.0,
|
|
988
|
+
context_tainted: bool = False, plan_step: "PlanStep | None" = None,
|
|
989
|
+
plan_choices: "dict | None" = None) -> Decision:
|
|
990
|
+
"""Fail-CLOSED wrapper. A security control must never fail open: if adjudication itself
|
|
991
|
+
errors (bad input, a bug, a corrupt label), we BLOCK and record it — the request is denied,
|
|
992
|
+
not allowed. The real decision logic lives in `_authorize`.
|
|
993
|
+
|
|
994
|
+
`context_tainted` (session taint): the caller's session has ingested untrusted content
|
|
995
|
+
that may have steered the model, even if no arg is PROVABLY derived from it (e.g. the
|
|
996
|
+
LLM paraphrased it). Sink actions then require STEP_UP unless declassified via
|
|
997
|
+
Policy.context_taint_exempt. Default False keeps cross-engine parity unchanged."""
|
|
998
|
+
ctx: dict = {"t0": time.perf_counter_ns(), "context_tainted": bool(context_tainted), "plan_step": plan_step,
|
|
999
|
+
"plan_choices": plan_choices}
|
|
1000
|
+
try:
|
|
1001
|
+
return self._authorize(action, args, risk, ctx)
|
|
1002
|
+
except Exception as ex: # noqa: BLE001 — deliberately catch-all; safety over specificity
|
|
1003
|
+
return self._emit(str(action), Verdict.BLOCK, "L0:fail-closed",
|
|
1004
|
+
f"enforcement error — failing closed: {type(ex).__name__}: {ex}",
|
|
1005
|
+
ReasonCode.FAIL_CLOSED, ctx=ctx)
|
|
1006
|
+
|
|
1007
|
+
def _content_only_taint(self, tainted: list[str], labels: dict[str, Label],
|
|
1008
|
+
args: dict[str, Value]) -> bool:
|
|
1009
|
+
"""Balanced mode: True iff every tainted arg is proven-provenance CONTENT, or a destination
|
|
1010
|
+
that policy already knows. Strict mode (default) → always False → Rule 1 BLOCKs."""
|
|
1011
|
+
p = self.policy
|
|
1012
|
+
if not getattr(p, "untrusted_content_stepup", False):
|
|
1013
|
+
return False
|
|
1014
|
+
for k in tainted:
|
|
1015
|
+
if labels[k].origin.startswith("unlabeled:"):
|
|
1016
|
+
return False # No provenance at all → stay fail-closed
|
|
1017
|
+
if is_destination_arg(k, p.destination_args):
|
|
1018
|
+
v = args[k].data if isinstance(args[k], Value) else args[k]
|
|
1019
|
+
if _safe_str(v) in p.known_destinations:
|
|
1020
|
+
continue
|
|
1021
|
+
if _host_of({"url": v}) in p.allowlist_hosts and p.allowlist_hosts:
|
|
1022
|
+
continue
|
|
1023
|
+
return False
|
|
1024
|
+
return True
|
|
1025
|
+
|
|
1026
|
+
def _authorize(self, action: str, args: dict[str, Value], risk: float = 0.0,
|
|
1027
|
+
ctx: dict | None = None) -> Decision:
|
|
1028
|
+
ctx = ctx if ctx is not None else {"t0": time.perf_counter_ns(), "context_tainted": False}
|
|
1029
|
+
emit = functools.partial(self._emit, ctx=ctx)
|
|
1030
|
+
args = args or {}
|
|
1031
|
+
sens = self.policy.sens(action)
|
|
1032
|
+
# Fail-closed labeling: build a label for EVERY arg, not only Value args.
|
|
1033
|
+
# A plain-string (unlabeled) arg carries no provenance; the engine cannot tell
|
|
1034
|
+
# "trusted" from "never labeled", so we MUST treat it as UNTRUSTED. Otherwise a
|
|
1035
|
+
# plain-string malicious body into a sink would bypass Rule 1 entirely.
|
|
1036
|
+
arg_labels: dict[str, Label] = {}
|
|
1037
|
+
for k, v in args.items():
|
|
1038
|
+
if isinstance(v, Value):
|
|
1039
|
+
arg_labels[k] = v.label
|
|
1040
|
+
else:
|
|
1041
|
+
arg_labels[k] = Label(
|
|
1042
|
+
trust=Trust.UNTRUSTED,
|
|
1043
|
+
is_secret=looks_like_secret(v) or self._known_secret(v),
|
|
1044
|
+
origin=f"unlabeled:{k}",
|
|
1045
|
+
derived_from=(),
|
|
1046
|
+
)
|
|
1047
|
+
untrusted_labels = [l for l in arg_labels.values() if l.trust is Trust.UNTRUSTED]
|
|
1048
|
+
ctx.update(
|
|
1049
|
+
sink_class=sink_class(action, self.policy),
|
|
1050
|
+
tainted=bool(untrusted_labels),
|
|
1051
|
+
taint_sources=_taint_tags(untrusted_labels),
|
|
1052
|
+
secret_in_args=any(l.is_secret for l in arg_labels.values()),
|
|
1053
|
+
target=target_signals(args, self.policy.allowlist_hosts),
|
|
1054
|
+
)
|
|
1055
|
+
|
|
1056
|
+
# Rule 0 — scope / least privilege (must return before Rule 1).
|
|
1057
|
+
if action not in self.policy.capabilities:
|
|
1058
|
+
return emit(action, Verdict.BLOCK, "L4:scope",
|
|
1059
|
+
f"action '{action}' not in identity capabilities",
|
|
1060
|
+
ReasonCode.SCOPE_DENY)
|
|
1061
|
+
|
|
1062
|
+
# Planned call: matches a step written from the user's request (see PlanStep). Untrusted data
|
|
1063
|
+
# in its SLOTS is not a reason to hold it; everything below except the taint holds still applies.
|
|
1064
|
+
planned = plan_matches(ctx.get("plan_step"), action, args, ctx.get("plan_choices"), self.policy)
|
|
1065
|
+
ctx["planned"] = planned
|
|
1066
|
+
|
|
1067
|
+
# Rule 1 — TAINT/IFC (the differentiator): untrusted data may not parameterize a
|
|
1068
|
+
# SINK. Structural sink default: an action is a sink UNLESS it is explicitly
|
|
1069
|
+
# non-sink (LOW / read-only). This replaces the hand-curated denylist semantics —
|
|
1070
|
+
# unknown actions resolve to HIGH via Policy.sens (fail_closed) and are therefore
|
|
1071
|
+
# sinks; only LOW read-only actions (read_file, query_ledger, list_dir) are
|
|
1072
|
+
# non-sinks, since reading untrusted content is fine, only acting on it isn't.
|
|
1073
|
+
# SINK_ACTIONS is kept as an explicit floor (belt-and-braces). Kills indirect
|
|
1074
|
+
# injection regardless of the action's nominal sensitivity tier.
|
|
1075
|
+
is_sink = ((sens is not Sensitivity.LOW) or (action in SINK_ACTIONS)
|
|
1076
|
+
or action in self.policy.destructive_actions)
|
|
1077
|
+
content_stepup = None
|
|
1078
|
+
# A read of a site the organisation trusts (Policy.allowlisted_reads): untrusted data can steer WHICH
|
|
1079
|
+
# allowlisted page is read, never send anything elsewhere. Secret, scope and risk rules still apply.
|
|
1080
|
+
known_read = (self.policy.allowlisted_reads and self.policy.is_fetch(action)
|
|
1081
|
+
and _egress_allowed(args, self.policy.allowlist_hosts))
|
|
1082
|
+
if is_sink:
|
|
1083
|
+
tainted = [k for k, l in arg_labels.items() if l.trust is Trust.UNTRUSTED]
|
|
1084
|
+
if planned or known_read:
|
|
1085
|
+
# Every argument of a planned call is either a value the planner wrote (matched exactly)
|
|
1086
|
+
# or a typed slot, so untrusted labels here can't steer the tool, the destination or a
|
|
1087
|
+
# fixed value. Secret and policy rules below still apply.
|
|
1088
|
+
tainted = []
|
|
1089
|
+
if tainted:
|
|
1090
|
+
chain = "; ".join(f"{k}<-{arg_labels[k].origin}" for k in tainted)
|
|
1091
|
+
if self._content_only_taint(tainted, arg_labels, args):
|
|
1092
|
+
# Balanced mode: hold for a human instead of a hard deny. Deferred so the
|
|
1093
|
+
# BLOCK rules below (secret egress, high risk) still win.
|
|
1094
|
+
content_stepup = f"untrusted data reached content arg(s) [{chain}]; approval required"
|
|
1095
|
+
else:
|
|
1096
|
+
return emit(action, Verdict.BLOCK, "L3:taint/IFC",
|
|
1097
|
+
f"untrusted data reached sensitive arg(s) [{chain}]",
|
|
1098
|
+
ReasonCode.IFC_UNTRUSTED_TO_SINK)
|
|
1099
|
+
|
|
1100
|
+
# Rule 2 — secret control at sinks. Secrets here are TRUSTED values (e.g. from
|
|
1101
|
+
# Engine.secret()), so Rule 1 (untrusted→sink) did NOT fire and still takes
|
|
1102
|
+
# precedence over this rule. Two sink flavors, different verdicts:
|
|
1103
|
+
# (a) EGRESS_ACTIONS (has a destination host): secret → non-allowlisted host is a
|
|
1104
|
+
# hard exfiltration path → BLOCK. Unchanged S3 behavior.
|
|
1105
|
+
# (b) Non-egress SINK actions (git_commit, destructive actions, wire_transfer,
|
|
1106
|
+
# kms_decrypt, …): a secret reaching a durable/persistent sink (e.g. a
|
|
1107
|
+
# credential committed to git) is dangerous but may be legitimate → STEP_UP
|
|
1108
|
+
# (human approval) rather than hard-deny. This closes the "secret committed to
|
|
1109
|
+
# git is TRUSTED so nothing fired → ALLOW" hole without over-blocking.
|
|
1110
|
+
# Sub-value secrets: a secret MINTED via secret() and later embedded in a larger
|
|
1111
|
+
# composed string is labeled is_secret at ingress (trusted/untrusted/derive/unlabeled)
|
|
1112
|
+
# via _embeds_minted (head+tail scan over the first/last _MINTED_SCAN_MAX/2 chars of an
|
|
1113
|
+
# oversized value). Registered/minted secrets also precompute common encoded forms
|
|
1114
|
+
# (base64/url-safe base64, hex, percent-encoding, reversed) so one-step encoded exfil
|
|
1115
|
+
# is still secret-labeled. Residual: split/chunked secrets are not recognised; and in a
|
|
1116
|
+
# value larger than _MINTED_SCAN_MAX, a secret buried in the middle (outside both the head
|
|
1117
|
+
# and tail windows) is not found.
|
|
1118
|
+
# Egress is a property of the CALL, not only of three canonical names: any sink whose arguments
|
|
1119
|
+
# name a network destination (an MCP `post_webhook`, a `slack_post`) can carry a secret out.
|
|
1120
|
+
has_secret = any(l.is_secret for l in arg_labels.values())
|
|
1121
|
+
# Explicit durable sinks keep their own rule below (a URL in a commit is content, not a destination).
|
|
1122
|
+
egress_like = action in EGRESS_ACTIONS or (is_sink and action not in SINK_ACTIONS and bool(_egress_hosts(args)))
|
|
1123
|
+
if egress_like:
|
|
1124
|
+
if has_secret and not _secret_egress_allowed(action, args, self.policy.allowlist_hosts):
|
|
1125
|
+
primary = _host_of(args)
|
|
1126
|
+
bad = primary if primary is not None and primary not in self.policy.allowlist_hosts else next(
|
|
1127
|
+
(h for h in _egress_hosts(args) if h not in self.policy.allowlist_hosts), primary)
|
|
1128
|
+
return emit(action, Verdict.BLOCK, "L3:secret-egress",
|
|
1129
|
+
f"secret in egress to non-allowlisted host '{bad or '?'}'",
|
|
1130
|
+
ReasonCode.SECRET_EGRESS_DENY)
|
|
1131
|
+
# A durable sink (git commit, transfer, destructive...) still needs approval for a secret even when
|
|
1132
|
+
# every destination it names is allowlisted: the secret is written somewhere that keeps it.
|
|
1133
|
+
if has_secret and action in SINK_ACTIONS and action not in EGRESS_ACTIONS:
|
|
1134
|
+
return emit(action, Verdict.STEP_UP, "L3:secret-sink",
|
|
1135
|
+
f"secret-labeled arg reaching durable sink '{action}' requires approval",
|
|
1136
|
+
ReasonCode.SECRET_TO_SINK_STEPUP)
|
|
1137
|
+
# Agent memory is durable too: a secret written there is recalled into later sessions and other tools.
|
|
1138
|
+
# (Untrusted content may be written: it is recorded as tainted and comes back untrusted on recall.)
|
|
1139
|
+
if has_secret and action in self.policy.memory_write_actions:
|
|
1140
|
+
return emit(action, Verdict.STEP_UP, "L3:secret-sink",
|
|
1141
|
+
f"secret-labeled arg written to agent memory via '{action}' requires approval",
|
|
1142
|
+
ReasonCode.SECRET_TO_SINK_STEPUP)
|
|
1143
|
+
|
|
1144
|
+
if content_stepup is not None:
|
|
1145
|
+
if risk >= 0.75:
|
|
1146
|
+
return emit(action, Verdict.BLOCK, "L1/L2:high-risk",
|
|
1147
|
+
f"untrusted content at sink with high risk score {risk:.2f}",
|
|
1148
|
+
ReasonCode.RISK_HIGH_BLOCK)
|
|
1149
|
+
return emit(action, Verdict.STEP_UP, "L3:taint/IFC", content_stepup,
|
|
1150
|
+
ReasonCode.UNTRUSTED_CONTENT_STEPUP)
|
|
1151
|
+
|
|
1152
|
+
# Rule 2b — SESSION (context) TAINT: the session has ingested untrusted content, so
|
|
1153
|
+
# the model's output may be steered by it even when no arg is provably derived from it
|
|
1154
|
+
# (paraphrase/summarize laundering). Not proof → STEP_UP (human confirms), not BLOCK.
|
|
1155
|
+
# Policy may declassify specific sinks; proven taint above is never declassified.
|
|
1156
|
+
# Never WEAKER than the rest of the pipeline: high probabilistic risk falls through to the
|
|
1157
|
+
# Rule 5 BLOCK. Only a read-style fetch to an allowlisted host is exempt; WRITE egress
|
|
1158
|
+
# (http_post / send_email) steps up even to allowlisted hosts — posting private data to a
|
|
1159
|
+
# trusted host (public issue / PR) is the canonical lethal-trifecta exfil.
|
|
1160
|
+
if (is_sink and ctx.get("context_tainted") and risk < 0.75 and not planned
|
|
1161
|
+
and action not in getattr(self.policy, "context_taint_exempt", set())
|
|
1162
|
+
and not known_read
|
|
1163
|
+
and not (action == "http_fetch" and _egress_allowed(args, self.policy.allowlist_hosts))):
|
|
1164
|
+
return emit(action, Verdict.STEP_UP, "L3:context-taint",
|
|
1165
|
+
f"session ingested untrusted content; '{action}' needs approval",
|
|
1166
|
+
ReasonCode.CONTEXT_TAINT_STEPUP)
|
|
1167
|
+
|
|
1168
|
+
# Rule 3 — destructive prod actions require human step-up
|
|
1169
|
+
if self.policy.is_destructive(action) and self.policy.env == "prod":
|
|
1170
|
+
return emit(action, Verdict.STEP_UP, "L4:policy",
|
|
1171
|
+
f"destructive action '{action}' on prod requires approval",
|
|
1172
|
+
ReasonCode.DESTRUCTIVE_STEPUP)
|
|
1173
|
+
|
|
1174
|
+
# Rule 4 — high-value transfer threshold → step-up
|
|
1175
|
+
if action == "wire_transfer":
|
|
1176
|
+
amt = _amount_of(args)
|
|
1177
|
+
limit = self.policy.transfer_threshold()
|
|
1178
|
+
if amt is not None and amt > limit:
|
|
1179
|
+
return emit(action, Verdict.STEP_UP, "L4:policy",
|
|
1180
|
+
f"wire_transfer {amt} exceeds {limit:g} threshold",
|
|
1181
|
+
ReasonCode.TRANSFER_THRESHOLD_STEPUP)
|
|
1182
|
+
|
|
1183
|
+
# Rule 5 — probabilistic fusion (advisory L1/L2 risk score, supplied by the caller).
|
|
1184
|
+
# Only escalates the otherwise-ALLOW path; deterministic BLOCK/STEP_UP above already
|
|
1185
|
+
# returned, so the guarantee always overrides a "safe" model score, and never vice-versa.
|
|
1186
|
+
if risk >= 0.75:
|
|
1187
|
+
return emit(action, Verdict.BLOCK, "L1/L2:high-risk",
|
|
1188
|
+
f"probabilistic risk {risk:.2f} >= 0.75",
|
|
1189
|
+
ReasonCode.RISK_HIGH_BLOCK)
|
|
1190
|
+
if risk >= 0.40:
|
|
1191
|
+
return emit(action, Verdict.STEP_UP, "L1/L2:elevated-risk",
|
|
1192
|
+
f"probabilistic risk {risk:.2f} elevated",
|
|
1193
|
+
ReasonCode.RISK_ELEVATED_STEPUP)
|
|
1194
|
+
|
|
1195
|
+
if known_read and not planned and (ctx.get("tainted") or ctx.get("context_tainted")):
|
|
1196
|
+
return emit(action, Verdict.ALLOW, "L3:known-read",
|
|
1197
|
+
"a read of an allowlisted site; untrusted data can only choose which allowlisted page",
|
|
1198
|
+
ReasonCode.ALLOWLISTED_READ)
|
|
1199
|
+
if planned and (ctx.get("tainted") or ctx.get("context_tainted")):
|
|
1200
|
+
return emit(action, Verdict.ALLOW, "L3:plan",
|
|
1201
|
+
"planned from the user's request; untrusted data only in planned slots",
|
|
1202
|
+
ReasonCode.PLANNED_CALL)
|
|
1203
|
+
return emit(action, Verdict.ALLOW, "L4:policy", "within policy",
|
|
1204
|
+
ReasonCode.ALLOW_WITHIN_POLICY)
|
|
1205
|
+
|
|
1206
|
+
# -- audit (immutable-style append log) --------------------------------------
|
|
1207
|
+
def _emit(self, action: str, verdict: Verdict, layer: str, reason: str,
|
|
1208
|
+
reason_code: str = "", ctx: dict | None = None) -> Decision:
|
|
1209
|
+
ctx = ctx or {}
|
|
1210
|
+
pv = getattr(self.policy, "version", "") or ""
|
|
1211
|
+
t0 = ctx.get("t0")
|
|
1212
|
+
latency_us = max(0, (time.perf_counter_ns() - t0) // 1000) if t0 else 0
|
|
1213
|
+
d = Decision(verdict, layer, reason, action, self.identity, reason_code, pv,
|
|
1214
|
+
sink_class=ctx.get("sink_class", ""),
|
|
1215
|
+
tainted=bool(ctx.get("tainted", False)),
|
|
1216
|
+
taint_sources=tuple(ctx.get("taint_sources", ())),
|
|
1217
|
+
secret_in_args=bool(ctx.get("secret_in_args", False)),
|
|
1218
|
+
context_tainted=bool(ctx.get("context_tainted", False)),
|
|
1219
|
+
latency_us=int(latency_us),
|
|
1220
|
+
target=dict(ctx.get("target") or {}),
|
|
1221
|
+
planned=bool(ctx.get("planned", False)))
|
|
1222
|
+
event = {
|
|
1223
|
+
"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
1224
|
+
"id": "dec_" + uuid.uuid4().hex[:10],
|
|
1225
|
+
"identity": self.identity, "action": action,
|
|
1226
|
+
"verdict": verdict.value, "layer": layer, "reason": reason,
|
|
1227
|
+
"reason_code": reason_code,
|
|
1228
|
+
"policy_version": pv, # Audit which policy revision produced this
|
|
1229
|
+
**decision_signals(d),
|
|
1230
|
+
}
|
|
1231
|
+
self.events.append(event)
|
|
1232
|
+
if self._audit_path:
|
|
1233
|
+
with open(self._audit_path, "a") as f:
|
|
1234
|
+
f.write(json.dumps(event) + "\n")
|
|
1235
|
+
return d
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
SIGNALS_SCHEMA_VERSION = 2
|
|
1239
|
+
|
|
1240
|
+
|
|
1241
|
+
def decision_signals(d: Decision) -> dict:
|
|
1242
|
+
"""Signals-v2 metadata block for a decision — the single mapping every mediator (SDK,
|
|
1243
|
+
reporter, audit log) uses, so the control plane sees one shape. Metadata only."""
|
|
1244
|
+
return {
|
|
1245
|
+
"v": SIGNALS_SCHEMA_VERSION,
|
|
1246
|
+
"sink_class": d.sink_class,
|
|
1247
|
+
"tainted": d.tainted,
|
|
1248
|
+
"taint_sources": list(d.taint_sources),
|
|
1249
|
+
"secret_in_args": d.secret_in_args,
|
|
1250
|
+
"context_tainted": d.context_tainted,
|
|
1251
|
+
"latency_us": d.latency_us,
|
|
1252
|
+
**({"planned": True} if getattr(d, "planned", False) else {}),
|
|
1253
|
+
**(getattr(d, "target", None) or {}),
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
|
|
1257
|
+
# ─────────────────── target signals: WHAT a call touched, as categories ───────────────────
|
|
1258
|
+
# Every decision says what kind of thing it targeted without shipping the thing itself, so the
|
|
1259
|
+
# control plane can reason about destinations and paths (lateral movement, known-bad services,
|
|
1260
|
+
# credential access) while raw values stay in the customer's process. Identical in every engine
|
|
1261
|
+
# (Python, TS enforce.ts, Go gateway target.go) and pinned by the same test table.
|
|
1262
|
+
# dest_class allowlisted | internal | ip_literal | public (the primary destination)
|
|
1263
|
+
# dest_fp first 32 hex of sha256(lowercased host, port stripped). Unsalted ON PURPOSE so the
|
|
1264
|
+
# control plane can match it against known-bad services; a public host is guessable
|
|
1265
|
+
# from it, an internal name is not sent in clear.
|
|
1266
|
+
# dest_root_fp the same fingerprint of the last two labels (a host with ≥3 labels, not an IP), so a
|
|
1267
|
+
# service that hands out random subdomains (abc.oast.fun) still matches its root
|
|
1268
|
+
# dest_count how many destinations the call names (1–16; a decoy-host call names several)
|
|
1269
|
+
# path_class credentials | system | temp | home | workspace | other (first path-like arg)
|
|
1270
|
+
# arg_bytes lt_1k | lt_10k | lt_100k | ge_100k (UTF-8 size of all argument values)
|
|
1271
|
+
# amount_band lt_100 | lt_500 | lt_1k | lt_2500 | lt_5k | le_10k | gt_10k (the `amount` arg, parsed as the
|
|
1272
|
+
# transfer rule parses it; only when finite). Lets replay judge a lowered transfer threshold
|
|
1273
|
+
# (docs/design/POLICY-THRESHOLDS.md) without sending the amount itself.
|
|
1274
|
+
_INTERNAL_SUFFIXES = (".internal", ".local", ".localhost", ".lan", ".home", ".corp", ".intranet")
|
|
1275
|
+
_PATH_TOKENS = frozenset({"path", "file", "filename", "filepath", "dir", "directory", "src", "dst",
|
|
1276
|
+
"source", "target", "dest", "folder"})
|
|
1277
|
+
_CRED_MARKERS = ("/.ssh/", "id_rsa", "id_ed25519", "/.aws/", "/.env", ".netrc", ".npmrc", ".pypirc",
|
|
1278
|
+
".git-credentials", "/.kube/config", "/.docker/config.json", "/.gnupg/", "credentials")
|
|
1279
|
+
_SYSTEM_PREFIXES = ("/etc/", "/usr/", "/bin/", "/sbin/", "/var/", "/proc/", "/sys/", "/boot/", "/root/",
|
|
1280
|
+
"c:/windows/")
|
|
1281
|
+
_TEMP_PREFIXES = ("/tmp/", "/var/tmp/", "/private/tmp/", "/dev/shm/")
|
|
1282
|
+
_HOME_PREFIXES = ("~/", "/users/", "/home/")
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
def _strip_port(host: str) -> str:
|
|
1286
|
+
h = host.strip().lower().rstrip(".")
|
|
1287
|
+
if h.startswith("["): # [v6]:port
|
|
1288
|
+
return h[1:h.index("]")] if "]" in h else h[1:]
|
|
1289
|
+
if h.count(":") == 1:
|
|
1290
|
+
return h.split(":", 1)[0]
|
|
1291
|
+
return h
|
|
1292
|
+
|
|
1293
|
+
|
|
1294
|
+
# An explicit list (not ipaddress.is_private, whose ranges vary by Python version) so every engine
|
|
1295
|
+
# classifies the same literal the same way.
|
|
1296
|
+
_PRIVATE_NETS = ("0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16",
|
|
1297
|
+
"172.16.0.0/12", "192.168.0.0/16", "::1/128", "fc00::/7", "fe80::/10")
|
|
1298
|
+
|
|
1299
|
+
|
|
1300
|
+
def _ip_kind(h: str) -> str | None:
|
|
1301
|
+
"""'private' / 'public' for an IP literal, else None."""
|
|
1302
|
+
import ipaddress
|
|
1303
|
+
try:
|
|
1304
|
+
ip = ipaddress.ip_address(h)
|
|
1305
|
+
except ValueError:
|
|
1306
|
+
return None
|
|
1307
|
+
if ip.version == 6 and ip.ipv4_mapped:
|
|
1308
|
+
ip = ip.ipv4_mapped
|
|
1309
|
+
return "private" if any(ip in ipaddress.ip_network(n) for n in _PRIVATE_NETS
|
|
1310
|
+
if ipaddress.ip_network(n).version == ip.version) else "public"
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
def dest_class(host: str, allowlist: Iterable[str]) -> str:
|
|
1314
|
+
if host in set(allowlist):
|
|
1315
|
+
return "allowlisted"
|
|
1316
|
+
h = _strip_port(host)
|
|
1317
|
+
kind = _ip_kind(h)
|
|
1318
|
+
if kind == "private":
|
|
1319
|
+
return "internal"
|
|
1320
|
+
if kind == "public":
|
|
1321
|
+
return "ip_literal"
|
|
1322
|
+
if h == "localhost" or "." not in h or h.endswith(_INTERNAL_SUFFIXES):
|
|
1323
|
+
return "internal"
|
|
1324
|
+
return "public"
|
|
1325
|
+
|
|
1326
|
+
|
|
1327
|
+
def dest_fingerprint(host: str) -> str:
|
|
1328
|
+
return hashlib.sha256(_strip_port(host).encode()).hexdigest()[:32]
|
|
1329
|
+
|
|
1330
|
+
|
|
1331
|
+
def to_fingerprint(args: dict) -> str | None:
|
|
1332
|
+
"""Every destination a call names, as one fingerprint: the HOST of each URL value, the full
|
|
1333
|
+
identifier (lower-cased) of every other destination arg (to, recipient, channel, iban,
|
|
1334
|
+
participants…; list elements count one by one). Domain-separated from dest_fp, which is the
|
|
1335
|
+
primary host only: an approval scoped "to cfo@corp.example" must not cover another address at
|
|
1336
|
+
corp.example, and a host never collides with an identifier. None when the call names none.
|
|
1337
|
+
Implemented identically in the TS SDK and the Go gateway (target_golden.json)."""
|
|
1338
|
+
items: set[str] = set()
|
|
1339
|
+
for k in sorted(args):
|
|
1340
|
+
v = args[k].data if isinstance(args[k], Value) else args[k]
|
|
1341
|
+
vals = list(v) if isinstance(v, (list, tuple)) else [v]
|
|
1342
|
+
named = is_destination_arg(k)
|
|
1343
|
+
for x in vals:
|
|
1344
|
+
sx = _safe_str(x).strip()
|
|
1345
|
+
if not sx:
|
|
1346
|
+
continue
|
|
1347
|
+
if sx.startswith(("http://", "https://")):
|
|
1348
|
+
h = _parse_host(sx)
|
|
1349
|
+
if h:
|
|
1350
|
+
items.add("host:" + _strip_port(h))
|
|
1351
|
+
elif named:
|
|
1352
|
+
items.add("id:" + sx.lower())
|
|
1353
|
+
if not items:
|
|
1354
|
+
return None
|
|
1355
|
+
return hashlib.sha256(("xtrom-to\x00" + "\n".join(sorted(items))).encode()).hexdigest()[:32]
|
|
1356
|
+
|
|
1357
|
+
|
|
1358
|
+
def dest_root(host: str) -> str | None:
|
|
1359
|
+
"""The last two labels of a ≥3-label DNS host, else None."""
|
|
1360
|
+
h = _strip_port(host)
|
|
1361
|
+
labels = h.split(".")
|
|
1362
|
+
if len(labels) < 3 or _ip_kind(h) is not None or not all(labels):
|
|
1363
|
+
return None
|
|
1364
|
+
return ".".join(labels[-2:])
|
|
1365
|
+
|
|
1366
|
+
|
|
1367
|
+
def path_class(p: str) -> str:
|
|
1368
|
+
s = p.strip().replace("\\", "/").lower()
|
|
1369
|
+
if any(m in s for m in _CRED_MARKERS):
|
|
1370
|
+
return "credentials"
|
|
1371
|
+
if s.startswith(_SYSTEM_PREFIXES):
|
|
1372
|
+
return "system"
|
|
1373
|
+
if s.startswith(_TEMP_PREFIXES):
|
|
1374
|
+
return "temp"
|
|
1375
|
+
if s.startswith(_HOME_PREFIXES):
|
|
1376
|
+
return "home"
|
|
1377
|
+
if not s.startswith("/") and not re.match(r"^[a-z]:/", s):
|
|
1378
|
+
return "workspace"
|
|
1379
|
+
return "other"
|
|
1380
|
+
|
|
1381
|
+
|
|
1382
|
+
def _looks_like_path(v: str) -> bool:
|
|
1383
|
+
return v.startswith(("/", "~/", "./", "../")) or bool(re.match(r"^[A-Za-z]:[\\/]", v))
|
|
1384
|
+
|
|
1385
|
+
|
|
1386
|
+
def _amount_band(a: float) -> str:
|
|
1387
|
+
# Edges are where a policy's threshold is likely to sit; "le_10k" ends AT the built-in hold (amount > 10000).
|
|
1388
|
+
for edge, band in ((100, "lt_100"), (500, "lt_500"), (1000, "lt_1k"), (2500, "lt_2500"), (5000, "lt_5k")):
|
|
1389
|
+
if a < edge:
|
|
1390
|
+
return band
|
|
1391
|
+
return "le_10k" if a <= 10000 else "gt_10k"
|
|
1392
|
+
|
|
1393
|
+
|
|
1394
|
+
def _bytes_bucket(n: int) -> str:
|
|
1395
|
+
return "lt_1k" if n < 1024 else "lt_10k" if n < 10240 else "lt_100k" if n < 102400 else "ge_100k"
|
|
1396
|
+
|
|
1397
|
+
|
|
1398
|
+
def target_signals(args: dict, allowlist: Iterable[str] = ()) -> dict:
|
|
1399
|
+
"""Categories for what a call targeted (see the block comment above). Never raises."""
|
|
1400
|
+
try:
|
|
1401
|
+
out: dict = {}
|
|
1402
|
+
hosts = _egress_hosts(args)
|
|
1403
|
+
host = _host_of(args) or (hosts[0] if hosts else None) # else the first destination named
|
|
1404
|
+
if host:
|
|
1405
|
+
out["dest_class"] = dest_class(host, allowlist)
|
|
1406
|
+
out["dest_fp"] = dest_fingerprint(host)
|
|
1407
|
+
root = dest_root(host)
|
|
1408
|
+
if root:
|
|
1409
|
+
out["dest_root_fp"] = dest_fingerprint(root)
|
|
1410
|
+
if hosts or host:
|
|
1411
|
+
out["dest_count"] = min(16, max(1, len(hosts)))
|
|
1412
|
+
to_fp = to_fingerprint(args)
|
|
1413
|
+
if to_fp:
|
|
1414
|
+
out["to_fp"] = to_fp
|
|
1415
|
+
total = 0
|
|
1416
|
+
path = None
|
|
1417
|
+
for k in sorted(args):
|
|
1418
|
+
v = args[k].data if isinstance(args[k], Value) else args[k]
|
|
1419
|
+
s = _safe_str(v)
|
|
1420
|
+
total += len(s.encode("utf-8", "surrogatepass"))
|
|
1421
|
+
if path is None and isinstance(v, str) and (
|
|
1422
|
+
any(t in _PATH_TOKENS for t in str(k).lower().split("_")) or _looks_like_path(s)) \
|
|
1423
|
+
and not s.startswith(("http://", "https://")):
|
|
1424
|
+
path = s
|
|
1425
|
+
if path:
|
|
1426
|
+
out["path_class"] = path_class(path)
|
|
1427
|
+
out["arg_bytes"] = _bytes_bucket(total)
|
|
1428
|
+
amt = _amount_of(args)
|
|
1429
|
+
if amt is not None and math.isfinite(amt):
|
|
1430
|
+
out["amount_band"] = _amount_band(amt)
|
|
1431
|
+
return out
|
|
1432
|
+
except Exception: # noqa: BLE001 — a signal must never break adjudication
|
|
1433
|
+
return {}
|
|
1434
|
+
|
|
1435
|
+
|
|
1436
|
+
def _parse_host(s: str) -> str | None:
|
|
1437
|
+
"""CANONICAL single-value host parse — identical in every engine. ONLY http:// and https:// are
|
|
1438
|
+
egress schemes; any other / absent scheme returns the RAW string (it can't match an allowlist
|
|
1439
|
+
entry, so e.g. a secret over ftp:// fails CLOSED). The authority ends at the first / \\ ? #, and
|
|
1440
|
+
the host sits after the LAST "@" within it — the same host a WHATWG client connects to."""
|
|
1441
|
+
if s.startswith("http://"):
|
|
1442
|
+
rest = s[7:]
|
|
1443
|
+
elif s.startswith("https://"):
|
|
1444
|
+
rest = s[8:]
|
|
1445
|
+
else:
|
|
1446
|
+
return s
|
|
1447
|
+
# The authority ends at the first "/", "\\", "?" or "#": WHATWG (fetch, browsers, Node) and urllib3
|
|
1448
|
+
# treat "\\" as a path separator for http(s), so "https://evil.com\\@allowed.com" goes to evil.com.
|
|
1449
|
+
for i, ch in enumerate(rest):
|
|
1450
|
+
if ch in "/\\?#":
|
|
1451
|
+
rest = rest[:i]
|
|
1452
|
+
break
|
|
1453
|
+
if "@" in rest:
|
|
1454
|
+
rest = rest.rsplit("@", 1)[1] # userinfo@host → host is after the LAST @
|
|
1455
|
+
return rest or None
|
|
1456
|
+
|
|
1457
|
+
|
|
1458
|
+
def _host_of(args: dict[str, Value]) -> str | None:
|
|
1459
|
+
# The PRIMARY destination (fixed key priority host, url, to, endpoint) — what a decision is
|
|
1460
|
+
# labelled with. NOT the egress check: a request can name several destinations, and every one
|
|
1461
|
+
# of them must be allowlisted (see _egress_hosts). Implemented identically in all four engines.
|
|
1462
|
+
for key in ("host", "url", "to", "endpoint"):
|
|
1463
|
+
if key in args:
|
|
1464
|
+
v = args[key].data if isinstance(args[key], Value) else args[key]
|
|
1465
|
+
return _parse_host(str(v))
|
|
1466
|
+
return None
|
|
1467
|
+
|
|
1468
|
+
|
|
1469
|
+
# Arg-name tokens that carry WHERE data is sent (matched per "_"-separated token, so callback_url,
|
|
1470
|
+
# webhook_url, redirect_uri and to_address count). Narrower than DEFAULT_DESTINATION_ARGS on purpose:
|
|
1471
|
+
# `repo`, `account`, `email` name a target inside a service, not a network destination.
|
|
1472
|
+
EGRESS_HOST_TOKENS = frozenset({
|
|
1473
|
+
"host", "url", "uri", "endpoint", "webhook", "callback", "destination", "dest", "domain", "server", "to",
|
|
1474
|
+
})
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
def _egress_hosts(args: dict[str, Value]) -> list[str]:
|
|
1478
|
+
"""EVERY destination a request names, in sorted arg-name order: args whose name carries a host
|
|
1479
|
+
token, plus any arg whose whole value is an http(s) URL. Secret egress is allowed only if each one
|
|
1480
|
+
is allowlisted — checking only the first let a benign allowlisted `url` cover an attacker
|
|
1481
|
+
`webhook`/`callback` in the same call (the decoy-host evasion). Identical in every engine."""
|
|
1482
|
+
out: list[str] = []
|
|
1483
|
+
for k in sorted(args):
|
|
1484
|
+
v = args[k].data if isinstance(args[k], Value) else args[k]
|
|
1485
|
+
s = str(v)
|
|
1486
|
+
if any(t in EGRESS_HOST_TOKENS for t in str(k).lower().split("_")) \
|
|
1487
|
+
or s.startswith(("http://", "https://")):
|
|
1488
|
+
h = _parse_host(s)
|
|
1489
|
+
if h and h not in out:
|
|
1490
|
+
out.append(h)
|
|
1491
|
+
return out
|
|
1492
|
+
|
|
1493
|
+
|
|
1494
|
+
def _egress_allowed(args: dict[str, Value], allowlist: set[str]) -> bool:
|
|
1495
|
+
"""True iff the PRIMARY destination (_host_of) is allowlisted AND so is every other destination
|
|
1496
|
+
the request names. Strictly tighter than the primary check alone: no primary destination still
|
|
1497
|
+
fails closed, and an extra destination can only add a BLOCK, never remove one."""
|
|
1498
|
+
primary = _host_of(args)
|
|
1499
|
+
return primary is not None and primary in allowlist and all(h in allowlist for h in _egress_hosts(args))
|
|
1500
|
+
|
|
1501
|
+
|
|
1502
|
+
def _secret_egress_allowed(action: str, args: dict[str, Value], allowlist: set[str]) -> bool:
|
|
1503
|
+
"""May a secret leave on this call? A canonical egress action needs its primary destination and every
|
|
1504
|
+
other named destination allowlisted (_egress_allowed). Any other sink is egress only because it names
|
|
1505
|
+
destinations (_egress_hosts is non-empty), so each of those must be allowlisted. Identical in every engine."""
|
|
1506
|
+
if action in EGRESS_ACTIONS:
|
|
1507
|
+
return _egress_allowed(args, allowlist)
|
|
1508
|
+
hosts = _egress_hosts(args)
|
|
1509
|
+
return bool(hosts) and all(h in allowlist for h in hosts)
|
|
1510
|
+
|
|
1511
|
+
|
|
1512
|
+
def _amount_of(args: dict[str, Value]) -> float | None:
|
|
1513
|
+
if "amount" in args:
|
|
1514
|
+
v = args["amount"].data if isinstance(args["amount"], Value) else args["amount"]
|
|
1515
|
+
try:
|
|
1516
|
+
return float(v)
|
|
1517
|
+
except (TypeError, ValueError):
|
|
1518
|
+
return None
|
|
1519
|
+
return None
|