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,95 @@
1
+ """Per-hop context.
2
+
3
+ The delegation chain and the depth are **read from the token**, never tracked alongside
4
+ it. There is no counter to increment and no list to append to, so a client cannot drift
5
+ out of sync with the signed truth — which is the whole point of deriving depth from
6
+ ``act`` in the first place.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import binascii
13
+ import json
14
+ from dataclasses import dataclass
15
+ from typing import Any
16
+
17
+ SESSION_HEADER = "X-Agentic-Session"
18
+
19
+
20
+ def _claims(token: str) -> dict[str, Any]:
21
+ try:
22
+ payload = token.split(".")[1]
23
+ return json.loads(base64.urlsafe_b64decode(payload + "=="))
24
+ except (IndexError, ValueError, binascii.Error, UnicodeDecodeError):
25
+ return {}
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class HopContext:
30
+ """What travels between hops: the session and the current token — plus, within a hop,
31
+ the taint this context has accumulated. The token's own ``taint`` claim is the
32
+ floor; ``tainted()`` can only raise it."""
33
+
34
+ session_id: str
35
+ token: str
36
+ _taint: str | None = None
37
+
38
+ @property
39
+ def taint(self) -> str | None:
40
+ """``trusted_internal`` | ``untrusted_external`` | ``None`` (nothing known)."""
41
+ claim = self.claims.get("taint")
42
+ labels = [x for x in (claim, self._taint) if x]
43
+ if not labels:
44
+ return None
45
+ return "untrusted_external" if "untrusted_external" in labels else "trusted_internal"
46
+
47
+ def tainted(self, trust: str, source_ref: str | None = None) -> HopContext:
48
+ """A copy whose taint is at least ``trust``. Monotonic: never lowers."""
49
+ if trust not in ("trusted_internal", "untrusted_external"):
50
+ raise ValueError(f"unknown trust class {trust!r}")
51
+ current = self.taint
52
+ if current == "untrusted_external" or trust == "trusted_internal":
53
+ return HopContext(self.session_id, self.token, current)
54
+ return HopContext(self.session_id, self.token, trust)
55
+
56
+ @property
57
+ def claims(self) -> dict[str, Any]:
58
+ return _claims(self.token)
59
+
60
+ @property
61
+ def act_chain(self) -> list[str]:
62
+ """``[human, first delegate, ..., current actor]``."""
63
+ c = self.claims
64
+ actors: list[str] = []
65
+ act = c.get("act")
66
+ while isinstance(act, dict):
67
+ actors.append(act.get("sub", ""))
68
+ act = act.get("act")
69
+ return [c.get("sub", ""), *reversed(actors)]
70
+
71
+ @property
72
+ def hop(self) -> int:
73
+ """Depth of the hop this token is being presented for."""
74
+ return len(self.act_chain)
75
+
76
+ @property
77
+ def caller(self) -> str:
78
+ """Who holds this token: the agent it was issued to, or the human at the root."""
79
+ c = self.claims
80
+ return c.get("aud", "") if c.get("act") else c.get("sub", "")
81
+
82
+ def headers(self) -> dict[str, str]:
83
+ """The complete propagation format. The chain and depth ride inside the signed
84
+ token; the session id is a convenience so the next hop can look up its session
85
+ before parsing a token it has not yet verified.
86
+
87
+ Nothing security-relevant travels in a header — a forged session id that
88
+ disagrees with the token's own is a deny.
89
+ """
90
+ return {"Authorization": f"Bearer {self.token}", SESSION_HEADER: self.session_id}
91
+
92
+ def advanced(self, token: str) -> HopContext:
93
+ """The context for the next hop. Same session, new narrowed token. The new token's
94
+ ``taint`` claim carries the delegator's taint downstream; nothing else is copied."""
95
+ return HopContext(session_id=self.session_id, token=token)
@@ -0,0 +1,118 @@
1
+ """The CI gate, callable from code.
2
+
3
+ ``agentic-auth drift record`` and ``drift check`` are the command-line form of exactly
4
+ this: aggregate the edge events an enforcement point recorded into one trace, then ask
5
+ whether every observed edge was declared. These functions exist so a pipeline — or a
6
+ notebook — can run the same gate in-process and branch on the report instead of parsing
7
+ stdout.
8
+
9
+ Both run from files only. No discovery, no reconciliation, no control plane, no
10
+ credentials: the question is only "was every observed edge declared", and CI should be
11
+ able to answer it offline.
12
+
13
+ Never a pass without evidence. Invalid or missing inputs, lost events, and a run that
14
+ observed nothing at all are each a distinct ``error`` in the report, and
15
+ :func:`check_drift` reports those as a failure rather than a pass.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from agentic_auth._extras import require_extra
21
+
22
+ require_extra("agentic_auth.sdk.drift", "drift", "yaml", "pydantic")
23
+
24
+ import os
25
+ from collections.abc import Sequence
26
+ from datetime import UTC, datetime
27
+ from pathlib import Path
28
+
29
+ from agentic_auth.schemas.edge_trace import DriftReport, EdgeTrace
30
+ from agentic_auth.services.drift import run_check
31
+ from agentic_auth.services.edge_trace import TRACE_PATH_ENV, EdgeRecorder, aggregate
32
+
33
+ # What CI exits with. `drift check` uses the same two codes.
34
+ PASS_EXIT = 0
35
+ FAIL_EXIT = 1
36
+
37
+
38
+ def trace_recorder(path: str | os.PathLike[str]) -> EdgeRecorder:
39
+ """An edge recorder writing to ``path``, for an enforcement point the SDK does not own.
40
+
41
+ An ``AgenticAuthClient`` built with ``trace_path=`` (or with
42
+ ``AGENTIC_AUTH_TRACE_PATH`` set, which is how ``drift record`` wires a child process)
43
+ already records one event per ``authorize``. Use this only to record edges taken by
44
+ something else — a hand-rolled call path, or a test harness standing in for one.
45
+ """
46
+ return EdgeRecorder(path, "sdk")
47
+
48
+
49
+ def trace_env(path: str | os.PathLike[str]) -> dict[str, str]:
50
+ """The environment a child process needs to record into ``path``.
51
+
52
+ ``{**os.environ, **trace_env(p)}`` is what ``drift record`` passes to the command it
53
+ wraps, so every SDK client and sidecar inside it records to one file.
54
+ """
55
+ return {TRACE_PATH_ENV: os.fspath(path)}
56
+
57
+
58
+ def aggregate_trace(
59
+ event_files: Sequence[str | os.PathLike[str]],
60
+ *,
61
+ out: str | os.PathLike[str] | None = None,
62
+ started_at: datetime | None = None,
63
+ finished_at: datetime | None = None,
64
+ command: list[str] | None = None,
65
+ exit_code: int | None = None,
66
+ ) -> EdgeTrace:
67
+ """Deduplicate recorded events into one trace — the ``drift record`` half of the gate.
68
+
69
+ ``recorder_errors`` counts evidence that was lost (an unparseable line, a killed
70
+ process, a write that failed). A non-zero count is why :func:`check_drift` refuses to
71
+ report a pass: a shrunken trace would otherwise look like a clean run.
72
+ """
73
+ now = datetime.now(UTC)
74
+ trace = aggregate(
75
+ [Path(os.fspath(f)) for f in event_files],
76
+ started_at=started_at or now,
77
+ finished_at=finished_at or now,
78
+ command=command,
79
+ exit_code=exit_code,
80
+ )
81
+ if out is not None:
82
+ Path(os.fspath(out)).write_text(trace.model_dump_json(indent=2), encoding="utf-8")
83
+ return trace
84
+
85
+
86
+ def check_drift(
87
+ manifest_dirs: Sequence[str | os.PathLike[str]],
88
+ trace: str | os.PathLike[str],
89
+ *,
90
+ generated_at: datetime | None = None,
91
+ ) -> DriftReport:
92
+ """Observed edges versus declared manifests — the ``drift check`` half of the gate.
93
+
94
+ The verdict for every edge comes from the same function the runtime PDP calls, over an
95
+ index built by the same compiler, so a pipeline and production cannot disagree about
96
+ what the manifests declare.
97
+ """
98
+ return run_check(
99
+ [Path(os.fspath(d)) for d in manifest_dirs],
100
+ Path(os.fspath(trace)),
101
+ generated_at=generated_at,
102
+ )
103
+
104
+
105
+ def exit_code_for(report: DriftReport) -> int:
106
+ """``0`` only for a clean, evidenced pass: no undeclared edges and no errors."""
107
+ return PASS_EXIT if report.result == "pass" else FAIL_EXIT
108
+
109
+
110
+ __all__ = [
111
+ "FAIL_EXIT",
112
+ "PASS_EXIT",
113
+ "aggregate_trace",
114
+ "check_drift",
115
+ "exit_code_for",
116
+ "trace_env",
117
+ "trace_recorder",
118
+ ]
@@ -0,0 +1,147 @@
1
+ """Every way an SDK call can refuse, in one place.
2
+
3
+ Three kinds, because a caller handles them differently:
4
+
5
+ * :class:`PolicyDenied` — the system worked and the answer is no. Carries the machine
6
+ reason, the recorded ``action_id``, and whether a step-up could recover it.
7
+ * :class:`ControlPlaneRejected` — the *request* was wrong (unknown agent, bad manifest,
8
+ wrong bearer). Fix the call. :class:`ManifestRejected` is the one worth catching by
9
+ name: it carries the reconciliation diff that says what to change.
10
+ * :class:`ControlPlaneUnavailable` — the system could not answer. Never proceed.
11
+
12
+ :class:`TransactionParamsRequired` is its own case: a privileged call the SDK refuses to
13
+ even attempt, because binding it needs parameters the caller did not pass. It is raised
14
+ before anything is spent.
15
+
16
+ They live here rather than next to the client so the admin/audit/identity planes and the
17
+ hop path can raise the same types without importing each other.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Any
23
+
24
+ from agentic_auth.schemas.authorize import DenyReason, is_recoverable
25
+
26
+
27
+ class PolicyDenied(Exception):
28
+ """A hop was refused.
29
+
30
+ Raised rather than returned: a refusal that is easy to ignore is a refusal that gets
31
+ ignored, and routing around the SDK is the failure mode this product exists to
32
+ prevent.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ reason: DenyReason,
38
+ *,
39
+ message: str,
40
+ target: str,
41
+ hop: int,
42
+ session_id: str,
43
+ policy_version: int | None = None,
44
+ action_id: str | None = None,
45
+ taint: str | None = None,
46
+ taint_source: str | None = None,
47
+ challenge: dict[str, Any] | None = None,
48
+ data_class: str | None = None,
49
+ ) -> None:
50
+ super().__init__(f"{reason.value}: {message}")
51
+ self.reason = reason
52
+ self.message = message
53
+ self.target = target
54
+ self.hop = hop
55
+ self.session_id = session_id
56
+ self.policy_version = policy_version
57
+ # Phase 4: the effective taint the refusal was decided under, and what introduced it.
58
+ self.taint = taint
59
+ self.taint_source = taint_source
60
+ # The audit record of this refusal — fetch its chain with
61
+ # GET /v1/audit/actions/{action_id}/chain. None when it could not be recorded.
62
+ self.action_id = action_id
63
+ # Phase 5. Present only when this refusal is recoverable AND the deployment has
64
+ # step-up enabled: the question to put to the consenting human. A non-recoverable
65
+ # refusal never carries one, so `if denied.challenge:` is a safe thing to branch
66
+ # on without re-checking recoverability.
67
+ self.challenge = challenge
68
+ self.data_class = data_class
69
+
70
+ @property
71
+ def recoverable(self) -> bool:
72
+ """True only for ``SCOPE_NOT_CONSENTED``.
73
+
74
+ Since Phase 5 that means "the human did not consent to this data class", not
75
+ "the manifest never declared it" — the second is ``OUT_OF_SCOPE`` and final,
76
+ because consent may only widen within the pinned manifest.
77
+ """
78
+ return is_recoverable(self.reason)
79
+
80
+
81
+ class ControlPlaneUnavailable(Exception):
82
+ """The control plane could not be reached or answered unusably. Always fatal to the
83
+ hop — there is no path here that proceeds with the un-narrowed token."""
84
+
85
+
86
+ class TransactionParamsRequired(Exception):
87
+ """The decision says this privileged call needs a transaction token, and no ``params``
88
+ were supplied to bind. Raised BEFORE any exchange, so nothing was spent."""
89
+
90
+
91
+ class ControlPlaneRejected(Exception):
92
+ """The control plane understood the request and refused it: the caller's to fix.
93
+
94
+ Distinct from :class:`ControlPlaneUnavailable`, which says nothing about the request.
95
+ Retrying this one unchanged will fail the same way.
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ *,
101
+ status: int,
102
+ code: str,
103
+ message: str,
104
+ details: dict[str, Any] | None = None,
105
+ method: str = "",
106
+ path: str = "",
107
+ ) -> None:
108
+ super().__init__(f"{status} {code}: {message}")
109
+ self.status = status
110
+ self.code = code
111
+ self.message = message
112
+ self.details = details or {}
113
+ self.method = method
114
+ self.path = path
115
+
116
+
117
+ class ManifestRejected(ControlPlaneRejected):
118
+ """A manifest was refused by reconciliation, or held for review.
119
+
120
+ ``diff`` is the reconciliation diff: one entry per tool reference that exceeds or
121
+ conflicts with what capability discovery advertises, each with its own ``remedy``.
122
+ ``needs_review`` separates the two cases — a hard rejection (edit the manifest) from
123
+ discovery having been unavailable (resubmit with ``override_reason=``, which is
124
+ recorded as a human attestation).
125
+ """
126
+
127
+ @property
128
+ def diff(self) -> list[dict[str, Any]]:
129
+ entries = self.details.get("diff")
130
+ return entries if isinstance(entries, list) else []
131
+
132
+ @property
133
+ def needs_review(self) -> bool:
134
+ return self.code == "needs_review"
135
+
136
+ def remedies(self) -> list[str]:
137
+ """One line per diff entry: the tool ref and what to do about it."""
138
+ return [f"{e.get('tool_ref', '?')}: {e.get('remedy', '')}" for e in self.diff]
139
+
140
+
141
+ __all__ = [
142
+ "ControlPlaneRejected",
143
+ "ControlPlaneUnavailable",
144
+ "ManifestRejected",
145
+ "PolicyDenied",
146
+ "TransactionParamsRequired",
147
+ ]
@@ -0,0 +1,162 @@
1
+ """An agent's identity key and the small tokens it signs.
2
+
3
+ ``AgentKey`` holds an Ed25519 private key. It signs exactly three things: the enrollment
4
+ challenge, the exchange ``actor_token``, and the resource-side ``Agent-Identity`` assertion.
5
+ It never authorizes anything — identity and authorization stay separate artifacts.
6
+
7
+ The private key never appears in ``repr``, logs, or any document this module produces.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import hashlib
14
+ import uuid
15
+ from datetime import UTC, datetime, timedelta
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import jwt
20
+ from cryptography.hazmat.primitives import serialization
21
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
22
+
23
+ ALGORITHM = "EdDSA"
24
+ ISSUER = "agentic-auth"
25
+ AGENT_PREFIX = "agent://"
26
+ TOKEN_LIFETIME_SECONDS = 60
27
+ CHALLENGE_LIFETIME_SECONDS = 120
28
+
29
+
30
+ def _b64url(raw: bytes) -> str:
31
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
32
+
33
+
34
+ def sha256_b64url(text: str) -> str:
35
+ return _b64url(hashlib.sha256(text.encode()).digest())
36
+
37
+
38
+ def thumbprint_of_jwk(jwk: dict[str, Any]) -> str:
39
+ """SHA-256 of the raw 32-byte public key, base64url. The identity of a KEY, chosen by
40
+ nobody — unlike ``kid``, which the agent picks."""
41
+ raw = base64.urlsafe_b64decode(jwk["x"] + "=" * (-len(jwk["x"]) % 4))
42
+ return _b64url(hashlib.sha256(raw).digest())
43
+
44
+
45
+ class AgentKey:
46
+ def __init__(self, private_key: Ed25519PrivateKey, *, kid: str | None = None) -> None:
47
+ self._private = private_key
48
+ self._kid = kid or self.thumbprint()[:16]
49
+
50
+ # -- construction -----------------------------------------------------------
51
+
52
+ @classmethod
53
+ def generate(cls, *, kid: str | None = None) -> AgentKey:
54
+ return cls(Ed25519PrivateKey.generate(), kid=kid)
55
+
56
+ @classmethod
57
+ def load(cls, source: str | Path, *, kid: str | None = None) -> AgentKey:
58
+ """From a PKCS8 PEM path or PEM text.
59
+
60
+ A PEM carries no ``kid``. Leave ``kid`` unset at ``generate()`` and ``load()`` and the
61
+ key names itself by a thumbprint prefix, so a key saved and reloaded keeps the ``kid``
62
+ it enrolled with. Pass the same explicit ``kid`` to both calls otherwise.
63
+ """
64
+ text = source if isinstance(source, str) and "BEGIN" in source else Path(source).read_text()
65
+ loaded = serialization.load_pem_private_key(text.encode(), password=None)
66
+ if not isinstance(loaded, Ed25519PrivateKey):
67
+ raise ValueError(f"agent key must be Ed25519, got {type(loaded).__name__}")
68
+ return cls(loaded, kid=kid)
69
+
70
+ def save(self, path: str | Path) -> None:
71
+ Path(path).write_bytes(self._private_pem())
72
+ Path(path).chmod(0o600)
73
+
74
+ def _private_pem(self) -> bytes:
75
+ return self._private.private_bytes(
76
+ serialization.Encoding.PEM,
77
+ serialization.PrivateFormat.PKCS8,
78
+ serialization.NoEncryption(),
79
+ )
80
+
81
+ # -- public material ----------------------------------------------------------
82
+
83
+ @property
84
+ def kid(self) -> str:
85
+ return self._kid
86
+
87
+ def public_raw(self) -> bytes:
88
+ return self._private.public_key().public_bytes(
89
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
90
+ )
91
+
92
+ def thumbprint(self) -> str:
93
+ return _b64url(hashlib.sha256(self.public_raw()).digest())
94
+
95
+ def jwk(self) -> dict[str, Any]:
96
+ return {
97
+ "kty": "OKP",
98
+ "crv": "Ed25519",
99
+ "x": _b64url(self.public_raw()),
100
+ "kid": self._kid,
101
+ "alg": ALGORITHM,
102
+ "use": "sig",
103
+ }
104
+
105
+ def identity_document(
106
+ self,
107
+ agent: str,
108
+ *,
109
+ claims: dict[str, Any] | None = None,
110
+ principal_assertion: str | None = None,
111
+ ) -> dict[str, Any]:
112
+ doc: dict[str, Any] = {
113
+ "sub": f"{AGENT_PREFIX}{agent}",
114
+ "jwks": {"keys": [self.jwk()]},
115
+ "claims": claims or {},
116
+ }
117
+ if principal_assertion is not None:
118
+ doc["principal_assertion"] = principal_assertion
119
+ return doc
120
+
121
+ # -- signing ------------------------------------------------------------------
122
+
123
+ def _sign(self, claims: dict[str, Any], *, lifetime: int) -> str:
124
+ now = datetime.now(UTC)
125
+ payload = {
126
+ "iat": int(now.timestamp()),
127
+ "exp": int((now + timedelta(seconds=lifetime)).timestamp()),
128
+ "jti": str(uuid.uuid4()),
129
+ **claims,
130
+ }
131
+ return jwt.encode(
132
+ payload, self._private_pem(), algorithm=ALGORITHM, headers={"kid": self._kid}
133
+ )
134
+
135
+ def sign_challenge(self, agent: str, nonce: str, *, aud: str = ISSUER) -> str:
136
+ sub = f"{AGENT_PREFIX}{agent}"
137
+ return self._sign(
138
+ {"iss": sub, "sub": sub, "aud": aud, "nonce": nonce},
139
+ lifetime=CHALLENGE_LIFETIME_SECONDS,
140
+ )
141
+
142
+ def actor_token(self, agent: str, subject_token: str, *, aud: str = ISSUER) -> str:
143
+ """RFC 8693 ``actor_token``: proof of possession bound to the exact subject token."""
144
+ sub = f"{AGENT_PREFIX}{agent}"
145
+ return self._sign(
146
+ {"iss": sub, "sub": sub, "aud": aud, "st_hash": sha256_b64url(subject_token)},
147
+ lifetime=TOKEN_LIFETIME_SECONDS,
148
+ )
149
+
150
+ def identity_assertion(self, agent: str, grant: str, audience: str) -> str:
151
+ """The ``Agent-Identity`` header: who is calling, bound to the exact grant string."""
152
+ sub = f"{AGENT_PREFIX}{agent}"
153
+ return self._sign(
154
+ {"iss": sub, "sub": sub, "aud": audience, "grant_hash": sha256_b64url(grant)},
155
+ lifetime=TOKEN_LIFETIME_SECONDS,
156
+ )
157
+
158
+ def __repr__(self) -> str:
159
+ return f"AgentKey(kid={self._kid!r})"
160
+
161
+
162
+ __all__ = ["AgentKey", "sha256_b64url", "thumbprint_of_jwk"]