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,93 @@
1
+ """``sandbox_runs`` — one bounded observation of an agent that has no manifest yet.
2
+
3
+ Deliberately **not** append-only, unlike the other Phase 4/5 record tables: a run
4
+ legitimately transitions ``running -> completed``. The durability guarantee lives on the
5
+ artefact the run produces — a ratified manifest is immutable — not on the observation.
6
+
7
+ Two invariants are in the database:
8
+
9
+ - **One run at a time per agent.** A partial unique index on ``agent_id WHERE status =
10
+ 'running'``. Two concurrent traces racing to become one proposal is a correctness
11
+ problem, not a capacity one, so the second start is a ``409``.
12
+ - **A run is open exactly while it has no end.** ``(status = 'running') = (ended_at IS
13
+ NULL)``, so a crashed run cannot sit as ``completed`` with nothing recorded.
14
+
15
+ ``recorder_errors`` is carried out of the ``EdgeTrace``. Non-zero means observation was
16
+ incomplete, so the proposal may be narrower than the agent's real behaviour — and the
17
+ proposal says so rather than silently under-declaring.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import uuid
23
+ from datetime import datetime
24
+ from typing import Any
25
+
26
+ from sqlalchemy import (
27
+ CheckConstraint,
28
+ ForeignKey,
29
+ Index,
30
+ Integer,
31
+ String,
32
+ text,
33
+ )
34
+ from sqlalchemy.orm import Mapped, mapped_column
35
+ from sqlalchemy.types import Uuid
36
+
37
+ from agentic_auth.models import Base, UUIDPrimaryKey
38
+ from agentic_auth.models.types import PortableJSON, TZDateTime
39
+
40
+ STATUS_RUNNING = "running"
41
+ STATUS_COMPLETED = "completed"
42
+ STATUS_DEADLINE_EXCEEDED = "deadline_exceeded"
43
+ STATUS_FAILED = "failed"
44
+
45
+ STATUSES = (STATUS_RUNNING, STATUS_COMPLETED, STATUS_DEADLINE_EXCEEDED, STATUS_FAILED)
46
+
47
+
48
+ class SandboxRun(UUIDPrimaryKey, Base):
49
+ __tablename__ = "sandbox_runs"
50
+ __table_args__ = (
51
+ CheckConstraint(
52
+ "status IN ('running', 'completed', 'deadline_exceeded', 'failed')",
53
+ name="ck_sandbox_runs_status",
54
+ ),
55
+ CheckConstraint(
56
+ "(status = 'running') = (ended_at IS NULL)",
57
+ name="ck_sandbox_runs_open_iff_no_end",
58
+ ),
59
+ CheckConstraint("deadline_at > started_at", name="ck_sandbox_runs_deadline_after_start"),
60
+ CheckConstraint("recorder_errors >= 0", name="ck_sandbox_runs_recorder_errors_nonneg"),
61
+ # One run at a time per agent. Partial, so completed runs accumulate freely.
62
+ Index(
63
+ "uq_sandbox_runs_one_running_per_agent",
64
+ "agent_id",
65
+ unique=True,
66
+ postgresql_where=("status = 'running'"),
67
+ sqlite_where=text("status = 'running'"),
68
+ ),
69
+ Index("ix_sandbox_runs_agent_started", "agent_id", "started_at"),
70
+ )
71
+
72
+ agent_id: Mapped[uuid.UUID] = mapped_column(
73
+ Uuid(as_uuid=True), ForeignKey("agents.id"), nullable=False
74
+ )
75
+ # 24, not 16: "deadline_exceeded" is 17 characters. A column too narrow for its own
76
+ # longest legal value is a bug that only shows up on the unhappy path.
77
+ status: Mapped[str] = mapped_column(String(24), nullable=False, default=STATUS_RUNNING)
78
+ # The scope the run is driven under — a synthetic all-allow scope, not a real one.
79
+ scope: Mapped[str] = mapped_column(String(255), nullable=False)
80
+ started_at: Mapped[datetime] = mapped_column(TZDateTime, nullable=False)
81
+ # started_at + sandbox_run_deadline_seconds. The run ends here whether or not the
82
+ # agent stopped.
83
+ deadline_at: Mapped[datetime] = mapped_column(TZDateTime, nullable=False)
84
+ ended_at: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True)
85
+ # The folded EdgeTrace. NULL while running.
86
+ trace: Mapped[dict[str, Any] | None] = mapped_column(PortableJSON, nullable=True)
87
+ recorder_errors: Mapped[int] = mapped_column(
88
+ Integer, nullable=False, default=0, server_default="0"
89
+ )
90
+
91
+ @property
92
+ def open(self) -> bool:
93
+ return self.status == STATUS_RUNNING
@@ -0,0 +1,63 @@
1
+ """``sessions`` — the unit of consented authority.
2
+
3
+ Immutable after insert. No column is ever updated: that is what keeps the PDP stateless,
4
+ since nothing accumulates across hops and a session read is a pure lookup.
5
+
6
+ **Phase 5 does not change that.** Step-up widens a session, but it does so by appending a
7
+ ``step_up_grants`` row and a Redis set entry that the decision reads alongside the taint
8
+ hash and the revoked set — never by updating this table. Mutating a row here would
9
+ invalidate ``session:{id}`` mid-flight and give the PDP a second source of truth for a
10
+ decision input.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from datetime import datetime
16
+
17
+ from sqlalchemy import (
18
+ CheckConstraint,
19
+ ForeignKeyConstraint,
20
+ Index,
21
+ Integer,
22
+ String,
23
+ )
24
+ from sqlalchemy.orm import Mapped, mapped_column
25
+
26
+ from agentic_auth.models import Base, TimestampCreated, UUIDPrimaryKey
27
+ from agentic_auth.models.types import PortableArray, TZDateTime
28
+
29
+
30
+ class Session(UUIDPrimaryKey, TimestampCreated, Base):
31
+ __tablename__ = "sessions"
32
+ __table_args__ = (
33
+ # A session can only pin a policy version that exists.
34
+ ForeignKeyConstraint(
35
+ ["scope", "policy_version"],
36
+ ["compiled_policies.scope", "compiled_policies.version"],
37
+ name="fk_sessions_compiled_policy",
38
+ ),
39
+ CheckConstraint("hop_budget >= 1", name="ck_sessions_hop_budget_positive"),
40
+ CheckConstraint("expires_at > created_at", name="ck_sessions_expiry_after_creation"),
41
+ CheckConstraint("user_sub <> ''", name="ck_sessions_user_sub_nonempty"),
42
+ Index("ix_sessions_expires_at", "expires_at"),
43
+ )
44
+
45
+ scope: Mapped[str] = mapped_column(String(255), nullable=False)
46
+ user_sub: Mapped[str] = mapped_column(String(255), nullable=False)
47
+ # Pinned at consent. Every decision in this session resolves against it, even if a
48
+ # newer policy version is published mid-chain.
49
+ policy_version: Mapped[int] = mapped_column(Integer, nullable=False)
50
+ hop_budget: Mapped[int] = mapped_column(Integer, nullable=False)
51
+ expires_at: Mapped[datetime] = mapped_column(TZDateTime, nullable=False)
52
+ # Phase 5. The subset of the pinned policy's data classes this consent covers.
53
+ #
54
+ # NULL means "every data class the pinned policy declares", which is exactly Phase 2-4
55
+ # semantics — so there is no backfill and no existing row changes meaning. A non-null
56
+ # array is validated against the pinned policy at consent time, not at first use, so a
57
+ # typo surfaces to the integrator immediately instead of as a refusal three hops in.
58
+ #
59
+ # Still immutable: step-up appends a `step_up_grants` row, it does not extend this
60
+ # array.
61
+ consented_data_classes: Mapped[list[str] | None] = mapped_column(
62
+ PortableArray(String(128)), nullable=True
63
+ )
@@ -0,0 +1,106 @@
1
+ """``step_up_grants`` — one append-only row per answered step-up challenge.
2
+
3
+ A widening a human approved is a security fact, and a security fact that can be edited is
4
+ not evidence. Same trigger shape as ``audit_decisions`` and ``transaction_tokens``; the
5
+ runtime role holds ``SELECT, INSERT`` only.
6
+
7
+ Three things this table makes true in the database rather than in code:
8
+
9
+ - **A grant is an approval or a decline, never both and never neither.**
10
+ - **An approval always names who approved it.** An anonymous widening is not consent.
11
+ - **A challenge can be answered once.** ``UNIQUE (challenge_hash)`` is the durable twin of
12
+ the Redis ``GETDEL``: even if the cache were lost and a challenge replayed, the second
13
+ insert is an ``IntegrityError``.
14
+
15
+ **The ceiling is enforced before the insert, not here.** ``data_class`` is checked against
16
+ ``PolicyIndex.data_classes_by_agent`` in :mod:`agentic_auth.services.stepup`, so a row outside the
17
+ pinned policy cannot exist. A check constraint could not express it: the policy
18
+ lives in another table, versioned per session.
19
+
20
+ The challenge value itself is never stored — only its SHA-256.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import uuid
26
+ from datetime import datetime
27
+
28
+ from sqlalchemy import (
29
+ CheckConstraint,
30
+ ForeignKey,
31
+ Index,
32
+ String,
33
+ func,
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 TZDateTime, install_append_only
40
+
41
+ # Duplicated, frozen, in migrations/versions/0005_stepup_coldstart_guarantee.py.
42
+ # tests/unit/test_audit_ddl.py fails if the two drift apart.
43
+ STEP_UP_APPEND_ONLY_SQL = (
44
+ """CREATE OR REPLACE FUNCTION step_up_grants_append_only() RETURNS trigger
45
+ LANGUAGE plpgsql AS $$
46
+ BEGIN
47
+ RAISE EXCEPTION 'step_up_grants is append-only' USING ERRCODE = '55000';
48
+ END;
49
+ $$""",
50
+ """CREATE TRIGGER step_up_grants_no_update_delete
51
+ BEFORE UPDATE OR DELETE ON step_up_grants
52
+ FOR EACH ROW EXECUTE FUNCTION step_up_grants_append_only()""",
53
+ )
54
+
55
+ WRITER_GRANTS_SQL_0005 = (
56
+ "GRANT SELECT, INSERT ON step_up_grants TO agentic_auth_writer",
57
+ # A run legitimately transitions running -> completed, so this one is updatable.
58
+ "GRANT SELECT, INSERT, UPDATE ON sandbox_runs TO agentic_auth_writer",
59
+ )
60
+
61
+
62
+ class StepUpGrant(UUIDPrimaryKey, Base):
63
+ __tablename__ = "step_up_grants"
64
+ __table_args__ = (
65
+ CheckConstraint(
66
+ "(approved_at IS NULL) <> (declined_at IS NULL)",
67
+ name="ck_step_up_grants_approved_xor_declined",
68
+ ),
69
+ CheckConstraint(
70
+ "(approved_by IS NULL) = (approved_at IS NULL)",
71
+ name="ck_step_up_grants_approver_iff_approved",
72
+ ),
73
+ CheckConstraint("data_class <> ''", name="ck_step_up_grants_data_class_nonempty"),
74
+ Index("ix_step_up_grants_session_created", "session_id", "created_at"),
75
+ )
76
+
77
+ session_id: Mapped[uuid.UUID] = mapped_column(
78
+ Uuid(as_uuid=True), ForeignKey("sessions.id"), nullable=False
79
+ )
80
+ # The refusal that raised the challenge. This is the audit link: the widening event
81
+ # carries `step_up_ref` back to this row, and this row points at the deny it answers.
82
+ blocked_action_id: Mapped[uuid.UUID] = mapped_column(
83
+ Uuid(as_uuid=True),
84
+ ForeignKey("audit_decisions.id", name="fk_step_up_grants_blocked_action"),
85
+ nullable=False,
86
+ )
87
+ # What was granted. Always within the pinned policy's ceiling; see the module docstring.
88
+ data_class: Mapped[str] = mapped_column(String(128), nullable=False)
89
+ # The blocked hop's target, so an operator reading the row does not have to join.
90
+ target: Mapped[str] = mapped_column(String(512), nullable=False)
91
+ # SHA-256 (hex) of the challenge id. The challenge itself never lands anywhere durable.
92
+ challenge_hash: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
93
+ # The consenting human's sub. NULL on a decline.
94
+ approved_by: Mapped[str | None] = mapped_column(String(255), nullable=True)
95
+ approved_at: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True)
96
+ declined_at: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True)
97
+ created_at: Mapped[datetime] = mapped_column(
98
+ TZDateTime, server_default=func.now(), nullable=False
99
+ )
100
+
101
+ @property
102
+ def approved(self) -> bool:
103
+ return self.approved_at is not None
104
+
105
+
106
+ install_append_only(StepUpGrant.__table__, STEP_UP_APPEND_ONLY_SQL)
@@ -0,0 +1,73 @@
1
+ """``transaction_tokens`` — one append-only row per call-bound authority.
2
+
3
+ Two facts this table makes true in the database, not in code:
4
+
5
+ - **One transaction token per recorded allow decision.** ``UNIQUE (action_id)``. A second
6
+ mint for the same decision is an ``IntegrityError``, never a second token.
7
+ - **Nothing rewrites history.** The same trigger shape as ``audit_decisions``; the runtime
8
+ role holds ``SELECT, INSERT`` only.
9
+
10
+ The token itself is never stored. ``params_hash`` is the fingerprint the audit read
11
+ models join on.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import uuid
17
+ from datetime import datetime
18
+
19
+ from sqlalchemy import CheckConstraint, ForeignKey, String
20
+ from sqlalchemy.orm import Mapped, mapped_column
21
+ from sqlalchemy.types import Uuid
22
+
23
+ from agentic_auth.models import Base
24
+ from agentic_auth.models.types import PortableJSON, TZDateTime, install_append_only
25
+
26
+ # Duplicated, frozen, in migrations/versions/0004_identity_taint_transactions.py.
27
+ # tests/unit/test_audit_ddl.py fails if the two drift apart.
28
+ TXN_APPEND_ONLY_SQL = (
29
+ """CREATE OR REPLACE FUNCTION transaction_tokens_append_only() RETURNS trigger
30
+ LANGUAGE plpgsql AS $$
31
+ BEGIN
32
+ RAISE EXCEPTION 'transaction_tokens is append-only' USING ERRCODE = '55000';
33
+ END;
34
+ $$""",
35
+ """CREATE TRIGGER transaction_tokens_no_update_delete
36
+ BEFORE UPDATE OR DELETE ON transaction_tokens
37
+ FOR EACH ROW EXECUTE FUNCTION transaction_tokens_append_only()""",
38
+ )
39
+
40
+ WRITER_GRANTS_SQL_0004 = (
41
+ # Revocation and enrollment update these two; nothing else is ever updated.
42
+ "GRANT SELECT, INSERT, UPDATE ON trust_anchors TO agentic_auth_writer",
43
+ "GRANT SELECT, INSERT ON transaction_tokens TO agentic_auth_writer",
44
+ )
45
+
46
+
47
+ class TransactionToken(Base):
48
+ __tablename__ = "transaction_tokens"
49
+ __table_args__ = (
50
+ CheckConstraint("expires_at > issued_at", name="ck_transaction_tokens_expiry_after_issue"),
51
+ )
52
+
53
+ # The token's jti (= txn). The single-use handle at the resource.
54
+ jti: Mapped[str] = mapped_column(String(64), primary_key=True)
55
+ action_id: Mapped[uuid.UUID] = mapped_column(
56
+ Uuid(as_uuid=True),
57
+ ForeignKey("audit_decisions.id", name="fk_transaction_tokens_action"),
58
+ nullable=False,
59
+ unique=True,
60
+ )
61
+ session_id: Mapped[uuid.UUID] = mapped_column(
62
+ Uuid(as_uuid=True), ForeignKey("sessions.id"), nullable=False, index=True
63
+ )
64
+ target: Mapped[str] = mapped_column(String(512), nullable=False)
65
+ # base64url SHA-256 of the canonical binding document (docs/canonicalization.md).
66
+ params_hash: Mapped[str] = mapped_column(String(64), nullable=False)
67
+ # The RFC 6901 pointers applied, or NULL for the whole body.
68
+ binding: Mapped[list[str] | None] = mapped_column(PortableJSON, nullable=True)
69
+ issued_at: Mapped[datetime] = mapped_column(TZDateTime, nullable=False)
70
+ expires_at: Mapped[datetime] = mapped_column(TZDateTime, nullable=False)
71
+
72
+
73
+ install_append_only(TransactionToken.__table__, TXN_APPEND_ONLY_SQL)
@@ -0,0 +1,59 @@
1
+ """``trust_anchors`` — one row per pinned (key set, manifest version, principal).
2
+
3
+ At most one row per agent is *live* (``revoked_at IS NULL``), enforced by a partial unique
4
+ index. Re-enrollment revokes the previous row and inserts ``version + 1`` in one
5
+ transaction; revocation sets ``revoked_at`` and never clears it. ``key_thumbprints`` is
6
+ what "a revoked key is never re-pinned" checks against — a ``kid`` is chosen by the agent
7
+ and proves nothing.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import uuid
13
+ from datetime import datetime
14
+ from typing import Any
15
+
16
+ from sqlalchemy import (
17
+ CheckConstraint,
18
+ ForeignKey,
19
+ Index,
20
+ Integer,
21
+ String,
22
+ Text,
23
+ UniqueConstraint,
24
+ text,
25
+ )
26
+ from sqlalchemy.orm import Mapped, mapped_column
27
+ from sqlalchemy.types import Uuid
28
+
29
+ from agentic_auth.models import Base, TimestampCreated, UUIDPrimaryKey
30
+ from agentic_auth.models.types import PortableArray, PortableJSON, TZDateTime
31
+
32
+
33
+ class TrustAnchor(UUIDPrimaryKey, TimestampCreated, Base):
34
+ __tablename__ = "trust_anchors"
35
+ __table_args__ = (
36
+ UniqueConstraint("agent_id", "version", name="uq_trust_anchors_agent_version"),
37
+ CheckConstraint("version >= 1", name="ck_trust_anchors_version_positive"),
38
+ Index("ix_trust_anchors_revoked_at", "revoked_at"),
39
+ Index(
40
+ "uq_trust_anchors_one_current",
41
+ "agent_id",
42
+ unique=True,
43
+ postgresql_where="revoked_at IS NULL",
44
+ sqlite_where=text("revoked_at IS NULL"),
45
+ ),
46
+ )
47
+
48
+ agent_id: Mapped[uuid.UUID] = mapped_column(
49
+ Uuid(as_uuid=True), ForeignKey("agents.id"), nullable=False, index=True
50
+ )
51
+ version: Mapped[int] = mapped_column(Integer, nullable=False)
52
+ # {"keys": [...]}: OKP/Ed25519 public keys only, each with a kid.
53
+ jwks: Mapped[dict[str, Any]] = mapped_column(PortableJSON, nullable=False)
54
+ key_thumbprints: Mapped[list[str]] = mapped_column(PortableArray(Text), nullable=False)
55
+ principal_ref: Mapped[str] = mapped_column(String(255), nullable=False)
56
+ manifest_version: Mapped[int] = mapped_column(Integer, nullable=False)
57
+ revoked_at: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True)
58
+ # Operator note from POST /v1/agents/{id}/revoke.
59
+ revoke_reason: Mapped[str | None] = mapped_column(String(1024), nullable=True)
@@ -0,0 +1,95 @@
1
+ """Column types and DDL that mean the same thing on PostgreSQL and SQLite.
2
+
3
+ PostgreSQL is the control plane's database. SQLite is the embedded control plane's
4
+ (``agentic_auth.embedded``): the same models, the same repositories, the same services, in
5
+ one process with no server. Every type here renders *exactly* the PostgreSQL DDL it replaced,
6
+ so the server schema and its migrations are unchanged; only the SQLite rendering is new.
7
+
8
+ The three things SQLite does not do natively, and what stands in for each:
9
+
10
+ - ``JSONB`` and ``ARRAY`` — JSON text.
11
+ - ``timestamptz`` — SQLite keeps no offset, so a stored UTC value comes back naive and then
12
+ fails every comparison against ``datetime.now(UTC)``. Values are normalised to UTC going in
13
+ and re-attached to UTC coming out.
14
+ - Append-only enforcement — a ``BEFORE UPDATE``/``BEFORE DELETE`` trigger that aborts, the
15
+ SQLite counterpart of the PL/pgSQL triggers in migrations 0003–0005.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import uuid
21
+ from datetime import UTC, datetime
22
+ from typing import Any
23
+
24
+ from sqlalchemy import DDL, JSON, DateTime, Uuid, event
25
+ from sqlalchemy.dialects.postgresql import ARRAY, JSONB
26
+ from sqlalchemy.engine import Dialect
27
+ from sqlalchemy.sql import FromClause
28
+ from sqlalchemy.types import TypeDecorator, TypeEngine
29
+
30
+ PortableJSON = JSON().with_variant(JSONB(), "postgresql")
31
+
32
+
33
+ class PortableArray(TypeDecorator[list[Any]]):
34
+ """``ARRAY(item_type)`` on PostgreSQL; a JSON list elsewhere. UUID items round-trip."""
35
+
36
+ impl = JSON
37
+ cache_ok = True
38
+
39
+ def __init__(self, item_type: TypeEngine[Any] | type[TypeEngine[Any]]) -> None:
40
+ super().__init__()
41
+ self.item_type = item_type() if isinstance(item_type, type) else item_type
42
+
43
+ def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
44
+ if dialect.name == "postgresql":
45
+ return dialect.type_descriptor(ARRAY(self.item_type))
46
+ return dialect.type_descriptor(JSON())
47
+
48
+ def process_bind_param(self, value: list[Any] | None, dialect: Dialect) -> Any:
49
+ if value is None or dialect.name == "postgresql":
50
+ return value
51
+ return [str(item) if isinstance(item, uuid.UUID) else item for item in value]
52
+
53
+ def process_result_value(self, value: Any, dialect: Dialect) -> list[Any] | None:
54
+ if value is None or dialect.name == "postgresql":
55
+ return value
56
+ if isinstance(self.item_type, Uuid):
57
+ return [uuid.UUID(item) for item in value]
58
+ return list(value)
59
+
60
+
61
+ class _UTCDateTime(TypeDecorator[datetime]):
62
+ """SQLite only: stores naive UTC, returns aware UTC."""
63
+
64
+ impl = DateTime
65
+ cache_ok = True
66
+
67
+ def process_bind_param(self, value: datetime | None, dialect: Dialect) -> datetime | None:
68
+ if value is None or value.tzinfo is None:
69
+ return value
70
+ return value.astimezone(UTC).replace(tzinfo=None)
71
+
72
+ def process_result_value(self, value: datetime | None, dialect: Dialect) -> datetime | None:
73
+ if value is None:
74
+ return None
75
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
76
+
77
+
78
+ TZDateTime = DateTime(timezone=True).with_variant(_UTCDateTime(), "sqlite")
79
+
80
+
81
+ def install_append_only(table: FromClause, postgresql: tuple[str, ...]) -> None:
82
+ """Attach append-only enforcement to ``table`` for whichever dialect creates it.
83
+
84
+ ``postgresql`` is the frozen PL/pgSQL from the migrations (tests/unit/test_audit_ddl.py
85
+ holds the two equal). The SQLite triggers are generated: same table, same refusal.
86
+ """
87
+ for statement in postgresql:
88
+ event.listen(table, "after_create", DDL(statement).execute_if(dialect="postgresql"))
89
+ name = table.name # type: ignore[attr-defined] # a mapped class's __table__ is a Table
90
+ for op in ("UPDATE", "DELETE"):
91
+ sqlite = (
92
+ f"CREATE TRIGGER {name}_no_{op.lower()} BEFORE {op} ON {name} "
93
+ f"BEGIN SELECT RAISE(ABORT, '{name} is append-only'); END"
94
+ )
95
+ event.listen(table, "after_create", DDL(sqlite).execute_if(dialect="sqlite"))