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.
Files changed (78) hide show
  1. agentlighthouse_core-0.4.0.dist-info/METADATA +358 -0
  2. agentlighthouse_core-0.4.0.dist-info/RECORD +78 -0
  3. agentlighthouse_core-0.4.0.dist-info/WHEEL +4 -0
  4. agentlighthouse_core-0.4.0.dist-info/entry_points.txt +2 -0
  5. agentlighthouse_core-0.4.0.dist-info/licenses/LICENSE +21 -0
  6. al_core/__init__.py +12 -0
  7. al_core/_bundled/configs/audit.yaml +12 -0
  8. al_core/_bundled/configs/balanced.yaml +36 -0
  9. al_core/_bundled/configs/strict.yaml +32 -0
  10. al_core/_bundled/dashboard/assets/index-CN2LU6nV.css +1 -0
  11. al_core/_bundled/dashboard/assets/index-DX6cZzRi.js +40 -0
  12. al_core/_bundled/dashboard/index.html +15 -0
  13. al_core/_bundled/policies/default-deny.yaml +37 -0
  14. al_core/a2a/__init__.py +25 -0
  15. al_core/a2a/envelope.py +60 -0
  16. al_core/a2a/mediator.py +221 -0
  17. al_core/app.py +427 -0
  18. al_core/audit/__init__.py +149 -0
  19. al_core/audit/db.py +481 -0
  20. al_core/audit/pg.py +350 -0
  21. al_core/audit/pool.py +260 -0
  22. al_core/audit/siem.py +97 -0
  23. al_core/capability/__init__.py +28 -0
  24. al_core/capability/budget.py +56 -0
  25. al_core/capability/gate.py +334 -0
  26. al_core/capability/hitl.py +331 -0
  27. al_core/capability/policy.py +270 -0
  28. al_core/capability/store.py +209 -0
  29. al_core/capability/taint.py +79 -0
  30. al_core/cli/__init__.py +1 -0
  31. al_core/cli/main.py +1275 -0
  32. al_core/config/__init__.py +436 -0
  33. al_core/config/watch.py +51 -0
  34. al_core/detect/__init__.py +23 -0
  35. al_core/detect/base.py +131 -0
  36. al_core/detect/bip39_words.py +267 -0
  37. al_core/detect/budget.py +92 -0
  38. al_core/detect/detect_secrets_adapter.py +110 -0
  39. al_core/detect/engine.py +270 -0
  40. al_core/detect/scanners.py +454 -0
  41. al_core/egress/__init__.py +27 -0
  42. al_core/egress/nftables.py +59 -0
  43. al_core/egress/selftest.py +94 -0
  44. al_core/embed.py +51 -0
  45. al_core/gateway/__init__.py +29 -0
  46. al_core/gateway/content.py +154 -0
  47. al_core/gateway/decision.py +124 -0
  48. al_core/gateway/dnspin.py +131 -0
  49. al_core/gateway/forward.py +261 -0
  50. al_core/gateway/policy.py +66 -0
  51. al_core/gateway/ssrf.py +178 -0
  52. al_core/gateway/vkeys.py +205 -0
  53. al_core/gateway/web.py +801 -0
  54. al_core/identity/__init__.py +209 -0
  55. al_core/jsonstore.py +73 -0
  56. al_core/keys/__init__.py +141 -0
  57. al_core/killswitch.py +130 -0
  58. al_core/learn/__init__.py +17 -0
  59. al_core/learn/bundle.py +76 -0
  60. al_core/learn/miner.py +156 -0
  61. al_core/learn/scanner.py +77 -0
  62. al_core/learn/testgen.py +107 -0
  63. al_core/mcp/__init__.py +25 -0
  64. al_core/mcp/chain.py +147 -0
  65. al_core/mcp/descriptors.py +111 -0
  66. al_core/mcp/mediator.py +150 -0
  67. al_core/mcp/proxy.py +161 -0
  68. al_core/mcp/session.py +537 -0
  69. al_core/memory/__init__.py +15 -0
  70. al_core/memory/guard.py +330 -0
  71. al_core/memory/store.py +80 -0
  72. al_core/normalize/__init__.py +254 -0
  73. al_core/principal.py +59 -0
  74. al_core/receipt/__init__.py +192 -0
  75. al_core/resources.py +33 -0
  76. al_core/runtime.py +471 -0
  77. al_core/skills/__init__.py +30 -0
  78. al_core/skills/guard.py +218 -0
