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,222 @@
1
+ """Recording decisions — the audit write path.
2
+
3
+ Every decision passes through :meth:`AuditService.record`, and ``record`` **commits before it
4
+ returns**. That ordering is the guarantee, and it is deliberately not left to the request
5
+ session's teardown. On FastAPI 0.141 a ``yield`` dependency's exit code runs *after* the
6
+ response has been sent, so a commit placed
7
+ there lets an allow reach the sidecar before its row exists — and if that commit then fails,
8
+ the call has already left with no record.
9
+
10
+ A failure never raises out of here. It returns ``recorded=False`` and the caller decides
11
+ what that means: a call that would leave the host is refused (``AUDIT_UNAVAILABLE``), and a
12
+ deny stays a deny.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import logging
19
+ import uuid
20
+ from dataclasses import dataclass
21
+ from datetime import UTC, datetime
22
+ from typing import Any
23
+
24
+ from sqlalchemy import text
25
+ from sqlalchemy.ext.asyncio import AsyncSession
26
+
27
+ from agentic_auth import runtime
28
+ from agentic_auth.config import get_settings
29
+ from agentic_auth.models.audit_decision import AuditDecision, target_kind_of
30
+ from agentic_auth.observability import logs, surface
31
+ from agentic_auth.repositories import audit_decisions as audit_repo
32
+ from agentic_auth.services.audit_chain import ChainEntry, ChainResult, ParentSnapshot, extend_chain
33
+ from agentic_auth.services.metrics import get_metrics
34
+ from agentic_auth.services.pdp import Decision
35
+ from agentic_auth.services.tokens.profile import VerifiedToken
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class RecordResult:
42
+ """The action id when the row committed, ``None`` when it did not.
43
+
44
+ Holds the id rather than the ORM row on purpose: after a rollback the row is expired,
45
+ and touching it would try to lazy-load on an async session.
46
+ """
47
+
48
+ action_id: uuid.UUID | None
49
+ # The parent row's chain document, when one was loaded. Phase 4's taint propagation
50
+ # reads ancestor `subject_jti`s off it without a second query.
51
+ parent_chain: list[dict[str, Any]] | None = None
52
+
53
+ @property
54
+ def recorded(self) -> bool:
55
+ return self.action_id is not None
56
+
57
+
58
+ def _normalized_session_id(session_id: str) -> str:
59
+ try:
60
+ return str(uuid.UUID(session_id))
61
+ except (ValueError, TypeError, AttributeError):
62
+ return session_id
63
+
64
+
65
+ def _snapshot(row: AuditDecision) -> ParentSnapshot:
66
+ return ParentSnapshot(
67
+ action_id=str(row.id),
68
+ session_id=str(row.session_id),
69
+ hop=row.hop,
70
+ outcome=row.outcome,
71
+ target=row.target,
72
+ chain=row.chain,
73
+ chain_complete=row.chain_complete,
74
+ )
75
+
76
+
77
+ class AuditService:
78
+ def __init__(self, *, write_timeout_seconds: float | None = None) -> None:
79
+ seconds = (
80
+ write_timeout_seconds
81
+ if write_timeout_seconds is not None
82
+ else get_settings().audit_write_timeout_seconds
83
+ )
84
+ self._timeout_ms = max(1, int(seconds * 1000))
85
+
86
+ async def record(
87
+ self,
88
+ db: AsyncSession,
89
+ *,
90
+ session_id: str,
91
+ caller: str,
92
+ target: str,
93
+ data_class: str,
94
+ decision: Decision,
95
+ enforced: bool,
96
+ taint: str | None,
97
+ policy_version: int,
98
+ token: VerifiedToken,
99
+ taint_source: str | None = None,
100
+ privileged: bool = False,
101
+ guarantee_level: str | None = None,
102
+ step_up_ref: uuid.UUID | None = None,
103
+ ) -> RecordResult:
104
+ action_id = uuid.uuid4()
105
+ ts = datetime.now(UTC)
106
+ try:
107
+ # Bound the whole append. An allow whose record cannot land in time is refused,
108
+ # not dispatched while the write is still pending.
109
+ # PostgreSQL only. The embedded store (SQLite) has no statement timeout; its
110
+ # writes are serialised behind one lock with a busy timeout instead
111
+ # (agentic_auth/embedded/store.py).
112
+ if db.get_bind().dialect.name == "postgresql":
113
+ await db.execute(text(f"SET LOCAL statement_timeout = {self._timeout_ms}"))
114
+
115
+ parent: ParentSnapshot | None = None
116
+ if token.action_id is not None:
117
+ parent_row = await audit_repo.get(db, uuid.UUID(token.action_id))
118
+ parent = _snapshot(parent_row) if parent_row is not None else None
119
+
120
+ entry = ChainEntry(
121
+ hop=decision.hop,
122
+ action_id=str(action_id),
123
+ acting_agent=token.holder,
124
+ target=target,
125
+ target_kind=target_kind_of(target),
126
+ data_class=data_class,
127
+ decision=decision.outcome,
128
+ deny_reason=decision.reason.value if decision.reason else None,
129
+ enforced=enforced,
130
+ ts=ts.isoformat(),
131
+ subject_jti=token.jti,
132
+ taint=taint,
133
+ taint_source=taint_source,
134
+ privileged=privileged,
135
+ )
136
+ chain = extend_chain(
137
+ parent,
138
+ entry,
139
+ session_id=_normalized_session_id(session_id),
140
+ token_action_id=token.action_id,
141
+ token_next_hop=token.next_hop,
142
+ token_act_chain=token.act_chain,
143
+ )
144
+
145
+ await audit_repo.append(
146
+ db,
147
+ action_id=action_id,
148
+ ts=ts,
149
+ session_id=uuid.UUID(session_id),
150
+ caller=caller,
151
+ target=target,
152
+ data_class=data_class,
153
+ hop=decision.hop,
154
+ outcome=decision.outcome,
155
+ deny_reason=entry.deny_reason,
156
+ recoverable=decision.recoverable,
157
+ enforced=enforced,
158
+ taint=taint,
159
+ taint_source=taint_source,
160
+ privileged=privileged,
161
+ policy_version=policy_version,
162
+ act_chain=token.act_chain,
163
+ acting_agent=token.holder,
164
+ subject_jti=token.jti,
165
+ # Only a parent that exists can be referenced; a dangling id is recorded as
166
+ # PARENT_NOT_FOUND in `chain_break` instead.
167
+ parent_action_id=uuid.UUID(parent.action_id) if parent is not None else None,
168
+ chain=chain.chain,
169
+ chain_complete=chain.complete,
170
+ chain_break=chain.break_reason.value if chain.break_reason else None,
171
+ # Phase 5. Reported by the enforcement point; recorded verbatim so the row
172
+ # says what actually enforced it. NULL only on a legacy row.
173
+ guarantee_level=guarantee_level,
174
+ deployment=runtime.deployment(),
175
+ step_up_ref=step_up_ref,
176
+ )
177
+ await self._commit(db)
178
+ except Exception as exc:
179
+ # Never the token, never the SQL parameters: the error type is enough to page on.
180
+ # The single most important operational record in the system: an uncommitted
181
+ # audit row means a call was blocked for lack of evidence. `target` stays out of
182
+ # the fields — it is an identity, and identities belong behind the audit-reader
183
+ # check; the session id is the handle an operator uses to find the rest.
184
+ logger.error(
185
+ "audit record failed; the call will be refused rather than dispatched",
186
+ extra=logs.fields(
187
+ surface.COMPONENT_CONTROL_PLANE,
188
+ session_id=session_id,
189
+ hop=decision.hop,
190
+ error_type=type(exc).__name__,
191
+ ),
192
+ )
193
+ with contextlib.suppress(Exception):
194
+ await db.rollback()
195
+ get_metrics().audit_write_failures.labels(outcome=decision.outcome).inc()
196
+ return RecordResult(action_id=None)
197
+
198
+ self._count_recorded(decision, enforced=enforced, target=target, chain=chain)
199
+ return RecordResult(
200
+ action_id=action_id, parent_chain=parent.chain if parent is not None else None
201
+ )
202
+
203
+ @staticmethod
204
+ def _count_recorded(
205
+ decision: Decision, *, enforced: bool, target: str, chain: ChainResult
206
+ ) -> None:
207
+ """Counted only once durable — a metric must never claim a decision the log lacks."""
208
+ metrics = get_metrics()
209
+ metrics.decisions.labels(
210
+ outcome=decision.outcome,
211
+ enforced=str(enforced).lower(),
212
+ target_kind=target_kind_of(target),
213
+ ).inc()
214
+ # Positional: `break` is a Python keyword, so it cannot be passed by name.
215
+ metrics.chain_writes.labels(
216
+ str(chain.complete).lower(),
217
+ chain.break_reason.value if chain.break_reason else "none",
218
+ ).inc()
219
+
220
+ async def _commit(self, db: AsyncSession) -> None:
221
+ """Separate so tests can make the audit store fail, or lie, at exactly this step."""
222
+ await db.commit()
@@ -0,0 +1,144 @@
1
+ """Materializing the delegation chain at write time — pure.
2
+
3
+ ``extend_chain`` decides, once and for all, which chain an audit row carries and whether it
4
+ is complete. No I/O, no clock, no exceptions: the audit service reads the parent row and the
5
+ clock, and this function only judges them. That is what turns every branch below into a
6
+ unit test instead of a database fixture.
7
+
8
+ A chain is only ever recorded as complete when every link was checked. The parent must be
9
+ the row the verified token names, in the same session, exactly one hop earlier. It must be
10
+ an allow that delegated to exactly the agent now acting, and its own chain must agree with
11
+ the signed ``act`` chain.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import asdict, dataclass
17
+ from enum import StrEnum
18
+ from typing import Any
19
+
20
+ AGENT_PREFIX = "agent://"
21
+
22
+
23
+ class ChainBreak(StrEnum):
24
+ # Written before Phase 3; per-hop detail was never captured.
25
+ LEGACY_RECORD = "LEGACY_RECORD"
26
+ # Presented token minted before the action_id claim existed.
27
+ LEGACY_TOKEN = "LEGACY_TOKEN"
28
+ PARENT_NOT_FOUND = "PARENT_NOT_FOUND"
29
+ PARENT_MISMATCH = "PARENT_MISMATCH"
30
+ # Inherited, not hidden: a broken ancestor keeps every descendant incomplete.
31
+ PARENT_INCOMPLETE = "PARENT_INCOMPLETE"
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class ChainEntry:
36
+ """One hop, exactly as it is stored in ``audit_decisions.chain``."""
37
+
38
+ hop: int
39
+ action_id: str
40
+ acting_agent: str | None
41
+ target: str
42
+ target_kind: str
43
+ data_class: str
44
+ decision: str
45
+ deny_reason: str | None
46
+ enforced: bool
47
+ ts: str
48
+ # Phase 4, additive. `subject_jti` is what upward taint propagation keys on;
49
+ # entries written by Phase 3 lack it and are treated as "unknown ancestor".
50
+ subject_jti: str | None = None
51
+ taint: str | None = None
52
+ taint_source: str | None = None
53
+ privileged: bool = False
54
+
55
+ def as_dict(self) -> dict[str, Any]:
56
+ return asdict(self)
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class ParentSnapshot:
61
+ """The fields of the parent row this function is allowed to judge."""
62
+
63
+ action_id: str
64
+ session_id: str
65
+ hop: int
66
+ outcome: str
67
+ target: str
68
+ chain: list[dict[str, Any]] | None
69
+ chain_complete: bool
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class ChainResult:
74
+ chain: list[dict[str, Any]]
75
+ complete: bool
76
+ break_reason: ChainBreak | None
77
+
78
+
79
+ def _complete(chain: list[dict[str, Any]]) -> ChainResult:
80
+ return ChainResult(chain=chain, complete=True, break_reason=None)
81
+
82
+
83
+ def _broken(chain: list[dict[str, Any]], reason: ChainBreak) -> ChainResult:
84
+ return ChainResult(chain=chain, complete=False, break_reason=reason)
85
+
86
+
87
+ def _links_to(
88
+ parent: ParentSnapshot,
89
+ entry: ChainEntry,
90
+ *,
91
+ session_id: str,
92
+ token_act_chain: list[str],
93
+ ) -> bool:
94
+ if parent.session_id != session_id:
95
+ return False
96
+ if parent.hop != entry.hop - 1:
97
+ return False
98
+ # A deny or a tool call issues no token, so it can never be the parent of a hop.
99
+ if parent.outcome != "allow":
100
+ return False
101
+ if entry.acting_agent is None or parent.target != f"{AGENT_PREFIX}{entry.acting_agent}":
102
+ return False
103
+ if parent.chain is not None:
104
+ # `act_chain[1:]` are the agents that acted at hops 1..n-1, signed into the token.
105
+ recorded = [hop.get("acting_agent") for hop in parent.chain]
106
+ signed = [actor.removeprefix(AGENT_PREFIX) for actor in token_act_chain[1:]]
107
+ if recorded != signed:
108
+ return False
109
+ return True
110
+
111
+
112
+ def extend_chain(
113
+ parent: ParentSnapshot | None,
114
+ entry: ChainEntry,
115
+ *,
116
+ session_id: str,
117
+ token_action_id: str | None,
118
+ token_next_hop: int,
119
+ token_act_chain: list[str],
120
+ ) -> ChainResult:
121
+ """The chain for a new row, and whether it is complete. Rules apply in table order."""
122
+ own = [entry.as_dict()]
123
+
124
+ # 1. The presented token names no parent action.
125
+ if token_action_id is None:
126
+ if token_next_hop == 1:
127
+ return _complete(own) # the root grant: this row IS the start of the chain
128
+ return _broken(own, ChainBreak.LEGACY_TOKEN)
129
+
130
+ # 2. It names one that does not exist.
131
+ if parent is None:
132
+ return _broken(own, ChainBreak.PARENT_NOT_FOUND)
133
+
134
+ # 3. It exists, but does not lead to this hop.
135
+ if not _links_to(parent, entry, session_id=session_id, token_act_chain=token_act_chain):
136
+ return _broken(own, ChainBreak.PARENT_MISMATCH)
137
+
138
+ # 4. It leads here, but its own chain was already broken.
139
+ if not parent.chain_complete:
140
+ extended = [*parent.chain, entry.as_dict()] if parent.chain else own
141
+ return _broken(extended, ChainBreak.PARENT_INCOMPLETE)
142
+
143
+ # 5. Every link checked.
144
+ return _complete([*(parent.chain or []), entry.as_dict()])
@@ -0,0 +1,55 @@
1
+ """Opaque cursors for the decision history.
2
+
3
+ A cursor carries two insertion sequence numbers: ``before`` (page strictly below it) and
4
+ ``hwm`` (the high-water mark fixed when the first page was served). Holding ``hwm`` across
5
+ the iteration is what keeps paging stable while decisions keep being recorded: a row
6
+ appended mid-iteration has ``seq > hwm`` and never appears in it.
7
+
8
+ Opaque to clients, but never trusted: anything that does not decode to a well-formed cursor
9
+ is a ``422`` naming ``cursor`` — not a silent restart at page one, which is what Phase 2's
10
+ id-anchored cursor did.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import binascii
17
+ import json
18
+
19
+ from agentic_auth.errors import QueryValidationError
20
+
21
+ CURSOR_VERSION = 1
22
+
23
+
24
+ def encode_cursor(before: int, hwm: int) -> str:
25
+ raw = json.dumps({"v": CURSOR_VERSION, "before": before, "hwm": hwm}, separators=(",", ":"))
26
+ return base64.urlsafe_b64encode(raw.encode()).rstrip(b"=").decode()
27
+
28
+
29
+ def _invalid(reason: str) -> QueryValidationError:
30
+ return QueryValidationError(
31
+ f"invalid cursor: {reason}", [{"loc": ["query", "cursor"], "msg": reason}]
32
+ )
33
+
34
+
35
+ def _is_int(value: object) -> bool:
36
+ return isinstance(value, int) and not isinstance(value, bool)
37
+
38
+
39
+ def decode_cursor(cursor: str) -> tuple[int, int]:
40
+ """``(before, hwm)``, or ``QueryValidationError``."""
41
+ try:
42
+ padded = cursor + "=" * (-len(cursor) % 4)
43
+ data = json.loads(base64.urlsafe_b64decode(padded))
44
+ except (ValueError, binascii.Error, UnicodeDecodeError) as exc:
45
+ raise _invalid("not a cursor issued by this API") from exc
46
+
47
+ if not isinstance(data, dict) or data.get("v") != CURSOR_VERSION:
48
+ raise _invalid("unsupported cursor version")
49
+ before, hwm = data.get("before"), data.get("hwm")
50
+ if not (_is_int(before) and _is_int(hwm)):
51
+ raise _invalid("malformed cursor")
52
+ assert isinstance(before, int) and isinstance(hwm, int) # narrowed above
53
+ if before < 1 or hwm < 1 or before > hwm:
54
+ raise _invalid("malformed cursor")
55
+ return before, hwm
@@ -0,0 +1,58 @@
1
+ """Scope catalog reads, backed by the immutable Redis DAG cache.
2
+
3
+ Cache key: ``dag:{scope}:{version}`` — immutable, no TTL. On a miss the catalog is read
4
+ from Postgres and written back.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import json
11
+
12
+ from redis.asyncio import Redis
13
+ from sqlalchemy.ext.asyncio import AsyncSession
14
+
15
+ from agentic_auth.errors import NotFoundError
16
+ from agentic_auth.repositories import compiled_policies as policies_repo
17
+ from agentic_auth.schemas.dag import ScopeCatalog
18
+
19
+
20
+ def _key(scope: str, version: int) -> str:
21
+ return f"dag:{scope}:{version}"
22
+
23
+
24
+ def _catalog_from_dag(scope: str, version: int, dag: dict) -> ScopeCatalog:
25
+ return ScopeCatalog(
26
+ scope=scope,
27
+ version=version,
28
+ tools=dag.get("tools", []),
29
+ data_classes=dag.get("data_classes", {"reads": [], "writes": []}),
30
+ downstream_agents=dag.get("downstream_agents", []),
31
+ hop_budget=dag["hop_budget"],
32
+ )
33
+
34
+
35
+ async def get_catalog(
36
+ session: AsyncSession, redis: Redis, scope: str, version: int | None
37
+ ) -> ScopeCatalog:
38
+ if version is None:
39
+ version = await policies_repo.latest_version_number(session, scope)
40
+ if version is None:
41
+ raise NotFoundError(f"no compiled DAG for scope {scope!r}")
42
+
43
+ cached = await redis.get(_key(scope, version))
44
+ if cached is not None:
45
+ return _catalog_from_dag(scope, version, json.loads(cached))
46
+
47
+ row = await policies_repo.get_version(session, scope, version)
48
+ if row is None:
49
+ raise NotFoundError(f"no compiled DAG for scope {scope!r} version {version}")
50
+
51
+ await redis.set(_key(scope, version), json.dumps(row.dag))
52
+ return _catalog_from_dag(scope, version, row.dag)
53
+
54
+
55
+ async def warm(redis: Redis, scope: str, version: int, dag: dict) -> None:
56
+ """Best-effort write-through after a compile."""
57
+ with contextlib.suppress(Exception):
58
+ await redis.set(_key(scope, version), json.dumps(dag))
@@ -0,0 +1,152 @@
1
+ """The delegation-chain query — "who authorized this, and through which agents?"
2
+
3
+ One read: the action's own audit row, joined to its (immutable) session for the root
4
+ consent. The chain comes from the row's materialized ``chain`` document, written when the
5
+ decision was made; nothing here correlates other decision rows. Completeness was
6
+ decided at write time too, so the answer cannot depend on what happens to be in the table
7
+ when the question is asked.
8
+
9
+ A legacy row — written before Phase 3 — is still answered, marked incomplete, with every
10
+ field that was never captured reported as unavailable rather than inferred.
11
+
12
+ Every query is timed and counted by result, which is how the SLO (p95 < 500 ms, 100% complete)
13
+ is observed in production rather than asserted once in a test.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import time
19
+ import uuid
20
+
21
+ from sqlalchemy import select
22
+ from sqlalchemy.ext.asyncio import AsyncSession
23
+
24
+ from agentic_auth.errors import NotFoundError
25
+ from agentic_auth.models import AuditDecision, Session
26
+ from agentic_auth.repositories import transaction_tokens as txn_repo
27
+ from agentic_auth.schemas.audit import (
28
+ ChainBreakRead,
29
+ ChainHop,
30
+ ChainRead,
31
+ RootConsent,
32
+ TransactionFingerprint,
33
+ )
34
+ from agentic_auth.services.audit_chain import AGENT_PREFIX, ChainBreak
35
+ from agentic_auth.services.metrics import get_metrics
36
+
37
+
38
+ def _own_hop(row: AuditDecision) -> ChainHop:
39
+ return ChainHop(
40
+ hop=row.hop,
41
+ action_id=row.id,
42
+ acting_agent=row.acting_agent,
43
+ target=row.target,
44
+ target_kind=row.target_kind,
45
+ data_class=row.data_class,
46
+ decision=row.outcome,
47
+ deny_reason=row.deny_reason,
48
+ enforced=row.enforced,
49
+ ts=row.ts,
50
+ taint=row.taint,
51
+ taint_source=row.taint_source,
52
+ privileged=row.privileged,
53
+ )
54
+
55
+
56
+ def _legacy_hops(row: AuditDecision) -> list[ChainHop]:
57
+ """Rebuild what a pre-Phase-3 row can honestly say.
58
+
59
+ ``act_chain`` is ``[human, agent at hop 1, ..., agent at hop n-1]`` — verified actor
60
+ names, and nothing else. Earlier hops therefore get their acting agent and no other
61
+ detail; only the row's own hop is known in full.
62
+ """
63
+ earlier = [
64
+ ChainHop(
65
+ hop=index,
66
+ action_id=None,
67
+ acting_agent=str(actor).removeprefix(AGENT_PREFIX),
68
+ target=None,
69
+ target_kind=None,
70
+ data_class=None,
71
+ decision=None,
72
+ deny_reason=None,
73
+ enforced=None,
74
+ ts=None,
75
+ unavailable=True,
76
+ )
77
+ for index, actor in enumerate(row.act_chain[1:], start=1)
78
+ if index < row.hop
79
+ ]
80
+ return [*earlier, _own_hop(row)]
81
+
82
+
83
+ def _break_point(chain: list[ChainHop]) -> int:
84
+ """The first hop whose link is missing: the hop just before the earliest one we hold."""
85
+ return max(1, chain[0].hop - 1)
86
+
87
+
88
+ class ChainQueryService:
89
+ async def get(self, db: AsyncSession, action_id: uuid.UUID) -> ChainRead:
90
+ started = time.perf_counter()
91
+ try:
92
+ chain = await self._read(db, action_id)
93
+ except NotFoundError:
94
+ self._observe("not_found", started)
95
+ raise
96
+ self._observe("complete" if chain.complete else "incomplete", started)
97
+ return chain
98
+
99
+ @staticmethod
100
+ def _observe(result: str, started: float) -> None:
101
+ metrics = get_metrics()
102
+ metrics.chain_query_duration.labels(result=result).observe(time.perf_counter() - started)
103
+ metrics.chain_queries.labels(result=result).inc()
104
+
105
+ async def _read(self, db: AsyncSession, action_id: uuid.UUID) -> ChainRead:
106
+ result = await db.execute(
107
+ select(AuditDecision, Session)
108
+ .join(Session, Session.id == AuditDecision.session_id)
109
+ .where(AuditDecision.id == action_id)
110
+ )
111
+ found = result.one_or_none()
112
+ if found is None:
113
+ raise NotFoundError(f"no recorded action {action_id}")
114
+ row, session = found
115
+
116
+ root = RootConsent(
117
+ user_sub=session.user_sub,
118
+ scope=session.scope,
119
+ consented_at=session.created_at,
120
+ session_id=session.id,
121
+ )
122
+
123
+ if row.chain is None:
124
+ hops = _legacy_hops(row)
125
+ reason = ChainBreak(row.chain_break) if row.chain_break else ChainBreak.LEGACY_RECORD
126
+ chain_break: ChainBreakRead | None = ChainBreakRead(at_hop=1, reason=reason)
127
+ else:
128
+ hops = [ChainHop.model_validate(hop) for hop in row.chain]
129
+ if row.privileged:
130
+ # Phase 4: the queried action's own transaction fingerprint, if minted.
131
+ txn = await txn_repo.get_by_action(db, row.id)
132
+ if txn is not None and hops:
133
+ hops[-1] = hops[-1].model_copy(
134
+ update={"transaction": TransactionFingerprint.model_validate(txn)}
135
+ )
136
+ chain_break = (
137
+ None
138
+ if row.chain_complete
139
+ else ChainBreakRead(
140
+ at_hop=_break_point(hops),
141
+ reason=ChainBreak(row.chain_break or ChainBreak.PARENT_INCOMPLETE),
142
+ )
143
+ )
144
+
145
+ return ChainRead(
146
+ action_id=row.id,
147
+ complete=row.chain_complete,
148
+ chain_break=chain_break,
149
+ root_consent=root,
150
+ policy_version=row.policy_version,
151
+ chain=hops,
152
+ )