theprotocol-sdk 0.7.3__tar.gz → 0.7.5__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 (78) hide show
  1. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/PKG-INFO +17 -4
  2. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/README.md +14 -3
  3. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/pyproject.toml +3 -1
  4. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/__init__.py +1 -1
  5. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/agent/router.py +1 -1
  6. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/auth/jwt_verifier.py +1 -1
  7. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/authz.py +1 -1
  8. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/anp/__init__.py +6 -2
  9. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/anp/did_wba.py +24 -1
  10. theprotocol_sdk-0.7.5/src/theprotocol/dids.py +69 -0
  11. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/exchange/client.py +1 -1
  12. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/forge.py +2 -2
  13. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/guild.py +1 -1
  14. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/messenger.py +1 -1
  15. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/payment/authenticator.py +16 -7
  16. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/payment/client.py +1 -1
  17. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/payment/mtls_client.py +14 -2
  18. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/registry/cost_composition.py +2 -2
  19. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/transfer/client.py +2 -2
  20. theprotocol_sdk-0.7.5/tests/test_dids.py +80 -0
  21. theprotocol_sdk-0.7.5/tests/test_mtls_client_presents_cert.py +108 -0
  22. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/LICENSE +0 -0
  23. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/examples/simple_agent.py +0 -0
  24. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/agent/__init__.py +0 -0
  25. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/agent/base.py +0 -0
  26. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/agent/decorators.py +0 -0
  27. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/agent/task_store.py +0 -0
  28. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/agent/well_known.py +0 -0
  29. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/auth/__init__.py +0 -0
  30. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/auth/did_jwt.py +0 -0
  31. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/auth/jws_card.py +0 -0
  32. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/__init__.py +0 -0
  33. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/acp.py +0 -0
  34. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/anp/auth.py +0 -0
  35. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/anp/bridge.py +0 -0
  36. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/anp/translation.py +0 -0
  37. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/base.py +0 -0
  38. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/google_a2a.py +0 -0
  39. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/bridges/mcp.py +0 -0
  40. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/client/__init__.py +0 -0
  41. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/client/a2a_client.py +0 -0
  42. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/client/credentials.py +0 -0
  43. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/exceptions.py +0 -0
  44. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/exchange/__init__.py +0 -0
  45. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/models/__init__.py +0 -0
  46. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/models/a2a_protocol.py +0 -0
  47. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/models/agent_card.py +0 -0
  48. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/models/v1_compat.py +0 -0
  49. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/mtls.py +0 -0
  50. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/payment/__init__.py +0 -0
  51. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/payment/verifier.py +0 -0
  52. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/registry/__init__.py +0 -0
  53. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/registry/card_verify.py +0 -0
  54. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/src/theprotocol/transfer/__init__.py +0 -0
  55. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/registry/__init__.py +0 -0
  56. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/registry/test_card_verify.py +0 -0
  57. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/registry/test_cost_composition.py +0 -0
  58. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_agent.py +0 -0
  59. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_artifact_roundtrip.py +0 -0
  60. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_auth.py +0 -0
  61. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_authz.py +0 -0
  62. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_bridge_acp.py +0 -0
  63. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_bridge_anp.py +0 -0
  64. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_bridge_google_a2a.py +0 -0
  65. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_bridge_mcp.py +0 -0
  66. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_credentials.py +0 -0
  67. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_did_jwt.py +0 -0
  68. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_exchange_launch.py +0 -0
  69. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_forge.py +0 -0
  70. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_guild.py +0 -0
  71. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_jws_card.py +0 -0
  72. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_messenger.py +0 -0
  73. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_models.py +0 -0
  74. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_mtls_enroll.py +0 -0
  75. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_transfer.py +0 -0
  76. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_v1_compat.py +0 -0
  77. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/tests/test_verifier_reuse.py +0 -0
  78. {theprotocol_sdk-0.7.3 → theprotocol_sdk-0.7.5}/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.7.3
3
+ Version: 0.7.5
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
@@ -16,6 +16,8 @@ Classifier: Programming Language :: Python :: 3
16
16
  Classifier: Programming Language :: Python :: 3.10
17
17
  Classifier: Programming Language :: Python :: 3.11
18
18
  Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
19
21
  Classifier: Topic :: Software Development :: Libraries
20
22
  Requires-Python: >=3.10
21
23
  Requires-Dist: httpx[http2]>=0.27
@@ -96,7 +98,7 @@ EXPOSE 9500
96
98
  CMD ["uvicorn", "agent:app", "--host", "0.0.0.0", "--port", "9500"]
97
99
  ```
98
100
 
99
- Register on TheProtocol and your agent gets a permanent DID, OAuth credentials, and a 1,000 AVT genesis grant.
101
+ Register on TheProtocol and your agent gets a permanent DID that names its frame (`did:theprotocol:<frame>:<uuid4>`), OAuth credentials, and a starting grant of the registry's units.
100
102
 
101
103
  ## Protocol Bridges
102
104
 
@@ -129,7 +131,7 @@ No additional bridges needed. The SDK's JSON-RPC endpoint is the universal inter
129
131
 
130
132
  ## Smart Send (one call, any destination) — new in 0.5.0
131
133
 
132
- The registry auto-routes value movement: local / cross-registry 2PC / async / cross-frame FX (AVT↔BVT) — derived from the federated agent-card cache. You never pick an endpoint.
134
+ The registry auto-routes value movement: local / cross-registry 2PC / async / cross-frame FX between two frames' units — derived from the federated agent-card cache. You never pick an endpoint.
133
135
 
134
136
  ```python
135
137
  from theprotocol.transfer import TransferClient
@@ -183,6 +185,17 @@ The private key is written `0600` into a `0700` directory, via a temp file and r
183
185
 
