authzai 0.2.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.
- agentic_auth/__init__.py +8 -0
- agentic_auth/_extras.py +24 -0
- agentic_auth/api/__init__.py +0 -0
- agentic_auth/api/deps.py +112 -0
- agentic_auth/api/errors.py +51 -0
- agentic_auth/api/responses.py +38 -0
- agentic_auth/api/service_deps.py +113 -0
- agentic_auth/api/v1/__init__.py +0 -0
- agentic_auth/api/v1/agents.py +88 -0
- agentic_auth/api/v1/audit.py +67 -0
- agentic_auth/api/v1/authorize.py +439 -0
- agentic_auth/api/v1/consent.py +21 -0
- agentic_auth/api/v1/decisions.py +43 -0
- agentic_auth/api/v1/enrollment.py +48 -0
- agentic_auth/api/v1/identity.py +97 -0
- agentic_auth/api/v1/jwks.py +21 -0
- agentic_auth/api/v1/manifests.py +68 -0
- agentic_auth/api/v1/scopes.py +22 -0
- agentic_auth/api/v1/token.py +203 -0
- agentic_auth/api/v1/transaction.py +94 -0
- agentic_auth/boundary/__init__.py +26 -0
- agentic_auth/boundary/guarantee.py +96 -0
- agentic_auth/cli/__init__.py +27 -0
- agentic_auth/cli/audit.py +130 -0
- agentic_auth/cli/drift.py +164 -0
- agentic_auth/cli/drift_render.py +148 -0
- agentic_auth/cli/identity.py +63 -0
- agentic_auth/cli/manifest.py +275 -0
- agentic_auth/config.py +182 -0
- agentic_auth/db.py +49 -0
- agentic_auth/embedded/__init__.py +427 -0
- agentic_auth/embedded/_schema.py +8 -0
- agentic_auth/embedded/_transport.py +39 -0
- agentic_auth/embedded/capabilities.py +34 -0
- agentic_auth/embedded/export.py +86 -0
- agentic_auth/embedded/idp.py +78 -0
- agentic_auth/embedded/store.py +240 -0
- agentic_auth/errors.py +145 -0
- agentic_auth/main.py +141 -0
- agentic_auth/models/__init__.py +70 -0
- agentic_auth/models/agent.py +58 -0
- agentic_auth/models/audit_decision.py +199 -0
- agentic_auth/models/compiled_policy.py +28 -0
- agentic_auth/models/manifest.py +96 -0
- agentic_auth/models/reconciliation_report.py +27 -0
- agentic_auth/models/sandbox_run.py +93 -0
- agentic_auth/models/session.py +63 -0
- agentic_auth/models/step_up_grant.py +106 -0
- agentic_auth/models/transaction_token.py +73 -0
- agentic_auth/models/trust_anchor.py +59 -0
- agentic_auth/models/types.py +95 -0
- agentic_auth/observability/__init__.py +370 -0
- agentic_auth/observability/config.py +137 -0
- agentic_auth/observability/context.py +128 -0
- agentic_auth/observability/ids.py +122 -0
- agentic_auth/observability/logs.py +191 -0
- agentic_auth/observability/pep.py +169 -0
- agentic_auth/observability/spans.py +225 -0
- agentic_auth/observability/surface.py +286 -0
- agentic_auth/observability/tracing.py +167 -0
- agentic_auth/redis.py +27 -0
- agentic_auth/repositories/__init__.py +0 -0
- agentic_auth/repositories/agents.py +96 -0
- agentic_auth/repositories/audit_decisions.py +152 -0
- agentic_auth/repositories/compiled_policies.py +72 -0
- agentic_auth/repositories/manifests.py +149 -0
- agentic_auth/repositories/reconciliation_reports.py +40 -0
- agentic_auth/repositories/sessions.py +41 -0
- agentic_auth/repositories/transaction_tokens.py +60 -0
- agentic_auth/repositories/trust_anchors.py +150 -0
- agentic_auth/runtime.py +81 -0
- agentic_auth/schemas/__init__.py +0 -0
- agentic_auth/schemas/agent.py +58 -0
- agentic_auth/schemas/audit.py +207 -0
- agentic_auth/schemas/authorize.py +205 -0
- agentic_auth/schemas/common.py +40 -0
- agentic_auth/schemas/consent.py +74 -0
- agentic_auth/schemas/dag.py +39 -0
- agentic_auth/schemas/edge_trace.py +166 -0
- agentic_auth/schemas/identity.py +152 -0
- agentic_auth/schemas/manifest.py +117 -0
- agentic_auth/schemas/manifest_api.py +38 -0
- agentic_auth/schemas/reconciliation.py +49 -0
- agentic_auth/schemas/token.py +122 -0
- agentic_auth/schemas/transaction.py +28 -0
- agentic_auth/sdk/__init__.py +114 -0
- agentic_auth/sdk/client.py +677 -0
- agentic_auth/sdk/context.py +95 -0
- agentic_auth/sdk/drift.py +118 -0
- agentic_auth/sdk/errors.py +147 -0
- agentic_auth/sdk/identity.py +162 -0
- agentic_auth/sdk/planes.py +362 -0
- agentic_auth/sdk/provenance.py +63 -0
- agentic_auth/services/__init__.py +0 -0
- agentic_auth/services/anchors.py +81 -0
- agentic_auth/services/audit.py +222 -0
- agentic_auth/services/audit_chain.py +144 -0
- agentic_auth/services/audit_cursor.py +55 -0
- agentic_auth/services/catalog_service.py +58 -0
- agentic_auth/services/chain_query.py +152 -0
- agentic_auth/services/dag_compiler.py +199 -0
- agentic_auth/services/decision_cache.py +123 -0
- agentic_auth/services/decision_history.py +71 -0
- agentic_auth/services/discovery.py +95 -0
- agentic_auth/services/drift.py +330 -0
- agentic_auth/services/edge_rules.py +62 -0
- agentic_auth/services/edge_trace.py +198 -0
- agentic_auth/services/enrollment.py +310 -0
- agentic_auth/services/enrollment_rules.py +80 -0
- agentic_auth/services/manifest_service.py +166 -0
- agentic_auth/services/metrics.py +419 -0
- agentic_auth/services/pdp.py +312 -0
- agentic_auth/services/policy_loader.py +255 -0
- agentic_auth/services/principal.py +143 -0
- agentic_auth/services/reconciler.py +119 -0
- agentic_auth/services/revocation.py +149 -0
- agentic_auth/services/sessions.py +231 -0
- agentic_auth/services/taint.py +204 -0
- agentic_auth/services/tokens/__init__.py +11 -0
- agentic_auth/services/tokens/act_chain.py +76 -0
- agentic_auth/services/tokens/exchange.py +319 -0
- agentic_auth/services/tokens/jwt_profile.py +362 -0
- agentic_auth/services/tokens/keys.py +117 -0
- agentic_auth/services/tokens/profile.py +167 -0
- agentic_auth/services/tokens/replay.py +53 -0
- agentic_auth/services/transactions.py +172 -0
- agentic_auth/sidecar/__init__.py +7 -0
- agentic_auth/sidecar/__main__.py +66 -0
- agentic_auth/sidecar/app.py +349 -0
- agentic_auth/sidecar/config.py +253 -0
- agentic_auth/sidecar/deny.py +108 -0
- agentic_auth/sidecar/enforce.py +640 -0
- agentic_auth/sidecar/identity.py +37 -0
- agentic_auth/verify/__init__.py +208 -0
- agentic_auth/verify/admit.py +131 -0
- agentic_auth/verify/anchors.py +250 -0
- agentic_auth/verify/canonical.py +228 -0
- agentic_auth/verify/grants.py +158 -0
- agentic_auth/verify/identity.py +111 -0
- agentic_auth/verify/replay.py +67 -0
- agentic_auth/verify/transaction.py +164 -0
- authzai-0.2.0.dist-info/METADATA +276 -0
- authzai-0.2.0.dist-info/RECORD +148 -0
- authzai-0.2.0.dist-info/WHEEL +5 -0
- authzai-0.2.0.dist-info/entry_points.txt +5 -0
- authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
- authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
- authzai-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Resource-side verification: identity AND grant AND, for privileged calls, transaction.
|
|
2
|
+
|
|
3
|
+
Importable with ``pyjwt[crypto]`` alone (``httpx`` only for the ``Http*`` stores). Nothing
|
|
4
|
+
here imports the control plane (``agentic_auth.services``, ``agentic_auth.api``,
|
|
5
|
+
``agentic_auth.models``), FastAPI,
|
|
6
|
+
SQLAlchemy or Redis at module level; ``tests/unit/test_verify_imports.py`` keeps it that
|
|
7
|
+
way. See ``docs/verifier-library.md``.
|
|
8
|
+
|
|
9
|
+
verifier = Verifier(issuer_jwks=HttpJwks(url), anchors=HttpAnchors(...), replay=RedisReplay(r))
|
|
10
|
+
await verifier.bootstrap()
|
|
11
|
+
admission = verifier.admit(request.headers, target=..., params=body, privileged=True)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Protocol, runtime_checkable
|
|
20
|
+
|
|
21
|
+
from agentic_auth.verify.admit import Admission, admit
|
|
22
|
+
from agentic_auth.verify.anchors import (
|
|
23
|
+
Anchor,
|
|
24
|
+
AnchorStore,
|
|
25
|
+
HttpAnchors,
|
|
26
|
+
HttpJwks,
|
|
27
|
+
JwksSource,
|
|
28
|
+
StaticAnchors,
|
|
29
|
+
StaticJwks,
|
|
30
|
+
)
|
|
31
|
+
from agentic_auth.verify.canonical import (
|
|
32
|
+
CanonicalizationError,
|
|
33
|
+
binding_document,
|
|
34
|
+
binding_hash,
|
|
35
|
+
canonical_json,
|
|
36
|
+
select_binding,
|
|
37
|
+
)
|
|
38
|
+
from agentic_auth.verify.grants import VerificationFailed, VerifiedGrant, verify_grant
|
|
39
|
+
from agentic_auth.verify.identity import VerifiedIdentity, verify_identity
|
|
40
|
+
from agentic_auth.verify.replay import (
|
|
41
|
+
InMemoryReplay,
|
|
42
|
+
RedisReplay,
|
|
43
|
+
ReplayStore,
|
|
44
|
+
ReplayStoreUnavailable,
|
|
45
|
+
)
|
|
46
|
+
from agentic_auth.verify.transaction import VerifiedTransaction, verify_transaction
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@runtime_checkable
|
|
50
|
+
class TelemetrySink(Protocol):
|
|
51
|
+
"""How an integrator gets the verifier's spans and events, without this package growing a
|
|
52
|
+
dependency on OpenTelemetry.
|
|
53
|
+
|
|
54
|
+
This package is importable with **only** ``pyjwt[crypto]``, which
|
|
55
|
+
``tests/unit/test_verify_imports.py`` enforces — so the seam is a ``Protocol``, not an
|
|
56
|
+
import. The OTel-backed implementation lives in ``agentic_auth.observability``, which the
|
|
57
|
+
integrator opts into; ``None`` means emit nothing, exactly as ``metrics_registry`` already
|
|
58
|
+
works.
|
|
59
|
+
|
|
60
|
+
It is a protocol for a second reason too. ``trace.set_tracer_provider()`` is process-global
|
|
61
|
+
and warns-and-ignores on a second call, so a library that installs telemetry in a host it
|
|
62
|
+
does not own either hijacks the host's pipeline or silently emits nothing. Accepting a sink
|
|
63
|
+
the host constructed is the only correct option.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def span(self, name: str, attributes: Mapping[str, Any]) -> None:
|
|
67
|
+
"""Record one completed span. Must not raise."""
|
|
68
|
+
|
|
69
|
+
def event(self, name: str, attributes: Mapping[str, Any]) -> None:
|
|
70
|
+
"""Record one point-in-time event. Must not raise."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _build_metrics(registry: Any) -> Any:
|
|
74
|
+
"""The verifier's own metric objects, defined here so this package never imports the
|
|
75
|
+
control plane's ``agentic_auth.services.metrics``. Names mirror docs/contracts/metrics/."""
|
|
76
|
+
from prometheus_client import Counter, Gauge
|
|
77
|
+
|
|
78
|
+
class _Metrics:
|
|
79
|
+
def __init__(self) -> None:
|
|
80
|
+
self.admissions = Counter(
|
|
81
|
+
"agentic_auth_admissions", "admit() outcomes", ["result"], registry=registry
|
|
82
|
+
)
|
|
83
|
+
self.transaction_rejections = Counter(
|
|
84
|
+
"agentic_auth_transaction_rejections",
|
|
85
|
+
"Transaction-token rejections by cause",
|
|
86
|
+
["cause"],
|
|
87
|
+
registry=registry,
|
|
88
|
+
)
|
|
89
|
+
self.identity_view_age = Gauge(
|
|
90
|
+
"agentic_auth_identity_view_age_seconds",
|
|
91
|
+
"Seconds since the anchor view was last refreshed",
|
|
92
|
+
registry=registry,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
return _Metrics()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class Verifier:
|
|
100
|
+
issuer_jwks: JwksSource
|
|
101
|
+
anchors: AnchorStore
|
|
102
|
+
replay: ReplayStore
|
|
103
|
+
identity_required: bool = True
|
|
104
|
+
freshness_seconds: int = 30
|
|
105
|
+
issuer: str = "agentic-auth"
|
|
106
|
+
leeway_seconds: int = 60
|
|
107
|
+
metrics_registry: Any = None
|
|
108
|
+
# Phase 6. Supplied by the integrator; None means emit nothing. The verifier
|
|
109
|
+
# never constructs one, and never touches process-global telemetry.
|
|
110
|
+
telemetry: TelemetrySink | None = None
|
|
111
|
+
_metrics: Any = field(default=None, init=False, repr=False)
|
|
112
|
+
|
|
113
|
+
def __post_init__(self) -> None:
|
|
114
|
+
if self.metrics_registry is not None:
|
|
115
|
+
self._metrics = _build_metrics(self.metrics_registry)
|
|
116
|
+
|
|
117
|
+
async def bootstrap(self) -> None:
|
|
118
|
+
"""Fetch issuer keys and anchors once, then start refreshing. Raises on failure."""
|
|
119
|
+
if isinstance(self.issuer_jwks, HttpJwks):
|
|
120
|
+
await self.issuer_jwks.refresh()
|
|
121
|
+
if isinstance(self.anchors, HttpAnchors):
|
|
122
|
+
self.anchors.freshness_seconds = self.freshness_seconds
|
|
123
|
+
await self.anchors.bootstrap()
|
|
124
|
+
self.anchors.start()
|
|
125
|
+
|
|
126
|
+
async def close(self) -> None:
|
|
127
|
+
if isinstance(self.anchors, HttpAnchors):
|
|
128
|
+
await self.anchors.stop()
|
|
129
|
+
|
|
130
|
+
def admit(
|
|
131
|
+
self,
|
|
132
|
+
headers: Mapping[str, str],
|
|
133
|
+
*,
|
|
134
|
+
target: str,
|
|
135
|
+
params: Mapping[str, Any] | None = None,
|
|
136
|
+
privileged: bool = False,
|
|
137
|
+
) -> Admission:
|
|
138
|
+
if self._metrics is not None and isinstance(self.anchors, HttpAnchors):
|
|
139
|
+
age = self.anchors.age_seconds()
|
|
140
|
+
if age is not None:
|
|
141
|
+
self._metrics.identity_view_age.set(age)
|
|
142
|
+
admission = admit(
|
|
143
|
+
headers,
|
|
144
|
+
target=target,
|
|
145
|
+
params=params,
|
|
146
|
+
privileged=privileged,
|
|
147
|
+
issuer_jwks=self.issuer_jwks,
|
|
148
|
+
anchors=self.anchors,
|
|
149
|
+
replay=self.replay,
|
|
150
|
+
identity_required=self.identity_required,
|
|
151
|
+
freshness_seconds=self.freshness_seconds,
|
|
152
|
+
issuer=self.issuer,
|
|
153
|
+
leeway_seconds=self.leeway_seconds,
|
|
154
|
+
metrics=self._metrics,
|
|
155
|
+
)
|
|
156
|
+
self._emit(admission, target=target, privileged=privileged)
|
|
157
|
+
return admission
|
|
158
|
+
|
|
159
|
+
def _emit(self, admission: Admission, *, target: str, privileged: bool) -> None:
|
|
160
|
+
"""Hand one span to the integrator's sink, if they supplied one.
|
|
161
|
+
|
|
162
|
+
Carries the outcome and the reason, and deliberately **not** the target: a target is an
|
|
163
|
+
identity, and identities stay behind the audit-reader check unless the deployment opted
|
|
164
|
+
in. A failing sink is swallowed — telemetry must never be the reason a resource server
|
|
165
|
+
refuses a legitimate call, or admits an illegitimate one.
|
|
166
|
+
"""
|
|
167
|
+
if self.telemetry is None:
|
|
168
|
+
return
|
|
169
|
+
with contextlib.suppress(Exception): # pragma: no cover - never fatal
|
|
170
|
+
self.telemetry.span(
|
|
171
|
+
"verify.admit",
|
|
172
|
+
{
|
|
173
|
+
"authz.outcome": "allow" if admission.admitted else "deny",
|
|
174
|
+
"authz.deny_reason": getattr(admission, "reason", None),
|
|
175
|
+
"authz.privileged": privileged,
|
|
176
|
+
},
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
__all__ = [
|
|
181
|
+
"Admission",
|
|
182
|
+
"TelemetrySink",
|
|
183
|
+
"Anchor",
|
|
184
|
+
"AnchorStore",
|
|
185
|
+
"CanonicalizationError",
|
|
186
|
+
"HttpAnchors",
|
|
187
|
+
"HttpJwks",
|
|
188
|
+
"InMemoryReplay",
|
|
189
|
+
"JwksSource",
|
|
190
|
+
"RedisReplay",
|
|
191
|
+
"ReplayStore",
|
|
192
|
+
"ReplayStoreUnavailable",
|
|
193
|
+
"StaticAnchors",
|
|
194
|
+
"StaticJwks",
|
|
195
|
+
"VerificationFailed",
|
|
196
|
+
"VerifiedGrant",
|
|
197
|
+
"VerifiedIdentity",
|
|
198
|
+
"VerifiedTransaction",
|
|
199
|
+
"Verifier",
|
|
200
|
+
"admit",
|
|
201
|
+
"binding_document",
|
|
202
|
+
"binding_hash",
|
|
203
|
+
"canonical_json",
|
|
204
|
+
"select_binding",
|
|
205
|
+
"verify_grant",
|
|
206
|
+
"verify_identity",
|
|
207
|
+
"verify_transaction",
|
|
208
|
+
]
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""``admit()`` — the one place identity and authorization are combined, as a conjunction.
|
|
2
|
+
|
|
3
|
+
grant AND (identity, when required) AND (transaction, when privileged)
|
|
4
|
+
|
|
5
|
+
There is no path here that admits on identity alone, and no path that admits a privileged
|
|
6
|
+
call without its transaction token. Each refusal names exactly the step that failed, so a
|
|
7
|
+
resource can answer precisely without leaking anything else (docs/verifier-library.md).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from agentic_auth.verify.anchors import AnchorStore, JwksSource
|
|
17
|
+
from agentic_auth.verify.grants import VerificationFailed, VerifiedGrant, verify_grant
|
|
18
|
+
from agentic_auth.verify.identity import VerifiedIdentity, verify_identity
|
|
19
|
+
from agentic_auth.verify.replay import ReplayStore
|
|
20
|
+
from agentic_auth.verify.transaction import REJECTION_CAUSE, VerifiedTransaction, verify_transaction
|
|
21
|
+
|
|
22
|
+
# `mutmut run` leaves 1 equivalent mutant here: the default `leeway_seconds` 60 -> 61. It moves
|
|
23
|
+
# a clock-skew boundary by one second, which cannot be observed deterministically without an
|
|
24
|
+
# injectable clock (PyJWT reads the wall clock). Every other mutant is killed, including that
|
|
25
|
+
# `issuer` and `leeway_seconds` actually reach the grant, identity and transaction checks
|
|
26
|
+
# (tests/unit/test_verify_admit.py: custom issuer, per-step leeway).
|
|
27
|
+
|
|
28
|
+
AUTHORIZATION = "authorization"
|
|
29
|
+
AGENT_IDENTITY = "agent-identity"
|
|
30
|
+
TXN_TOKEN = "txn-token"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Admission:
|
|
35
|
+
ok: bool
|
|
36
|
+
reason: str | None = None
|
|
37
|
+
detail: str | None = None
|
|
38
|
+
grant: VerifiedGrant | None = None
|
|
39
|
+
identity: VerifiedIdentity | None = None
|
|
40
|
+
transaction: VerifiedTransaction | None = None
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def details(self) -> dict[str, Any]:
|
|
44
|
+
return {"reason": self.reason, "detail": self.detail}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _header(headers: Mapping[str, str], name: str) -> str | None:
|
|
48
|
+
for key, value in headers.items():
|
|
49
|
+
if key.lower() == name:
|
|
50
|
+
return value
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _bearer(headers: Mapping[str, str]) -> str | None:
|
|
55
|
+
raw = _header(headers, AUTHORIZATION)
|
|
56
|
+
if not raw or not raw.startswith("Bearer "):
|
|
57
|
+
return None
|
|
58
|
+
return raw.removeprefix("Bearer ").strip() or None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def admit(
|
|
62
|
+
headers: Mapping[str, str],
|
|
63
|
+
*,
|
|
64
|
+
target: str,
|
|
65
|
+
params: Mapping[str, Any] | None,
|
|
66
|
+
privileged: bool,
|
|
67
|
+
issuer_jwks: JwksSource,
|
|
68
|
+
anchors: AnchorStore,
|
|
69
|
+
replay: ReplayStore,
|
|
70
|
+
identity_required: bool,
|
|
71
|
+
freshness_seconds: int,
|
|
72
|
+
issuer: str = "agentic-auth",
|
|
73
|
+
leeway_seconds: int = 60,
|
|
74
|
+
metrics: Any = None,
|
|
75
|
+
) -> Admission:
|
|
76
|
+
"""Decide admission from the request headers alone. No I/O beyond the replay claim."""
|
|
77
|
+
jwks = issuer_jwks.jwks()
|
|
78
|
+
try:
|
|
79
|
+
if jwks is None:
|
|
80
|
+
raise VerificationFailed("GRANT_INVALID", "issuer keys were never bootstrapped")
|
|
81
|
+
|
|
82
|
+
# 1. the grant: what this call is allowed to be
|
|
83
|
+
grant = verify_grant(
|
|
84
|
+
_bearer(headers),
|
|
85
|
+
issuer_jwks=jwks,
|
|
86
|
+
audience=target,
|
|
87
|
+
issuer=issuer,
|
|
88
|
+
leeway_seconds=leeway_seconds,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# 2. the identity: who is presenting it (never sufficient on its own)
|
|
92
|
+
identity: VerifiedIdentity | None = None
|
|
93
|
+
if identity_required:
|
|
94
|
+
identity = verify_identity(
|
|
95
|
+
_header(headers, AGENT_IDENTITY),
|
|
96
|
+
anchors=anchors,
|
|
97
|
+
target=target,
|
|
98
|
+
grant=grant,
|
|
99
|
+
freshness_seconds=freshness_seconds,
|
|
100
|
+
leeway_seconds=leeway_seconds,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# 3. the transaction: this exact call, once
|
|
104
|
+
transaction: VerifiedTransaction | None = None
|
|
105
|
+
if privileged:
|
|
106
|
+
if params is None:
|
|
107
|
+
raise VerificationFailed("TXN_PARAMS_MISMATCH", "privileged call has no params")
|
|
108
|
+
transaction = verify_transaction(
|
|
109
|
+
_header(headers, TXN_TOKEN),
|
|
110
|
+
target=target,
|
|
111
|
+
params=params,
|
|
112
|
+
grant=grant,
|
|
113
|
+
issuer_jwks=jwks,
|
|
114
|
+
replay=replay,
|
|
115
|
+
issuer=issuer,
|
|
116
|
+
leeway_seconds=leeway_seconds,
|
|
117
|
+
)
|
|
118
|
+
except VerificationFailed as failed:
|
|
119
|
+
if metrics is not None:
|
|
120
|
+
metrics.admissions.labels(result=failed.reason).inc()
|
|
121
|
+
cause = REJECTION_CAUSE.get(failed.reason)
|
|
122
|
+
if cause is not None:
|
|
123
|
+
metrics.transaction_rejections.labels(cause=cause).inc()
|
|
124
|
+
return Admission(ok=False, reason=failed.reason, detail=failed.detail)
|
|
125
|
+
|
|
126
|
+
if metrics is not None:
|
|
127
|
+
metrics.admissions.labels(result="admitted").inc()
|
|
128
|
+
return Admission(ok=True, grant=grant, identity=identity, transaction=transaction)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
__all__ = ["Admission", "admit"]
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Where a resource gets the keys it verifies against — and how fresh that view is.
|
|
2
|
+
|
|
3
|
+
Two kinds of material: the control plane's issuer JWKS (hop and transaction tokens) and
|
|
4
|
+
each agent's pinned trust anchor (identity assertions). ``Static*`` variants are for tests
|
|
5
|
+
and air-gapped deployments; ``Http*`` variants bootstrap once and refresh in the
|
|
6
|
+
background. Every verification is a dictionary lookup: no I/O on the request path.
|
|
7
|
+
|
|
8
|
+
Freshness is a property the verifier refuses on. ``as_of()`` is the last successful
|
|
9
|
+
refresh; past ``freshness_seconds`` every identity is ``IDENTITY_STALE`` until a refresh
|
|
10
|
+
succeeds. A store that never bootstrapped refuses everything.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import contextlib
|
|
17
|
+
import logging
|
|
18
|
+
import time
|
|
19
|
+
from collections.abc import Iterable, Mapping
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from datetime import UTC, datetime
|
|
22
|
+
from typing import Any, Protocol
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# -- issuer keys -------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class JwksSource(Protocol):
|
|
31
|
+
def jwks(self) -> Mapping[str, Any] | None: ...
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class StaticJwks:
|
|
35
|
+
def __init__(self, jwks: Mapping[str, Any]) -> None:
|
|
36
|
+
self._jwks = dict(jwks)
|
|
37
|
+
|
|
38
|
+
def jwks(self) -> Mapping[str, Any]:
|
|
39
|
+
return self._jwks
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class HttpJwks:
|
|
43
|
+
"""Fetches ``GET {url}`` once at bootstrap and on every refresh."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, url: str, *, client: Any = None) -> None:
|
|
46
|
+
self._url = url
|
|
47
|
+
self._client = client
|
|
48
|
+
self._jwks: dict[str, Any] | None = None
|
|
49
|
+
|
|
50
|
+
def jwks(self) -> Mapping[str, Any] | None:
|
|
51
|
+
return self._jwks
|
|
52
|
+
|
|
53
|
+
async def refresh(self) -> None:
|
|
54
|
+
import httpx
|
|
55
|
+
|
|
56
|
+
client = self._client or httpx.AsyncClient(timeout=httpx.Timeout(5.0))
|
|
57
|
+
try:
|
|
58
|
+
response = await client.get(self._url)
|
|
59
|
+
response.raise_for_status()
|
|
60
|
+
body = response.json()
|
|
61
|
+
if not isinstance(body, dict) or not isinstance(body.get("keys"), list):
|
|
62
|
+
raise ValueError("JWKS document is malformed")
|
|
63
|
+
self._jwks = body
|
|
64
|
+
finally:
|
|
65
|
+
if self._client is None:
|
|
66
|
+
await client.aclose()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# -- trust anchors ---------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class Anchor:
|
|
74
|
+
"""One agent's identity material, as ``GET /v1/agents/{id}/identity`` serves it."""
|
|
75
|
+
|
|
76
|
+
agent: str
|
|
77
|
+
status: str
|
|
78
|
+
trust_anchor_version: int | None
|
|
79
|
+
jwks: Mapping[str, Any] | None
|
|
80
|
+
revoked: bool
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def from_read(read: Mapping[str, Any]) -> Anchor:
|
|
84
|
+
return Anchor(
|
|
85
|
+
agent=str(read["agent"]),
|
|
86
|
+
status=str(read.get("status", "registered")),
|
|
87
|
+
trust_anchor_version=read.get("trust_anchor_version"),
|
|
88
|
+
jwks=read.get("jwks"),
|
|
89
|
+
revoked=bool(read.get("revoked", False)) or read.get("status") == "revoked",
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def live(self) -> bool:
|
|
94
|
+
return self.status == "enrolled" and not self.revoked and self.jwks is not None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class AnchorStore(Protocol):
|
|
98
|
+
def current(self, agent: str) -> Anchor | None: ...
|
|
99
|
+
def revoked(self, agent: str) -> bool: ...
|
|
100
|
+
def as_of(self) -> datetime | None: ...
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class StaticAnchors:
|
|
104
|
+
"""Anchors shipped as data. Never stale: the integrator owns rotation."""
|
|
105
|
+
|
|
106
|
+
def __init__(self, reads: Iterable[Mapping[str, Any]]) -> None:
|
|
107
|
+
self._anchors = {a.agent: a for a in (Anchor.from_read(r) for r in reads)}
|
|
108
|
+
self._as_of = datetime.now(UTC)
|
|
109
|
+
|
|
110
|
+
def current(self, agent: str) -> Anchor | None:
|
|
111
|
+
return self._anchors.get(agent)
|
|
112
|
+
|
|
113
|
+
def revoked(self, agent: str) -> bool:
|
|
114
|
+
anchor = self._anchors.get(agent)
|
|
115
|
+
return anchor is not None and anchor.revoked
|
|
116
|
+
|
|
117
|
+
def as_of(self) -> datetime | None:
|
|
118
|
+
return self._as_of
|
|
119
|
+
|
|
120
|
+
def revoke(self, agent: str) -> None: # tests and manual operations
|
|
121
|
+
anchor = self._anchors.get(agent)
|
|
122
|
+
if anchor is not None:
|
|
123
|
+
self._anchors[agent] = Anchor(
|
|
124
|
+
anchor.agent, "revoked", anchor.trust_anchor_version, anchor.jwks, True
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _is_unknown_agent(response: Any) -> bool:
|
|
129
|
+
"""The control plane answers an unregistered agent with its error envelope
|
|
130
|
+
(``{"error": {"code": "not_found"}}``). A bare ``{"detail": "Not Found"}`` is the
|
|
131
|
+
framework saying the route does not exist — a deployment problem that must fail the
|
|
132
|
+
bootstrap, not be mistaken for an agent nobody registered."""
|
|
133
|
+
try:
|
|
134
|
+
body = response.json()
|
|
135
|
+
except ValueError:
|
|
136
|
+
return False
|
|
137
|
+
return isinstance(body, dict) and isinstance(body.get("error"), dict)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass
|
|
141
|
+
class HttpAnchors:
|
|
142
|
+
"""Bootstraps each configured agent's identity and the revocation list from the
|
|
143
|
+
control plane, then refreshes every ``freshness_seconds``.
|
|
144
|
+
|
|
145
|
+
``token`` is an identity-reader bearer (the audit reader or admin token) — it needs no
|
|
146
|
+
other privilege. ``agents`` are the names this resource expects to see; an agent outside
|
|
147
|
+
the list is ``IDENTITY_UNKNOWN_AGENT`` until the list is widened.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
base_url: str
|
|
151
|
+
token: str
|
|
152
|
+
agents: list[str]
|
|
153
|
+
freshness_seconds: int = 30
|
|
154
|
+
client: Any = None
|
|
155
|
+
clock: Any = time.monotonic
|
|
156
|
+
_anchors: dict[str, Anchor] = field(default_factory=dict)
|
|
157
|
+
_as_of: datetime | None = None
|
|
158
|
+
_as_of_mono: float | None = None
|
|
159
|
+
_revocations_since: str | None = None
|
|
160
|
+
_task: asyncio.Task[None] | None = None
|
|
161
|
+
|
|
162
|
+
def current(self, agent: str) -> Anchor | None:
|
|
163
|
+
return self._anchors.get(agent)
|
|
164
|
+
|
|
165
|
+
def revoked(self, agent: str) -> bool:
|
|
166
|
+
anchor = self._anchors.get(agent)
|
|
167
|
+
return anchor is not None and anchor.revoked
|
|
168
|
+
|
|
169
|
+
def as_of(self) -> datetime | None:
|
|
170
|
+
return self._as_of
|
|
171
|
+
|
|
172
|
+
def age_seconds(self) -> float | None:
|
|
173
|
+
return None if self._as_of_mono is None else self.clock() - self._as_of_mono
|
|
174
|
+
|
|
175
|
+
# -- I/O ----------------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
def _http(self) -> Any:
|
|
178
|
+
import httpx
|
|
179
|
+
|
|
180
|
+
return self.client or httpx.AsyncClient(timeout=httpx.Timeout(5.0))
|
|
181
|
+
|
|
182
|
+
async def bootstrap(self) -> None:
|
|
183
|
+
"""Fetch everything once. Raises on failure: a verifier must not start with an
|
|
184
|
+
empty view and admit nothing while looking healthy — it must fail to start."""
|
|
185
|
+
await self.refresh(raise_on_error=True)
|
|
186
|
+
|
|
187
|
+
async def refresh(self, *, raise_on_error: bool = False) -> bool:
|
|
188
|
+
"""Refresh the view. Returns ``True`` on success. On failure the previous view is
|
|
189
|
+
kept and ``as_of`` keeps ageing toward stale."""
|
|
190
|
+
http = self._http()
|
|
191
|
+
headers = {"Authorization": f"Bearer {self.token}"}
|
|
192
|
+
try:
|
|
193
|
+
fresh: dict[str, Anchor] = {}
|
|
194
|
+
for name in self.agents:
|
|
195
|
+
r = await http.get(f"{self.base_url}/v1/identity/agents/{name}", headers=headers)
|
|
196
|
+
if r.status_code == 404 and _is_unknown_agent(r):
|
|
197
|
+
continue # never registered: unknown, not an error
|
|
198
|
+
r.raise_for_status() # a 404 WITHOUT the error envelope is a missing route
|
|
199
|
+
fresh[name] = Anchor.from_read(r.json())
|
|
200
|
+
revoked = await http.get(
|
|
201
|
+
f"{self.base_url}/v1/identity/revocations?limit=100", headers=headers
|
|
202
|
+
)
|
|
203
|
+
revoked.raise_for_status()
|
|
204
|
+
for item in revoked.json().get("items", []):
|
|
205
|
+
name = item["agent"]
|
|
206
|
+
anchor = fresh.get(name)
|
|
207
|
+
if anchor is not None and not anchor.revoked:
|
|
208
|
+
fresh[name] = Anchor(
|
|
209
|
+
anchor.agent, "revoked", anchor.trust_anchor_version, anchor.jwks, True
|
|
210
|
+
)
|
|
211
|
+
self._anchors = fresh
|
|
212
|
+
self._as_of = datetime.now(UTC)
|
|
213
|
+
self._as_of_mono = self.clock()
|
|
214
|
+
return True
|
|
215
|
+
except Exception as exc:
|
|
216
|
+
logger.warning("anchor refresh failed: %s", type(exc).__name__)
|
|
217
|
+
if raise_on_error:
|
|
218
|
+
raise
|
|
219
|
+
return False
|
|
220
|
+
finally:
|
|
221
|
+
if self.client is None:
|
|
222
|
+
await http.aclose()
|
|
223
|
+
|
|
224
|
+
def start(self) -> None:
|
|
225
|
+
"""Refresh in the background every ``freshness_seconds / 2``."""
|
|
226
|
+
if self._task is None:
|
|
227
|
+
self._task = asyncio.create_task(self._loop())
|
|
228
|
+
|
|
229
|
+
async def stop(self) -> None:
|
|
230
|
+
if self._task is not None:
|
|
231
|
+
self._task.cancel()
|
|
232
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
233
|
+
await self._task
|
|
234
|
+
self._task = None
|
|
235
|
+
|
|
236
|
+
async def _loop(self) -> None:
|
|
237
|
+
while True:
|
|
238
|
+
await asyncio.sleep(max(self.freshness_seconds / 2, 1))
|
|
239
|
+
await self.refresh()
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
__all__ = [
|
|
243
|
+
"Anchor",
|
|
244
|
+
"AnchorStore",
|
|
245
|
+
"HttpAnchors",
|
|
246
|
+
"HttpJwks",
|
|
247
|
+
"JwksSource",
|
|
248
|
+
"StaticAnchors",
|
|
249
|
+
"StaticJwks",
|
|
250
|
+
]
|