primarypath-verify 1.0.0rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: primarypath-verify
3
+ Version: 1.0.0rc1
4
+ Summary: Offline verifier for Primary Path audit bundles: the record stands on its own math
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ License-File: LICENSE
8
+ Requires-Dist: cryptography>=42
9
+ Dynamic: license-file
@@ -0,0 +1,7 @@
1
+ primarypath_verify.py,sha256=jp4EZprfrby27TdeboJhXXC06O0tNghZfqYLlqwXzo0,23849
2
+ primarypath_verify-1.0.0rc1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
3
+ primarypath_verify-1.0.0rc1.dist-info/METADATA,sha256=wFy-pyKLI7C6oLV2QwvhBA8ibN0NM_vLAKs1m92nTHM,288
4
+ primarypath_verify-1.0.0rc1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
5
+ primarypath_verify-1.0.0rc1.dist-info/entry_points.txt,sha256=1_rQQ8YiTGEnR_DY1frBx6QSk13Y0G6buwiHMpghz_M,63
6
+ primarypath_verify-1.0.0rc1.dist-info/top_level.txt,sha256=_BwW5Qpg6pvsUbFLlwzYXtMVNu064rWQay-kld7rD0E,19
7
+ primarypath_verify-1.0.0rc1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ primarypath-verify = primarypath_verify:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ primarypath_verify
primarypath_verify.py ADDED
@@ -0,0 +1,517 @@
1
+ """Offline audit verifier: prove the record without trusting the server.
2
+
3
+ primarypath-verify bundle.json # verify a saved bundle
4
+ primarypath-verify bundle.json --pubring ring.json # also pin the signing key
5
+ primarypath-verify https://primarypath.example.com --token <admin-token> # fetch first
6
+ primarypath-verify https://primarypath.example.com --agent payments-bot --token ...
7
+
8
+ Bundle shapes (all verified offline, air-gapped for a file bundle):
9
+ - a chain bundle (`scope` "full" single-chain, "agent:<name>", or
10
+ "governance"): one hash chain from its own genesis to its head — F24
11
+ gives every agent its own chain, so an auditor verifies ONE agent
12
+ without processing the other 99
13
+ - a whole-log bundle (`chains`: [...]): every chain, each verified alone;
14
+ one signature over all the heads
15
+ - a run-scoped bundle (`scope` "run:..."): per-record integrity only
16
+
17
+ Checks, in order:
18
+ 1. every event's hash recomputes from (seq|ts_ms|type|payload|prev_hash)
19
+ 2. the chain links from its own genesis and reaches `head`
20
+ 3. the Ed25519 signature verifies with the bundle's public key — for a
21
+ per-agent bundle that is the key its EVIDENCE PROFILE demands
22
+ 4. (--pubring) the bundle's key_id is in your pinned public-key ring
23
+
24
+ The hashing is byte-identical to the server's (and to the original
25
+ walking skeleton).
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import base64
31
+ import hashlib
32
+ import json
33
+ import sys
34
+ import time
35
+
36
+ GENESIS = "genesis"
37
+
38
+
39
+ def canonical(payload: dict) -> str:
40
+ return json.dumps(payload, sort_keys=True, separators=(",", ":"),
41
+ ensure_ascii=False)
42
+
43
+
44
+ def chain_hash(seq: int, ts_ms: int, type: str, payload_json: str,
45
+ prev_hash: str) -> str:
46
+ line = f"{seq}|{ts_ms}|{type}|{payload_json}|{prev_hash}"
47
+ return hashlib.sha256(line.encode("utf-8")).hexdigest()
48
+
49
+
50
+ def _is_contiguous(bundle: dict) -> bool:
51
+ """Whether this bundle claims to be a complete chain (genesis -> head).
52
+ Run-scoped bundles are excerpts: per-record integrity only."""
53
+ scope = bundle.get("scope", "full")
54
+ return (scope in ("full", "governance")
55
+ or scope.startswith("agent:"))
56
+
57
+
58
+ def _verify_events(events: list[dict], head: str, full: bool,
59
+ label: str = "") -> tuple[bool, str]:
60
+ where = f"{label} " if label else ""
61
+ prev = GENESIS
62
+ for e in events:
63
+ payload = e["payload"]
64
+ payload_json = payload if isinstance(payload, str) else canonical(payload)
65
+ if full and e["prev_hash"] != prev:
66
+ return False, f"broken at {where}seq {e['seq']}: prev_hash mismatch"
67
+ recomputed = chain_hash(e["seq"], e["ts_ms"], e["type"], payload_json,
68
+ e["prev_hash"] if not full else prev)
69
+ if recomputed != e["hash"]:
70
+ return False, (f"broken at {where}seq {e['seq']}: recomputed hash "
71
+ f"differs, record was modified after writing")
72
+ prev = recomputed
73
+ last = events[-1]["hash"] if events else GENESIS
74
+ if head != last:
75
+ return False, (f"{where}head {head[:16]}… does not match last "
76
+ f"event hash")
77
+ return True, ""
78
+
79
+
80
+ def verify_chain(bundle: dict) -> tuple[bool, str]:
81
+ if "chains" in bundle:
82
+ total = 0
83
+ for c in bundle["chains"]:
84
+ ok, msg = _verify_events(c["events"], c.get("head", GENESIS),
85
+ full=True, label=f"chain {c['chain_id']}")
86
+ if not ok:
87
+ return False, msg
88
+ total += len(c["events"])
89
+ return True, (f"chain OK: {len(bundle['chains'])} chains, "
90
+ f"{total} events, each verified independently")
91
+ events = bundle["events"]
92
+ full = _is_contiguous(bundle)
93
+ head = bundle.get("head", GENESIS)
94
+ ok, msg = _verify_events(events, head, full)
95
+ if not ok:
96
+ return False, msg
97
+ if not full:
98
+ # a scoped bundle proves each record is what was written, but cannot
99
+ # prove no record was omitted — only the full chain proves completeness
100
+ return True, (f"records OK: {len(events)} events, head {head[:16]}… "
101
+ f"(run-scoped: per-record integrity, not completeness)")
102
+ what = bundle.get("scope", "full")
103
+ label = "" if what == "full" else f" [{what}]"
104
+ return True, f"chain OK: {len(events)} events, head {head[:16]}…{label}"
105
+
106
+
107
+ def _signed_record(bundle: dict) -> dict:
108
+ if "chains" in bundle:
109
+ return {"chains": [{
110
+ "chain_id": c["chain_id"],
111
+ "head": c["head"],
112
+ "count": len(c["events"]),
113
+ "first_seq": c["events"][0]["seq"] if c["events"] else None,
114
+ "last_seq": c["events"][-1]["seq"] if c["events"] else None,
115
+ } for c in sorted(bundle["chains"], key=lambda c: c["chain_id"])]}
116
+ events = bundle["events"]
117
+ record = {
118
+ "head": bundle["head"],
119
+ "count": len(events),
120
+ "first_seq": events[0]["seq"] if events else None,
121
+ "last_seq": events[-1]["seq"] if events else None,
122
+ }
123
+ if "events_hash" in bundle:
124
+ # non-contiguous (run) bundles: the signature commits to every event
125
+ # hash. RECOMPUTE the commitment from the events themselves; a lying
126
+ # events_hash field then fails signature verification, and stripping
127
+ # the field changes the record shape, which also fails.
128
+ record["events_hash"] = hashlib.sha256(canonical(
129
+ {"hashes": [e["hash"] for e in events]}).encode("utf-8")
130
+ ).hexdigest()
131
+ return record
132
+
133
+
134
+ SIGNATURE_FIELDS = ("signature", "public_key", "key_id")
135
+
136
+
137
+ def verify_signature(bundle: dict, pubring: dict | None = None,
138
+ allow_unsigned: bool = False) -> tuple[bool, str]:
139
+ present = [f for f in SIGNATURE_FIELDS if f in bundle]
140
+ if not present:
141
+ if pubring is not None and not allow_unsigned:
142
+ # a pinned ring asks "did MY org sign this": an attacker who
143
+ # cannot forge the signature can always delete it, so absence
144
+ # must fail exactly like a bad signature
145
+ return False, ("UNSIGNED: a pinned ring was given but the bundle "
146
+ "carries no signature, so nothing ties it to your "
147
+ "org's key. If this chain is unsigned on purpose "
148
+ "(evidence profile signing_backend: none), pass "
149
+ "--allow-unsigned for an integrity-only check")
150
+ return True, ("unsigned bundle (no signature present): integrity "
151
+ "only, NOT authenticity")
152
+ if len(present) != len(SIGNATURE_FIELDS):
153
+ missing = [f for f in SIGNATURE_FIELDS if f not in bundle]
154
+ return False, (f"SIGNATURE INVALID: bundle is missing "
155
+ f"{', '.join(missing)}")
156
+ try:
157
+ from cryptography.exceptions import InvalidSignature
158
+ from cryptography.hazmat.primitives.asymmetric import ed25519
159
+ except ImportError:
160
+ return False, "signature present but `cryptography` is not installed"
161
+
162
+ record = _signed_record(bundle)
163
+ raw_pub = base64.b64decode(bundle["public_key"])
164
+ kid = hashlib.sha256(raw_pub).hexdigest()[:16]
165
+ if kid != bundle.get("key_id"):
166
+ return False, "key_id does not match the embedded public key"
167
+ if pubring is not None and kid not in pubring:
168
+ return False, f"key {kid} is not in the pinned public-key ring"
169
+ key = ed25519.Ed25519PublicKey.from_public_bytes(raw_pub)
170
+ try:
171
+ key.verify(base64.b64decode(bundle["signature"]),
172
+ canonical(record).encode("utf-8"))
173
+ except InvalidSignature:
174
+ return False, "SIGNATURE INVALID: bundle does not match its signature"
175
+ caveat = ""
176
+ if not _is_contiguous(bundle) and "events_hash" not in bundle:
177
+ # a pre-events_hash run export: its signature does not commit to the
178
+ # event contents, only to head/count/seqs
179
+ caveat = (" WARNING: legacy run bundle without events_hash; the "
180
+ "signature does not bind the event contents. Re-export "
181
+ "from a current server for a content-bound signature.")
182
+ if pubring is None:
183
+ # self-consistency only: a malicious operator can rewrite history and
184
+ # re-sign with a fresh embedded key. Authenticity needs pinning.
185
+ return True, (f"signature OK: key {kid} — UNPINNED: this only proves "
186
+ f"the bundle matches its own embedded key, NOT that the "
187
+ f"key is your org's. Pin the ring once, out of band, "
188
+ f"and pass --pubring to establish authenticity"
189
+ f"{caveat}")
190
+ return True, f"signature OK: key {kid} (pinned in ring){caveat}"
191
+
192
+
193
+ GRANT_SIGNED_FIELDS = ("v", "approval_id", "tenant", "agent_id", "tool",
194
+ "action_digest", "issued_ms", "expires_ms", "nonce")
195
+
196
+
197
+ def verify_grants(bundle: dict, pubring: dict | None = None) -> tuple[bool, str]:
198
+ """Execution grants: every approval_granted that carries a grant must
199
+ carry a valid signature (against the pinned ring, else the bundle's
200
+ embedded key), and every grant_redeemed must name a grant that
201
+ exists — so the bundle proves the executor ran exactly the approved
202
+ action, and could run it only once."""
203
+ grants: dict[str, dict] = {}
204
+ redeemed: list[dict] = []
205
+ for e in _all_events(bundle):
206
+ p = e["payload"]
207
+ try:
208
+ p = json.loads(p) if isinstance(p, str) else p
209
+ except ValueError:
210
+ continue
211
+ if not isinstance(p, dict):
212
+ continue
213
+ if e["type"] == "approval_granted" and isinstance(p.get("grant"), dict):
214
+ grants[p["approval_id"]] = p["grant"]
215
+ elif e["type"] == "grant_redeemed":
216
+ redeemed.append(p)
217
+ if not grants and not redeemed:
218
+ return True, "no execution grants in this bundle"
219
+ keys = dict(pubring or {})
220
+ # the embedded key is a fallback for UNPINNED runs only: an empty ring
221
+ # is still a ring, and pins nothing
222
+ if pubring is None and bundle.get("public_key"):
223
+ keys[bundle.get("key_id", "")] = bundle["public_key"]
224
+ try:
225
+ from cryptography.exceptions import InvalidSignature
226
+ from cryptography.hazmat.primitives.asymmetric import ed25519
227
+ except ImportError:
228
+ return False, "grants present but `cryptography` is not installed"
229
+ for approval_id, g in grants.items():
230
+ pub = keys.get(g.get("key_id", ""))
231
+ if pub is None:
232
+ return False, (f"GRANT INVALID: {approval_id} signed by key "
233
+ f"{g.get('key_id')} which is not in the ring")
234
+ try:
235
+ record = canonical({k: g[k] for k in GRANT_SIGNED_FIELDS})
236
+ ed25519.Ed25519PublicKey.from_public_bytes(
237
+ base64.b64decode(pub)).verify(
238
+ base64.b64decode(g["signature"]), record.encode("utf-8"))
239
+ except (InvalidSignature, KeyError, ValueError):
240
+ return False, f"GRANT INVALID: {approval_id} does not match its signature"
241
+ seen: set[tuple[str, str]] = set()
242
+ for r in redeemed:
243
+ g = grants.get(r.get("approval_id"))
244
+ if g is None or g.get("nonce") != r.get("nonce"):
245
+ return False, (f"GRANT INVALID: {r.get('approval_id')} redeemed "
246
+ f"with a nonce no grant in this bundle issued")
247
+ if g.get("action_digest") != r.get("action_digest"):
248
+ return False, (f"GRANT INVALID: {r.get('approval_id')} redeemed "
249
+ f"for a different action digest than granted")
250
+ key = (r["approval_id"], r["nonce"])
251
+ if key in seen:
252
+ return False, f"GRANT INVALID: {r['approval_id']} redeemed twice"
253
+ seen.add(key)
254
+ return True, (f"{len(grants)} execution grant(s) verified, "
255
+ f"{len(redeemed)} redeemed")
256
+
257
+
258
+ def verify_bundle(bundle: dict, pubring: dict | None = None,
259
+ allow_unsigned: bool = False) -> tuple[bool, str]:
260
+ ok, msg = verify_chain(bundle)
261
+ if not ok:
262
+ return False, msg
263
+ ok2, msg2 = verify_signature(bundle, pubring, allow_unsigned)
264
+ if not ok2:
265
+ return False, f"{msg}; {msg2}"
266
+ ok3, msg3 = verify_grants(bundle, pubring)
267
+ return ok3, f"{msg}; {msg2}; {msg3}"
268
+
269
+
270
+ def _load(src: str, token: str | None, agent: str | None = None,
271
+ governance: bool = False) -> dict:
272
+ if src.startswith("http://") or src.startswith("https://"):
273
+ import urllib.parse
274
+ import urllib.request
275
+ url = f"{src.rstrip('/')}/api/audit/export"
276
+ if agent:
277
+ url += "?" + urllib.parse.urlencode({"agent": agent})
278
+ elif governance:
279
+ url += "?scope=governance"
280
+ req = urllib.request.Request(url)
281
+ if token:
282
+ req.add_header("Authorization", f"Bearer {token}")
283
+ with urllib.request.urlopen(req, timeout=10) as r:
284
+ return json.loads(r.read().decode("utf-8"))
285
+ with open(src, encoding="utf-8") as f:
286
+ return json.load(f)
287
+
288
+
289
+ # -- the evidence pack: the same proof, readable by a human -------------------
290
+
291
+ _REPORT_CSS = """
292
+ body { font: 14px/1.5 -apple-system, "Segoe UI", sans-serif; color: #1a1f2e;
293
+ max-width: 960px; margin: 32px auto; padding: 0 16px; }
294
+ h1 { font-size: 22px; margin-bottom: 2px; }
295
+ h2 { font-size: 15px; margin: 26px 0 8px; text-transform: uppercase;
296
+ letter-spacing: 0.04em; color: #5a6072; }
297
+ .sub { color: #5a6072; margin-top: 0; }
298
+ .verdict { padding: 10px 14px; border-radius: 6px; font-weight: 600;
299
+ margin: 14px 0; }
300
+ .ok { background: #e7f5ec; color: #116632; border: 1px solid #b5dfc4; }
301
+ .bad { background: #fdebea; color: #a11a25; border: 1px solid #f3c1be; }
302
+ table { border-collapse: collapse; width: 100%; font-size: 13px; }
303
+ th { text-align: left; color: #5a6072; font-weight: 600; }
304
+ th, td { padding: 6px 10px 6px 0; border-bottom: 1px solid #e4e6ec;
305
+ vertical-align: top; }
306
+ code, .mono { font-family: ui-monospace, Consolas, monospace; font-size: 12px;
307
+ overflow-wrap: anywhere; }
308
+ .badge { font-size: 11px; padding: 1px 8px; border-radius: 999px;
309
+ white-space: nowrap; }
310
+ .granted { background: #e7f5ec; color: #116632; }
311
+ .denied { background: #fdebea; color: #a11a25; }
312
+ .pending { background: #fff4dd; color: #8a5a00; }
313
+ footer { margin-top: 30px; color: #5a6072; font-size: 12px;
314
+ border-top: 1px solid #e4e6ec; padding-top: 10px; }
315
+ """
316
+
317
+
318
+ def _all_events(bundle: dict) -> list[dict]:
319
+ if "chains" in bundle:
320
+ out = []
321
+ for c in bundle["chains"]:
322
+ out.extend(c["events"])
323
+ return out
324
+ return bundle["events"]
325
+
326
+
327
+ def _fold_for_report(events: list[dict]) -> tuple[list[dict], list[dict]]:
328
+ """Approvals (with endorsement + decision) and control-plane changes,
329
+ folded from the bundle alone — the report never trusts anything the
330
+ verified events do not carry."""
331
+ approvals: dict[str, dict] = {}
332
+ controls: list[dict] = []
333
+ for e in sorted(events, key=lambda x: (x["ts_ms"], x["seq"])):
334
+ p = e["payload"]
335
+ try:
336
+ p = json.loads(p) if isinstance(p, str) else p
337
+ except ValueError:
338
+ continue # a tampered payload still gets its FAILED verdict
339
+ if not isinstance(p, dict):
340
+ continue
341
+ t = e["type"]
342
+ if t == "approval_requested" and p.get("approval_id"):
343
+ approvals[p["approval_id"]] = {
344
+ "approval_id": p["approval_id"], "tool": p.get("tool"),
345
+ "arguments": p.get("arguments") or {},
346
+ "reasoning": p.get("reasoning"),
347
+ "requested_ts_ms": e["ts_ms"], "status": "pending",
348
+ "endorsed_by": None, "reviewer": None, "reason": None,
349
+ "reviewer_role": None, "decided_ts_ms": None,
350
+ "executed_by": None, "executed_instance": None,
351
+ "executed_ts_ms": None,
352
+ }
353
+ elif t == "approval_endorsed" and p.get("approval_id") in approvals:
354
+ approvals[p["approval_id"]]["endorsed_by"] = p.get("reviewer")
355
+ elif t in ("approval_granted", "approval_denied") \
356
+ and p.get("approval_id") in approvals:
357
+ a = approvals[p["approval_id"]]
358
+ if a["status"] == "pending":
359
+ a["status"] = ("granted" if t == "approval_granted"
360
+ else "denied")
361
+ a["reviewer"] = p.get("reviewer")
362
+ a["reason"] = p.get("reason")
363
+ a["reviewer_role"] = p.get("reviewer_role")
364
+ a["decided_ts_ms"] = e["ts_ms"]
365
+ elif t == "grant_redeemed" and p.get("approval_id") in approvals:
366
+ a = approvals[p["approval_id"]]
367
+ if a["executed_ts_ms"] is None:
368
+ a["executed_by"] = p.get("executor")
369
+ a["executed_instance"] = p.get("executor_instance")
370
+ a["executed_ts_ms"] = e["ts_ms"]
371
+ elif t in ("policy_set", "budget_set", "gate_decision",
372
+ "admin_action", "agent_registered", "evidence_set",
373
+ "eval_recorded", "audit_exported"):
374
+ controls.append({"ts_ms": e["ts_ms"], "type": t,
375
+ "by": p.get("by"),
376
+ "reason": p.get("reason"),
377
+ "detail": {k: v for k, v in p.items()
378
+ if k not in ("by", "reason")}})
379
+ return list(approvals.values()), controls
380
+
381
+
382
+ def _ts(ms) -> str:
383
+ import datetime
384
+ if not ms:
385
+ return ""
386
+ return datetime.datetime.fromtimestamp(
387
+ ms / 1000, tz=datetime.UTC).strftime("%Y-%m-%d %H:%M:%SZ")
388
+
389
+
390
+ def write_report(bundle: dict, path: str, ok: bool, msg: str,
391
+ pinned: bool, source: str) -> None:
392
+ """A self-contained HTML evidence pack: the verification verdict plus
393
+ every decision (who, as what role, when, why) folded from the verified
394
+ events. For the auditor who will not read JSON; the machine-checkable
395
+ bundle stays the proof."""
396
+ from html import escape as h
397
+
398
+ approvals, controls = _fold_for_report(_all_events(bundle))
399
+ scope = bundle.get("scope", "full")
400
+ head = bundle.get("head") or "(multi-chain)"
401
+ key_id = bundle.get("key_id")
402
+
403
+ rows = []
404
+ for a in sorted(approvals, key=lambda x: x["requested_ts_ms"]):
405
+ args_txt = ", ".join(f"{k}={v}" for k, v in a["arguments"].items())
406
+ who = a["reviewer"] or ""
407
+ if a["endorsed_by"]:
408
+ who = f"{a['endorsed_by']} (endorsed) + {who}" if who else \
409
+ f"{a['endorsed_by']} (endorsed, awaiting second)"
410
+ executed = ""
411
+ if a["executed_ts_ms"]:
412
+ inst = (f" as <i>{h(a['executed_instance'])}</i>"
413
+ if a.get("executed_instance") else "")
414
+ executed = (f"<br><small>executed by {h(a['executed_by'] or '?')}"
415
+ f"{inst} {_ts(a['executed_ts_ms'])}</small>")
416
+ rows.append(
417
+ f"<tr><td class=mono>{h(a['approval_id'])}</td>"
418
+ f"<td><code>{h(a['tool'] or '')}</code><br>"
419
+ f"<span class=mono>{h(args_txt[:200])}</span></td>"
420
+ f"<td><span class='badge {a['status']}'>{a['status']}</span>"
421
+ f"{executed}</td>"
422
+ f"<td>{h(who)}"
423
+ f"{(' <i>(' + h(a['reviewer_role']) + ')</i>') if a['reviewer_role'] else ''}"
424
+ f"</td>"
425
+ f"<td>{h(a['reason'] or '')}</td>"
426
+ f"<td class=mono>{_ts(a['requested_ts_ms'])}<br>"
427
+ f"{_ts(a['decided_ts_ms'])}</td></tr>")
428
+
429
+ ctl_rows = [
430
+ f"<tr><td class=mono>{_ts(c['ts_ms'])}</td>"
431
+ f"<td><code>{h(c['type'])}</code></td>"
432
+ f"<td>{h(str(c['by'] or ''))}</td>"
433
+ f"<td>{h(str(c['reason'] or ''))}</td>"
434
+ f"<td class=mono>{h(json.dumps(c['detail'])[:220])}</td></tr>"
435
+ for c in controls]
436
+
437
+ verdict_cls = "ok" if ok else "bad"
438
+ verdict_word = "VERIFIED" if ok else "VERIFICATION FAILED"
439
+ if not bundle.get("signature"):
440
+ key_line = ("Unsigned bundle: the hash chain is the integrity "
441
+ "proof; signature authenticity does not apply.")
442
+ elif pinned:
443
+ key_line = (f"Signed with key <code>{key_id}</code>, verified "
444
+ f"against the pinned key ring.")
445
+ else:
446
+ key_line = (f"Signed with key <code>{key_id}</code>. UNPINNED: "
447
+ f"this proves self-consistency only; pass --pubring "
448
+ f"for authenticity.")
449
+
450
+ html_doc = f"""<!doctype html><html lang=en><head><meta charset=utf-8>
451
+ <title>Primary Path evidence pack · {h(scope)}</title>
452
+ <style>{_REPORT_CSS}</style></head><body>
453
+ <h1>Evidence pack</h1>
454
+ <p class=sub>Scope <code>{h(scope)}</code> · {len(_all_events(bundle))}
455
+ chained events · generated {_ts(time.time() * 1000)} from
456
+ <code>{h(source)}</code></p>
457
+ <div class="verdict {verdict_cls}">{verdict_word} — {h(msg)}</div>
458
+ <p class=sub>{key_line}
459
+ Chain head <code>{h(str(head))}</code>. Every statement below is folded
460
+ from the verified events themselves; re-verify this pack's source bundle
461
+ anytime with <code>primarypath-verify bundle.json --pubring
462
+ pubring.json</code>.</p>
463
+ <h2>Decisions ({len(approvals)})</h2>
464
+ <table><tr><th>approval</th><th>action</th><th>outcome</th>
465
+ <th>decided by</th><th>reason</th><th>requested / decided (UTC)</th></tr>
466
+ {''.join(rows) or '<tr><td colspan=6>none in this bundle</td></tr>'}</table>
467
+ <h2>Control-plane changes ({len(controls)})</h2>
468
+ <table><tr><th>at (UTC)</th><th>change</th><th>by</th><th>reason</th>
469
+ <th>detail</th></tr>
470
+ {''.join(ctl_rows) or '<tr><td colspan=5>none in this bundle</td></tr>'}</table>
471
+ <footer>Primary Path evidence pack. The proof is the hash chain and the
472
+ Ed25519 signature, not this rendering: any edit to any event names itself
473
+ under re-verification. Tamper-evidence, not tamper-prevention.</footer>
474
+ </body></html>"""
475
+ with open(path, "w", encoding="utf-8") as f:
476
+ f.write(html_doc)
477
+
478
+
479
+ def main() -> int:
480
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
481
+ ap.add_argument("source", help="bundle.json path or service base URL")
482
+ ap.add_argument("--pubring", help="pinned public-key ring JSON (key_id -> b64)")
483
+ ap.add_argument("--allow-unsigned", action="store_true",
484
+ help="with --pubring: accept a bundle that carries no "
485
+ "signature as an integrity-only check (for chains "
486
+ "profiled signing_backend: none). Without this, an "
487
+ "unsigned bundle FAILS pinned verification")
488
+ ap.add_argument("--token", help="admin token when fetching from a URL")
489
+ ap.add_argument("--agent", help="fetch ONE agent's chain (its own head, "
490
+ "its own key)")
491
+ ap.add_argument("--governance", action="store_true",
492
+ help="fetch the control-plane chain")
493
+ ap.add_argument("--report", metavar="PACK.html",
494
+ help="also write a self-contained HTML evidence pack "
495
+ "(verdict + every decision, human-readable)")
496
+ args = ap.parse_args()
497
+
498
+ bundle = _load(args.source, args.token, agent=args.agent,
499
+ governance=args.governance)
500
+ pubring = None
501
+ if args.pubring:
502
+ with open(args.pubring, encoding="utf-8") as f:
503
+ pubring = json.load(f)
504
+
505
+ ok, msg = verify_bundle(bundle, pubring,
506
+ allow_unsigned=args.allow_unsigned)
507
+ print(("OK " if ok else "FAIL") + " " + msg)
508
+ if args.report:
509
+ # a failed verdict is documented too: that IS the evidence
510
+ write_report(bundle, args.report, ok, msg,
511
+ pinned=pubring is not None, source=args.source)
512
+ print(f"evidence pack written to {args.report}")
513
+ return 0 if ok else 1
514
+
515
+
516
+ if __name__ == "__main__":
517
+ sys.exit(main())