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,8 @@
1
+ """Agentic Authorization SDK. Distributed as ``authzai``; see ``pyproject.toml`` for the
2
+ install options and what each one makes importable.
3
+
4
+ Imports nothing: ``import agentic_auth`` must work from the base install, which has only
5
+ ``pyjwt[crypto]``.
6
+ """
7
+
8
+ __version__ = "0.2.0"
@@ -0,0 +1,24 @@
1
+ """Name the missing install option instead of failing three imports deep.
2
+
3
+ ``authzai`` ships one wheel with optional dependency sets (see ``pyproject.toml``). Importing a
4
+ surface whose set is not installed would otherwise raise ``No module named 'fastapi'`` from a
5
+ module the integrator never imported directly, which reads as a broken package rather than a
6
+ missing ``pip install 'authzai[server]'``. The message format is fixed by
7
+ contracts/packaging.md and asserted by ``tests/packaging/test_missing_extra.py``.
8
+
9
+ Stdlib only: this runs before any optional dependency is known to be present.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import importlib.util
15
+
16
+
17
+ def require_extra(module: str, extra: str, *dependencies: str) -> None:
18
+ """Raise ``ImportError`` naming ``extra`` if any of ``dependencies`` is not importable."""
19
+ for dependency in dependencies:
20
+ if importlib.util.find_spec(dependency) is None:
21
+ raise ImportError(
22
+ f"{module} needs the '{extra}' extra: pip install 'authzai[{extra}]'",
23
+ name=dependency,
24
+ )
File without changes
@@ -0,0 +1,112 @@
1
+ """FastAPI dependencies: admin auth, DB session, pagination."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hmac
6
+ from typing import Annotated
7
+
8
+ from fastapi import Depends, Header, Query
9
+ from sqlalchemy.ext.asyncio import AsyncSession
10
+
11
+ from agentic_auth.config import get_settings
12
+ from agentic_auth.db import get_session
13
+ from agentic_auth.errors import UnauthorizedError
14
+ from agentic_auth.schemas.common import DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT, PaginationParams
15
+ from agentic_auth.services.tokens.profile import VerifiedToken
16
+
17
+
18
+ async def require_admin(authorization: Annotated[str | None, Header()] = None) -> None:
19
+ expected = get_settings().admin_token
20
+ if not authorization or not authorization.startswith("Bearer "):
21
+ raise UnauthorizedError("missing or malformed admin bearer token")
22
+ token = authorization.removeprefix("Bearer ").strip()
23
+ # Constant-time: `!=` stops at the first differing byte, which leaks how much of the
24
+ # token was guessed correctly to anyone who can time the response.
25
+ if not hmac.compare_digest(token.encode(), expected.encode()):
26
+ raise UnauthorizedError("invalid admin bearer token")
27
+
28
+
29
+ async def require_audit_reader(authorization: Annotated[str | None, Header()] = None) -> None:
30
+ """Audit data is readable with the dedicated reader token or the admin token.
31
+
32
+ An auditor should never need the credential that can register manifests or record
33
+ consent, so ``AGENTIC_AUTH_AUDIT_READ_TOKEN`` exists; the admin token keeps working. An
34
+ empty reader setting disables that token rather than accepting an empty bearer.
35
+ """
36
+ if not authorization or not authorization.startswith("Bearer "):
37
+ raise UnauthorizedError("missing or malformed audit reader bearer token")
38
+ presented = authorization.removeprefix("Bearer ").strip().encode()
39
+ settings = get_settings()
40
+ accepted = [t.encode() for t in (settings.audit_read_token, settings.admin_token) if t]
41
+ # Compare against every accepted token, not just until the first match, so timing does
42
+ # not reveal which one was presented.
43
+ matches = [hmac.compare_digest(presented, token) for token in accepted]
44
+ if not presented or not any(matches):
45
+ raise UnauthorizedError("invalid audit reader bearer token")
46
+
47
+
48
+ async def require_enroller(authorization: Annotated[str | None, Header()] = None) -> None:
49
+ """Enrollment is begun and completed with the dedicated enroller token or the admin
50
+ token. An empty enroller setting disables that token, never accepts an empty bearer."""
51
+ if not authorization or not authorization.startswith("Bearer "):
52
+ raise UnauthorizedError("missing or malformed enroller bearer token")
53
+ presented = authorization.removeprefix("Bearer ").strip().encode()
54
+ settings = get_settings()
55
+ accepted = [t.encode() for t in (settings.enroll_token, settings.admin_token) if t]
56
+ # Compare against every accepted token, not just until the first match, so timing does
57
+ # not reveal which one was presented.
58
+ matches = [hmac.compare_digest(presented, token) for token in accepted]
59
+ if not presented or not any(matches):
60
+ raise UnauthorizedError("invalid enroller bearer token")
61
+
62
+
63
+ async def require_identity_reader(authorization: Annotated[str | None, Header()] = None) -> None:
64
+ """Identity material and the revocation list are readable by verifiers and operators:
65
+ the audit reader token or the admin token."""
66
+ if not authorization or not authorization.startswith("Bearer "):
67
+ raise UnauthorizedError("missing or malformed identity reader bearer token")
68
+ presented = authorization.removeprefix("Bearer ").strip().encode()
69
+ settings = get_settings()
70
+ accepted = [t.encode() for t in (settings.audit_read_token, settings.admin_token) if t]
71
+ matches = [hmac.compare_digest(presented, token) for token in accepted]
72
+ if not presented or not any(matches):
73
+ raise UnauthorizedError("invalid identity reader bearer token")
74
+
75
+
76
+ def pagination_params(
77
+ limit: int = Query(default=DEFAULT_PAGE_LIMIT, ge=1, le=MAX_PAGE_LIMIT),
78
+ cursor: str | None = Query(default=None),
79
+ ) -> PaginationParams:
80
+ return PaginationParams(limit=limit, cursor=cursor)
81
+
82
+
83
+ async def presented_token(
84
+ authorization: Annotated[str | None, Header()] = None,
85
+ ) -> VerifiedToken:
86
+ """Verify the caller's current hop token before a single claim is read.
87
+
88
+ Returns a :class:`VerifiedToken`, never a raw string, so downstream code has no way
89
+ to reach an unverified claim. Every failure is a rejection — there is no path here
90
+ that yields a partially trusted token.
91
+ """
92
+ from agentic_auth.api.service_deps import get_token_profile
93
+ from agentic_auth.services.tokens.jwt_profile import TokenVerificationError
94
+
95
+ if not authorization or not authorization.startswith("Bearer "):
96
+ raise UnauthorizedError("missing or malformed bearer token")
97
+ raw = authorization.removeprefix("Bearer ").strip()
98
+ try:
99
+ # Audience is checked against the concrete target by the caller of this
100
+ # dependency, which knows what is being called; here we establish authenticity.
101
+ return get_token_profile().verify(raw)
102
+ except TokenVerificationError as exc:
103
+ raise UnauthorizedError(f"token rejected: {exc}") from exc
104
+
105
+
106
+ SessionDep = Annotated[AsyncSession, Depends(get_session)]
107
+ PresentedTokenDep = Annotated[VerifiedToken, Depends(presented_token)]
108
+ AdminDep = Depends(require_admin)
109
+ AuditReaderDep = Depends(require_audit_reader)
110
+ EnrollerDep = Depends(require_enroller)
111
+ IdentityReaderDep = Depends(require_identity_reader)
112
+ PaginationDep = Annotated[PaginationParams, Depends(pagination_params)]
@@ -0,0 +1,51 @@
1
+ """Exception handlers that render the standard error envelope."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import FastAPI, Request
6
+ from fastapi.exceptions import RequestValidationError
7
+ from fastapi.responses import JSONResponse
8
+
9
+ from agentic_auth.errors import DomainError
10
+ from agentic_auth.services.tokens.exchange import ExchangeRefused
11
+
12
+
13
+ def _envelope(code: str, message: str, details: dict | None = None) -> dict:
14
+ body: dict = {"error": {"code": code, "message": message}}
15
+ if details is not None:
16
+ body["error"]["details"] = details
17
+ return body
18
+
19
+
20
+ async def _domain_handler(_: Request, exc: DomainError) -> JSONResponse:
21
+ return JSONResponse(
22
+ status_code=exc.status_code,
23
+ content=_envelope(exc.code, exc.message, exc.details),
24
+ )
25
+
26
+
27
+ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONResponse:
28
+ fields = [{"loc": [str(p) for p in err["loc"]], "msg": err["msg"]} for err in exc.errors()]
29
+ return JSONResponse(
30
+ status_code=422,
31
+ content=_envelope("validation_error", "request validation failed", {"fields": fields}),
32
+ )
33
+
34
+
35
+ async def _oauth_handler(_: Request, exc: ExchangeRefused) -> JSONResponse:
36
+ """RFC 6749 §5.2 error body — the token endpoint speaks OAuth, not our envelope.
37
+
38
+ Registered app-wide rather than caught in the route because the grant grammar is
39
+ validated in a dependency, which runs before the handler body.
40
+ """
41
+ status = 403 if exc.oauth_error == "invalid_target" else 400
42
+ return JSONResponse(
43
+ status_code=status,
44
+ content={"error": exc.oauth_error, "error_description": exc.description},
45
+ )
46
+
47
+
48
+ def register_error_handlers(app: FastAPI) -> None:
49
+ app.add_exception_handler(DomainError, _domain_handler) # type: ignore[arg-type]
50
+ app.add_exception_handler(RequestValidationError, _validation_handler) # type: ignore[arg-type]
51
+ app.add_exception_handler(ExchangeRefused, _oauth_handler) # type: ignore[arg-type]
@@ -0,0 +1,38 @@
1
+ """Shared helpers for rendering process outcomes to HTTP responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi.responses import JSONResponse
6
+
7
+ from agentic_auth.services.manifest_service import ProcessOutcome
8
+
9
+
10
+ def _envelope(code: str, message: str, details: dict | None = None) -> dict:
11
+ body: dict = {"error": {"code": code, "message": message}}
12
+ if details is not None:
13
+ body["error"]["details"] = details
14
+ return body
15
+
16
+
17
+ def render_outcome(outcome: ProcessOutcome, *, created_key: dict) -> JSONResponse:
18
+ """``created_key`` is the 201 body (already JSON-serializable)."""
19
+ if outcome.http_status == 201:
20
+ return JSONResponse(status_code=201, content=created_key)
21
+ if outcome.http_status == 422:
22
+ return JSONResponse(
23
+ status_code=422,
24
+ content=_envelope(
25
+ "reconciliation_rejected",
26
+ "manifest declares capabilities that exceed or conflict with what is discoverable",
27
+ {"diff": outcome.diff},
28
+ ),
29
+ )
30
+ # 409
31
+ return JSONResponse(
32
+ status_code=409,
33
+ content=_envelope(
34
+ "needs_review",
35
+ "capability discovery was unavailable; resubmit with an override reason to proceed",
36
+ {"diff": outcome.diff},
37
+ ),
38
+ )
@@ -0,0 +1,113 @@
1
+ """Dependency wiring for the manifest service (overridden in tests)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator
6
+ from functools import lru_cache
7
+ from typing import Annotated
8
+
9
+ from fastapi import Depends
10
+ from redis.asyncio import Redis
11
+
12
+ from agentic_auth import runtime
13
+ from agentic_auth.config import get_settings
14
+ from agentic_auth.redis import get_redis
15
+ from agentic_auth.services.anchors import AnchorCache
16
+ from agentic_auth.services.audit import AuditService
17
+ from agentic_auth.services.chain_query import ChainQueryService
18
+ from agentic_auth.services.discovery import DiscoveryClient
19
+ from agentic_auth.services.enrollment import EnrollmentService
20
+ from agentic_auth.services.manifest_service import ManifestService
21
+ from agentic_auth.services.principal import PrincipalBinder
22
+ from agentic_auth.services.revocation import RevocationService
23
+ from agentic_auth.services.sessions import SessionService
24
+ from agentic_auth.services.tokens.exchange import TokenExchangeService
25
+ from agentic_auth.services.tokens.jwt_profile import JwtTokenProfile
26
+ from agentic_auth.services.tokens.profile import TokenProfile
27
+ from agentic_auth.services.transactions import TransactionService
28
+
29
+
30
+ async def get_manifest_service() -> AsyncIterator[ManifestService]:
31
+ settings = get_settings()
32
+ current = runtime.override()
33
+ # An embedded instance discovers capabilities through its own in-process transport.
34
+ discovery = (
35
+ DiscoveryClient(client=current.http)
36
+ if current is not None
37
+ else DiscoveryClient(timeout=settings.discovery_timeout_seconds)
38
+ )
39
+ try:
40
+ yield ManifestService(discovery=discovery)
41
+ finally:
42
+ await discovery.aclose()
43
+
44
+
45
+ def get_redis_dep() -> Redis:
46
+ return get_redis()
47
+
48
+
49
+ def get_token_profile() -> TokenProfile:
50
+ """One profile per control plane: the process's, or an embedded instance's own."""
51
+ current = runtime.override()
52
+ if current is None:
53
+ return _process_token_profile()
54
+ if current._token_profile is None:
55
+ current._token_profile = JwtTokenProfile()
56
+ profile: TokenProfile = current._token_profile
57
+ return profile
58
+
59
+
60
+ @lru_cache
61
+ def _process_token_profile() -> TokenProfile:
62
+ """One issuer key per process — regenerating per request would invalidate every
63
+ token already in flight."""
64
+ return JwtTokenProfile()
65
+
66
+
67
+ def get_session_service() -> SessionService:
68
+ return SessionService(tokens=get_token_profile())
69
+
70
+
71
+ def get_token_exchange_service() -> TokenExchangeService:
72
+ return TokenExchangeService(tokens=get_token_profile(), sessions=get_session_service())
73
+
74
+
75
+ def get_transaction_service() -> TransactionService:
76
+ return TransactionService(tokens=get_token_profile(), sessions=get_session_service())
77
+
78
+
79
+ def get_anchor_cache(redis: Redis = Depends(get_redis_dep)) -> AnchorCache: # noqa: B008
80
+ return AnchorCache(redis)
81
+
82
+
83
+ def get_enrollment_service(
84
+ anchors: AnchorCache = Depends(get_anchor_cache), # noqa: B008
85
+ ) -> EnrollmentService:
86
+ return EnrollmentService(binder=PrincipalBinder(), anchors=anchors)
87
+
88
+
89
+ def get_revocation_service(
90
+ anchors: AnchorCache = Depends(get_anchor_cache), # noqa: B008
91
+ ) -> RevocationService:
92
+ return RevocationService(anchors)
93
+
94
+
95
+ def get_audit_service() -> AuditService:
96
+ return AuditService()
97
+
98
+
99
+ def get_chain_query_service() -> ChainQueryService:
100
+ return ChainQueryService()
101
+
102
+
103
+ ManifestServiceDep = Annotated[ManifestService, Depends(get_manifest_service)]
104
+ RedisDep = Annotated[Redis, Depends(get_redis_dep)]
105
+ TokenProfileDep = Annotated[TokenProfile, Depends(get_token_profile)]
106
+ SessionServiceDep = Annotated[SessionService, Depends(get_session_service)]
107
+ TokenExchangeServiceDep = Annotated[TokenExchangeService, Depends(get_token_exchange_service)]
108
+ AuditServiceDep = Annotated[AuditService, Depends(get_audit_service)]
109
+ TransactionServiceDep = Annotated[TransactionService, Depends(get_transaction_service)]
110
+ AnchorCacheDep = Annotated[AnchorCache, Depends(get_anchor_cache)]
111
+ EnrollmentServiceDep = Annotated[EnrollmentService, Depends(get_enrollment_service)]
112
+ RevocationServiceDep = Annotated[RevocationService, Depends(get_revocation_service)]
113
+ ChainQueryServiceDep = Annotated[ChainQueryService, Depends(get_chain_query_service)]
File without changes
@@ -0,0 +1,88 @@
1
+ """``/v1/agents`` — registration, listing, reconciliation reports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from typing import Annotated
7
+
8
+ from fastapi import APIRouter, Query, Response
9
+
10
+ from agentic_auth.api.deps import AdminDep, PaginationDep, SessionDep
11
+ from agentic_auth.api.responses import render_outcome
12
+ from agentic_auth.api.service_deps import ManifestServiceDep, RedisDep
13
+ from agentic_auth.errors import NotFoundError
14
+ from agentic_auth.repositories import agents as agents_repo
15
+ from agentic_auth.repositories import reconciliation_reports as reports_repo
16
+ from agentic_auth.schemas.agent import AgentCreate, AgentListItem, AgentStatus
17
+ from agentic_auth.schemas.common import Page, PageInfo
18
+ from agentic_auth.schemas.reconciliation import ReconciliationReport
19
+
20
+ router = APIRouter(prefix="/v1", tags=["agents"], dependencies=[AdminDep])
21
+
22
+ ADMIN_IDENTITY = "admin"
23
+
24
+
25
+ @router.post("/agents")
26
+ async def register_agent(
27
+ body: AgentCreate,
28
+ session: SessionDep,
29
+ service: ManifestServiceDep,
30
+ redis: RedisDep,
31
+ ) -> Response:
32
+ outcome = await service.register_agent(
33
+ session,
34
+ redis,
35
+ name=body.name,
36
+ manifest=body.manifest,
37
+ attested_by=ADMIN_IDENTITY,
38
+ override=body.override,
39
+ )
40
+ return render_outcome(
41
+ outcome,
42
+ created_key={
43
+ "agent_id": str(outcome.agent_id),
44
+ "manifest_version": outcome.version,
45
+ "status": outcome.status,
46
+ },
47
+ )
48
+
49
+
50
+ @router.get("/agents", response_model=Page[AgentListItem])
51
+ async def list_agents(
52
+ session: SessionDep,
53
+ pagination: PaginationDep,
54
+ status: Annotated[AgentStatus | None, Query()] = None,
55
+ ) -> Page[AgentListItem]:
56
+ rows, next_cursor = await agents_repo.list_page(
57
+ session, pagination.limit, pagination.cursor, status=status
58
+ )
59
+ latest = await agents_repo.latest_versions(session, [a.id for a in rows])
60
+ items = [
61
+ AgentListItem(
62
+ id=a.id,
63
+ name=a.name,
64
+ status=a.status,
65
+ trust_anchor_version=a.trust_anchor_version,
66
+ latest_manifest_version=latest.get(a.id, (None, None))[0],
67
+ latest_status=latest.get(a.id, (None, None))[1],
68
+ )
69
+ for a in rows
70
+ ]
71
+ return Page(data=items, page=PageInfo(next_cursor=next_cursor, limit=pagination.limit))
72
+
73
+
74
+ @router.get("/agents/{agent_id}/reconciliation", response_model=ReconciliationReport)
75
+ async def get_reconciliation(agent_id: uuid.UUID, session: SessionDep) -> ReconciliationReport:
76
+ agent = await agents_repo.get_by_id(session, agent_id)
77
+ if agent is None:
78
+ raise NotFoundError(f"agent {agent_id} not found")
79
+ found = await reports_repo.get_latest_for_agent(session, agent_id)
80
+ if found is None:
81
+ raise NotFoundError(f"agent {agent_id} has no manifest submission yet")
82
+ report, manifest = found
83
+ return ReconciliationReport(
84
+ manifest_version=manifest.version,
85
+ status=manifest.status,
86
+ discovery_ok=report.discovery_ok,
87
+ diff=report.diff,
88
+ )
@@ -0,0 +1,67 @@
1
+ """``/v1/audit`` — the read-only audit plane.
2
+
3
+ Every route requires an audit-reader bearer (the dedicated reader token or the admin token).
4
+ No route here writes: audit rows are created only by the decision path, and the database
5
+ refuses to change them afterwards.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import uuid
11
+ from typing import Annotated
12
+
13
+ from fastapi import APIRouter, Query
14
+
15
+ from agentic_auth.api.deps import AuditReaderDep, PaginationDep, SessionDep
16
+ from agentic_auth.api.service_deps import ChainQueryServiceDep
17
+ from agentic_auth.schemas.audit import AuditDecisionPage, ChainRead
18
+ from agentic_auth.services.decision_history import history_page
19
+
20
+ router = APIRouter(prefix="/v1/audit", tags=["audit"], dependencies=[AuditReaderDep])
21
+
22
+ # Filters are accepted as strings and validated together in the service, so a bad value
23
+ # and a bad combination produce the same error shape.
24
+ OptionalQuery = Annotated[str | None, Query()]
25
+
26
+
27
+ @router.get("/actions/{action_id}/chain", response_model=ChainRead)
28
+ async def get_chain(
29
+ action_id: uuid.UUID, db: SessionDep, chains: ChainQueryServiceDep
30
+ ) -> ChainRead:
31
+ """The full delegation chain for one recorded action, back to the consenting human."""
32
+ return await chains.get(db, action_id)
33
+
34
+
35
+ @router.get("/decisions", response_model=AuditDecisionPage)
36
+ async def list_decisions(
37
+ db: SessionDep,
38
+ pagination: PaginationDep,
39
+ session_id: OptionalQuery = None,
40
+ agent: OptionalQuery = None,
41
+ outcome: OptionalQuery = None,
42
+ deny_reason: OptionalQuery = None,
43
+ enforced: OptionalQuery = None,
44
+ target_kind: OptionalQuery = None,
45
+ since: OptionalQuery = None,
46
+ until: OptionalQuery = None,
47
+ taint: OptionalQuery = None,
48
+ privileged: OptionalQuery = None,
49
+ ) -> AuditDecisionPage:
50
+ """Filtered decision history, newest first, stable under concurrent appends."""
51
+ return await history_page(
52
+ db,
53
+ raw_filters={
54
+ "session_id": session_id,
55
+ "agent": agent,
56
+ "outcome": outcome,
57
+ "deny_reason": deny_reason,
58
+ "enforced": enforced,
59
+ "target_kind": target_kind,
60
+ "since": since,
61
+ "until": until,
62
+ "taint": taint,
63
+ "privileged": privileged,
64
+ },
65
+ limit=pagination.limit,
66
+ cursor=pagination.cursor,
67
+ )