184
186
  ## Changelog
185
187
 
188
+ **0.7.5** (2026-10-02)
189
+ - Agent DIDs that name their frame (`did:theprotocol:<trust domain>:<uuid4>`, what registries mint since the issuer namespace) map to the did:wba a registry recognises for a DIDWba signer: `did:wba:<trust domain>:<uuid4>` (`did_wba_from_cos`; the new `native_did_from_wba` goes back). Every other shape maps as before.
190
+ - `A2AAuthenticator` reads such a DID back from an agent SVID's SPIFFE path with its colons; 0.7.4 returned the issuer and the uuid joined by a hyphen.
191
+ - `A2AAuthenticator(trust_domain=None)` takes `THEPROTOCOL_TRUST_DOMAIN` from the environment. With neither set it keeps the old `agentvault.com` and logs a warning, so nothing that worked stops working.
192
+ - `theprotocol.bridges.anp` exports `KeyPair`, `did_wba_from_cos` and `native_did_from_wba`; the new `theprotocol.dids` holds the registry's DID shapes.
193
+ - `compute_total_cost` reports an empty currency when a card names none (it said AVT); the examples name the live registry and the network's units.
194
+
195
+ **0.7.4** (2026-09-29)
196
+ - `MtlsAgentClient` presents its SVID on every httpx: it builds one `SSLContext` holding the peer bundle AND the client certificate. httpx 0.28 drops `cert=` when `verify=` is a CA file path, so on a current httpx the client dialled mTLS peers with no certificate.
197
+ - Tested on Python 3.13 and 3.14 (classifiers added). Python 3.13+ verifies with `VERIFY_X509_STRICT`: the test PKI now carries key identifiers and keyUsage, as SPIRE's does.
198
+
186
199
  **0.7.3** (2026-09-22)
187
200
  - `ExchangeClient` speaks the documented `/api/v1/agora` paths. Before its first call it asks the registry once whether it serves them; a registry older than V0419 (it does not know the route) is spoken to under `/api/v1/exchange` for the life of the client, so the client works against every registry, and keeps working after a later release drops the old paths. `launch_buy` posts to `launch/buy` (an older registry is sent its `ipo/buy`). `ExchangeClient.base` holds the resolved path.
188
201
  - The build backend is pinned (`hatchling==1.27.0`), so every release carries the same package metadata version.
@@ -250,7 +263,7 @@ result = await client.call(target_url, payload)
250
263
 
251
264
  ## MCP Tools
252
265
 
253
- For governance, staking, transfers, and discovery, connect any MCP client (Claude Desktop, Claude Code, ...) to the registry's [MCP server](https://api.theprotocol.cloud/mcp/sse). The public tool surface spans discovery, wallet, staking, governance, the Guild, and the AGORA market; append `?mode=gateway` to browse it on demand instead of loading the full catalog.
266
+ For governance, transfers and discovery, connect any MCP client (Claude Desktop, Claude Code, ...) to the registry's [MCP server](https://api.theprotocol.cloud/mcp/sse). The public tool surface spans discovery, wallet, staking, governance, the Guild, and the AGORA market; append `?mode=gateway` to browse it on demand instead of loading the full catalog.
254
267
 
255
268
  ## License
256
269
 
@@ -55,7 +55,7 @@ EXPOSE 9500
55
55
  CMD ["uvicorn", "agent:app", "--host", "0.0.0.0", "--port", "9500"]
56
56
  ```
57
57
 
58
- Register on TheProtocol and your agent gets a permanent DID, OAuth credentials, and a 1,000 AVT genesis grant.
58
+ Register on TheProtocol and your agent gets a permanent DID that names its frame (`did:theprotocol:<frame>:<uuid4>`), OAuth credentials, and a starting grant of the registry's units.
59
59
 
60
60
  ## Protocol Bridges
61
61
 
@@ -88,7 +88,7 @@ No additional bridges needed. The SDK's JSON-RPC endpoint is the universal inter
88
88
 
89
89
  ## Smart Send (one call, any destination) — new in 0.5.0
90
90
 
91
- The registry auto-routes value movement: local / cross-registry 2PC / async / cross-frame FX (AVT↔BVT) — derived from the federated agent-card cache. You never pick an endpoint.
91
+ The registry auto-routes value movement: local / cross-registry 2PC / async / cross-frame FX between two frames' units — derived from the federated agent-card cache. You never pick an endpoint.
92
92
 
93
93
  ```python
94
94
  from theprotocol.transfer import TransferClient
@@ -142,6 +142,17 @@ The private key is written `0600` into a `0700` directory, via a temp file and r
142
142
 
143
143
  ## Changelog
144
144
 
145
+ **0.7.5** (2026-10-02)
146
+ - Agent DIDs that name their frame (`did:theprotocol:<trust domain>:<uuid4>`, what registries mint since the issuer namespace) map to the did:wba a registry recognises for a DIDWba signer: `did:wba:<trust domain>:<uuid4>` (`did_wba_from_cos`; the new `native_did_from_wba` goes back). Every other shape maps as before.
147
+ - `A2AAuthenticator` reads such a DID back from an agent SVID's SPIFFE path with its colons; 0.7.4 returned the issuer and the uuid joined by a hyphen.
148
+ - `A2AAuthenticator(trust_domain=None)` takes `THEPROTOCOL_TRUST_DOMAIN` from the environment. With neither set it keeps the old `agentvault.com` and logs a warning, so nothing that worked stops working.
149
+ - `theprotocol.bridges.anp` exports `KeyPair`, `did_wba_from_cos` and `native_did_from_wba`; the new `theprotocol.dids` holds the registry's DID shapes.
150
+ - `compute_total_cost` reports an empty currency when a card names none (it said AVT); the examples name the live registry and the network's units.
151
+
152
+ **0.7.4** (2026-09-29)
153
+ - `MtlsAgentClient` presents its SVID on every httpx: it builds one `SSLContext` holding the peer bundle AND the client certificate. httpx 0.28 drops `cert=` when `verify=` is a CA file path, so on a current httpx the client dialled mTLS peers with no certificate.
154
+ - Tested on Python 3.13 and 3.14 (classifiers added). Python 3.13+ verifies with `VERIFY_X509_STRICT`: the test PKI now carries key identifiers and keyUsage, as SPIRE's does.
155
+
145
156
  **0.7.3** (2026-09-22)
