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.
Files changed (148) hide show
  1. agentic_auth/__init__.py +8 -0
  2. agentic_auth/_extras.py +24 -0
  3. agentic_auth/api/__init__.py +0 -0
  4. agentic_auth/api/deps.py +112 -0
  5. agentic_auth/api/errors.py +51 -0
  6. agentic_auth/api/responses.py +38 -0
  7. agentic_auth/api/service_deps.py +113 -0
  8. agentic_auth/api/v1/__init__.py +0 -0
  9. agentic_auth/api/v1/agents.py +88 -0
  10. agentic_auth/api/v1/audit.py +67 -0
  11. agentic_auth/api/v1/authorize.py +439 -0
  12. agentic_auth/api/v1/consent.py +21 -0
  13. agentic_auth/api/v1/decisions.py +43 -0
  14. agentic_auth/api/v1/enrollment.py +48 -0
  15. agentic_auth/api/v1/identity.py +97 -0
  16. agentic_auth/api/v1/jwks.py +21 -0
  17. agentic_auth/api/v1/manifests.py +68 -0
  18. agentic_auth/api/v1/scopes.py +22 -0
  19. agentic_auth/api/v1/token.py +203 -0
  20. agentic_auth/api/v1/transaction.py +94 -0
  21. agentic_auth/boundary/__init__.py +26 -0
  22. agentic_auth/boundary/guarantee.py +96 -0
  23. agentic_auth/cli/__init__.py +27 -0
  24. agentic_auth/cli/audit.py +130 -0
  25. agentic_auth/cli/drift.py +164 -0
  26. agentic_auth/cli/drift_render.py +148 -0
  27. agentic_auth/cli/identity.py +63 -0
  28. agentic_auth/cli/manifest.py +275 -0
  29. agentic_auth/config.py +182 -0
  30. agentic_auth/db.py +49 -0
  31. agentic_auth/embedded/__init__.py +427 -0
  32. agentic_auth/embedded/_schema.py +8 -0
  33. agentic_auth/embedded/_transport.py +39 -0
  34. agentic_auth/embedded/capabilities.py +34 -0
  35. agentic_auth/embedded/export.py +86 -0
  36. agentic_auth/embedded/idp.py +78 -0
  37. agentic_auth/embedded/store.py +240 -0
  38. agentic_auth/errors.py +145 -0
  39. agentic_auth/main.py +141 -0
  40. agentic_auth/models/__init__.py +70 -0
  41. agentic_auth/models/agent.py +58 -0
  42. agentic_auth/models/audit_decision.py +199 -0
  43. agentic_auth/models/compiled_policy.py +28 -0
  44. agentic_auth/models/manifest.py +96 -0
  45. agentic_auth/models/reconciliation_report.py +27 -0
  46. agentic_auth/models/sandbox_run.py +93 -0
  47. agentic_auth/models/session.py +63 -0
  48. agentic_auth/models/step_up_grant.py +106 -0
  49. agentic_auth/models/transaction_token.py +73 -0
  50. agentic_auth/models/trust_anchor.py +59 -0
  51. agentic_auth/models/types.py +95 -0
  52. agentic_auth/observability/__init__.py +370 -0
  53. agentic_auth/observability/config.py +137 -0
  54. agentic_auth/observability/context.py +128 -0
  55. agentic_auth/observability/ids.py +122 -0
  56. agentic_auth/observability/logs.py +191 -0
  57. agentic_auth/observability/pep.py +169 -0
  58. agentic_auth/observability/spans.py +225 -0
  59. agentic_auth/observability/surface.py +286 -0
  60. agentic_auth/observability/tracing.py +167 -0
  61. agentic_auth/redis.py +27 -0
  62. agentic_auth/repositories/__init__.py +0 -0
  63. agentic_auth/repositories/agents.py +96 -0
  64. agentic_auth/repositories/audit_decisions.py +152 -0
  65. agentic_auth/repositories/compiled_policies.py +72 -0
  66. agentic_auth/repositories/manifests.py +149 -0
  67. agentic_auth/repositories/reconciliation_reports.py +40 -0
  68. agentic_auth/repositories/sessions.py +41 -0
  69. agentic_auth/repositories/transaction_tokens.py +60 -0
  70. agentic_auth/repositories/trust_anchors.py +150 -0
  71. agentic_auth/runtime.py +81 -0
  72. agentic_auth/schemas/__init__.py +0 -0
  73. agentic_auth/schemas/agent.py +58 -0
  74. agentic_auth/schemas/audit.py +207 -0
  75. agentic_auth/schemas/authorize.py +205 -0
  76. agentic_auth/schemas/common.py +40 -0
  77. agentic_auth/schemas/consent.py +74 -0
  78. agentic_auth/schemas/dag.py +39 -0
  79. agentic_auth/schemas/edge_trace.py +166 -0
  80. agentic_auth/schemas/identity.py +152 -0
  81. agentic_auth/schemas/manifest.py +117 -0
  82. agentic_auth/schemas/manifest_api.py +38 -0
  83. agentic_auth/schemas/reconciliation.py +49 -0
  84. agentic_auth/schemas/token.py +122 -0
  85. agentic_auth/schemas/transaction.py +28 -0
  86. agentic_auth/sdk/__init__.py +114 -0
  87. agentic_auth/sdk/client.py +677 -0
  88. agentic_auth/sdk/context.py +95 -0
  89. agentic_auth/sdk/drift.py +118 -0
  90. agentic_auth/sdk/errors.py +147 -0
  91. agentic_auth/sdk/identity.py +162 -0
  92. agentic_auth/sdk/planes.py +362 -0
  93. agentic_auth/sdk/provenance.py +63 -0
  94. agentic_auth/services/__init__.py +0 -0
  95. agentic_auth/services/anchors.py +81 -0
  96. agentic_auth/services/audit.py +222 -0
  97. agentic_auth/services/audit_chain.py +144 -0
  98. agentic_auth/services/audit_cursor.py +55 -0
  99. agentic_auth/services/catalog_service.py +58 -0
  100. agentic_auth/services/chain_query.py +152 -0
  101. agentic_auth/services/dag_compiler.py +199 -0
  102. agentic_auth/services/decision_cache.py +123 -0
  103. agentic_auth/services/decision_history.py +71 -0
  104. agentic_auth/services/discovery.py +95 -0
  105. agentic_auth/services/drift.py +330 -0
  106. agentic_auth/services/edge_rules.py +62 -0
  107. agentic_auth/services/edge_trace.py +198 -0
  108. agentic_auth/services/enrollment.py +310 -0
  109. agentic_auth/services/enrollment_rules.py +80 -0
  110. agentic_auth/services/manifest_service.py +166 -0
  111. agentic_auth/services/metrics.py +419 -0
  112. agentic_auth/services/pdp.py +312 -0
  113. agentic_auth/services/policy_loader.py +255 -0
  114. agentic_auth/services/principal.py +143 -0
  115. agentic_auth/services/reconciler.py +119 -0
  116. agentic_auth/services/revocation.py +149 -0
  117. agentic_auth/services/sessions.py +231 -0
  118. agentic_auth/services/taint.py +204 -0
  119. agentic_auth/services/tokens/__init__.py +11 -0
  120. agentic_auth/services/tokens/act_chain.py +76 -0
  121. agentic_auth/services/tokens/exchange.py +319 -0
  122. agentic_auth/services/tokens/jwt_profile.py +362 -0
  123. agentic_auth/services/tokens/keys.py +117 -0
  124. agentic_auth/services/tokens/profile.py +167 -0
  125. agentic_auth/services/tokens/replay.py +53 -0
  126. agentic_auth/services/transactions.py +172 -0
  127. agentic_auth/sidecar/__init__.py +7 -0
  128. agentic_auth/sidecar/__main__.py +66 -0
  129. agentic_auth/sidecar/app.py +349 -0
  130. agentic_auth/sidecar/config.py +253 -0
  131. agentic_auth/sidecar/deny.py +108 -0
  132. agentic_auth/sidecar/enforce.py +640 -0
  133. agentic_auth/sidecar/identity.py +37 -0
  134. agentic_auth/verify/__init__.py +208 -0
  135. agentic_auth/verify/admit.py +131 -0
  136. agentic_auth/verify/anchors.py +250 -0
  137. agentic_auth/verify/canonical.py +228 -0
  138. agentic_auth/verify/grants.py +158 -0
  139. agentic_auth/verify/identity.py +111 -0
  140. agentic_auth/verify/replay.py +67 -0
  141. agentic_auth/verify/transaction.py +164 -0
  142. authzai-0.2.0.dist-info/METADATA +276 -0
  143. authzai-0.2.0.dist-info/RECORD +148 -0
  144. authzai-0.2.0.dist-info/WHEEL +5 -0
  145. authzai-0.2.0.dist-info/entry_points.txt +5 -0
  146. authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
  147. authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
  148. authzai-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,143 @@
