regent-receipt-verify 0.1.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.
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
5
+ .venv/
6
+ node_modules/
7
+ *.tgz
8
+ .DS_Store
@@ -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,3 @@
1
+ Copyright 2026 Regent Protocol
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); see LICENSE.
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.5
2
+ Name: regent-receipt-verify
3
+ Version: 0.1.0
4
+ Summary: Verify Regent Control receipts and allow tokens offline against a saved JWKS; open mandate and policy reveals
5
+ Project-URL: Homepage, https://github.com/regent-protocol/regent-receipt-verify
6
+ Project-URL: Source, https://github.com/regent-protocol/regent-receipt-verify
7
+ Project-URL: Issues, https://github.com/regent-protocol/regent-receipt-verify/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: cryptography>=41.0
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # regent-receipt-verify
18
+
19
+ Verify a Regent Control **receipt** or **allow token** without Regent: only the token and a JWKS
20
+ you saved while the issuer was reachable. Nothing calls the network. One dependency
21
+ (`cryptography`) for RS256.
22
+
23
+ ```
24
+ pip install regent-receipt-verify
25
+ curl -s https://control-api.regentprotocol.org/v1/control/.well-known/jwks.json > jwks-2026-09.json # save it now, keep it with the receipts
26
+ regent-verify @receipt.txt --jwks jwks-2026-09.json --request request.json --mandate mandate-v2-reveal.json --policy policy-v3-reveal.json
27
+ ```
28
+
29
+ ```python
30
+ from regent_receipt_verify import verify
31
+ res = verify(token, jwks, request={"tool": "stripe", "action": "charge.create", "resource": None, "args": {...}},
32
+ mandate_reveal=reveal_from_owner, policy_reveal=policy_reveal_from_org)
33
+ res.valid, res.kind, res.claims, res.args_hash_match, res.mandate_match, res.policy_match
34
+ ```
35
+
36
+ What it proves:
37
+
38
+ | check | meaning |
39
+ |---|---|
40
+ | signature (RS256, kid from the JWKS) | Regent's issuer signed exactly these claims |
41
+ | `kind` receipt / allow / budget | a receipt (`typ receipt+jwt`, `aud regent-receipt`) can never pass as an access token |
42
+ | `expired` | receipts carry a 10-year evidence period; an allow token lives about a minute, so for evidence its expiry is a note, not a failure |
43
+ | `args_hash_match` | the token authorised this exact request (tool, action, resource, args) and nothing else |
44
+ | `mandate_match` | the owner's revealed mandate version (snapshot + salt, `terms-v2`) opens the receipt's `mandate_hash` |
45
+ | `policy_match` | the organisation's revealed policy version (text + profile + salt, `policy-v1`) opens `policy_hash`; starter-pack decisions need only the public text |
46
+
47
+ Key rotation: pass `--jwks` several times (every JWKS you saved). Exit code 0 when the signature
48
+ verifies and every supplied check matches.
49
+
50
+ Test vectors are minted by the real issuer (`packages/receipt-verify-vectors`), and the same
51
+ file drives the Node package `@regent-protocol/receipt-verify`.
@@ -0,0 +1,35 @@
1
+ # regent-receipt-verify
2
+
3
+ Verify a Regent Control **receipt** or **allow token** without Regent: only the token and a JWKS
4
+ you saved while the issuer was reachable. Nothing calls the network. One dependency
5
+ (`cryptography`) for RS256.
6
+
7
+ ```
8
+ pip install regent-receipt-verify
9
+ curl -s https://control-api.regentprotocol.org/v1/control/.well-known/jwks.json > jwks-2026-09.json # save it now, keep it with the receipts
10
+ regent-verify @receipt.txt --jwks jwks-2026-09.json --request request.json --mandate mandate-v2-reveal.json --policy policy-v3-reveal.json
11
+ ```
12
+
13
+ ```python
14
+ from regent_receipt_verify import verify
15
+ res = verify(token, jwks, request={"tool": "stripe", "action": "charge.create", "resource": None, "args": {...}},
16
+ mandate_reveal=reveal_from_owner, policy_reveal=policy_reveal_from_org)
17
+ res.valid, res.kind, res.claims, res.args_hash_match, res.mandate_match, res.policy_match
18
+ ```
19
+
20
+ What it proves:
21
+
22
+ | check | meaning |
23
+ |---|---|
24
+ | signature (RS256, kid from the JWKS) | Regent's issuer signed exactly these claims |
25
+ | `kind` receipt / allow / budget | a receipt (`typ receipt+jwt`, `aud regent-receipt`) can never pass as an access token |
26
+ | `expired` | receipts carry a 10-year evidence period; an allow token lives about a minute, so for evidence its expiry is a note, not a failure |
27
+ | `args_hash_match` | the token authorised this exact request (tool, action, resource, args) and nothing else |
28
+ | `mandate_match` | the owner's revealed mandate version (snapshot + salt, `terms-v2`) opens the receipt's `mandate_hash` |
29
+ | `policy_match` | the organisation's revealed policy version (text + profile + salt, `policy-v1`) opens `policy_hash`; starter-pack decisions need only the public text |
30
+
31
+ Key rotation: pass `--jwks` several times (every JWKS you saved). Exit code 0 when the signature
32
+ verifies and every supplied check matches.
33
+
34
+ Test vectors are minted by the real issuer (`packages/receipt-verify-vectors`), and the same
35
+ file drives the Node package `@regent-protocol/receipt-verify`.
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "regent-receipt-verify"
7
+ version = "0.1.0"
8
+ description = "Verify Regent Control receipts and allow tokens offline against a saved JWKS; open mandate and policy reveals"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ dependencies = ["cryptography>=41.0"]
13
+
14
+ [project.urls]
15
+ Homepage = "https://github.com/regent-protocol/regent-receipt-verify"
16
+ Source = "https://github.com/regent-protocol/regent-receipt-verify"
17
+ Issues = "https://github.com/regent-protocol/regent-receipt-verify/issues"
18
+
19
+ [project.optional-dependencies]
20
+ dev = ["pytest>=8.0.0"]
21
+
22
+ [project.scripts]
23
+ regent-verify = "regent_receipt_verify.cli:main"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/regent_receipt_verify"]
@@ -0,0 +1,254 @@
1
+ """regent-receipt-verify — check a Regent Control receipt or allow token without Regent.
2
+
3
+ Everything needed is in the token and a JWKS you saved while the issuer was reachable
4
+ (GET https://control-api.regentprotocol.org/v1/control/.well-known/jwks.json). Nothing here
5
+ calls the network. Signature: RS256 via `cryptography`. Commitments: the same canonical
6
+ strings as the gate (terms-v2 for mandates, policy-v1 for policies) and the same request
7
+ hash (sha256 over canonical JSON of {tool, action, resource, args}).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import hashlib
14
+ import hmac
15
+ import json
16
+ import time
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+
20
+ from cryptography.exceptions import InvalidSignature
21
+ from cryptography.hazmat.primitives import hashes
22
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
23
+
24
+ __version__ = "0.1.0"
25
+ __all__ = [
26
+ "VerificationResult", "verify_token", "verify", "canonical_args_hash", "check_request_binding",
27
+ "mandate_commitment", "check_mandate_reveal", "policy_commitment", "check_policy_reveal",
28
+ ]
29
+
30
+
31
+ # ── JWS ───────────────────────────────────────────────────────────────────────
32
+
33
+ def _b64url_decode(s: str) -> bytes:
34
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
35
+
36
+
37
+ def _b64url_uint(s: str) -> int:
38
+ return int.from_bytes(_b64url_decode(s), "big")
39
+
40
+
41
+ def _keys(jwks: Any) -> list[dict[str, Any]]:
42
+ """Accept a JWKS dict, a list of JWKS dicts (key rotation), or a list of JWKs."""
43
+ if isinstance(jwks, dict) and "keys" in jwks:
44
+ return list(jwks["keys"])
45
+ if isinstance(jwks, dict):
46
+ return [jwks]
47
+ out: list[dict[str, Any]] = []
48
+ for item in jwks or []:
49
+ out.extend(_keys(item))
50
+ return out
51
+
52
+
53
+ @dataclass
54
+ class VerificationResult:
55
+ signature_valid: bool
56
+ kind: str # receipt | allow | budget | unknown
57
+ header: dict[str, Any] = field(default_factory=dict)
58
+ claims: dict[str, Any] = field(default_factory=dict)
59
+ kid: str | None = None
60
+ expired: bool | None = None
61
+ errors: list[str] = field(default_factory=list)
62
+ warnings: list[str] = field(default_factory=list)
63
+ # populated by verify() when the optional inputs are given
64
+ args_hash_match: bool | None = None
65
+ mandate_match: bool | None = None
66
+ policy_match: bool | None = None
67
+
68
+ @property
69
+ def valid(self) -> bool:
70
+ """Authentic and, for a receipt, still inside its evidence period."""
71
+ return self.signature_valid and not self.errors
72
+
73
+ def to_dict(self) -> dict[str, Any]:
74
+ return {
75
+ "valid": self.valid, "signature_valid": self.signature_valid, "kind": self.kind, "kid": self.kid,
76
+ "expired": self.expired, "args_hash_match": self.args_hash_match, "mandate_match": self.mandate_match,
77
+ "policy_match": self.policy_match, "errors": self.errors, "warnings": self.warnings,
78
+ "header": self.header, "claims": self.claims,
79
+ }
80
+
81
+
82
+ def _kind(header: dict[str, Any], claims: dict[str, Any]) -> str:
83
+ typ = str(header.get("typ") or "")
84
+ if typ == "receipt+jwt" or claims.get("aud") == "regent-receipt":
85
+ return "receipt"
86
+ if typ == "aa-auth+jwt" or "budget" in claims:
87
+ return "budget"
88
+ if "scope" in claims and "decision_id" in claims:
89
+ return "allow"
90
+ return "unknown"
91
+
92
+
93
+ def verify_token(token: str, jwks: Any, *, now: float | None = None, issuer: str | None = "regent-control") -> VerificationResult:
94
+ """Signature + structure. Returns a result even for invalid tokens (never raises on bad input)."""
95
+ now = time.time() if now is None else now
96
+ parts = token.strip().split(".")
97
+ if len(parts) != 3:
98
+ return VerificationResult(False, "unknown", errors=["not a compact JWS (expected header.payload.signature)"])
99
+ try:
100
+ header = json.loads(_b64url_decode(parts[0]))
101
+ claims = json.loads(_b64url_decode(parts[1]))
102
+ signature = _b64url_decode(parts[2])
103
+ except Exception as exc: # noqa: BLE001
104
+ return VerificationResult(False, "unknown", errors=[f"cannot decode token: {exc}"])
105
+ res = VerificationResult(False, _kind(header, claims), header=header, claims=claims, kid=header.get("kid"))
106
+ if header.get("alg") != "RS256":
107
+ res.errors.append(f"unsupported alg {header.get('alg')!r} (Regent signs RS256)")
108
+ return res
109
+ candidates = [k for k in _keys(jwks) if k.get("kty") == "RSA" and (res.kid is None or k.get("kid") == res.kid)]
110
+ if not candidates:
111
+ res.errors.append(f"no RSA key with kid {res.kid!r} in the JWKS you supplied")
112
+ return res
113
+ signed = f"{parts[0]}.{parts[1]}".encode("ascii")
114
+ for k in candidates:
115
+ try:
116
+ pub = rsa.RSAPublicNumbers(_b64url_uint(k["e"]), _b64url_uint(k["n"])).public_key()
117
+ pub.verify(signature, signed, padding.PKCS1v15(), hashes.SHA256())
118
+ res.signature_valid = True
119
+ res.kid = k.get("kid")
120
+ break
121
+ except (InvalidSignature, ValueError, KeyError):
122
+ continue
123
+ if not res.signature_valid:
124
+ res.errors.append("signature does not verify against the supplied key(s)")
125
+ return res
126
+ # structure
127
+ if issuer and claims.get("iss") != issuer:
128
+ res.errors.append(f"issuer is {claims.get('iss')!r}, expected {issuer!r}")
129
+ if res.kind == "receipt" and claims.get("aud") != "regent-receipt":
130
+ res.errors.append("receipt audience must be 'regent-receipt'")
131
+ exp = claims.get("exp")
132
+ if isinstance(exp, (int, float)):
133
+ res.expired = exp < now
134
+ if res.expired:
135
+ if res.kind == "receipt":
136
+ res.errors.append("receipt is past its evidence period (exp)")
137
+ else:
138
+ res.warnings.append("token expired (allow tokens live about a minute; signature and binding still verify)")
139
+ iat = claims.get("iat")
140
+ if isinstance(iat, (int, float)) and iat > now + 300:
141
+ res.errors.append("issued in the future (iat)")
142
+ if res.kind == "allow" and "scope" in claims and claims.get("scope") != f"{claims.get('aud')}:{claims.get('scope','').split(':', 1)[-1]}":
143
+ res.warnings.append("scope does not start with the audience tool")
144
+ return res
145
+
146
+
147
+ # ── request binding (args_hash) ───────────────────────────────────────────────
148
+
149
+ def canonical_args_hash(tool: str, action: str, resource: str | None, args: dict[str, Any] | None) -> str:
150
+ """Byte-identical to the gate: sha256 over canonical JSON of {tool, action, resource, args}."""
151
+ canonical = json.dumps({"tool": tool, "action": action, "resource": resource, "args": args or {}},
152
+ sort_keys=True, separators=(",", ":"), ensure_ascii=False)
153
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
154
+
155
+
156
+ def check_request_binding(claims: dict[str, Any], *, tool: str, action: str, resource: str | None = None,
157
+ args: dict[str, Any] | None = None) -> bool:
158
+ expected = claims.get("args_hash")
159
+ return bool(expected) and hmac.compare_digest(canonical_args_hash(tool, action, resource, args), str(expected))
160
+
161
+
162
+ # ── mandate terms (terms-v2) ──────────────────────────────────────────────────
163
+
164
+ MANDATE_FIELDS = ("mandate_id", "version", "agent_id", "owner_id", "currency", "settlement_chain", "status",
165
+ "per_tx_limit", "daily_limit", "monthly_limit", "per_entity_limit", "entity_key", "relational_cap",
166
+ "expires_at", "agent_may_read_limits")
167
+
168
+
169
+ def _cv(value: Any) -> str:
170
+ if value is None:
171
+ return "none"
172
+ if value is True:
173
+ return "true"
174
+ if value is False:
175
+ return "false"
176
+ return str(value)
177
+
178
+
179
+ def mandate_canonical_string(snapshot: dict[str, Any], salt: str) -> str:
180
+ return "|".join(["terms-v2", *(f"{n}={_cv(snapshot.get(n))}" for n in MANDATE_FIELDS), f"salt={salt}"])
181
+
182
+
183
+ def mandate_commitment(snapshot: dict[str, Any], salt: str) -> str:
184
+ return hashlib.sha256(mandate_canonical_string(snapshot, salt).encode("utf-8")).hexdigest()
185
+
186
+
187
+ def check_mandate_reveal(claims: dict[str, Any], reveal: dict[str, Any]) -> bool:
188
+ """`reveal` = the owner's version object ({snapshot, salt, ...}) or {snapshot, salt}."""
189
+ expected = str(claims.get("mandate_hash") or "")
190
+ snap = reveal.get("snapshot") if isinstance(reveal.get("snapshot"), dict) else reveal
191
+ salt = str(reveal.get("salt") or "")
192
+ if not expected or not salt:
193
+ return False
194
+ if "version" in snap and claims.get("mandate_version") is not None and int(snap["version"]) != int(claims["mandate_version"]):
195
+ return False
196
+ return hmac.compare_digest(mandate_commitment(snap, salt.lower()), expected.lower())
197
+
198
+
199
+ # ── policy (policy-v1) ────────────────────────────────────────────────────────
200
+
201
+ def _text_digest(text: str) -> str:
202
+ return hashlib.sha256((text or "").encode("utf-8")).hexdigest()
203
+
204
+
205
+ def policy_canonical_string(org_id: str, version: int, cedar_text: str, profile: dict[str, Any] | None, salt: str) -> str:
206
+ prof = None if profile is None else hashlib.sha256(
207
+ json.dumps(profile, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
208
+ return "|".join(["policy-v1", f"org_id={org_id}", f"version={int(version)}", f"text_sha256={_text_digest(cedar_text)}",
209
+ f"profile_sha256={prof if prof is not None else 'none'}", f"salt={salt}"])
210
+
211
+
212
+ def policy_commitment(org_id: str, version: int, cedar_text: str, profile: dict[str, Any] | None, salt: str) -> str:
213
+ return hashlib.sha256(policy_canonical_string(org_id, version, cedar_text, profile, salt).encode("utf-8")).hexdigest()
214
+
215
+
216
+ def check_policy_reveal(claims: dict[str, Any], reveal: dict[str, Any] | str) -> bool:
217
+ """`reveal` = the org's version object ({org_id, version, cedar_text, profile, salt}); for a
218
+ starter-pack or legacy decision the Cedar text alone (str or {cedar_text})."""
219
+ expected = str(claims.get("policy_hash") or "")
220
+ if not expected:
221
+ return False
222
+ if isinstance(reveal, str):
223
+ reveal = {"cedar_text": reveal}
224
+ text = reveal.get("cedar_text") if isinstance(reveal.get("cedar_text"), str) else reveal.get("cedar")
225
+ if not isinstance(text, str):
226
+ return False
227
+ if claims.get("policy_source") in ("starter", "legacy"):
228
+ return hmac.compare_digest(_text_digest(text), expected.lower())
229
+ try:
230
+ version = reveal["version"] if reveal.get("version") is not None else claims.get("policy_version")
231
+ got = policy_commitment(str(reveal.get("org_id") or ""), int(version), text,
232
+ reveal.get("profile") if isinstance(reveal.get("profile"), dict) else None,
233
+ str(reveal.get("salt") or "").lower())
234
+ except (TypeError, ValueError):
235
+ return False
236
+ return hmac.compare_digest(got, expected.lower())
237
+
238
+
239
+ # ── one call for everything ───────────────────────────────────────────────────
240
+
241
+ def verify(token: str, jwks: Any, *, request: dict[str, Any] | None = None, mandate_reveal: dict[str, Any] | None = None,
242
+ policy_reveal: dict[str, Any] | str | None = None, now: float | None = None,
243
+ issuer: str | None = "regent-control") -> VerificationResult:
244
+ res = verify_token(token, jwks, now=now, issuer=issuer)
245
+ if not res.signature_valid:
246
+ return res
247
+ if request is not None:
248
+ res.args_hash_match = check_request_binding(res.claims, tool=request.get("tool", ""), action=request.get("action", ""),
249
+ resource=request.get("resource"), args=request.get("args"))
250
+ if mandate_reveal is not None:
251
+ res.mandate_match = check_mandate_reveal(res.claims, mandate_reveal)
252
+ if policy_reveal is not None:
253
+ res.policy_match = check_policy_reveal(res.claims, policy_reveal)
254
+ return res
@@ -0,0 +1,69 @@
1
+ """regent-verify — command line for regent_receipt_verify.
2
+
3
+ regent-verify TOKEN --jwks jwks.json [--jwks older.json] [--request req.json]
4
+ [--mandate reveal.json] [--policy reveal.json|text.cedar] [--json] [--now EPOCH]
5
+
6
+ Exit 0 when the signature verifies and every supplied check matches; 1 otherwise."""
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+
13
+ from . import __version__, verify
14
+
15
+
16
+ def _load(path: str):
17
+ with open(path, encoding="utf-8") as f:
18
+ text = f.read()
19
+ try:
20
+ return json.loads(text)
21
+ except ValueError:
22
+ return text # a Cedar text file for --policy
23
+
24
+
25
+ def main(argv: list[str] | None = None) -> int:
26
+ ap = argparse.ArgumentParser(prog="regent-verify", description="Verify a Regent receipt or allow token offline.")
27
+ ap.add_argument("token", help="the JWT, or @file to read it from a file")
28
+ ap.add_argument("--jwks", action="append", required=True, help="saved JWKS file (repeat for older keys)")
29
+ ap.add_argument("--request", help='JSON {"tool","action","resource","args"} to check args_hash')
30
+ ap.add_argument("--mandate", help="mandate version reveal JSON from the owner")
31
+ ap.add_argument("--policy", help="policy version reveal JSON, or the Cedar text for starter-pack decisions")
32
+ ap.add_argument("--issuer", default="regent-control")
33
+ ap.add_argument("--now", type=float, help="epoch seconds to evaluate exp against (default: now)")
34
+ ap.add_argument("--json", action="store_true", help="machine-readable output")
35
+ ap.add_argument("--version", action="version", version=__version__)
36
+ a = ap.parse_args(argv)
37
+
38
+ token = open(a.token[1:], encoding="utf-8").read().strip() if a.token.startswith("@") else a.token
39
+ res = verify(token, [_load(p) for p in a.jwks],
40
+ request=_load(a.request) if a.request else None,
41
+ mandate_reveal=_load(a.mandate) if a.mandate else None,
42
+ policy_reveal=_load(a.policy) if a.policy else None,
43
+ now=a.now, issuer=a.issuer or None)
44
+ checks = [res.args_hash_match, res.mandate_match, res.policy_match]
45
+ ok = res.valid and all(c is not False for c in checks)
46
+ if a.json:
47
+ print(json.dumps(res.to_dict(), indent=2, ensure_ascii=False))
48
+ return 0 if ok else 1
49
+ c = res.claims
50
+ print(("VALID" if res.valid else "INVALID") + f" — {res.kind} signed by {c.get('iss', '?')} (kid {res.kid})")
51
+ for e in res.errors:
52
+ print(f" error: {e}")
53
+ for w in res.warnings:
54
+ print(f" note: {w}")
55
+ if res.signature_valid:
56
+ for k in ("decision_id", "status", "sub", "amount", "currency", "payee", "mandate_id", "mandate_version",
57
+ "mandate_hash", "policy_source", "policy_version", "policy_hash", "risk_model", "tool", "action",
58
+ "scope", "args_hash", "settlement_mismatch", "jti", "iat", "exp"):
59
+ if k in c:
60
+ print(f" {k}: {c[k]}")
61
+ for label, val in (("request binding (args_hash)", res.args_hash_match), ("mandate reveal", res.mandate_match),
62
+ ("policy reveal", res.policy_match)):
63
+ if val is not None:
64
+ print(f" {label}: {'MATCH' if val else 'NO MATCH'}")
65
+ return 0 if ok else 1
66
+
67
+
68
+ if __name__ == "__main__": # pragma: no cover
69
+ sys.exit(main())
@@ -0,0 +1,95 @@
1
+ """Both verifier packages run the same vectors, minted by the real issuer (make_vectors.py)."""
2
+ import json
3
+ import os
4
+
5
+ import pytest
6
+
7
+ from regent_receipt_verify import (
8
+ canonical_args_hash, check_mandate_reveal, check_policy_reveal, check_request_binding, verify, verify_token,
9
+ )
10
+ from regent_receipt_verify.cli import main
11
+
12
+ V = json.load(open(os.path.join(os.path.dirname(__file__), "..", "..", "receipt-verify-vectors", "vectors.json")))
13
+ NOW = V["now"]
14
+
15
+
16
+ def test_args_hash_matches_the_gate():
17
+ r = V["request"]
18
+ assert canonical_args_hash(r["tool"], r["action"], r["resource"], r["args"]) == V["args_hash"]
19
+
20
+
21
+ @pytest.mark.parametrize("name", ["receipt", "allow"])
22
+ def test_full_verification(name):
23
+ case = V["cases"][name]
24
+ res = verify(case["token"], V["jwks"], request=V["request"], mandate_reveal=V["mandate_reveal"],
25
+ policy_reveal=V["policy_reveal"], now=NOW)
26
+ e = case["expect"]
27
+ assert res.kind == e["kind"] and res.signature_valid is True and res.valid is True
28
+ assert res.expired is False and res.args_hash_match is True
29
+ assert res.mandate_match is True and res.policy_match is True
30
+ assert res.kid == V["jwks"]["keys"][0]["kid"]
31
+ # every tampering of a reveal or the request must fail to open the commitment
32
+ assert verify(case["token"], V["jwks"], request=V["wrong_request"], now=NOW).args_hash_match is False
33
+ bad_m = {**V["mandate_reveal"], "salt": "00" * 32}
34
+ assert check_mandate_reveal(res.claims, bad_m) is False
35
+ bad_snap = {**V["mandate_reveal"], "snapshot": {**V["mandate_reveal"]["snapshot"], "daily_limit": "9999.000000"}}
36
+ assert check_mandate_reveal(res.claims, bad_snap) is False
37
+ assert check_policy_reveal(res.claims, {**V["policy_reveal"], "cedar_text": V["policy_reveal"]["cedar_text"] + " "}) is False
38
+ assert check_policy_reveal(res.claims, {**V["policy_reveal"], "profile": None}) is False
39
+
40
+
41
+ def test_allow_token_expiry_is_a_note_not_an_error():
42
+ case = V["cases"]["allow_expired"]
43
+ res = verify_token(case["token"], V["jwks"], now=case["now"])
44
+ assert res.signature_valid and res.expired is True and res.valid is True and res.warnings
45
+
46
+
47
+ def test_receipt_past_evidence_period_is_invalid():
48
+ res = verify_token(V["cases"]["receipt"]["token"], V["jwks"], now=NOW + 86400 * 4000)
49
+ assert res.signature_valid and res.expired is True and res.valid is False
50
+
51
+
52
+ def test_starter_policy_opens_with_text_only():
53
+ res = verify(V["cases"]["starter_receipt"]["token"], V["jwks"], policy_reveal=V["starter_text"], now=NOW)
54
+ assert res.policy_match is True
55
+ assert verify(V["cases"]["starter_receipt"]["token"], V["jwks"], policy_reveal=V["starter_text"] + "\n", now=NOW).policy_match is False
56
+
57
+
58
+ def test_budget_token_is_classified_and_verifies():
59
+ res = verify_token(V["cases"]["budget"]["token"], V["jwks"], now=NOW)
60
+ assert res.kind == "budget" and res.signature_valid
61
+
62
+
63
+ def test_wrong_key_and_tampering_fail():
64
+ assert verify_token(V["cases"]["wrong_key"]["token"], V["jwks"], now=NOW).signature_valid is False
65
+ assert verify_token(V["cases"]["tampered"]["token"], V["jwks"], now=NOW).signature_valid is False
66
+ # the wrong key's own JWKS verifies it — key rotation: pass several JWKS
67
+ assert verify_token(V["cases"]["wrong_key"]["token"], [V["jwks"], V["other_jwks"]], now=NOW).signature_valid is True
68
+
69
+
70
+ def test_garbage_never_raises():
71
+ for bad in ("", "abc", "a.b", "a.b.c", "x" * 10):
72
+ res = verify_token(bad, V["jwks"], now=NOW)
73
+ assert res.signature_valid is False and res.errors
74
+
75
+
76
+ def test_request_binding_helper():
77
+ claims = verify_token(V["cases"]["allow"]["token"], V["jwks"], now=NOW).claims
78
+ r = V["request"]
79
+ assert check_request_binding(claims, tool=r["tool"], action=r["action"], resource=r["resource"], args=r["args"])
80
+ assert not check_request_binding(claims, tool=r["tool"], action="charge.refund", resource=r["resource"], args=r["args"])
81
+
82
+
83
+ def test_cli(tmp_path, capsys):
84
+ jw = tmp_path / "jwks.json"; jw.write_text(json.dumps(V["jwks"]))
85
+ req = tmp_path / "req.json"; req.write_text(json.dumps(V["request"]))
86
+ man = tmp_path / "m.json"; man.write_text(json.dumps(V["mandate_reveal"]))
87
+ pol = tmp_path / "p.json"; pol.write_text(json.dumps(V["policy_reveal"]))
88
+ rc = main([V["cases"]["receipt"]["token"], "--jwks", str(jw), "--request", str(req), "--mandate", str(man),
89
+ "--policy", str(pol), "--now", str(NOW)])
90
+ out = capsys.readouterr().out
91
+ assert rc == 0 and out.startswith("VALID") and "mandate reveal: MATCH" in out and "policy reveal: MATCH" in out
92
+ rc = main([V["cases"]["tampered"]["token"], "--jwks", str(jw), "--json", "--now", str(NOW)])
93
+ assert rc == 1 and json.loads(capsys.readouterr().out)["signature_valid"] is False
94
+ bad = tmp_path / "bad.json"; bad.write_text(json.dumps(V["wrong_request"]))
95
+ assert main([V["cases"]["allow"]["token"], "--jwks", str(jw), "--request", str(bad), "--now", str(NOW)]) == 1