pregen 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.
pregen-0.1.0/LICENSE ADDED
@@ -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.
pregen-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: pregen
3
+ Version: 0.1.0
4
+ Summary: Verify PRE-GEN signatures against the signed registry directory, with the PRE-GEN steward key built in
5
+ Author: Valerii Egorov (Pastheroza)
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://www.pregen.org
8
+ Project-URL: Source, https://github.com/Pastheroza/PRE-GEN-site/tree/main/packages/verify-py
9
+ Keywords: pre-gen,pregen,pre-generation authorization,ed25519,verification
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: cryptography>=42
14
+ Dynamic: license-file
15
+
16
+ # pregen
17
+
18
+ Checks that a PRE-GEN decision or license was really signed by the registry
19
+ that owns its PG code, using the signed registry directory at
20
+ [pregen.org](https://www.pregen.org/registries.json). The PRE-GEN steward key
21
+ is built in. Same API as the npm package `@pregen/verify`.
22
+
23
+ ```python
24
+ import pregen
25
+
26
+ directory = pregen.load_directory(min_sequence=saved_sequence)
27
+ save_sequence(directory.sequence) # refuse older copies next time
28
+
29
+ # decision: the JSON a registry returned from /v1/verify
30
+ # code: the PG code you asked about (the license id, or the subject code)
31
+ if not pregen.verify_decision(decision, code, directory):
32
+ raise RuntimeError("not genuine")
33
+ ```
34
+
35
+ The chain it checks:
36
+
37
+ 1. the directory is signed by the PRE-GEN steward key
38
+ (`pg-ed25519:dcdd244659e6d0e2426f2b504cb11590`) and is not older than one
39
+ you have seen;
40
+ 2. the code's namespace (bare `PG-…` or a four-letter prefix) belongs to one
41
+ listed registry;
42
+ 3. the decision's `operator_key_id` is one of that registry's listed keys, and
43
+ the key its key set serves hashes to that fingerprint;
44
+ 4. the Ed25519 signature over the canonical JSON verifies.
45
+
46
+ What it does **not** check, and you still must (`PRE-GEN-SPEC.md` §5.4):
47
+ that the decision answers your own request (V-4), has not expired (V-3),
48
+ carries a verified user binding when you named a user (V-13), and that
49
+ `disposition` is `allow` before you generate (P-5). A listing in the directory
50
+ proves which registry may issue a code, not that it holds any right over a
51
+ person or a work.
52
+
53
+ Also: `verify_directory`, `Directory.check_signer` / `registry_for` /
54
+ `public_key`, `verify_license` (subject signature plus operator
55
+ countersignature), `verify_signed`, `canonical_json`, `fingerprint`, `issuer_of`.
56
+
57
+ Tests: `pytest packages/verify-py/tests`, and the PRE-GEN Level 1 vectors with
58
+ `python3 spec/conformance/level1/run_conformance.py --adapter "python3 packages/verify-py/tests/conformance_adapter.py"`.
59
+
60
+ Apache-2.0. Part of the PRE-GEN standard,
61
+ [github.com/Pastheroza/PRE-GEN-site](https://github.com/Pastheroza/PRE-GEN-site).
pregen-0.1.0/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # pregen
2
+
3
+ Checks that a PRE-GEN decision or license was really signed by the registry
4
+ that owns its PG code, using the signed registry directory at
5
+ [pregen.org](https://www.pregen.org/registries.json). The PRE-GEN steward key
6
+ is built in. Same API as the npm package `@pregen/verify`.
7
+
8
+ ```python
9
+ import pregen
10
+
11
+ directory = pregen.load_directory(min_sequence=saved_sequence)
12
+ save_sequence(directory.sequence) # refuse older copies next time
13
+
14
+ # decision: the JSON a registry returned from /v1/verify
15
+ # code: the PG code you asked about (the license id, or the subject code)
16
+ if not pregen.verify_decision(decision, code, directory):
17
+ raise RuntimeError("not genuine")
18
+ ```
19
+
20
+ The chain it checks:
21
+
22
+ 1. the directory is signed by the PRE-GEN steward key
23
+ (`pg-ed25519:dcdd244659e6d0e2426f2b504cb11590`) and is not older than one
24
+ you have seen;
25
+ 2. the code's namespace (bare `PG-…` or a four-letter prefix) belongs to one
26
+ listed registry;
27
+ 3. the decision's `operator_key_id` is one of that registry's listed keys, and
28
+ the key its key set serves hashes to that fingerprint;
29
+ 4. the Ed25519 signature over the canonical JSON verifies.
30
+
31
+ What it does **not** check, and you still must (`PRE-GEN-SPEC.md` §5.4):
32
+ that the decision answers your own request (V-4), has not expired (V-3),
33
+ carries a verified user binding when you named a user (V-13), and that
34
+ `disposition` is `allow` before you generate (P-5). A listing in the directory
35
+ proves which registry may issue a code, not that it holds any right over a
36
+ person or a work.
37
+
38
+ Also: `verify_directory`, `Directory.check_signer` / `registry_for` /
39
+ `public_key`, `verify_license` (subject signature plus operator
40
+ countersignature), `verify_signed`, `canonical_json`, `fingerprint`, `issuer_of`.
41
+
42
+ Tests: `pytest packages/verify-py/tests`, and the PRE-GEN Level 1 vectors with
43
+ `python3 spec/conformance/level1/run_conformance.py --adapter "python3 packages/verify-py/tests/conformance_adapter.py"`.
44
+
45
+ Apache-2.0. Part of the PRE-GEN standard,
46
+ [github.com/Pastheroza/PRE-GEN-site](https://github.com/Pastheroza/PRE-GEN-site).
@@ -0,0 +1,248 @@
1
+ """pregen — check PRE-GEN signatures against the signed registry directory
2
+ (PG-CODE.md §9.1, PRE-GEN-SPEC.md §2, V-9 to V-12). The PRE-GEN steward key is
3
+ built in. Same API as the npm package @pregen/verify.
4
+ """
5
+
6
+ import hashlib
7
+ import json
8
+ import re
9
+ import urllib.request
10
+ from copy import deepcopy
11
+ from urllib.parse import urlsplit
12
+
13
+ from cryptography.exceptions import InvalidSignature
14
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
15
+
16
+ __version__ = "0.1.0"
17
+ __all__ = [
18
+ "STEWARD_PUBLIC_KEY_HEX", "DIRECTORY_URL", "PregenError", "Directory", "canonical_json",
19
+ "fingerprint", "verify_bytes", "verify_signed", "verify_license", "issuer_of",
20
+ "verify_directory", "load_directory", "verify_decision",
21
+ ]
22
+
23
+ STEWARD_PUBLIC_KEY_HEX = "5cb949aab04186e3e216ec541b847c912fc3f78138c0ec3cb2560b2dad0d1f1b"
24
+ DIRECTORY_URL = "https://www.pregen.org/registries.json"
25
+ SCHEMA = "pregen.registries.v2"
26
+ _MAX_INT = 2**53 - 1
27
+ _PREFIX = re.compile(r"[ABCDEFGHJKMNPQRSTVWXYZ]{4}")
28
+ _FINGERPRINT = re.compile(r"pg-ed25519:[0-9a-f]{32}")
29
+ _ISSUER_IN_CODE = re.compile(r"^PG-([ABCDEFGHJKMNPQRSTVWXYZ]{4})-")
30
+ _BARE_CODE = re.compile(r"^PG-(?:(?:STD|SUB|PRM|RND)-)?[0-9]")
31
+
32
+
33
+ class PregenError(ValueError):
34
+ """Not something a verifier may accept."""
35
+
36
+
37
+ def canonical_json(value) -> bytes:
38
+ """Canonical JSON (PRE-GEN-SPEC.md §2), UTF-8 encoded."""
39
+ def check(v):
40
+ if v is None or type(v) is bool:
41
+ return
42
+ if type(v) is int:
43
+ if abs(v) > _MAX_INT:
44
+ raise PregenError("signed JSON numbers must be safe integers")
45
+ elif isinstance(v, str):
46
+ try:
47
+ v.encode("utf-8")
48
+ except UnicodeError as e:
49
+ raise PregenError("invalid Unicode in signed JSON") from e
50
+ elif isinstance(v, list):
51
+ for item in v:
52
+ check(item)
53
+ elif isinstance(v, dict):
54
+ for k, item in v.items():
55
+ if not isinstance(k, str):
56
+ raise PregenError("signed JSON keys must be strings")
57
+ check(k)
58
+ check(item)
59
+ else:
60
+ raise PregenError("signed JSON must contain only JSON values and integers")
61
+ check(value)
62
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
63
+ allow_nan=False).encode("utf-8")
64
+
65
+
66
+ def fingerprint(public_key_hex: str) -> str:
67
+ """"pg-ed25519:" + first 32 hex of SHA-256(raw public key) (§2.1)."""
68
+ if not isinstance(public_key_hex, str) or not re.fullmatch(r"[0-9a-fA-F]{64}", public_key_hex):
69
+ raise PregenError("public key must be 32 bytes of hex")
70
+ return "pg-ed25519:" + hashlib.sha256(bytes.fromhex(public_key_hex)).hexdigest()[:32]
71
+
72
+
73
+ def verify_bytes(public_key_hex: str, signature_hex: str, message: bytes) -> bool:
74
+ """Ed25519 over raw bytes. False on any bad signature or key encoding."""
75
+ try:
76
+ Ed25519PublicKey.from_public_bytes(bytes.fromhex(public_key_hex)).verify(
77
+ bytes.fromhex(signature_hex), message)
78
+ return True
79
+ except (InvalidSignature, ValueError, TypeError):
80
+ return False
81
+
82
+
83
+ def verify_signed(obj: dict, public_key_hex: str, signature_field: str, exclude=None) -> bool:
84
+ """Verify obj[signature_field] over the canonical JSON of obj without the excluded fields."""
85
+ if not isinstance(obj, dict):
86
+ return False
87
+ exclude = exclude or [signature_field]
88
+ body = {k: v for k, v in obj.items() if k not in exclude}
89
+ return verify_bytes(public_key_hex, str(obj.get(signature_field, "")), canonical_json(body))
90
+
91
+
92
+ def verify_license(body: dict, license_id: str, subject_public_key_hex: str, subject_signature_hex: str,
93
+ operator_public_key_hex: str, operator_signature_hex: str) -> dict:
94
+ """A license (§1.2): subject signature over the body; operator countersignature over
95
+ canonical body || subject signature (64 raw bytes) || license id (ASCII)."""
96
+ body_bytes = canonical_json(body)
97
+ subject_valid = verify_bytes(subject_public_key_hex, subject_signature_hex, body_bytes)
98
+ try:
99
+ message = body_bytes + bytes.fromhex(subject_signature_hex) + str(license_id).encode("utf-8")
100
+ operator_valid = len(bytes.fromhex(subject_signature_hex)) == 64 and verify_bytes(
101
+ operator_public_key_hex, operator_signature_hex, message)
102
+ except (ValueError, TypeError):
103
+ operator_valid = False
104
+ return {"subject_valid": subject_valid, "operator_valid": operator_valid}
105
+
106
+
107
+ def issuer_of(code: str) -> str:
108
+ """The namespace of a PG code: its four-letter prefix, or "" for the bare namespace."""
109
+ if not isinstance(code, str):
110
+ raise PregenError("PG code must be a string")
111
+ c = code.strip().upper()
112
+ m = _ISSUER_IN_CODE.match(c)
113
+ if m:
114
+ return m.group(1)
115
+ if not _BARE_CODE.match(c):
116
+ raise PregenError("unrecognized PG namespace")
117
+ return ""
118
+
119
+
120
+ def _https_url(value, field):
121
+ try:
122
+ url = urlsplit(value)
123
+ url.port # rejects invalid ports
124
+ except (ValueError, TypeError, AttributeError) as e:
125
+ raise PregenError(f"registry {field} must be a URL") from e
126
+ if url.scheme != "https" or not url.hostname or url.username or url.password or url.query or url.fragment:
127
+ raise PregenError(f"registry {field} must use HTTPS without credentials, query or fragment")
128
+
129
+
130
+ def _check_invariants(d):
131
+ if not isinstance(d, dict):
132
+ raise PregenError("directory must be an object")
133
+ if d.get("schema") != SCHEMA:
134
+ raise PregenError(f"schema must be {SCHEMA}")
135
+ seq = d.get("sequence")
136
+ if type(seq) is not int or not 1 <= seq <= _MAX_INT:
137
+ raise PregenError("sequence must be a positive integer")
138
+ if not _FINGERPRINT.fullmatch(str(d.get("steward_key_id", ""))):
139
+ raise PregenError("steward_key_id must be a pg-ed25519 fingerprint")
140
+ regs = d.get("registries")
141
+ if not isinstance(regs, list) or not regs:
142
+ raise PregenError("registries must be a non-empty list")
143
+ seen = set()
144
+ for r in regs:
145
+ if not isinstance(r, dict):
146
+ raise PregenError("registry entry must be an object")
147
+ if not isinstance(r.get("name"), str) or not r["name"].strip():
148
+ raise PregenError("registry name must be nonempty")
149
+ _https_url(r.get("api"), "api")
150
+ _https_url(r.get("keys"), "keys")
151
+ prefix = r.get("prefix")
152
+ if prefix != "" and not (isinstance(prefix, str) and _PREFIX.fullmatch(prefix)):
153
+ raise PregenError(f"bad prefix {prefix!r}")
154
+ if prefix in seen:
155
+ raise PregenError("the bare namespace is listed twice" if prefix == "" else f"prefix {prefix} is listed twice")
156
+ seen.add(prefix)
157
+ fps = r.get("key_fingerprints")
158
+ if not isinstance(fps, list) or not fps or not all(_FINGERPRINT.fullmatch(str(f)) for f in fps):
159
+ raise PregenError(f"registry {r.get('name')!r}: key_fingerprints must list pg-ed25519 fingerprints")
160
+ if "" not in seen:
161
+ raise PregenError("no registry holds the bare namespace")
162
+
163
+
164
+ def _get_json(url: str):
165
+ # urllib follows redirects; a registry key set or directory has no reason to redirect.
166
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
167
+ def redirect_request(self, *args, **kwargs):
168
+ raise PregenError(f"refusing redirect from {url}")
169
+ opener = urllib.request.build_opener(_NoRedirect)
170
+ with opener.open(urllib.request.Request(url, headers={"Accept": "application/json"}), timeout=10) as res:
171
+ return json.loads(res.read().decode("utf-8"))
172
+
173
+
174
+ class Directory:
175
+ """A directory accepted under V-12. Get one from verify_directory() or load_directory()."""
176
+
177
+ def __init__(self, directory: dict, _token=None):
178
+ if _token is not _TOKEN:
179
+ raise PregenError("use verify_directory() or load_directory()")
180
+ self._d = deepcopy(directory)
181
+
182
+ @property
183
+ def sequence(self) -> int:
184
+ """Store it and pass it back as min_sequence, so an older directory is refused."""
185
+ return self._d["sequence"]
186
+
187
+ @property
188
+ def registries(self) -> list:
189
+ return deepcopy(self._d["registries"])
190
+
191
+ def registry_for(self, code: str):
192
+ """The registry that owns a code's namespace (resolve codes only there, V-11), or None."""
193
+ try:
194
+ issuer = issuer_of(code)
195
+ except PregenError:
196
+ return None
197
+ r = next((x for x in self._d["registries"] if x["prefix"] == issuer), None)
198
+ return deepcopy(r) if r else None
199
+
200
+ def check_signer(self, code: str, signer_key_id: str) -> str:
201
+ """V-10: "valid", "unknown_issuer" or "issuer_mismatch"."""
202
+ r = self.registry_for(code)
203
+ if r is None:
204
+ return "unknown_issuer"
205
+ return "valid" if signer_key_id in r["key_fingerprints"] else "issuer_mismatch"
206
+
207
+ def public_key(self, code: str, key_id: str, get_json=_get_json) -> str:
208
+ """The owner's public key for key_id, from its key set, checked against the listed fingerprint."""
209
+ verdict = self.check_signer(code, key_id)
210
+ if verdict != "valid":
211
+ raise PregenError(f"{key_id} may not sign {code}: {verdict}")
212
+ keys = get_json(self.registry_for(code)["keys"]).get("keys") or []
213
+ entry = next((k for k in keys if isinstance(k, dict) and k.get("key_id") == key_id), None)
214
+ if entry is None or fingerprint(entry.get("public_key_hex")) != key_id:
215
+ raise PregenError(f"no key {key_id} in the key set")
216
+ return entry["public_key_hex"]
217
+
218
+
219
+ _TOKEN = object()
220
+
221
+
222
+ def verify_directory(directory: dict, steward_public_key_hex: str = STEWARD_PUBLIC_KEY_HEX,
223
+ min_sequence: int = 0) -> Directory:
224
+ """V-12: accept the directory only with the pinned steward's signature, its
225
+ invariants, and a sequence no lower than one already seen."""
226
+ if type(min_sequence) is not int or not 0 <= min_sequence <= _MAX_INT:
227
+ raise PregenError("min_sequence must be a nonnegative integer")
228
+ _check_invariants(directory)
229
+ if directory["steward_key_id"] != fingerprint(steward_public_key_hex):
230
+ raise PregenError("signed by a different steward key")
231
+ if not verify_signed(directory, steward_public_key_hex, "signature"):
232
+ raise PregenError("bad steward signature")
233
+ if directory["sequence"] < min_sequence:
234
+ raise PregenError(f"sequence {directory['sequence']} is older than {min_sequence} already seen")
235
+ return Directory(directory, _TOKEN)
236
+
237
+
238
+ def load_directory(url: str = DIRECTORY_URL, min_sequence: int = 0, get_json=_get_json) -> Directory:
239
+ """Download and verify the directory from pregen.org."""
240
+ return verify_directory(get_json(url), min_sequence=min_sequence)
241
+
242
+
243
+ def verify_decision(decision: dict, code: str, directory: Directory = None, get_json=_get_json) -> bool:
244
+ """Step 4 in one call: is this registry decision genuine, and signed by a key of the
245
+ registry that owns `code`? Request matching and expiry (V-3, V-4, V-13) stay with the caller."""
246
+ directory = directory or load_directory(get_json=get_json)
247
+ key = directory.public_key(code, (decision or {}).get("operator_key_id"), get_json=get_json)
248
+ return verify_signed(decision, key, "operator_signature")
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: pregen
3
+ Version: 0.1.0
4
+ Summary: Verify PRE-GEN signatures against the signed registry directory, with the PRE-GEN steward key built in
5
+ Author: Valerii Egorov (Pastheroza)
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://www.pregen.org
8
+ Project-URL: Source, https://github.com/Pastheroza/PRE-GEN-site/tree/main/packages/verify-py
9
+ Keywords: pre-gen,pregen,pre-generation authorization,ed25519,verification
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: cryptography>=42
14
+ Dynamic: license-file
15
+
16
+ # pregen
17
+
18
+ Checks that a PRE-GEN decision or license was really signed by the registry
19
+ that owns its PG code, using the signed registry directory at
20
+ [pregen.org](https://www.pregen.org/registries.json). The PRE-GEN steward key
21
+ is built in. Same API as the npm package `@pregen/verify`.
22
+
23
+ ```python
24
+ import pregen
25
+
26
+ directory = pregen.load_directory(min_sequence=saved_sequence)
27
+ save_sequence(directory.sequence) # refuse older copies next time
28
+
29
+ # decision: the JSON a registry returned from /v1/verify
30
+ # code: the PG code you asked about (the license id, or the subject code)
31
+ if not pregen.verify_decision(decision, code, directory):
32
+ raise RuntimeError("not genuine")
33
+ ```
34
+
35
+ The chain it checks:
36
+
37
+ 1. the directory is signed by the PRE-GEN steward key
38
+ (`pg-ed25519:dcdd244659e6d0e2426f2b504cb11590`) and is not older than one
39
+ you have seen;
40
+ 2. the code's namespace (bare `PG-…` or a four-letter prefix) belongs to one
41
+ listed registry;
42
+ 3. the decision's `operator_key_id` is one of that registry's listed keys, and
43
+ the key its key set serves hashes to that fingerprint;
44
+ 4. the Ed25519 signature over the canonical JSON verifies.
45
+
46
+ What it does **not** check, and you still must (`PRE-GEN-SPEC.md` §5.4):
47
+ that the decision answers your own request (V-4), has not expired (V-3),
48
+ carries a verified user binding when you named a user (V-13), and that
49
+ `disposition` is `allow` before you generate (P-5). A listing in the directory
50
+ proves which registry may issue a code, not that it holds any right over a
51
+ person or a work.
52
+
53
+ Also: `verify_directory`, `Directory.check_signer` / `registry_for` /
54
+ `public_key`, `verify_license` (subject signature plus operator
55
+ countersignature), `verify_signed`, `canonical_json`, `fingerprint`, `issuer_of`.
56
+
57
+ Tests: `pytest packages/verify-py/tests`, and the PRE-GEN Level 1 vectors with
58
+ `python3 spec/conformance/level1/run_conformance.py --adapter "python3 packages/verify-py/tests/conformance_adapter.py"`.
59
+
60
+ Apache-2.0. Part of the PRE-GEN standard,
61
+ [github.com/Pastheroza/PRE-GEN-site](https://github.com/Pastheroza/PRE-GEN-site).
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ pregen/__init__.py
5
+ pregen.egg-info/PKG-INFO
6
+ pregen.egg-info/SOURCES.txt
7
+ pregen.egg-info/dependency_links.txt
8
+ pregen.egg-info/requires.txt
9
+ pregen.egg-info/top_level.txt
10
+ tests/test_verify.py
@@ -0,0 +1 @@
1
+ cryptography>=42
@@ -0,0 +1 @@
1
+ pregen
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pregen"
7
+ version = "0.1.0"
8
+ description = "Verify PRE-GEN signatures against the signed registry directory, with the PRE-GEN steward key built in"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = ["cryptography>=42"]
14
+ authors = [{ name = "Valerii Egorov (Pastheroza)" }]
15
+ keywords = ["pre-gen", "pregen", "pre-generation authorization", "ed25519", "verification"]
16
+
17
+ [project.urls]
18
+ Homepage = "https://www.pregen.org"
19
+ Source = "https://github.com/Pastheroza/PRE-GEN-site/tree/main/packages/verify-py"
20
+
21
+ [tool.setuptools]
22
+ packages = ["pregen"]
pregen-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,86 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
6
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
9
+ from pregen import PregenError, canonical_json, fingerprint, verify_decision, verify_directory # noqa: E402
10
+
11
+
12
+ class Key:
13
+ def __init__(self):
14
+ self.k = Ed25519PrivateKey.generate()
15
+ self.pub = self.k.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw).hex()
16
+ self.id = fingerprint(self.pub)
17
+
18
+ def sign(self, obj, field):
19
+ body = {k: v for k, v in obj.items() if k != field}
20
+ return {**obj, field: self.k.sign(canonical_json(body)).hex()}
21
+
22
+
23
+ steward, origin, other = Key(), Key(), Key()
24
+ KEY_SETS = {"https://origin.test/keys": {"keys": [{"key_id": origin.id, "public_key_hex": origin.pub}]},
25
+ "https://other.test/keys": {"keys": [{"key_id": other.id, "public_key_hex": other.pub}]}}
26
+
27
+
28
+ def directory(sequence=2, registries=None):
29
+ return steward.sign({"schema": "pregen.registries.v2", "sequence": sequence, "steward_key_id": steward.id,
30
+ "registries": registries or [
31
+ {"name": "Origin", "prefix": "", "api": "https://origin.test",
32
+ "keys": "https://origin.test/keys", "key_fingerprints": [origin.id]},
33
+ {"name": "Other", "prefix": "NWRD", "api": "https://other.test",
34
+ "keys": "https://other.test/keys", "key_fingerprints": [other.id]}]}, "signature")
35
+
36
+
37
+ def load(d, min_sequence=0):
38
+ return verify_directory(d, steward.pub, min_sequence)
39
+
40
+
41
+ def test_directory_signed_by_pinned_steward_is_accepted():
42
+ assert load(directory()).sequence == 2
43
+
44
+
45
+ def test_tampered_foreign_older_or_malformed_directory_is_refused():
46
+ d = directory()
47
+ with pytest.raises(PregenError):
48
+ load({**d, "registries": d["registries"][:1]})
49
+ with pytest.raises(PregenError, match="different steward"):
50
+ verify_directory(d) # the default pin is the real steward key
51
+ with pytest.raises(PregenError, match="older"):
52
+ load(d, 3)
53
+ with pytest.raises(PregenError, match="HTTPS"):
54
+ load(directory(registries=[{"name": "X", "prefix": "", "api": "http://x.test", "keys": "https://x.test/k",
55
+ "key_fingerprints": [origin.id]}]))
56
+
57
+
58
+ def test_namespaces_are_symmetric():
59
+ dir_ = load(directory())
60
+ assert dir_.check_signer("PG-000042*", origin.id) == "valid"
61
+ assert dir_.check_signer("PG-000042*", other.id) == "issuer_mismatch"
62
+ assert dir_.check_signer("PG-NWRD-000042-K", other.id) == "valid"
63
+ assert dir_.check_signer("PG-NWRD-000042-K", origin.id) == "issuer_mismatch"
64
+ assert dir_.check_signer("PG-ABCD-000042-K", origin.id) == "unknown_issuer"
65
+
66
+
67
+ def test_decision_is_genuine_only_from_the_namespace_owner():
68
+ dir_ = load(directory())
69
+ get = KEY_SETS.__getitem__
70
+ decision = origin.sign({"decision_id": "d1", "allowed": True, "license_id": "PG-RND-000042-ZZZZZZ1",
71
+ "operator_key_id": origin.id}, "operator_signature")
72
+ assert verify_decision(decision, decision["license_id"], dir_, get) is True
73
+ assert verify_decision({**decision, "allowed": False}, decision["license_id"], dir_, get) is False
74
+ forged = other.sign({"decision_id": "d2", "allowed": True, "operator_key_id": other.id}, "operator_signature")
75
+ with pytest.raises(PregenError, match="issuer_mismatch"):
76
+ verify_decision(forged, "PG-000042*", dir_, get)
77
+ swapped = {"https://origin.test/keys": {"keys": [{"key_id": origin.id, "public_key_hex": other.pub}]}}
78
+ with pytest.raises(PregenError, match="no key"):
79
+ verify_decision(decision, decision["license_id"], dir_, swapped.__getitem__)
80
+
81
+
82
+ def test_canonical_json_refuses_unportable_values():
83
+ for bad in ({"x": 1.5}, {"x": 2**53}, {"x": "\ud800"}, {"x": object()}):
84
+ with pytest.raises(PregenError):
85
+ canonical_json(bad)
86
+