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.
- agentic_auth/__init__.py +8 -0
- agentic_auth/_extras.py +24 -0
- agentic_auth/api/__init__.py +0 -0
- agentic_auth/api/deps.py +112 -0
- agentic_auth/api/errors.py +51 -0
- agentic_auth/api/responses.py +38 -0
- agentic_auth/api/service_deps.py +113 -0
- agentic_auth/api/v1/__init__.py +0 -0
- agentic_auth/api/v1/agents.py +88 -0
- agentic_auth/api/v1/audit.py +67 -0
- agentic_auth/api/v1/authorize.py +439 -0
- agentic_auth/api/v1/consent.py +21 -0
- agentic_auth/api/v1/decisions.py +43 -0
- agentic_auth/api/v1/enrollment.py +48 -0
- agentic_auth/api/v1/identity.py +97 -0
- agentic_auth/api/v1/jwks.py +21 -0
- agentic_auth/api/v1/manifests.py +68 -0
- agentic_auth/api/v1/scopes.py +22 -0
- agentic_auth/api/v1/token.py +203 -0
- agentic_auth/api/v1/transaction.py +94 -0
- agentic_auth/boundary/__init__.py +26 -0
- agentic_auth/boundary/guarantee.py +96 -0
- agentic_auth/cli/__init__.py +27 -0
- agentic_auth/cli/audit.py +130 -0
- agentic_auth/cli/drift.py +164 -0
- agentic_auth/cli/drift_render.py +148 -0
- agentic_auth/cli/identity.py +63 -0
- agentic_auth/cli/manifest.py +275 -0
- agentic_auth/config.py +182 -0
- agentic_auth/db.py +49 -0
- agentic_auth/embedded/__init__.py +427 -0
- agentic_auth/embedded/_schema.py +8 -0
- agentic_auth/embedded/_transport.py +39 -0
- agentic_auth/embedded/capabilities.py +34 -0
- agentic_auth/embedded/export.py +86 -0
- agentic_auth/embedded/idp.py +78 -0
- agentic_auth/embedded/store.py +240 -0
- agentic_auth/errors.py +145 -0
- agentic_auth/main.py +141 -0
- agentic_auth/models/__init__.py +70 -0
- agentic_auth/models/agent.py +58 -0
- agentic_auth/models/audit_decision.py +199 -0
- agentic_auth/models/compiled_policy.py +28 -0
- agentic_auth/models/manifest.py +96 -0
- agentic_auth/models/reconciliation_report.py +27 -0
- agentic_auth/models/sandbox_run.py +93 -0
- agentic_auth/models/session.py +63 -0
- agentic_auth/models/step_up_grant.py +106 -0
- agentic_auth/models/transaction_token.py +73 -0
- agentic_auth/models/trust_anchor.py +59 -0
- agentic_auth/models/types.py +95 -0
- agentic_auth/observability/__init__.py +370 -0
- agentic_auth/observability/config.py +137 -0
- agentic_auth/observability/context.py +128 -0
- agentic_auth/observability/ids.py +122 -0
- agentic_auth/observability/logs.py +191 -0
- agentic_auth/observability/pep.py +169 -0
- agentic_auth/observability/spans.py +225 -0
- agentic_auth/observability/surface.py +286 -0
- agentic_auth/observability/tracing.py +167 -0
- agentic_auth/redis.py +27 -0
- agentic_auth/repositories/__init__.py +0 -0
- agentic_auth/repositories/agents.py +96 -0
- agentic_auth/repositories/audit_decisions.py +152 -0
- agentic_auth/repositories/compiled_policies.py +72 -0
- agentic_auth/repositories/manifests.py +149 -0
- agentic_auth/repositories/reconciliation_reports.py +40 -0
- agentic_auth/repositories/sessions.py +41 -0
- agentic_auth/repositories/transaction_tokens.py +60 -0
- agentic_auth/repositories/trust_anchors.py +150 -0
- agentic_auth/runtime.py +81 -0
- agentic_auth/schemas/__init__.py +0 -0
- agentic_auth/schemas/agent.py +58 -0
- agentic_auth/schemas/audit.py +207 -0
- agentic_auth/schemas/authorize.py +205 -0
- agentic_auth/schemas/common.py +40 -0
- agentic_auth/schemas/consent.py +74 -0
- agentic_auth/schemas/dag.py +39 -0
- agentic_auth/schemas/edge_trace.py +166 -0
- agentic_auth/schemas/identity.py +152 -0
- agentic_auth/schemas/manifest.py +117 -0
- agentic_auth/schemas/manifest_api.py +38 -0
- agentic_auth/schemas/reconciliation.py +49 -0
- agentic_auth/schemas/token.py +122 -0
- agentic_auth/schemas/transaction.py +28 -0
- agentic_auth/sdk/__init__.py +114 -0
- agentic_auth/sdk/client.py +677 -0
- agentic_auth/sdk/context.py +95 -0
- agentic_auth/sdk/drift.py +118 -0
- agentic_auth/sdk/errors.py +147 -0
- agentic_auth/sdk/identity.py +162 -0
- agentic_auth/sdk/planes.py +362 -0
- agentic_auth/sdk/provenance.py +63 -0
- agentic_auth/services/__init__.py +0 -0
- agentic_auth/services/anchors.py +81 -0
- agentic_auth/services/audit.py +222 -0
- agentic_auth/services/audit_chain.py +144 -0
- agentic_auth/services/audit_cursor.py +55 -0
- agentic_auth/services/catalog_service.py +58 -0
- agentic_auth/services/chain_query.py +152 -0
- agentic_auth/services/dag_compiler.py +199 -0
- agentic_auth/services/decision_cache.py +123 -0
- agentic_auth/services/decision_history.py +71 -0
- agentic_auth/services/discovery.py +95 -0
- agentic_auth/services/drift.py +330 -0
- agentic_auth/services/edge_rules.py +62 -0
- agentic_auth/services/edge_trace.py +198 -0
- agentic_auth/services/enrollment.py +310 -0
- agentic_auth/services/enrollment_rules.py +80 -0
- agentic_auth/services/manifest_service.py +166 -0
- agentic_auth/services/metrics.py +419 -0
- agentic_auth/services/pdp.py +312 -0
- agentic_auth/services/policy_loader.py +255 -0
- agentic_auth/services/principal.py +143 -0
- agentic_auth/services/reconciler.py +119 -0
- agentic_auth/services/revocation.py +149 -0
- agentic_auth/services/sessions.py +231 -0
- agentic_auth/services/taint.py +204 -0
- agentic_auth/services/tokens/__init__.py +11 -0
- agentic_auth/services/tokens/act_chain.py +76 -0
- agentic_auth/services/tokens/exchange.py +319 -0
- agentic_auth/services/tokens/jwt_profile.py +362 -0
- agentic_auth/services/tokens/keys.py +117 -0
- agentic_auth/services/tokens/profile.py +167 -0
- agentic_auth/services/tokens/replay.py +53 -0
- agentic_auth/services/transactions.py +172 -0
- agentic_auth/sidecar/__init__.py +7 -0
- agentic_auth/sidecar/__main__.py +66 -0
- agentic_auth/sidecar/app.py +349 -0
- agentic_auth/sidecar/config.py +253 -0
- agentic_auth/sidecar/deny.py +108 -0
- agentic_auth/sidecar/enforce.py +640 -0
- agentic_auth/sidecar/identity.py +37 -0
- agentic_auth/verify/__init__.py +208 -0
- agentic_auth/verify/admit.py +131 -0
- agentic_auth/verify/anchors.py +250 -0
- agentic_auth/verify/canonical.py +228 -0
- agentic_auth/verify/grants.py +158 -0
- agentic_auth/verify/identity.py +111 -0
- agentic_auth/verify/replay.py +67 -0
- agentic_auth/verify/transaction.py +164 -0
- authzai-0.2.0.dist-info/METADATA +276 -0
- authzai-0.2.0.dist-info/RECORD +148 -0
- authzai-0.2.0.dist-info/WHEEL +5 -0
- authzai-0.2.0.dist-info/entry_points.txt +5 -0
- authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
- authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
- authzai-0.2.0.dist-info/top_level.txt +1 -0
agentic_auth/main.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""FastAPI application factory for the control plane."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from agentic_auth._extras import require_extra
|
|
6
|
+
|
|
7
|
+
require_extra(
|
|
8
|
+
"agentic_auth.main",
|
|
9
|
+
"server",
|
|
10
|
+
"fastapi",
|
|
11
|
+
"sqlalchemy",
|
|
12
|
+
"pydantic_settings",
|
|
13
|
+
"redis",
|
|
14
|
+
"multipart",
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
import logging
|
|
19
|
+
from collections.abc import AsyncIterator
|
|
20
|
+
|
|
21
|
+
from fastapi import FastAPI
|
|
22
|
+
from fastapi.responses import Response
|
|
23
|
+
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
|
|
24
|
+
from sqlalchemy import text
|
|
25
|
+
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
26
|
+
|
|
27
|
+
from agentic_auth import observability
|
|
28
|
+
from agentic_auth.api.errors import register_error_handlers
|
|
29
|
+
from agentic_auth.api.v1 import (
|
|
30
|
+
agents,
|
|
31
|
+
audit,
|
|
32
|
+
authorize,
|
|
33
|
+
consent,
|
|
34
|
+
decisions,
|
|
35
|
+
enrollment,
|
|
36
|
+
identity,
|
|
37
|
+
jwks,
|
|
38
|
+
manifests,
|
|
39
|
+
scopes,
|
|
40
|
+
token,
|
|
41
|
+
transaction,
|
|
42
|
+
)
|
|
43
|
+
from agentic_auth.config import get_settings
|
|
44
|
+
from agentic_auth.db import get_engine, get_sessionmaker
|
|
45
|
+
from agentic_auth.observability import logs, surface
|
|
46
|
+
from agentic_auth.redis import get_redis
|
|
47
|
+
from agentic_auth.runtime import Runtime, use_runtime
|
|
48
|
+
from agentic_auth.services.anchors import AnchorCache
|
|
49
|
+
from agentic_auth.services.metrics import exposition_registry, get_metrics
|
|
50
|
+
from agentic_auth.services.revocation import RevocationService
|
|
51
|
+
|
|
52
|
+
logger = logging.getLogger(__name__)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@contextlib.asynccontextmanager
|
|
56
|
+
async def _lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
|
57
|
+
"""Rebuild the revoked-agents set from the database, so a flushed Redis can never make
|
|
58
|
+
the control plane more permissive than the table."""
|
|
59
|
+
try:
|
|
60
|
+
async with get_sessionmaker()() as session:
|
|
61
|
+
await RevocationService(AnchorCache(get_redis())).rebuild(session, get_redis())
|
|
62
|
+
except Exception: # pragma: no cover - startup without a database (docs builds, tests)
|
|
63
|
+
logger.warning("could not rebuild the revoked-agents set at startup")
|
|
64
|
+
|
|
65
|
+
# Telemetry. Off by default; `setup` never raises, so a missing
|
|
66
|
+
# collector, a missing OTel extra or a missing telemetry key cannot stop the control plane
|
|
67
|
+
# from serving. Deliberately the opposite posture to the audit log above.
|
|
68
|
+
logs.configure()
|
|
69
|
+
observability.setup(service_name=surface.COMPONENT_CONTROL_PLANE, metrics=get_metrics())
|
|
70
|
+
get_metrics().telemetry_identity_disclosure.set(
|
|
71
|
+
1 if observability.config().identity_disclosure else 0
|
|
72
|
+
)
|
|
73
|
+
try:
|
|
74
|
+
yield
|
|
75
|
+
finally:
|
|
76
|
+
# force_flush happens here and nowhere else: it is the one call that can block, so it
|
|
77
|
+
# never touches a request path.
|
|
78
|
+
observability.shutdown()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _RuntimeMiddleware:
|
|
82
|
+
"""Runs every request of an embedded app inside its own runtime (agentic_auth/runtime.py),
|
|
83
|
+
so the process-wide accessors hand that instance its own database, Redis and keys."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, app: ASGIApp, runtime: Runtime) -> None:
|
|
86
|
+
self.app = app
|
|
87
|
+
self.runtime = runtime
|
|
88
|
+
|
|
89
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
90
|
+
with use_runtime(self.runtime):
|
|
91
|
+
await self.app(scope, receive, send)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def create_app(runtime: Runtime | None = None) -> FastAPI:
|
|
95
|
+
"""The control plane. ``runtime`` is for the embedded control plane only: the app then
|
|
96
|
+
serves that instance and skips the server's startup, which the instance runs itself."""
|
|
97
|
+
app = FastAPI(
|
|
98
|
+
title="Agentic Authorization SDK — Control Plane",
|
|
99
|
+
version="0.1.0",
|
|
100
|
+
lifespan=_lifespan if runtime is None else None,
|
|
101
|
+
)
|
|
102
|
+
if runtime is not None:
|
|
103
|
+
app.add_middleware(_RuntimeMiddleware, runtime=runtime)
|
|
104
|
+
register_error_handlers(app)
|
|
105
|
+
app.include_router(agents.router)
|
|
106
|
+
app.include_router(manifests.router)
|
|
107
|
+
app.include_router(scopes.router)
|
|
108
|
+
app.include_router(consent.router)
|
|
109
|
+
app.include_router(authorize.router)
|
|
110
|
+
app.include_router(token.router)
|
|
111
|
+
app.include_router(transaction.router)
|
|
112
|
+
app.include_router(enrollment.router)
|
|
113
|
+
app.include_router(identity.router)
|
|
114
|
+
app.include_router(decisions.router)
|
|
115
|
+
app.include_router(audit.router)
|
|
116
|
+
app.include_router(jwks.router)
|
|
117
|
+
|
|
118
|
+
@app.get("/healthz", tags=["ops"])
|
|
119
|
+
async def healthz() -> dict:
|
|
120
|
+
return {"status": "ok"}
|
|
121
|
+
|
|
122
|
+
@app.get("/readyz", tags=["ops"])
|
|
123
|
+
async def readyz() -> dict:
|
|
124
|
+
async with get_engine().connect() as conn:
|
|
125
|
+
await conn.execute(text("SELECT 1"))
|
|
126
|
+
await get_redis().ping()
|
|
127
|
+
return {"status": "ready"}
|
|
128
|
+
|
|
129
|
+
if get_settings().metrics_enabled:
|
|
130
|
+
|
|
131
|
+
@app.get("/metrics", tags=["ops"], include_in_schema=False)
|
|
132
|
+
async def metrics() -> Response:
|
|
133
|
+
"""Prometheus text exposition. Internal network only — labels carry no agent,
|
|
134
|
+
user, session or target identities. The registry is
|
|
135
|
+
resolved per request, so a multi-process collector sees every worker."""
|
|
136
|
+
return Response(generate_latest(exposition_registry()), media_type=CONTENT_TYPE_LATEST)
|
|
137
|
+
|
|
138
|
+
return app
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
app = create_app()
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""SQLAlchemy ORM base and shared column mixins."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from sqlalchemy import Uuid, event, func
|
|
10
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
11
|
+
|
|
12
|
+
from agentic_auth.models.types import TZDateTime
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Base(DeclarativeBase):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class UUIDPrimaryKey:
|
|
20
|
+
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TimestampCreated:
|
|
24
|
+
created_at: Mapped[datetime] = mapped_column(
|
|
25
|
+
TZDateTime, server_default=func.now(), nullable=False
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@event.listens_for(Base, "before_insert", propagate=True)
|
|
30
|
+
def _sqlite_timestamps(_mapper: Any, connection: Any, target: Any) -> None:
|
|
31
|
+
"""SQLite's CURRENT_TIMESTAMP has whole-second precision; PostgreSQL's now() has
|
|
32
|
+
microseconds. The embedded store compares creation times against the moment it was
|
|
33
|
+
opened (agentic_auth/runtime.py: superseded_before), and a second of slack there would
|
|
34
|
+
let a session from before a restart through. So on SQLite only, every server-defaulted
|
|
35
|
+
timestamp is filled in here, at full precision, in UTC."""
|
|
36
|
+
if connection.dialect.name != "sqlite":
|
|
37
|
+
return
|
|
38
|
+
now = datetime.now(UTC)
|
|
39
|
+
for column in _mapper.columns:
|
|
40
|
+
default = getattr(column.server_default, "arg", None)
|
|
41
|
+
if getattr(default, "name", None) == "now" and getattr(target, column.key, None) is None:
|
|
42
|
+
setattr(target, column.key, now)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
from agentic_auth.models.agent import Agent # noqa: E402,F401
|
|
46
|
+
from agentic_auth.models.audit_decision import AuditDecision # noqa: E402,F401
|
|
47
|
+
from agentic_auth.models.compiled_policy import CompiledPolicy # noqa: E402,F401
|
|
48
|
+
from agentic_auth.models.manifest import Manifest # noqa: E402,F401
|
|
49
|
+
from agentic_auth.models.reconciliation_report import ReconciliationReport # noqa: E402,F401
|
|
50
|
+
from agentic_auth.models.sandbox_run import SandboxRun # noqa: E402,F401
|
|
51
|
+
from agentic_auth.models.session import Session # noqa: E402,F401
|
|
52
|
+
from agentic_auth.models.step_up_grant import StepUpGrant # noqa: E402,F401
|
|
53
|
+
from agentic_auth.models.transaction_token import TransactionToken # noqa: E402,F401
|
|
54
|
+
from agentic_auth.models.trust_anchor import TrustAnchor # noqa: E402,F401
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"Base",
|
|
58
|
+
"UUIDPrimaryKey",
|
|
59
|
+
"TimestampCreated",
|
|
60
|
+
"Agent",
|
|
61
|
+
"Manifest",
|
|
62
|
+
"CompiledPolicy",
|
|
63
|
+
"ReconciliationReport",
|
|
64
|
+
"Session",
|
|
65
|
+
"AuditDecision",
|
|
66
|
+
"TrustAnchor",
|
|
67
|
+
"TransactionToken",
|
|
68
|
+
"StepUpGrant",
|
|
69
|
+
"SandboxRun",
|
|
70
|
+
]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""``agents`` — one row per registered agent.
|
|
2
|
+
|
|
3
|
+
Phase 4 adds identity state. ``status`` moves ``registered -> enrolled | quarantined``, and
|
|
4
|
+
``enrolled | quarantined -> revoked`` (terminal). A trust anchor version and a principal exist
|
|
5
|
+
together or not at all: identity is pinned as one fact, never half of one.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from sqlalchemy import CheckConstraint, Integer, String
|
|
13
|
+
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
14
|
+
|
|
15
|
+
from agentic_auth.models import Base, TimestampCreated, UUIDPrimaryKey
|
|
16
|
+
from agentic_auth.models.types import PortableJSON
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from agentic_auth.models.manifest import Manifest
|
|
20
|
+
|
|
21
|
+
AGENT_STATUSES = ("registered", "enrolled", "quarantined", "revoked")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Agent(UUIDPrimaryKey, TimestampCreated, Base):
|
|
25
|
+
__tablename__ = "agents"
|
|
26
|
+
__table_args__ = (
|
|
27
|
+
CheckConstraint(
|
|
28
|
+
"status IN ('registered', 'enrolled', 'quarantined', 'revoked')",
|
|
29
|
+
name="ck_agents_status",
|
|
30
|
+
),
|
|
31
|
+
# An anchor version exists exactly when the agent is (or was) enrolled.
|
|
32
|
+
CheckConstraint(
|
|
33
|
+
"(status IN ('enrolled', 'revoked')) = (trust_anchor_version IS NOT NULL)",
|
|
34
|
+
name="ck_agents_anchor_iff_enrolled_or_revoked",
|
|
35
|
+
),
|
|
36
|
+
# A pinned anchor always names an accountable principal.
|
|
37
|
+
CheckConstraint(
|
|
38
|
+
"trust_anchor_version IS NULL OR principal_ref IS NOT NULL",
|
|
39
|
+
name="ck_agents_principal_iff_anchor",
|
|
40
|
+
),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
name: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, index=True)
|
|
44
|
+
# Phase 1 registered agents stay here until they enroll.
|
|
45
|
+
status: Mapped[str] = mapped_column(
|
|
46
|
+
String(16), nullable=False, default="registered", server_default="registered"
|
|
47
|
+
)
|
|
48
|
+
# "<idp issuer>#<sub>" once an accountable principal is bound.
|
|
49
|
+
principal_ref: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
|
50
|
+
# The current trust anchor's version; NULL unless enrolled or revoked.
|
|
51
|
+
trust_anchor_version: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
|
52
|
+
# The identity document a quarantined agent presented, kept for operator inspection.
|
|
53
|
+
# Public keys only; cleared on enrollment.
|
|
54
|
+
pending_identity: Mapped[dict[str, Any] | None] = mapped_column(PortableJSON, nullable=True)
|
|
55
|
+
|
|
56
|
+
manifests: Mapped[list[Manifest]] = relationship(
|
|
57
|
+
back_populates="agent", order_by="Manifest.version"
|
|
58
|
+
)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""``audit_decisions`` — one append-only row per authorization decision.
|
|
2
|
+
|
|
3
|
+
Phase 2's ``decisions`` table, renamed and extended in Phase 3 (migration 0003). ``id`` is
|
|
4
|
+
the action id. Three things hold for every row, forever:
|
|
5
|
+
|
|
6
|
+
- **Nothing updates or deletes it.** A trigger rejects ``UPDATE`` and ``DELETE`` for every
|
|
7
|
+
role, the table owner included, and the runtime role holds only ``SELECT, INSERT``. The
|
|
8
|
+
trigger is also attached below via ``after_create``, so the ``create_all()`` test schema
|
|
9
|
+
enforces exactly what the migration does.
|
|
10
|
+
- **Its chain is decided once.** ``chain`` is materialized at write time from the parent row
|
|
11
|
+
named by the verified token's ``action_id`` claim; ``chain_complete`` never changes after.
|
|
12
|
+
- **It carries no secrets.** No token, credential, or payload is a column.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import uuid
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from sqlalchemy import (
|
|
22
|
+
BigInteger,
|
|
23
|
+
Boolean,
|
|
24
|
+
CheckConstraint,
|
|
25
|
+
ForeignKey,
|
|
26
|
+
Identity,
|
|
27
|
+
Index,
|
|
28
|
+
Integer,
|
|
29
|
+
String,
|
|
30
|
+
UniqueConstraint,
|
|
31
|
+
event,
|
|
32
|
+
func,
|
|
33
|
+
select,
|
|
34
|
+
)
|
|
35
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
36
|
+
from sqlalchemy.types import Uuid
|
|
37
|
+
|
|
38
|
+
from agentic_auth.models import Base, UUIDPrimaryKey
|
|
39
|
+
from agentic_auth.models.types import PortableJSON, TZDateTime, install_append_only
|
|
40
|
+
|
|
41
|
+
TARGET_KIND_AGENT = "agent"
|
|
42
|
+
TARGET_KIND_TOOL = "tool"
|
|
43
|
+
|
|
44
|
+
# The SQL below is duplicated, frozen, in migrations/versions/0003_audit_decisions.py.
|
|
45
|
+
# tests/unit/test_audit_ddl.py fails if the two drift apart.
|
|
46
|
+
APPEND_ONLY_SQL = (
|
|
47
|
+
"""CREATE OR REPLACE FUNCTION audit_decisions_append_only() RETURNS trigger
|
|
48
|
+
LANGUAGE plpgsql AS $$
|
|
49
|
+
BEGIN
|
|
50
|
+
RAISE EXCEPTION 'audit_decisions is append-only' USING ERRCODE = '55000';
|
|
51
|
+
END;
|
|
52
|
+
$$""",
|
|
53
|
+
"""CREATE TRIGGER audit_decisions_no_update_delete
|
|
54
|
+
BEFORE UPDATE OR DELETE ON audit_decisions
|
|
55
|
+
FOR EACH ROW EXECUTE FUNCTION audit_decisions_append_only()""",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
WRITER_ROLE_SQL = """DO $$
|
|
59
|
+
BEGIN
|
|
60
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'agentic_auth_writer') THEN
|
|
61
|
+
CREATE ROLE agentic_auth_writer NOLOGIN;
|
|
62
|
+
END IF;
|
|
63
|
+
END
|
|
64
|
+
$$"""
|
|
65
|
+
|
|
66
|
+
WRITER_GRANTS_SQL = (
|
|
67
|
+
"GRANT USAGE ON SCHEMA public TO agentic_auth_writer",
|
|
68
|
+
"GRANT SELECT, INSERT, UPDATE, DELETE ON agents, manifests, compiled_policies, "
|
|
69
|
+
"reconciliation_reports TO agentic_auth_writer",
|
|
70
|
+
"GRANT SELECT, INSERT ON sessions TO agentic_auth_writer",
|
|
71
|
+
"GRANT SELECT, INSERT ON audit_decisions TO agentic_auth_writer",
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def target_kind_of(target: str) -> str:
|
|
76
|
+
"""Derived from the target itself — never accepted from a caller."""
|
|
77
|
+
return TARGET_KIND_AGENT if target.startswith("agent://") else TARGET_KIND_TOOL
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class AuditDecision(UUIDPrimaryKey, Base):
|
|
81
|
+
__tablename__ = "audit_decisions"
|
|
82
|
+
__table_args__ = (
|
|
83
|
+
CheckConstraint("outcome IN ('allow', 'deny')", name="ck_audit_decisions_outcome"),
|
|
84
|
+
# An allow can never carry a reason; a deny can never lack one.
|
|
85
|
+
CheckConstraint(
|
|
86
|
+
"(outcome = 'deny') = (deny_reason IS NOT NULL)",
|
|
87
|
+
name="ck_audit_decisions_reason_iff_deny",
|
|
88
|
+
),
|
|
89
|
+
CheckConstraint("hop >= 1", name="ck_audit_decisions_hop_positive"),
|
|
90
|
+
CheckConstraint("target_kind IN ('tool', 'agent')", name="ck_audit_decisions_target_kind"),
|
|
91
|
+
CheckConstraint(
|
|
92
|
+
"NOT chain_complete OR chain IS NOT NULL",
|
|
93
|
+
name="ck_audit_decisions_complete_has_chain",
|
|
94
|
+
),
|
|
95
|
+
# Incomplete always says why; complete never carries a reason.
|
|
96
|
+
CheckConstraint(
|
|
97
|
+
"chain_complete = (chain_break IS NULL)",
|
|
98
|
+
name="ck_audit_decisions_break_iff_incomplete",
|
|
99
|
+
),
|
|
100
|
+
CheckConstraint(
|
|
101
|
+
"hop > 1 OR parent_action_id IS NULL", name="ck_audit_decisions_root_has_no_parent"
|
|
102
|
+
),
|
|
103
|
+
UniqueConstraint("seq", name="uq_audit_decisions_seq"),
|
|
104
|
+
Index("ix_audit_decisions_session_seq", "session_id", "seq"),
|
|
105
|
+
Index("ix_audit_decisions_acting_agent_seq", "acting_agent", "seq"),
|
|
106
|
+
Index("ix_audit_decisions_outcome_seq", "outcome", "seq"),
|
|
107
|
+
Index("ix_audit_decisions_outcome_enforced", "outcome", "enforced"),
|
|
108
|
+
Index("ix_audit_decisions_ts", "ts"),
|
|
109
|
+
Index("ix_audit_decisions_parent_action_id", "parent_action_id"),
|
|
110
|
+
)
|
|
111
|
+
# `seq` and `ts` are server-generated; fetch them with the INSERT so no lazy load is
|
|
112
|
+
# ever attempted on an async session.
|
|
113
|
+
__mapper_args__ = {"eager_defaults": True}
|
|
114
|
+
|
|
115
|
+
# Monotonic insertion order — the pagination key.
|
|
116
|
+
seq: Mapped[int] = mapped_column(BigInteger, Identity(always=True), nullable=False)
|
|
117
|
+
session_id: Mapped[uuid.UUID] = mapped_column(
|
|
118
|
+
Uuid(as_uuid=True), ForeignKey("sessions.id"), nullable=False
|
|
119
|
+
)
|
|
120
|
+
ts: Mapped[datetime] = mapped_column(TZDateTime, server_default=func.now(), nullable=False)
|
|
121
|
+
# Request `caller` as sent (`user:<sub>` at hop 1).
|
|
122
|
+
caller: Mapped[str] = mapped_column(String(255), nullable=False)
|
|
123
|
+
# The verified token holder. NULL for a tool-call token and for every legacy row.
|
|
124
|
+
acting_agent: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
|
125
|
+
target: Mapped[str] = mapped_column(String(512), nullable=False)
|
|
126
|
+
target_kind: Mapped[str] = mapped_column(String(8), nullable=False)
|
|
127
|
+
data_class: Mapped[str] = mapped_column(String(128), nullable=False)
|
|
128
|
+
# Derived from the verified act chain, never from a caller-supplied value.
|
|
129
|
+
hop: Mapped[int] = mapped_column(Integer, nullable=False)
|
|
130
|
+
outcome: Mapped[str] = mapped_column(String(8), nullable=False)
|
|
131
|
+
deny_reason: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
|
132
|
+
recoverable: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
|
133
|
+
# False in observe mode. Makes every record unambiguous about what actually happened.
|
|
134
|
+
enforced: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
|
135
|
+
# Phase 4: the EFFECTIVE taint the decision was made under (trusted_internal |
|
|
136
|
+
# untrusted_external), or NULL when unknown. Before Phase 4 it echoed the request.
|
|
137
|
+
taint: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
|
138
|
+
# The target that introduced the taint into this context, or NULL.
|
|
139
|
+
taint_source: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
|
140
|
+
# The target was privileged in the pinned policy.
|
|
141
|
+
privileged: Mapped[bool] = mapped_column(
|
|
142
|
+
Boolean, nullable=False, default=False, server_default="false"
|
|
143
|
+
)
|
|
144
|
+
# Denormalized from the session so a record reads standalone.
|
|
145
|
+
policy_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
|
146
|
+
# The verified actors at decision time: [human, previous actors...].
|
|
147
|
+
act_chain: Mapped[list[Any]] = mapped_column(PortableJSON, nullable=False)
|
|
148
|
+
# `jti` of the presented token. The exchange binds to it. NULL on legacy rows.
|
|
149
|
+
subject_jti: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
|
150
|
+
parent_action_id: Mapped[uuid.UUID | None] = mapped_column(
|
|
151
|
+
Uuid(as_uuid=True),
|
|
152
|
+
ForeignKey("audit_decisions.id", name="fk_audit_decisions_parent_action"),
|
|
153
|
+
nullable=True,
|
|
154
|
+
)
|
|
155
|
+
chain: Mapped[list[dict[str, Any]] | None] = mapped_column(PortableJSON, nullable=True)
|
|
156
|
+
chain_complete: Mapped[bool] = mapped_column(
|
|
157
|
+
Boolean, nullable=False, default=False, server_default="false"
|
|
158
|
+
)
|
|
159
|
+
chain_break: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
|
160
|
+
# Phase 5: how strong the enforcement actually was for this decision — one of
|
|
161
|
+
# full | connector | network | consent_only. Reported by the enforcement point on the
|
|
162
|
+
# request, exactly as `enforced` is, and never an input to the decision.
|
|
163
|
+
#
|
|
164
|
+
# NULL is only ever a legacy row, and is READ AS `full`. That is accurate rather than
|
|
165
|
+
# a guess: every row written before migration 0005 came from the sidecar or the
|
|
166
|
+
# control plane's own path, both of which are per-hop.
|
|
167
|
+
#
|
|
168
|
+
# There is deliberately no NOT NULL constraint — adding one would require rewriting
|
|
169
|
+
# legacy rows, which the append-only trigger forbids. The not-null property is
|
|
170
|
+
# enforced at the write path instead, where the value comes off a StrEnum with no
|
|
171
|
+
# default, so a PEP that omits it gets a 422.
|
|
172
|
+
guarantee_level: Mapped[str | None] = mapped_column(String(16), nullable=True)
|
|
173
|
+
# Which deployment wrote the row: the control plane (`server`) or an embedded instance
|
|
174
|
+
# inside the calling process (`embedded`, development and testing only). Additive; every
|
|
175
|
+
# row written before the column existed came from a server.
|
|
176
|
+
deployment: Mapped[str] = mapped_column(
|
|
177
|
+
String(16), nullable=False, default="server", server_default="server"
|
|
178
|
+
)
|
|
179
|
+
# Set on the audit event that records a step-up widening, pointing at the grant that
|
|
180
|
+
# authorized it. NULL on every ordinary decision.
|
|
181
|
+
step_up_ref: Mapped[uuid.UUID | None] = mapped_column(
|
|
182
|
+
Uuid(as_uuid=True),
|
|
183
|
+
ForeignKey("step_up_grants.id", name="fk_audit_decisions_step_up"),
|
|
184
|
+
nullable=True,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
install_append_only(AuditDecision.__table__, APPEND_ONLY_SQL)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@event.listens_for(AuditDecision, "before_insert")
|
|
192
|
+
def _assign_seq_on_sqlite(_mapper: Any, connection: Any, target: AuditDecision) -> None:
|
|
193
|
+
"""SQLite has no identity column that is not the primary key, so the embedded store
|
|
194
|
+
numbers rows itself. Safe because every embedded transaction begins IMMEDIATE, so no two
|
|
195
|
+
writers ever read the same maximum (agentic_auth/embedded/store.py). PostgreSQL keeps
|
|
196
|
+
``GENERATED ALWAYS``, which would refuse an explicit value — hence the dialect check."""
|
|
197
|
+
if connection.dialect.name != "sqlite" or target.seq is not None:
|
|
198
|
+
return
|
|
199
|
+
target.seq = connection.scalar(select(func.coalesce(func.max(AuditDecision.seq), 0) + 1))
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""``compiled_policies`` — append-only, versioned scope→capability DAG artifacts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import CheckConstraint, Integer, String, UniqueConstraint
|
|
9
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
10
|
+
from sqlalchemy.types import Uuid
|
|
11
|
+
|
|
12
|
+
from agentic_auth.models import Base, TimestampCreated, UUIDPrimaryKey
|
|
13
|
+
from agentic_auth.models.types import PortableArray, PortableJSON
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CompiledPolicy(UUIDPrimaryKey, TimestampCreated, Base):
|
|
17
|
+
__tablename__ = "compiled_policies"
|
|
18
|
+
__table_args__ = (
|
|
19
|
+
UniqueConstraint("scope", "version", name="uq_compiled_policies_scope_version"),
|
|
20
|
+
CheckConstraint("version >= 1", name="ck_compiled_policies_version_positive"),
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
scope: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
|
24
|
+
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
|
25
|
+
dag: Mapped[dict[str, Any]] = mapped_column(PortableJSON, nullable=False)
|
|
26
|
+
source_manifest_ids: Mapped[list[uuid.UUID]] = mapped_column(
|
|
27
|
+
PortableArray(Uuid(as_uuid=True)), nullable=False
|
|
28
|
+
)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""``manifests`` — append-only, server-versioned agent manifests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import TYPE_CHECKING, Any
|
|
8
|
+
|
|
9
|
+
from sqlalchemy import (
|
|
10
|
+
CheckConstraint,
|
|
11
|
+
ForeignKey,
|
|
12
|
+
Index,
|
|
13
|
+
Integer,
|
|
14
|
+
String,
|
|
15
|
+
UniqueConstraint,
|
|
16
|
+
text,
|
|
17
|
+
)
|
|
18
|
+
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
19
|
+
from sqlalchemy.types import Uuid
|
|
20
|
+
|
|
21
|
+
from agentic_auth.models import Base, TimestampCreated, UUIDPrimaryKey
|
|
22
|
+
from agentic_auth.models.types import PortableJSON, TZDateTime
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from agentic_auth.models.agent import Agent
|
|
26
|
+
from agentic_auth.models.reconciliation_report import ReconciliationReport
|
|
27
|
+
|
|
28
|
+
MANIFEST_STATUSES = ("reconciled", "needs_review", "rejected", "proposed")
|
|
29
|
+
|
|
30
|
+
# Phase 5. A proposal is inert: it is never compiled, so no session can pin it and no
|
|
31
|
+
# decision can resolve against it. Every read path that feeds a decision filters it out.
|
|
32
|
+
STATUS_PROPOSED = "proposed"
|
|
33
|
+
RESOLVABLE_STATUSES = ("reconciled", "needs_review", "rejected")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Manifest(UUIDPrimaryKey, TimestampCreated, Base):
|
|
37
|
+
__tablename__ = "manifests"
|
|
38
|
+
__table_args__ = (
|
|
39
|
+
UniqueConstraint("agent_id", "version", name="uq_manifests_agent_version"),
|
|
40
|
+
CheckConstraint("version >= 1", name="ck_manifests_version_positive"),
|
|
41
|
+
CheckConstraint(
|
|
42
|
+
# Phase 5 adds 'proposed': an observation-derived candidate that governs
|
|
43
|
+
# nothing. Inertness is a read-path property, not a constraint — a proposed
|
|
44
|
+
# row is never compiled, so no session can pin it.
|
|
45
|
+
"status IN ('reconciled', 'needs_review', 'rejected', 'proposed')",
|
|
46
|
+
name="ck_manifests_status",
|
|
47
|
+
),
|
|
48
|
+
CheckConstraint(
|
|
49
|
+
"status <> 'reconciled' OR override_reason IS NULL OR override_reason <> ''",
|
|
50
|
+
name="ck_manifests_override_reason_nonempty",
|
|
51
|
+
),
|
|
52
|
+
CheckConstraint("attested_by <> ''", name="ck_manifests_attested_by_nonempty"),
|
|
53
|
+
# Phase 5. An approval always names who approved it; an anonymous ratification is
|
|
54
|
+
# not a human decision.
|
|
55
|
+
CheckConstraint(
|
|
56
|
+
"(ratified_by IS NULL) = (ratified_at IS NULL)",
|
|
57
|
+
name="ck_manifests_ratifier_iff_ratified",
|
|
58
|
+
),
|
|
59
|
+
# An observation-derived manifest is either still proposed or has been ratified.
|
|
60
|
+
# A hand-written manifest has neither a run nor a ratifier and stays legal.
|
|
61
|
+
CheckConstraint(
|
|
62
|
+
"proposed_from_run_id IS NULL OR ratified_at IS NOT NULL OR status = 'proposed'",
|
|
63
|
+
name="ck_manifests_proposal_pending_or_ratified",
|
|
64
|
+
),
|
|
65
|
+
# One proposal per run, and therefore one ratification.
|
|
66
|
+
Index(
|
|
67
|
+
"uq_manifests_proposed_from_run",
|
|
68
|
+
"proposed_from_run_id",
|
|
69
|
+
unique=True,
|
|
70
|
+
postgresql_where=("proposed_from_run_id IS NOT NULL"),
|
|
71
|
+
sqlite_where=text("proposed_from_run_id IS NOT NULL"),
|
|
72
|
+
),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
agent_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("agents.id"), nullable=False, index=True)
|
|
76
|
+
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
|
77
|
+
doc: Mapped[dict[str, Any]] = mapped_column(PortableJSON, nullable=False)
|
|
78
|
+
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
|
79
|
+
attested_by: Mapped[str] = mapped_column(String(255), nullable=False)
|
|
80
|
+
override_reason: Mapped[str | None] = mapped_column(String(1024), nullable=True)
|
|
81
|
+
# Phase 5. The sandbox run this manifest was proposed from, or NULL for a
|
|
82
|
+
# hand-written one. Ratification is recorded here rather than in a second table, so
|
|
83
|
+
# "what the administrator approved" and "what got pinned" are one row that cannot
|
|
84
|
+
# differ.
|
|
85
|
+
proposed_from_run_id: Mapped[uuid.UUID | None] = mapped_column(
|
|
86
|
+
Uuid(as_uuid=True),
|
|
87
|
+
ForeignKey("sandbox_runs.id", name="fk_manifests_proposed_from_run"),
|
|
88
|
+
nullable=True,
|
|
89
|
+
)
|
|
90
|
+
ratified_by: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
|
91
|
+
ratified_at: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True)
|
|
92
|
+
|
|
93
|
+
agent: Mapped[Agent] = relationship(back_populates="manifests")
|
|
94
|
+
reconciliation_report: Mapped[ReconciliationReport | None] = relationship(
|
|
95
|
+
back_populates="manifest", uselist=False
|
|
96
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""``reconciliation_reports`` — one actionable-diff report per manifest submission."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import Boolean, ForeignKey
|
|
9
|
+
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
10
|
+
|
|
11
|
+
from agentic_auth.models import Base, TimestampCreated, UUIDPrimaryKey
|
|
12
|
+
from agentic_auth.models.types import PortableJSON
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from agentic_auth.models.manifest import Manifest
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ReconciliationReport(UUIDPrimaryKey, TimestampCreated, Base):
|
|
19
|
+
__tablename__ = "reconciliation_reports"
|
|
20
|
+
|
|
21
|
+
manifest_id: Mapped[uuid.UUID] = mapped_column(
|
|
22
|
+
ForeignKey("manifests.id"), nullable=False, unique=True, index=True
|
|
23
|
+
)
|
|
24
|
+
diff: Mapped[list[dict[str, Any]]] = mapped_column(PortableJSON, nullable=False)
|
|
25
|
+
discovery_ok: Mapped[bool] = mapped_column(Boolean, nullable=False)
|
|
26
|
+
|
|
27
|
+
manifest: Mapped[Manifest] = relationship(back_populates="reconciliation_report")
|