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
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Xtrom interface contracts — the stable ABI between the control plane, the data
|
|
3
|
+
plane, and the pluggable backends.
|
|
4
|
+
|
|
5
|
+
These are the load-bearing contracts. Every implementation (Python reference,
|
|
6
|
+
Rust production engine, first-party AWS/GCP/Azure/Vault brokers, and any
|
|
7
|
+
future third-party plug-ins) MUST honor them exactly. Anything that violates
|
|
8
|
+
these contracts violates the product invariants in ``product/PRODUCT.md``.
|
|
9
|
+
|
|
10
|
+
Three contracts:
|
|
11
|
+
|
|
12
|
+
- :mod:`~xtrom.interfaces.idp_broker` — the pluggable JIT identity broker.
|
|
13
|
+
Every credential the data plane hands to an agent is minted through one of
|
|
14
|
+
these. Zero standing secrets, TTL-bounded, revocable-or-short-lived.
|
|
15
|
+
- :mod:`~xtrom.interfaces.policy_engine` — the deterministic enforcement
|
|
16
|
+
boundary. Given a signed policy bundle and a tool-call event, produces a
|
|
17
|
+
verdict + a taint-state delta + a trace. Pure function of its inputs
|
|
18
|
+
(invariant #1: determinism).
|
|
19
|
+
- :mod:`~xtrom.interfaces.corpus_sink` — the ITDR corpus + audit write path.
|
|
20
|
+
Where enforcement decisions and identity events go so they can be replayed
|
|
21
|
+
(invariant #3) and used to train the control-plane detection models
|
|
22
|
+
(invariant #2 — models stay server-side, corpus is the training substrate).
|
|
23
|
+
|
|
24
|
+
These interfaces are intentionally small. New capabilities are added by
|
|
25
|
+
composing them, never by extending a single interface with more methods.
|
|
26
|
+
"""
|
|
27
|
+
from .idp_broker import IdPBroker, IdPBrokerError, IssuedCredential
|
|
28
|
+
from .policy_engine import PolicyEngine, PolicyEngineError, Verdict, EnforcementDecision
|
|
29
|
+
from .corpus_sink import CorpusSink, CorpusSinkError, CorpusEvent
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"IdPBroker",
|
|
33
|
+
"IdPBrokerError",
|
|
34
|
+
"IssuedCredential",
|
|
35
|
+
"PolicyEngine",
|
|
36
|
+
"PolicyEngineError",
|
|
37
|
+
"Verdict",
|
|
38
|
+
"EnforcementDecision",
|
|
39
|
+
"CorpusSink",
|
|
40
|
+
"CorpusSinkError",
|
|
41
|
+
"CorpusEvent",
|
|
42
|
+
]
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CorpusSink — the ITDR corpus + audit write contract.
|
|
3
|
+
|
|
4
|
+
Where every enforcement decision, identity event, and ITDR detection goes
|
|
5
|
+
after the data plane produces it. Two consumers downstream:
|
|
6
|
+
|
|
7
|
+
1. **WORM audit trail** — customer-visible, replayable, tamper-evident.
|
|
8
|
+
Powers the console Audit screen, SIEM export, and compliance evidence.
|
|
9
|
+
2. **Cross-fleet ITDR corpus** — the compounding moat. Every tenant's
|
|
10
|
+
labeled events feed the control-plane detection models (invariant #2:
|
|
11
|
+
ML stays server-side). Consent + tenancy boundaries are enforced by
|
|
12
|
+
the control plane; the sink itself is content-agnostic.
|
|
13
|
+
|
|
14
|
+
Product invariants surfaced here:
|
|
15
|
+
|
|
16
|
+
- **Invariant #3 — Replayability.** Every written event MUST be sufficient
|
|
17
|
+
to reproduce the original decision on a fresh engine given the same
|
|
18
|
+
``policy_bundle.version``. Sinks that drop fields, batch-lossy, or
|
|
19
|
+
mutate event bodies violate this.
|
|
20
|
+
- **Append-only, monotonic.** The sink MUST NOT rewrite or delete a
|
|
21
|
+
previously-accepted event (WORM). Backends that support retention
|
|
22
|
+
(S3 Object Lock, DynamoDB TTL) are configured externally, never by
|
|
23
|
+
the enforcement path.
|
|
24
|
+
|
|
25
|
+
Reference production implementation lives in ``xtrom_intel`` (corpus
|
|
26
|
+
side) and the control-plane audit handlers (WORM audit side). Both
|
|
27
|
+
conform to this interface.
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from abc import ABC, abstractmethod
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from typing import Any, Iterable
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CorpusSinkError(Exception):
|
|
37
|
+
"""Raised on unrecoverable sink failure.
|
|
38
|
+
|
|
39
|
+
Callers (the gateway, the SDK) MUST NOT drop the event on this exception.
|
|
40
|
+
Retry with backoff, then fall back to the DLQ (see gateway's
|
|
41
|
+
``webhook_retry`` and the DLQ hardening). Losing an event to an
|
|
42
|
+
exception is an invariant-3 violation — the audit trail becomes
|
|
43
|
+
incomplete and decisions become un-replayable.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class CorpusEvent:
|
|
49
|
+
"""A single event written to the corpus.
|
|
50
|
+
|
|
51
|
+
The shape matches ``schemas/events/v1.json`` (published alongside the
|
|
52
|
+
policy schema). Additive-only within v1; a new required field means v2.
|
|
53
|
+
|
|
54
|
+
Attributes:
|
|
55
|
+
event_id: Globally unique event id (UUIDv7 recommended for lexical-
|
|
56
|
+
time-ordering). Duplicate ids MUST be idempotent no-ops in the
|
|
57
|
+
sink — replays and retries are normal.
|
|
58
|
+
tenant: The tenant that produced the event. Sinks MUST enforce
|
|
59
|
+
tenant isolation on read (cross-tenant leak = Sev-1).
|
|
60
|
+
actor: The agent identity that produced the event (e.g.
|
|
61
|
+
``"svc-claude-code"``).
|
|
62
|
+
kind: A stable event-type discriminator: ``"decision"``,
|
|
63
|
+
``"identity"``, ``"grant"``, ``"detection"``, ``"audit"``.
|
|
64
|
+
ts_iso: ISO-8601 UTC timestamp of event *arrival* at the sink.
|
|
65
|
+
Informational — enforcement never reads this back.
|
|
66
|
+
policy_version: The policy bundle version this event was produced
|
|
67
|
+
under. Required for replay (invariant #3).
|
|
68
|
+
payload: The event body. Schema depends on ``kind``; see
|
|
69
|
+
``schemas/events/v1.json`` for the discriminated union.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
event_id: str
|
|
73
|
+
tenant: str
|
|
74
|
+
actor: str
|
|
75
|
+
kind: str
|
|
76
|
+
ts_iso: str
|
|
77
|
+
policy_version: int
|
|
78
|
+
payload: dict[str, Any] = field(default_factory=dict)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class CorpusSink(ABC):
|
|
82
|
+
"""Stable interface for corpus / audit sinks.
|
|
83
|
+
|
|
84
|
+
Implementations MUST be idempotent on ``event_id``. Implementations MUST
|
|
85
|
+
be append-only from the enforcement path (retention/expiry is a control-
|
|
86
|
+
plane concern, not the sink's).
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
@abstractmethod
|
|
90
|
+
def write(self, event: CorpusEvent) -> None:
|
|
91
|
+
"""Persist a single event.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
event: The event to write. Sinks MUST accept the full payload
|
|
95
|
+
without truncation. If the backend has a size limit, the
|
|
96
|
+
sink MUST reject (raise :class:`CorpusSinkError`) rather
|
|
97
|
+
than silently truncate — silent truncation makes decisions
|
|
98
|
+
un-replayable.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
CorpusSinkError: Only on unrecoverable failure. Duplicate
|
|
102
|
+
``event_id`` is NOT a failure — it's a no-op.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
@abstractmethod
|
|
106
|
+
def write_batch(self, events: Iterable[CorpusEvent]) -> None:
|
|
107
|
+
"""Persist a batch of events atomically-per-event.
|
|
108
|
+
|
|
109
|
+
The batch is not required to be atomic as a whole (network partition
|
|
110
|
+
during a 100-event batch may persist 60 and error the rest). But
|
|
111
|
+
every event that IS persisted MUST be fully persisted (no torn
|
|
112
|
+
payloads). Callers retry the failed subset.
|
|
113
|
+
|
|
114
|
+
Raises:
|
|
115
|
+
CorpusSinkError: On any per-event failure; the exception message
|
|
116
|
+
SHOULD identify which event ids failed so callers can retry
|
|
117
|
+
precisely.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
@abstractmethod
|
|
121
|
+
def query(
|
|
122
|
+
self,
|
|
123
|
+
tenant: str,
|
|
124
|
+
*,
|
|
125
|
+
kind: str | None = None,
|
|
126
|
+
since_ts: str | None = None,
|
|
127
|
+
until_ts: str | None = None,
|
|
128
|
+
limit: int = 100,
|
|
129
|
+
) -> Iterable[CorpusEvent]:
|
|
130
|
+
"""Read events back (for replay + audit-view + corpus training).
|
|
131
|
+
|
|
132
|
+
Tenant scoping is REQUIRED — the ``tenant`` argument is not
|
|
133
|
+
optional. A sink implementation that returns cross-tenant events is
|
|
134
|
+
a Sev-1 bug (cross-tenant isolation is one of the hardening surfaces
|
|
135
|
+
in SECURITY.md).
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
tenant: The tenant scope. Non-negotiable.
|
|
139
|
+
kind: Optional event-kind filter.
|
|
140
|
+
since_ts, until_ts: Optional ISO-8601 UTC bounds.
|
|
141
|
+
limit: Max events to return.
|
|
142
|
+
|
|
143
|
+
Yields:
|
|
144
|
+
:class:`CorpusEvent` — in stable, engine-defined order (typically
|
|
145
|
+
``event_id`` ascending). Order MUST be deterministic across
|
|
146
|
+
repeat queries for replay to work.
|
|
147
|
+
"""
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""
|
|
2
|
+
IdPBroker — the pluggable JIT (just-in-time) identity broker contract.
|
|
3
|
+
|
|
4
|
+
Every credential Xtrom hands to an agent is minted through an implementation
|
|
5
|
+
of this interface. The four first-party backends (AWS STS, GCP Workload
|
|
6
|
+
Identity, Azure Managed Identity, HashiCorp Vault) all conform. Third parties
|
|
7
|
+
may plug in their own; the control plane discovers backends via
|
|
8
|
+
``resolve_backend(kind)``.
|
|
9
|
+
|
|
10
|
+
Product invariants surfaced here:
|
|
11
|
+
|
|
12
|
+
- **Zero standing secrets.** Every issued credential MUST have a TTL. A
|
|
13
|
+
broker that returns a non-expiring credential is by definition broken.
|
|
14
|
+
- **Scoped, not universal.** ``scope`` MUST be honored — the returned
|
|
15
|
+
credential MUST NOT grant more than ``scope`` describes. A broker that
|
|
16
|
+
hands out a credential wider than requested is a Sev-1.
|
|
17
|
+
- **Revoke-or-short-lived.** Either ``revoke()`` actually revokes (Vault,
|
|
18
|
+
IAM session policy), OR the TTL is short enough that expiry is the
|
|
19
|
+
revocation (STS, GCP WI, Azure MI). No "revoked but usable" states.
|
|
20
|
+
|
|
21
|
+
The reference production implementations live in ``xtrom_jit.broker`` and
|
|
22
|
+
are re-exported via ``xtrom_jit.resolve_backend``. New backends should
|
|
23
|
+
subclass this ABC and register with ``AVAILABLE_BACKENDS`` in that module.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from abc import ABC, abstractmethod
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class IdPBrokerError(Exception):
|
|
33
|
+
"""Raised when a broker cannot honor a mint/revoke request.
|
|
34
|
+
|
|
35
|
+
Callers MUST treat this as fail-closed: if the broker fails, no credential
|
|
36
|
+
is issued and the request that needed one is denied. Silently substituting
|
|
37
|
+
a stub/mock credential would violate invariant #1 (determinism) and
|
|
38
|
+
invariant #3 (replayability).
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class IssuedCredential:
|
|
44
|
+
"""The successful result of :meth:`IdPBroker.mint`.
|
|
45
|
+
|
|
46
|
+
Attributes:
|
|
47
|
+
token: Opaque credential material. The broker MUST NOT log this in
|
|
48
|
+
plaintext; callers MUST redact it in any external log path (see
|
|
49
|
+
product invariant on PII/secret redaction in SECURITY.md).
|
|
50
|
+
expires_at: Absolute UNIX epoch seconds. Consumers MUST reject the
|
|
51
|
+
token if ``now >= expires_at`` — no grace, no skew tolerance
|
|
52
|
+
beyond the tenant-configured clock-skew allowance.
|
|
53
|
+
metadata: Backend-specific opaque bag (e.g. AWS ARN, GCP SA email,
|
|
54
|
+
Vault lease id). Used for revocation and audit correlation.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
token: str
|
|
58
|
+
expires_at: float
|
|
59
|
+
metadata: dict[str, Any]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class IdPBroker(ABC):
|
|
63
|
+
"""Stable interface for JIT credential brokers.
|
|
64
|
+
|
|
65
|
+
Implementations MUST be safe to call from multiple threads. Implementations
|
|
66
|
+
MUST NOT read wall-clock time in a way that affects the returned token —
|
|
67
|
+
the token is deterministic in ``(identity, scope, ttl, backend_state)`` up
|
|
68
|
+
to the backend's own nonce. ``expires_at`` is the only time-varying field.
|
|
69
|
+
|
|
70
|
+
Concrete implementations live in ``xtrom_jit.broker`` (production) and
|
|
71
|
+
``xtrom_jit.broker.MockBackend`` (tests). See ``resolve_backend()`` for
|
|
72
|
+
the config-driven factory.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
#: Human-readable backend name (e.g. ``"aws-sts"``, ``"vault"``). Used
|
|
76
|
+
#: by ``resolve_backend()`` and appears in decision traces / audit logs.
|
|
77
|
+
name: str
|
|
78
|
+
|
|
79
|
+
@abstractmethod
|
|
80
|
+
def mint(self, identity: str, scope: str, ttl: int) -> IssuedCredential:
|
|
81
|
+
"""Mint a short-lived, scoped credential.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
identity: The agent identity requesting the credential. This is
|
|
85
|
+
the *tenant-scoped* identity, e.g. ``"demo:svc-payments"``.
|
|
86
|
+
scope: A backend-neutral scope descriptor. For AWS this maps to
|
|
87
|
+
an IAM session policy; for Vault to a role; for GCP WI to a
|
|
88
|
+
service-account impersonation target.
|
|
89
|
+
ttl: Requested lifetime in seconds. The broker MAY reduce this
|
|
90
|
+
(e.g. AWS caps at 3600s for chained assume-role) but MUST NOT
|
|
91
|
+
extend it. A broker that returns ``expires_at > now + ttl``
|
|
92
|
+
is broken.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
:class:`IssuedCredential` — the token, its expiry, and
|
|
96
|
+
backend-specific metadata for revocation.
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
IdPBrokerError: On any failure. Callers fail-closed.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
@abstractmethod
|
|
103
|
+
def revoke(self, credential: IssuedCredential) -> None:
|
|
104
|
+
"""Revoke a previously-issued credential.
|
|
105
|
+
|
|
106
|
+
For backends that support live revocation (Vault, IAM session policy
|
|
107
|
+
with session-condition), this MUST actually invalidate the token.
|
|
108
|
+
For backends that don't (STS, GCP WI, Azure MI), this MAY be a no-op
|
|
109
|
+
as long as the TTL is short enough for expiry to serve as revocation.
|
|
110
|
+
|
|
111
|
+
Idempotent: revoking an already-revoked or already-expired credential
|
|
112
|
+
MUST NOT raise.
|
|
113
|
+
|
|
114
|
+
Raises:
|
|
115
|
+
IdPBrokerError: Only on a true failure (network error to Vault
|
|
116
|
+
revocation endpoint, etc.). Callers should retry with backoff
|
|
117
|
+
and eventually alert.
|
|
118
|
+
"""
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PolicyEngine — the deterministic enforcement contract.
|
|
3
|
+
|
|
4
|
+
This is the load-bearing invariant of the whole product: given the same
|
|
5
|
+
inputs, any conforming implementation MUST produce byte-identical outputs.
|
|
6
|
+
The Python reference implementation (``xtrom.core.Engine``) and the Rust
|
|
7
|
+
production engine (``xtrom-engine-rs``) both implement this contract and are
|
|
8
|
+
tested against each other via 10k-run differential fuzz on every PR
|
|
9
|
+
(see ``scripts/check_invariants.py``).
|
|
10
|
+
|
|
11
|
+
Product invariants surfaced here (from ``product/PRODUCT.md``):
|
|
12
|
+
|
|
13
|
+
- **Invariant #1 — Determinism.** ``evaluate()`` is a pure function of
|
|
14
|
+
``(policy_bundle, event, prior_taint_state)``. No wall-clock reads. No
|
|
15
|
+
network calls. No non-deterministic map iteration. No ML.
|
|
16
|
+
- **Invariant #3 — Replayability.** The returned decision, together with
|
|
17
|
+
the input triple and the ``policy_bundle.version``, is enough to reproduce
|
|
18
|
+
the verdict on any conforming engine at any point in the future.
|
|
19
|
+
|
|
20
|
+
Silent-allow fallbacks are forbidden. If the engine cannot decide, it MUST
|
|
21
|
+
return ``Verdict.BLOCK`` with a ``reason_code`` explaining why (fail-closed).
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from abc import ABC, abstractmethod
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from enum import Enum
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PolicyEngineError(Exception):
|
|
32
|
+
"""Raised for irrecoverable engine errors.
|
|
33
|
+
|
|
34
|
+
Note: callers MUST NOT catch this and substitute a default verdict. The
|
|
35
|
+
engine's own ``authorize()`` fail-closed wrapper catches unhandled
|
|
36
|
+
exceptions internally and emits a ``L0:fail-closed`` BLOCK decision.
|
|
37
|
+
Reaching this exception at the caller means the engine itself
|
|
38
|
+
(initialization, bundle-verification) failed — the safe response is to
|
|
39
|
+
refuse traffic entirely, not to fall back to a permissive default.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Verdict(str, Enum):
|
|
44
|
+
"""The three possible outcomes of enforcement.
|
|
45
|
+
|
|
46
|
+
``ALLOW`` and ``BLOCK`` are terminal. ``STEP_UP`` hands the decision to
|
|
47
|
+
the human-approvals queue with a tenant-configured SLA; silence past the
|
|
48
|
+
SLA is a ``BLOCK``, never an ``ALLOW`` (fail-closed).
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
ALLOW = "ALLOW"
|
|
52
|
+
STEP_UP = "STEP_UP"
|
|
53
|
+
BLOCK = "BLOCK"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class EnforcementDecision:
|
|
58
|
+
"""The output of :meth:`PolicyEngine.evaluate`.
|
|
59
|
+
|
|
60
|
+
All fields are populated; there are no "optional / may be None" fields
|
|
61
|
+
in the successful path. This is what gets written to the WORM audit
|
|
62
|
+
(invariant #3: replayability).
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
verdict: Verdict
|
|
66
|
+
#: A stable, engine-versioned code like ``"L4:scope"`` or ``"L3:taint"``.
|
|
67
|
+
#: Consumers (console, SIEM, alerting) MUST treat this as the canonical
|
|
68
|
+
#: machine-readable reason. Human-readable ``reason_text`` is for UI only.
|
|
69
|
+
reason_code: str
|
|
70
|
+
reason_text: str
|
|
71
|
+
#: Structured trace of which rules fired, which taint labels contributed,
|
|
72
|
+
#: which capabilities were checked. Populates the console decision-detail
|
|
73
|
+
#: view and is the replay input for the ITDR corpus (invariant #3).
|
|
74
|
+
trace: dict[str, Any] = field(default_factory=dict)
|
|
75
|
+
#: The policy bundle version that produced this decision. A future replay
|
|
76
|
+
#: against the same bundle version MUST reproduce the same verdict.
|
|
77
|
+
policy_version: int = 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class PolicyEngine(ABC):
|
|
81
|
+
"""Stable interface for enforcement engines.
|
|
82
|
+
|
|
83
|
+
Implementations MUST honor the three invariants above. Implementations
|
|
84
|
+
MAY cache signed policy bundles internally; the cache MUST fail-closed
|
|
85
|
+
past a configured max-staleness (see ``XTROM_POLICY_MAX_STALE_SECONDS``).
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
@abstractmethod
|
|
89
|
+
def evaluate(
|
|
90
|
+
self,
|
|
91
|
+
policy_bundle: dict[str, Any],
|
|
92
|
+
event: dict[str, Any],
|
|
93
|
+
prior_taint_state: dict[str, Any] | None = None,
|
|
94
|
+
) -> EnforcementDecision:
|
|
95
|
+
"""Adjudicate a single tool-call event.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
policy_bundle: A validated, signed bundle conforming to
|
|
99
|
+
:file:`schemas/policy/bundle.json`. Callers are responsible for
|
|
100
|
+
verifying the signature envelope before passing in;
|
|
101
|
+
``evaluate()`` MAY re-verify defensively but MUST NOT accept
|
|
102
|
+
an unsigned bundle.
|
|
103
|
+
event: A tool-call event: action name, argument values (with
|
|
104
|
+
their taint labels), agent identity, tenant, arriving-clock
|
|
105
|
+
(informational; NEVER used in the decision).
|
|
106
|
+
prior_taint_state: The engine's view of prior taint propagation
|
|
107
|
+
for the calling agent's session. ``None`` on first call.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
:class:`EnforcementDecision`.
|
|
111
|
+
|
|
112
|
+
Contract:
|
|
113
|
+
- Pure function of arguments. No I/O, no clocks, no randomness.
|
|
114
|
+
- On any internal error, returns ``Verdict.BLOCK`` with
|
|
115
|
+
``reason_code == "L0:fail-closed"``. NEVER raises for
|
|
116
|
+
enforcement-path errors — raises only for setup/configuration
|
|
117
|
+
errors (invalid bundle schema, missing signature, etc.).
|
|
118
|
+
- Output is byte-identical across conforming implementations for
|
|
119
|
+
identical inputs (differential-fuzz guarantee).
|
|
120
|
+
"""
|
xtrom/memory.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Memory provenance (docs/design/MEMORY-PROVENANCE.md, OWASP ASI06).
|
|
2
|
+
|
|
3
|
+
Taint tracking lives inside one session; agent memory outlives it. So memory keeps the provenance of what
|
|
4
|
+
was written, and recall restores it: what an agent stores is fingerprinted with whether it was clean or
|
|
5
|
+
tainted, and what it later recalls is labelled by those fingerprints. Pure and deterministic; every runtime
|
|
6
|
+
reproduces xtrom-engine/memory_golden.json. No I/O: callers decide where a MemoryProvenance lives.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import re
|
|
12
|
+
from collections import OrderedDict
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .core import DEFAULT_MEMORY_READ_ACTIONS, DEFAULT_MEMORY_WRITE_ACTIONS, Trust, Value # noqa: F401 (re-exported)
|
|
16
|
+
|
|
17
|
+
MIN_CHUNK = 16 # a piece shorter than this joins its neighbours
|
|
18
|
+
MAX_STRINGS = 512 # string leaves read from one value
|
|
19
|
+
_SPLIT_RX = re.compile(r"[\r\n]+|(?<=[.!?])\s+")
|
|
20
|
+
_WS_RX = re.compile(r"\s+")
|
|
21
|
+
_DEST_MARKS = ("://", "@", "/", "\\")
|
|
22
|
+
LONG_TOKEN = 64 # a no-space string this long is attributed (encoded payloads)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
MAX_DEPTH = 16
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _Reader:
|
|
29
|
+
"""String leaves of a value (dict keys included, in sorted order), and whether all of it was read. Numbers,
|
|
30
|
+
booleans and None carry no words. Objects are read by their fields (a LangChain Document, a dataclass, a
|
|
31
|
+
pydantic model), bytes as UTF-8. Anything else, or anything past the bounds, leaves `complete` False:
|
|
32
|
+
content Xtrom could not read is never vouched for."""
|
|
33
|
+
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
self.out: list[str] = []
|
|
36
|
+
self.complete = True
|
|
37
|
+
|
|
38
|
+
def leaf(self, s: str) -> None:
|
|
39
|
+
if len(self.out) >= MAX_STRINGS:
|
|
40
|
+
self.complete = False
|
|
41
|
+
else:
|
|
42
|
+
self.out.append(s)
|
|
43
|
+
|
|
44
|
+
def walk(self, value: Any, depth: int = 0) -> None:
|
|
45
|
+
if value is None or isinstance(value, (bool, int, float)):
|
|
46
|
+
return
|
|
47
|
+
if depth > MAX_DEPTH or len(self.out) >= MAX_STRINGS:
|
|
48
|
+
self.complete = False
|
|
49
|
+
return
|
|
50
|
+
if isinstance(value, str):
|
|
51
|
+
self.leaf(value)
|
|
52
|
+
elif isinstance(value, (bytes, bytearray)):
|
|
53
|
+
self.leaf(bytes(value).decode("utf-8", "replace"))
|
|
54
|
+
elif isinstance(value, Value):
|
|
55
|
+
self.walk(value.data, depth)
|
|
56
|
+
elif isinstance(value, dict):
|
|
57
|
+
for k in sorted(value, key=str):
|
|
58
|
+
if isinstance(k, str):
|
|
59
|
+
self.leaf(k)
|
|
60
|
+
self.walk(value[k], depth + 1)
|
|
61
|
+
elif isinstance(value, (list, tuple)):
|
|
62
|
+
for v in value:
|
|
63
|
+
self.walk(v, depth + 1)
|
|
64
|
+
elif isinstance(value, (set, frozenset)):
|
|
65
|
+
for v in sorted(value, key=str):
|
|
66
|
+
self.walk(v, depth + 1)
|
|
67
|
+
else:
|
|
68
|
+
try:
|
|
69
|
+
fields = vars(value)
|
|
70
|
+
except TypeError:
|
|
71
|
+
self.complete = False # no readable fields (a C object, __slots__ only)
|
|
72
|
+
return
|
|
73
|
+
self.walk(dict(fields), depth)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _read(value: Any) -> _Reader:
|
|
77
|
+
r = _Reader()
|
|
78
|
+
r.walk(value)
|
|
79
|
+
return r
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_text(leaf: str) -> bool:
|
|
83
|
+
"""Could carry an instruction or steer an action: has words, names a destination (URL, address, path),
|
|
84
|
+
or is very long. The ids, scores and timestamps a memory backend adds to its results are not attributed,
|
|
85
|
+
or every recall would read as unknown."""
|
|
86
|
+
t = leaf.strip()
|
|
87
|
+
if not t:
|
|
88
|
+
return False
|
|
89
|
+
return bool(_WS_RX.search(t)) or any(m in t for m in _DEST_MARKS) or len(t) >= LONG_TOKEN
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def memory_chunks(value: Any) -> list[str]:
|
|
93
|
+
"""Normalised pieces of what was stored or recalled: every text leaf, split on lines and sentence ends,
|
|
94
|
+
lowercased, whitespace collapsed. A piece shorter than MIN_CHUNK joins its neighbours instead of being
|
|
95
|
+
dropped, so every word belongs to some chunk (an instruction split into short lines is still seen)."""
|
|
96
|
+
return _chunks(_read(value).out)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _chunks(leaves: list[str]) -> list[str]:
|
|
100
|
+
out: list[str] = []
|
|
101
|
+
for leaf in leaves:
|
|
102
|
+
if not _is_text(leaf):
|
|
103
|
+
continue
|
|
104
|
+
pieces = [p for p in (_WS_RX.sub(" ", s).strip().lower() for s in _SPLIT_RX.split(leaf)) if p]
|
|
105
|
+
mine: list[str] = []
|
|
106
|
+
buf = ""
|
|
107
|
+
for p in pieces:
|
|
108
|
+
buf = p if not buf else buf + " " + p
|
|
109
|
+
if len(buf) >= MIN_CHUNK:
|
|
110
|
+
mine.append(buf)
|
|
111
|
+
buf = ""
|
|
112
|
+
if buf:
|
|
113
|
+
if mine:
|
|
114
|
+
mine[-1] = mine[-1] + " " + buf
|
|
115
|
+
else:
|
|
116
|
+
mine.append(buf)
|
|
117
|
+
out.extend(mine)
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def memory_fingerprints(value: Any) -> list[str]:
|
|
122
|
+
"""sha256 of each chunk, de-duplicated, in first-seen order."""
|
|
123
|
+
return _fingerprints(memory_chunks(value))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _fingerprints(chunks: list[str]) -> list[str]:
|
|
127
|
+
seen: dict[str, None] = {}
|
|
128
|
+
for c in chunks:
|
|
129
|
+
seen.setdefault(hashlib.sha256(c.encode("utf-8", "surrogatepass")).hexdigest(), None)
|
|
130
|
+
return list(seen)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def memory_read_trust(value: Any, clean: set[str], tainted: set[str], unknown: Trust = Trust.UNTRUSTED) -> Trust:
|
|
134
|
+
"""Trust of recalled content: untrusted if any part was written tainted; trusted if every part was
|
|
135
|
+
written clean and all of it could be read; otherwise (never seen written through Xtrom, or not readable
|
|
136
|
+
in full) the policy's `unknown`. Nothing to read at all → trusted."""
|
|
137
|
+
r = _read(value)
|
|
138
|
+
fps = _fingerprints(_chunks(r.out))
|
|
139
|
+
if any(f in tainted for f in fps):
|
|
140
|
+
return Trust.UNTRUSTED
|
|
141
|
+
if not r.complete:
|
|
142
|
+
return unknown
|
|
143
|
+
if all(f in clean for f in fps):
|
|
144
|
+
return Trust.TRUSTED
|
|
145
|
+
return unknown
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class MemoryProvenance:
|
|
149
|
+
"""Fingerprints of what an agent wrote to memory, clean or tainted. Bounded, oldest evicted first: an
|
|
150
|
+
evicted fingerprint is unknown, which falls back to the policy default (untrusted unless set otherwise).
|
|
151
|
+
Tainted wins: a chunk once written from a tainted session stays tainted even if later written clean."""
|
|
152
|
+
|
|
153
|
+
MAX_FINGERPRINTS = 50_000
|
|
154
|
+
|
|
155
|
+
def __init__(self, entries: dict[str, str] | None = None) -> None:
|
|
156
|
+
self._fp: OrderedDict[str, str] = OrderedDict()
|
|
157
|
+
for k, v in (entries or {}).items():
|
|
158
|
+
if v in ("clean", "tainted") and isinstance(k, str) and len(k) == 64:
|
|
159
|
+
self._fp[k] = v
|
|
160
|
+
self._evict()
|
|
161
|
+
|
|
162
|
+
def record_write(self, value: Any, tainted: bool) -> None:
|
|
163
|
+
for f in memory_fingerprints(value):
|
|
164
|
+
prev = self._fp.pop(f, None)
|
|
165
|
+
self._fp[f] = "tainted" if tainted or prev == "tainted" else "clean"
|
|
166
|
+
self._evict()
|
|
167
|
+
|
|
168
|
+
def trust_of(self, value: Any, unknown: Trust = Trust.UNTRUSTED) -> Trust:
|
|
169
|
+
clean = {f for f, s in self._fp.items() if s == "clean"}
|
|
170
|
+
tainted = {f for f, s in self._fp.items() if s == "tainted"}
|
|
171
|
+
return memory_read_trust(value, clean, tainted, unknown)
|
|
172
|
+
|
|
173
|
+
def entries(self) -> dict[str, str]:
|
|
174
|
+
return dict(self._fp)
|
|
175
|
+
|
|
176
|
+
def _evict(self) -> None:
|
|
177
|
+
while len(self._fp) > self.MAX_FINGERPRINTS:
|
|
178
|
+
self._fp.popitem(last=False)
|
xtrom/reason_text.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_comment": "Plain-English sentence for each decision reason code. The one source: the Python CLI reads it, the TypeScript SDK and the console carry copies that tests keep equal to it.",
|
|
3
|
+
"reasons": {
|
|
4
|
+
"policy.allow": "Within policy",
|
|
5
|
+
"scope.deny": "Action is outside the agent's policy scope",
|
|
6
|
+
"ifc.untrusted_to_sink": "Untrusted data reached a sensitive argument",
|
|
7
|
+
"ifc.untrusted_content_stepup": "Untrusted content reached this action — needs approval",
|
|
8
|
+
"ifc.context_tainted_stepup": "Sensitive action after untrusted input in this session",
|
|
9
|
+
"egress.secret_non_allowlisted": "A secret was headed to a host not on the allowlist",
|
|
10
|
+
"egress.secret_to_durable_sink": "A secret was headed into durable storage — needs approval",
|
|
11
|
+
"policy.destructive_prod_stepup": "Destructive action in production — needs approval",
|
|
12
|
+
"policy.transfer_threshold_stepup": "Transfer above the approval threshold",
|
|
13
|
+
"risk.high_block": "Behavioural risk score over the block threshold",
|
|
14
|
+
"risk.elevated_stepup": "Elevated behavioural risk — needs approval",
|
|
15
|
+
"fail_closed": "Enforcement error — failed closed",
|
|
16
|
+
"plan.planned_call": "Planned from the user's request; untrusted data only filled planned fields",
|
|
17
|
+
"ifc.allowlisted_read": "Read of an allowlisted site; untrusted content only chose which page",
|
|
18
|
+
"approval.allowance": "Covered by an earlier approval",
|
|
19
|
+
"local.tamper_protected": "Tried to change Xtrom's own files or settings",
|
|
20
|
+
"local.env_override": "Tried to set an Xtrom environment override",
|
|
21
|
+
"local.shell_startup": "Tried to edit a shell startup file",
|
|
22
|
+
"local.self_manage": "Tried to reinstall, remove or reconnect Xtrom",
|
|
23
|
+
"local.settings_change": "Tried to change the coding agent's hook settings",
|
|
24
|
+
"local.fail_safe_state": "Session state unreadable — asked to be safe",
|
|
25
|
+
"local.browser_credentials": "Touched a site's cookies or storage",
|
|
26
|
+
"local.browser_secret_entry": "Typed a secret into a web page",
|
|
27
|
+
"local.browser_secret_upload": "Uploaded a credential file to a web page",
|
|
28
|
+
"context.tainted": "Sensitive action after untrusted input in this session"
|
|
29
|
+
}
|
|
30
|
+
}
|