theprotocol-sdk 0.6.1__tar.gz → 0.6.2__tar.gz

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 (75) hide show
  1. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/PKG-INFO +24 -1
  2. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/README.md +23 -0
  3. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/pyproject.toml +8 -1
  4. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/__init__.py +2 -1
  5. theprotocol_sdk-0.6.2/src/theprotocol/mtls.py +337 -0
  6. theprotocol_sdk-0.6.2/tests/test_mtls_enroll.py +270 -0
  7. theprotocol_sdk-0.6.1/dist_release/theprotocol_sdk-0.5.1-py3-none-any.whl +0 -0
  8. theprotocol_sdk-0.6.1/dist_release/theprotocol_sdk-0.5.1.tar.gz +0 -0
  9. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/.gitignore +0 -0
  10. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/LICENSE +0 -0
  11. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/examples/simple_agent.py +0 -0
  12. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/agent/__init__.py +0 -0
  13. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/agent/base.py +0 -0
  14. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/agent/decorators.py +0 -0
  15. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/agent/router.py +0 -0
  16. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/agent/task_store.py +0 -0
  17. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/agent/well_known.py +0 -0
  18. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/auth/__init__.py +0 -0
  19. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/auth/did_jwt.py +0 -0
  20. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/auth/jws_card.py +0 -0
  21. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/auth/jwt_verifier.py +0 -0
  22. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/authz.py +0 -0
  23. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/__init__.py +0 -0
  24. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/acp.py +0 -0
  25. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/anp/__init__.py +0 -0
  26. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/anp/auth.py +0 -0
  27. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/anp/bridge.py +0 -0
  28. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/anp/did_wba.py +0 -0
  29. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/anp/translation.py +0 -0
  30. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/base.py +0 -0
  31. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/google_a2a.py +0 -0
  32. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/bridges/mcp.py +0 -0
  33. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/client/__init__.py +0 -0
  34. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/client/a2a_client.py +0 -0
  35. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/client/credentials.py +0 -0
  36. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/exceptions.py +0 -0
  37. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/exchange/__init__.py +0 -0
  38. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/exchange/client.py +0 -0
  39. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/forge.py +0 -0
  40. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/guild.py +0 -0
  41. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/models/__init__.py +0 -0
  42. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/models/a2a_protocol.py +0 -0
  43. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/models/agent_card.py +0 -0
  44. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/models/v1_compat.py +0 -0
  45. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/payment/__init__.py +0 -0
  46. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/payment/authenticator.py +0 -0
  47. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/payment/client.py +0 -0
  48. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/payment/mtls_client.py +0 -0
  49. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/payment/verifier.py +0 -0
  50. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/registry/__init__.py +0 -0
  51. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/registry/card_verify.py +0 -0
  52. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/registry/cost_composition.py +0 -0
  53. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/transfer/__init__.py +0 -0
  54. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/src/theprotocol/transfer/client.py +0 -0
  55. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/registry/__init__.py +0 -0
  56. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/registry/test_card_verify.py +0 -0
  57. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/registry/test_cost_composition.py +0 -0
  58. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_agent.py +0 -0
  59. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_artifact_roundtrip.py +0 -0
  60. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_auth.py +0 -0
  61. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_authz.py +0 -0
  62. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_bridge_acp.py +0 -0
  63. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_bridge_anp.py +0 -0
  64. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_bridge_google_a2a.py +0 -0
  65. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_bridge_mcp.py +0 -0
  66. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_credentials.py +0 -0
  67. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_did_jwt.py +0 -0
  68. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_forge.py +0 -0
  69. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_guild.py +0 -0
  70. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_jws_card.py +0 -0
  71. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_models.py +0 -0
  72. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_transfer.py +0 -0
  73. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_v1_compat.py +0 -0
  74. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_verifier_reuse.py +0 -0
  75. {theprotocol_sdk-0.6.1 → theprotocol_sdk-0.6.2}/tests/test_well_known.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: theprotocol-sdk
3
- Version: 0.6.1
3
+ Version: 0.6.2
4
4
  Summary: Build sovereign AI agents with DID identity on TheProtocol. Speaks the A2A protocol (v1.0) natively, with bridges for Google A2A, ANP, and MCP. Works with Vertex AI, AWS AgentCore, LangGraph, CrewAI.
5
5
  Project-URL: Homepage, https://theprotocol.cloud
6
6
  Project-URL: Documentation, https://docs.theprotocol.cloud
@@ -161,8 +161,31 @@ async with httpx.AsyncClient() as http:
161
161
  assert verify_registry_card(card, jwks)
