cortexhub 3.2.0__tar.gz → 3.4.0__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.
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cortexhub
3
- Version: 3.2.0
3
+ Version: 3.4.0
4
4
  Summary: CortexHub platform SDK: point your agent at the governed LLM router + MCP gateway.
5
5
  Project-URL: Homepage, https://cortexhub.ai
6
6
  Project-URL: Documentation, https://docs.cortexhub.ai
7
7
  Author-email: CortexHub <hello@cortexhub.ai>
8
8
  License: MIT
9
9
  License-File: LICENSE
10
- Keywords: agents,ai,governance,mcp,programmatic
10
+ Keywords: agents,ai,audit,governance,mcp,programmatic,verification
11
11
  Classifier: Development Status :: 5 - Production/Stable
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: License :: OSI Approved :: MIT License
@@ -21,10 +21,13 @@ Requires-Python: >=3.10
21
21
  Provides-Extra: ai
22
22
  Requires-Dist: openai>=1.40; extra == 'ai'
23
23
  Provides-Extra: all
24
+ Requires-Dist: cryptography>=42; extra == 'all'
24
25
  Requires-Dist: mcp<2,>=1.0; extra == 'all'
25
26
  Requires-Dist: openai>=1.40; extra == 'all'
26
27
  Provides-Extra: mcp
27
28
  Requires-Dist: mcp<2,>=1.0; extra == 'mcp'
29
+ Provides-Extra: verify
30
+ Requires-Dist: cryptography>=42; extra == 'verify'
28
31
  Description-Content-Type: text/markdown
29
32
 
30
33
  # cortexhub
@@ -47,6 +50,7 @@ You don't rewrite your agent. You change a base URL and drop in one key.
47
50
  pip install cortexhub # zero-dependency core (URLs + headers)
48
51
  pip install 'cortexhub[ai]' # + a ready OpenAI-compatible client via cx.llm
49
52
  pip install 'cortexhub[mcp]' # + the official MCP client for cx.mcp() sessions
53
+ pip install 'cortexhub[verify]' # + `cortexhub verify`: check receipts and evidence packs offline
50
54
  ```
51
55
 
52
56
  ## The key
@@ -92,6 +96,7 @@ s.mcp.url # https://mcp.cortexhub.ai/v1/mcp
92
96
  s.mcp.headers # wire into your MCP transport (see "Tools" below)
93
97
 
94
98
  s.session_id # "conv-42" -- log or forward it to correlate
99
+ s.ai_headers # router headers for your own OpenAI-compatible client (below)
95
100
  ```
96
101
 
97
102
  Reuse the same handle across the run's turns so they group. An autonomous agent
@@ -100,49 +105,73 @@ Reuse the same handle across the run's turns so they group. An autonomous agent
100
105
 
101
106
  ## Inference without a session
102
107
 
103
- For a quick, standalone call, `cx.llm` is a ready OpenAI-compatible client and
104
- `cx.ai` gives the raw `base_url` + `api_key` any framework needs. These are NOT
105
- grouped into a session (no Sessions row) -- prefer `cx.session(...)` above when
106
- you want the run visible in CortexHub.
108
+ `cx.ai` gives the raw `base_url` + `api_key` any client needs, and `cx.llm` is a
109
+ ready OpenAI-compatible client. The router requires every call to name the end
110
+ user it acts for (`X-CortexHub-End-User-Subject`, else HTTP 400), so in practice
111
+ build the client from a session handle (`s.llm`, or `s.ai_headers` below).
107
112
 
108
113
  ```python
109
- cx.llm.chat.completions.create(model="cortexhub/auto", messages=[...])
110
- cx.llm.responses.create(model="cortexhub/auto", input="hi")
111
- cx.llm.models.list()
112
-
113
114
  cx.ai.base_url # e.g. https://api.cortexhub.ai/v1 (override with CORTEXHUB_ROUTER_URL)
114
115
  cx.ai.api_key # your cxh_key_...
116
+ cx.llm.models.list()
115
117
  ```
116
118
 
117
119
  ## Use your existing framework
118
120
 
119
121
  The router speaks the OpenAI wire protocol, so every framework integrates the
120
122
  same way: point its OpenAI-compatible provider at `cx.ai.base_url`, pass
121
- `cx.ai.api_key`, and choose a `model`.
123
+ `cx.ai.api_key`, choose a `model`, and send the session handle's **`ai_headers`**
124
+ as the client's default headers. They tell the router which run the call
125
+ belongs to and which end user it acts for (`X-CortexHub-End-User-Subject`,
126
+ `X-CortexHub-Session-Id`), so the framework's model calls land in the same
127
+ CortexHub session as the handle's tool calls.
122
128
 
123
129
  ```python
124
- base, key = cx.ai.base_url, cx.ai.api_key
130
+ s = cx.session(agent="support-bot", mcp_session_id="conv-42", end_user_subject="user_42")
131
+ base, key, headers = cx.ai.base_url, cx.ai.api_key, s.ai_headers
125
132
 
126
133
  # OpenAI SDK / plain
127
134
  from openai import OpenAI
128
- OpenAI(base_url=base, api_key=key).chat.completions.create(model="cortexhub/auto", messages=[...])
135
+ OpenAI(base_url=base, api_key=key, default_headers=headers)
129
136
 
130
137
  # LangChain / LangGraph
131
138
  from langchain_openai import ChatOpenAI
132
- ChatOpenAI(base_url=base, api_key=key, model="cortexhub/auto")
139
+ ChatOpenAI(base_url=base, api_key=key, model="cortexhub/auto", default_headers=headers)
133
140
 
134
141
  # CrewAI (LiteLLM under the hood)
135
142
  from crewai import LLM
136
- LLM(model="openai/cortexhub/auto", base_url=base, api_key=key)
143
+ LLM(model="openai/cortexhub/auto", base_url=base, api_key=key, extra_headers=headers)
137
144
 
138
145
  # AutoGen
139
146
  from autogen_ext.models.openai import OpenAIChatCompletionClient
140
- OpenAIChatCompletionClient(model="cortexhub/auto", base_url=base, api_key=key)
147
+ OpenAIChatCompletionClient(model="cortexhub/auto", base_url=base, api_key=key,
148
+ default_headers=headers)
141
149
 
142
150
  # Pydantic AI
151
+ from openai import AsyncOpenAI
143
152
  from pydantic_ai.models.openai import OpenAIModel
144
153
  from pydantic_ai.providers.openai import OpenAIProvider
145
- OpenAIModel("cortexhub/auto", provider=OpenAIProvider(base_url=base, api_key=key))
154
+ OpenAIModel("cortexhub/auto", provider=OpenAIProvider(
155
+ openai_client=AsyncOpenAI(base_url=base, api_key=key, default_headers=headers)))
156
+ ```
157
+
158
+ A LangGraph agent with CortexHub's model AND its governed tools (the MCP
159
+ connection through `langchain-mcp-adapters`), in one session:
160
+
161
+ ```python
162
+ from langchain_mcp_adapters.tools import load_mcp_tools
163
+ from langchain_openai import ChatOpenAI
164
+ from langgraph.prebuilt import create_react_agent
165
+ from mcp import ClientSession
166
+
167
+ run = cx.session(agent="lead-assistant", end_user_subject="northwind-ops",
168
+ mcp_session_id="lead-assistant-run-1")
169
+ llm = ChatOpenAI(model="cortexhub/auto", base_url=cx.ai.base_url,
170
+ api_key=cx.ai.api_key, default_headers=run.ai_headers)
171
+ async with run.mcp.open() as (read, write), ClientSession(read, write) as mcp:
172
+ await mcp.initialize()
173
+ agent = create_react_agent(llm, await load_mcp_tools(mcp))
174
+ state = await agent.ainvoke({"messages": [("user", "...")]})
146
175
  ```
147
176
 
148
177
  **Anthropic SDK:** the router is OpenAI-compatible, not Anthropic-Messages, so
@@ -153,8 +182,10 @@ Claude) rather than the Anthropic SDK.
153
182
 
154
183
  `s.mcp` (the session handle above) is the MCP connection your agent's loop
155
184
  drives. Any MCP-capable framework registers it as a server; the `cortexhub_*`
