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,310 @@
|
|
|
1
|
+
"""Enrollment: challenge, then a signed response; enrolled, quarantined, or rejected.
|
|
2
|
+
|
|
3
|
+
``begin`` stores a single-use challenge bound to the agent and to a hash of the identity
|
|
4
|
+
document. ``complete`` consumes it (``GETDEL``) before doing anything else, verifies the
|
|
5
|
+
signature against a key IN THE PRESENTED DOCUMENT (never the issuer's keys, never a key the
|
|
6
|
+
agent names but did not present), runs principal binding, then hands every fact to the pure
|
|
7
|
+
:func:`agentic_auth.services.enrollment_rules.decide` and applies the outcome in one transaction.
|
|
8
|
+
|
|
9
|
+
Completing enrollment grants nothing. It pins a trust anchor; authorization is elsewhere.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
import secrets
|
|
17
|
+
import uuid
|
|
18
|
+
from datetime import UTC, datetime, timedelta
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import jwt
|
|
22
|
+
from redis.asyncio import Redis
|
|
23
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
24
|
+
|
|
25
|
+
from agentic_auth.config import get_settings
|
|
26
|
+
from agentic_auth.errors import (
|
|
27
|
+
IdpUnavailable,
|
|
28
|
+
KeyRevoked,
|
|
29
|
+
NotFoundError,
|
|
30
|
+
ReconciliationRejected,
|
|
31
|
+
UnauthorizedError,
|
|
32
|
+
)
|
|
33
|
+
from agentic_auth.repositories import agents as agents_repo
|
|
34
|
+
from agentic_auth.repositories import manifests as manifests_repo
|
|
35
|
+
from agentic_auth.repositories import reconciliation_reports as reports_repo
|
|
36
|
+
from agentic_auth.repositories import trust_anchors as anchors_repo
|
|
37
|
+
from agentic_auth.schemas.identity import (
|
|
38
|
+
EnrollBegin,
|
|
39
|
+
EnrollChallenge,
|
|
40
|
+
EnrollComplete,
|
|
41
|
+
EnrollOutcome,
|
|
42
|
+
IdentityDocument,
|
|
43
|
+
)
|
|
44
|
+
from agentic_auth.services.anchors import AnchorCache, thumbprint
|
|
45
|
+
from agentic_auth.services.enrollment_rules import (
|
|
46
|
+
Bound,
|
|
47
|
+
EnrollDecision,
|
|
48
|
+
NotConfigured,
|
|
49
|
+
Unbindable,
|
|
50
|
+
decide,
|
|
51
|
+
)
|
|
52
|
+
from agentic_auth.services.metrics import get_metrics
|
|
53
|
+
from agentic_auth.services.principal import PrincipalBinder
|
|
54
|
+
from agentic_auth.verify.canonical import canonical_json
|
|
55
|
+
|
|
56
|
+
logger = logging.getLogger(__name__)
|
|
57
|
+
|
|
58
|
+
AGENT_PREFIX = "agent://"
|
|
59
|
+
RESPONSE_MAX_LIFETIME = 120
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ChallengeStoreUnavailable(RuntimeError):
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def challenge_key(challenge_id: uuid.UUID | str) -> str:
|
|
67
|
+
return f"enroll:{challenge_id}"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _doc_hash(doc: IdentityDocument) -> str:
|
|
71
|
+
import base64
|
|
72
|
+
import hashlib
|
|
73
|
+
|
|
74
|
+
digest = hashlib.sha256(canonical_json(doc.public_document())).digest()
|
|
75
|
+
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class EnrollmentService:
|
|
79
|
+
def __init__(self, binder: PrincipalBinder, anchors: AnchorCache) -> None:
|
|
80
|
+
self._binder = binder
|
|
81
|
+
self._anchors = anchors
|
|
82
|
+
|
|
83
|
+
# -- begin ---------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
async def begin(
|
|
86
|
+
self, db: AsyncSession, redis: Redis | None, agent_id: uuid.UUID, body: EnrollBegin
|
|
87
|
+
) -> EnrollChallenge:
|
|
88
|
+
agent = await agents_repo.get_by_id(db, agent_id)
|
|
89
|
+
if agent is None:
|
|
90
|
+
raise NotFoundError(f"agent {agent_id} not found")
|
|
91
|
+
if agent.status == "revoked":
|
|
92
|
+
raise KeyRevoked(f"agent {agent.name} is revoked; enrollment is closed")
|
|
93
|
+
if body.identity_doc.sub != f"{AGENT_PREFIX}{agent.name}":
|
|
94
|
+
from agentic_auth.errors import ManifestValidationError
|
|
95
|
+
|
|
96
|
+
raise ManifestValidationError(
|
|
97
|
+
"identity document names another agent",
|
|
98
|
+
{
|
|
99
|
+
"fields": [
|
|
100
|
+
{
|
|
101
|
+
"loc": ["identity_doc", "sub"],
|
|
102
|
+
"msg": f"expected agent://{agent.name}",
|
|
103
|
+
}
|
|
104
|
+
]
|
|
105
|
+
},
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
settings = get_settings()
|
|
109
|
+
challenge_id = uuid.uuid4()
|
|
110
|
+
nonce = secrets.token_urlsafe(32)
|
|
111
|
+
expires_at = datetime.now(UTC) + timedelta(seconds=settings.enroll_challenge_ttl_seconds)
|
|
112
|
+
record = {
|
|
113
|
+
"agent_id": str(agent.id),
|
|
114
|
+
"doc_hash": _doc_hash(body.identity_doc),
|
|
115
|
+
"nonce": nonce,
|
|
116
|
+
# The public document is kept with the challenge so `complete` verifies against
|
|
117
|
+
# exactly the keys that were presented, and can keep them for quarantine.
|
|
118
|
+
"doc": body.identity_doc.public_document(),
|
|
119
|
+
# The assertion is a short-lived IdP credential. It is held ONLY here, in the
|
|
120
|
+
# control plane's own Redis, for at most enroll_challenge_ttl_seconds, consumed
|
|
121
|
+
# by GETDEL on the first `complete`, and never written to a table, a metric or
|
|
122
|
+
# a log (security audit). Requiring the agent to re-present it at
|
|
123
|
+
# `complete` would let a caller swap in a different principal than the one the
|
|
124
|
+
# challenge was issued for, which is why it is bound to the challenge instead.
|
|
125
|
+
"principal_assertion": body.identity_doc.principal_assertion,
|
|
126
|
+
}
|
|
127
|
+
if redis is None:
|
|
128
|
+
raise ChallengeStoreUnavailable("no challenge store configured")
|
|
129
|
+
try:
|
|
130
|
+
await redis.set(
|
|
131
|
+
challenge_key(challenge_id),
|
|
132
|
+
json.dumps(record),
|
|
133
|
+
ex=settings.enroll_challenge_ttl_seconds,
|
|
134
|
+
)
|
|
135
|
+
except Exception as exc:
|
|
136
|
+
raise ChallengeStoreUnavailable(f"challenge store unreachable: {exc}") from exc
|
|
137
|
+
return EnrollChallenge(challenge_id=challenge_id, nonce=nonce, expires_at=expires_at)
|
|
138
|
+
|
|
139
|
+
# -- complete ------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
async def complete(
|
|
142
|
+
self, db: AsyncSession, redis: Redis | None, agent_id: uuid.UUID, body: EnrollComplete
|
|
143
|
+
) -> EnrollOutcome:
|
|
144
|
+
metrics = get_metrics()
|
|
145
|
+
agent = await agents_repo.get_by_id(db, agent_id)
|
|
146
|
+
if agent is None:
|
|
147
|
+
raise NotFoundError(f"agent {agent_id} not found")
|
|
148
|
+
|
|
149
|
+
record = await self._consume_challenge(redis, body.challenge_id)
|
|
150
|
+
if record is None or record.get("agent_id") != str(agent.id):
|
|
151
|
+
metrics.enrollments.labels(outcome="rejected").inc()
|
|
152
|
+
raise UnauthorizedError("challenge is unknown, expired, or already used")
|
|
153
|
+
|
|
154
|
+
doc: dict[str, Any] = record["doc"]
|
|
155
|
+
keys: list[dict[str, Any]] = doc["jwks"]["keys"]
|
|
156
|
+
signature_ok = self._verify_response(
|
|
157
|
+
body.signed_response, keys, record["nonce"], agent.name
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
presented = {thumbprint(k) for k in keys}
|
|
161
|
+
revoked = await anchors_repo.revoked_thumbprints(db, agent.id)
|
|
162
|
+
revoked_key = agent.status == "revoked" or bool(presented & revoked)
|
|
163
|
+
|
|
164
|
+
principal: Any
|
|
165
|
+
if signature_ok and not revoked_key:
|
|
166
|
+
principal = await self._binder.bind(record.get("principal_assertion"), agent.name)
|
|
167
|
+
else:
|
|
168
|
+
principal = Unbindable("not evaluated")
|
|
169
|
+
|
|
170
|
+
latest = await manifests_repo.get_latest(db, agent.id)
|
|
171
|
+
manifest_reconciled = latest is not None and latest.status == "reconciled"
|
|
172
|
+
|
|
173
|
+
outcome = decide(
|
|
174
|
+
signature_ok=signature_ok,
|
|
175
|
+
revoked_key=revoked_key,
|
|
176
|
+
principal=principal,
|
|
177
|
+
manifest_reconciled=manifest_reconciled,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
if outcome is EnrollDecision.REJECTED_SIGNATURE:
|
|
181
|
+
metrics.enrollments.labels(outcome="rejected").inc()
|
|
182
|
+
raise UnauthorizedError("signed response does not verify against the presented keys")
|
|
183
|
+
if outcome is EnrollDecision.REJECTED_KEY_REVOKED:
|
|
184
|
+
metrics.enrollments.labels(outcome="key_revoked").inc()
|
|
185
|
+
raise KeyRevoked(
|
|
186
|
+
f"agent {agent.name} is revoked"
|
|
187
|
+
if agent.status == "revoked"
|
|
188
|
+
else "a presented key belongs to a revoked trust anchor and is never re-pinned"
|
|
189
|
+
)
|
|
190
|
+
if outcome is EnrollDecision.FAILED_IDP_UNREACHABLE:
|
|
191
|
+
metrics.enrollments.labels(outcome="idp_unavailable").inc()
|
|
192
|
+
raise IdpUnavailable(getattr(principal, "detail", "identity provider unreachable"))
|
|
193
|
+
if outcome is EnrollDecision.QUARANTINED:
|
|
194
|
+
reason = (
|
|
195
|
+
"PRINCIPAL_IDP_NOT_CONFIGURED"
|
|
196
|
+
if isinstance(principal, NotConfigured)
|
|
197
|
+
else "PRINCIPAL_UNBINDABLE"
|
|
198
|
+
)
|
|
199
|
+
detail = getattr(principal, "detail", None)
|
|
200
|
+
await agents_repo.set_status(
|
|
201
|
+
db,
|
|
202
|
+
agent,
|
|
203
|
+
status="quarantined",
|
|
204
|
+
principal_ref=None,
|
|
205
|
+
trust_anchor_version=None,
|
|
206
|
+
pending_identity=doc,
|
|
207
|
+
)
|
|
208
|
+
await db.commit()
|
|
209
|
+
await self._anchors.invalidate(agent.name)
|
|
210
|
+
metrics.enrollments.labels(outcome="quarantined").inc()
|
|
211
|
+
return EnrollOutcome(status="quarantined", reason=reason, detail=detail)
|
|
212
|
+
if outcome is EnrollDecision.REJECTED_MANIFEST:
|
|
213
|
+
metrics.enrollments.labels(outcome="reconciliation_rejected").inc()
|
|
214
|
+
diff: list[dict[str, Any]] = []
|
|
215
|
+
if latest is not None:
|
|
216
|
+
found = await reports_repo.get_latest_for_agent(db, agent.id)
|
|
217
|
+
if found is not None:
|
|
218
|
+
diff = found[0].diff
|
|
219
|
+
version_text = latest.version if latest else "?"
|
|
220
|
+
status_text = latest.status if latest else "missing"
|
|
221
|
+
raise ReconciliationRejected(
|
|
222
|
+
f"manifest version {version_text} has status {status_text}; "
|
|
223
|
+
"enrollment requires a reconciled manifest",
|
|
224
|
+
{"diff": diff},
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
# ENROLLED
|
|
228
|
+
assert isinstance(principal, Bound) and latest is not None
|
|
229
|
+
now = datetime.now(UTC)
|
|
230
|
+
await anchors_repo.revoke_current(
|
|
231
|
+
db, agent.id, at=now, reason="superseded by re-enrollment"
|
|
232
|
+
)
|
|
233
|
+
version = await anchors_repo.next_version(db, agent.id)
|
|
234
|
+
await anchors_repo.append(
|
|
235
|
+
db,
|
|
236
|
+
agent_id=agent.id,
|
|
237
|
+
version=version,
|
|
238
|
+
jwks=doc["jwks"],
|
|
239
|
+
key_thumbprints=sorted(presented),
|
|
240
|
+
principal_ref=principal.principal_ref,
|
|
241
|
+
manifest_version=latest.version,
|
|
242
|
+
)
|
|
243
|
+
await agents_repo.set_status(
|
|
244
|
+
db,
|
|
245
|
+
agent,
|
|
246
|
+
status="enrolled",
|
|
247
|
+
principal_ref=principal.principal_ref,
|
|
248
|
+
trust_anchor_version=version,
|
|
249
|
+
pending_identity=None,
|
|
250
|
+
)
|
|
251
|
+
await db.commit()
|
|
252
|
+
await self._anchors.invalidate(agent.name)
|
|
253
|
+
metrics.enrollments.labels(outcome="enrolled").inc()
|
|
254
|
+
return EnrollOutcome(
|
|
255
|
+
status="enrolled", trust_anchor_version=version, principal_ref=principal.principal_ref
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
# -- helpers -------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
async def _consume_challenge(
|
|
261
|
+
self, redis: Redis | None, challenge_id: uuid.UUID
|
|
262
|
+
) -> dict[str, Any] | None:
|
|
263
|
+
if redis is None:
|
|
264
|
+
raise ChallengeStoreUnavailable("no challenge store configured")
|
|
265
|
+
try:
|
|
266
|
+
raw = await redis.getdel(challenge_key(challenge_id))
|
|
267
|
+
except Exception as exc:
|
|
268
|
+
raise ChallengeStoreUnavailable(f"challenge store unreachable: {exc}") from exc
|
|
269
|
+
if raw is None:
|
|
270
|
+
return None
|
|
271
|
+
try:
|
|
272
|
+
data = json.loads(raw)
|
|
273
|
+
return data if isinstance(data, dict) else None
|
|
274
|
+
except ValueError:
|
|
275
|
+
return None
|
|
276
|
+
|
|
277
|
+
@staticmethod
|
|
278
|
+
def _verify_response(
|
|
279
|
+
signed: str, keys: list[dict[str, Any]], nonce: str, agent_name: str
|
|
280
|
+
) -> bool:
|
|
281
|
+
try:
|
|
282
|
+
header = jwt.get_unverified_header(signed)
|
|
283
|
+
except jwt.PyJWTError:
|
|
284
|
+
return False
|
|
285
|
+
if header.get("alg") != "EdDSA":
|
|
286
|
+
return False
|
|
287
|
+
key_entry = next((k for k in keys if k.get("kid") == header.get("kid")), None)
|
|
288
|
+
if key_entry is None:
|
|
289
|
+
return False # a kid the document does not present proves nothing
|
|
290
|
+
try:
|
|
291
|
+
public = jwt.PyJWK(dict(key_entry), algorithm="EdDSA").key
|
|
292
|
+
claims = jwt.decode(
|
|
293
|
+
signed,
|
|
294
|
+
public,
|
|
295
|
+
algorithms=["EdDSA"],
|
|
296
|
+
audience=get_settings().issuer,
|
|
297
|
+
options={"require": ["exp", "iat", "sub", "aud", "nonce"]},
|
|
298
|
+
leeway=5,
|
|
299
|
+
)
|
|
300
|
+
except jwt.PyJWTError:
|
|
301
|
+
return False
|
|
302
|
+
expected = f"{AGENT_PREFIX}{agent_name}"
|
|
303
|
+
if claims.get("sub") != expected or claims.get("iss") != expected:
|
|
304
|
+
return False
|
|
305
|
+
if claims.get("nonce") != nonce:
|
|
306
|
+
return False
|
|
307
|
+
return int(claims["exp"]) - int(claims["iat"]) <= RESPONSE_MAX_LIFETIME
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
__all__ = ["ChallengeStoreUnavailable", "EnrollmentService", "challenge_key"]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The enrollment decision — pure.
|
|
2
|
+
|
|
3
|
+
Given what the service established (did the signature verify, is any presented key on a
|
|
4
|
+
revoked anchor, what did principal binding say, is the manifest reconciled), decide one of
|
|
5
|
+
five outcomes, in a fixed order. No I/O, no exceptions: every row of the contract's table
|
|
6
|
+
is a branch here, and ``tests/unit/test_enrollment_rules.py`` is that table.
|
|
7
|
+
|
|
8
|
+
The order matters. A bad signature is refused before anything is looked up. A revoked key
|
|
9
|
+
is refused before binding, so a revoked agent cannot even be quarantined back into
|
|
10
|
+
inspection. An unreachable IdP is a retry, never a quarantine. Reconciliation is checked
|
|
11
|
+
last, so its diff reaches an agent whose identity is otherwise in order.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from enum import StrEnum
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Bound:
|
|
22
|
+
principal_ref: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Unbindable:
|
|
27
|
+
detail: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Unreachable:
|
|
32
|
+
detail: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class NotConfigured:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
PrincipalResult = Bound | Unbindable | Unreachable | NotConfigured
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class EnrollDecision(StrEnum):
|
|
44
|
+
ENROLLED = "enrolled"
|
|
45
|
+
QUARANTINED = "quarantined"
|
|
46
|
+
REJECTED_SIGNATURE = "rejected_signature"
|
|
47
|
+
REJECTED_KEY_REVOKED = "rejected_key_revoked"
|
|
48
|
+
FAILED_IDP_UNREACHABLE = "failed_idp_unreachable"
|
|
49
|
+
REJECTED_MANIFEST = "rejected_manifest"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def decide(
|
|
53
|
+
*,
|
|
54
|
+
signature_ok: bool,
|
|
55
|
+
revoked_key: bool,
|
|
56
|
+
principal: PrincipalResult,
|
|
57
|
+
manifest_reconciled: bool,
|
|
58
|
+
) -> EnrollDecision:
|
|
59
|
+
if not signature_ok:
|
|
60
|
+
return EnrollDecision.REJECTED_SIGNATURE
|
|
61
|
+
if revoked_key:
|
|
62
|
+
return EnrollDecision.REJECTED_KEY_REVOKED
|
|
63
|
+
if isinstance(principal, Unreachable):
|
|
64
|
+
return EnrollDecision.FAILED_IDP_UNREACHABLE
|
|
65
|
+
if isinstance(principal, Unbindable | NotConfigured):
|
|
66
|
+
return EnrollDecision.QUARANTINED
|
|
67
|
+
if not manifest_reconciled:
|
|
68
|
+
return EnrollDecision.REJECTED_MANIFEST
|
|
69
|
+
return EnrollDecision.ENROLLED
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
__all__ = [
|
|
73
|
+
"Bound",
|
|
74
|
+
"EnrollDecision",
|
|
75
|
+
"NotConfigured",
|
|
76
|
+
"PrincipalResult",
|
|
77
|
+
"Unbindable",
|
|
78
|
+
"Unreachable",
|
|
79
|
+
"decide",
|
|
80
|
+
]
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Orchestrates validate → reconcile → persist → compile in one transaction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from redis.asyncio import Redis
|
|
9
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
10
|
+
|
|
11
|
+
from agentic_auth.errors import ManifestValidationError, NotFoundError
|
|
12
|
+
from agentic_auth.repositories import agents as agents_repo
|
|
13
|
+
from agentic_auth.repositories import compiled_policies as policies_repo
|
|
14
|
+
from agentic_auth.repositories import manifests as manifests_repo
|
|
15
|
+
from agentic_auth.repositories import reconciliation_reports as reports_repo
|
|
16
|
+
from agentic_auth.schemas.agent import OverrideDecl
|
|
17
|
+
from agentic_auth.schemas.manifest import AgentManifest
|
|
18
|
+
from agentic_auth.services import catalog_service
|
|
19
|
+
from agentic_auth.services.dag_compiler import DagCompiler
|
|
20
|
+
from agentic_auth.services.discovery import DiscoveryClient
|
|
21
|
+
from agentic_auth.services.reconciler import ReconcilerService
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class ProcessOutcome:
|
|
26
|
+
agent_id: uuid.UUID
|
|
27
|
+
agent_name: str
|
|
28
|
+
version: int
|
|
29
|
+
status: str # reconciled | needs_review | rejected
|
|
30
|
+
discovery_ok: bool
|
|
31
|
+
diff: list[dict]
|
|
32
|
+
http_status: int # 201 | 409 | 422
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ManifestService:
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
*,
|
|
39
|
+
discovery: DiscoveryClient,
|
|
40
|
+
reconciler: ReconcilerService | None = None,
|
|
41
|
+
compiler: DagCompiler | None = None,
|
|
42
|
+
) -> None:
|
|
43
|
+
self._discovery = discovery
|
|
44
|
+
self._reconciler = reconciler or ReconcilerService()
|
|
45
|
+
self._compiler = compiler or DagCompiler()
|
|
46
|
+
|
|
47
|
+
async def register_agent(
|
|
48
|
+
self,
|
|
49
|
+
session: AsyncSession,
|
|
50
|
+
redis: Redis,
|
|
51
|
+
*,
|
|
52
|
+
name: str,
|
|
53
|
+
manifest: AgentManifest,
|
|
54
|
+
attested_by: str,
|
|
55
|
+
override: OverrideDecl | None,
|
|
56
|
+
) -> ProcessOutcome:
|
|
57
|
+
if manifest.metadata.agent != name:
|
|
58
|
+
raise ManifestValidationError(
|
|
59
|
+
"metadata.agent must match the registered agent name",
|
|
60
|
+
{"fields": [{"loc": ["manifest", "metadata", "agent"], "msg": "name mismatch"}]},
|
|
61
|
+
)
|
|
62
|
+
agent = await agents_repo.create(session, name)
|
|
63
|
+
return await self._process(session, redis, agent.id, name, manifest, attested_by, override)
|
|
64
|
+
|
|
65
|
+
async def submit_manifest(
|
|
66
|
+
self,
|
|
67
|
+
session: AsyncSession,
|
|
68
|
+
redis: Redis,
|
|
69
|
+
*,
|
|
70
|
+
agent_name: str,
|
|
71
|
+
manifest: AgentManifest,
|
|
72
|
+
attested_by: str,
|
|
73
|
+
override: OverrideDecl | None,
|
|
74
|
+
) -> ProcessOutcome:
|
|
75
|
+
agent = await agents_repo.get_by_name(session, agent_name)
|
|
76
|
+
if agent is None:
|
|
77
|
+
raise NotFoundError(f"agent {agent_name!r} is not registered")
|
|
78
|
+
if manifest.metadata.agent != agent_name:
|
|
79
|
+
raise ManifestValidationError(
|
|
80
|
+
"manifest.metadata.agent must match the target agent",
|
|
81
|
+
{"fields": [{"loc": ["manifest", "metadata", "agent"], "msg": "name mismatch"}]},
|
|
82
|
+
)
|
|
83
|
+
return await self._process(
|
|
84
|
+
session, redis, agent.id, agent_name, manifest, attested_by, override
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
async def _process(
|
|
88
|
+
self,
|
|
89
|
+
session: AsyncSession,
|
|
90
|
+
redis: Redis,
|
|
91
|
+
agent_id: uuid.UUID,
|
|
92
|
+
agent_name: str,
|
|
93
|
+
manifest: AgentManifest,
|
|
94
|
+
attested_by: str,
|
|
95
|
+
override: OverrideDecl | None,
|
|
96
|
+
) -> ProcessOutcome:
|
|
97
|
+
try:
|
|
98
|
+
manifest.ensure_create_form()
|
|
99
|
+
except ValueError as exc:
|
|
100
|
+
raise ManifestValidationError(
|
|
101
|
+
str(exc),
|
|
102
|
+
{"fields": [{"loc": ["manifest", "metadata", "version"], "msg": str(exc)}]},
|
|
103
|
+
) from exc
|
|
104
|
+
|
|
105
|
+
discovered = await self._discovery.discover(self._reconciler.authorities(manifest))
|
|
106
|
+
outcome = self._reconciler.reconcile(manifest, discovered)
|
|
107
|
+
|
|
108
|
+
status = outcome.status
|
|
109
|
+
override_reason: str | None = None
|
|
110
|
+
http_status = 201
|
|
111
|
+
|
|
112
|
+
if status == "rejected":
|
|
113
|
+
http_status = 422
|
|
114
|
+
elif status == "needs_review":
|
|
115
|
+
if override is not None:
|
|
116
|
+
override_reason = override.validated_reason()
|
|
117
|
+
status = "reconciled"
|
|
118
|
+
else:
|
|
119
|
+
http_status = 409
|
|
120
|
+
|
|
121
|
+
manifest_row = await manifests_repo.append_version(
|
|
122
|
+
session,
|
|
123
|
+
agent_id=agent_id,
|
|
124
|
+
doc=manifest.canonical_doc(),
|
|
125
|
+
status=status,
|
|
126
|
+
attested_by=attested_by,
|
|
127
|
+
override_reason=override_reason,
|
|
128
|
+
)
|
|
129
|
+
await reports_repo.create(
|
|
130
|
+
session,
|
|
131
|
+
manifest_id=manifest_row.id,
|
|
132
|
+
diff=[d.model_dump(mode="json") for d in outcome.diff],
|
|
133
|
+
discovery_ok=outcome.discovery_ok,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
if status == "reconciled":
|
|
137
|
+
await self._recompile(session, redis, agent_name)
|
|
138
|
+
|
|
139
|
+
return ProcessOutcome(
|
|
140
|
+
agent_id=agent_id,
|
|
141
|
+
agent_name=agent_name,
|
|
142
|
+
version=manifest_row.version,
|
|
143
|
+
status=status,
|
|
144
|
+
discovery_ok=outcome.discovery_ok,
|
|
145
|
+
diff=[d.model_dump(mode="json") for d in outcome.diff],
|
|
146
|
+
http_status=http_status,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
async def _recompile(self, session: AsyncSession, redis: Redis, changed_agent: str) -> None:
|
|
150
|
+
reconciled = await manifests_repo.all_reconciled(session)
|
|
151
|
+
manifests = {
|
|
152
|
+
m.doc["metadata"]["agent"]: AgentManifest.model_validate(m.doc) for m in reconciled
|
|
153
|
+
}
|
|
154
|
+
manifest_id_by_agent = {m.doc["metadata"]["agent"]: m.id for m in reconciled}
|
|
155
|
+
compiled = self._compiler.compile(manifests) # raises DagCycleError -> route rollback
|
|
156
|
+
|
|
157
|
+
for scope, cs in compiled.items():
|
|
158
|
+
if changed_agent not in cs.source_agents:
|
|
159
|
+
continue
|
|
160
|
+
source_ids = [
|
|
161
|
+
manifest_id_by_agent[a] for a in cs.source_agents if a in manifest_id_by_agent
|
|
162
|
+
]
|
|
163
|
+
row = await policies_repo.append_version(
|
|
164
|
+
session, scope=scope, dag=cs.to_dag(), source_manifest_ids=source_ids
|
|
165
|
+
)
|
|
166
|
+
await catalog_service.warm(redis, scope, row.version, row.dag)
|