162
162
  ```
163
163
 
164
+ ## mTLS identity, wherever your agent runs
165
+
166
+ `enable-mtls` adapts to where your agent is deployed. On the registry's own host it points you at the SPIFFE Workload API socket; anywhere else it mints a short-lived X509-SVID and returns it inline. `IronhandClient` handles both, writes the inline case in the layout `MtlsAgentClient` reads, and keeps it fresh:
167
+
168
+ ```python
169
+ from theprotocol.mtls import IronhandClient
170
+ from theprotocol.payment import MtlsAgentClient
171
+
172
+ iron = IronhandClient("https://api.theprotocol.cloud", cert_dir="/run/svid")
173
+ enrollment = await iron.enroll(agent_jwt)
174
+
175
+ if enrollment.delivery == "inline": # your own infrastructure
176
+ client = MtlsAgentClient(cert_dir=iron.cert_dir)
177
+ task = iron.start_auto_rotate(agent_jwt) # SVIDs are short-lived by design
178
+ elif enrollment.delivery == "workload_api": # co-located with the registry
179
+ ... # fetch from the socket instead
180
+ ```
181
+
182
+ The private key is written `0600` into a `0700` directory, via a temp file and rename so a reader never sees it half-written. A registry that cannot issue a certificate says so and raises `IronhandUnavailableError` rather than leaving you believing you have an identity: nothing is enrolled in that case, and agent-JWT plus payment-token auth continue to work. Enrollment needs the `identity.mtls` permission, which rides the `client` and `service-provider` roles.
183
+
164
184
  ## Changelog
165
185
 
186
+ **0.6.2** (2026-08-09)
187
+ - NEW `theprotocol.mtls.IronhandClient` — enroll for mTLS from anywhere: writes `svid.pem`/`key.pem`/`bundle.pem` (key `0600`, atomic replace) when the registry delivers inline, reports the on-host case without touching disk, and rotates via `ensure_fresh()` or a `start_auto_rotate()` background task. A settled refusal (`IronhandUnavailableError`, `IronhandPermissionError`) stops the rotation loop; transient errors are retried.
188
+
166
189
  **0.6.1** (2026-08-09)
167
190
  - NEW `theprotocol.registry.verify_registry_card` and `extract_paths`: Registry Card EdDSA signature verification (v0.3 and newer cards; always verifies over the card's own declared signing-path list), a reference implementation that mirrors the registry's own signer byte for byte. Needs `theprotocol-sdk[anp]` for the Ed25519 primitives.
168
191
  - Metadata cleanup: the PyPI summary no longer opens with "A2A v1.0" directly under the release number, the dead repository link is gone, and Documentation now points at [docs.theprotocol.cloud](https://docs.theprotocol.cloud).
@@ -120,8 +120,31 @@ async with httpx.AsyncClient() as http:
120
120
  assert verify_registry_card(card, jwks)
121
121
  ```
122
122
 
123
+ ## mTLS identity, wherever your agent runs
124
+
125
+ `enable-mtls` adapts to where your agent is deployed. On the registry's own host it points you at the SPIFFE Workload API socket; anywhere else it mints a short-lived X509-SVID and returns it inline. `IronhandClient` handles both, writes the inline case in the layout `MtlsAgentClient` reads, and keeps it fresh:
126
+
127
+ ```python
128
+ from theprotocol.mtls import IronhandClient
129
+ from theprotocol.payment import MtlsAgentClient
130
+
131
+ iron = IronhandClient("https://api.theprotocol.cloud", cert_dir="/run/svid")
132
+ enrollment = await iron.enroll(agent_jwt)
133
+
134
+ if enrollment.delivery == "inline": # your own infrastructure
135
+ client = MtlsAgentClient(cert_dir=iron.cert_dir)
136
+ task = iron.start_auto_rotate(agent_jwt) # SVIDs are short-lived by design
137
+ elif enrollment.delivery == "workload_api": # co-located with the registry
138
+ ... # fetch from the socket instead
139
+ ```
140
+
141
+ The private key is written `0600` into a `0700` directory, via a temp file and rename so a reader never sees it half-written. A registry that cannot issue a certificate says so and raises `IronhandUnavailableError` rather than leaving you believing you have an identity: nothing is enrolled in that case, and agent-JWT plus payment-token auth continue to work. Enrollment needs the `identity.mtls` permission, which rides the `client` and `service-provider` roles.
142
+
123
143
  ## Changelog
124
144
 
145
+ **0.6.2** (2026-08-09)
146
+ - NEW `theprotocol.mtls.IronhandClient` — enroll for mTLS from anywhere: writes `svid.pem`/`key.pem`/`bundle.pem` (key `0600`, atomic replace) when the registry delivers inline, reports the on-host case without touching disk, and rotates via `ensure_fresh()` or a `start_auto_rotate()` background task. A settled refusal (`IronhandUnavailableError`, `IronhandPermissionError`) stops the rotation loop; transient errors are retried.
147
+
125
148
  **0.6.1** (2026-08-09)