156
- tools (governed toolkit calls, brain recall/learn, files search) then appear
157
- automatically -- and, on the session handle, group with that run's LLM turns.
185
+ meta-tools (search, schemas, invoke) and the built-in toolkits the agent's group
186
+ is granted (`brain_recall`, `brain_learn`, `files_search`, `skills_find`, ...)
187
+ then appear automatically -- and, on the session handle, group with that run's
188
+ LLM turns.
158
189
 
159
190
  ```python
160
191
  conn = s.mcp # from cx.session(...) -> same session as .llm
@@ -275,9 +306,14 @@ def _parked_task(result):
275
306
  async def _await_decision(mcp, task_id: str) -> str:
276
307
  # Poll until the human decides in CortexHub; an approval runs the action.
277
308
  for _ in range(600): # ~10 min at 1s waits
278
- res = await mcp.call_tool("cortexhub_get_task", {"task_id": task_id, "wait_ms": 1000})
279
- if _payload(res).get("terminal"):
309
+ res = await mcp.call_tool("cortexhub_get_task", {"task_id": task_id, "wait_seconds": 1})
310
+ # structuredContent is {"ok", "status", "meta_tool", "result": {...}}.
311
+ task = _payload(res).get("result") or {}
312
+ if task.get("terminal"):
280
313
  return _text(res)
314
+ # While it waits, task["approval"]["routed_to"] names who approves it
315
+ # (e.g. ["Priya Shah"]), the same on the held invoke result's
316
+ # details.approval.
281
317
  return "approval timed out"
282
318
 
283
319
  print(asyncio.run(run_turn("Email the Q3 report to the finance team")))
@@ -296,3 +332,27 @@ the model step, each tool call, and the approval as a single trace.
296
332
 
297
333
  The MCP gateway also accepts MCP OAuth from third-party clients (Claude, Cursor)
298
334
  independently of this SDK.
335
+
336
+ ## Verify receipts and evidence packs without CortexHub
337
+
338
+ CortexHub signs every authorization record, receipt and enforcement decision
339
+ with the agent's Ed25519 key, and every evidence pack with a platform key. The
340
+ public keys are published at `https://api.cortexhub.ai/.well-known/cortexhub-signing-keys.json`
341
+ (platform) and `.../cortexhub-signing-keys/agents/<agent_id>.json` (per agent).
342
+ `cortexhub verify` checks a downloaded file against them; it never calls a
343
+ CortexHub API.
344
+
345
+ ```bash
346
+ pip install 'cortexhub[verify]'
347
+ cortexhub verify receipt.json # a downloaded receipt or authorization record
348
+ cortexhub verify evidence-pack.zip # signed manifest, every file, every record, every chain
349
+ cortexhub verify evidence-pack.zip --pack-record pack.json # also the whole-archive signature
350
+
351
+ # air-gapped: save the key sets once, then
352
+ cortexhub verify evidence-pack.zip --offline --keys cortexhub-signing-keys.json
353
+ ```
354
+
355
+ Exit code 0 means verified, 1 a check failed, 2 the file could not be read. The
356
+ verifier is one file (`src/cortexhub/verify.py`, standard library plus
357
+ `cryptography`) that also runs on its own: `python verify.py <file>`.
358
+ [How to verify](https://docs.cortexhub.ai/docs/architecture/verify-offline)
@@ -18,6 +18,7 @@ You don't rewrite your agent. You change a base URL and drop in one key.
18
18
  pip install cortexhub # zero-dependency core (URLs + headers)
19
19
  pip install 'cortexhub[ai]' # + a ready OpenAI-compatible client via cx.llm
20
20
  pip install 'cortexhub[mcp]' # + the official MCP client for cx.mcp() sessions
21
+ pip install 'cortexhub[verify]' # + `cortexhub verify`: check receipts and evidence packs offline
21
22
  ```
22
23
 
23
24
  ## The key
@@ -63,6 +64,7 @@ s.mcp.url # https://mcp.cortexhub.ai/v1/mcp
63
64
  s.mcp.headers # wire into your MCP transport (see "Tools" below)
64
65
 
65
66
  s.session_id # "conv-42" -- log or forward it to correlate
67
+ s.ai_headers # router headers for your own OpenAI-compatible client (below)
66
68
  ```
67
69
 
68
70
  Reuse the same handle across the run's turns so they group. An autonomous agent
@@ -71,49 +73,73 @@ Reuse the same handle across the run's turns so they group. An autonomous agent
71
73
 
72
74
  ## Inference without a session
73
75
 
74
- For a quick, standalone call, `cx.llm` is a ready OpenAI-compatible client and
75
- `cx.ai` gives the raw `base_url` + `api_key` any framework needs. These are NOT
76
- grouped into a session (no Sessions row) -- prefer `cx.session(...)` above when
77
- you want the run visible in CortexHub.
76
+ `cx.ai` gives the raw `base_url` + `api_key` any client needs, and `cx.llm` is a
77
+ ready OpenAI-compatible client. The router requires every call to name the end
78
+ user it acts for (`X-CortexHub-End-User-Subject`, else HTTP 400), so in practice
79
+ build the client from a session handle (`s.llm`, or `s.ai_headers` below).
78
80
 
79
81
  ```python
80
- cx.llm.chat.completions.create(model="cortexhub/auto", messages=[...])
81
- cx.llm.responses.create(model="cortexhub/auto", input="hi")
82
- cx.llm.models.list()
83
-
84
82
  cx.ai.base_url # e.g. https://api.cortexhub.ai/v1 (override with CORTEXHUB_ROUTER_URL)
85
83
  cx.ai.api_key # your cxh_key_...
84
+ cx.llm.models.list()
86
85
  ```
87
86
 
88
87
  ## Use your existing framework
89
88
 
90
89
  The router speaks the OpenAI wire protocol, so every framework integrates the
91
90
  same way: point its OpenAI-compatible provider at `cx.ai.base_url`, pass
92
- `cx.ai.api_key`, and choose a `model`.
91
+ `cx.ai.api_key`, choose a `model`, and send the session handle's **`ai_headers`**
92
+ as the client's default headers. They tell the router which run the call
93
+ belongs to and which end user it acts for (`X-CortexHub-End-User-Subject`,
94
+ `X-CortexHub-Session-Id`), so the framework's model calls land in the same
95
+ CortexHub session as the handle's tool calls.
93
96
 
94
97
  ```python
95
- base, key = cx.ai.base_url, cx.ai.api_key
98
+ s = cx.session(agent="support-bot", mcp_session_id="conv-42", end_user_subject="user_42")
99
+ base, key, headers = cx.ai.base_url, cx.ai.api_key, s.ai_headers
96
100
 
97
101
  # OpenAI SDK / plain
98
102
  from openai import OpenAI
99
- OpenAI(base_url=base, api_key=key).chat.completions.create(model="cortexhub/auto", messages=[...])
103
+ OpenAI(base_url=base, api_key=key, default_headers=headers)
100
104
 
101
105
  # LangChain / LangGraph
102
106
  from langchain_openai import ChatOpenAI
103
- ChatOpenAI(base_url=base, api_key=key, model="cortexhub/auto")
107
+ ChatOpenAI(base_url=base, api_key=key, model="cortexhub/auto", default_headers=headers)
104
108
 
105
109
  # CrewAI (LiteLLM under the hood)
106
110
  from crewai import LLM
107
- LLM(model="openai/cortexhub/auto", base_url=base, api_key=key)
111
+ LLM(model="openai/cortexhub/auto", base_url=base, api_key=key, extra_headers=headers)
108
112
 
109
113
  # AutoGen
110
114
  from autogen_ext.models.openai import OpenAIChatCompletionClient
111
- OpenAIChatCompletionClient(model="cortexhub/auto", base_url=base, api_key=key)
115
+ OpenAIChatCompletionClient(model="cortexhub/auto", base_url=base, api_key=key,
116
+ default_headers=headers)
112
117
 
113
118
  # Pydantic AI
119
+ from openai import AsyncOpenAI
114
120
  from pydantic_ai.models.openai import OpenAIModel
115
121
  from pydantic_ai.providers.openai import OpenAIProvider
116
- OpenAIModel("cortexhub/auto", provider=OpenAIProvider(base_url=base, api_key=key))
122
+ OpenAIModel("cortexhub/auto", provider=OpenAIProvider(
123
+ openai_client=AsyncOpenAI(base_url=base, api_key=key, default_headers=headers)))
124
+ ```
125
+
126
+ A LangGraph agent with CortexHub's model AND its governed tools (the MCP
127
+ connection through `langchain-mcp-adapters`), in one session:
128
+
129
+ ```python
130
+ from langchain_mcp_adapters.tools import load_mcp_tools
131
+ from langchain_openai import ChatOpenAI
132
+ from langgraph.prebuilt import create_react_agent
133
+ from mcp import ClientSession
134
+
135
+ run = cx.session(agent="lead-assistant", end_user_subject="northwind-ops",
136
+ mcp_session_id="lead-assistant-run-1")
137
+ llm = ChatOpenAI(model="cortexhub/auto", base_url=cx.ai.base_url,
138
+ api_key=cx.ai.api_key, default_headers=run.ai_headers)
139
+ async with run.mcp.open() as (read, write), ClientSession(read, write) as mcp:
140
+ await mcp.initialize()
141
+ agent = create_react_agent(llm, await load_mcp_tools(mcp))
142
+ state = await agent.ainvoke({"messages": [("user", "...")]})
117
143
  ```