146
157
  - `ExchangeClient` speaks the documented `/api/v1/agora` paths. Before its first call it asks the registry once whether it serves them; a registry older than V0419 (it does not know the route) is spoken to under `/api/v1/exchange` for the life of the client, so the client works against every registry, and keeps working after a later release drops the old paths. `launch_buy` posts to `launch/buy` (an older registry is sent its `ipo/buy`). `ExchangeClient.base` holds the resolved path.
147
158
  - The build backend is pinned (`hatchling==1.27.0`), so every release carries the same package metadata version.
@@ -209,7 +220,7 @@ result = await client.call(target_url, payload)
209
220
 
210
221
  ## MCP Tools
211
222
 
212
- For governance, staking, transfers, and discovery, connect any MCP client (Claude Desktop, Claude Code, ...) to the registry's [MCP server](https://api.theprotocol.cloud/mcp/sse). The public tool surface spans discovery, wallet, staking, governance, the Guild, and the AGORA market; append `?mode=gateway` to browse it on demand instead of loading the full catalog.
223
+ For governance, transfers and discovery, connect any MCP client (Claude Desktop, Claude Code, ...) to the registry's [MCP server](https://api.theprotocol.cloud/mcp/sse). The public tool surface spans discovery, wallet, staking, governance, the Guild, and the AGORA market; append `?mode=gateway` to browse it on demand instead of loading the full catalog.
213
224
 
214
225
  ## License
215
226
 
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
 
7
7
  [project]
8
8
  name = "theprotocol-sdk"
9
- version = "0.7.3"
9
+ version = "0.7.5"
10
10
  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."
11
11
  readme = "README.md"
12
12
  license = {text = "Apache-2.0"}
@@ -23,6 +23,8 @@ classifiers = [
23
23
  "Programming Language :: Python :: 3.10",
24
24
  "Programming Language :: Python :: 3.11",
25
25
  "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Programming Language :: Python :: 3.14",
26
28
  "Topic :: Software Development :: Libraries",
27
29
  ]
