agentlighthouse-core 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentlighthouse_core-0.4.0.dist-info/METADATA +358 -0
- agentlighthouse_core-0.4.0.dist-info/RECORD +78 -0
- agentlighthouse_core-0.4.0.dist-info/WHEEL +4 -0
- agentlighthouse_core-0.4.0.dist-info/entry_points.txt +2 -0
- agentlighthouse_core-0.4.0.dist-info/licenses/LICENSE +21 -0
- al_core/__init__.py +12 -0
- al_core/_bundled/configs/audit.yaml +12 -0
- al_core/_bundled/configs/balanced.yaml +36 -0
- al_core/_bundled/configs/strict.yaml +32 -0
- al_core/_bundled/dashboard/assets/index-CN2LU6nV.css +1 -0
- al_core/_bundled/dashboard/assets/index-DX6cZzRi.js +40 -0
- al_core/_bundled/dashboard/index.html +15 -0
- al_core/_bundled/policies/default-deny.yaml +37 -0
- al_core/a2a/__init__.py +25 -0
- al_core/a2a/envelope.py +60 -0
- al_core/a2a/mediator.py +221 -0
- al_core/app.py +427 -0
- al_core/audit/__init__.py +149 -0
- al_core/audit/db.py +481 -0
- al_core/audit/pg.py +350 -0
- al_core/audit/pool.py +260 -0
- al_core/audit/siem.py +97 -0
- al_core/capability/__init__.py +28 -0
- al_core/capability/budget.py +56 -0
- al_core/capability/gate.py +334 -0
- al_core/capability/hitl.py +331 -0
- al_core/capability/policy.py +270 -0
- al_core/capability/store.py +209 -0
- al_core/capability/taint.py +79 -0
- al_core/cli/__init__.py +1 -0
- al_core/cli/main.py +1275 -0
- al_core/config/__init__.py +436 -0
- al_core/config/watch.py +51 -0
- al_core/detect/__init__.py +23 -0
- al_core/detect/base.py +131 -0
- al_core/detect/bip39_words.py +267 -0
- al_core/detect/budget.py +92 -0
- al_core/detect/detect_secrets_adapter.py +110 -0
- al_core/detect/engine.py +270 -0
- al_core/detect/scanners.py +454 -0
- al_core/egress/__init__.py +27 -0
- al_core/egress/nftables.py +59 -0
- al_core/egress/selftest.py +94 -0
- al_core/embed.py +51 -0
- al_core/gateway/__init__.py +29 -0
- al_core/gateway/content.py +154 -0
- al_core/gateway/decision.py +124 -0
- al_core/gateway/dnspin.py +131 -0
- al_core/gateway/forward.py +261 -0
- al_core/gateway/policy.py +66 -0
- al_core/gateway/ssrf.py +178 -0
- al_core/gateway/vkeys.py +205 -0
- al_core/gateway/web.py +801 -0
- al_core/identity/__init__.py +209 -0
- al_core/jsonstore.py +73 -0
- al_core/keys/__init__.py +141 -0
- al_core/killswitch.py +130 -0
- al_core/learn/__init__.py +17 -0
- al_core/learn/bundle.py +76 -0
- al_core/learn/miner.py +156 -0
- al_core/learn/scanner.py +77 -0
- al_core/learn/testgen.py +107 -0
- al_core/mcp/__init__.py +25 -0
- al_core/mcp/chain.py +147 -0
- al_core/mcp/descriptors.py +111 -0
- al_core/mcp/mediator.py +150 -0
- al_core/mcp/proxy.py +161 -0
- al_core/mcp/session.py +537 -0
- al_core/memory/__init__.py +15 -0
- al_core/memory/guard.py +330 -0
- al_core/memory/store.py +80 -0
- al_core/normalize/__init__.py +254 -0
- al_core/principal.py +59 -0
- al_core/receipt/__init__.py +192 -0
- al_core/resources.py +33 -0
- al_core/runtime.py +471 -0
- al_core/skills/__init__.py +30 -0
- al_core/skills/guard.py +218 -0
al_core/audit/siem.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""SIEM export — receipts as flat, MITRE-tagged events (L6).
|
|
2
|
+
|
|
3
|
+
A receipt is evidence: canonical, signed, chained. A SIEM event is a *query
|
|
4
|
+
surface*: flat, denormalized, tagged with the ATT&CK techniques and OWASP ASI
|
|
5
|
+
risks the findings cite, so a SOC can pivot on `threat.technique.id` without
|
|
6
|
+
knowing anything about AgentLighthouse.
|
|
7
|
+
|
|
8
|
+
The mapping is lossless in the direction that matters — every exported event
|
|
9
|
+
carries `record_hash`, `prev_hash`, and `sig`, so an analyst who sees an alert
|
|
10
|
+
can pull the original receipt and verify it with `al-verify`. Fields follow
|
|
11
|
+
Elastic Common Schema names where an obvious one exists (`@timestamp`,
|
|
12
|
+
`event.*`, `user.*`, `threat.*`); the rest live under `al.*`. Nothing is
|
|
13
|
+
invented: the event says only what the receipt said, never plaintext.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
from typing import Any, Iterable, TextIO
|
|
20
|
+
|
|
21
|
+
#: Verdict -> ECS event.outcome + a severity floor a SIEM can alert on.
|
|
22
|
+
_OUTCOME = {
|
|
23
|
+
"block": ("failure", "high"),
|
|
24
|
+
"strip": ("success", "medium"),
|
|
25
|
+
"warn": ("success", "low"),
|
|
26
|
+
"ask": ("unknown", "medium"),
|
|
27
|
+
"allow": ("success", "low"),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
_SEVERITY_RANK = {"low": 0, "medium": 1, "high": 2, "critical": 3}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def to_event(receipt: dict[str, Any]) -> dict[str, Any]:
|
|
34
|
+
"""One receipt -> one flat SIEM event (ECS-shaped, MITRE-tagged)."""
|
|
35
|
+
findings = receipt.get("findings") or []
|
|
36
|
+
verdict = receipt.get("verdict", "allow")
|
|
37
|
+
outcome, floor = _OUTCOME.get(verdict, ("unknown", "medium"))
|
|
38
|
+
|
|
39
|
+
# Severity = the strongest finding, floored by the verdict's own weight.
|
|
40
|
+
severity = max(
|
|
41
|
+
(f.get("severity", "low") for f in findings),
|
|
42
|
+
key=lambda s: _SEVERITY_RANK.get(s, 0),
|
|
43
|
+
default=floor,
|
|
44
|
+
)
|
|
45
|
+
if _SEVERITY_RANK.get(severity, 0) < _SEVERITY_RANK[floor]:
|
|
46
|
+
severity = floor
|
|
47
|
+
|
|
48
|
+
techniques = sorted({f["mitre"] for f in findings if f.get("mitre")})
|
|
49
|
+
owasp = sorted({f["owasp"] for f in findings if f.get("owasp")})
|
|
50
|
+
|
|
51
|
+
event: dict[str, Any] = {
|
|
52
|
+
"@timestamp": receipt.get("ts"),
|
|
53
|
+
"event": {
|
|
54
|
+
"kind": "alert" if verdict == "block" else "event",
|
|
55
|
+
"category": ["intrusion_detection"],
|
|
56
|
+
"action": receipt.get("action"),
|
|
57
|
+
"outcome": outcome,
|
|
58
|
+
"severity": severity,
|
|
59
|
+
"provider": "agentlighthouse",
|
|
60
|
+
"sequence": receipt.get("seq"),
|
|
61
|
+
},
|
|
62
|
+
"user": {"id": receipt.get("actor")},
|
|
63
|
+
"al": {
|
|
64
|
+
"verdict": verdict,
|
|
65
|
+
"target": receipt.get("target"),
|
|
66
|
+
"block_reason": receipt.get("block_reason"),
|
|
67
|
+
"policy_hash": receipt.get("policy_hash"),
|
|
68
|
+
"redaction": receipt.get("redaction"),
|
|
69
|
+
"session": receipt.get("session"),
|
|
70
|
+
"latency_ms": receipt.get("latency_ms"),
|
|
71
|
+
"rules": [f"{f.get('scanner')}/{f.get('rule_id')}" for f in findings],
|
|
72
|
+
"owasp": owasp,
|
|
73
|
+
# The pointers that make the alert verifiable, not just readable.
|
|
74
|
+
"record_hash": receipt.get("record_hash"),
|
|
75
|
+
"prev_hash": receipt.get("prev_hash"),
|
|
76
|
+
"sig": receipt.get("sig"),
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
if techniques:
|
|
80
|
+
event["threat"] = {
|
|
81
|
+
"framework": "MITRE ATT&CK",
|
|
82
|
+
"technique": {"id": techniques},
|
|
83
|
+
}
|
|
84
|
+
return {k: v for k, v in event.items() if v is not None}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def export(receipts: Iterable[dict[str, Any]], out: TextIO) -> int:
|
|
88
|
+
"""Write receipts as newline-delimited SIEM events. Returns the count."""
|
|
89
|
+
n = 0
|
|
90
|
+
for receipt in receipts:
|
|
91
|
+
out.write(json.dumps(to_event(receipt), ensure_ascii=False,
|
|
92
|
+
separators=(",", ":")) + "\n")
|
|
93
|
+
n += 1
|
|
94
|
+
return n
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
__all__ = ["export", "to_event"]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""L4 capability & taint gate — identity-bound tool policy, HITL, taint."""
|
|
2
|
+
|
|
3
|
+
from .hitl import ApprovalRequest, HitlGate
|
|
4
|
+
from .policy import (
|
|
5
|
+
AgentPolicy,
|
|
6
|
+
ArgConstraint,
|
|
7
|
+
BudgetRule,
|
|
8
|
+
ToolCall,
|
|
9
|
+
ToolPolicy,
|
|
10
|
+
ToolPolicyConfig,
|
|
11
|
+
ToolRule,
|
|
12
|
+
)
|
|
13
|
+
from .taint import TaintSource, TaintState, TaintTracker
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"AgentPolicy",
|
|
17
|
+
"ApprovalRequest",
|
|
18
|
+
"ArgConstraint",
|
|
19
|
+
"BudgetRule",
|
|
20
|
+
"HitlGate",
|
|
21
|
+
"TaintSource",
|
|
22
|
+
"TaintState",
|
|
23
|
+
"TaintTracker",
|
|
24
|
+
"ToolCall",
|
|
25
|
+
"ToolPolicy",
|
|
26
|
+
"ToolPolicyConfig",
|
|
27
|
+
"ToolRule",
|
|
28
|
+
]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Per-actor tool-call rate budgets — a sliding 60-second window.
|
|
2
|
+
|
|
3
|
+
The tripwire behind ``AgentPolicy.budgets.max_tool_calls_per_min``. Enforced at
|
|
4
|
+
the ActionGate: an actor may make at most N authorized calls in any rolling
|
|
5
|
+
minute; the N+1th within the window is denied (``BUDGET_EXCEEDED``) and
|
|
6
|
+
receipted like any other decision. The window truly slides — the earliest call
|
|
7
|
+
ages out exactly 60s after it happened, not on a fixed bucket boundary — so a
|
|
8
|
+
burst cannot ride a bucket reset.
|
|
9
|
+
|
|
10
|
+
State is per-actor and in-memory: a rate window is soft, self-healing state,
|
|
11
|
+
not evidence (the receipts are the record), so it does not need the persistence
|
|
12
|
+
the HITL/taint store carries.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import threading
|
|
18
|
+
from collections import defaultdict, deque
|
|
19
|
+
from typing import Callable
|
|
20
|
+
|
|
21
|
+
WINDOW_S = 60.0
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class BudgetTracker:
|
|
25
|
+
"""Counts authorized calls per actor over a sliding window."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, clock: Callable[[], float] | None = None) -> None:
|
|
28
|
+
import time
|
|
29
|
+
|
|
30
|
+
self._clock = clock or time.monotonic
|
|
31
|
+
self._calls: dict[str, deque[float]] = defaultdict(deque)
|
|
32
|
+
# The gate serves requests from a thread pool; the check-and-append is
|
|
33
|
+
# a read-modify-write, so without a lock two racing calls could both
|
|
34
|
+
# pass the limit check and both append — the exact overrun a rate cap
|
|
35
|
+
# exists to prevent.
|
|
36
|
+
self._lock = threading.Lock()
|
|
37
|
+
|
|
38
|
+
def check_and_consume(self, actor: str, limit: int) -> bool:
|
|
39
|
+
"""Record a call for ``actor`` if it fits within ``limit`` per minute.
|
|
40
|
+
|
|
41
|
+
Returns True and consumes a slot when there is room; returns False and
|
|
42
|
+
consumes nothing when the actor is already at the limit.
|
|
43
|
+
"""
|
|
44
|
+
with self._lock:
|
|
45
|
+
now = self._clock()
|
|
46
|
+
window = self._calls[actor]
|
|
47
|
+
cutoff = now - WINDOW_S
|
|
48
|
+
while window and window[0] <= cutoff:
|
|
49
|
+
window.popleft()
|
|
50
|
+
if len(window) >= limit:
|
|
51
|
+
return False
|
|
52
|
+
window.append(now)
|
|
53
|
+
return True
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
__all__ = ["BudgetTracker", "WINDOW_S"]
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""ActionGate (L4) — one decision point for every tool call.
|
|
2
|
+
|
|
3
|
+
Ties the Phase-3 pieces into a single ``authorize`` call, applied in
|
|
4
|
+
fail-closed order:
|
|
5
|
+
|
|
6
|
+
1. **Identity** — no actor / unregistered actor -> deny (``NO_IDENTITY_TOOL``).
|
|
7
|
+
2. **Tool policy** — identity-bound default-deny + argument constraints.
|
|
8
|
+
3. **Chain detection** — record the call; a completed recon->exfil chain denies
|
|
9
|
+
and taints the session.
|
|
10
|
+
4. **HITL** — irreversible verbs (and, in a tainted session, protected verbs)
|
|
11
|
+
pause for human approval; the outcome carries the request id.
|
|
12
|
+
|
|
13
|
+
A separate ``scan_result`` runs tool *output* back through the content gate
|
|
14
|
+
(bidirectional scanning) and taints the session on untrusted/injection-bearing
|
|
15
|
+
results, so a later protected call in the same session is escalated.
|
|
16
|
+
|
|
17
|
+
Every decision is receipted (``mcp_tool_call`` / ``mcp_tool_result``) through
|
|
18
|
+
an injected recorder, so the whole flow is evidence-backed.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from typing import Any, Callable
|
|
26
|
+
|
|
27
|
+
from ..detect import ContentGate, GateResult, ScanContext
|
|
28
|
+
from ..gateway.decision import BlockReason, Decision, finding
|
|
29
|
+
from .budget import BudgetTracker
|
|
30
|
+
from .hitl import HitlGate, args_digest
|
|
31
|
+
from .policy import ToolCall, ToolPolicy
|
|
32
|
+
from .taint import TaintSource, TaintTracker
|
|
33
|
+
from ..mcp.chain import ChainDetector
|
|
34
|
+
|
|
35
|
+
Recorder = Callable[..., Any]
|
|
36
|
+
|
|
37
|
+
# Cap on the call rendering shown to an approver; the digest still binds the
|
|
38
|
+
# approval to the full arguments.
|
|
39
|
+
_DETAIL_MAX = 2000
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _render_call(tool: str, args: dict[str, Any]) -> str:
|
|
43
|
+
"""What the human is approving: the tool and its (DLP-redacted) arguments.
|
|
44
|
+
Approving a bare tool name is not informed consent."""
|
|
45
|
+
rendered = json.dumps(args, sort_keys=True, ensure_ascii=False, default=str)
|
|
46
|
+
if len(rendered) > _DETAIL_MAX:
|
|
47
|
+
rendered = rendered[:_DETAIL_MAX] + "…(truncated)"
|
|
48
|
+
return f"{tool} {rendered}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _ArgBlocked(Exception):
|
|
52
|
+
"""Internal: a tool argument tripped a blocking scanner (unwinds the walk)."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, result: GateResult) -> None:
|
|
55
|
+
self.result = result
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class ActionOutcome:
|
|
60
|
+
"""Result of authorizing a tool call. ``hitl_request_id`` is set when the
|
|
61
|
+
call is held for approval (verdict block, reason ``HITL_REQUIRED``).
|
|
62
|
+
|
|
63
|
+
``args`` is what the tool may actually be called with: the original
|
|
64
|
+
arguments, or a **redacted** copy when outbound DLP stripped something from
|
|
65
|
+
them. Callers must forward ``outcome.args``, not the arguments they passed
|
|
66
|
+
in — that is how a redaction actually takes effect on the wire.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
decision: Decision
|
|
70
|
+
hitl_request_id: str | None = None
|
|
71
|
+
args: dict[str, Any] = field(default_factory=dict)
|
|
72
|
+
redaction: dict[str, int] = field(default_factory=dict)
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def allowed(self) -> bool:
|
|
76
|
+
return self.decision.allowed
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class ActionGate:
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
policy: ToolPolicy,
|
|
83
|
+
*,
|
|
84
|
+
chain: ChainDetector | None = None,
|
|
85
|
+
hitl: HitlGate | None = None,
|
|
86
|
+
taint: TaintTracker | None = None,
|
|
87
|
+
content_gate: ContentGate | None = None,
|
|
88
|
+
recorder: Recorder | None = None,
|
|
89
|
+
known_actor: Callable[[str], bool] | None = None,
|
|
90
|
+
killswitch: Callable[[], bool] | None = None,
|
|
91
|
+
clock: Callable[[], float] | None = None,
|
|
92
|
+
) -> None:
|
|
93
|
+
self._policy = policy
|
|
94
|
+
self._chain = chain or ChainDetector()
|
|
95
|
+
self._hitl = hitl or HitlGate()
|
|
96
|
+
self._taint = taint or TaintTracker()
|
|
97
|
+
self._gate = content_gate
|
|
98
|
+
self._record = recorder or (lambda **_: None)
|
|
99
|
+
self._budget = BudgetTracker(clock=clock)
|
|
100
|
+
# By default any non-empty actor is accepted (transport already
|
|
101
|
+
# authenticated it); pass a registry membership check to tighten.
|
|
102
|
+
self._known_actor = known_actor or (lambda a: bool(a))
|
|
103
|
+
self._killswitch = killswitch or (lambda: False)
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def hitl(self) -> HitlGate:
|
|
107
|
+
return self._hitl
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def taint(self) -> TaintTracker:
|
|
111
|
+
return self._taint
|
|
112
|
+
|
|
113
|
+
def authorize(
|
|
114
|
+
self, actor: str, tool: str, args: dict[str, Any] | None = None,
|
|
115
|
+
*, session_id: str = "default", hitl_request_id: str | None = None,
|
|
116
|
+
) -> ActionOutcome:
|
|
117
|
+
"""``hitl_request_id`` optionally names the approval the agent is
|
|
118
|
+
retrying under; without it the gate finds the approval by the call
|
|
119
|
+
itself. Either way the approval must bind to this exact call."""
|
|
120
|
+
args = args or {}
|
|
121
|
+
requested_args = args # an approval binds to what the agent asked for
|
|
122
|
+
target = f"tool:{tool}"
|
|
123
|
+
|
|
124
|
+
# 0. Kill switch: full deny-all, before anything else.
|
|
125
|
+
if self._killswitch():
|
|
126
|
+
return self._deny(actor, target, Decision.block(
|
|
127
|
+
BlockReason.KILLSWITCH_ENGAGED,
|
|
128
|
+
[finding("killswitch", "killswitch.engaged", "critical")],
|
|
129
|
+
), session=session_id)
|
|
130
|
+
|
|
131
|
+
# 1. Identity.
|
|
132
|
+
if not actor or not self._known_actor(actor):
|
|
133
|
+
return self._deny(actor, target, Decision.block(
|
|
134
|
+
BlockReason.NO_IDENTITY_TOOL,
|
|
135
|
+
[finding("tool_policy", "policy.no_identity", "high", owasp="ASI03")],
|
|
136
|
+
), session=session_id)
|
|
137
|
+
|
|
138
|
+
# 2. Tool policy (default-deny + arg constraints).
|
|
139
|
+
decision = self._policy.check(ToolCall(actor=actor, tool=tool, args=args))
|
|
140
|
+
if not decision.allowed:
|
|
141
|
+
return self._deny(actor, target, decision, session=session_id)
|
|
142
|
+
|
|
143
|
+
# 3. Outbound DLP on the ARGUMENTS themselves.
|
|
144
|
+
#
|
|
145
|
+
# Policy proves the *shape* of a call is permitted (allowed tool, allowed
|
|
146
|
+
# host, path under /workspace, value in range). It says nothing about
|
|
147
|
+
# what the agent put *inside* those arguments. An agent legitimately
|
|
148
|
+
# allowed to http_post to an allow-listed host can carry the system
|
|
149
|
+
# prompt, the conversation, or an AWS key out in the request body — a
|
|
150
|
+
# permitted call, exfiltrating context. So the arguments get the same
|
|
151
|
+
# content gate the reverse proxy already applies to outbound prompts.
|
|
152
|
+
blocked, args, redaction, findings = self._scan_args(
|
|
153
|
+
actor, tool, target, args, session=session_id)
|
|
154
|
+
if blocked is not None:
|
|
155
|
+
return blocked
|
|
156
|
+
|
|
157
|
+
# 4. Chain detection.
|
|
158
|
+
chain_block = self._chain.record(session_id, tool)
|
|
159
|
+
if chain_block is not None:
|
|
160
|
+
self._taint.mark(session_id, TaintSource.UNPINNED_TOOL_RESULT)
|
|
161
|
+
return self._deny(actor, target, chain_block, session=session_id)
|
|
162
|
+
|
|
163
|
+
# 5. HITL for irreversible / (tainted) protected verbs. An approved
|
|
164
|
+
# request for this exact call is a single-use grant: the call goes on
|
|
165
|
+
# to execute. Otherwise it is held (reusing a request already pending
|
|
166
|
+
# for the same call, so retries don't flood the approvals queue).
|
|
167
|
+
tainted = self._taint.is_tainted(session_id)
|
|
168
|
+
grant = None
|
|
169
|
+
if self._hitl.requires_approval(tool, tainted=tainted):
|
|
170
|
+
req = self._hitl.claim(actor, tool, requested_args, session=session_id,
|
|
171
|
+
request_id=hitl_request_id)
|
|
172
|
+
if req is None:
|
|
173
|
+
req = self._hitl.submit(actor, tool, args=requested_args,
|
|
174
|
+
detail=_render_call(tool, args),
|
|
175
|
+
session=session_id)
|
|
176
|
+
decision = self._hitl.decision(req.request_id)
|
|
177
|
+
if not decision.allowed:
|
|
178
|
+
if decision.block_reason == BlockReason.HITL_DENIED:
|
|
179
|
+
return self._deny(actor, target, decision, session=session_id)
|
|
180
|
+
self._record(actor=actor, action="mcp_tool_call", target=target,
|
|
181
|
+
verdict="ask", block_reason=decision.block_reason,
|
|
182
|
+
findings=decision.findings, session=session_id)
|
|
183
|
+
return ActionOutcome(decision=decision, hitl_request_id=req.request_id,
|
|
184
|
+
args=args, redaction=redaction)
|
|
185
|
+
grant = req
|
|
186
|
+
|
|
187
|
+
# Per-actor rate budget — the last gate, so a slot is consumed only by
|
|
188
|
+
# a call that will actually proceed. A call denied by policy/DLP/chain
|
|
189
|
+
# returned earlier, and one held for HITL returned above; none of them
|
|
190
|
+
# counts. The N+1th executing call in the rolling minute fails closed
|
|
191
|
+
# with a retryable BUDGET_EXCEEDED. It runs before a grant is spent, so
|
|
192
|
+
# a rate-limited retry keeps its approval.
|
|
193
|
+
limit = self._policy.budget_for(actor)
|
|
194
|
+
if limit is not None and not self._budget.check_and_consume(actor, limit):
|
|
195
|
+
return self._deny(actor, target, Decision.block(
|
|
196
|
+
BlockReason.BUDGET_EXCEEDED,
|
|
197
|
+
[finding("tool_policy", "policy.budget_exceeded", "medium",
|
|
198
|
+
owasp="ASI08")],
|
|
199
|
+
), session=session_id)
|
|
200
|
+
|
|
201
|
+
if grant is not None:
|
|
202
|
+
if not self._hitl.consume(grant.request_id, actor, tool, requested_args,
|
|
203
|
+
session=session_id):
|
|
204
|
+
# lost a race for the grant (another process spent it)
|
|
205
|
+
return self._deny(actor, target, self._hitl.decision(grant.request_id),
|
|
206
|
+
session=session_id)
|
|
207
|
+
findings = [*findings, finding("hitl", "hitl.grant_consumed", "low",
|
|
208
|
+
owasp="ASI09")]
|
|
209
|
+
|
|
210
|
+
# A redaction is an ALLOW with the payload removed — the call proceeds
|
|
211
|
+
# with the placeholder. Only a blocking verdict stops it (above).
|
|
212
|
+
self._record(actor=actor, action="mcp_tool_call", target=target,
|
|
213
|
+
verdict="strip" if redaction else "allow",
|
|
214
|
+
findings=findings or None, redaction=redaction or None,
|
|
215
|
+
session=session_id)
|
|
216
|
+
return ActionOutcome(decision=Decision.allow(), args=args, redaction=redaction,
|
|
217
|
+
hitl_request_id=grant.request_id if grant else None)
|
|
218
|
+
|
|
219
|
+
def _scan_args(
|
|
220
|
+
self, actor: str, tool: str, target: str, args: dict[str, Any],
|
|
221
|
+
*, session: str | None = None,
|
|
222
|
+
) -> tuple[ActionOutcome | None, dict[str, Any], dict[str, int], list[dict[str, Any]]]:
|
|
223
|
+
"""Run the tool's string arguments through the content gate (outbound).
|
|
224
|
+
|
|
225
|
+
Returns ``(denial | None, args, redaction, findings)``. Block -> the call
|
|
226
|
+
never happens. Strip -> the offending value is redacted **in the
|
|
227
|
+
arguments the caller must then use**, so the tool is invoked with the
|
|
228
|
+
placeholder, not the secret. Scanning is per-string-field, which keeps
|
|
229
|
+
each placeholder local to the field it came from (the same choice the
|
|
230
|
+
reverse-proxy DLP makes for prompts). Nested dicts/lists are walked;
|
|
231
|
+
non-strings carry no payload.
|
|
232
|
+
"""
|
|
233
|
+
redaction: dict[str, int] = {}
|
|
234
|
+
findings: list[dict[str, Any]] = []
|
|
235
|
+
if self._gate is None:
|
|
236
|
+
return None, args, redaction, findings
|
|
237
|
+
|
|
238
|
+
ctx = ScanContext(actor=actor, direction="outbound", target=target,
|
|
239
|
+
content_type="text/plain")
|
|
240
|
+
|
|
241
|
+
def walk(value: Any) -> Any:
|
|
242
|
+
if isinstance(value, str):
|
|
243
|
+
if not value:
|
|
244
|
+
return value
|
|
245
|
+
result = self._gate.scan_text(value, ctx)
|
|
246
|
+
if result.blocked:
|
|
247
|
+
raise _ArgBlocked(result)
|
|
248
|
+
if result.verdict == "strip":
|
|
249
|
+
for cls, n in (result.redaction or {}).items():
|
|
250
|
+
redaction[cls] = redaction.get(cls, 0) + n
|
|
251
|
+
findings.extend(result.findings)
|
|
252
|
+
return result.text
|
|
253
|
+
if result.findings:
|
|
254
|
+
findings.extend(result.findings)
|
|
255
|
+
return value
|
|
256
|
+
if isinstance(value, dict):
|
|
257
|
+
return {k: walk(v) for k, v in value.items()}
|
|
258
|
+
if isinstance(value, list):
|
|
259
|
+
return [walk(v) for v in value]
|
|
260
|
+
return value # ints/bools/None carry no payload
|
|
261
|
+
|
|
262
|
+
try:
|
|
263
|
+
redacted = walk(args)
|
|
264
|
+
except _ArgBlocked as blocked:
|
|
265
|
+
result = blocked.result
|
|
266
|
+
decision = Decision.block(
|
|
267
|
+
result.block_reason or BlockReason.CONTENT_BLOCKED,
|
|
268
|
+
[finding("tool_args", "tool.arg_exfiltration", "high",
|
|
269
|
+
owasp="ASI03", mitre="T1041")] + result.findings,
|
|
270
|
+
)
|
|
271
|
+
return (self._deny(actor, target, decision, session=session),
|
|
272
|
+
args, redaction, findings)
|
|
273
|
+
|
|
274
|
+
return None, redacted, redaction, findings
|
|
275
|
+
|
|
276
|
+
def resume(self, request_id: str, actor: str, tool: str,
|
|
277
|
+
args: dict[str, Any] | None = None,
|
|
278
|
+
*, session_id: str | None = None) -> ActionOutcome:
|
|
279
|
+
"""Re-evaluate a held call after an operator resolved its approval.
|
|
280
|
+
|
|
281
|
+
Allows only if the approval binds to this exact call (actor, tool,
|
|
282
|
+
arguments, and session when given) and spends the grant: a second
|
|
283
|
+
resume of the same request is denied."""
|
|
284
|
+
target = f"tool:{tool}"
|
|
285
|
+
req = self._hitl.request(request_id)
|
|
286
|
+
if req is not None and not req.binds(actor, tool, args_digest(args), session_id):
|
|
287
|
+
decision = Decision.block(
|
|
288
|
+
BlockReason.HITL_DENIED,
|
|
289
|
+
[finding("hitl", "hitl.grant_mismatch", "high", owasp="ASI09")],
|
|
290
|
+
)
|
|
291
|
+
elif self._hitl.consume(request_id, actor, tool, args, session=session_id):
|
|
292
|
+
decision = Decision.allow()
|
|
293
|
+
else:
|
|
294
|
+
decision = self._hitl.decision(request_id)
|
|
295
|
+
verdict = "allow" if decision.allowed else "block"
|
|
296
|
+
self._record(actor=actor, action="mcp_tool_call", target=target,
|
|
297
|
+
verdict=verdict, block_reason=decision.block_reason,
|
|
298
|
+
findings=decision.findings, session=session_id)
|
|
299
|
+
return ActionOutcome(decision=decision, hitl_request_id=request_id,
|
|
300
|
+
args=args or {})
|
|
301
|
+
|
|
302
|
+
def scan_result(
|
|
303
|
+
self, text: str, *, actor: str = "", tool: str = "", session_id: str = "default",
|
|
304
|
+
) -> GateResult:
|
|
305
|
+
"""Scan a tool result (bidirectional). Taints the session on a hostile
|
|
306
|
+
result so subsequent protected calls escalate. Returns the GateResult
|
|
307
|
+
(blocked/strip/allow); the caller withholds a blocked result."""
|
|
308
|
+
target = f"tool:{tool}:result"
|
|
309
|
+
if self._gate is None:
|
|
310
|
+
return GateResult(verdict="allow", text=text)
|
|
311
|
+
result = self._gate.scan_text(
|
|
312
|
+
text, ScanContext(actor=actor, direction="inbound", target=target,
|
|
313
|
+
content_type="text/plain"))
|
|
314
|
+
if result.blocked:
|
|
315
|
+
self._taint.mark(session_id, TaintSource.INJECTION_DETECTED)
|
|
316
|
+
self._record(actor=actor, action="mcp_tool_result", target=target,
|
|
317
|
+
verdict="block", block_reason=result.block_reason,
|
|
318
|
+
findings=result.findings, session=session_id)
|
|
319
|
+
elif result.verdict in ("strip", "warn"):
|
|
320
|
+
self._taint.mark(session_id, TaintSource.UNPINNED_TOOL_RESULT)
|
|
321
|
+
self._record(actor=actor, action="mcp_tool_result", target=target,
|
|
322
|
+
verdict=result.verdict, findings=result.findings,
|
|
323
|
+
redaction=result.redaction or None, session=session_id)
|
|
324
|
+
return result
|
|
325
|
+
|
|
326
|
+
def _deny(self, actor: str, target: str, decision: Decision,
|
|
327
|
+
*, session: str | None = None) -> ActionOutcome:
|
|
328
|
+
self._record(actor=actor or "anonymous", action="mcp_tool_call", target=target,
|
|
329
|
+
verdict="block", block_reason=decision.block_reason,
|
|
330
|
+
findings=decision.findings, session=session)
|
|
331
|
+
return ActionOutcome(decision=decision)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
__all__ = ["ActionGate", "ActionOutcome"]
|