118
144
 
119
145
  **Anthropic SDK:** the router is OpenAI-compatible, not Anthropic-Messages, so
@@ -124,8 +150,10 @@ Claude) rather than the Anthropic SDK.
124
150
 
125
151
  `s.mcp` (the session handle above) is the MCP connection your agent's loop
126
152
  drives. Any MCP-capable framework registers it as a server; the `cortexhub_*`
127
- tools (governed toolkit calls, brain recall/learn, files search) then appear
128
- automatically -- and, on the session handle, group with that run's LLM turns.
153
+ meta-tools (search, schemas, invoke) and the built-in toolkits the agent's group
154
+ is granted (`brain_recall`, `brain_learn`, `files_search`, `skills_find`, ...)
155
+ then appear automatically -- and, on the session handle, group with that run's
156
+ LLM turns.
129
157
 
130
158
  ```python
131
159
  conn = s.mcp # from cx.session(...) -> same session as .llm
@@ -246,9 +274,14 @@ def _parked_task(result):
246
274
  async def _await_decision(mcp, task_id: str) -> str:
247
275
  # Poll until the human decides in CortexHub; an approval runs the action.
248
276
  for _ in range(600): # ~10 min at 1s waits
249
- res = await mcp.call_tool("cortexhub_get_task", {"task_id": task_id, "wait_ms": 1000})
250
- if _payload(res).get("terminal"):
277
+ res = await mcp.call_tool("cortexhub_get_task", {"task_id": task_id, "wait_seconds": 1})
278
+ # structuredContent is {"ok", "status", "meta_tool", "result": {...}}.
279
+ task = _payload(res).get("result") or {}
280
+ if task.get("terminal"):
251
281
  return _text(res)
282
+ # While it waits, task["approval"]["routed_to"] names who approves it
283
+ # (e.g. ["Priya Shah"]), the same on the held invoke result's
284
+ # details.approval.
252
285
  return "approval timed out"
253
286
 
254
287
  print(asyncio.run(run_turn("Email the Q3 report to the finance team")))
@@ -267,3 +300,27 @@ the model step, each tool call, and the approval as a single trace.
267
300
 
268
301
  The MCP gateway also accepts MCP OAuth from third-party clients (Claude, Cursor)
269
302
  independently of this SDK.
303
+
304
+ ## Verify receipts and evidence packs without CortexHub
305
+
306
+ CortexHub signs every authorization record, receipt and enforcement decision
307
+ with the agent's Ed25519 key, and every evidence pack with a platform key. The
308
+ public keys are published at `https://api.cortexhub.ai/.well-known/cortexhub-signing-keys.json`
309
+ (platform) and `.../cortexhub-signing-keys/agents/<agent_id>.json` (per agent).
310
+ `cortexhub verify` checks a downloaded file against them; it never calls a
311
+ CortexHub API.
312
+
313
+ ```bash
314
+ pip install 'cortexhub[verify]'
315
+ cortexhub verify receipt.json # a downloaded receipt or authorization record
316
+ cortexhub verify evidence-pack.zip # signed manifest, every file, every record, every chain
317
+ cortexhub verify evidence-pack.zip --pack-record pack.json # also the whole-archive signature
318
+
319
+ # air-gapped: save the key sets once, then
320
+ cortexhub verify evidence-pack.zip --offline --keys cortexhub-signing-keys.json
321
+ ```
322
+
323
+ Exit code 0 means verified, 1 a check failed, 2 the file could not be read. The
324
+ verifier is one file (`src/cortexhub/verify.py`, standard library plus
325
+ `cryptography`) that also runs on its own: `python verify.py <file>`.
326
+ [How to verify](https://docs.cortexhub.ai/docs/architecture/verify-offline)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "3.2.0"
3
+ version = "3.4.0"
4
4
  description = "CortexHub platform SDK: point your agent at the governed LLM router + MCP gateway."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -8,7 +8,7 @@ license = { text = "MIT" }
8
8
  authors = [
9
9
  { name = "CortexHub", email = "hello@cortexhub.ai" }
10
10
  ]
11
- keywords = ["ai", "agents", "mcp" , "programmatic", "governance"]
11
+ keywords = ["ai", "agents", "mcp" , "programmatic", "governance", "audit", "verification"]
12
12
  classifiers = [
13
13
  "Development Status :: 5 - Production/Stable",
14
14
  "Intended Audience :: Developers",
@@ -37,7 +37,13 @@ ai = ["openai>=1.40"]
37
37
  # client's initialize handshake 404s on it. Cap to the gateway's major until it
38
38
  # moves to 2.x, so `pip install cortexhub[mcp]` resolves a compatible client.
39
39
  mcp = ["mcp>=1.0,<2"]
40
- all = ["openai>=1.40", "mcp>=1.0,<2"]
40
+ # `cortexhub verify`: check CortexHub receipts, authorization records and
41
+ # evidence packs offline (Ed25519 via the cryptography package).
42
+ verify = ["cryptography>=42"]
43
+ all = ["openai>=1.40", "mcp>=1.0,<2", "cryptography>=42"]
44
+
45
+ [project.scripts]
46
+ cortexhub = "cortexhub.cli:main"
41
47
 
42
48
  [project.urls]
43
49
  Homepage = "https://cortexhub.ai"
@@ -89,6 +95,7 @@ python-preference = "only-managed"
89
95
 
90
96
  [dependency-groups]
91
97
  dev = [
98
+ "cryptography==50.0.2",
92
99
  "pytest==9.0.3",
93
100
  "ruff==0.14.11",
94
101
  "mypy==1.19.1",
@@ -31,9 +31,7 @@ from .mcp_key import CortexhubKeyClient, McpKeySession
31
31
  from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession, McpOAuthToken
32
32
  from .session import SessionMcp
33
33
 
34
- __version__ = "3.2.0"
35
-
36
-
34
+ __version__ = "3.4.0"
37
35
  def init(api_key: str | None = None, **kwargs: object) -> Cortexhub:
38
36
  """Create a CortexHub client. Alias for :class:`Cortexhub`.
39
37
 
@@ -62,6 +60,6 @@ __all__ = [
62
60
  "McpOAuthSession",
63
61
  "McpOAuthToken",
64
62
  "SessionMcp",
65
- "init",
66
63
  "__version__",
64
+ "init",
67
65
  ]
@@ -0,0 +1,44 @@
1
+ """``cortexhub`` command line.
2
+
3
+ Subcommands:
4
+
5
+ * ``cortexhub verify <file>``: verify a CortexHub receipt, authorization record
6
+ or evidence pack without CortexHub (see :mod:`cortexhub.verify`).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+
13
+ from . import __version__
14
+
15
+ _USAGE = (
16
+ "usage: cortexhub <command> [options]\n"
17
+ "\n"
18
+ "commands:\n"
19
+ " verify verify a CortexHub receipt, authorization record or evidence pack offline\n"
20
+ "\n"
21
+ "Run 'cortexhub <command> --help' for a command's options."
22
+ )
23
+
24
+
25
+ def main(argv: list[str] | None = None) -> int:
26
+ """Entry point of the ``cortexhub`` console script."""
27
+ args = list(sys.argv[1:] if argv is None else argv)
28
+ if not args or args[0] in ("-h", "--help"):
29
+ print(_USAGE)
30
+ return 0 if args else 2
31
+ if args[0] == "--version":
32
+ print(f"cortexhub {__version__}")
33
+ return 0
34
+ command, rest = args[0], args[1:]
35
+ if command == "verify":
36
+ from .verify import main as verify_main
37
+
38
+ return verify_main(rest)
39
+ print(f"cortexhub: unknown command {command!r}\n\n{_USAGE}", file=sys.stderr)
40
+ return 2
41
+
42
+
43
+ if __name__ == "__main__":
44
+ sys.exit(main())
@@ -23,12 +23,13 @@ _AGENT_HEADER = "X-CortexHub-Agent"
23
23
  _END_USER_SUBJECT_HEADER = "X-CortexHub-End-User-Subject"
24
24
  _END_USER_DISPLAY_HINT_HEADER = "X-CortexHub-End-User-Display-Hint"
25
25
 
26
- # The LLM router groups a turn into a CortexHub session by these headers -- the
26
+ # The LLM router groups a turn into a CortexHub session by this header -- the
27
27
  # same session the MCP tool calls (Mcp-Session-Id) land in -- so one handle's
28
28
  # ``.llm`` and ``.mcp`` share one Session -> Trace -> Span with cost + user
29
- # attribution. The router names them without the ``-Subject`` suffix.
29
+ # attribution. The end user rides the same ``X-CortexHub-End-User-Subject``
30
+ # header the MCP gateway reads (the router still accepts the older
31
+ # ``X-CortexHub-End-User`` spelling from earlier SDKs).
30
32
  _ROUTER_SESSION_HEADER = "X-CortexHub-Session-Id"
31
- _ROUTER_END_USER_HEADER = "X-CortexHub-End-User"
32
33
 
33
34
  _KEY_PREFIX = "cxh_key_"
34
35
 
@@ -71,6 +72,38 @@ class McpKeySession:
71
72
  """
72
73
  return self.mcp_session_id
73
74
 
75
+ @property
76
+ def ai_headers(self) -> dict[str, str]:
77
+ """Headers for ANY OpenAI-compatible client on the CortexHub router.
78
+
79
+ The router groups a call into this handle's CortexHub session and
80
+ attributes it to its end user by these headers, so pass them as the
81
+ client's default headers when you build your own client (LangChain's
82
+ ``ChatOpenAI``, LlamaIndex, the OpenAI Agents SDK, raw HTTP) instead of
83
+ using :attr:`llm`. Auth is separate: the client's ``api_key`` is your
84
+ ``cxh_key_...`` (``cx.ai.api_key``) and its ``base_url`` is
85
+ ``cx.ai.base_url``.
86
+
87
+ .. code-block:: python
88
+
89
+ from langchain_openai import ChatOpenAI
90
+
91
+ run = cx.session(agent="lead-assistant", mcp_session_id="run-42",
92
+ end_user_subject="northwind-ops")
93
+ llm = ChatOpenAI(model="cortexhub/auto", base_url=cx.ai.base_url,
94
+ api_key=cx.ai.api_key, default_headers=run.ai_headers)
95
+
96
+ Contains ``X-CortexHub-End-User-Subject`` (when the handle has an end
97
+ user) and ``X-CortexHub-Session-Id`` (when it has a session id). A new
98
+ dict each call, safe to extend.
99
+ """
100
+ headers: dict[str, str] = {}
101
+ if self.end_user_subject:
102
+ headers[_END_USER_SUBJECT_HEADER] = self.end_user_subject
103
+ if self.mcp_session_id:
104
+ headers[_ROUTER_SESSION_HEADER] = self.mcp_session_id
105
+ return headers
106
+
74
107
  @property
75
108
  def llm(self) -> Any:
76
109
  """A ready OpenAI-compatible client scoped to THIS session (extra: ``ai``).
@@ -88,16 +121,13 @@ class McpKeySession:
88
121
  s.llm.chat.completions.create(model="cortexhub/auto", messages=[...])
89
122
  # ...and s.mcp for tools -- both in session "conv-42".
90
123
 
91
- Requires the ``openai`` package (``pip install 'cortexhub[ai]'``).
124
+ It sends :attr:`ai_headers`; to use another OpenAI-compatible client,
125
+ pass those headers to it yourself. Requires the ``openai`` package
126
+ (``pip install 'cortexhub[ai]'``).
92
127
  """
93
128
  from .ai import build_ai_gateway
94
129
 
95
- headers: dict[str, str] = {}
96
- if self.mcp_session_id:
97
- headers[_ROUTER_SESSION_HEADER] = self.mcp_session_id
98
- if self.end_user_subject:
99
- headers[_ROUTER_END_USER_HEADER] = self.end_user_subject
100
- return build_ai_gateway(self.api_key).client(default_headers=headers)
130
+ return build_ai_gateway(self.api_key).client(default_headers=self.ai_headers)
101
131
 
102
132
  def decide(
103
133
  self, approval_id: str, decision: str, note: str | None = None
@@ -155,7 +185,7 @@ class McpKeySession:
155
185
  method="POST",
156
186
  )
157
187
  try:
158
- with urllib.request.urlopen(req, timeout=30) as resp: # noqa: S310 - https
188
+ with urllib.request.urlopen(req, timeout=30) as resp:
159
189
  return json.loads(resp.read().decode("utf-8"))
160
190
  except urllib.error.HTTPError as exc:
161
191
  detail = exc.read().decode("utf-8", errors="replace")[:300]
@@ -0,0 +1,707 @@
1
+ """Verify CortexHub receipts, authorization records and evidence packs offline.
2
+
3
+ This module checks CortexHub signed artifacts with public material only: the
4
+ file itself and CortexHub's published public keys. It does not call any
5
+ CortexHub API, and it works air-gapped when given saved copies of the key sets.
6
+
7
+ It is a single file on purpose. It needs the Python standard library (3.11 or
8
+ later) and the ``cryptography`` package, nothing else, so a reviewer can read
9
+ it end to end and run it without installing CortexHub::
10
+
11
+ pip install cryptography
12
+ python verify.py receipt.json
13
+ python verify.py evidence-pack.zip --offline --keys cortexhub-signing-keys.json
14
+
15
+ With the SDK installed (``pip install 'cortexhub[verify]'``) the same checks
16
+ run as ``cortexhub verify <file>``.
17
+
18
+ What it checks
19
+ --------------
20
+ * A signed record file (``cortexhub.signed-record.v1``: a receipt or an
21
+ authorization record): the Ed25519 signature over the record's
22
+ ``cxh-canonical-json-v1`` bytes, with the agent key named in the record.
23
+ * An evidence pack ZIP (``cortexhub.evidence-pack.v2``): the platform
24
+ signature over ``manifest.json``; that every file matches the SHA-256 and
25
+ size the manifest lists and no file is unlisted; every receipt,
26
+ authorization record and enforcement decision signature, with the agent
27
+ keys in ``signing_keys.json``; and every per-agent hash chain (each record
28
+ links to the previous record's canonical hash, one start per chain in the
29
+ period, no gaps, no forks, consecutive receipt sequence numbers).
30
+ * Optionally (``--pack-record``) the whole-archive signature on the pack's API
31
+ record, the only check available for packs issued before the signed
32
+ manifest existed.
33
+
34
+ Where the keys come from
35
+ ------------------------
36
+ ``--keys`` (a JWKS file or URL, repeatable) is used first. Otherwise the key set
37
+ is fetched from ``--api-url`` (default https://api.cortexhub.ai). A key URL
38
+ written inside a file is followed only when it is https on cortexhub.ai or a
39
+ subdomain, so a forged file cannot point this tool at keys of its own choosing.
40
+ ``--offline`` never touches the network.
41
+
42
+ Exit codes: 0 verified, 1 a check failed, 2 the input could not be read.
43
+
44
+ MIT licensed. Part of the CortexHub Python SDK.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import argparse
50
+ import base64
51
+ import hashlib
52
+ import io
53
+ import json
54
+ import sys
55
+ import urllib.request
56
+ import zipfile
57
+ from dataclasses import dataclass, field
58
+ from datetime import datetime, timezone
59
+ from pathlib import Path
60
+ from typing import Any
61
+ from urllib.parse import urlparse
62
+
63
+ VERIFIER_VERSION = "1"
64
+ CANONICALIZATION = "cxh-canonical-json-v1"
65
+ SIGNED_RECORD_FORMAT = "cortexhub.signed-record.v1"
66
+ EVIDENCE_PACK_FORMAT = "cortexhub.evidence-pack.v2"
67
+ DEFAULT_API_URL = "https://api.cortexhub.ai"
68
+ PLATFORM_KEYS_PATH = "/.well-known/cortexhub-signing-keys.json"
69
+ AGENT_KEYS_PATH = "/.well-known/cortexhub-signing-keys/agents/{agent_id}.json"
70
+ TRUSTED_KEY_HOST = "cortexhub.ai"
71
+ DOCS_URL = "https://docs.cortexhub.ai/docs/architecture/verify-offline"
72
+
73
+ PURPOSE_EVIDENCE_PACK = "evidence_pack"
74
+ PURPOSE_AGENT_RECORDS = "agent_records"
75
+
76
+ RECEIPT = "receipt"
77
+ AUTHORIZATION_RECORD = "authorization_record"
78
+ DECISION = "decision"
79
+
80
+ # Fields outside each record's signature (``cxh-canonical-json-v1`` scope).
81
+ UNSIGNED_FIELDS: dict[str, tuple[str, ...]] = {
82
+ AUTHORIZATION_RECORD: (
83
+ "signature",
84
+ "calls_made",
85
+ "consumed_at",
86
+ "created_at",
87
+ "sequence_number",
88
+ ),
89
+ RECEIPT: ("signature", "created_at", "purged_at", "purge_reason"),
90
+ DECISION: ("signature", "created_at"),
91
+ }
92
+ # Annotations an export adds to a record; never signed.
93
+ SIGNED_CONNECTION_ID = "signed_connection_id"
94
+ ANNOTATION_FIELDS: tuple[str, ...] = (
95
+ "agent_name",
96
+ "withheld_fields",
97
+ "signed_body_sha256",
98
+ SIGNED_CONNECTION_ID,
99
+ )
100
+ # An enforcement decision recorded by an earlier CortexHub version for a call
101
+ # with no connection was signed with one of these internal placeholders in
102
+ # ``connection_id`` and stored with it empty. Its export names the placeholder
103
+ # in ``signed_connection_id``; it is put back for the signature check only (the
104
+ # chain hash stays on the stored record). Fixed list: the platform's
105
+ # ``SENTINEL_CONNECTION_IDS`` (cxh_platform/constants/toolkit.py).
106
+ LEGACY_DECISION_CONNECTION_PLACEHOLDERS: tuple[str, ...] = (
107
+ "cxh_conn_curated",
108
+ "cxh_conn_meta",
109
+ "cxh_conn_unresolved",
110
+ )
111
+
112
+ # Evidence pack members that hold signed records, and each chain's link fields.
113
+ PACK_RECORD_MEMBERS: dict[str, str] = {
114
+ "receipts.ndjson": RECEIPT,
115
+ "envelopes.ndjson": AUTHORIZATION_RECORD,
116
+ "decisions.ndjson": DECISION,
117
+ }
118
+ CHAIN_LINKS: dict[str, tuple[str, str]] = {
119
+ RECEIPT: ("prev_receipt_id", "prev_receipt_hash"),
120
+ AUTHORIZATION_RECORD: ("prev_envelope_id", "prev_envelope_hash"),
121
+ DECISION: ("prev_decision_id", "prev_decision_hash"),
122
+ }
123
+ RECORD_LABELS: dict[str, str] = {
124
+ RECEIPT: "Receipts",
125
+ AUTHORIZATION_RECORD: "Authorization records",
126
+ DECISION: "Enforcement decisions",
127
+ }
128
+ GENESIS = "GENESIS"
129
+ MANIFEST_MEMBER = "manifest.json"
130
+ MANIFEST_SIGNATURE_MEMBER = "manifest.signature.json"
131
+ SIGNING_KEYS_MEMBER = "signing_keys.json"
132
+
133
+
134
+ class InputError(Exception):
135
+ """The input could not be read or is not a CortexHub artifact."""
136
+
137
+
138
+ # -- canonical form -------------------------------------------------------------
139
+
140
+
141
+ def _iso_milliseconds(value: datetime) -> str:
142
+ value = value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value.astimezone(timezone.utc)
143
+ value = value.replace(microsecond=(value.microsecond // 1000) * 1000)
144
+ return value.isoformat(timespec="milliseconds")
145
+
146
+
147
+ def _coerce(value: Any) -> Any:
148
+ # A string that parses as an ISO-8601 datetime is rewritten as UTC with
149
+ # milliseconds; everything else is unchanged. Matches the platform rule
150
+ # byte for byte (Python 3.11+ ``fromisoformat`` grammar).
151
+ if isinstance(value, str):
152
+ if len(value) >= 10 and value[4] == "-":
153
+ try:
154
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
155
+ except ValueError:
156
+ parsed = None
157
+ if parsed is not None:
158
+ return _iso_milliseconds(parsed)
159
+ return value
160
+ if isinstance(value, dict):
161
+ return {k: _coerce(v) for k, v in value.items()}
162
+ if isinstance(value, list):
163
+ return [_coerce(v) for v in value]
164
+ return value
165
+
166
+
167
+ def canonical_bytes(body: dict[str, Any]) -> bytes:
168
+ """``cxh-canonical-json-v1`` bytes of ``body``.
169
+
170
+ Drop the ``signature`` key and top-level null values (nested nulls stay),
171
+ rewrite ISO-8601 datetime strings as UTC milliseconds, then serialise with
172
+ sorted keys, no whitespace and non-ASCII kept, encoded UTF-8.
173
+ """
174
+ scoped = {k: _coerce(v) for k, v in body.items() if k != "signature" and v is not None}
175
+ return json.dumps(scoped, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
176
+
177
+
178
+ def signed_body(record_type: str, record: dict[str, Any]) -> dict[str, Any]:
179
+ """The record minus its unsigned fields and export annotations."""
180
+ drop = set(UNSIGNED_FIELDS[record_type]) | set(ANNOTATION_FIELDS)
181
+ return {k: v for k, v in record.items() if k not in drop}
182
+
183
+
184
+ def record_hash(record_type: str, record: dict[str, Any]) -> str:
185
+ """SHA-256 hex of a record's canonical bytes (what the next record links to)."""
186
+ withheld_hash = record.get("signed_body_sha256")
187
+ if record.get("withheld_fields") and isinstance(withheld_hash, str):
188
+ return withheld_hash
189
+ return hashlib.sha256(canonical_bytes(signed_body(record_type, record))).hexdigest()
190
+
191
+
192
+ # -- keys -------------------------------------------------------------------------
193
+
194
+
195
+ def _b64url_decode(value: str) -> bytes:
196
+ return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
197
+
198
+
199
+ def key_fingerprint(jwk: dict[str, Any]) -> str:
200
+ """SHA-256 hex of the raw public key (``cxh:fingerprint_sha256``)."""
201
+ return hashlib.sha256(_b64url_decode(str(jwk["x"]))).hexdigest()
202
+
203
+
204
+ def short_fingerprint(fingerprint: str) -> str:
205
+ head = fingerprint[:16]
206
+ return " ".join(head[i : i + 4] for i in range(0, len(head), 4))
207
+
208
+
209
+ def verify_ed25519(jwk: dict[str, Any], signature_b64url: str, data: bytes) -> bool:
210
+ """True when ``signature_b64url`` is a valid Ed25519 signature of ``data``."""
211
+ try:
212
+ from cryptography.exceptions import InvalidSignature
213
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
214
+ except ImportError as exc: # pragma: no cover - environment guard
215
+ raise InputError(
216
+ "the 'cryptography' package is required: pip install 'cortexhub[verify]'"
217
+ ) from exc
218
+ if jwk.get("kty") != "OKP" or jwk.get("crv") != "Ed25519":
219
+ return False
220
+ try:
221
+ public_key = Ed25519PublicKey.from_public_bytes(_b64url_decode(str(jwk["x"])))
222
+ public_key.verify(_b64url_decode(signature_b64url), data)
223
+ except (InvalidSignature, ValueError):
224
+ return False
225
+ return True
226
+
227
+
228
+ def _trusted_key_url(url: Any) -> bool:
229
+ if not isinstance(url, str):
230
+ return False
231
+ parsed = urlparse(url)
232
+ host = (parsed.hostname or "").lower()
233
+ return parsed.scheme == "https" and (host == TRUSTED_KEY_HOST or host.endswith("." + TRUSTED_KEY_HOST))
234
+
235
+
236
+ def _json_object(text: str, source: str) -> dict[str, Any]:
237
+ value = json.loads(text)
238
+ if not isinstance(value, dict):
239
+ raise InputError(f"{source} is not a JSON object")
240
+ return value
241
+
242
+
243
+ def _fetch_json(url: str) -> dict[str, Any]:
244
+ # Only https on cortexhub.ai, or the --api-url the user typed, reaches here.
245
+ request = urllib.request.Request(
246
+ url,
247
+ headers={"Accept": "application/json", "User-Agent": f"cortexhub-verify/{VERIFIER_VERSION}"},
248
+ )
249
+ with urllib.request.urlopen(request, timeout=20) as response:
250
+ return _json_object(response.read().decode("utf-8"), url)
251
+
252
+
253
+ class KeyStore:
254
+ """Public keys by kid, from ``--keys`` sources, a pack, or the published sets."""
255
+
256
+ def __init__(
257
+ self,
258
+ *,
259
+ sources: list[str] | None = None,
260
+ api_url: str | None = None,
261
+ offline: bool = False,
262
+ ) -> None:
263
+ self._explicit_api_url = api_url.rstrip("/") if api_url else None
264
+ self._offline = offline
265
+ self._keys: dict[str, dict[str, Any]] = {}
266
+ self._origin: dict[str, str] = {}
267
+ self._fetched: set[str] = set()
268
+ for source in sources or []:
269
+ self.add_jwks(self._load_source(source), origin=source)
270
+
271
+ def _load_source(self, source: str) -> dict[str, Any]:
272
+ if source.startswith(("https://", "http://")):
273
+ if self._offline:
274
+ raise InputError(f"--offline was given but --keys names a URL: {source}")
275
+ return _fetch_json(source)
276
+ try:
277
+ return _json_object(Path(source).read_text(encoding="utf-8"), source)
278
+ except (OSError, ValueError) as exc:
279
+ raise InputError(f"cannot read key set {source}: {exc}") from exc
280
+
281
+ def add_jwks(self, jwks: dict[str, Any], *, origin: str) -> list[str]:
282
+ """Add a JWKS; a kid already known with a different key is a conflict."""
283
+ problems: list[str] = []
284
+ for jwk in jwks.get("keys", []) if isinstance(jwks, dict) else []:
285
+ kid = jwk.get("kid")
286
+ if not isinstance(kid, str) or "x" not in jwk:
287
+ continue
288
+ known = self._keys.get(kid)
289
+ if known is not None and known.get("x") != jwk.get("x"):
290
+ problems.append(f"key {kid} differs between {self._origin[kid]} and {origin}")
291
+ continue
292
+ self._keys.setdefault(kid, jwk)
293
+ self._origin.setdefault(kid, origin)
294
+ return problems
295
+
296
+ def _api_url(self, hint: Any) -> str:
297
+ if self._explicit_api_url:
298
+ return self._explicit_api_url
299
+ if _trusted_key_url(hint):
300
+ parsed = urlparse(str(hint))
301
+ return f"{parsed.scheme}://{parsed.netloc}"
302
+ return DEFAULT_API_URL
303
+
304
+ def _fetch_once(self, url: str) -> None:
305
+ if self._offline or url in self._fetched:
306
+ return
307
+ self._fetched.add(url)
308
+ try:
309
+ self.add_jwks(_fetch_json(url), origin=url)
310
+ except (OSError, ValueError) as exc:
311
+ raise InputError(f"cannot fetch {url}: {exc}") from exc
312
+
313
+ def platform_key(self, kid: str, *, url_hint: Any = None) -> dict[str, Any] | None:
314
+ if kid not in self._keys:
315
+ self._fetch_once(self._api_url(url_hint) + PLATFORM_KEYS_PATH)
316
+ jwk = self._keys.get(kid)
317
+ if jwk is None or jwk.get("cxh:purpose") != PURPOSE_EVIDENCE_PACK:
318
+ return None
319
+ return jwk
320
+
321
+ def agent_key(self, agent_id: str, kid: str, *, url_hint: Any = None) -> dict[str, Any] | None:
322
+ if kid not in self._keys:
323
+ self._fetch_once(self._api_url(url_hint) + AGENT_KEYS_PATH.format(agent_id=agent_id))
324
+ jwk = self._keys.get(kid)
325
+ if jwk is None or jwk.get("cxh:purpose") != PURPOSE_AGENT_RECORDS:
326
+ return None
327
+ if jwk.get("cxh:agent_id") != agent_id:
328
+ return None
329
+ return jwk
330
+
331
+ def origin(self, kid: str) -> str:
332
+ return self._origin.get(kid, "")
333
+
334
+ @property
335
+ def offline(self) -> bool:
336
+ return self._offline
337
+
338
+ def missing_hint(self) -> str:
339
+ return " (not in the key sets given with --keys)" if self._offline else ""
340
+
341
+
342
+ # -- report -----------------------------------------------------------------------
343
+
344
+
345
+ @dataclass
346
+ class Check:
347
+ """One check. ``ok`` is None when the check cannot be made offline."""
348
+
349
+ name: str
350
+ ok: bool | None
351
+ detail: str
352
+
353
+
354
+ @dataclass
355
+ class Report:
356
+ artifact: str
357
+ checks: list[Check] = field(default_factory=list)
358
+
359
+ def add(self, name: str, ok: bool | None, detail: str) -> None:
360
+ self.checks.append(Check(name, ok, detail))
361
+
362
+ @property
363
+ def ok(self) -> bool:
364
+ return bool(self.checks) and all(c.ok is not False for c in self.checks) and any(
365
+ c.ok for c in self.checks
366
+ )
367
+
368
+ def as_dict(self) -> dict[str, Any]:
369
+ return {
370
+ "artifact": self.artifact,
371
+ "verified": self.ok,
372
+ "checks": [{"name": c.name, "ok": c.ok, "detail": c.detail} for c in self.checks],
373
+ }
374
+
375
+ def render(self) -> str:
376
+ marks = {True: "[ok] ", False: "[FAIL]", None: "[n/a] "}
377
+ lines = [f"CortexHub verify: {self.artifact}"]
378
+ lines += [f" {marks[c.ok]} {c.name}: {c.detail}" for c in self.checks]
379
+ lines.append("Result: VERIFIED" if self.ok else "Result: NOT VERIFIED")
380
+ return "\n".join(lines)
381
+
382
+
383
+ def _key_label(jwk: dict[str, Any]) -> str:
384
+ status = jwk.get("cxh:status")
385
+ suffix = ", retired" if status == "retired" else ""
386
+ return f"CortexHub public key {short_fingerprint(key_fingerprint(jwk))} ({jwk['kid']}{suffix})"
387
+
388
+
389
+ # -- single record ----------------------------------------------------------------
390
+
391
+
392
+ def verify_record_signature(record_type: str, record: dict[str, Any], keys: KeyStore, *, url_hint: Any = None) -> Check:
393
+ """Check one record's signature with its agent's key."""
394
+ name = "Signature"
395
+ agent_id = record.get("agent_id")
396
+ kid = record.get("signing_key_id")
397
+ signature = record.get("signature")
398
+ if not (isinstance(agent_id, str) and isinstance(kid, str) and isinstance(signature, str)):
399
+ return Check(name, False, "the record has no agent_id, signing_key_id or signature")
400
+ jwk = keys.agent_key(agent_id, kid, url_hint=url_hint)
401
+ if jwk is None:
402
+ return Check(
403
+ name,
404
+ False,
405
+ f"no published key {kid} for agent {agent_id}{keys.missing_hint()} (revoked, or not a CortexHub key)",
406
+ )
407
+ body = signed_body(record_type, record)
408
+ legacy = SIGNED_CONNECTION_ID in record
409
+ if legacy:
410
+ placeholder = record.get(SIGNED_CONNECTION_ID)
411
+ if record_type != DECISION or placeholder not in LEGACY_DECISION_CONNECTION_PLACEHOLDERS:
412
+ return Check(name, False, f"{SIGNED_CONNECTION_ID} {placeholder!r} is not allowed on this record")
413
+ if record.get("connection_id") is not None:
414
+ return Check(name, False, f"{SIGNED_CONNECTION_ID} is set but the record has a connection_id")
415
+ body["connection_id"] = placeholder
416
+ if not verify_ed25519(jwk, signature, canonical_bytes(body)):
417
+ return Check(name, False, f"does not match {_key_label(jwk)}: the record was changed")
418
+ if legacy:
419
+ return Check(
420
+ name,
421
+ True,
422
+ f"verified with {_key_label(jwk)} (recorded by an earlier CortexHub version, signed with an internal "
423
+ "placeholder where the connection is empty)",
424
+ )
425
+ return Check(name, True, f"verified with {_key_label(jwk)}")
426
+
427
+
428
+ def verify_signed_record_document(doc: dict[str, Any], keys: KeyStore) -> Report:
429
+ """Verify a ``cortexhub.signed-record.v1`` file."""
430
+ record_type = doc.get("record_type")
431
+ record = doc.get("record")
432
+ report = Report(f"{str(record_type).replace('_', ' ')} {record.get('id') if isinstance(record, dict) else ''}".strip())
433
+ if record_type not in UNSIGNED_FIELDS or not isinstance(record, dict):
434
+ raise InputError("not a CortexHub signed record (unknown record_type or no record)")
435
+ if doc.get("canonicalization") != CANONICALIZATION:
436
+ report.add("Canonical form", False, f"unsupported canonicalization {doc.get('canonicalization')!r}")
437
+ return report
438
+ if list(doc.get("unsigned_fields") or []) != list(UNSIGNED_FIELDS[record_type]):
439
+ report.add(
440
+ "Unsigned fields",
441
+ False,
442
+ "the file lists different unsigned fields than CortexHub signs; the built-in list is used",
443
+ )
444
+ check = verify_record_signature(record_type, record, keys, url_hint=doc.get("keys_url"))
445
+ report.checks.append(check)
446
+ claimed = doc.get("key_fingerprint_sha256")
447
+ kid = record.get("signing_key_id")
448
+ agent_id = record.get("agent_id")
449
+ if check.ok and isinstance(claimed, str) and isinstance(kid, str) and isinstance(agent_id, str):
450
+ jwk = keys.agent_key(agent_id, kid)
451
+ if jwk is not None and key_fingerprint(jwk) != claimed:
452
+ report.add("Key fingerprint", False, "the file names a different key fingerprint than the published key")
453
+ return report
454
+
455
+
456
+ # -- evidence pack ----------------------------------------------------------------
457
+
458
+
459
+ def _verify_pack_record(zip_bytes: bytes, pack_record: dict[str, Any], keys: KeyStore, report: Report) -> None:
460
+ manifest = pack_record.get("manifest") or {}
461
+ sha = hashlib.sha256(zip_bytes).hexdigest()
462
+ if manifest.get("sha256") != sha:
463
+ report.add("Archive hash", False, "the ZIP's SHA-256 differs from the pack record: the archive was changed")
464
+ return
465
+ report.add("Archive hash", True, "the ZIP's SHA-256 matches the pack record")
466
+ completed_at = str(pack_record.get("completed_at") or "")
467
+ if completed_at.endswith("Z"):
468
+ completed_at = completed_at[:-1] + "+00:00"
469
+ payload = json.dumps(
470
+ {"completed_at": completed_at, "pack_id": pack_record.get("id"), "sha256": sha},
471
+ sort_keys=True,
472
+ separators=(",", ":"),
473
+ ).encode("utf-8")
474
+ jwk = keys.platform_key(str(manifest.get("signing_key_id")))
475
+ if jwk is None:
476
+ report.add("Archive signature", False, f"no published platform key {manifest.get('signing_key_id')}")
477
+ elif verify_ed25519(jwk, str(manifest.get("signature") or ""), payload):
478
+ report.add("Archive signature", True, f"verified with {_key_label(jwk)}")
479
+ else:
480
+ report.add("Archive signature", False, f"does not match {_key_label(jwk)}")
481
+
482
+
483
+ def _check_chain(record_type: str, records: list[dict[str, Any]], report: Report) -> None:
484
+ label = RECORD_LABELS[record_type]
485
+ if not records:
486
+ report.add(f"{label} chain", True, "no records in the period")
487
+ return
488
+ prev_id_field, prev_hash_field = CHAIN_LINKS[record_type]
489
+ problems: list[str] = []
490
+ by_agent: dict[str, list[dict[str, Any]]] = {}
491
+ for record in records:
492
+ by_agent.setdefault(str(record.get("agent_id")), []).append(record)
493
+ for agent_id, chain in sorted(by_agent.items()):
494
+ by_id = {str(r.get("id")): r for r in chain}
495
+ children: dict[str, int] = {}
496
+ starts = 0
497
+ for record in chain:
498
+ prev_id = record.get(prev_id_field)
499
+ prev_hash = record.get(prev_hash_field)
500
+ if prev_id is None:
501
+ starts += 1
502
+ if prev_hash != GENESIS:
503
+ problems.append(f"{record.get('id')} has no previous record but is not the first ({agent_id})")
504
+ continue
505
+ children[str(prev_id)] = children.get(str(prev_id), 0) + 1
506
+ prev = by_id.get(str(prev_id))
507
+ if prev is None:
508
+ starts += 1
509
+ continue
510
+ if record_hash(record_type, prev) != prev_hash:
511
+ problems.append(f"{record.get('id')} does not link to {prev_id} ({agent_id}): a record was changed")
512
+ if starts > 1:
513
+ problems.append(f"{starts - 1} gap(s) in the chain of agent {agent_id}: records are missing")
514
+ problems += [f"{prev} has {n} successors ({agent_id}): the chain forks" for prev, n in children.items() if n > 1]
515
+ if record_type == RECEIPT:
516
+ seqs = sorted(int(r.get("sequence_number") or 0) for r in chain)
517
+ if seqs and seqs != list(range(seqs[0], seqs[0] + len(seqs))):
518
+ problems.append(f"receipt sequence numbers of agent {agent_id} are not consecutive")
519
+ if problems:
520
+ report.add(f"{label} chain", False, "; ".join(problems))
521
+ return
522
+ agents = len(by_agent)
523
+ across = f" across {agents} agents" if agents > 1 else ""
524
+ noun = "record" if len(records) == 1 else "records"
525
+ report.add(f"{label} chain", True, f"Chain intact: {len(records)} {noun}{across}, no gaps")
526
+
527
+
528
+ def verify_evidence_pack(zip_bytes: bytes, keys: KeyStore, *, pack_record: dict[str, Any] | None = None) -> Report:
529
+ """Verify an evidence pack ZIP."""
530
+ try:
531
+ archive = zipfile.ZipFile(io.BytesIO(zip_bytes))
532
+ except zipfile.BadZipFile as exc:
533
+ raise InputError(f"not a ZIP archive: {exc}") from exc
534
+ with archive:
535
+ names = archive.namelist()
536
+ if MANIFEST_MEMBER not in names:
537
+ raise InputError("not a CortexHub evidence pack (no manifest.json)")
538
+ manifest_bytes = archive.read(MANIFEST_MEMBER)
539
+ manifest = json.loads(manifest_bytes.decode("utf-8"))
540
+ report = Report(f"evidence pack {manifest.get('pack_id', '')}".strip())
541
+ if pack_record is not None:
542
+ _verify_pack_record(zip_bytes, pack_record, keys, report)
543
+ if MANIFEST_SIGNATURE_MEMBER not in names:
544
+ report.add(
545
+ "Signed manifest",
546
+ None if pack_record is not None else False,
547
+ "this pack was issued before packs carried a signed manifest; "
548
+ + ("only the archive signature above applies" if pack_record is not None else "pass --pack-record <the pack's API record JSON>"),
549
+ )
550
+ return report
551
+ signature = json.loads(archive.read(MANIFEST_SIGNATURE_MEMBER).decode("utf-8"))
552
+ kid = str(signature.get("key_id") or manifest.get("signing_key_id") or "")
553
+ jwk = keys.platform_key(kid, url_hint=manifest.get("keys_url"))
554
+ if signature.get("signed_file") != MANIFEST_MEMBER:
555
+ report.add("Manifest signature", False, "the signature does not name manifest.json")
556
+ return report
557
+ if jwk is None:
558
+ report.add("Manifest signature", False, f"no published CortexHub platform key {kid}{keys.missing_hint()}")
559
+ return report
560
+ if not verify_ed25519(jwk, str(signature.get("signature") or ""), manifest_bytes):
561
+ report.add("Manifest signature", False, f"does not match {_key_label(jwk)}: manifest.json was changed")
562
+ return report
563
+ report.add("Manifest signature", True, f"verified with {_key_label(jwk)}")
564
+ if manifest.get("canonicalization") != CANONICALIZATION:
565
+ report.add("Canonical form", False, f"unsupported canonicalization {manifest.get('canonicalization')!r}")
566
+ return report
567
+
568
+ # Every file is listed with the right hash and size; nothing extra.
569
+ listed: dict[str, dict[str, Any]] = manifest.get("files") or {}
570
+ problems = []
571
+ for name in names:
572
+ if name in (MANIFEST_MEMBER, MANIFEST_SIGNATURE_MEMBER) or name.endswith("/"):
573
+ continue
574
+ entry = listed.get(name)
575
+ body = archive.read(name)
576
+ if entry is None:
577
+ problems.append(f"{name} is not in the signed manifest")
578
+ elif entry.get("sha256") != hashlib.sha256(body).hexdigest() or entry.get("bytes") != len(body):
579
+ problems.append(f"{name} was changed")
580
+ problems += [f"{name} is missing" for name in listed if name not in names]
581
+ if problems:
582
+ report.add("Files", False, "; ".join(problems))
583
+ return report
584
+ report.add("Files", True, f"{len(listed)} files match the signed manifest")
585
+
586
+ # Agent keys come with the pack; the signed manifest vouches for them.
587
+ conflicts = keys.add_jwks(json.loads(archive.read(SIGNING_KEYS_MEMBER).decode("utf-8")), origin=SIGNING_KEYS_MEMBER) if SIGNING_KEYS_MEMBER in names else []
588
+ if conflicts:
589
+ report.add("Agent keys", False, "; ".join(conflicts))
590
+
591
+ verified = failed = withheld = legacy = 0
592
+ failures: list[str] = []
593
+ records_by_type: dict[str, list[dict[str, Any]]] = {t: [] for t in PACK_RECORD_MEMBERS.values()}
594
+ for member, record_type in PACK_RECORD_MEMBERS.items():
595
+ if member not in names:
596
+ continue
597
+ for line in archive.read(member).decode("utf-8").splitlines():
598
+ if not line.strip():
599
+ continue
600
+ record = json.loads(line)
601
+ records_by_type[record_type].append(record)
602
+ if record.get("withheld_fields"):
603
+ withheld += 1
604
+ continue
605
+ check = verify_record_signature(record_type, record, keys, url_hint=manifest.get("keys_url"))
606
+ if check.ok:
607
+ verified += 1
608
+ if SIGNED_CONNECTION_ID in record:
609
+ legacy += 1
610
+ else:
611
+ failed += 1
612
+ if len(failures) < 5:
613
+ failures.append(f"{record.get('id')}: {check.detail}")
614
+ total = verified + failed + withheld
615
+ if failed:
616
+ report.add("Record signatures", False, f"{failed} of {total} failed: " + "; ".join(failures))
617
+ else:
618
+ note = ""
619
+ if legacy:
620
+ noun = "decision was" if legacy == 1 else "decisions were"
621
+ note = (
622
+ f" ({legacy} enforcement {noun} recorded by an earlier CortexHub version and signed with an internal "
623
+ "placeholder where the connection is empty)"
624
+ )
625
+ report.add("Record signatures", True, f"{verified} of {total} verified with the agents' keys{note}")
626
+ if withheld:
627
+ report.add(
628
+ "Withheld records",
629
+ None,
630
+ f"{withheld} authorization record(s) carry the agent owner's private reason, withheld from the "
631
+ "pack; their own signatures cannot be checked here, their chain links are",
632
+ )
633
+ for record_type, records in records_by_type.items():
634
+ _check_chain(record_type, records, report)
635
+ return report
636
+
637
+
638
+ # -- entry points -----------------------------------------------------------------
639
+
640
+
641
+ def verify_path(path: str, keys: KeyStore, *, pack_record: dict[str, Any] | None = None) -> Report:
642
+ """Verify a signed record JSON file or an evidence pack ZIP."""
643
+ try:
644
+ data = Path(path).read_bytes()
645
+ except OSError as exc:
646
+ raise InputError(f"cannot read {path}: {exc}") from exc
647
+ if data[:2] == b"PK":
648
+ return verify_evidence_pack(data, keys, pack_record=pack_record)
649
+ try:
650
+ doc = json.loads(data.decode("utf-8"))
651
+ except ValueError as exc:
652
+ raise InputError(f"{path} is neither a ZIP nor JSON: {exc}") from exc
653
+ if not isinstance(doc, dict) or doc.get("format") != SIGNED_RECORD_FORMAT:
654
+ raise InputError(f"{path} is not a CortexHub signed record ({SIGNED_RECORD_FORMAT})")
655
+ return verify_signed_record_document(doc, keys)
656
+
657
+
658
+ def build_parser(prog: str = "cortexhub verify") -> argparse.ArgumentParser:
659
+ parser = argparse.ArgumentParser(
660
+ prog=prog,
661
+ description="Verify a CortexHub receipt, authorization record or evidence pack without CortexHub.",
662
+ epilog=f"Guide: {DOCS_URL}",
663
+ )
664
+ parser.add_argument("file", help="a signed record (.json) or an evidence pack (.zip)")
665
+ parser.add_argument(
666
+ "--keys",
667
+ action="append",
668
+ default=[],
669
+ metavar="FILE_OR_URL",
670
+ help="a CortexHub key set (JWKS) to use; repeatable. Saved copies make the check air-gapped.",
671
+ )
672
+ parser.add_argument(
673
+ "--api-url",
674
+ default=None,
675
+ help=f"where to fetch the published key sets (default {DEFAULT_API_URL})",
676
+ )
677
+ parser.add_argument("--offline", action="store_true", help="never use the network; needs --keys for platform keys")
678
+ parser.add_argument(
679
+ "--pack-record",
680
+ metavar="FILE",
681
+ help="the pack's API record JSON, to also check the whole-archive signature",
682
+ )
683
+ parser.add_argument("--json", action="store_true", help="print the result as JSON")
684
+ return parser
685
+
686
+
687
+ def main(argv: list[str] | None = None, *, prog: str = "cortexhub verify") -> int:
688
+ """Run the verifier. Returns the process exit code."""
689
+ args = build_parser(prog).parse_args(argv)
690
+ if sys.version_info < (3, 11):
691
+ print("cortexhub verify needs Python 3.11 or later", file=sys.stderr)
692
+ return 2
693
+ try:
694
+ keys = KeyStore(sources=args.keys, api_url=args.api_url, offline=args.offline)
695
+ pack_record = None
696
+ if args.pack_record:
697
+ pack_record = json.loads(Path(args.pack_record).read_text(encoding="utf-8"))
698
+ report = verify_path(args.file, keys, pack_record=pack_record)
699
+ except (InputError, OSError, ValueError) as exc:
700
+ print(f"cortexhub verify: {exc}", file=sys.stderr)
701
+ return 2
702
+ print(json.dumps(report.as_dict(), indent=2) if args.json else report.render())
703
+ return 0 if report.ok else 1
704
+
705
+
706
+ if __name__ == "__main__":
707
+ sys.exit(main(prog="verify.py"))
File without changes
File without changes
File without changes