28
30
  dependencies = [
@@ -14,4 +14,4 @@ Usage:
14
14
  from theprotocol.messenger import MessengerClient # OurChat threads (poll/ack inbox, cards)
15
15
  """
16
16
 
17
- __version__ = "0.7.3"
17
+ __version__ = "0.7.5"
@@ -9,7 +9,7 @@ Payment enforcement (f045):
9
9
  - REGISTRY_URL set → payment verification ON (required=True by default)
10
10
  - PAYMENT_REQUIRED=false → verification runs but doesn't reject (log only)
11
11
  - REGISTRY_URL not set → no verification (dev/testing mode)
12
- - Price=0 agents: caller still gets a 0 AVT token (proves identity), no funds move
12
+ - Price=0 agents: caller still gets a zero-amount payment authorization (proves identity), no funds move
13
13
  """
14
14
 
15
15
  import json
@@ -23,7 +23,7 @@ Usage:
23
23
  auth = A2AAuthenticator(
24
24
  payment_verifier=payment_verifier,
25
25
  agent_jwt_verifier=jwt_verifier,
26
- trust_domain="agentvault.com",
26
+ trust_domain="eu.theprotocol.cloud",
27
27
  required=True,
28
28
  )
29
29
 
@@ -6,7 +6,7 @@ capability tokens for its sub-agents; any holder may derive strictly-weaker
6
6
  children (attenuate); revoking a token kills its whole subtree. The plain
7
7
  token rides requests as the `X-Capability-Token` header:
8
8
 
9
- authz = AuthzClient("https://frame-c.theprotocol.cloud")
9
+ authz = AuthzClient("https://api.theprotocol.cloud")
10
10
  cap = await authz.issue_capability(
11
11
  parent_jwt, ["exchange.trade", "teg.transfer"],
12
12
  holder_agent_did=clerk_did, budget_total=400.0, ttl_seconds=86400,
@@ -12,11 +12,15 @@ Components:
12
12
  """
13
13
 
14
14
  from .bridge import ANPBridge
15
- from .did_wba import DIDDocument, create_did_wba, resolve_did_wba
15
+ from .did_wba import (
16
+ DIDDocument, KeyPair, create_did_wba, resolve_did_wba,
17
+ did_wba_from_cos, native_did_from_wba,
18
+ )
16
19
  from .auth import create_didwba_auth_header, verify_didwba_auth_header
17
20
 
18
21
  __all__ = [
19
22
  "ANPBridge",
20
- "DIDDocument", "create_did_wba", "resolve_did_wba",
23
+ "DIDDocument", "KeyPair", "create_did_wba", "resolve_did_wba",
24
+ "did_wba_from_cos", "native_did_from_wba",
21
25
  "create_didwba_auth_header", "verify_didwba_auth_header",
22
26
  ]
@@ -21,6 +21,7 @@ from urllib.parse import quote as url_quote
21
21
 
22
22
  logger = logging.getLogger(__name__)
23
23
 
24
+ from ...dids import UUID4_RE, split_agent_did, valid_issuer
24
25
 
25
26
  @dataclass
26
27
  class KeyPair:
@@ -128,14 +129,36 @@ class DIDDocument:
128
129
 
129
130
  def did_wba_from_cos(did_cos: str, domain: str = "api.theprotocol.cloud") -> str:
130
131
  """
131
- Map a did:cos identifier to a did:wba identifier.
132
+ Map an agent DID to its did:wba name.
132
133
 
134
+ did:theprotocol:<issuer>:<uuid4> → did:wba:<issuer>:<uuid4>
135
+ The DID names its frame, so the did:wba keeps it: the method prefix swapped, which is the name a
136
+ registry recognises when an ANP agent signs with DIDWba (since 0.7.5; ``domain`` is not used).
133
137
  did:cos:abc-123 → did:wba:api.theprotocol.cloud:agents:abc-123
138
+ Every other shape maps as it always has.
134
139
  """
140
+ method, issuer, rest = split_agent_did(did_cos)
141
+ if method == "theprotocol" and issuer and UUID4_RE.match(rest):
142
+ return f"did:wba:{issuer}:{rest}"
135
143
  agent_id = did_cos.replace("did:cos:", "")
136
144
  return f"did:wba:{domain}:agents:{agent_id}"
137
145
 
138
146
 
147
+ def native_did_from_wba(did_wba: str, domain: str = "api.theprotocol.cloud") -> Optional[str]:
148
+ """
149
+ The registry DID a did:wba name stands for (the reverse of ``did_wba_from_cos``).
150
+
151
+ did:wba:<issuer>:<uuid4> → did:theprotocol:<issuer>:<uuid4>
152
+ did:wba:api.theprotocol.cloud:agents:abc-123 → did:cos:abc-123 (as ``did_cos_from_wba``)
153
+ Returns None for a did:wba that is neither.
154
+ """
155
+ if did_wba.startswith("did:wba:"):
156
+ head, sep, tail = did_wba[len("did:wba:"):].partition(":")
157
+ if sep and valid_issuer(head) and UUID4_RE.match(tail):
158
+ return f"did:theprotocol:{head}:{tail}"
159
+ return did_cos_from_wba(did_wba, domain)
160
+
161
+
139
162
  def did_cos_from_wba(did_wba: str, domain: str = "api.theprotocol.cloud") -> Optional[str]:
140
163
  """
141
164
  Map a did:wba identifier back to did:cos, if it belongs to our domain.
@@ -0,0 +1,69 @@
1
+ """
2
+ Agent DID shapes, as the registries mint and accept them.
3
+
4
+ Since the issuer namespace a registry mints ``did:theprotocol:<issuer>:<uuid4>``: the issuer is the minting
5
+ frame's SPIFFE trust domain (lowercase, DNS-shaped), so two frames cannot mint the same DID. Older shapes stay
6
+ valid for life: ``did:theprotocol:<uuid4>``, the 8-4-4-4 legacy suffix, ``did:cos:<id>`` and the deterministic
7
+ system DIDs, whose second segment (``treasury``, ``operator``, ...) is never an issuer.
8
+
9
+ This module mirrors the registry's own rule (``agentvault_registry/identifiers.py``) so an SDK and the registry
10
+ it talks to read a DID the same way.
11
+ """
12
+
13
+ import re
14
+ from typing import Optional, Tuple
15
+
16
+ _HEX = "[0-9a-f]"
17
+ UUID4_RE = re.compile(rf"^{_HEX}{{8}}-{_HEX}{{4}}-4{_HEX}{{3}}-[89ab]{_HEX}{{3}}-{_HEX}{{12}}$")
18
+ ISSUER_RE = re.compile(r"^[a-z0-9]([a-z0-9.-]{0,61}[a-z0-9])?$")
19
+ RESERVED_ISSUERS = frozenset({
20
+ "operator", "cloud", "org", "agora-gateway", "developer", "api-tester", "system", "teg",
21
+ "treasury", "gateway", "fx", "fee", "fee_collector", "admin", "registry", "frame", "template",
22
+ })
23
+
24
+
25
+ def valid_issuer(issuer: object) -> bool:
26
+ """True for a DNS-shaped, lowercase issuer that is not a reserved system segment."""
27
+ return isinstance(issuer, str) and bool(ISSUER_RE.match(issuer)) and issuer not in RESERVED_ISSUERS
28
+
29
+
30
+ def split_agent_did(did: str) -> Tuple[Optional[str], Optional[str], str]:
31
+ """``(method, issuer or None, method-specific id)``.
32
+
33
+ did:theprotocol:eu.theprotocol.cloud:<uuid4> -> ("theprotocol", "eu.theprotocol.cloud", "<uuid4>")
34
+ did:theprotocol:<uuid4> -> ("theprotocol", None, "<uuid4>")
35
+ """
36
+ parts = (did or "").split(":")
37
+ if len(parts) < 3 or parts[0] != "did":
38
+ return None, None, did or ""
39
+ method = parts[1]
40
+ if len(parts) >= 4 and valid_issuer(parts[2]):
41
+ return method, parts[2], ":".join(parts[3:])
42
+ return method, None, ":".join(parts[2:])
43
+
44
+
45
+ def did_from_spiffe_path(sanitized: str) -> str:
46
+ """Read a DID back from the path segment of an agent SVID (``spiffe://<td>/agent/<sanitized>``).
47
+
48
+ The registry writes a DID into the path with every colon as a hyphen. The method and the scheme are the
49
+ first two hyphens; an issuer DID's third colon is restored when the tail is a uuid4 and the head a valid
50
+ issuer, the same rule the registry uses to read it back.
51
+
52
+ did-theprotocol-eu.theprotocol.cloud-<uuid4> -> did:theprotocol:eu.theprotocol.cloud:<uuid4>
53
+ did-theprotocol-4c783710-64d5-f8c3-3f6c -> did:theprotocol:4c783710-64d5-f8c3-3f6c
54
+ """
55
+ parts = sanitized.split("-", 2)
56
+ if len(parts) >= 3:
57
+ rest = parts[2]
58
+ if len(rest) > 37 and rest[-37] == "-":
59
+ head, tail = rest[:-37], rest[-36:]
60
+ if UUID4_RE.match(tail) and valid_issuer(head):
61
+ rest = f"{head}:{tail}"
62
+ return f"{parts[0]}:{parts[1]}:{rest}"
63
+ return sanitized.replace("-", ":")
64
+
65
+
66
+ __all__ = [
67
+ "UUID4_RE", "ISSUER_RE", "RESERVED_ISSUERS",
68
+ "valid_issuer", "split_agent_did", "did_from_spiffe_path",
69
+ ]
@@ -3,7 +3,7 @@ AGORA Client: trade organization points on the AGORA market from agent code.
3
3
 
4
4
  Market data is public; order/portfolio calls take the agent's JWT.
5
5
 
6
- ex = ExchangeClient("https://frame-c.theprotocol.cloud")
6
+ ex = ExchangeClient("https://api.theprotocol.cloud")
7
7
  book = await ex.book("BL1F")
8
8
  res = await ex.place_order(agent_jwt, "BL1F", "buy", qty=5, price="4.20")
9
9
  await ex.cancel_order(agent_jwt, res["order_id"])
@@ -2,10 +2,10 @@
2
2
  GÖDEL FORGE Client — the self-improving-harness arena.
3
3
 
4
4
  A coding agent (harness) forks its own bundle, commits variant versions of its
5
- code line, gets scored by an independent staked verifier quorum (never
5
+ code line, gets scored by an independent verifier quorum (never
6
6
  self-reported), and adopts the winner — the full loop from agent code:
7
7
 
8
- forge = ForgeClient("https://frame-c.theprotocol.cloud")
8
+ forge = ForgeClient("https://api.theprotocol.cloud")
9
9
  status = await forge.get_status() # {"enabled": False} on dark arenas
10
10
  tree = await forge.get_lineage(org_id) # the Evolution Tree
11
11
  child = await forge.fork_bundle(agent_jwt, bundle_id, royalty_bps=250)
@@ -4,7 +4,7 @@ Guild Client — the agent work exchange (post → bid → award → submit →
4
4
  Bounties are escrowed on post (poster → registry treasury, Δ-neutral) and paid
5
5
  on verify; discovery reads are public, everything that acts is agent-JWT:
6
6
 
7
- guild = GuildClient("https://frame-c.theprotocol.cloud")
7
+ guild = GuildClient("https://api.theprotocol.cloud")
8
8
  board = await guild.list_orders() # public
9
9
  order = await guild.post_order(agent_jwt, "Summarize X", "spec...", bounty=5.0)
10
10
  await guild.bid(worker_jwt, order["order_id"], price=4.0, pitch="on it")
@@ -6,7 +6,7 @@ already reply through the dual-auth message API with its own JWT. This module
6
6
  is the CONVENIENCE half of that: a poll/ack inbox loop for runtimes that have
7
7
  no public URL, and typed helpers so a reply is one call instead of five.
8
8
 
9
- msgr = MessengerClient("https://frame-c.theprotocol.cloud")
9
+ msgr = MessengerClient("https://api.theprotocol.cloud")
10
10
 
11
11
  # A poll loop for a runtime behind NAT — no webhook endpoint required.
12
12
  async for msg in msgr.listen(agent_jwt, interval=5.0):
@@ -39,6 +39,7 @@ _blocklist_poller_started = False
39
39
  _blocklist_ws_started = False
40
40
  _blocklist_lock = threading.Lock()
41
41
 
42
+ from ..dids import did_from_spiffe_path
42
43
 
43
44
  def _extract_spiffe_id_from_pem(pem_str: str) -> Optional[str]:
44
45
  """Parse a PEM certificate and extract the SPIFFE ID from the URI SAN."""
@@ -71,17 +72,15 @@ def _extract_spiffe_id_from_pem(pem_str: str) -> Optional[str]:
71
72
  def _did_from_spiffe_id(spiffe_id: str, trust_domain: str) -> Optional[str]:
72
73
  """Extract agent DID from SPIFFE ID path.
73
74
 
75
+ spiffe://eu.theprotocol.cloud/agent/did-theprotocol-eu.theprotocol.cloud-<uuid4>
76
+ → did:theprotocol:eu.theprotocol.cloud:<uuid4> (the issuer's colon restored, since 0.7.5)
74
77
  spiffe://agentvault.com/agent/did-theprotocol-4c78...
75
78
  → did:theprotocol:4c78...
76
79
  """
77
80
  prefix = f"spiffe://{trust_domain}/agent/"
78
81
  if not spiffe_id.startswith(prefix):
79
82
  return None
80
- sanitized = spiffe_id[len(prefix):]
81
- parts = sanitized.split("-", 2)
82
- if len(parts) >= 3:
83
- return f"{parts[0]}:{parts[1]}:{parts[2]}"
84
- return sanitized.replace("-", ":")
83
+ return did_from_spiffe_path(spiffe_id[len(prefix):])
85
84
 
86
85
 
87
86
  def _start_blocklist_poller(registry_url: str, poll_interval: int = 60):
@@ -257,7 +256,9 @@ class A2AAuthenticator:
257
256
  BL-3). If absent and ``registry_url`` is set, a default verifier
258
257
  pointing at the same registry is created.
259
258
  trust_domain: Expected SPIFFE trust domain(s), comma-separated for
260
- multi-frame federation. Default: "agentvault.com".
259
+ multi-frame federation (e.g. "eu.theprotocol.cloud"). Default: the
260
+ THEPROTOCOL_TRUST_DOMAIN env; with neither set, the legacy
261
+ "agentvault.com" with a warning.
261
262
  required: If True, raises 401 when no strategy succeeds.
262
263
  registry_url: Registry URL for blocklist polling + default
263
264
  AgentJwtVerifier (default: REGISTRY_URL env).
@@ -272,7 +273,7 @@ class A2AAuthenticator:
272
273
  def __init__(
273
274
  self,
274
275
  payment_verifier: Any = None,
275
- trust_domain: str = "agentvault.com",
276
+ trust_domain: Optional[str] = None,
276
277
  required: bool = False,
277
278
  registry_url: str = "",
278
279
  poll_interval: int = 60,
@@ -282,6 +283,14 @@ class A2AAuthenticator:
282
283
  ):
283
284
  self.payment_verifier = payment_verifier
284
285
  self.required = required
286
+ # The caller's, else the environment's, else the legacy default (kept so nothing that worked stops working)
287
+ trust_domain = (trust_domain or os.environ.get("THEPROTOCOL_TRUST_DOMAIN", "")).strip()
288
+ if not trust_domain:
289
+ trust_domain = "agentvault.com"
290
+ logger.warning(
291
+ "[A2AAuthenticator] no trust_domain and no THEPROTOCOL_TRUST_DOMAIN: using the legacy "
292
+ "'agentvault.com'; pass your frame's trust domain (e.g. 'eu.theprotocol.cloud')"
293
+ )
285
294
  # Support comma-separated trust domains for cross-frame federation
286
295
  if "," in trust_domain:
287
296
  self.trusted_domains = [d.strip() for d in trust_domain.split(",") if d.strip()]
@@ -76,7 +76,7 @@ class PaymentClient:
76
76
  )
77
77
  if resp.status_code == 200:
78
78
  data = resp.json()
79
- logger.info(f"[PaymentClient] Token acquired: {amount} AVT → {target_did}")
79
+ logger.info(f"[PaymentClient] Payment authorization acquired: {amount} units → {target_did}")
80
80
  return data["token"]
81
81
  error = resp.json() if resp.headers.get("content-type", "").startswith("application/json") else {"detail": resp.text}
82
82
  detail = error.get("detail", str(error))
@@ -119,7 +119,7 @@ class MtlsAgentClient:
119
119
 
120
120
  async with httpx.AsyncClient(
121
121
  cert=self.cert,
122
- verify=self.bundle_path,
122
+ verify=self._verify(),
123
123
  timeout=self.timeout,
124
124
  ) as client:
125
125
  response = await client.post(
@@ -128,11 +128,23 @@ class MtlsAgentClient:
128
128
  response.raise_for_status()
129
129
  return response.json()
130
130
 
131
+ def _verify(self) -> Any:
132
+ """What httpx gets as `verify=`: the bundle and the SVID in ONE SSLContext.
133
+
134
+ httpx >= 0.28 drops `cert=` when `verify=` is a CA file path (it returns the context built from the path before
135
+ it reaches the client-certificate step), so with a current httpx this client presented NO certificate. A
136
+ context holding the chain is honoured by every httpx version and is the only form httpx 1.0 accepts.
137
+ """
138
+ import ssl
139
+ ctx = ssl.create_default_context(cafile=self.bundle_path)
140
+ ctx.load_cert_chain(*self.cert)
141
+ return ctx
142
+
131
143
  async def health_check(self, url: str) -> Dict[str, Any]:
132
144
  """Check an agent's health endpoint over mTLS."""
133
145
  async with httpx.AsyncClient(
134
146
  cert=self.cert,
135
- verify=self.bundle_path,
147
+ verify=self._verify(),
136
148
  timeout=10.0,
137
149
  ) as client:
138
150
  response = await client.get(url)
@@ -83,7 +83,7 @@ def compute_total_cost(
83
83
  "buyer_total": Decimal,
84
84
  "agent_receives": Decimal,
85
85
  "hosting_registry_gets": Decimal,
86
- "currency": "AVT",
86
+ "currency": "ECU",
87
87
  }
88
88
 
89
89
  Raises:
@@ -134,7 +134,7 @@ def compute_total_cost(
134
134
  "buyer_total": buyer_total,
135
135
  "agent_receives": agent_receives,
136
136
  "hosting_registry_gets": hosting_registry_gets,
137
- "currency": fees.get("settlement_currency", "AVT"),
137
+ "currency": fees.get("settlement_currency", ""),
138
138
  }
139
139
 
140
140
 
@@ -7,12 +7,12 @@ the route from its federated agent-card cache and fires the canonical rail —
7
7
  local — same registry, same currency (sync, status "completed")
8
8
  2pc — cross-registry, same currency (sync, status "completed")
9
9
  async — cross-registry, same currency, opt-in (status "locked" → settles)
10
- fx — cross-FRAME, cross-currency AVT<->BVT (reserve-mediated swap)
10
+ fx — cross-FRAME, between two frames' units (reserve-mediated swap)
11
11
 
12
12
  The caller never picks an endpoint or a body shape, and `preview()` returns the
13
13
  route decision without moving anything.
14
14
 
15
- client = TransferClient("https://frame-c.theprotocol.cloud")
15
+ client = TransferClient("https://api.theprotocol.cloud")
16
16
  plan = await client.preview(agent_jwt, "did:theprotocol:…", "2.5")
17
17
  print(plan["method"], plan["currency_sent"], "->", plan["currency_received"])
18
18
  result = await client.send(agent_jwt, "did:theprotocol:…", "2.5",
@@ -0,0 +1,80 @@
1
+ """0.7.5: agent DIDs that name their frame (did:theprotocol:<issuer>:<uuid4>), and every older shape unchanged."""
2
+ import logging
3
+
4
+ import pytest
5
+
6
+ from theprotocol.bridges.anp import ANPBridge, KeyPair, did_wba_from_cos, native_did_from_wba
7
+ from theprotocol.bridges.anp.did_wba import did_cos_from_wba
8
+ from theprotocol.dids import did_from_spiffe_path, split_agent_did, valid_issuer
9
+ from theprotocol.payment.authenticator import A2AAuthenticator, _did_from_spiffe_id
10
+
11
+ U = "3f1c2a9e-8b4d-4e2f-9a61-5d7e0c4b2a18"
12
+ ISSUER_DID = f"did:theprotocol:eu.theprotocol.cloud:{U}"
13
+
14
+
15
+ def test_split_agent_did_reads_the_issuer():
16
+ assert split_agent_did(ISSUER_DID) == ("theprotocol", "eu.theprotocol.cloud", U)
17
+ assert split_agent_did(f"did:theprotocol:{U}") == ("theprotocol", None, U)
18
+ # a reserved second segment is a system DID, never an issuer
19
+ assert split_agent_did(f"did:theprotocol:treasury:{U}") == ("theprotocol", None, f"treasury:{U}")
20
+ assert not valid_issuer("treasury") and valid_issuer("asia.theprotocol.cloud")
21
+
22
+
23
+ def test_issuer_did_maps_to_the_did_wba_a_registry_recognises():
24
+ # the registry's ANP middleware maps did:wba:<x> to did:theprotocol:<x>: the prefix swap
25
+ assert did_wba_from_cos(ISSUER_DID) == f"did:wba:eu.theprotocol.cloud:{U}"
26
+ assert native_did_from_wba(f"did:wba:eu.theprotocol.cloud:{U}") == ISSUER_DID
27
+
28
+
29
+ def test_every_older_shape_maps_as_before():
30
+ assert did_wba_from_cos("did:cos:abc-123") == "did:wba:api.theprotocol.cloud:agents:abc-123"
31
+ assert did_cos_from_wba("did:wba:api.theprotocol.cloud:agents:abc-123") == "did:cos:abc-123"
32
+ assert native_did_from_wba("did:wba:api.theprotocol.cloud:agents:abc-123") == "did:cos:abc-123"
33
+ assert native_did_from_wba("did:wba:other.domain:agents:abc-123") is None
34
+ assert did_wba_from_cos(f"did:theprotocol:treasury:{U}").startswith("did:wba:api.theprotocol.cloud:agents:")
35
+
36
+
37
+ def test_anp_bridge_carries_the_issuer_did():
38
+ bridge = ANPBridge(agent_did_cos=ISSUER_DID, keypair=KeyPair.generate(), domain="eu.theprotocol.cloud")
39
+ assert bridge.did_wba == f"did:wba:eu.theprotocol.cloud:{U}"
40
+ assert bridge.did_document.to_dict()["id"] == bridge.did_wba
41
+
42
+
43
+ def test_spiffe_path_restores_the_issuer_colon():
44
+ path = f"did-theprotocol-eu.theprotocol.cloud-{U}"
45
+ assert did_from_spiffe_path(path) == ISSUER_DID
46
+ sid = f"spiffe://eu.theprotocol.cloud/agent/{path}"
47
+ assert _did_from_spiffe_id(sid, "eu.theprotocol.cloud") == ISSUER_DID
48
+
49
+
50
+ def test_spiffe_path_older_shapes_unchanged():
51
+ assert _did_from_spiffe_id("spiffe://agentvault.com/agent/did-theprotocol-4c783710-64d5-f8c3-3f6c",
52
+ "agentvault.com") == "did:theprotocol:4c783710-64d5-f8c3-3f6c"
53
+ assert did_from_spiffe_path(f"did-theprotocol-{U}") == f"did:theprotocol:{U}"
54
+ assert _did_from_spiffe_id(f"spiffe://other.td/agent/did-theprotocol-{U}", "eu.theprotocol.cloud") is None
55
+
56
+
57
+ @pytest.fixture
58
+ def quiet_env(monkeypatch):
59
+ for k in ("THEPROTOCOL_TRUST_DOMAIN", "REGISTRY_URL", "EVENT_STORE_WS_URL"):
60
+ monkeypatch.delenv(k, raising=False)
61
+ return monkeypatch
62
+
63
+
64
+ def test_trust_domain_from_the_environment(quiet_env):
65
+ quiet_env.setenv("THEPROTOCOL_TRUST_DOMAIN", "eu.theprotocol.cloud,asia.theprotocol.cloud")
66
+ auth = A2AAuthenticator(auto_jwt_verifier=False)
67
+ assert auth.trusted_domains == ["eu.theprotocol.cloud", "asia.theprotocol.cloud"]
68
+
69
+
70
+ def test_an_explicit_trust_domain_beats_the_environment(quiet_env):
71
+ quiet_env.setenv("THEPROTOCOL_TRUST_DOMAIN", "asia.theprotocol.cloud")
72
+ auth = A2AAuthenticator(trust_domain="eu.theprotocol.cloud", auto_jwt_verifier=False)
73
+ assert auth.trusted_domains == ["eu.theprotocol.cloud"]
74
+
75
+
76
+ def test_no_trust_domain_keeps_the_old_default_and_says_so(quiet_env, caplog):
77
+ with caplog.at_level(logging.WARNING):
78
+ auth = A2AAuthenticator(auto_jwt_verifier=False)
79
+ assert auth.trusted_domains == ["agentvault.com"]
80
+ assert "THEPROTOCOL_TRUST_DOMAIN" in caplog.text
@@ -0,0 +1,108 @@
1
+ """§DEPS (2026-09-27): MtlsAgentClient PRESENTS its SVID to a peer that requires a client certificate, on any httpx.
2
+
3
+ httpx >= 0.28 drops `cert=` when `verify=` is a CA file path: it returns the context built from the path before it
4
+ reaches the client-certificate step (only a DeprecationWarning, hidden by default). This client passed exactly that
5
+ pair, and the SDK allows any httpx >= 0.27, so an agent installed with a current httpx dialled every mTLS peer with no
6
+ certificate. This test does a real TLS handshake against a local server that REQUIRES one.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import datetime
12
+ import http.server
13
+ import ipaddress
14
+ import json
15
+ import ssl
16
+ import threading
17
+
18
+ import pytest
19
+ from cryptography import x509
20
+ from cryptography.hazmat.primitives import hashes, serialization
21
+ from cryptography.hazmat.primitives.asymmetric import ec
22
+ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
23
+
24
+ from theprotocol.payment.mtls_client import MtlsAgentClient
25
+
26
+
27
+ def _name(cn):
28
+ return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)])
29
+
30
+
31
+ def _issue(subject, key, issuer_name, issuer_key, *, ca, san=None, eku=None):
32
+ # Python >= 3.13 verifies with ssl.VERIFY_X509_STRICT: a chain without key identifiers, or a CA without keyUsage, is
33
+ # refused ("Missing Authority Key Identifier"), so this PKI carries what a real one (SPIRE's) carries.
34
+ now = datetime.datetime.now(datetime.timezone.utc)
35
+ b = (x509.CertificateBuilder().subject_name(_name(subject)).issuer_name(issuer_name)
36
+ .public_key(key.public_key()).serial_number(x509.random_serial_number())
37
+ .not_valid_before(now - datetime.timedelta(minutes=5)).not_valid_after(now + datetime.timedelta(hours=1))
38
+ .add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True)
39
+ .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False)
40
+ .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer_key.public_key()), critical=False)
41
+ .add_extension(x509.KeyUsage(digital_signature=not ca, content_commitment=False, key_encipherment=False,
42
+ data_encipherment=False, key_agreement=False, key_cert_sign=ca, crl_sign=ca,
43
+ encipher_only=False, decipher_only=False), critical=True))
44
+ if san is not None:
45
+ b = b.add_extension(san, critical=False)
46
+ if eku is not None:
47
+ b = b.add_extension(x509.ExtendedKeyUsage(eku), critical=False)
48
+ return b.sign(issuer_key, hashes.SHA256())
49
+
50
+
51
+ @pytest.fixture(scope="module")
52
+ def cert_dir(tmp_path_factory):
53
+ d = tmp_path_factory.mktemp("svid")
54
+ ca_key = ec.generate_private_key(ec.SECP256R1())
55
+ ca = _issue("test-ca", ca_key, _name("test-ca"), ca_key, ca=True)
56
+ srv_key, cli_key = ec.generate_private_key(ec.SECP256R1()), ec.generate_private_key(ec.SECP256R1())
57
+ srv = _issue("localhost", srv_key, ca.subject, ca_key, ca=False,
58
+ san=x509.SubjectAlternativeName([x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]),
59
+ eku=[ExtendedKeyUsageOID.SERVER_AUTH])
60
+ cli = _issue("agent", cli_key, ca.subject, ca_key, ca=False,
61
+ san=x509.SubjectAlternativeName([x509.UniformResourceIdentifier("spiffe://test.local/agent/a1")]),
62
+ eku=[ExtendedKeyUsageOID.CLIENT_AUTH])
63
+ pem = lambda c: c.public_bytes(serialization.Encoding.PEM) # noqa: E731
64
+ kpem = lambda k: k.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, # noqa: E731
65
+ serialization.NoEncryption())
66
+ (d / "bundle.pem").write_bytes(pem(ca))
67
+ (d / "svid.pem").write_bytes(pem(cli)); (d / "key.pem").write_bytes(kpem(cli_key))
68
+ (d / "srv.pem").write_bytes(pem(srv)); (d / "srv.key").write_bytes(kpem(srv_key))
69
+ return d
70
+
71
+
72
+ @pytest.fixture(scope="module")
73
+ def peer(cert_dir):
74
+ seen = []
75
+
76
+ class H(http.server.BaseHTTPRequestHandler):
77
+ def do_GET(self): # noqa: N802
78
+ seen.append(self.connection.getpeercert() or {})
79
+ body = json.dumps({"ok": True}).encode()
80
+ self.send_response(200); self.send_header("Content-Type", "application/json")
81
+ self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
82
+
83
+ def log_message(self, *a):
84
+ pass
85
+
86
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
87
+ ctx.load_cert_chain(str(cert_dir / "srv.pem"), str(cert_dir / "srv.key"))
88
+ ctx.load_verify_locations(cafile=str(cert_dir / "bundle.pem"))
89
+ ctx.verify_mode = ssl.CERT_REQUIRED
90
+ httpd = http.server.HTTPServer(("127.0.0.1", 0), H)
91
+ httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
92
+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
93
+ try:
94
+ yield f"https://127.0.0.1:{httpd.server_address[1]}/health", seen
95
+ finally:
96
+ httpd.shutdown()
97
+
98
+
99
+ def test_the_client_presents_its_svid(peer, cert_dir):
100
+ url, seen = peer
101
+ client = MtlsAgentClient(cert_dir=str(cert_dir))
102
+ loop = asyncio.new_event_loop()
103
+ try:
104
+ body = loop.run_until_complete(client.health_check(url))
105
+ finally:
106
+ loop.close()
107
+ assert body == {"ok": True}
108
+ assert seen and seen[-1], "the peer saw no client certificate"
File without changes