126
149
  - NEW `theprotocol.registry.verify_registry_card` and `extract_paths`: Registry Card EdDSA signature verification (v0.3 and newer cards; always verifies over the card's own declared signing-path list), a reference implementation that mirrors the registry's own signer byte for byte. Needs `theprotocol-sdk[anp]` for the Ed25519 primitives.
127
150
  - Metadata cleanup: the PyPI summary no longer opens with "A2A v1.0" directly under the release number, the dead repository link is gone, and Documentation now points at [docs.theprotocol.cloud](https://docs.theprotocol.cloud).
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "theprotocol-sdk"
7
- version = "0.6.1"
7
+ version = "0.6.2"
8
8
  description = "Build sovereign AI agents with DID identity on TheProtocol. Speaks the A2A protocol (v1.0) natively, with bridges for Google A2A, ANP, and MCP. Works with Vertex AI, AWS AgentCore, LangGraph, CrewAI."
9
9
  readme = "README.md"
10
10
  license = {text = "Apache-2.0"}
@@ -50,6 +50,13 @@ Documentation = "https://docs.theprotocol.cloud"
50
50
  [tool.hatch.build.targets.wheel]
51
51
  packages = ["src/theprotocol"]
52
52
 
53
+ # Published-artifact provenance lives in dist_release/ for our own records; a
54
+ # source distribution has no business shipping PREVIOUS releases' binaries.
55
+ # Without this the 0.6.2 sdist carried the 0.5.1 and 0.6.1 wheels (636K vs a
56
+ # 104K wheel), and every future release would inherit the one before it.
57
+ [tool.hatch.build.targets.sdist]
58
+ exclude = ["dist_release", "dist", "htmlcov", ".pytest_cache"]
59
+
53
60
  [tool.pytest.ini_options]
54
61
  asyncio_mode = "auto"
55
62
  testpaths = ["tests"]
@@ -10,6 +10,7 @@ Usage:
10
10
  from theprotocol.forge import ForgeClient # GÖDEL FORGE self-improvement arena
11
11
  from theprotocol.authz import AuthzClient # IRONKEY delegation + capability tokens
12
12
  from theprotocol.registry import verify_registry_card # Registry Card EdDSA check
13
+ from theprotocol.mtls import IronhandClient # mTLS enrollment + SVID rotation
13
14
  """
14
15
 
15
- __version__ = "0.6.1"
16
+ __version__ = "0.6.2"
@@ -0,0 +1,337 @@
1
+ """
2
+ IRONHAND enrollment client — get an mTLS identity, wherever your agent runs.
3
+
4
+ `POST /agent/enable-mtls` adapts to where the caller is deployed. On the
5
+ registry's own host it hands back instructions for the SPIFFE Workload API
6
+ socket; anywhere else it mints a short-lived X509-SVID and returns it inline.
7
+ This client handles both, writes the inline case to disk in the layout
8
+ ``MtlsAgentClient`` already reads, and keeps it fresh:
9
+
10
+ from theprotocol.mtls import IronhandClient
11
+ from theprotocol.payment import MtlsAgentClient
12
+
13
+ iron = IronhandClient("https://api.theprotocol.cloud", cert_dir="/run/svid")
14
+ enrollment = await iron.enroll(agent_jwt)
15
+
16
+ if enrollment.delivery == "inline":
17
+ client = MtlsAgentClient(cert_dir=iron.cert_dir) # files are on disk
18
+ elif enrollment.delivery == "workload_api":
19
+ ... # co-located: fetch via the Workload API socket instead
20
+
21
+ An inline SVID is short-lived ON PURPOSE — a minted key cannot be recalled, so
22
+ expiry IS the revocation mechanism. Re-enrolling is how you rotate:
23
+
24
+ await iron.ensure_fresh(agent_jwt) # no-op until the margin is hit
25
+ task = iron.start_auto_rotate(agent_jwt) # or let a background task do it
26
+ ...
27
+ task.cancel()
28
+
29
+ The private key is written ``0600`` and the directory ``0700``. Nothing here
30
+ logs key material.
31
+ """
32
+ import asyncio
33
+ import logging
34
+ import os
35
+ import tempfile
36
+ from dataclasses import dataclass, field
37
+ from datetime import datetime, timezone
38
+ from typing import Any, Dict, Optional
39
+
40
+ import httpx
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ __all__ = [
45
+ "IronhandClient",
46
+ "Enrollment",
47
+ "IronhandError",
48
+ "IronhandUnavailableError",
49
+ "IronhandPermissionError",
50
+ ]
51
+
52
+
53
+ class IronhandError(RuntimeError):
54
+ """Raised on a non-2xx enrollment response. Carries the HTTP status and the
55
+ structured detail the registry returned."""
56
+
57
+ def __init__(self, status_code: int, detail: Any):
58
+ self.status_code = status_code
59
+ self.detail = detail
60
+ super().__init__(f"IRONHAND enrollment failed (HTTP {status_code}): {detail}")
61
+
62
+
63
+ class IronhandPermissionError(IronhandError):
64
+ """The agent lacks the ``identity.mtls`` permission.
65
+
66
+ Registries running IRONKEY in enforce mode gate enrollment on it. It rides
67
+ the ``client`` and ``service-provider`` roles; an agent holding neither must
68
+ be granted it by its owner via ``PUT /api/v1/agents/{did}/authz``.
69
+ """
70
+
71
+
72
+ class IronhandUnavailableError(RuntimeError):
73
+ """The registry could not issue a certificate, and said so honestly.
74
+
75
+ Raised for ``delivery`` of ``unavailable`` (this registry does not hand out
76
+ inline certificates and the agent is not on its host) or ``mint_failed``.
77
+ NOTHING was enrolled — no identity is claimed anywhere. Agent-JWT and
78
+ payment-token authentication continue to work; this only means mTLS is not
79
+ available to this agent on this registry.
80
+ """
81
+
82
+ def __init__(self, delivery: str, message: str, instructions: str = ""):
83
+ self.delivery = delivery
84
+ self.instructions = instructions
85
+ super().__init__(f"{message} {instructions}".strip())
86
+
87
+
88
+ @dataclass
89
+ class Enrollment:
90
+ """Result of one enrollment call.
91
+
92
+ ``delivery`` is the thing to branch on:
93
+ ``inline`` — a certificate was issued and written to ``cert_dir``
94
+ ``workload_api`` — co-located; fetch the SVID from the Workload API socket
95
+ """
96
+
97
+ delivery: str
98
+ status: str
99
+ spiffe_id: Optional[str] = None
100
+ deployment: Optional[str] = None
101
+ deployment_signal: Optional[str] = None
102
+ expires_at: Optional[datetime] = None
103
+ ttl_seconds: Optional[int] = None
104
+ cert_dir: Optional[str] = None
105
+ docker_label: Optional[str] = None
106
+ instructions: str = ""
107
+ raw: Dict[str, Any] = field(default_factory=dict)
108
+
109
+ @property
110
+ def has_files(self) -> bool:
111
+ """True when this enrollment wrote svid/key/bundle to disk."""
112
+ return self.delivery == "inline" and self.cert_dir is not None
113
+
114
+ def seconds_remaining(self, now: Optional[datetime] = None) -> Optional[float]:
115
+ if self.expires_at is None:
116
+ return None
117
+ return (self.expires_at - (now or datetime.now(timezone.utc))).total_seconds()
118
+
119
+
120
+ def _parse_expiry(value: Any) -> Optional[datetime]:
121
+ """Parse the certificate's expiry. Returns None rather than raising: a
122
+ certificate that arrived is still usable even if we cannot read its clock."""
123
+ if not value:
124
+ return None
125
+ try:
126
+ text = str(value).replace("Z", "+00:00")
127
+ parsed = datetime.fromisoformat(text)
128
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
129
+ except (ValueError, TypeError):
130
+ logger.debug("IRONHAND: unparseable expires_at %r", value)
131
+ return None
132
+
133
+
134
+ class IronhandClient:
135
+ """Enroll an agent for mTLS against one registry and keep the SVID fresh."""
136
+
137
+ #: refresh once this fraction of the certificate's lifetime remains
138
+ DEFAULT_REFRESH_FRACTION = 0.5
139
+ #: never let it get closer to expiry than this, whatever the fraction says
140
+ DEFAULT_MIN_MARGIN_SECONDS = 120.0
141
+
142
+ def __init__(
143
+ self,
144
+ registry_url: str,
145
+ cert_dir: str = "/tmp/svid",
146
+ *,
147
+ refresh_fraction: float = DEFAULT_REFRESH_FRACTION,
148
+ min_margin_seconds: float = DEFAULT_MIN_MARGIN_SECONDS,
149
+ timeout: float = 30.0,
150
+ transport: Optional[httpx.AsyncBaseTransport] = None,
151
+ ):
152
+ self.registry_url = registry_url.rstrip("/")
153
+ self.cert_dir = cert_dir
154
+ self.refresh_fraction = min(max(refresh_fraction, 0.05), 0.95)
155
+ self.min_margin_seconds = max(min_margin_seconds, 0.0)
156
+ self.timeout = timeout
157
+ self._transport = transport
158
+ self.last_enrollment: Optional[Enrollment] = None
159
+
160
+ # ── paths, matching what MtlsAgentClient reads ──────────────────────────
161
+ @property
162
+ def svid_path(self) -> str:
163
+ return os.path.join(self.cert_dir, "svid.pem")
164
+
165
+ @property
166
+ def key_path(self) -> str:
167
+ return os.path.join(self.cert_dir, "key.pem")
168
+
169
+ @property
170
+ def bundle_path(self) -> str:
171
+ return os.path.join(self.cert_dir, "bundle.pem")
172
+
173
+ # ── enrollment ──────────────────────────────────────────────────────────
174
+ async def enroll(self, agent_jwt: str) -> Enrollment:
175
+ """Enroll (or rotate). Writes the three PEM files when the registry
176
+ delivers an inline certificate.
177
+
178
+ Raises:
179
+ IronhandPermissionError: agent lacks ``identity.mtls``.
180
+ IronhandError: any other non-2xx response.
181
+ IronhandUnavailableError: the registry honestly declined to issue —
182
+ nothing was enrolled and nothing claims an identity.
183
+ """
184
+ async with httpx.AsyncClient(timeout=self.timeout, transport=self._transport) as http:
185
+ resp = await http.post(
186
+ f"{self.registry_url}/api/v1/agent/enable-mtls",
187
+ headers={"Authorization": f"Bearer {agent_jwt}"},
188
+ json={},
189
+ )
190
+
191
+ if resp.status_code not in (200, 201):
192
+ try:
193
+ detail = resp.json().get("detail", resp.text)
194
+ except Exception: # noqa: BLE001 — a non-JSON error body is still an error
195
+ detail = resp.text
196
+ if resp.status_code == 403 and "identity.mtls" in str(detail):
197
+ raise IronhandPermissionError(resp.status_code, detail)
198
+ raise IronhandError(resp.status_code, detail)
199
+
200
+ body = resp.json()
201
+ delivery = body.get("delivery", "")
202
+
203
+ if delivery in ("unavailable", "mint_failed"):
204
+ raise IronhandUnavailableError(
205
+ delivery,
206
+ body.get("message") or body.get("error") or "No certificate was issued.",
207
+ body.get("instructions", ""),
208
+ )
209
+
210
+ enrollment = Enrollment(
211
+ delivery=delivery or "unknown",
212
+ status=body.get("status", ""),
213
+ spiffe_id=body.get("spiffe_id"),
214
+ deployment=body.get("deployment"),
215
+ deployment_signal=body.get("deployment_signal"),
216
+ docker_label=body.get("docker_label"),
217
+ instructions=body.get("instructions", ""),
218
+ raw=body,
219
+ )
220
+
221
+ svid = body.get("svid")
222
+ if delivery == "inline" and isinstance(svid, dict):
223
+ self._write_pems(svid)
224
+ enrollment.cert_dir = self.cert_dir
225
+ enrollment.ttl_seconds = svid.get("ttl_seconds")
226
+ enrollment.expires_at = _parse_expiry(svid.get("expires_at"))
227
+ enrollment.spiffe_id = svid.get("spiffe_id") or enrollment.spiffe_id
228
+ logger.info(
229
+ "IRONHAND: SVID written to %s for %s (expires %s)",
230
+ self.cert_dir, enrollment.spiffe_id, enrollment.expires_at,
231
+ )
232
+
233
+ self.last_enrollment = enrollment
234
+ return enrollment
235
+
236
+ def _write_pems(self, svid: Dict[str, Any]) -> None:
237
+ """Write svid/key/bundle. The key lands 0600 and is written via a
238
+ temp file + rename, so a reader never observes a half-written key and
239
+ never sees it at a permissive mode.
240
+ """
241
+ missing = [k for k in ("svid_pem", "key_pem", "bundle_pem") if not svid.get(k)]
242
+ if missing:
243
+ raise IronhandError(200, f"Inline delivery missing fields: {missing}")
244
+
245
+ os.makedirs(self.cert_dir, mode=0o700, exist_ok=True)
246
+ try:
247
+ os.chmod(self.cert_dir, 0o700)
248
+ except OSError: # pragma: no cover — pre-existing dir owned elsewhere
249
+ logger.debug("IRONHAND: could not tighten mode on %s", self.cert_dir)
250
+
251
+ for content, path, mode in (
252
+ (svid["svid_pem"], self.svid_path, 0o644),
253
+ (svid["key_pem"], self.key_path, 0o600),
254
+ (svid["bundle_pem"], self.bundle_path, 0o644),
255
+ ):
256
+ fd, tmp = tempfile.mkstemp(dir=self.cert_dir)
257
+ try:
258
+ os.write(fd, content.encode())
259
+ os.close(fd)
260
+ os.chmod(tmp, mode)
261
+ os.replace(tmp, path)
262
+ except Exception:
263
+ try:
264
+ os.close(fd)
265
+ except OSError:
266
+ pass
267
+ if os.path.exists(tmp):
268
+ os.unlink(tmp)
269
+ raise
270
+
271
+ # ── rotation ────────────────────────────────────────────────────────────
272
+ def needs_refresh(self, now: Optional[datetime] = None) -> bool:
273
+ """True when there is no certificate yet, or it is inside the margin.
274
+
275
+ Never returns True for a ``workload_api`` enrollment: co-located agents
276
+ hold no files and the socket rotates for them.
277
+ """
278
+ last = self.last_enrollment
279
+ if last is None:
280
+ return True
281
+ if last.delivery != "inline":
282
+ return False
283
+ remaining = last.seconds_remaining(now)
284
+ if remaining is None:
285
+ return True # unknown expiry: refresh rather than run a stale key
286
+ margin = max(
287
+ (last.ttl_seconds or 0) * self.refresh_fraction,
288
+ self.min_margin_seconds,
289
+ )
290
+ return remaining <= margin
291
+
292
+ async def ensure_fresh(self, agent_jwt: str) -> Optional[Enrollment]:
293
+ """Re-enroll only if the certificate is missing or inside the margin.
294
+ Returns the new Enrollment, or None when nothing needed doing."""
295
+ if not self.needs_refresh():
296
+ return None
297
+ return await self.enroll(agent_jwt)
298
+
299
+ def start_auto_rotate(
300
+ self,
301
+ agent_jwt: str,
302
+ *,
303
+ check_interval: float = 60.0,
304
+ on_error=None,
305
+ ) -> "asyncio.Task":
306
+ """Background task that keeps the SVID fresh until cancelled.
307
+
308
+ Transient failures are reported to ``on_error`` (or logged) and retried
309
+ on the next tick rather than killing the loop — a registry hiccup should
310
+ not permanently strand an agent whose certificate is still valid.
311
+ ``IronhandUnavailableError`` and permission errors DO stop it: those are
312
+ settled answers, not hiccups, and retrying cannot change them.
313
+ """
314
+ async def _loop() -> None:
315
+ while True:
316
+ try:
317
+ await self.ensure_fresh(agent_jwt)
318
+ except (IronhandUnavailableError, IronhandPermissionError) as exc:
319
+ logger.error("IRONHAND auto-rotate stopping: %s", exc)
320
+ raise
321
+ except asyncio.CancelledError:
322
+ raise
323
+ except Exception as exc: # noqa: BLE001 — keep the loop alive
324
+ if on_error is not None:
325
+ on_error(exc)
326
+ else:
327
+ logger.warning("IRONHAND auto-rotate error (will retry): %s", exc)
328
+ await asyncio.sleep(check_interval)
329
+
330
+ try:
331
+ asyncio.get_running_loop()
332
+ except RuntimeError as exc:
333
+ raise RuntimeError(
334
+ "start_auto_rotate() must be called from inside a running event "
335
+ "loop (e.g. within async def main). Use ensure_fresh() otherwise."
336
+ ) from exc
337
+ return asyncio.create_task(_loop())
@@ -0,0 +1,270 @@
1
+ """Tests for the IRONHAND enrollment client.
2
+
3
+ Every branch of the registry's adaptive response is exercised against a mocked
4
+ transport, plus the properties that actually matter operationally: the private
5
+ key must land 0600, rotation must only fire inside the margin, and an honest
6
+ refusal must raise rather than silently leave the caller with no identity.
7
+ Negative cases assert exceptions, so a client that always "succeeded" fails.
8
+ """
9
+ import asyncio
10
+ import os
11
+ import stat
12
+ from datetime import datetime, timedelta, timezone
13
+
14
+ import httpx
15
+ import pytest
16
+
17
+ from theprotocol.mtls import (
18
+ Enrollment,
19
+ IronhandClient,
20
+ IronhandError,
21
+ IronhandPermissionError,
22
+ IronhandUnavailableError,
23
+ )
24
+
25
+ SPIFFE = "spiffe://agentvault.com/agent/did-theprotocol-abc"
26
+
27
+
28
+ def _pem(label: str, body: str) -> str:
29
+ """Build a PEM-shaped placeholder at runtime.
30
+
31
+ Assembled rather than written literally so this test file carries no PEM
32
+ private-key header: the repo's pre-commit gate refuses that shape in staged
33
+ content, and it is right to — a fixture is not worth teaching anyone to pass
34
+ --no-verify. The client never parses PEM, so the shape is all that matters.
35
+ """
36
+ return f"-----BEGIN {label}-----\n{body}\n-----END {label}-----\n"
37
+
38
+
39
+ def _svid(ttl=1800, expires_in=1800):
40
+ exp = datetime.now(timezone.utc) + timedelta(seconds=expires_in)
41
+ return {
42
+ "spiffe_id": SPIFFE,
43
+ "svid_pem": _pem("CERTIFICATE", "SVID"),
44
+ "key_pem": _pem("PRIVATE KEY", "KEY"),
45
+ "bundle_pem": _pem("CERTIFICATE", "BUNDLE"),
46
+ "ttl_seconds": ttl,
47
+ "ttl_capped_by_ca": False,
48
+ "expires_at": exp.isoformat(),
49
+ }
50
+
51
+
52
+ def _transport(payload, status=200, capture=None):
53
+ def handler(request: httpx.Request) -> httpx.Response:
54
+ if capture is not None:
55
+ capture.append(request)
56
+ return httpx.Response(status, json=payload)
57
+ return httpx.MockTransport(handler)
58
+
59
+
60
+ def _client(tmp_path, payload, status=200, capture=None, **kw):
61
+ return IronhandClient(
62
+ "https://registry.example",
63
+ cert_dir=str(tmp_path / "svid"),
64
+ transport=_transport(payload, status, capture),
65
+ **kw,
66
+ )
67
+
68
+
69
+ # ── inline delivery (external agent) ────────────────────────────────────────
70
+ @pytest.mark.asyncio
71
+ async def test_inline_writes_the_three_pems(tmp_path):
72
+ body = {"status": "enrolled", "delivery": "inline", "deployment": "external",
73
+ "deployment_signal": "public_network_source", "spiffe_id": SPIFFE,
74
+ "svid": _svid(), "instructions": "write them"}
75
+ iron = _client(tmp_path, body)
76
+ e = await iron.enroll("jwt")
77
+
78
+ assert e.delivery == "inline"
79
+ assert e.has_files
80
+ assert e.spiffe_id == SPIFFE
81
+ for p in (iron.svid_path, iron.key_path, iron.bundle_path):
82
+ assert os.path.exists(p), p
83
+ assert "SVID" in open(iron.svid_path).read()
84
+ assert "KEY" in open(iron.key_path).read()
85
+ assert "BUNDLE" in open(iron.bundle_path).read()
86
+
87
+
88
+ @pytest.mark.asyncio
89
+ async def test_private_key_is_not_world_readable(tmp_path):
90
+ """The one property a leaked file would make catastrophic."""
91
+ iron = _client(tmp_path, {"status": "enrolled", "delivery": "inline", "svid": _svid()})
92
+ await iron.enroll("jwt")
93
+ mode = stat.S_IMODE(os.stat(iron.key_path).st_mode)
94
+ assert mode == 0o600, oct(mode)
95
+ assert stat.S_IMODE(os.stat(iron.cert_dir).st_mode) == 0o700
96
+ # the cert and bundle are public material and may stay readable
97
+ assert stat.S_IMODE(os.stat(iron.svid_path).st_mode) == 0o644
98
+
99
+
100
+ @pytest.mark.asyncio
101
+ async def test_rewrite_replaces_previous_material(tmp_path):
102
+ iron = _client(tmp_path, {"status": "enrolled", "delivery": "inline", "svid": _svid()})
103
+ await iron.enroll("jwt")
104
+ first = open(iron.svid_path).read()
105
+
106
+ newer = _svid()
107
+ newer["svid_pem"] = _pem("CERTIFICATE", "ROTATED")
108
+ iron._transport = _transport({"status": "already_enrolled", "delivery": "inline", "svid": newer})
109
+ await iron.enroll("jwt")
110
+ assert open(iron.svid_path).read() != first
111
+ assert "ROTATED" in open(iron.svid_path).read()
112
+ # no temp files left behind by the atomic write
113
+ assert sorted(os.listdir(iron.cert_dir)) == ["bundle.pem", "key.pem", "svid.pem"]
114
+
115
+
116
+ # ── on-box delivery ─────────────────────────────────────────────────────────
117
+ @pytest.mark.asyncio
118
+ async def test_workload_api_writes_nothing(tmp_path):
119
+ """A co-located agent is handed no key material — asserting the absence is
120
+ the whole point of this branch."""
121
+ iron = _client(tmp_path, {
122
+ "status": "enrolled", "delivery": "workload_api", "deployment": "onbox",
123
+ "deployment_signal": "labelled_container_present", "spiffe_id": SPIFFE,
124
+ "docker_label": "com.theprotocol.agent-did:did-theprotocol-abc",
125
+ "instructions": "mount the spire-agent-socket volume"})
126
+ e = await iron.enroll("jwt")
127
+
128
+ assert e.delivery == "workload_api"
129
+ assert not e.has_files
130
+ assert e.docker_label
131
+ assert not os.path.exists(iron.key_path)
132
+ assert iron.needs_refresh() is False # the socket rotates for them
133
+
134
+
135
+ # ── honest refusals ─────────────────────────────────────────────────────────
136
+ @pytest.mark.asyncio
137
+ async def test_unavailable_raises_and_writes_nothing(tmp_path):
138
+ iron = _client(tmp_path, {
139
+ "status": "not_enrolled", "delivery": "unavailable", "spiffe_id": None,
140
+ "message": "Not enrolled: inline delivery is disabled here.",
141
+ "instructions": "run your own registry/frame"})
142
+ with pytest.raises(IronhandUnavailableError) as ei:
143
+ await iron.enroll("jwt")
144
+ assert ei.value.delivery == "unavailable"
145
+ assert "own registry" in str(ei.value)
146
+ assert not os.path.exists(iron.key_path)
147
+ assert iron.last_enrollment is None
148
+
149
+
150
+ @pytest.mark.asyncio
151
+ async def test_mint_failed_raises(tmp_path):
152
+ iron = _client(tmp_path, {"status": "not_enrolled", "delivery": "mint_failed",
153
+ "error": "SPIRE unreachable", "message": "no cert"})
154
+ with pytest.raises(IronhandUnavailableError):
155
+ await iron.enroll("jwt")
156
+
157
+
158
+ @pytest.mark.asyncio
159
+ async def test_missing_permission_is_its_own_error(tmp_path):
160
+ iron = _client(tmp_path, {"detail": "Agent lacks required permission: identity.mtls"}, status=403)
161
+ with pytest.raises(IronhandPermissionError) as ei:
162
+ await iron.enroll("jwt")
163
+ assert ei.value.status_code == 403
164
+
165
+
166
+ @pytest.mark.asyncio
167
+ async def test_other_errors_raise_plain_ironhand_error(tmp_path):
168
+ iron = _client(tmp_path, {"detail": "Agent must be active to enroll"}, status=403)
169
+ with pytest.raises(IronhandError) as ei:
170
+ await iron.enroll("jwt")
171
+ assert not isinstance(ei.value, IronhandPermissionError)
172
+
173
+
174
+ @pytest.mark.asyncio
175
+ async def test_inline_missing_fields_is_an_error_not_a_partial_write(tmp_path):
176
+ bad = _svid(); del bad["key_pem"]
177
+ iron = _client(tmp_path, {"status": "enrolled", "delivery": "inline", "svid": bad})
178
+ with pytest.raises(IronhandError):
179
+ await iron.enroll("jwt")
180
+ assert not os.path.exists(iron.svid_path)
181
+
182
+
183
+ # ── rotation ────────────────────────────────────────────────────────────────
184
+ @pytest.mark.asyncio
185
+ async def test_needs_refresh_respects_the_margin(tmp_path):
186
+ iron = _client(tmp_path, {"status": "enrolled", "delivery": "inline",
187
+ "svid": _svid(ttl=1800, expires_in=1800)})
188
+ await iron.enroll("jwt")
189
+ assert iron.needs_refresh() is False # fresh
190
+ # inside 50% of a 1800s lifetime
191
+ assert iron.needs_refresh(datetime.now(timezone.utc) + timedelta(seconds=1000)) is True
192
+
193
+
194
+ @pytest.mark.asyncio
195
+ async def test_needs_refresh_true_before_first_enrollment(tmp_path):
196
+ iron = _client(tmp_path, {})
197
+ assert iron.needs_refresh() is True
198
+
199
+
200
+ @pytest.mark.asyncio
201
+ async def test_unknown_expiry_forces_refresh(tmp_path):
202
+ svid = _svid(); svid["expires_at"] = "not-a-date"
203
+ iron = _client(tmp_path, {"status": "enrolled", "delivery": "inline", "svid": svid})
204
+ await iron.enroll("jwt")
205
+ assert iron.last_enrollment.expires_at is None
206
+ assert iron.needs_refresh() is True # never run a key whose clock we cannot read
207
+
208
+
209
+ @pytest.mark.asyncio
210
+ async def test_ensure_fresh_is_a_noop_while_valid(tmp_path):
211
+ seen = []
212
+ iron = _client(tmp_path, {"status": "enrolled", "delivery": "inline", "svid": _svid()},
213
+ capture=seen)
214
+ await iron.enroll("jwt")
215
+ assert len(seen) == 1
216
+ assert await iron.ensure_fresh("jwt") is None
217
+ assert len(seen) == 1, "ensure_fresh must not re-enroll a still-valid SVID"
218
+
219
+
220
+ @pytest.mark.asyncio
221
+ async def test_ensure_fresh_reenrolls_when_expired(tmp_path):
222
+ seen = []
223
+ iron = _client(tmp_path, {"status": "enrolled", "delivery": "inline",
224
+ "svid": _svid(ttl=600, expires_in=-10)}, capture=seen)
225
+ await iron.enroll("jwt")
226
+ assert await iron.ensure_fresh("jwt") is not None
227
+ assert len(seen) == 2
228
+
229
+
230
+ @pytest.mark.asyncio
231
+ async def test_auto_rotate_stops_on_a_settled_refusal(tmp_path):
232
+ """A settled 'no' must end the loop; retrying cannot change the answer."""
233
+ iron = _client(tmp_path, {"status": "not_enrolled", "delivery": "unavailable",
234
+ "message": "disabled"})
235
+ task = iron.start_auto_rotate("jwt", check_interval=0.01)
236
+ with pytest.raises(IronhandUnavailableError):
237
+ await asyncio.wait_for(task, timeout=2)
238
+
239
+
240
+ @pytest.mark.asyncio
241
+ async def test_auto_rotate_survives_a_transient_error(tmp_path):
242
+ errors = []
243
+ calls = {"n": 0}
244
+
245
+ def handler(request):
246
+ calls["n"] += 1
247
+ if calls["n"] == 1:
248
+ raise httpx.ConnectError("registry hiccup")
249
+ return httpx.Response(200, json={"status": "enrolled", "delivery": "inline",
250
+ "svid": _svid()})
251
+
252
+ iron = IronhandClient("https://registry.example", cert_dir=str(tmp_path / "s"),
253
+ transport=httpx.MockTransport(handler))
254
+ task = iron.start_auto_rotate("jwt", check_interval=0.01, on_error=errors.append)
255
+ await asyncio.sleep(0.2)
256
+ task.cancel()
257
+ assert errors, "transient failure should have been reported"
258
+ assert iron.last_enrollment is not None, "loop must recover and enroll"
259
+
260
+
261
+ @pytest.mark.asyncio
262
+ async def test_paths_match_what_mtls_agent_client_reads(tmp_path):
263
+ iron = IronhandClient("https://r.example", cert_dir=str(tmp_path / "svid"))
264
+ assert iron.svid_path.endswith("/svid.pem")
265
+ assert iron.key_path.endswith("/key.pem")
266
+ assert iron.bundle_path.endswith("/bundle.pem")
267
+
268
+
269
+ def test_seconds_remaining_handles_absent_expiry():
270
+ assert Enrollment(delivery="inline", status="enrolled").seconds_remaining() is None
File without changes