1
+ """Principal binding: is this agent acting for an accountable human or organization?
2
+
3
+ The agent presents an OIDC ID token from the organization's human IdP. The control plane
4
+ verifies it against the IdP's JWKS and requires the binding claim to name this agent.
5
+ Three outcomes are distinct on purpose:
6
+
7
+ - ``Bound``: the assertion verifies and names this agent.
8
+ - ``Unbindable``: no assertion, or one that does not verify or names another agent. This
9
+ is quarantine — a fact about the agent.
10
+ - ``Unreachable``: the IdP could not be consulted. This is a retryable failure — a fact about
11
+ the network — and must never become a quarantine.
12
+
13
+ The IdP's JWKS is fetched over ``httpx`` through a module-level factory so tests can route
14
+ it to an in-process fake; PyJWT's ``PyJWK`` loads the OKP/EC/RSA key it names.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ from collections.abc import Callable
21
+ from typing import Any
22
+
23
+ import httpx
24
+ import jwt
25
+
26
+ from agentic_auth import runtime
27
+ from agentic_auth.config import Settings, get_settings
28
+ from agentic_auth.services.enrollment_rules import (
29
+ Bound,
30
+ NotConfigured,
31
+ PrincipalResult,
32
+ Unbindable,
33
+ Unreachable,
34
+ )
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ AGENT_PREFIX = "agent://"
39
+
40
+
41
+ class _IdpUnreachable(Exception):
42
+ """Internal: the JWKS fetch failed. ``bind`` turns it into ``Unreachable``."""
43
+
44
+
45
+ def _default_client() -> httpx.AsyncClient:
46
+ return httpx.AsyncClient(timeout=httpx.Timeout(5.0))
47
+
48
+
49
+ # Replaced by tests with a client routed to the fake IdP.
50
+ jwks_http_client: Callable[[], httpx.AsyncClient] = _default_client
51
+
52
+
53
+ class PrincipalBinder:
54
+ def __init__(self, settings: Settings | None = None) -> None:
55
+ self._settings = settings or get_settings()
56
+
57
+ @property
58
+ def configured(self) -> bool:
59
+ s = self._settings
60
+ return bool(
61
+ s.principal_idp_issuer and s.principal_idp_jwks_url and s.principal_idp_audience
62
+ )
63
+
64
+ async def bind(self, assertion: str | None, agent_name: str) -> PrincipalResult:
65
+ if not self.configured:
66
+ return NotConfigured()
67
+ if not assertion:
68
+ return Unbindable("no principal assertion presented")
69
+
70
+ try:
71
+ header = jwt.get_unverified_header(assertion)
72
+ except jwt.PyJWTError as exc:
73
+ return Unbindable(f"assertion is not a JWT: {exc}")
74
+ kid = header.get("kid")
75
+
76
+ try:
77
+ jwks = await self._fetch_jwks()
78
+ except _IdpUnreachable as exc:
79
+ logger.warning("principal identity provider unreachable: %s", exc)
80
+ return Unreachable(str(exc))
81
+
82
+ key = _key_for(jwks, kid)
83
+ if key is None:
84
+ return Unbindable(f"assertion kid {kid!r} is not in the identity provider's JWKS")
85
+
86
+ s = self._settings
87
+ try:
88
+ claims: dict[str, Any] = jwt.decode(
89
+ assertion,
90
+ key,
91
+ algorithms=[header.get("alg", "EdDSA")],
92
+ issuer=s.principal_idp_issuer,
93
+ audience=s.principal_idp_audience,
94
+ options={"require": ["exp", "iat", "sub", "iss", "aud"]},
95
+ )
96
+ except jwt.PyJWTError as exc:
97
+ return Unbindable(f"assertion did not verify: {exc}")
98
+
99
+ bound_agent = claims.get(s.principal_binding_claim)
100
+ expected = f"{AGENT_PREFIX}{agent_name}"
101
+ if bound_agent != expected:
102
+ return Unbindable(
103
+ f"assertion names {bound_agent!r}, not {expected!r} "
104
+ f"(claim {s.principal_binding_claim!r})"
105
+ )
106
+ return Bound(f"{claims['iss']}#{claims['sub']}")
107
+
108
+ async def _fetch_jwks(self) -> dict[str, Any]:
109
+ # An embedded instance reaches its own identity provider through its own transport,
110
+ # whatever this module's hook has been pointed at for the rest of the process.
111
+ current = runtime.override()
112
+ client = current.http if current is not None else jwks_http_client()
113
+ try:
114
+ response = await client.get(self._settings.principal_idp_jwks_url)
115
+ except httpx.HTTPError as exc:
116
+ raise _IdpUnreachable(f"could not fetch JWKS: {type(exc).__name__}") from exc
117
+ if response.status_code >= 500:
118
+ raise _IdpUnreachable(f"identity provider returned {response.status_code}")
119
+ if response.status_code != 200:
120
+ # A 4xx is the IdP telling us the URL is wrong: a configuration fact, so a
121
+ # deployment notices, but not something a retry fixes. Treated as unreachable
122
+ # because enrolling nobody is safer than quarantining everybody.
123
+ raise _IdpUnreachable(f"identity provider returned {response.status_code}")
124
+ try:
125
+ body = response.json()
126
+ except ValueError as exc:
127
+ raise _IdpUnreachable("identity provider JWKS is not JSON") from exc
128
+ if not isinstance(body, dict) or not isinstance(body.get("keys"), list):
129
+ raise _IdpUnreachable("identity provider JWKS is malformed")
130
+ return body
131
+
132
+
133
+ def _key_for(jwks: dict[str, Any], kid: str | None) -> Any:
134
+ for entry in jwks.get("keys", []):
135
+ if entry.get("kid") == kid:
136
+ try:
137
+ return jwt.PyJWK(dict(entry)).key
138
+ except jwt.PyJWTError:
139
+ return None
140
+ return None
141
+
142
+
143
+ __all__ = ["PrincipalBinder", "jwks_http_client"]
@@ -0,0 +1,119 @@
1
+ """Reconcile a declared manifest against discovered capabilities.
2
+
3
+ Output: a terminal status (``reconciled`` | ``needs_review`` | ``rejected``) plus a
4
+ 100%-actionable diff — every entry names the exact offending tool ref, the field, the
5
+ declared vs discovered value, a machine code, and a concrete remedy.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+ from agentic_auth.schemas.manifest import AgentManifest, ToolDecl
13
+ from agentic_auth.schemas.reconciliation import HARD_CODES, DiffCode, DiffEntry
14
+ from agentic_auth.services.discovery import DiscoveryResult, authority_for, tool_name
15
+
16
+
17
+ @dataclass
18
+ class ReconcileOutcome:
19
+ status: str # reconciled | needs_review | rejected
20
+ diff: list[DiffEntry]
21
+ discovery_ok: bool
22
+
23
+
24
+ def _entry(
25
+ tool: ToolDecl, field: str, declared: object, discovered: object, code: DiffCode, remedy: str
26
+ ) -> DiffEntry:
27
+ return DiffEntry(
28
+ tool_ref=tool.ref,
29
+ field=field,
30
+ declared=declared,
31
+ discovered=discovered,
32
+ code=code,
33
+ remedy=remedy,
34
+ )
35
+
36
+
37
+ class ReconcilerService:
38
+ def authorities(self, manifest: AgentManifest) -> set[str]:
39
+ return {authority_for(t.ref) for t in manifest.spec.tools}
40
+
41
+ def reconcile(
42
+ self, manifest: AgentManifest, discovered: dict[str, DiscoveryResult]
43
+ ) -> ReconcileOutcome:
44
+ diff: list[DiffEntry] = []
45
+ discovery_ok = True
46
+
47
+ for tool in manifest.spec.tools:
48
+ authority = authority_for(tool.ref)
49
+ result = discovered.get(authority)
50
+
51
+ if result is None or not result.ok or result.resource is None:
52
+ discovery_ok = False
53
+ reason = result.error if result else "not attempted"
54
+ diff.append(
55
+ _entry(
56
+ tool,
57
+ "ref",
58
+ tool.ref,
59
+ None,
60
+ DiffCode.DISCOVERY_UNAVAILABLE,
61
+ f"capability source {authority} is unreachable ({reason}); "
62
+ f"retry once it is up or submit an admin override with a recorded reason",
63
+ )
64
+ )
65
+ continue
66
+
67
+ resource = result.resource
68
+ name = tool_name(tool.ref)
69
+ advertised = resource.tools.get(name)
70
+
71
+ if advertised is None:
72
+ diff.append(
73
+ _entry(
74
+ tool,
75
+ "ref",
76
+ tool.ref,
77
+ sorted(resource.tools),
78
+ DiffCode.UNKNOWN_TOOL,
79
+ f"tool {name!r} is not advertised by {authority}; "
80
+ f"remove it or point `ref` at an advertised tool",
81
+ )
82
+ )
83
+ continue
84
+
85
+ allowed = set(advertised.data_classes)
86
+ for dc in tool.data_classes:
87
+ if dc in allowed:
88
+ continue
89
+ diff.append(
90
+ _entry(
91
+ tool,
92
+ "data_classes",
93
+ sorted(tool.data_classes),
94
+ sorted(allowed),
95
+ DiffCode.DECLARED_EXCEEDS_DISCOVERED,
96
+ f"remove data class {dc!r} from tool {tool.ref} or widen the "
97
+ f"manifest scope request — {authority} does not advertise it for "
98
+ f"tool {name!r}",
99
+ )
100
+ )
101
+
102
+ if tool.privileged != advertised.privileged and advertised.privileged:
103
+ diff.append(
104
+ _entry(
105
+ tool,
106
+ "privileged",
107
+ tool.privileged,
108
+ advertised.privileged,
109
+ DiffCode.DATA_CLASS_CONFLICT,
110
+ f"{authority} classifies tool {name!r} as privileged; "
111
+ f"set `privileged: true` on this tool",
112
+ )
113
+ )
114
+
115
+ if any(d.code in HARD_CODES for d in diff):
116
+ return ReconcileOutcome("rejected", diff, discovery_ok)
117
+ if not discovery_ok:
118
+ return ReconcileOutcome("needs_review", diff, discovery_ok)
119
+ return ReconcileOutcome("reconciled", diff, discovery_ok)
@@ -0,0 +1,149 @@
1
+ """Revocation: cut an agent off, and everything built on it.
2
+
3
+ One transaction flips the live anchor's ``revoked_at`` and the agent's status; then the
4
+ anchor cache entry is deleted and the name is added to the ``revoked_agents`` set that
5
+ ``decide()`` consults on every hop. The set is a cache of ``agents.status = 'revoked'``,
6
+ rebuilt at startup, so a flushed Redis can only make the control plane slower, never more
7
+ permissive: a miss falls back to the database.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import logging
14
+ import uuid
15
+ from datetime import UTC, datetime
16
+
17
+ from redis.asyncio import Redis
18
+ from sqlalchemy.ext.asyncio import AsyncSession
19
+
20
+ from agentic_auth.errors import NotEnrolled, NotFoundError
21
+ from agentic_auth.repositories import agents as agents_repo
22
+ from agentic_auth.repositories import trust_anchors as anchors_repo
23
+ from agentic_auth.schemas.identity import (
24
+ RevocationItem,
25
+ RevocationListRead,
26
+ RevocationPage,
27
+ RevokeOutcome,
28
+ )
29
+ from agentic_auth.services.anchors import AnchorCache
30
+ from agentic_auth.services.metrics import get_metrics
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ REVOKED_SET = "revoked_agents"
35
+ REVOKED_READY = "revoked_agents:ready"
36
+
37
+
38
+ class RevocationService:
39
+ def __init__(self, anchors: AnchorCache) -> None:
40
+ self._anchors = anchors
41
+
42
+ async def revoke(
43
+ self, db: AsyncSession, redis: Redis | None, agent_id: uuid.UUID, reason: str | None
44
+ ) -> RevokeOutcome:
45
+ agent = await agents_repo.get_by_id(db, agent_id)
46
+ if agent is None:
47
+ raise NotFoundError(f"agent {agent_id} not found")
48
+ current = await anchors_repo.current(db, agent.id)
49
+ if current is None:
50
+ raise NotEnrolled(f"agent {agent.name} has no trust anchor")
51
+
52
+ if agent.status == "revoked" and current.revoked_at is not None:
53
+ # Idempotent: the same body, no second write, no second count.
54
+ return RevokeOutcome(
55
+ status="revoked",
56
+ trust_anchor_version=current.version,
57
+ revoked_at=current.revoked_at,
58
+ )
59
+
60
+ now = datetime.now(UTC)
61
+ live = await anchors_repo.revoke_current(db, agent.id, at=now, reason=reason)
62
+ version = live.version if live is not None else current.version
63
+ await agents_repo.set_status(
64
+ db,
65
+ agent,
66
+ status="revoked",
67
+ principal_ref=agent.principal_ref,
68
+ trust_anchor_version=version,
69
+ pending_identity=None,
70
+ )
71
+ await db.commit()
72
+
73
+ await self._anchors.invalidate(agent.name)
74
+ await self._add_revoked(redis, agent.name)
75
+ get_metrics().revocations.inc()
76
+ return RevokeOutcome(status="revoked", trust_anchor_version=version, revoked_at=now)
77
+
78
+ # -- the revoked set -----------------------------------------------------------------
79
+
80
+ async def revoked_set(self, db: AsyncSession, redis: Redis | None) -> frozenset[str]:
81
+ """Every revoked agent name. Redis first; the database when Redis has no view."""
82
+ if redis is not None:
83
+ try:
84
+ # One round trip for both: this runs on every authorize and every exchange.
85
+ pipe = redis.pipeline(transaction=False)
86
+ pipe.get(REVOKED_READY)
87
+ pipe.smembers(REVOKED_SET)
88
+ ready, members = await pipe.execute()
89
+ if ready:
90
+ return frozenset(m.decode() if isinstance(m, bytes) else m for m in members)
91
+ except Exception:
92
+ logger.warning("revoked set unavailable in redis; reading the database")
93
+ names = await agents_repo.revoked_names(db)
94
+ await self._rebuild_into(redis, names)
95
+ return frozenset(names)
96
+
97
+ async def rebuild(self, db: AsyncSession, redis: Redis | None) -> None:
98
+ await self._rebuild_into(redis, await agents_repo.revoked_names(db))
99
+
100
+ async def _rebuild_into(self, redis: Redis | None, names: set[str]) -> None:
101
+ if redis is None:
102
+ return
103
+ with contextlib.suppress(Exception):
104
+ pipe = redis.pipeline(transaction=True)
105
+ pipe.delete(REVOKED_SET)
106
+ if names:
107
+ pipe.sadd(REVOKED_SET, *names)
108
+ pipe.set(REVOKED_READY, "1")
109
+ await pipe.execute()
110
+
111
+ async def _add_revoked(self, redis: Redis | None, name: str) -> None:
112
+ if redis is None:
113
+ return
114
+ with contextlib.suppress(Exception):
115
+ await redis.sadd(REVOKED_SET, name)
116
+
117
+ # -- the list -----------------------------------------------------------------------------
118
+
119
+ async def list(
120
+ self,
121
+ db: AsyncSession,
122
+ *,
123
+ since: datetime | None,
124
+ limit: int,
125
+ cursor: str | None,
126
+ ) -> RevocationListRead:
127
+ rows, next_cursor = await anchors_repo.list_revocations(
128
+ db, since=since, limit=limit, cursor=cursor
129
+ )
130
+ names: dict[uuid.UUID, str] = {}
131
+ for row in rows:
132
+ if row.agent_id not in names:
133
+ agent = await agents_repo.get_by_id(db, row.agent_id)
134
+ names[row.agent_id] = agent.name if agent is not None else str(row.agent_id)
135
+ return RevocationListRead(
136
+ as_of=datetime.now(UTC),
137
+ items=[
138
+ RevocationItem(
139
+ agent=names[row.agent_id],
140
+ trust_anchor_version=row.version,
141
+ revoked_at=row.revoked_at,
142
+ )
143
+ for row in rows
144
+ ],
145
+ page=RevocationPage(next_cursor=next_cursor, limit=limit),
146
+ )
147
+
148
+
149
+ __all__ = ["REVOKED_SET", "RevocationService"]
@@ -0,0 +1,231 @@
1
+ """Consent, policy-version pinning, and session reads.
2
+
3
+ A session is created once and never updated. Everything a decision needs is either in the
4
+ request, in the presented token, or in this immutable row — which is what lets the PDP
5
+ stay stateless and lets a session read be a pure cache-friendly lookup.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import uuid
13
+ from dataclasses import dataclass
14
+ from datetime import UTC, datetime, timedelta
15
+ from typing import Any
16
+
17
+ from redis.asyncio import Redis
18
+ from sqlalchemy.ext.asyncio import AsyncSession
19
+
20
+ from agentic_auth import runtime
21
+ from agentic_auth.config import get_settings
22
+ from agentic_auth.errors import (
23
+ NotFoundError,
24
+ QueryValidationError,
25
+ SessionExpired,
26
+ SessionSuperseded,
27
+ )
28
+ from agentic_auth.repositories import sessions as sessions_repo
29
+ from agentic_auth.schemas.consent import ConsentCreate, ConsentRead
30
+ from agentic_auth.services import policy_loader
31
+ from agentic_auth.services.policy_loader import PolicyIndex
32
+ from agentic_auth.services.tokens.profile import TokenProfile
33
+
34
+
35
+ def _key(session_id: str) -> str:
36
+ return f"session:{session_id}"
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class PinnedSession:
41
+ id: uuid.UUID
42
+ scope: str
43
+ user_sub: str
44
+ policy_version: int
45
+ hop_budget: int
46
+ created_at: datetime
47
+ expires_at: datetime
48
+ # Phase 5. The subset of the pinned policy's data classes this consent covers, or
49
+ # None for "everything the policy declares" — which is exactly Phase 2-4 semantics.
50
+ # Nothing reads it until the PDP split lands.
51
+ consented_data_classes: list[str] | None = None
52
+
53
+ def as_cache(self) -> str:
54
+ return json.dumps(
55
+ {
56
+ "id": str(self.id),
57
+ "scope": self.scope,
58
+ "user_sub": self.user_sub,
59
+ "policy_version": self.policy_version,
60
+ "hop_budget": self.hop_budget,
61
+ "created_at": self.created_at.isoformat(),
62
+ "expires_at": self.expires_at.isoformat(),
63
+ "consented_data_classes": self.consented_data_classes,
64
+ }
65
+ )
66
+
67
+ @classmethod
68
+ def from_cache(cls, raw: str | bytes) -> PinnedSession:
69
+ d = json.loads(raw)
70
+ return cls(
71
+ id=uuid.UUID(d["id"]),
72
+ scope=d["scope"],
73
+ user_sub=d["user_sub"],
74
+ policy_version=d["policy_version"],
75
+ hop_budget=d["hop_budget"],
76
+ created_at=datetime.fromisoformat(d["created_at"]),
77
+ expires_at=datetime.fromisoformat(d["expires_at"]),
78
+ # `.get`, not `[...]`: an entry cached before this field existed must still
79
+ # load, and its absence means exactly what None means.
80
+ consented_data_classes=d.get("consented_data_classes"),
81
+ )
82
+
83
+ @classmethod
84
+ def from_row(cls, row: Any) -> PinnedSession:
85
+ return cls(
86
+ id=row.id,
87
+ scope=row.scope,
88
+ user_sub=row.user_sub,
89
+ policy_version=row.policy_version,
90
+ hop_budget=row.hop_budget,
91
+ created_at=row.created_at,
92
+ expires_at=row.expires_at,
93
+ consented_data_classes=row.consented_data_classes,
94
+ )
95
+
96
+
97
+ class SessionService:
98
+ def __init__(self, tokens: TokenProfile, *, ttl_seconds: int | None = None) -> None:
99
+ self._tokens = tokens
100
+ self._ttl = ttl_seconds or get_settings().session_ttl_seconds
101
+
102
+ async def consent(
103
+ self, db: AsyncSession, redis: Redis | None, body: ConsentCreate
104
+ ) -> ConsentRead:
105
+ """Record consent and pin the policy version in effect at this moment.
106
+
107
+ Loading the policy here is not just a lookup — it is the gate that refuses a scope
108
+ whose compiled policy predates runtime enforcement, rather than pinning something
109
+ the PDP could not later decide against.
110
+ """
111
+ version = await policy_loader.latest_version(db, body.scope)
112
+ if version is None:
113
+ raise NotFoundError(f"no compiled policy for scope {body.scope!r}")
114
+
115
+ # Raises PolicyRecompileRequired for a v1 policy. Deliberately before the insert.
116
+ index = await policy_loader.load(db, redis, body.scope, version)
117
+
118
+ consented = self._validate_data_classes(index, body.data_classes)
119
+
120
+ now = datetime.now(UTC)
121
+ expires_at = now + timedelta(seconds=body.ttl_seconds or self._ttl)
122
+ row = await sessions_repo.create(
123
+ db,
124
+ scope=body.scope,
125
+ user_sub=body.user_sub,
126
+ policy_version=version,
127
+ # Copied at consent, so a later publish cannot widen a running session.
128
+ hop_budget=index.hop_budget,
129
+ expires_at=expires_at,
130
+ consented_data_classes=consented,
131
+ )
132
+ session = PinnedSession.from_row(row)
133
+ root_grant = self._tokens.mint_root_grant(
134
+ sub=body.user_sub,
135
+ scope=body.scope,
136
+ session_id=str(row.id),
137
+ policy_version=version,
138
+ )
139
+ await self._cache(redis, session)
140
+ return ConsentRead(
141
+ session_id=str(row.id),
142
+ root_grant=root_grant,
143
+ policy_version=version,
144
+ scope=body.scope,
145
+ user_sub=body.user_sub,
146
+ hop_budget=index.hop_budget,
147
+ expires_at=expires_at,
148
+ data_classes=consented,
149
+ )
150
+
151
+ @staticmethod
152
+ def _validate_data_classes(index: PolicyIndex, requested: list[str] | None) -> list[str] | None:
153
+ """Check a consented subset against the pinned policy, before the insert.
154
+
155
+ Validating here rather than at first use means a typo surfaces to the integrator
156
+ as a 422 on the consent call, instead of as a refusal three hops into a chain
157
+ where it reads like a policy bug.
158
+
159
+ Rejected outright when the feature is off, so a caller cannot believe it pinned a
160
+ narrower consent than it did — silently ignoring the field would be the same
161
+ class of error the guarantee level exists to prevent.
162
+ """
163
+ if requested is None:
164
+ return None
165
+ if not get_settings().consent_granularity_enabled:
166
+ raise QueryValidationError(
167
+ "data_classes requires consent granularity, which is disabled on this "
168
+ "deployment (AGENTIC_AUTH_CONSENT_GRANULARITY_ENABLED)",
169
+ [{"loc": ["body", "data_classes"], "msg": "feature disabled"}],
170
+ )
171
+
172
+ declared = {cls for classes in index.data_classes_by_agent.values() for cls in classes}
173
+ unknown = sorted(set(requested) - declared)
174
+ if unknown:
175
+ raise QueryValidationError(
176
+ f"data classes {unknown} are not declared by any agent in scope "
177
+ f"{index.scope!r} at policy version {index.version}",
178
+ [{"loc": ["body", "data_classes"], "msg": f"not declared: {unknown}"}],
179
+ )
180
+ # Deduplicated and ordered so the stored array, the cache and the read model
181
+ # cannot disagree about a set that was written twice.
182
+ return sorted(set(requested))
183
+
184
+ async def get(self, db: AsyncSession, redis: Redis | None, session_id: str) -> PinnedSession:
185
+ """Read-through by id. Raises ``SessionExpired`` past ``expires_at``.
186
+
187
+ Expiry is checked against this record, not against the token's ``exp``, so a
188
+ still-valid token inside a dead session is refused.
189
+ """
190
+ try:
191
+ sid = uuid.UUID(session_id)
192
+ except (ValueError, AttributeError, TypeError) as exc:
193
+ raise NotFoundError(f"unknown session {session_id!r}") from exc
194
+
195
+ session: PinnedSession | None = None
196
+ if redis is not None:
197
+ with contextlib.suppress(Exception):
198
+ cached = await redis.get(_key(session_id))
199
+ if cached is not None:
200
+ session = PinnedSession.from_cache(cached)
201
+
202
+ if session is None:
203
+ row = await sessions_repo.get(db, sid)
204
+ if row is None:
205
+ raise NotFoundError(f"unknown session {session_id!r}")
206
+ session = PinnedSession.from_row(row)
207
+ await self._cache(redis, session)
208
+
209
+ if session.expires_at <= datetime.now(UTC):
210
+ raise SessionExpired(
211
+ f"session {session_id} expired at {session.expires_at.isoformat()}"
212
+ )
213
+ current = runtime.override()
214
+ if (
215
+ current is not None
216
+ and current.superseded_before is not None
217
+ and session.created_at < current.superseded_before
218
+ ):
219
+ raise SessionSuperseded(
220
+ f"session {session_id} predates this embedded store's last open; consent again"
221
+ )
222
+ return session
223
+
224
+ async def _cache(self, redis: Redis | None, session: PinnedSession) -> None:
225
+ if redis is None:
226
+ return
227
+ ttl = int((session.expires_at - datetime.now(UTC)).total_seconds())
228
+ if ttl <= 0:
229
+ return
230
+ with contextlib.suppress(Exception):
231
+ await redis.set(_key(str(session.id)), session.as_cache(), ex=ttl)