@@ -0,0 +1,331 @@
1
+ """Human-in-the-loop gate (L4) — irreversible verbs pause for approval (ASI09).
2
+
3
+ Irreversible actions (send, delete, transfer, publish, deploy) do not execute
4
+ on the agent's say-so: the call is held as a pending approval that a human
5
+ resolves via the control plane. **Timeout is a denial** — an unattended
6
+ request fails closed, never open.
7
+
8
+ A **tainted** session (see :mod:`.taint`) widens the gate: protected — not just
9
+ irreversible — operations then also require approval, because a session that
10
+ ingested untrusted content can no longer be trusted to drive even normally-
11
+ allowed writes unattended.
12
+
13
+ The gate holds state (pending requests) but does not block a thread waiting:
14
+ the caller submits, returns ``HITL_REQUIRED`` to the agent, and the decision
15
+ resolves out of band. ``decision`` maps a request to allow / block at any time.
16
+
17
+ An approval is a **grant** for exactly what was asked: the actor, tool,
18
+ argument digest and session that filed the request. The agent retries the same
19
+ call; :meth:`HitlGate.claim` finds the grant and :meth:`HitlGate.consume`
20
+ spends it, once. A grant is valid for ``timeout_s`` after it was given, then it
21
+ lapses like an unanswered request. With a store attached the store is the
22
+ source of truth, so a request filed by one process and resolved by another
23
+ (data plane / control plane) behaves as if both were one gate.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import secrets
31
+ from dataclasses import dataclass
32
+ from typing import Any, Callable
33
+
34
+ from typing import TYPE_CHECKING
35
+
36
+ from ..gateway.decision import BlockReason, Decision, finding
37
+
38
+ if TYPE_CHECKING:
39
+ from .store import CapabilityStore
40
+
41
+ # Verb → irreversible if the tool name starts with one of these (or is listed
42
+ # explicitly in ``extra_irreversible``). Irreversible = cannot be undone once
43
+ # it leaves the boundary.
44
+ _IRREVERSIBLE_PREFIXES = ("send", "delete", "remove", "transfer", "publish",
45
+ "deploy", "purchase", "pay", "wire", "email", "post")
46
+
47
+ # When a session is TAINTED, these broader protected operations also gate.
48
+ _PROTECTED_PREFIXES = _IRREVERSIBLE_PREFIXES + (
49
+ "write", "exec", "run", "http_post", "update", "create", "modify", "put")
50
+
51
+ _PENDING = "pending"
52
+ _APPROVED = "approved"
53
+ _DENIED = "denied"
54
+ _CONSUMED = "consumed" # grant spent: never reusable
55
+ _EXPIRED = "expired" # grant not spent within its window
56
+ _TIMED_OUT = "timed_out"
57
+
58
+
59
+ def args_digest(args: dict[str, Any] | None) -> str:
60
+ """Stable digest of a call's arguments: what an approval is bound to."""
61
+ canonical = json.dumps(args or {}, sort_keys=True, separators=(",", ":"),
62
+ ensure_ascii=False, default=str)
63
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
64
+
65
+
66
+ def _verb_matches(tool: str, prefixes: tuple[str, ...], explicit: frozenset[str]) -> bool:
67
+ # Match on a word boundary (exact verb, or verb_noun) so "post" gates
68
+ # "post_message" but not "postgres_query".
69
+ t = tool.lower()
70
+ return t in explicit or any(t == p or t.startswith(p + "_") for p in prefixes)
71
+
72
+
73
+ @dataclass
74
+ class ApprovalRequest:
75
+ request_id: str
76
+ actor: str
77
+ tool: str
78
+ created_at: float
79
+ timeout_s: float
80
+ status: str = _PENDING
81
+ resolved_at: float | None = None
82
+ resolved_by: str | None = None
83
+ #: What is actually being approved — e.g. the fully rendered commands a
84
+ #: remote-exec host will run. Approving a bare tool name is not informed
85
+ #: consent; every resolution surface shows this.
86
+ detail: str | None = None
87
+ #: The caller's session the request belongs to, so an embedder can
88
+ #: re-associate a rehydrated request with the run that filed it.
89
+ session: str | None = None
90
+ #: Digest of the call's arguments (:func:`args_digest`). An approval only
91
+ #: grants a call whose arguments hash the same.
92
+ args_digest: str | None = None
93
+
94
+ def binds(self, actor: str, tool: str, digest: str | None,
95
+ session: str | None) -> bool:
96
+ """True if the call (actor, tool, args, session) is the one requested.
97
+ The session is bound only when both sides name one."""
98
+ return (self.actor == actor and self.tool == tool
99
+ and self.args_digest == digest
100
+ and (self.session is None or session is None or self.session == session))
101
+
102
+
103
+ class HitlGate:
104
+ """Holds pending approvals; resolves them to allow/deny with timeout=deny."""
105
+
106
+ def __init__(
107
+ self,
108
+ *,
109
+ timeout_s: float = 300.0,
110
+ extra_irreversible: tuple[str, ...] = (),
111
+ clock: Callable[[], float] | None = None,
112
+ store: "CapabilityStore | None" = None,
113
+ ) -> None:
114
+ self._timeout_s = timeout_s
115
+ self._explicit = frozenset(t.lower() for t in extra_irreversible)
116
+ import time
117
+ self._clock = clock or time.monotonic
118
+ self._pending: dict[str, ApprovalRequest] = {}
119
+ self._store = store
120
+ if store is not None:
121
+ # Rehydrate every live request, so an unspent grant is still found
122
+ # by the call it was filed for. The store keeps wall-clock ages;
123
+ # re-anchor each in THIS process's clock preserving elapsed age, so
124
+ # the original deadline is enforced. The store drops lapsed and
125
+ # from-the-future rows itself (fail closed). Later resolutions are
126
+ # read through on demand (``_sync``).
127
+ for row in store.live_approvals():
128
+ self._adopt(row)
129
+
130
+ # -- classification ------------------------------------------------------
131
+
132
+ def is_irreversible(self, tool: str) -> bool:
133
+ return _verb_matches(tool, _IRREVERSIBLE_PREFIXES, self._explicit)
134
+
135
+ def requires_approval(self, tool: str, *, tainted: bool = False) -> bool:
136
+ """Irreversible always gates; a tainted session also gates protected ops."""
137
+ if self.is_irreversible(tool):
138
+ return True
139
+ if tainted and _verb_matches(tool, _PROTECTED_PREFIXES, self._explicit):
140
+ return True
141
+ return False
142
+
143
+ # -- request lifecycle ---------------------------------------------------
144
+
145
+ def submit(
146
+ self, actor: str, tool: str, *,
147
+ detail: str | None = None, session: str | None = None,
148
+ args: dict[str, Any] | None = None,
149
+ ) -> ApprovalRequest:
150
+ self._evict_final()
151
+ req = ApprovalRequest(
152
+ request_id="hitl_" + secrets.token_hex(8),
153
+ actor=actor, tool=tool,
154
+ created_at=self._clock(), timeout_s=self._timeout_s,
155
+ detail=detail, session=session, args_digest=args_digest(args),
156
+ )
157
+ self._pending[req.request_id] = req
158
+ if self._store is not None:
159
+ self._store.save_approval(req.request_id, actor, tool, req.timeout_s,
160
+ detail=detail, session=session,
161
+ args_digest=req.args_digest)
162
+ return req
163
+
164
+ def approve(self, request_id: str, *, by: str | None = None) -> bool:
165
+ return self._resolve(request_id, _APPROVED, by=by)
166
+
167
+ def deny(self, request_id: str, *, by: str | None = None) -> bool:
168
+ return self._resolve(request_id, _DENIED, by=by)
169
+
170
+ def _resolve(self, request_id: str, status: str, *, by: str | None = None) -> bool:
171
+ req = self._sync(request_id)
172
+ if req is None or req.status != _PENDING:
173
+ return False
174
+ if self._timed_out(req):
175
+ return False # already lapsed → cannot be resolved
176
+ if self._store is not None and not self._store.resolve_approval(
177
+ request_id, status, by):
178
+ self._sync(request_id) # another process resolved it first
179
+ return False
180
+ req.status = status
181
+ req.resolved_at = self._clock()
182
+ req.resolved_by = by
183
+ return True
184
+
185
+ def claim(
186
+ self, actor: str, tool: str, args: dict[str, Any] | None, *,
187
+ session: str | None, request_id: str | None = None,
188
+ ) -> ApprovalRequest | None:
189
+ """The live request covering this exact call, if any: an approved one
190
+ first, then a pending one. A request the agent names explicitly is also
191
+ returned once finally denied, so the agent learns the answer. Does not
192
+ spend a grant (:meth:`consume` does). A named request that does not
193
+ bind to this call is ignored: an id never widens what was approved."""
194
+ digest = args_digest(args)
195
+ if request_id is not None:
196
+ req = self._sync(request_id)
197
+ if (req is not None and req.binds(actor, tool, digest, session)
198
+ and self.status(request_id) in (_APPROVED, _PENDING, _DENIED, _TIMED_OUT)):
199
+ return req
200
+ matching = [r for r in list(self._pending.values())
201
+ if r.binds(actor, tool, digest, session)]
202
+ for wanted in (_APPROVED, _PENDING):
203
+ for r in matching:
204
+ if self.status(r.request_id) == wanted:
205
+ return r
206
+ return None
207
+
208
+ def consume(self, request_id: str, actor: str, tool: str,
209
+ args: dict[str, Any] | None, *, session: str | None) -> bool:
210
+ """Spend an approval grant on this exact call. True at most once per
211
+ grant, across every process sharing the store."""
212
+ req = self._sync(request_id)
213
+ if req is None or self.status(request_id) != _APPROVED:
214
+ return False
215
+ if not req.binds(actor, tool, args_digest(args), session):
216
+ return False
217
+ if self._store is not None and not self._store.consume_approval(request_id):
218
+ req.status = _CONSUMED # spent elsewhere, or lapsed in the store
219
+ return False
220
+ req.status = _CONSUMED
221
+ return True
222
+
223
+ def _sync(self, request_id: str) -> ApprovalRequest | None:
224
+ """Refresh one request from the store, the cross-process truth."""
225
+ req = self._pending.get(request_id)
226
+ if self._store is None:
227
+ return req
228
+ row = self._store.approval(request_id)
229
+ if row is None:
230
+ # Gone from the store: spent by another process, or pruned after
231
+ # its window. Either way an approval here can no longer be used.
232
+ if req is not None and req.status == _APPROVED:
233
+ req.status = _CONSUMED
234
+ return req
235
+ if req is None:
236
+ return self._adopt(row)
237
+ if req.status == _PENDING and row["status"] != _PENDING:
238
+ self._apply_resolution(req, row)
239
+ return req
240
+
241
+ def _adopt(self, row: dict) -> ApprovalRequest:
242
+ """Materialize a store row in this process's clock, elapsed age kept."""
243
+ req = ApprovalRequest(
244
+ request_id=row["request_id"], actor=row["actor"], tool=row["tool"],
245
+ created_at=self._clock() - row["age_s"], timeout_s=row["timeout_s"],
246
+ detail=row["detail"], session=row["session"],
247
+ args_digest=row["args_digest"],
248
+ )
249
+ if row["status"] != _PENDING:
250
+ self._apply_resolution(req, row)
251
+ self._pending[req.request_id] = req
252
+ return req
253
+
254
+ def _apply_resolution(self, req: ApprovalRequest, row: dict) -> None:
255
+ req.status = row["status"]
256
+ req.resolved_by = row["resolved_by"]
257
+ req.resolved_at = self._clock() - row["resolved_age_s"]
258
+
259
+ def _evict_final(self) -> None:
260
+ """Forget requests two windows old. By then each is final whatever
261
+ happened (pending timed out one window in; a grant lasts one window
262
+ from approval, which came within the first), so its decision is a deny
263
+ with or without it, and memory stays bounded by the filing rate. The
264
+ store, when there is one, stays the cross-process truth."""
265
+ now = self._clock()
266
+ for rid, req in list(self._pending.items()):
267
+ if now - req.created_at >= 2 * req.timeout_s:
268
+ del self._pending[rid]
269
+
270
+ def _timed_out(self, req: ApprovalRequest) -> bool:
271
+ return req.status == _PENDING and (self._clock() - req.created_at) >= req.timeout_s
272
+
273
+ def _grant_expired(self, req: ApprovalRequest) -> bool:
274
+ return (req.status == _APPROVED and req.resolved_at is not None
275
+ and (self._clock() - req.resolved_at) >= req.timeout_s)
276
+
277
+ def age_s(self, request_id: str) -> float | None:
278
+ """Seconds since the request was submitted (None for an unknown id)."""
279
+ req = self._pending.get(request_id)
280
+ return None if req is None else max(0.0, self._clock() - req.created_at)
281
+
282
+ def remaining_s(self, request_id: str) -> float | None:
283
+ """Seconds until the request lapses (0 once lapsed; None if unknown)."""
284
+ req = self._pending.get(request_id)
285
+ if req is None:
286
+ return None
287
+ return max(0.0, req.timeout_s - (self._clock() - req.created_at))
288
+
289
+ def request(self, request_id: str) -> ApprovalRequest | None:
290
+ """The request itself, resolved or not (None for an unknown id)."""
291
+ return self._sync(request_id)
292
+
293
+ def status(self, request_id: str) -> str:
294
+ req = self._sync(request_id)
295
+ if req is None:
296
+ return "unknown"
297
+ if self._timed_out(req):
298
+ return _TIMED_OUT
299
+ if self._grant_expired(req):
300
+ return _EXPIRED
301
+ return req.status
302
+
303
+ def pending(self) -> list[ApprovalRequest]:
304
+ if self._store is not None:
305
+ for row in self._store.load_approvals(): # filed by any process
306
+ self._sync(row["request_id"])
307
+ return [r for r in list(self._pending.values())
308
+ if r.status == _PENDING and self.status(r.request_id) == _PENDING]
309
+
310
+ # -- decision mapping ----------------------------------------------------
311
+
312
+ def decision(self, request_id: str) -> Decision:
313
+ """Map a request's current state to a gateway Decision (fail-closed)."""
314
+ st = self.status(request_id)
315
+ if st == _APPROVED:
316
+ return Decision.allow()
317
+ if st == _PENDING:
318
+ return Decision.block(
319
+ BlockReason.HITL_REQUIRED,
320
+ [finding("hitl", "hitl.awaiting_approval", "medium", owasp="ASI09")],
321
+ )
322
+ # denied, timed_out, consumed, expired, unknown → deny
323
+ rule = {_TIMED_OUT: "hitl.timed_out", _CONSUMED: "hitl.grant_consumed",
324
+ _EXPIRED: "hitl.grant_expired"}.get(st, "hitl.denied")
325
+ return Decision.block(
326
+ BlockReason.HITL_DENIED,
327
+ [finding("hitl", rule, "high", owasp="ASI09")],
328
+ )
329
+
330
+
331
+ __all__ = ["ApprovalRequest", "HitlGate", "args_digest"]
@@ -0,0 +1,270 @@
1
+ """L4 identity-bound tool policy — the moat (ASI02/ASI03).
2
+
3
+ Every tool call is evaluated against a **default-deny** policy keyed on the
4
+ agent's SPIFFE identity: a tool runs only if this identity has an explicit
5
+ allow rule *and* the call's arguments satisfy that rule's constraints. No
6
+ identity, no matching allow, or a violated constraint → deny, pre-execution,
7
+ with an agent-legible ``block_reason``.
8
+
9
+ Policy is data (YAML), not code, so it hot-reloads and is auditable:
10
+
11
+ agents:
12
+ "spiffe://acme/agent/claude-code":
13
+ allow:
14
+ - tool: http_fetch
15
+ args: { url: { allow_hosts: [docs.python.org, "*.internal"] } }
16
+ - tool: read_file
17
+ args: { path: { allow_prefixes: [/workspace/], deny_prefixes: [/etc/, /secrets/] } }
18
+ deny:
19
+ - { tool: exec_shell }
20
+ budgets: { max_tool_calls_per_min: 60 }
21
+ default: { allow: [] } # unknown identities: deny everything
22
+
23
+ Precedence within an identity: an explicit ``deny`` rule always wins, then an
24
+ ``allow`` rule whose constraints pass; otherwise default-deny. Constraints are
25
+ conjunctive (every listed arg constraint must hold).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import posixpath
31
+ import re
32
+ from dataclasses import dataclass, field
33
+ from pathlib import Path
34
+ from typing import Any
35
+ from urllib.parse import unquote, urlsplit
36
+
37
+ import yaml
38
+ from pydantic import BaseModel, ConfigDict
39
+
40
+ from ..gateway.decision import BlockReason, Decision, finding
41
+ from ..gateway.ssrf import host_allowed
42
+
43
+ _STRICT = ConfigDict(extra="forbid")
44
+
45
+
46
+ class ArgConstraint(BaseModel):
47
+ """Constraints on one argument's value. All present checks must pass."""
48
+
49
+ model_config = _STRICT
50
+ allow_hosts: list[str] | None = None # value is a URL/host; host must match
51
+ allow_prefixes: list[str] | None = None # normalized path must start with one
52
+ deny_prefixes: list[str] | None = None # normalized path must start with none
53
+ allow_values: list[Any] | None = None # value ∈ set
54
+ deny_values: list[Any] | None = None # value ∉ set
55
+ max_len: int | None = None # str length cap
56
+
57
+
58
+ class ToolRule(BaseModel):
59
+ model_config = _STRICT
60
+ tool: str
61
+ args: dict[str, ArgConstraint] = {}
62
+
63
+
64
+ class BudgetRule(BaseModel):
65
+ model_config = _STRICT
66
+ max_tool_calls_per_min: int | None = None
67
+
68
+
69
+ class AgentPolicy(BaseModel):
70
+ model_config = _STRICT
71
+ allow: list[ToolRule] = []
72
+ deny: list[ToolRule] = []
73
+ budgets: BudgetRule = BudgetRule()
74
+
75
+
76
+ class ToolPolicyConfig(BaseModel):
77
+ model_config = _STRICT
78
+ agents: dict[str, AgentPolicy] = {}
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class ToolCall:
83
+ """One tool invocation to authorize. ``args`` maps arg name -> value."""
84
+
85
+ actor: str
86
+ tool: str
87
+ args: dict[str, Any] = field(default_factory=dict)
88
+
89
+
90
+ #: Percent-decoding rounds: enough to unwrap any realistic nesting. A value
91
+ #: still encoded after this is refused rather than guessed at.
92
+ _MAX_DECODE_ROUNDS = 3
93
+ _REPEATED_SLASHES = re.compile(r"/{2,}")
94
+
95
+
96
+ def _normalize_path(value: Any) -> str | None:
97
+ """Canonicalize a path argument so a prefix check cannot be walked out of.
98
+
99
+ Percent-encoding (decoded repeatedly, so double-encoding cannot hide), a
100
+ local ``file://`` scheme, backslashes, repeated slashes and ``..`` / ``.``
101
+ are all collapsed: ``/workspace/../etc/passwd``, ``//etc/passwd``,
102
+ ``/%65tc/passwd`` and ``file:///etc/passwd`` all normalize to
103
+ ``/etc/passwd``. Returns ``None`` for a value that cannot be judged safely
104
+ (a NUL byte, a remote ``file://`` host, or encoding nested too deep), which
105
+ the caller treats as a failed constraint.
106
+
107
+ Symlinks are *not* resolved: the mediator does not see the tool's
108
+ filesystem, so a link inside an allowed prefix must be contained by the
109
+ tool or its sandbox."""
110
+ s = str(value)
111
+ for _ in range(_MAX_DECODE_ROUNDS):
112
+ decoded = unquote(s)
113
+ if decoded == s:
114
+ break
115
+ s = decoded
116
+ else:
117
+ if unquote(s) != s:
118
+ return None
119
+ if "\x00" in s:
120
+ return None
121
+ s = s.replace("\\", "/")
122
+ if s[:7].lower() == "file://":
123
+ authority, slash, rest = s[7:].partition("/")
124
+ if authority.lower() not in ("", "localhost"):
125
+ return None
126
+ s = slash + rest
127
+ # POSIX normpath keeps a leading '//', but the kernel reads it as '/'.
128
+ s = _REPEATED_SLASHES.sub("/", s)
129
+ normed = posixpath.normpath(s)
130
+ # normpath strips a trailing slash; keep leading slash semantics intact.
131
+ if s.startswith("/") and not normed.startswith("/"):
132
+ normed = "/" + normed
133
+ return normed
134
+
135
+
136
+ def _host_of(value: Any) -> str:
137
+ s = str(value)
138
+ parts = urlsplit(s if "://" in s else "//" + s)
139
+ return (parts.hostname or "").lower()
140
+
141
+
142
+ def _constraint_fails(name: str, value: Any, c: ArgConstraint) -> str | None:
143
+ """Return a rule_id describing the first failure, or None if the value passes."""
144
+ if c.max_len is not None and len(str(value)) > c.max_len:
145
+ return f"arg.{name}.too_long"
146
+ if c.allow_hosts is not None:
147
+ if not host_allowed(_host_of(value), c.allow_hosts):
148
+ return f"arg.{name}.host_not_allowed"
149
+ if c.allow_prefixes is not None or c.deny_prefixes is not None:
150
+ p = _normalize_path(value)
151
+ if p is None:
152
+ return f"arg.{name}.invalid"
153
+ if c.allow_prefixes is not None:
154
+ if not any(p == pre.rstrip("/") or p.startswith(pre if pre.endswith("/") else pre + "/")
155
+ for pre in c.allow_prefixes):
156
+ return f"arg.{name}.prefix_not_allowed"
157
+ if c.deny_prefixes is not None:
158
+ if any(p == pre.rstrip("/") or p.startswith(pre if pre.endswith("/") else pre + "/")
159
+ for pre in c.deny_prefixes):
160
+ return f"arg.{name}.prefix_denied"
161
+ if c.allow_values is not None and value not in c.allow_values:
162
+ return f"arg.{name}.value_not_allowed"
163
+ if c.deny_values is not None and value in c.deny_values:
164
+ return f"arg.{name}.value_denied"
165
+ return None
166
+
167
+
168
+ def _rule_matches_args(rule: ToolRule, call: ToolCall) -> str | None:
169
+ """None if every constraint holds; else the failing rule_id.
170
+
171
+ A constraint on an argument the call does not supply fails closed — an
172
+ allow rule that constrains ``path`` exists precisely to bound ``path``, so
173
+ a call omitting it does not get the allow (it falls through to deny)."""
174
+ for arg_name, constraint in rule.args.items():
175
+ if arg_name not in call.args:
176
+ return f"arg.{arg_name}.missing"
177
+ failure = _constraint_fails(arg_name, call.args[arg_name], constraint)
178
+ if failure is not None:
179
+ return failure
180
+ return None
181
+
182
+
183
+ class ToolPolicy:
184
+ """Evaluates tool calls against a :class:`ToolPolicyConfig` (default-deny)."""
185
+
186
+ DEFAULT_KEY = "default"
187
+
188
+ def __init__(self, config: ToolPolicyConfig) -> None:
189
+ self._config = config
190
+
191
+ @classmethod
192
+ def from_yaml(cls, path: str | Path) -> "ToolPolicy":
193
+ raw = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {}
194
+ return cls(ToolPolicyConfig(**raw))
195
+
196
+ @classmethod
197
+ def from_dict(cls, data: dict[str, Any]) -> "ToolPolicy":
198
+ return cls(ToolPolicyConfig(**data))
199
+
200
+ def _policy_for(self, actor: str) -> AgentPolicy | None:
201
+ return self._config.agents.get(actor) or self._config.agents.get(self.DEFAULT_KEY)
202
+
203
+ def budget_for(self, actor: str) -> int | None:
204
+ """This actor's max tool calls per minute, or None for no budget.
205
+
206
+ Keyed on the actor's own policy — never the ``default`` block, so an
207
+ unlisted identity carries no budget (it is already deny-all). A value
208
+ of 0 or less means *no budget* (consistent with ``--max-lifetime 0``
209
+ and ``--idle-timeout 0`` = disabled), never a total lockout."""
210
+ policy = self._config.agents.get(actor)
211
+ if policy is None:
212
+ return None
213
+ limit = policy.budgets.max_tool_calls_per_min
214
+ return limit if (limit is not None and limit > 0) else None
215
+
216
+ def check(self, call: ToolCall) -> Decision:
217
+ """Authorize one tool call. Allow only on an explicit, satisfied rule."""
218
+ policy = self._policy_for(call.actor)
219
+ if policy is None:
220
+ return Decision.block(
221
+ BlockReason.TOOL_NOT_ALLOWED,
222
+ [finding("tool_policy", "policy.no_identity_policy", "high",
223
+ owasp="ASI03", mitre="T1078")],
224
+ )
225
+
226
+ # Explicit deny wins over everything.
227
+ for rule in policy.deny:
228
+ if rule.tool == call.tool and _rule_matches_args(rule, call) is None:
229
+ return Decision.block(
230
+ BlockReason.TOOL_DENIED,
231
+ [finding("tool_policy", "policy.explicit_deny", "high",
232
+ owasp="ASI02", mitre="T1059")],
233
+ )
234
+
235
+ # An allow rule for this tool whose constraints all pass.
236
+ arg_failure: str | None = None
237
+ tool_seen = False
238
+ for rule in policy.allow:
239
+ if rule.tool != call.tool:
240
+ continue
241
+ tool_seen = True
242
+ failure = _rule_matches_args(rule, call)
243
+ if failure is None:
244
+ return Decision.allow()
245
+ arg_failure = failure
246
+
247
+ if tool_seen and arg_failure is not None:
248
+ # The tool is allowed in principle, but an argument constraint failed.
249
+ return Decision.block(
250
+ BlockReason.ARG_NOT_ALLOWED,
251
+ [finding("tool_policy", f"policy.{arg_failure}", "high",
252
+ owasp="ASI02", mitre="T1059")],
253
+ )
254
+
255
+ return Decision.block(
256
+ BlockReason.TOOL_NOT_ALLOWED,
257
+ [finding("tool_policy", "policy.default_deny", "high",
258
+ owasp="ASI03", mitre="T1078")],
259
+ )
260
+
261
+
262
+ __all__ = [
263
+ "AgentPolicy",
264
+ "ArgConstraint",
265
+ "BudgetRule",
266
+ "ToolCall",
267
+ "ToolPolicy",
268
+ "ToolPolicyConfig",
269
+ "ToolRule",
270
+ ]