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,39 @@
1
+ """One ``httpx`` transport, several in-process services, routed by host. No sockets.
2
+
3
+ The embedded control plane, the capability documents its manifests reconcile against, the
4
+ test identity provider and any tool server a test mounts all live behind this. A request for
5
+ a host nothing is mounted on fails exactly as an unreachable network host does, so every
6
+ "discovery unavailable" and "control plane down" path is the real one.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+ WELL_KNOWN = "/.well-known/oauth-protected-resource"
16
+ CAPABILITIES = "capabilities.embedded.invalid"
17
+
18
+
19
+ class HostRouter(httpx.AsyncBaseTransport):
20
+ def __init__(self) -> None:
21
+ self.routes: dict[str, httpx.AsyncBaseTransport] = {}
22
+ # Hosts made unreachable on purpose, the way an outage does (fail-closed demos).
23
+ self.cut: set[str] = set()
24
+
25
+ def mount(self, host: str, app: Any) -> None:
26
+ self.routes[host] = httpx.ASGITransport(app=app)
27
+
28
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
29
+ host = request.url.host
30
+ if host in self.cut:
31
+ raise httpx.ConnectError(f"{host} is unreachable", request=request)
32
+ # A tool host's RFC 9728 document is served by the capability source, the way a real
33
+ # MCP server answers on its own well-known path.
34
+ if request.url.path == WELL_KNOWN and host not in self.routes:
35
+ host = CAPABILITIES
36
+ transport = self.routes.get(host)
37
+ if transport is None:
38
+ raise httpx.ConnectError(f"nothing is listening on {host}", request=request)
39
+ return await transport.handle_async_request(request)
@@ -0,0 +1,34 @@
1
+ """The RFC 9728 documents an embedded instance reconciles manifests against.
2
+
3
+ A real deployment fetches ``/.well-known/oauth-protected-resource`` from each MCP server a
4
+ manifest names. An embedded instance has no network, so it is handed the documents instead,
5
+ keyed by host. A host with no document is *unreachable*, not empty: reconciliation reports
6
+ discovery as unavailable and the manifest needs a recorded override reason, exactly the rule
7
+ the server applies when a tool host is down.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Mapping
13
+ from typing import Any
14
+
15
+ from starlette.applications import Starlette
16
+ from starlette.requests import Request
17
+ from starlette.responses import JSONResponse
18
+ from starlette.routing import Route
19
+
20
+ from agentic_auth.embedded._transport import WELL_KNOWN
21
+
22
+
23
+ def capability_app(documents: Mapping[str, Mapping[str, Any]]) -> Starlette:
24
+ docs = {host: dict(doc) for host, doc in documents.items()}
25
+
26
+ async def document(request: Request) -> JSONResponse:
27
+ host = request.headers.get("host", "").split(":")[0]
28
+ doc = docs.get(host)
29
+ if doc is None:
30
+ # Indistinguishable, to the discovery client, from a host that is down.
31
+ return JSONResponse({"error": "unavailable"}, status_code=503)
32
+ return JSONResponse(doc)
33
+
34
+ return Starlette(routes=[Route(WELL_KNOWN, document)])
@@ -0,0 +1,86 @@
1
+ """Export an embedded store as an NDJSON bundle (data-model.md, "Export bundle").
2
+
3
+ One JSON object per line, in an order a reader can replay:
4
+
5
+ 1. a ``header`` naming where the bundle came from
6
+ 2. ``agent`` and ``manifest`` records, every manifest version in version order
7
+ 3. ``trust_anchor`` records: enrollments, with their revocations
8
+ 4. ``audit`` records in write order, parent links intact
9
+
10
+ Sessions, keys, taint marks and replay records are deliberately absent: they are runtime
11
+ state of *this* instance, and carrying a development signing key into a deployment would be
12
+ the one export worse than none.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import uuid
19
+ from datetime import UTC, datetime
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from sqlalchemy import select
24
+
25
+ import agentic_auth
26
+ from agentic_auth.models import Agent, AuditDecision, Manifest, TrustAnchor
27
+ from agentic_auth.runtime import Runtime
28
+
29
+
30
+ def _jsonable(value: Any) -> Any:
31
+ if isinstance(value, uuid.UUID):
32
+ return str(value)
33
+ if isinstance(value, datetime):
34
+ return value.isoformat()
35
+ return value
36
+
37
+
38
+ def _row(kind: str, obj: Any) -> dict[str, Any]:
39
+ columns = obj.__table__.columns
40
+ return {"kind": kind, **{c.key: _jsonable(getattr(obj, c.key)) for c in columns}}
41
+
42
+
43
+ async def export_bundle(runtime: Runtime, path: Path) -> Path:
44
+ async with runtime.sessionmaker() as db:
45
+ agents = (await db.execute(select(Agent).order_by(Agent.name))).scalars().all()
46
+ manifests = (
47
+ (await db.execute(select(Manifest).order_by(Manifest.agent_id, Manifest.version)))
48
+ .scalars()
49
+ .all()
50
+ )
51
+ anchors = (
52
+ (
53
+ await db.execute(
54
+ select(TrustAnchor).order_by(TrustAnchor.agent_id, TrustAnchor.version)
55
+ )
56
+ )
57
+ .scalars()
58
+ .all()
59
+ )
60
+ audit = (
61
+ (await db.execute(select(AuditDecision).order_by(AuditDecision.seq))).scalars().all()
62
+ )
63
+
64
+ header = {
65
+ "kind": "header",
66
+ "source_deployment": runtime.deployment,
67
+ "package_version": agentic_auth.__version__,
68
+ "exported_at": datetime.now(UTC).isoformat(),
69
+ "counts": {
70
+ "agent": len(agents),
71
+ "manifest": len(manifests),
72
+ "trust_anchor": len(anchors),
73
+ "audit": len(audit),
74
+ },
75
+ }
76
+ lines = [header]
77
+ lines += [_row("agent", a) for a in agents]
78
+ lines += [_row("manifest", m) for m in manifests]
79
+ lines += [_row("trust_anchor", t) for t in anchors]
80
+ lines += [_row("audit", r) for r in audit]
81
+
82
+ path.parent.mkdir(parents=True, exist_ok=True)
83
+ with path.open("w", encoding="utf-8") as out:
84
+ for line in lines:
85
+ out.write(json.dumps(line, sort_keys=True, separators=(",", ":")) + "\n")
86
+ return path
@@ -0,0 +1,78 @@
1
+ """A stand-in for the human identity provider enrollment binds an agent to.
2
+
3
+ Enrollment requires an accountable principal: an ID token from the organisation's IdP naming
4
+ the agent. An embedded instance has no IdP, so it carries this one. Anything it binds is a
5
+ *test* principal, and says so: the enrollment's principal assertion carries
6
+ ``principal_source: embedded-test``, so an exported record can never pass for a real binding.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import uuid
13
+ from dataclasses import dataclass, field
14
+ from datetime import UTC, datetime, timedelta
15
+ from typing import Any
16
+
17
+ import jwt
18
+ from cryptography.hazmat.primitives import serialization
19
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
20
+ from starlette.applications import Starlette
21
+ from starlette.requests import Request
22
+ from starlette.responses import JSONResponse
23
+ from starlette.routing import Route
24
+
25
+ HOST = "idp.embedded.invalid"
26
+ ISSUER = f"https://{HOST}"
27
+ AUDIENCE = "agentic-auth"
28
+ BINDING_CLAIM = "agent"
29
+ PRINCIPAL_SOURCE = "embedded-test"
30
+
31
+
32
+ def _b64url(raw: bytes) -> str:
33
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
34
+
35
+
36
+ @dataclass
37
+ class TestIdp:
38
+ __test__ = False # not a pytest class, whatever its name
39
+
40
+ key: Ed25519PrivateKey = field(default_factory=Ed25519PrivateKey.generate)
41
+ kid: str = "embedded-idp-1"
42
+
43
+ def jwks(self) -> dict[str, Any]:
44
+ raw = self.key.public_key().public_bytes(
45
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
46
+ )
47
+ return {
48
+ "keys": [
49
+ {"kty": "OKP", "crv": "Ed25519", "x": _b64url(raw), "kid": self.kid}
50
+ | {"alg": "EdDSA", "use": "sig"}
51
+ ]
52
+ }
53
+
54
+ def mint(self, *, agent: str, sub: str, expires_in: int = 300) -> str:
55
+ """An ID token for ``sub`` naming ``agent`` in the binding claim."""
56
+ now = datetime.now(UTC)
57
+ claims = {
58
+ "iss": ISSUER,
59
+ "sub": sub,
60
+ "aud": AUDIENCE,
61
+ "iat": int(now.timestamp()),
62
+ "exp": int((now + timedelta(seconds=expires_in)).timestamp()),
63
+ "jti": str(uuid.uuid4()),
64
+ BINDING_CLAIM: f"agent://{agent}",
65
+ "principal_source": PRINCIPAL_SOURCE,
66
+ }
67
+ pem = self.key.private_bytes(
68
+ serialization.Encoding.PEM,
69
+ serialization.PrivateFormat.PKCS8,
70
+ serialization.NoEncryption(),
71
+ )
72
+ return jwt.encode(claims, pem, algorithm="EdDSA", headers={"kid": self.kid})
73
+
74
+ def app(self) -> Starlette:
75
+ async def jwks(_: Request) -> JSONResponse:
76
+ return JSONResponse(self.jwks())
77
+
78
+ return Starlette(routes=[Route("/.well-known/jwks.json", jwks)])
@@ -0,0 +1,240 @@
1
+ """The embedded control plane's database: SQLite, in a temporary file or a durable one.
2
+
3
+ The schema is the server's own models (``Base.metadata``), rendered for SQLite by the portable
4
+ types in ``agentic_auth/models/types.py``, append-only triggers included. One extra table,
5
+ ``embedded_meta``, records what created the file and when it was last opened.
6
+
7
+ Concurrency. Every transaction begins ``IMMEDIATE``, so it holds SQLite's write lock from its
8
+ first statement. Two transactions therefore never interleave, which is what makes reading
9
+ the audit chain's parent and numbering the next row safe without PostgreSQL's isolation.
10
+ Waiters block on ``busy_timeout`` rather than failing. Throughput is a single writer — right
11
+ for a development and test control plane, and the reason this is not one for production.
12
+
13
+ ``":memory:"`` is a temporary *file*, deleted on close, not SQLite's ``:memory:``: an in-memory
14
+ database lives in one connection, and sharing one connection between concurrent requests
15
+ would let their transactions interleave.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import contextlib
21
+ import os
22
+ import sys
23
+ import tempfile
24
+ from dataclasses import dataclass, field
25
+ from datetime import UTC, datetime
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ from sqlalchemy import Column, DateTime, MetaData, String, Table, Text, event, insert, select
30
+ from sqlalchemy.ext.asyncio import (
31
+ AsyncEngine,
32
+ AsyncSession,
33
+ async_sessionmaker,
34
+ create_async_engine,
35
+ )
36
+
37
+ import agentic_auth
38
+ from agentic_auth.embedded._schema import SCHEMA_REVISION
39
+ from agentic_auth.models import Base
40
+
41
+ MEMORY = ":memory:"
42
+ BUSY_TIMEOUT_MS = 5000
43
+
44
+ _meta = MetaData()
45
+ embedded_meta = Table(
46
+ "embedded_meta",
47
+ _meta,
48
+ Column("schema_revision", String(64), nullable=False),
49
+ Column("package_version", String(32), nullable=False),
50
+ Column("created_at", DateTime, nullable=False),
51
+ Column("opened_at", DateTime, nullable=False),
52
+ # Durable stores only. The issuer's signing key, so tokens survive a restart. Acceptable
53
+ # only because embedded mode is development and testing only: the file is mode 0600.
54
+ Column("issuer_private_key", Text, nullable=True),
55
+ )
56
+
57
+
58
+ class StoreLocked(RuntimeError):
59
+ """Another process has this store open."""
60
+
61
+ def __init__(self, path: Path, pid: int | None) -> None:
62
+ holder = f"process {pid}" if pid else "another process"
63
+ super().__init__(f"embedded store {path} is open in {holder}")
64
+ self.path = path
65
+ self.pid = pid
66
+
67
+
68
+ class StoreVersionMismatch(RuntimeError):
69
+ """The store was created by a package with a different schema."""
70
+
71
+ def __init__(self, found: str, expected: str) -> None:
72
+ super().__init__(
73
+ f"embedded store schema is {found!r}, this package needs {expected!r}. "
74
+ "Export it with the version that created it (EmbeddedControlPlane.export) and "
75
+ "start a new store, or open it with that version."
76
+ )
77
+ self.found = found
78
+ self.expected = expected
79
+
80
+
81
+ @dataclass
82
+ class StoreHandle:
83
+ path: Path
84
+ durable: bool
85
+ engine: AsyncEngine
86
+ sessionmaker: async_sessionmaker[AsyncSession]
87
+ # When this open happened. For a durable store, every session older than this is
88
+ # superseded (agentic_auth/runtime.py); for a temporary one there is nothing older.
89
+ opened_at: datetime
90
+ issuer_private_key: str | None = None
91
+ _lock: Any = field(default=None, repr=False)
92
+ _tmpdir: tempfile.TemporaryDirectory[str] | None = field(default=None, repr=False)
93
+
94
+ async def close(self) -> None:
95
+ await self.engine.dispose()
96
+ if self._lock is not None:
97
+ _release(self._lock)
98
+ self._lock = None
99
+ if self._tmpdir is not None:
100
+ self._tmpdir.cleanup()
101
+ self._tmpdir = None
102
+
103
+
104
+ def _engine(path: Path) -> AsyncEngine:
105
+ engine = create_async_engine(
106
+ f"sqlite+aiosqlite:///{path}", connect_args={"timeout": BUSY_TIMEOUT_MS / 1000}
107
+ )
108
+
109
+ @event.listens_for(engine.sync_engine, "connect")
110
+ def _on_connect(dbapi_connection: Any, _record: Any) -> None:
111
+ # Hand transaction control to the "begin" hook below instead of pysqlite's own
112
+ # deferred BEGIN, which takes the write lock only at the first write.
113
+ dbapi_connection.isolation_level = None
114
+ cursor = dbapi_connection.cursor()
115
+ cursor.execute("PRAGMA journal_mode=WAL")
116
+ cursor.execute("PRAGMA foreign_keys=ON")
117
+ cursor.execute(f"PRAGMA busy_timeout={BUSY_TIMEOUT_MS}")
118
+ cursor.close()
119
+
120
+ @event.listens_for(engine.sync_engine, "begin")
121
+ def _on_begin(connection: Any) -> None:
122
+ connection.exec_driver_sql("BEGIN IMMEDIATE")
123
+
124
+ return engine
125
+
126
+
127
+ async def open_store(target: str | os.PathLike[str] = MEMORY) -> StoreHandle:
128
+ """Open (and on first use, create) a store. Raises ``StoreLocked`` or
129
+ ``StoreVersionMismatch``; never opens a store it cannot use correctly."""
130
+ tmpdir: tempfile.TemporaryDirectory[str] | None = None
131
+ lock = None
132
+ if os.fspath(target) == MEMORY:
133
+ tmpdir = tempfile.TemporaryDirectory(prefix="agentic-auth-embedded-")
134
+ path, durable = Path(tmpdir.name) / "store.db", False
135
+ else:
136
+ path, durable = Path(target).resolve(), True
137
+ path.parent.mkdir(parents=True, exist_ok=True)
138
+ lock = _acquire(path.with_name(path.name + ".lock"), path)
139
+
140
+ created = not path.exists()
141
+ if created and durable:
142
+ # Create it 0600 before SQLite writes anything into it.
143
+ os.close(os.open(path, os.O_CREAT | os.O_WRONLY, 0o600))
144
+ engine = _engine(path)
145
+ now = datetime.now(UTC)
146
+ try:
147
+ async with engine.begin() as conn:
148
+ if created or not await conn.run_sync(
149
+ lambda c: c.dialect.has_table(c, "embedded_meta")
150
+ ):
151
+ await conn.run_sync(Base.metadata.create_all)
152
+ await conn.run_sync(_meta.create_all)
153
+ await conn.execute(
154
+ insert(embedded_meta).values(
155
+ schema_revision=SCHEMA_REVISION,
156
+ package_version=agentic_auth.__version__,
157
+ created_at=now.replace(tzinfo=None),
158
+ opened_at=now.replace(tzinfo=None),
159
+ )
160
+ )
161
+ key = None
162
+ else:
163
+ row = (await conn.execute(select(embedded_meta))).one()
164
+ if row.schema_revision != SCHEMA_REVISION:
165
+ raise StoreVersionMismatch(row.schema_revision, SCHEMA_REVISION)
166
+ await conn.execute(
167
+ embedded_meta.update().values(opened_at=now.replace(tzinfo=None))
168
+ )
169
+ key = row.issuer_private_key
170
+ except BaseException:
171
+ await engine.dispose()
172
+ if lock is not None:
173
+ _release(lock)
174
+ if tmpdir is not None:
175
+ tmpdir.cleanup()
176
+ raise
177
+
178
+ return StoreHandle(
179
+ path=path,
180
+ durable=durable,
181
+ engine=engine,
182
+ sessionmaker=async_sessionmaker(engine, expire_on_commit=False, autoflush=False),
183
+ opened_at=now,
184
+ issuer_private_key=key,
185
+ _lock=lock,
186
+ _tmpdir=tmpdir,
187
+ )
188
+
189
+
190
+ async def remember_issuer_key(handle: StoreHandle, pem: str) -> None:
191
+ """Durable stores keep the issuer key, so tokens and anchors outlive a restart."""
192
+ if not handle.durable:
193
+ return
194
+ async with handle.engine.begin() as conn:
195
+ await conn.execute(embedded_meta.update().values(issuer_private_key=pem))
196
+ handle.issuer_private_key = pem
197
+
198
+
199
+ # -- single-writer lock --------------------------------------------------------------------
200
+ #
201
+ # An OS advisory lock on a sidecar file, held for the instance's lifetime. The OS releases it
202
+ # when the process dies, so a crashed process never leaves a store permanently locked; the PID
203
+ # written into the file is only there to name the holder in the error.
204
+
205
+
206
+ def _acquire(lock_path: Path, store: Path) -> Any:
207
+ handle = open(lock_path, "a+") # noqa: SIM115 - held open for the store's lifetime
208
+ try:
209
+ if sys.platform == "win32":
210
+ import msvcrt
211
+
212
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
213
+ else:
214
+ import fcntl
215
+
216
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
217
+ except OSError:
218
+ handle.seek(0)
219
+ holder = handle.read().strip()
220
+ handle.close()
221
+ raise StoreLocked(store, int(holder) if holder.isdigit() else None) from None
222
+ handle.seek(0)
223
+ handle.truncate()
224
+ handle.write(str(os.getpid()))
225
+ handle.flush()
226
+ return handle
227
+
228
+
229
+ def _release(handle: Any) -> None:
230
+ with contextlib.suppress(OSError):
231
+ if sys.platform == "win32":
232
+ import msvcrt
233
+
234
+ handle.seek(0)
235
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
236
+ else:
237
+ import fcntl
238
+
239
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
240
+ handle.close()
agentic_auth/errors.py ADDED
@@ -0,0 +1,145 @@
1
+ """Domain exceptions raised by the service layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class DomainError(Exception):
9
+ """Base for errors that map to a specific HTTP response."""
10
+
11
+ status_code: int = 400
12
+ code: str = "domain_error"
13
+
14
+ def __init__(self, message: str, details: dict[str, Any] | None = None) -> None:
15
+ super().__init__(message)
16
+ self.message = message
17
+ self.details = details
18
+
19
+
20
+ class NotFoundError(DomainError):
21
+ status_code = 404
22
+ code = "not_found"
23
+
24
+
25
+ class QueryValidationError(DomainError):
26
+ """A query string that cannot be honoured. Rendered exactly like request validation —
27
+ ``422 validation_error`` with ``details.fields[].loc`` naming the parameter — so a
28
+ client never has to tell the two apart."""
29
+
30
+ status_code = 422
31
+ code = "validation_error"
32
+
33
+ def __init__(self, message: str, fields: list[dict[str, Any]]) -> None:
34
+ super().__init__(message, {"fields": fields})
35
+
36
+
37
+ class UnauthorizedError(DomainError):
38
+ status_code = 401
39
+ code = "unauthorized"
40
+
41
+
42
+ class ReconciliationRejected(DomainError):
43
+ status_code = 422
44
+ code = "reconciliation_rejected"
45
+
46
+
47
+ class NeedsReviewWithoutOverride(DomainError):
48
+ status_code = 409
49
+ code = "needs_review"
50
+
51
+
52
+ class DagCycleError(DomainError):
53
+ status_code = 422
54
+ code = "dag_cycle"
55
+
56
+
57
+ class ManifestValidationError(DomainError):
58
+ status_code = 422
59
+ code = "validation_error"
60
+
61
+
62
+ class SessionExpired(DomainError):
63
+ status_code = 401
64
+ code = "session_expired"
65
+
66
+
67
+ class SessionSuperseded(SessionExpired):
68
+ """An embedded store was reopened after this session was created.
69
+
70
+ The taint marks and replay records that protected the session lived in memory and did
71
+ not survive the restart, so honouring it would fail open. The remedy is the same as for
72
+ an expired session: consent again. Never raised by the server deployment.
73
+ """
74
+
75
+ code = "session_superseded"
76
+
77
+
78
+ class PolicyRecompileRequired(DomainError):
79
+ """The scope's compiled policy predates the runtime plane's DAG schema.
80
+
81
+ Never guessed past: an unenforceable policy must not silently become an allow.
82
+ Resubmitting the manifest compiles a new version (append-only; nothing mutates).
83
+ """
84
+
85
+ status_code = 409
86
+ code = "policy_recompile_required"
87
+
88
+
89
+ class PolicyDenied(DomainError):
90
+ """A hop was refused by policy. ``details`` carries reason, recoverability,
91
+ target and hop so the caller can act rather than guess."""
92
+
93
+ status_code = 403
94
+ code = "policy_denied"
95
+
96
+
97
+ class PolicyUnavailable(DomainError):
98
+ """A decision could not be made. Always a deny — never a fallthrough."""
99
+
100
+ status_code = 503
101
+ code = "pdp_unavailable"
102
+
103
+
104
+ class TokenServiceUnavailable(DomainError):
105
+ """Narrowed authority could not be issued after an allow. The presented token is
106
+ never forwarded as a fallback."""
107
+
108
+ status_code = 503
109
+ code = "token_service_unavailable"
110
+
111
+
112
+ # -- Phase 4 -------------------------------------------------------------------------
113
+
114
+
115
+ class TransactionAlreadyMinted(DomainError):
116
+ """One transaction token per recorded decision; this decision already has one."""
117
+
118
+ status_code = 409
119
+ code = "transaction_already_minted"
120
+
121
+
122
+ class TransactionValidationError(QueryValidationError):
123
+ """A mint request that cannot be honoured: non-privileged target, oversized or
124
+ non-canonicalizable params. Rendered as ``422 validation_error``."""
125
+
126
+
127
+ class KeyRevoked(DomainError):
128
+ """A presented key belongs to a revoked trust anchor, or the agent is revoked."""
129
+
130
+ status_code = 409
131
+ code = "key_revoked"
132
+
133
+
134
+ class NotEnrolled(DomainError):
135
+ """The agent has no trust anchor to act on."""
136
+
137
+ status_code = 409
138
+ code = "not_enrolled"
139
+
140
+
141
+ class IdpUnavailable(DomainError):
142
+ """The principal identity provider could not be reached. Retryable; status unchanged."""
143
+
144
+ status_code = 503
145
+ code = "idp_unavailable"