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
agentic_auth/config.py ADDED
@@ -0,0 +1,182 @@
1
+ """Runtime configuration, loaded from the environment (prefix ``AGENTIC_AUTH_``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import lru_cache
6
+
7
+ from pydantic_settings import BaseSettings, SettingsConfigDict
8
+
9
+ from agentic_auth import runtime
10
+
11
+
12
+ class Settings(BaseSettings):
13
+ model_config = SettingsConfigDict(
14
+ env_prefix="AGENTIC_AUTH_",
15
+ env_file=".env",
16
+ extra="ignore",
17
+ )
18
+
19
+ database_url: str = "postgresql+asyncpg://app:app@localhost:5432/agentic_auth"
20
+ redis_url: str = "redis://localhost:6379/0"
21
+ admin_token: str = "dev-admin-token"
22
+ discovery_timeout_seconds: float = 5.0
23
+
24
+ # -- runtime plane -------------------------------------------
25
+ issuer: str = "agentic-auth"
26
+ # Ed25519 private key, PEM. Empty in dev -> an ephemeral key is generated at
27
+ # startup and logged as ephemeral. Never leave this empty in production.
28
+ issuer_private_key: str = ""
29
+ issuer_kid: str = ""
30
+ hop_token_ttl_seconds: int = 60
31
+ session_ttl_seconds: int = 1800
32
+ decision_cache_ttl_seconds: int = 30
33
+
34
+ # -- audit plane ---------------------------------------------
35
+ # A read-only bearer for the audit endpoints, so an auditor never needs the admin
36
+ # token that can register manifests or record consent. Empty disables it; the admin
37
+ # token is always accepted.
38
+ audit_read_token: str = ""
39
+ # Bound on the audit append + commit. An allow whose record cannot be committed in
40
+ # this window is refused rather than dispatched without a record.
41
+ audit_write_timeout_seconds: float = 1.0
42
+ metrics_enabled: bool = True
43
+
44
+ # -- Phase 4: three independent controls ---------------
45
+ # Each is gated so an integrator adopts the sidecar + token-exchange core first and
46
+ # layers the rest on. With all three off, Phase 1-3 behaviour is unchanged.
47
+ #
48
+ # transaction_tokens_enabled: privileged tool calls need a call-bound transaction token
49
+ # (POST /v1/token/transaction). Off -> the route answers 404, decisions report
50
+ # transaction_required=false, the sidecar and SDK never buffer or mint.
51
+ # taint_enforcement_enabled: TAINTED_INTO_PRIVILEGED is returned. Off -> taint is still
52
+ # derived, propagated and RECORDED so operators can tune before enforcing.
53
+ # identity_required: the exchange requires an actor_token signed by the holder's pinned
54
+ # key, and refuses agents without a live trust anchor (AGENT_NOT_ENROLLED). Off by
55
+ # default because it refuses every agent that has not enrolled.
56
+ transaction_tokens_enabled: bool = True
57
+ taint_enforcement_enabled: bool = True
58
+ identity_required: bool = False
59
+
60
+ # Transaction-token lifetime, seconds. One privileged call, minted right before it.
61
+ transaction_token_ttl_seconds: int = 30
62
+ # Largest request body the sidecar / mint will canonicalize for binding. Over the cap is
63
+ # refused, never forwarded unbound.
64
+ max_privileged_body_bytes: int = 1_048_576
65
+
66
+ # -- Phase 4: identity ------------------------------------------------------
67
+ # Bearer that may begin/complete enrollment. Empty disables it; admin always works.
68
+ enroll_token: str = ""
69
+ enroll_challenge_ttl_seconds: int = 120
70
+ # The organization's human IdP, for principal binding. All
71
+ # three empty -> every completion is quarantined with PRINCIPAL_IDP_NOT_CONFIGURED.
72
+ principal_idp_issuer: str = ""
73
+ principal_idp_jwks_url: str = ""
74
+ principal_idp_audience: str = ""
75
+ # The ID-token claim that must equal "agent://<name>".
76
+ principal_binding_claim: str = "agent"
77
+ # How long an offline verifier may go without refreshing revocation state before it
78
+ # refuses every identity as stale.
79
+ revocation_freshness_seconds: int = 30
80
+
81
+ # -- Phase 5: four independent workstreams ---------------
82
+ # Same discipline as Phase 4: each control is gated, every default reproduces Phase 4
83
+ # behaviour, and an integrator adopts the gateway, a boundary mode, step-up and cold
84
+ # start in any order. With all of these off, Phase 1-4 behaviour is unchanged.
85
+ #
86
+ # consent_granularity_enabled: a session may consent to a SUBSET of the data classes its
87
+ # pinned policy declares. Off -> the consented set is the declared set, which is
88
+ # exactly Phase 2-4 semantics, and ConsentCreate.data_classes is rejected.
89
+ # This is what makes SCOPE_NOT_CONSENTED mean what its name says: with it off, that
90
+ # reason fires only for a data class the pinned policy never declared, which step-up
91
+ # must never grant.
92
+ # step_up_enabled: a recoverable deny returns a challenge instead of a hard failure, and
93
+ # /v1/consent/step-up* are routed. Off -> those routes answer 404 and no decision
94
+ # carries a challenge.
95
+ # sandbox_enabled: /v1/agents/{id}/sandbox* are routed. Off -> 404.
96
+ consent_granularity_enabled: bool = False
97
+ step_up_enabled: bool = False
98
+ sandbox_enabled: bool = False
99
+
100
+ # How long a step-up challenge may go unanswered. Consumed with GETDEL, so a second
101
+ # answer fails even inside the window.
102
+ step_up_challenge_ttl_seconds: int = 300
103
+ # A sandbox observation run ends here whether or not the agent stopped, and the
104
+ # proposal covers what was observed up to that point.
105
+ sandbox_run_deadline_seconds: int = 300
106
+ # Bound on the gateway's decision. Past it the call is REFUSED, never retried: a slow
107
+ # decision is no decision. Matches the sidecar's control_plane_timeout_seconds
108
+ # so the gateway is not less available than a sidecar against the same control plane.
109
+ gateway_decision_deadline_ms: int = 2000
110
+ # What the control plane records when an enforcement point predates the guarantee
111
+ # field. Every such caller was per-hop, so `full` is accurate rather than a guess.
112
+ default_guarantee_level: str = "full"
113
+
114
+ # -- Phase 6: observability ------------------------------------
115
+ # Off by default, so a Phase 1-5 deployment sees no change at all. When off, nothing is
116
+ # exported, `agentic_auth.observability` never imports the OpenTelemetry SDK, and the existing
117
+ # `/metrics` surface behaves exactly as before.
118
+ #
119
+ # telemetry_key is REQUIRED when telemetry is enabled. It keys both the identity
120
+ # pseudonyms and the session-derived trace ids. Missing -> the exporter refuses to start
121
+ # and logs once; the component still serves traffic. There is deliberately no fallback to
122
+ # plaintext and none to an unkeyed digest: agent names are a small, enumerable space, so an
123
+ # unkeyed digest is recovered by brute force by anyone holding the telemetry.
124
+ #
125
+ # telemetry_identity_disclosure: export real agent names and the act chain instead of
126
+ # pseudonyms. Off by default; its state is itself exported as a gauge so an organization can
127
+ # alert on any deployment that has it on. Metrics are unaffected either way — "labels never
128
+ # carry identities" is absolute and has no opt-in.
129
+ #
130
+ # telemetry_allow_sample_ratio: the fraction of ALLOW spans kept. Refusals ignore it
131
+ # entirely -- a denied, fail-closed, taint-blocked or unrecorded decision is always kept.
132
+ telemetry_enabled: bool = False
133
+ telemetry_key: str = ""
134
+ telemetry_identity_disclosure: bool = False
135
+ telemetry_allow_sample_ratio: float = 1.0
136
+
137
+ def model_post_init(self, _context: object) -> None:
138
+ """Refuse a configuration that cannot do what it claims.
139
+
140
+ Step-up without consent granularity is the one combination that is not merely
141
+ unusual but incoherent: the only recoverable deny reason is SCOPE_NOT_CONSENTED,
142
+ and without granularity that reason fires only for a data class the pinned policy
143
+ never declared — which a consent prompt must never grant. The endpoints
144
+ would answer every request correctly and grant nothing, forever. Refusing at
145
+ startup is cheaper than discovering that in production.
146
+ """
147
+ if self.step_up_enabled and not self.consent_granularity_enabled:
148
+ raise ValueError(
149
+ "step_up_enabled requires consent_granularity_enabled: without it the only "
150
+ "recoverable deny reason (SCOPE_NOT_CONSENTED) fires only for a data class "
151
+ "the pinned policy never declared, which step-up may never grant. Set "
152
+ "AGENTIC_AUTH_CONSENT_GRANULARITY_ENABLED=true, or turn step-up off."
153
+ )
154
+
155
+ # NOTE: there is deliberately no server-side observe-mode setting. The PDP is
156
+ # mode-blind — it always decides honestly and always records — so it cannot be a
157
+ # deployment-wide kill switch. Observe mode belongs to the enforcement point, which
158
+ # is the only component that knows whether it will act on a deny:
159
+ # AGENTIC_AUTH_SIDECAR_OBSERVE_MODE, per sidecar. A server-side flag here would read
160
+ # as fleet-wide while changing nothing, and would make `false` look like "enforcement
161
+ # is on" while a sidecar was still forwarding denied calls.
162
+ #
163
+ # The same reasoning rules out a server-side telemetry observe-mode flag. Each enforcement
164
+ # point configures its own telemetry under AGENTIC_AUTH_SIDECAR_TELEMETRY_*; a setting here
165
+ # that read as fleet-wide while changing nothing in a sidecar's process would be worse than
166
+ # no setting at all.
167
+
168
+
169
+ @lru_cache
170
+ def _environment_settings() -> Settings:
171
+ return Settings()
172
+
173
+
174
+ def get_settings() -> Settings:
175
+ """This process's settings, from the environment — or, inside an embedded control
176
+ plane's request, that instance's own (agentic_auth/runtime.py)."""
177
+ current = runtime.override()
178
+ return current.settings if current is not None else _environment_settings()
179
+
180
+
181
+ # Tests and the notebook reset the environment-derived settings between scenarios.
182
+ get_settings.cache_clear = _environment_settings.cache_clear # type: ignore[attr-defined]
agentic_auth/db.py ADDED
@@ -0,0 +1,49 @@
1
+ """Async SQLAlchemy engine and session factory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator
6
+
7
+ from sqlalchemy.ext.asyncio import (
8
+ AsyncEngine,
9
+ AsyncSession,
10
+ async_sessionmaker,
11
+ create_async_engine,
12
+ )
13
+
14
+ from agentic_auth import runtime
15
+ from agentic_auth.config import get_settings
16
+
17
+ _engine: AsyncEngine | None = None
18
+ _sessionmaker: async_sessionmaker[AsyncSession] | None = None
19
+
20
+
21
+ def get_engine() -> AsyncEngine:
22
+ current = runtime.override()
23
+ if current is not None:
24
+ return current.engine
25
+ global _engine
26
+ if _engine is None:
27
+ _engine = create_async_engine(get_settings().database_url, future=True)
28
+ return _engine
29
+
30
+
31
+ def get_sessionmaker() -> async_sessionmaker[AsyncSession]:
32
+ current = runtime.override()
33
+ if current is not None:
34
+ return current.sessionmaker
35
+ global _sessionmaker
36
+ if _sessionmaker is None:
37
+ _sessionmaker = async_sessionmaker(get_engine(), expire_on_commit=False, autoflush=False)
38
+ return _sessionmaker
39
+
40
+
41
+ async def get_session() -> AsyncIterator[AsyncSession]:
42
+ """FastAPI dependency: a session that commits on success, rolls back on error."""
43
+ async with get_sessionmaker()() as session:
44
+ try:
45
+ yield session
46
+ await session.commit()
47
+ except Exception:
48
+ await session.rollback()
49
+ raise
@@ -0,0 +1,427 @@
1
+ """The whole control plane inside your process, for development and testing.
2
+
3
+ from agentic_auth.embedded import EmbeddedControlPlane
4
+
5
+ async with EmbeddedControlPlane.open("manifests/", override_reason="local") as cp:
6
+ client = cp.client()
7
+ session = await client.consent(scope="bank-assistant", user_sub="user:alice")
8
+ ...
9
+
10
+ This is the real control plane, not a model of it: the same FastAPI app, routes, PDP, token
11
+ profile and audit writer as a deployment, reached through an in-process transport instead of
12
+ a socket, on SQLite instead of PostgreSQL and an in-process Redis instead of a server.
13
+ ``cp.client()`` returns the same ``AgenticAuthClient`` you would point at a deployed control
14
+ plane, so moving between the two changes only how the client is constructed. The conformance
15
+ suite (tests/conformance) holds the two to identical decisions.
16
+
17
+ **Development and testing only.** The signing keys and the policy decision point run in the
18
+ same process as the agent they constrain, so the agent's own code could reach the keys that
19
+ grant its authority. Every instance says so when it starts, and every decision it records
20
+ carries ``deployment: embedded``. Deploy the control plane — with the sidecar, gateway or
21
+ boundary adapter in front of your agents — for anything real.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from agentic_auth._extras import require_extra
27
+
28
+ require_extra(
29
+ "agentic_auth.embedded", "embedded", "fastapi", "sqlalchemy", "aiosqlite", "fakeredis"
30
+ )
31
+
32
+ import logging
33
+ import os
34
+ import secrets
35
+ from collections.abc import Iterable, Mapping, Sequence
36
+ from pathlib import Path
37
+ from types import TracebackType
38
+ from typing import Any
39
+
40
+ import httpx
41
+ import yaml
42
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
43
+ from fakeredis import FakeServer
44
+ from fakeredis.aioredis import FakeRedis
45
+ from prometheus_client import CollectorRegistry
46
+
47
+ from agentic_auth.config import Settings
48
+ from agentic_auth.embedded import idp as _idp
49
+ from agentic_auth.embedded._transport import CAPABILITIES, HostRouter
50
+ from agentic_auth.embedded.capabilities import capability_app
51
+ from agentic_auth.embedded.store import (
52
+ MEMORY,
53
+ StoreHandle,
54
+ StoreLocked,
55
+ StoreVersionMismatch,
56
+ open_store,
57
+ remember_issuer_key,
58
+ )
59
+ from agentic_auth.runtime import Runtime, use_runtime
60
+ from agentic_auth.schemas.manifest import AgentManifest
61
+ from agentic_auth.sdk import AgenticAuthClient, AgentKey, HttpAnchors, HttpJwks, InMemoryReplay
62
+ from agentic_auth.sdk.errors import ManifestRejected, PolicyDenied
63
+ from agentic_auth.services.metrics import build_control_plane_metrics
64
+ from agentic_auth.services.tokens.keys import IssuerKey, _thumbprint, load_or_generate
65
+ from agentic_auth.verify import Verifier
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+ HOST = "control-plane.embedded.invalid"
70
+ BASE_URL = f"http://{HOST}"
71
+
72
+ BANNER = (
73
+ "embedded control plane: development and testing only — signing keys and policy "
74
+ "decisions run inside this process (store={store})"
75
+ )
76
+
77
+
78
+ class _EmbeddedSettings(Settings):
79
+ """Settings from constructor arguments only. An embedded instance must never pick up
80
+ the host process's AGENTIC_AUTH_* environment, which may belong to a real deployment."""
81
+
82
+ @classmethod
83
+ def settings_customise_sources( # type: ignore[override]
84
+ cls, settings_cls: type[Settings], init_settings: Any, **_: Any
85
+ ) -> tuple[Any, ...]:
86
+ return (init_settings,)
87
+
88
+
89
+ ManifestSource = (
90
+ str | os.PathLike[str] | Sequence[str | os.PathLike[str]] | Mapping[str, Mapping[str, Any]]
91
+ )
92
+
93
+
94
+ def _manifests_from(sources: ManifestSource) -> dict[str, AgentManifest]:
95
+ """Files or directories of YAML/JSON manifests (the formats the CLI and drift check
96
+ take), or manifest documents keyed by agent name."""
97
+ from agentic_auth.services.drift import load_manifest_dirs
98
+
99
+ if isinstance(sources, Mapping):
100
+ return {name: AgentManifest.model_validate(doc) for name, doc in sources.items()}
101
+ paths = [sources] if isinstance(sources, (str, os.PathLike)) else list(sources)
102
+ found: dict[str, AgentManifest] = {}
103
+ for raw in paths:
104
+ path = Path(raw)
105
+ if path.is_dir():
106
+ loaded = load_manifest_dirs([path])
107
+ if loaded.errors:
108
+ details = "; ".join(f"{e.code} {e.path or ''} {e.message}" for e in loaded.errors)
109
+ raise ValueError(f"could not load manifests from {path}: {details}")
110
+ found.update(loaded.manifests)
111
+ else:
112
+ manifest = AgentManifest.model_validate(yaml.safe_load(path.read_text("utf-8")))
113
+ found[manifest.metadata.agent] = manifest
114
+ return found
115
+
116
+
117
+ class EmbeddedControlPlane:
118
+ """One self-contained control plane: its own keys, store, sessions and audit log."""
119
+
120
+ deployment = "embedded"
121
+
122
+ def __init__(
123
+ self,
124
+ *,
125
+ runtime: Runtime,
126
+ store: StoreHandle,
127
+ router: HostRouter,
128
+ idp: _idp.TestIdp,
129
+ ) -> None:
130
+ self._runtime = runtime
131
+ self._store = store
132
+ self._router = router
133
+ self._idp = idp
134
+ self._closed = False
135
+
136
+ # -- lifecycle -------------------------------------------------------------------
137
+
138
+ @classmethod
139
+ def open(
140
+ cls,
141
+ manifests: ManifestSource | None = None,
142
+ *,
143
+ store: str | os.PathLike[str] = MEMORY,
144
+ override_reason: str | None = None,
145
+ capabilities: Mapping[str, Mapping[str, Any]] | None = None,
146
+ identity_required: bool = False,
147
+ **settings: Any,
148
+ ) -> _Opening:
149
+ """``async with EmbeddedControlPlane.open(...) as cp:`` — see :meth:`start`."""
150
+ return _Opening(
151
+ cls.start(
152
+ manifests,
153
+ store=store,
154
+ override_reason=override_reason,
155
+ capabilities=capabilities,
156
+ identity_required=identity_required,
157
+ **settings,
158
+ )
159
+ )
160
+
161
+ @classmethod
162
+ async def start(
163
+ cls,
164
+ manifests: ManifestSource | None = None,
165
+ *,
166
+ store: str | os.PathLike[str] = MEMORY,
167
+ override_reason: str | None = None,
168
+ capabilities: Mapping[str, Mapping[str, Any]] | None = None,
169
+ identity_required: bool = False,
170
+ **settings: Any,
171
+ ) -> EmbeddedControlPlane:
172
+ """Start an instance; pair with :meth:`aclose`. For notebooks and fixtures that cannot
173
+ hold an ``async with`` open.
174
+
175
+ ``store`` is ``":memory:"`` (a temporary store, deleted on close) or a file path (kept,
176
+ and refused if another process has it open). ``capabilities`` are the RFC 9728
177
+ documents manifests reconcile against, keyed by tool host; without one, a tool's host
178
+ is unreachable and its manifest needs ``override_reason``. Any other keyword is a
179
+ control-plane setting (``Settings`` field), e.g. ``step_up_enabled=True``.
180
+ """
181
+ handle = await open_store(store)
182
+ try:
183
+ instance = await cls._assemble(
184
+ handle,
185
+ capabilities=capabilities or {},
186
+ identity_required=identity_required,
187
+ settings=settings,
188
+ )
189
+ except BaseException:
190
+ await handle.close()
191
+ raise
192
+ logger.warning(BANNER.format(store=os.fspath(store)))
193
+ if manifests is not None:
194
+ try:
195
+ await instance.register(manifests, override_reason=override_reason)
196
+ except BaseException:
197
+ await instance.aclose()
198
+ raise
199
+ return instance
200
+
201
+ @classmethod
202
+ async def _assemble(
203
+ cls,
204
+ handle: StoreHandle,
205
+ *,
206
+ capabilities: Mapping[str, Mapping[str, Any]],
207
+ identity_required: bool,
208
+ settings: Mapping[str, Any],
209
+ ) -> EmbeddedControlPlane:
210
+ if handle.issuer_private_key:
211
+ issuer_key = load_or_generate(handle.issuer_private_key)
212
+ else:
213
+ private = Ed25519PrivateKey.generate()
214
+ issuer_key = IssuerKey(private_key=private, kid=_thumbprint(private.public_key()))
215
+ await remember_issuer_key(handle, issuer_key.private_pem().decode())
216
+
217
+ config = _EmbeddedSettings(
218
+ # Informational only: the engine below is what the instance uses.
219
+ database_url=f"sqlite+aiosqlite:///{handle.path}",
220
+ redis_url="redis://embedded.invalid/0",
221
+ # Per-instance bearers. Nothing outside this object ever needs them.
222
+ admin_token=secrets.token_urlsafe(32),
223
+ audit_read_token=secrets.token_urlsafe(32),
224
+ enroll_token=secrets.token_urlsafe(32),
225
+ principal_idp_issuer=_idp.ISSUER,
226
+ principal_idp_jwks_url=f"{_idp.ISSUER}/.well-known/jwks.json",
227
+ principal_idp_audience=_idp.AUDIENCE,
228
+ principal_binding_claim=_idp.BINDING_CLAIM,
229
+ identity_required=identity_required,
230
+ telemetry_enabled=False,
231
+ **settings,
232
+ )
233
+
234
+ router = HostRouter()
235
+ http = httpx.AsyncClient(transport=router, timeout=httpx.Timeout(10.0))
236
+ runtime = Runtime(
237
+ settings=config,
238
+ engine=handle.engine,
239
+ sessionmaker=handle.sessionmaker,
240
+ redis=FakeRedis(server=FakeServer(), decode_responses=True),
241
+ issuer_key=issuer_key,
242
+ metrics=build_control_plane_metrics(CollectorRegistry()),
243
+ http=http,
244
+ deployment="embedded",
245
+ superseded_before=handle.opened_at if handle.durable else None,
246
+ )
247
+ test_idp = _idp.TestIdp()
248
+
249
+ from agentic_auth.main import create_app
250
+ from agentic_auth.services.anchors import AnchorCache
251
+ from agentic_auth.services.revocation import RevocationService
252
+
253
+ with use_runtime(runtime):
254
+ router.mount(HOST, create_app(runtime))
255
+ router.mount(CAPABILITIES, capability_app(capabilities))
256
+ router.mount(_idp.HOST, test_idp.app())
257
+ # What the server's startup does: rebuild the revoked-agents set from the table,
258
+ # so a durable store reopened with an empty Redis is never more permissive.
259
+ async with runtime.sessionmaker() as session:
260
+ await RevocationService(AnchorCache(runtime.redis)).rebuild(session, runtime.redis)
261
+
262
+ return cls(runtime=runtime, store=handle, router=router, idp=test_idp)
263
+
264
+ async def aclose(self) -> None:
265
+ if self._closed:
266
+ return
267
+ self._closed = True
268
+ await self._runtime.http.aclose()
269
+ await self._runtime.redis.aclose()
270
+ await self._store.close()
271
+
272
+ def _check_open(self) -> None:
273
+ if self._closed:
274
+ raise RuntimeError("embedded control plane is closed")
275
+
276
+ # -- what callers use -------------------------------------------------------------
277
+
278
+ @property
279
+ def store(self) -> Path | None:
280
+ """The store's file, for a durable store; ``None`` for a temporary one."""
281
+ return self._store.path if self._store.durable else None
282
+
283
+ @property
284
+ def http(self) -> httpx.AsyncClient:
285
+ """The in-process HTTP client. Reaches the control plane, the capability source,
286
+ the test identity provider and anything :meth:`mount` adds — and nothing else."""
287
+ return self._runtime.http
288
+
289
+ def client(
290
+ self,
291
+ agent_name: str | None = None,
292
+ *,
293
+ key: AgentKey | None = None,
294
+ trace_path: str | os.PathLike[str] | None = None,
295
+ ) -> AgenticAuthClient:
296
+ """The same SDK client a deployment uses, wired to this instance. With ``agent_name``
297
+ and ``key``, it presents that agent's identity on every exchange and call."""
298
+ self._check_open()
299
+ settings = self._runtime.settings
300
+ return AgenticAuthClient(
301
+ BASE_URL,
302
+ admin_token=settings.admin_token,
303
+ audit_token=settings.audit_read_token,
304
+ client=self._runtime.http,
305
+ identity_key=key,
306
+ agent_name=agent_name if key else None,
307
+ trace_path=os.fspath(trace_path) if trace_path else None,
308
+ )
309
+
310
+ async def register(
311
+ self,
312
+ manifests: ManifestSource,
313
+ *,
314
+ override_reason: str | None = None,
315
+ ) -> list[Any]:
316
+ """Register every manifest, downstream agents first. Raises ``ManifestRejected`` with
317
+ the reconciliation diff, exactly as the admin API does."""
318
+ from agentic_auth.services.drift import registration_order
319
+
320
+ self._check_open()
321
+ found = _manifests_from(manifests)
322
+ admin = self.client().admin
323
+ return [
324
+ await admin.register_agent(
325
+ name, found[name].canonical_doc(), override_reason=override_reason
326
+ )
327
+ for name in registration_order(found)
328
+ ]
329
+
330
+ def jwks(self) -> dict[str, Any]:
331
+ """The public key every grant this instance issues is signed with."""
332
+ return {"keys": [self._runtime.issuer_key.public_jwk()]}
333
+
334
+ async def verifier(self, *, agents: Iterable[str] = (), **kwargs: Any) -> Verifier:
335
+ """A resource-side verifier that trusts *this* instance's grants and the identities
336
+ of ``agents`` — bootstrapped, then offline like any other. A token from a different
337
+ instance does not verify against it."""
338
+ self._check_open()
339
+ settings = self._runtime.settings
340
+ freshness = kwargs.pop("freshness_seconds", settings.revocation_freshness_seconds)
341
+ verifier = Verifier(
342
+ issuer_jwks=HttpJwks(f"{BASE_URL}/.well-known/jwks.json", client=self.http),
343
+ anchors=HttpAnchors(
344
+ base_url=BASE_URL,
345
+ token=settings.audit_read_token,
346
+ agents=list(agents),
347
+ freshness_seconds=freshness,
348
+ client=self.http,
349
+ ),
350
+ replay=kwargs.pop("replay", None) or InMemoryReplay(),
351
+ freshness_seconds=freshness,
352
+ **kwargs,
353
+ )
354
+ await verifier.bootstrap()
355
+ return verifier
356
+
357
+ async def enroll_test_principal(
358
+ self, agent_name: str, key: AgentKey, *, principal: str = "user:test"
359
+ ) -> dict[str, Any]:
360
+ """Enroll ``agent_name`` bound to ``principal`` at the built-in test identity
361
+ provider. The binding is labelled test-only in the principal assertion."""
362
+ self._check_open()
363
+ client = self.client()
364
+ agent_id = await client.admin.agent_id(agent_name)
365
+ return await client.enroll(
366
+ agent_id,
367
+ key=key,
368
+ agent_name=agent_name,
369
+ principal_assertion=self._idp.mint(agent=agent_name, sub=principal),
370
+ enroll_token=self._runtime.settings.enroll_token,
371
+ )
372
+
373
+ def mount(self, host: str, app: Any) -> None:
374
+ """Serve an ASGI app (a tool server, say) at ``https://{host}`` on :attr:`http`."""
375
+ self._check_open()
376
+ self._router.mount(host, app)
377
+
378
+ def cut(self, host: str = HOST) -> None:
379
+ """Make a host unreachable, the way an outage does — the control plane by default."""
380
+ self._router.cut.add(host)
381
+
382
+ def restore(self, host: str = HOST) -> None:
383
+ self._router.cut.discard(host)
384
+
385
+ async def export(self, path: str | os.PathLike[str]) -> Path:
386
+ """Write an export bundle for moving to a deployed control plane."""
387
+ from agentic_auth.embedded.export import export_bundle
388
+
389
+ self._check_open()
390
+ return await export_bundle(self._runtime, Path(path))
391
+
392
+
393
+ class _Opening:
394
+ """What :meth:`EmbeddedControlPlane.open` returns: an async context manager."""
395
+
396
+ def __init__(self, starting: Any) -> None:
397
+ self._starting = starting
398
+ self._instance: EmbeddedControlPlane | None = None
399
+
400
+ async def __aenter__(self) -> EmbeddedControlPlane:
401
+ self._instance = await self._starting
402
+ return self._instance
403
+
404
+ async def __aexit__(
405
+ self,
406
+ exc_type: type[BaseException] | None,
407
+ exc: BaseException | None,
408
+ tb: TracebackType | None,
409
+ ) -> None:
410
+ if self._instance is not None:
411
+ await self._instance.aclose()
412
+
413
+ def __await__(self) -> Any:
414
+ raise TypeError(
415
+ "use `async with EmbeddedControlPlane.open(...) as cp`, "
416
+ "or `cp = await EmbeddedControlPlane.start(...)`"
417
+ )
418
+
419
+
420
+ __all__ = [
421
+ "BASE_URL",
422
+ "EmbeddedControlPlane",
423
+ "ManifestRejected",
424
+ "PolicyDenied",
425
+ "StoreLocked",
426
+ "StoreVersionMismatch",
427
+ ]
@@ -0,0 +1,8 @@
1
+ """The schema an embedded store is created with: the Alembic head this package was built at.
2
+
3
+ The migrations are not shipped in the wheel, so the revision is recorded here.
4
+ ``tests/unit/test_embedded_schema_revision.py`` fails when a new migration lands without this
5
+ moving with it. A store created at a different revision is refused rather than half-read.
6
+ """
7
+
8
+ SCHEMA_REVISION = "0006_audit_deployment"