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,68 @@
1
+ """``/v1/manifests`` — submit a new version, immutable version-pinned reads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import APIRouter, Query, Response
6
+
7
+ from agentic_auth.api.deps import AdminDep, SessionDep
8
+ from agentic_auth.api.responses import render_outcome
9
+ from agentic_auth.api.service_deps import ManifestServiceDep, RedisDep
10
+ from agentic_auth.api.v1.agents import ADMIN_IDENTITY
11
+ from agentic_auth.errors import NotFoundError
12
+ from agentic_auth.repositories import agents as agents_repo
13
+ from agentic_auth.repositories import manifests as manifests_repo
14
+ from agentic_auth.schemas.manifest_api import ManifestCreate, ManifestRead
15
+
16
+ router = APIRouter(prefix="/v1", tags=["manifests"], dependencies=[AdminDep])
17
+
18
+
19
+ @router.post("/manifests")
20
+ async def submit_manifest(
21
+ body: ManifestCreate,
22
+ session: SessionDep,
23
+ service: ManifestServiceDep,
24
+ redis: RedisDep,
25
+ ) -> Response:
26
+ outcome = await service.submit_manifest(
27
+ session,
28
+ redis,
29
+ agent_name=body.agent,
30
+ manifest=body.manifest,
31
+ attested_by=ADMIN_IDENTITY,
32
+ override=body.override,
33
+ )
34
+ return render_outcome(
35
+ outcome,
36
+ created_key={
37
+ "agent": outcome.agent_name,
38
+ "version": outcome.version,
39
+ "status": outcome.status,
40
+ },
41
+ )
42
+
43
+
44
+ @router.get("/manifests/{scope}", response_model=ManifestRead)
45
+ async def read_manifest(
46
+ scope: str,
47
+ session: SessionDep,
48
+ version: int | None = Query(default=None, ge=1),
49
+ ) -> ManifestRead:
50
+ agent = await agents_repo.get_by_name(session, scope)
51
+ if agent is None:
52
+ raise NotFoundError(f"no manifest for scope {scope!r}")
53
+
54
+ if version is None:
55
+ row = await manifests_repo.get_latest(session, agent.id)
56
+ else:
57
+ row = await manifests_repo.get_version(session, agent.id, version)
58
+ if row is None:
59
+ raise NotFoundError(f"no manifest for scope {scope!r} version {version}")
60
+
61
+ return ManifestRead(
62
+ agent=scope,
63
+ version=row.version,
64
+ status=row.status,
65
+ attested_by=row.attested_by,
66
+ doc=row.doc,
67
+ created_at=row.created_at,
68
+ )
@@ -0,0 +1,22 @@
1
+ """``/v1/scopes/{scope}/catalog`` — what a scope expands to."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import APIRouter, Query
6
+
7
+ from agentic_auth.api.deps import AdminDep, SessionDep
8
+ from agentic_auth.api.service_deps import RedisDep
9
+ from agentic_auth.schemas.dag import ScopeCatalog
10
+ from agentic_auth.services import catalog_service
11
+
12
+ router = APIRouter(prefix="/v1", tags=["scopes"], dependencies=[AdminDep])
13
+
14
+
15
+ @router.get("/scopes/{scope}/catalog", response_model=ScopeCatalog)
16
+ async def get_scope_catalog(
17
+ scope: str,
18
+ session: SessionDep,
19
+ redis: RedisDep,
20
+ version: int | None = Query(default=None, ge=1),
21
+ ) -> ScopeCatalog:
22
+ return await catalog_service.get_catalog(session, redis, scope, version)
@@ -0,0 +1,203 @@
1
+ """``POST /v1/token/exchange`` — RFC 8693, form-encoded.
2
+
3
+ Errors follow RFC 6749 §5.2 rather than this project's envelope, because an OAuth client
4
+ already knows how to read ``{"error": "invalid_grant"}`` and this endpoint is the one
5
+ place we speak someone else's protocol.
6
+
7
+ From Phase 3 an exchange must name the recorded allow it is spending (``action_id``). The
8
+ service refuses to mint unless that row is committed and matches this exact hop, which is
9
+ what makes audit-before-dispatch a database property rather than an ordering convention.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import uuid
16
+ from collections.abc import Mapping
17
+ from typing import Annotated
18
+
19
+ from fastapi import APIRouter, Depends, Form, Request
20
+ from fastapi.responses import JSONResponse
21
+
22
+ from agentic_auth import observability
23
+ from agentic_auth.api.deps import SessionDep
24
+ from agentic_auth.api.service_deps import AuditServiceDep, RedisDep, TokenExchangeServiceDep
25
+ from agentic_auth.errors import DomainError
26
+ from agentic_auth.observability import surface
27
+ from agentic_auth.schemas.authorize import DenyReason, Taint
28
+ from agentic_auth.schemas.token import GRANT_TYPE, JWT_TOKEN_TYPE, TokenExchangeRequest
29
+ from agentic_auth.services.metrics import get_metrics
30
+ from agentic_auth.services.tokens.exchange import ExchangeDenied, ExchangeRefused
31
+ from agentic_auth.services.tokens.replay import ReplayGuardUnavailable, TokenAlreadyExchanged
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ router = APIRouter(prefix="/v1", tags=["token"])
36
+
37
+ ACTION_ID_REQUIRED = (
38
+ "action_id is required: pass the action_id from the allow decision for this hop"
39
+ )
40
+ ACTION_ID_INVALID = "action_id is not a valid UUID"
41
+
42
+
43
+ def exchange_form(
44
+ grant_type: Annotated[str, Form()],
45
+ subject_token: Annotated[str, Form()],
46
+ subject_token_type: Annotated[str, Form()],
47
+ resource: Annotated[str, Form()],
48
+ scope: Annotated[str, Form()],
49
+ actor_token: Annotated[str | None, Form()] = None,
50
+ actor_token_type: Annotated[str | None, Form()] = None,
51
+ audience: Annotated[str | None, Form()] = None,
52
+ taint: Annotated[str | None, Form()] = None,
53
+ # Optional in the signature only so that its absence is an RFC 6749 `invalid_request`
54
+ # with the fix spelled out, rather than FastAPI's generic 422.
55
+ action_id: Annotated[str | None, Form()] = None,
56
+ ) -> tuple[TokenExchangeRequest, Taint | None, uuid.UUID]:
57
+ if grant_type != GRANT_TYPE:
58
+ raise ExchangeRefused("unsupported_grant_type", f"unsupported grant_type {grant_type!r}")
59
+ if subject_token_type != JWT_TOKEN_TYPE:
60
+ raise ExchangeRefused(
61
+ "invalid_request", f"unsupported subject_token_type {subject_token_type!r}"
62
+ )
63
+ if not action_id:
64
+ raise ExchangeRefused("invalid_request", ACTION_ID_REQUIRED)
65
+ try:
66
+ recorded_action = uuid.UUID(action_id)
67
+ except ValueError as exc:
68
+ raise ExchangeRefused("invalid_request", ACTION_ID_INVALID) from exc
69
+
70
+ return (
71
+ TokenExchangeRequest(
72
+ grant_type=GRANT_TYPE,
73
+ subject_token=subject_token,
74
+ subject_token_type=JWT_TOKEN_TYPE,
75
+ resource=resource,
76
+ scope=scope,
77
+ actor_token=actor_token,
78
+ actor_token_type=JWT_TOKEN_TYPE if actor_token_type else None,
79
+ audience=audience,
80
+ ),
81
+ Taint(taint) if taint else None,
82
+ recorded_action,
83
+ )
84
+
85
+
86
+ def _oauth_error(
87
+ status: int, error: str, description: str, *, reason: DenyReason | None = None
88
+ ) -> JSONResponse:
89
+ """RFC 6749 §5.2, plus the machine reason when policy is what refused.
90
+
91
+ ``error`` stays the OAuth code an OAuth client branches on. ``reason`` is an additive
92
+ member (§5.2 permits them) carrying the same deny vocabulary the decision endpoint
93
+ returns, because an enforcement point needs to tell AGENT_NOT_ENROLLED from
94
+ OUT_OF_SCOPE — and only this response knows which it was: ``AGENT_NOT_ENROLLED`` is
95
+ established by the proof-of-possession check, which lives here and not in the PDP.
96
+ """
97
+ body: dict[str, str] = {"error": error, "error_description": description}
98
+ if reason is not None:
99
+ body["reason"] = reason.value
100
+ return JSONResponse(status_code=status, content=body)
101
+
102
+
103
+ @router.post("/token/exchange")
104
+ async def exchange_token(
105
+ request: Request,
106
+ parsed: Annotated[tuple[TokenExchangeRequest, Taint | None, uuid.UUID], Depends(exchange_form)],
107
+ db: SessionDep,
108
+ redis: RedisDep,
109
+ service: TokenExchangeServiceDep,
110
+ audit: AuditServiceDep,
111
+ ) -> JSONResponse:
112
+ body, taint, action_id = parsed
113
+ span = _ExchangeSpan(request.headers, action_id)
114
+ try:
115
+ response, _decision, _subject = await service.exchange(
116
+ db, redis, body, taint=taint, action_id=action_id
117
+ )
118
+ except ExchangeDenied as denied:
119
+ # The recorded allow no longer holds under a fresh decision. Record the refusal,
120
+ # then say no. A denied hop yields no token, whether or not the record lands.
121
+ await audit.record(
122
+ db,
123
+ session_id=denied.session_id,
124
+ caller=denied.caller,
125
+ target=denied.target,
126
+ data_class=denied.data_class,
127
+ decision=denied.decision,
128
+ enforced=True,
129
+ taint=denied.decision.taint.value if denied.decision.taint else None,
130
+ taint_source=denied.taint_source,
131
+ privileged=denied.decision.privileged,
132
+ policy_version=denied.policy_version,
133
+ token=denied.token,
134
+ )
135
+ if denied.decision.reason is not None:
136
+ get_metrics().denials.labels(reason=denied.decision.reason.value).inc()
137
+ span.emit("denied", session_id=str(denied.session_id), hop=denied.decision.hop)
138
+ return _oauth_error(403, "invalid_target", str(denied), reason=denied.decision.reason)
139
+ except TokenAlreadyExchanged as exc:
140
+ span.emit("already_exchanged")
141
+ return _oauth_error(400, "invalid_grant", str(exc))
142
+ except ReplayGuardUnavailable as exc:
143
+ # The stack trace is deliberately NOT recorded: once a sink is attached the SDK exports
144
+ # `exception.stacktrace` verbatim, and a traceback through token verification can carry
145
+ # a token fragment.
146
+ logger.error(
147
+ "replay guard unavailable; refusing to issue",
148
+ extra={
149
+ "authz.component": surface.COMPONENT_CONTROL_PLANE,
150
+ "error.type": type(exc).__name__,
151
+ },
152
+ )
153
+ span.emit("replay_guard_unavailable")
154
+ return _oauth_error(503, "invalid_grant", "single-use guard unavailable; refusing to issue")
155
+ except DomainError:
156
+ span.emit("refused")
157
+ raise
158
+ # ExchangeRefused is rendered by the app-wide OAuth handler (agentic_auth/api/errors.py),
159
+ # because the grant grammar is validated in a dependency that runs before this body.
160
+
161
+ span.emit("ok")
162
+ return JSONResponse(status_code=200, content=response.model_dump())
163
+
164
+
165
+ class _ExchangeSpan:
166
+ """Emits exactly one ``authz.exchange`` span, whichever way the handler leaves.
167
+
168
+ A small class rather than a ``with`` block because the handler has six exits and the
169
+ attributes are only known at each one. ``emit`` is idempotent, so a path that records and
170
+ then re-raises cannot double-count.
171
+ """
172
+
173
+ __slots__ = ("_action_id", "_done", "_headers")
174
+
175
+ def __init__(self, headers: Mapping[str, str], action_id: uuid.UUID) -> None:
176
+ self._headers = headers
177
+ self._action_id = action_id
178
+ self._done = False
179
+
180
+ def emit(self, result: str, *, session_id: str | None = None, hop: int | None = None) -> None:
181
+ if self._done:
182
+ return
183
+ self._done = True
184
+ config = observability.config()
185
+ if not config.enabled:
186
+ return
187
+ parent = observability.extract_parent(
188
+ self._headers, session_id=session_id, key=config.key, metrics=get_metrics()
189
+ )
190
+ attributes = observability.exchange_attributes(
191
+ config,
192
+ action_id=str(self._action_id),
193
+ session_id=session_id,
194
+ hop=hop,
195
+ result=result,
196
+ )
197
+ with observability.tracer().start_as_current_span(
198
+ surface.SPAN_EXCHANGE,
199
+ context=parent,
200
+ attributes=attributes,
201
+ record_exception=False,
202
+ ):
203
+ pass
@@ -0,0 +1,94 @@
1
+ """``POST /v1/token/transaction`` — call-bound authority for one privileged tool call.
2
+
3
+ Bearer: the hop token minted for the tool call (``aud`` = target). The recorded decision is
4
+ read from the token's signed ``action_id`` claim, never from the body.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from fastapi import APIRouter, Request
10
+
11
+ from agentic_auth import observability
12
+ from agentic_auth.api.deps import PresentedTokenDep, SessionDep
13
+ from agentic_auth.api.service_deps import RedisDep, TransactionServiceDep
14
+ from agentic_auth.config import get_settings
15
+ from agentic_auth.errors import NotFoundError, TransactionValidationError
16
+ from agentic_auth.observability import surface
17
+ from agentic_auth.schemas.transaction import TransactionMinted, TransactionMintRequest
18
+ from agentic_auth.services.metrics import get_metrics
19
+
20
+ router = APIRouter(prefix="/v1", tags=["token"])
21
+
22
+
23
+ @router.post("/token/transaction", response_model=TransactionMinted)
24
+ async def mint_transaction_token(
25
+ request: Request,
26
+ body: TransactionMintRequest,
27
+ db: SessionDep,
28
+ redis: RedisDep,
29
+ service: TransactionServiceDep,
30
+ token: PresentedTokenDep,
31
+ ) -> TransactionMinted:
32
+ settings = get_settings()
33
+ if not settings.transaction_tokens_enabled:
34
+ raise NotFoundError("transaction tokens are disabled")
35
+ declared = request.headers.get("content-length")
36
+ if (
37
+ declared is not None
38
+ and declared.isdigit()
39
+ and int(declared) > settings.max_privileged_body_bytes
40
+ ):
41
+ _emit_mint_span(request, token, "too_large")
42
+ raise TransactionValidationError(
43
+ "params exceed the binding size cap",
44
+ [{"loc": ["params"], "msg": f"> {settings.max_privileged_body_bytes} bytes"}],
45
+ )
46
+ try:
47
+ minted = await service.mint(db, redis, token, body.params)
48
+ except Exception as exc:
49
+ _emit_mint_span(request, token, "refused", error_type=type(exc).__name__)
50
+ raise
51
+ _emit_mint_span(request, token, "minted")
52
+ return minted
53
+
54
+
55
+ def _emit_mint_span(
56
+ request: Request,
57
+ token: object,
58
+ result: str,
59
+ *,
60
+ error_type: str | None = None,
61
+ ) -> None:
62
+ """``authz.transaction.mint``.
63
+
64
+ Records *that* a binding was computed and nothing about what was bound: no ``params``, no
65
+ ``params_hash``, no binding, no part of the request body.
66
+ ``agentic_auth/observability/surface.py``
67
+ refuses those keys by substring, so this is enforced rather than merely intended.
68
+ """
69
+ config = observability.config()
70
+ if not config.enabled:
71
+ return
72
+ session_id = getattr(token, "session_id", None)
73
+ attributes = observability.mint_attributes(
74
+ config,
75
+ action_id=str(getattr(token, "action_id", "") or "") or None,
76
+ session_id=str(session_id) if session_id else None,
77
+ result=result,
78
+ acting_agent=getattr(token, "holder", None),
79
+ )
80
+ if error_type is not None:
81
+ attributes[surface.ATTR_ERROR_TYPE] = error_type
82
+ parent = observability.extract_parent(
83
+ request.headers,
84
+ session_id=str(session_id) if session_id else None,
85
+ key=config.key,
86
+ metrics=get_metrics(),
87
+ )
88
+ with observability.tracer().start_as_current_span(
89
+ surface.SPAN_MINT,
90
+ context=parent,
91
+ attributes=attributes,
92
+ record_exception=False,
93
+ ):
94
+ pass
@@ -0,0 +1,26 @@
1
+ """Boundary enforcement — the FR-14 rungs, in decreasing order of strength.
2
+
3
+ Each module here answers a different "what does the integrator actually control?":
4
+
5
+ - :mod:`agentic_auth.boundary.resource` — you own the tool. A guard over Phase 4's
6
+ :mod:`agentic_auth.verify`, admitting only on identity AND grant AND (privileged) transaction.
7
+ The calling agent's cooperation is irrelevant. Reports ``full``.
8
+ - :mod:`agentic_auth.boundary.mcp` — you own the agent's tool configuration. Repoint it at this
9
+ proxy and the agent never knows. Reports ``connector``.
10
+ - :mod:`agentic_auth.boundary.egress` — you own the runtime and nothing else. A CONNECT proxy with
11
+ TLS interception, so the agent's only route out is through us. Reports ``network``.
12
+
13
+ **None of them re-implements policy.** ``resource`` calls ``agentic_auth.verify.Verifier.admit()``;
14
+ ``mcp`` and ``egress`` call ``agentic_auth.sidecar.enforce.enforce()``. That is what makes the
15
+ conformance suite meaningful rather than aspirational: there is one decision core, and the
16
+ modes differ only in transport and trust assumptions.
17
+
18
+ Import direction is one-way: this package imports :mod:`agentic_auth.verify`, never the reverse, so
19
+ the verifier library's closed import graph is preserved.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from agentic_auth.boundary.guarantee import STRENGTH, Guarantee, is_degrade, strongest, weakest
25
+
26
+ __all__ = ["Guarantee", "STRENGTH", "strongest", "weakest", "is_degrade"]
@@ -0,0 +1,96 @@
1
+ """How strong the enforcement actually was — the one field that keeps a weak deployment
2
+ from reading as a strong one.
3
+
4
+ PRD §8.3 FR-14's last rung says a reduced-guarantee mode "MUST be surfaced explicitly …
5
+ rather than silently degrading". This module is that requirement, made into a type.
6
+
7
+ **Reported by the enforcement point, never derived here.** ``AuthorizeRequest.guarantee``
8
+ follows ``AuthorizeRequest.enforced`` exactly: the PEP self-reports, the control plane
9
+ records, and the PDP never sees it. The control plane genuinely cannot tell a sidecar from
10
+ a gateway from a connector proxy — they all present a hop token over HTTP — so inferring
11
+ the level would mean inventing a per-PEP credential for a field whose whole job is honesty
12
+ about a deployment choice.
13
+
14
+ A PEP could report the wrong level. That is not the threat this field addresses: an
15
+ attacker who controls the enforcement point has already won by a shorter route. The field
16
+ exists so an *honest* deployment cannot accidentally look stronger than it is, which is an
17
+ operator-error problem.
18
+
19
+ See https://authzai.dev/explanation/enforcement-point-tradeoffs.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from enum import StrEnum
25
+
26
+
27
+ class Guarantee(StrEnum):
28
+ """Strongest to weakest. The order of declaration is not the contract — ``STRENGTH``
29
+ is — but keeping them aligned makes the file readable."""
30
+
31
+ # Every hop decided before dispatch, authority narrowed per hop, privileged calls
32
+ # bound to their parameters, every decision audited. The sidecar, the gateway with
33
+ # verified identity, and the resource-side guard.
34
+ FULL = "full"
35
+ # Same per-hop decision, but only for calls that go through the agent's configured
36
+ # tool connector. A call made by some other route is not seen.
37
+ CONNECTOR = "connector"
38
+ # Same per-hop decision applied to whatever leaves the agent's runtime. Depends on
39
+ # trust material installed in a runtime the integrator does not fully own.
40
+ NETWORK = "network"
41
+ # Coarse scoping at grant time, revocation, and an audit record at the edge. There is
42
+ # no per-hop decision at all.
43
+ CONSENT_ONLY = "consent_only"
44
+
45
+
46
+ STRENGTH: dict[Guarantee, int] = {
47
+ Guarantee.FULL: 3,
48
+ Guarantee.CONNECTOR: 2,
49
+ Guarantee.NETWORK: 1,
50
+ Guarantee.CONSENT_ONLY: 0,
51
+ }
52
+
53
+ # Every level has a strength. A new member without one would silently sort as weakest,
54
+ # which is the wrong direction to fail for a field about honesty.
55
+ assert set(Guarantee) == set(STRENGTH), "every guarantee level needs a strength"
56
+
57
+
58
+ def strongest(*levels: Guarantee) -> Guarantee:
59
+ """The strongest of the modes that **actually decided** this call.
60
+
61
+ Two modes deciding one call is ordinary: a connector proxy in front of a tool that
62
+ also carries a resource-side guard. The outcome is the stricter of the two — a refusal
63
+ anywhere refuses — but the recorded level is the strongest, because the resource guard
64
+ genuinely did verify identity, grant and, for a privileged target, the call binding.
65
+
66
+ "Actually decided" excludes a mode that was configured but not consulted for this
67
+ call; the caller is responsible for passing only the levels that produced a verdict.
68
+ """
69
+ if not levels:
70
+ raise ValueError(
71
+ "strongest() needs at least one level: a decision with no guarantee level "
72
+ "must not be emitted"
73
+ )
74
+ return max(levels, key=lambda level: STRENGTH[level])
75
+
76
+
77
+ def weakest(*levels: Guarantee) -> Guarantee:
78
+ """The weakest of several levels — used when reporting what a deployment as a whole
79
+ can promise, as opposed to what one decision achieved."""
80
+ if not levels:
81
+ raise ValueError("weakest() needs at least one level")
82
+ return min(levels, key=lambda level: STRENGTH[level])
83
+
84
+
85
+ def is_degrade(previous: Guarantee, current: Guarantee) -> bool:
86
+ """True when the level in force has become weaker.
87
+
88
+ A degrade is written as its own audit event, so it lands in the same timeline
89
+ as the decisions around it rather than in a separate log an operator has to correlate.
90
+ Starting weak is a configuration, not a degrade, so this is only ever asked when a
91
+ previous level exists.
92
+ """
93
+ return STRENGTH[current] < STRENGTH[previous]
94
+
95
+
96
+ __all__ = ["Guarantee", "STRENGTH", "strongest", "weakest", "is_degrade"]
@@ -0,0 +1,27 @@
1
+ """``agentic-auth`` command-line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from agentic_auth._extras import require_extra
6
+
7
+ require_extra("agentic_auth.cli", "drift", "typer", "rich", "yaml", "httpx", "prometheus_client")
8
+
9
+ import typer
10
+
11
+ from agentic_auth.cli.audit import audit_app
12
+ from agentic_auth.cli.drift import drift_app
13
+ from agentic_auth.cli.identity import app as identity_app
14
+ from agentic_auth.cli.manifest import manifest_app
15
+
16
+ app = typer.Typer(help="Agentic Authorization SDK developer CLI", no_args_is_help=True)
17
+ app.add_typer(manifest_app, name="manifest")
18
+ app.add_typer(audit_app, name="audit")
19
+ app.add_typer(drift_app, name="drift")
20
+ app.add_typer(identity_app, name="identity")
21
+
22
+
23
+ def main() -> None:
24
+ app()
25
+
26
+
27
+ __all__ = ["app", "main"]
@@ -0,0 +1,130 @@
1
+ """``agentic-auth audit export`` — read-only archival of the append-only audit log.
2
+
3
+ Exports rows older than a cutoff as JSON lines, oldest first. It never deletes anything: a
4
+ command that could remove audit rows is a mutation path the runtime must never have. Purging
5
+ after an export is a documented, owner-run maintenance step
6
+ (https://authzai.dev/how-to/query-a-delegation-chain).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json
13
+ import uuid
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ import typer
19
+ from rich import print as rprint
20
+
21
+ from agentic_auth._extras import require_extra
22
+
23
+ # The CLI is installed by the `drift` extra, which has no database stack, and `agentic-auth`
24
+ # imports every command group to build its help. So the database is imported by the command
25
+ # that reads it, not by this module.
26
+ if TYPE_CHECKING:
27
+ from agentic_auth.models import AuditDecision
28
+
29
+ audit_app = typer.Typer(help="Read and archive the append-only audit log")
30
+
31
+ EXIT_OK = 0
32
+ EXIT_ERROR = 2
33
+ EXPORT_BATCH = 1000
34
+
35
+
36
+ def _jsonable(value: Any) -> Any:
37
+ if isinstance(value, uuid.UUID):
38
+ return str(value)
39
+ if isinstance(value, datetime):
40
+ return value.isoformat()
41
+ return value
42
+
43
+
44
+ def serialize(row: AuditDecision) -> dict[str, Any]:
45
+ from agentic_auth.models import AuditDecision
46
+
47
+ return {
48
+ column.name: _jsonable(getattr(row, column.name))
49
+ for column in AuditDecision.__table__.columns
50
+ }
51
+
52
+
53
+ async def export_before(database_url: str, before: datetime, out: Path) -> int:
54
+ """Write every row with ``ts < before`` to ``out``, oldest first. Returns the count.
55
+
56
+ Pages on ``seq`` so a very large table never loads into memory at once.
57
+ """
58
+ from sqlalchemy import select
59
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
60
+ from sqlalchemy.pool import NullPool
61
+
62
+ from agentic_auth.models import AuditDecision
63
+
64
+ engine = create_async_engine(database_url, poolclass=NullPool)
65
+ count = 0
66
+ try:
67
+ async with async_sessionmaker(engine, expire_on_commit=False)() as db:
68
+ with out.open("w", encoding="utf-8") as handle:
69
+ last_seq = 0
70
+ while True:
71
+ rows = (
72
+ (
73
+ await db.execute(
74
+ select(AuditDecision)
75
+ .where(AuditDecision.ts < before, AuditDecision.seq > last_seq)
76
+ .order_by(AuditDecision.seq)
77
+ .limit(EXPORT_BATCH)
78
+ )
79
+ )
80
+ .scalars()
81
+ .all()
82
+ )
83
+ if not rows:
84
+ break
85
+ for row in rows:
86
+ handle.write(json.dumps(serialize(row), sort_keys=True) + "\n")
87
+ count += 1
88
+ last_seq = rows[-1].seq
89
+ finally:
90
+ await engine.dispose()
91
+ return count
92
+
93
+
94
+ def _parse_cutoff(raw: str) -> datetime | None:
95
+ try:
96
+ cutoff = datetime.fromisoformat(raw.replace("Z", "+00:00"))
97
+ except ValueError:
98
+ return None
99
+ return cutoff if cutoff.tzinfo is not None else None
100
+
101
+
102
+ @audit_app.command("export")
103
+ def export(
104
+ before: str = typer.Option(
105
+ ..., "--before", help="RFC 3339 cutoff; strictly older rows are exported"
106
+ ),
107
+ out: Path = typer.Option(..., "--out", help="Destination JSON-lines file"),
108
+ database_url: str | None = typer.Option(
109
+ None, "--database-url", help="Defaults to AGENTIC_AUTH_DATABASE_URL"
110
+ ),
111
+ ) -> None:
112
+ """Export audit rows older than a cutoff. Read-only: never deletes."""
113
+ cutoff = _parse_cutoff(before)
114
+ if cutoff is None:
115
+ rprint(f"[red]--before must be an RFC 3339 timestamp with a timezone, got {before!r}[/red]")
116
+ raise typer.Exit(EXIT_ERROR)
117
+ if not out.parent.is_dir():
118
+ rprint(f"[red]cannot write {out}: directory {out.parent} does not exist[/red]")
119
+ raise typer.Exit(EXIT_ERROR)
120
+
121
+ require_extra("agentic-auth audit export", "server", "sqlalchemy", "asyncpg")
122
+ from agentic_auth.config import get_settings
123
+
124
+ try:
125
+ count = asyncio.run(export_before(database_url or get_settings().database_url, cutoff, out))
126
+ except Exception as exc:
127
+ rprint(f"[red]export failed: {type(exc).__name__}[/red]")
128
+ raise typer.Exit(EXIT_ERROR) from exc
129
+
130
+ rprint(f"exported {count} audit rows older than {cutoff.isoformat()} to {out}")